@detiq/crawler 1.1.14 → 1.1.15

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 (109) hide show
  1. package/Dockerfile +1 -1
  2. package/dist/accessibility-tree-crawler.js +156 -0
  3. package/dist/accessibility-tree-crawler.js.map +7 -0
  4. package/dist/advanced-ui-probes.js +310 -0
  5. package/dist/advanced-ui-probes.js.map +7 -0
  6. package/dist/content-chunker.js +2 -2
  7. package/dist/content-chunker.js.map +2 -2
  8. package/dist/crawl-session-manager.js +145 -0
  9. package/dist/crawl-session-manager.js.map +7 -0
  10. package/dist/crawler.js +1142 -263
  11. package/dist/crawler.js.map +2 -2
  12. package/dist/crud-interaction.js +264 -0
  13. package/dist/crud-interaction.js.map +7 -0
  14. package/dist/dropdown-enumerator.js +230 -0
  15. package/dist/dropdown-enumerator.js.map +7 -0
  16. package/dist/filter-pagination-crawler.js +299 -0
  17. package/dist/filter-pagination-crawler.js.map +7 -0
  18. package/dist/frontier.js +5 -3
  19. package/dist/frontier.js.map +2 -2
  20. package/dist/gap-pass.js +47 -14
  21. package/dist/gap-pass.js.map +2 -2
  22. package/dist/http-engine.js +28 -15
  23. package/dist/http-engine.js.map +2 -2
  24. package/dist/index.js +15 -1
  25. package/dist/index.js.map +2 -2
  26. package/dist/job-queue.js +12 -5
  27. package/dist/job-queue.js.map +2 -2
  28. package/dist/locator-extractor.js +23 -0
  29. package/dist/locator-extractor.js.map +2 -2
  30. package/dist/multi-context-handler.js +182 -0
  31. package/dist/multi-context-handler.js.map +7 -0
  32. package/dist/nested-window-crawler.js +172 -0
  33. package/dist/nested-window-crawler.js.map +7 -0
  34. package/dist/network-action-correlator.js +209 -0
  35. package/dist/network-action-correlator.js.map +7 -0
  36. package/dist/performance-metrics-collector.js +155 -0
  37. package/dist/performance-metrics-collector.js.map +7 -0
  38. package/dist/performance-metrics.js.map +2 -2
  39. package/dist/policies/crawl-safety.js +5 -1
  40. package/dist/policies/crawl-safety.js.map +2 -2
  41. package/dist/profiles/domain-profile.js +21 -1
  42. package/dist/profiles/domain-profile.js.map +2 -2
  43. package/dist/rate-limiter.js +2 -2
  44. package/dist/rate-limiter.js.map +2 -2
  45. package/dist/screen-reader.js +1 -0
  46. package/dist/screen-reader.js.map +2 -2
  47. package/dist/service-worker-interceptor.js +136 -0
  48. package/dist/service-worker-interceptor.js.map +7 -0
  49. package/dist/session-capture.js +4 -2
  50. package/dist/session-capture.js.map +2 -2
  51. package/dist/shadow-dom-crawler.js +132 -0
  52. package/dist/shadow-dom-crawler.js.map +7 -0
  53. package/dist/sitemap.js +16 -10
  54. package/dist/sitemap.js.map +2 -2
  55. package/dist/state-graph.js +193 -0
  56. package/dist/state-graph.js.map +7 -0
  57. package/dist/stealth/human-behavior.js +36 -3
  58. package/dist/stealth/human-behavior.js.map +2 -2
  59. package/dist/url-pattern-completer.js +48 -14
  60. package/dist/url-pattern-completer.js.map +2 -2
  61. package/dist/visual-diff-verdict.js +3 -1
  62. package/dist/visual-diff-verdict.js.map +2 -2
  63. package/package.json +2 -1
  64. package/src/accessibility-tree-crawler.ts +246 -0
  65. package/src/advanced-ui-probes.ts +470 -0
  66. package/src/crawl-session-manager.ts +231 -0
  67. package/src/crawler.ts +1050 -134
  68. package/src/crud-interaction.ts +386 -0
  69. package/src/dropdown-enumerator.ts +312 -0
  70. package/src/filter-pagination-crawler.ts +500 -0
  71. package/src/gap-pass.ts +58 -16
  72. package/src/index.ts +14 -1
  73. package/src/locator-extractor.ts +45 -0
  74. package/src/multi-context-handler.ts +296 -0
  75. package/src/nested-window-crawler.ts +310 -0
  76. package/src/network-action-correlator.ts +320 -0
  77. package/src/performance-metrics-collector.ts +243 -0
  78. package/src/performance-metrics.ts +1 -1
  79. package/src/screen-reader.ts +4 -1
  80. package/src/service-worker-interceptor.ts +185 -0
  81. package/src/session-capture.ts +3 -0
  82. package/src/shadow-dom-crawler.ts +198 -0
  83. package/src/state-graph.ts +280 -0
  84. package/src/stealth/human-behavior.ts +38 -4
  85. package/src/url-pattern-completer.ts +61 -15
  86. package/tsconfig.json +1 -1
  87. package/types/accessibility-tree-crawler.d.ts +44 -0
  88. package/types/advanced-ui-probes.d.ts +47 -0
  89. package/types/crawl-session-manager.d.ts +44 -0
  90. package/types/crawler.d.ts +3 -1
  91. package/types/crud-interaction.d.ts +31 -0
  92. package/types/dropdown-enumerator.d.ts +20 -0
  93. package/types/filter-pagination-crawler.d.ts +52 -0
  94. package/types/gap-pass.d.ts +1 -0
  95. package/types/index.d.ts +14 -1
  96. package/types/job-queue.d.ts +18 -9
  97. package/types/locator-extractor.d.ts +7 -0
  98. package/types/multi-context-handler.d.ts +55 -0
  99. package/types/nested-window-crawler.d.ts +41 -0
  100. package/types/network-action-correlator.d.ts +47 -0
  101. package/types/performance-metrics-collector.d.ts +50 -0
  102. package/types/performance-metrics.d.ts +1 -2
  103. package/types/screen-reader.d.ts +1 -2
  104. package/types/service-worker-interceptor.d.ts +36 -0
  105. package/types/session-capture.d.ts +1 -1
  106. package/types/shadow-dom-crawler.d.ts +35 -0
  107. package/types/sitemap.d.ts +2 -2
  108. package/types/state-graph.d.ts +59 -0
  109. package/types/stealth/human-behavior.d.ts +1 -1
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Service Worker detection — inspects SW registrations, cache storage, background
3
+ * sync queues, and PWA installability for a crawled page.
4
+ * Surfaces offline-first contracts and push-capable surfaces that HTTP-only
5
+ * crawlers cannot observe.
6
+ */
7
+
8
+ import type { Page } from 'playwright';
9
+
10
+ export interface SwRegistration {
11
+ scope: string;
12
+ scriptURL: string | null;
13
+ state: 'active' | 'installing' | 'waiting' | 'none';
14
+ updateViaCache: string;
15
+ }
16
+
17
+ export interface SwCacheEntry {
18
+ cacheName: string;
19
+ entryCount: number;
20
+ sampleUrls: string[];
21
+ }
22
+
23
+ export interface BackgroundSyncInfo {
24
+ scope: string;
25
+ pendingTags: string[];
26
+ }
27
+
28
+ export interface PwaInfo {
29
+ isInstallable: boolean;
30
+ manifestUrl: string | null;
31
+ hasPushPermission: boolean;
32
+ }
33
+
34
+ export interface ServiceWorkerResult {
35
+ supported: boolean;
36
+ active: boolean;
37
+ registrations: SwRegistration[];
38
+ cacheStorages: SwCacheEntry[];
39
+ backgroundSync: BackgroundSyncInfo[];
40
+ pwa: PwaInfo;
41
+ totalCachedEntries: number;
42
+ }
43
+
44
+ const EMPTY_RESULT: ServiceWorkerResult = {
45
+ supported: false,
46
+ active: false,
47
+ registrations: [],
48
+ cacheStorages: [],
49
+ backgroundSync: [],
50
+ pwa: { isInstallable: false, manifestUrl: null, hasPushPermission: false },
51
+ totalCachedEntries: 0,
52
+ };
53
+
54
+ async function detectServiceWorkers(
55
+ page: any,
56
+ ): Promise<{ supported: boolean; active: boolean; registrations: SwRegistration[] }> {
57
+ const result = await page.evaluate(async () => {
58
+ if (!('serviceWorker' in navigator)) return { supported: false, active: false, registrations: [] };
59
+ try {
60
+ const controller = navigator.serviceWorker.controller;
61
+ const regs = await navigator.serviceWorker.getRegistrations();
62
+ return {
63
+ supported: true,
64
+ active: !!controller,
65
+ registrations: regs.map(r => ({
66
+ scope: r.scope,
67
+ scriptURL: r.active?.scriptURL || r.installing?.scriptURL || r.waiting?.scriptURL || null,
68
+ state: r.active ? 'active' : r.installing ? 'installing' : r.waiting ? 'waiting' : 'none',
69
+ updateViaCache: r.updateViaCache,
70
+ })),
71
+ };
72
+ } catch {
73
+ return { supported: true, active: false, registrations: [] };
74
+ }
75
+ });
76
+ return result as { supported: boolean; active: boolean; registrations: SwRegistration[] };
77
+ }
78
+
79
+ async function enumerateCacheStorage(page: any): Promise<SwCacheEntry[]> {
80
+ const caches = await page.evaluate(async () => {
81
+ if (!('caches' in window)) return [];
82
+ try {
83
+ const names = await window.caches.keys();
84
+ const result = [];
85
+ for (const name of names) {
86
+ try {
87
+ const cache = await window.caches.open(name);
88
+ const keys = await cache.keys();
89
+ result.push({
90
+ cacheName: name,
91
+ entryCount: keys.length,
92
+ sampleUrls: keys.slice(0, 15).map(k => {
93
+ try { return new URL(k.url).pathname; } catch { return k.url.slice(0, 80); }
94
+ }),
95
+ });
96
+ } catch { /* skip inaccessible cache */ }
97
+ }
98
+ return result;
99
+ } catch {
100
+ return [];
101
+ }
102
+ });
103
+ return caches as SwCacheEntry[];
104
+ }
105
+
106
+ async function detectBackgroundSync(page: any): Promise<BackgroundSyncInfo[]> {
107
+ const syncInfo = await page.evaluate(async () => {
108
+ if (!('serviceWorker' in navigator)) return [];
109
+ try {
110
+ const regs = await navigator.serviceWorker.getRegistrations();
111
+ const result = [];
112
+ for (const reg of regs) {
113
+ if ('sync' in reg) {
114
+ try {
115
+ const tags = await (reg as any).sync.getTags();
116
+ result.push({ scope: reg.scope, pendingTags: tags || [] });
117
+ } catch {
118
+ result.push({ scope: reg.scope, pendingTags: [] });
119
+ }
120
+ }
121
+ }
122
+ return result;
123
+ } catch {
124
+ return [];
125
+ }
126
+ });
127
+ return syncInfo as BackgroundSyncInfo[];
128
+ }
129
+
130
+ async function detectPwa(page: any): Promise<PwaInfo> {
131
+ const pwa = await page.evaluate(() => {
132
+ const manifestEl = document.querySelector('link[rel="manifest"]');
133
+ const manifestUrl = manifestEl?.getAttribute('href') || null;
134
+ const hasSW = 'serviceWorker' in navigator && !!navigator.serviceWorker.controller;
135
+ let hasPushPermission = false;
136
+ try { hasPushPermission = Notification.permission === 'granted'; } catch { /* ignore */ }
137
+ return {
138
+ isInstallable: !!(manifestUrl && hasSW),
139
+ manifestUrl,
140
+ hasPushPermission,
141
+ };
142
+ });
143
+ return pwa as PwaInfo;
144
+ }
145
+
146
+ export async function inspectServiceWorker(page: any): Promise<ServiceWorkerResult> {
147
+ try {
148
+ // Allow SW on HTTPS or localhost (http://localhost and http://127.0.0.1 support SW)
149
+ const url = page.url();
150
+ const isSecureContext = url.startsWith('https://') ||
151
+ /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?/.test(url);
152
+ if (!isSecureContext) return { ...EMPTY_RESULT };
153
+
154
+ const [swResult, cacheResult, syncResult, pwaResult] = await Promise.allSettled([
155
+ detectServiceWorkers(page),
156
+ enumerateCacheStorage(page),
157
+ detectBackgroundSync(page),
158
+ detectPwa(page),
159
+ ]);
160
+
161
+ const sw = swResult.status === 'fulfilled'
162
+ ? swResult.value
163
+ : { supported: false, active: false, registrations: [] };
164
+
165
+ const cacheStorages = cacheResult.status === 'fulfilled' ? cacheResult.value : [];
166
+ const backgroundSync = syncResult.status === 'fulfilled' ? syncResult.value : [];
167
+ const pwa = pwaResult.status === 'fulfilled'
168
+ ? pwaResult.value
169
+ : EMPTY_RESULT.pwa;
170
+
171
+ const totalCachedEntries = cacheStorages.reduce((sum, c) => sum + c.entryCount, 0);
172
+
173
+ return {
174
+ supported: sw.supported,
175
+ active: sw.active,
176
+ registrations: sw.registrations,
177
+ cacheStorages,
178
+ backgroundSync,
179
+ pwa,
180
+ totalCachedEntries,
181
+ };
182
+ } catch {
183
+ return { ...EMPTY_RESULT };
184
+ }
185
+ }
@@ -207,6 +207,7 @@ export async function validateAndCaptureSession(
207
207
  },
208
208
  llmConfig?: { modelName: string; apiKey: string },
209
209
  captchaOpts?: { apiKey?: string; provider?: '2captcha' | 'capsolver' },
210
+ loginInstructions?: string,
210
211
  ): Promise<{ storageState: string; cookies: number; localStorage: number; finalUrl?: string }> {
211
212
  const browser = await chromium.launch({ headless: true });
212
213
  try {
@@ -257,6 +258,8 @@ export async function validateAndCaptureSession(
257
258
  { username: creds.username, password: creds.password, getOneTimeCode },
258
259
  appUrl,
259
260
  captchaOpts,
261
+ undefined,
262
+ loginInstructions,
260
263
  );
261
264
  if (shLoggedIn) {
262
265
  const shCtx = (sh as any).context ?? (sh as any).browserContext;
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Shadow DOM crawler — enumerate shadow hosts and detect web component libraries.
3
+ *
4
+ * Walks the live DOM recursively (up to depth 8) to find all open shadow roots
5
+ * and custom elements with closed shadow roots, then classifies the component
6
+ * framework in use. Results feed ZeTa's test generator so it can account for
7
+ * elements that are invisible to standard Playwright locators.
8
+ */
9
+
10
+ import type { Page } from 'playwright';
11
+
12
+ export interface ShadowInteractiveEl {
13
+ role: string;
14
+ label: string;
15
+ type: string;
16
+ tagName: string;
17
+ }
18
+
19
+ export interface ShadowHostInfo {
20
+ tagName: string;
21
+ hostId: string;
22
+ shadowMode: 'open' | 'closed';
23
+ depth: number;
24
+ interactiveCount: number;
25
+ interactiveElements: ShadowInteractiveEl[];
26
+ slotNames: string[];
27
+ childShadowHosts: number;
28
+ }
29
+
30
+ export interface ShadowDomCrawlResult {
31
+ shadowHostCount: number;
32
+ openShadowCount: number;
33
+ closedShadowCount: number;
34
+ maxNestingDepth: number;
35
+ hosts: ShadowHostInfo[];
36
+ totalInteractiveInShadow: number;
37
+ detectedLibraries: string[];
38
+ blindSpots: string[];
39
+ }
40
+
41
+ interface RawShadowHost {
42
+ tagName: string;
43
+ hostId: string;
44
+ shadowMode: 'open' | 'closed';
45
+ depth: number;
46
+ interactiveCount: number;
47
+ interactiveDetails: Array<{ role: string; label: string; type: string; tagName: string }>;
48
+ slotNames: string[];
49
+ childShadowHosts: number;
50
+ }
51
+
52
+ async function enumerateShadowHosts(page: any): Promise<ShadowHostInfo[]> {
53
+ const raw: RawShadowHost[] = await page.evaluate(() => {
54
+ // esbuild injects __name() for named function declarations; polyfill prevents ReferenceError in browser.
55
+ if (typeof (globalThis as any).__name === 'undefined') (globalThis as any).__name = (fn: any) => fn;
56
+ function collectHosts(root: Document | ShadowRoot, depth: number): RawShadowHost[] {
57
+ if (depth > 8) return [];
58
+ const hosts: RawShadowHost[] = [];
59
+ const els = root.querySelectorAll('*');
60
+ for (const el of Array.from(els)) {
61
+ const htmlEl = el as HTMLElement & { shadowRoot: ShadowRoot | null };
62
+ if (htmlEl.shadowRoot) {
63
+ const interactive = htmlEl.shadowRoot.querySelectorAll(
64
+ 'button,input,select,textarea,a[href],[role="button"],[role="link"],[role="checkbox"],[role="menuitem"],[role="tab"],[role="switch"]'
65
+ );
66
+ const slots = Array.from(htmlEl.shadowRoot.querySelectorAll('slot')).map(
67
+ (s) => (s as HTMLSlotElement).name || 'default'
68
+ );
69
+ const nestedHosts = Array.from(htmlEl.shadowRoot.querySelectorAll('*')).filter(
70
+ (c) => (c as HTMLElement & { shadowRoot: ShadowRoot | null }).shadowRoot
71
+ ).length;
72
+ hosts.push({
73
+ tagName: htmlEl.tagName.toLowerCase(),
74
+ hostId:
75
+ htmlEl.id ||
76
+ (htmlEl.className?.toString()?.split(' ')[0]) ||
77
+ '',
78
+ shadowMode: 'open',
79
+ depth,
80
+ interactiveCount: interactive.length,
81
+ interactiveDetails: Array.from(interactive)
82
+ .slice(0, 8)
83
+ .map((i) => {
84
+ const iEl = i as HTMLElement;
85
+ return {
86
+ role: iEl.getAttribute('role') || iEl.tagName.toLowerCase(),
87
+ label: (
88
+ iEl.getAttribute('aria-label') ||
89
+ iEl.getAttribute('placeholder') ||
90
+ iEl.textContent?.trim() ||
91
+ ''
92
+ ).slice(0, 40),
93
+ type: iEl.getAttribute('type') || '',
94
+ tagName: iEl.tagName.toLowerCase(),
95
+ };
96
+ }),
97
+ slotNames: slots,
98
+ childShadowHosts: nestedHosts,
99
+ });
100
+ const nested = collectHosts(htmlEl.shadowRoot, depth + 1);
101
+ hosts.push(...nested);
102
+ } else if (el.tagName.includes('-') && !(el as HTMLElement & { shadowRoot: ShadowRoot | null }).shadowRoot) {
103
+ hosts.push({
104
+ tagName: el.tagName.toLowerCase(),
105
+ hostId: (el as HTMLElement).id || '',
106
+ shadowMode: 'closed',
107
+ depth,
108
+ interactiveCount: 0,
109
+ interactiveDetails: [],
110
+ slotNames: [],
111
+ childShadowHosts: 0,
112
+ });
113
+ }
114
+ }
115
+ return hosts;
116
+ }
117
+ return collectHosts(document, 0);
118
+ });
119
+
120
+ return raw.slice(0, 100).map((h) => ({
121
+ tagName: h.tagName,
122
+ hostId: h.hostId,
123
+ shadowMode: h.shadowMode,
124
+ depth: h.depth,
125
+ interactiveCount: h.interactiveCount,
126
+ interactiveElements: h.interactiveDetails,
127
+ slotNames: h.slotNames,
128
+ childShadowHosts: h.childShadowHosts,
129
+ }));
130
+ }
131
+
132
+ async function detectWebComponentLibrary(page: any): Promise<string[]> {
133
+ return page.evaluate(() => {
134
+ const checks: [string, string][] = [
135
+ ['sl-button', 'Shoelace'],
136
+ ['fast-button', 'Microsoft FAST'],
137
+ ['mwc-button', 'Material Web Components'],
138
+ ['ion-button', 'Ionic'],
139
+ ['vaadin-button', 'Vaadin'],
140
+ ['fluent-button', 'Fluent UI Web Components'],
141
+ ['hy-icon', 'Hydra'],
142
+ ];
143
+ const detected: string[] = [];
144
+ for (const [tag, name] of checks) {
145
+ if (customElements.get(tag)) detected.push(name);
146
+ }
147
+ const allTags = Array.from(document.querySelectorAll('*'))
148
+ .map((e) => e.tagName.toLowerCase())
149
+ .filter((t) => t.includes('-'));
150
+ const uniqueTags = Array.from(new Set(allTags));
151
+ if (uniqueTags.some((t) => t.startsWith('sl-')) && !detected.includes('Shoelace'))
152
+ detected.push('Shoelace');
153
+ if (uniqueTags.some((t) => t.startsWith('fast-')) && !detected.includes('Microsoft FAST'))
154
+ detected.push('Microsoft FAST');
155
+ if (uniqueTags.some((t) => t.startsWith('ion-')) && !detected.includes('Ionic'))
156
+ detected.push('Ionic');
157
+ return detected;
158
+ });
159
+ }
160
+
161
+ export async function crawlShadowDom(page: any): Promise<ShadowDomCrawlResult> {
162
+ const empty: ShadowDomCrawlResult = {
163
+ shadowHostCount: 0,
164
+ openShadowCount: 0,
165
+ closedShadowCount: 0,
166
+ maxNestingDepth: 0,
167
+ hosts: [],
168
+ totalInteractiveInShadow: 0,
169
+ detectedLibraries: [],
170
+ blindSpots: [],
171
+ };
172
+
173
+ try {
174
+ const [hosts, detectedLibraries] = await Promise.all([
175
+ enumerateShadowHosts(page),
176
+ detectWebComponentLibrary(page),
177
+ ]);
178
+
179
+ const openHosts = hosts.filter((h) => h.shadowMode === 'open');
180
+ const closedHosts = hosts.filter((h) => h.shadowMode === 'closed');
181
+ const maxNestingDepth = hosts.reduce((max, h) => Math.max(max, h.depth), 0);
182
+ const totalInteractiveInShadow = openHosts.reduce((sum, h) => sum + h.interactiveCount, 0);
183
+ const blindSpots = [...new Set(closedHosts.map((h) => h.tagName))];
184
+
185
+ return {
186
+ shadowHostCount: hosts.length,
187
+ openShadowCount: openHosts.length,
188
+ closedShadowCount: closedHosts.length,
189
+ maxNestingDepth,
190
+ hosts,
191
+ totalInteractiveInShadow,
192
+ detectedLibraries,
193
+ blindSpots,
194
+ };
195
+ } catch {
196
+ return empty;
197
+ }
198
+ }
@@ -0,0 +1,280 @@
1
+ import type { Page } from 'playwright';
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Internal: FNV-1a 32-bit SimHash
5
+ // ---------------------------------------------------------------------------
6
+
7
+ function fnv1a32(token: string): number {
8
+ let h = 2166136261;
9
+ for (let i = 0; i < token.length; i++) {
10
+ h = Math.imul(h ^ token.charCodeAt(i), 16777619);
11
+ h = h >>> 0;
12
+ }
13
+ return h;
14
+ }
15
+
16
+ export function simHash32(text: string): number {
17
+ const tokens = text
18
+ .split(/\W+/)
19
+ .filter((t) => t.length > 2)
20
+ .slice(0, 500);
21
+
22
+ const vec = new Array<number>(32).fill(0);
23
+
24
+ for (const token of tokens) {
25
+ const h = fnv1a32(token);
26
+ for (let b = 0; b < 32; b++) {
27
+ vec[b] += (h >>> b) & 1 ? 1 : -1;
28
+ }
29
+ }
30
+
31
+ let result = 0;
32
+ for (let b = 0; b < 32; b++) {
33
+ if (vec[b] > 0) result |= 1 << b;
34
+ }
35
+ return result >>> 0;
36
+ }
37
+
38
+ export function hammingDistance32(a: number, b: number): number {
39
+ let n = (a ^ b) >>> 0;
40
+ n = n - ((n >>> 1) & 0x55555555);
41
+ n = (n & 0x33333333) + ((n >>> 2) & 0x33333333);
42
+ n = (n + (n >>> 4)) & 0x0f0f0f0f;
43
+ return Math.imul(n, 0x01010101) >>> 24;
44
+ }
45
+
46
+ // ---------------------------------------------------------------------------
47
+ // URL normalisation
48
+ // ---------------------------------------------------------------------------
49
+
50
+ const STRIP_PARAMS = new Set([
51
+ 'utm_source', 'utm_medium', 'utm_campaign',
52
+ 'ref', '_ga', 'fbclid', 'session_id',
53
+ ]);
54
+
55
+ export function normalizeUrl(raw: string): string {
56
+ try {
57
+ const u = new URL(raw);
58
+ u.hash = '';
59
+ const keep: Array<[string, string]> = [];
60
+ u.searchParams.forEach((v, k) => {
61
+ if (!STRIP_PARAMS.has(k)) keep.push([k, v]);
62
+ });
63
+ keep.sort((a, b) => a[0].localeCompare(b[0]));
64
+ u.search = keep.length
65
+ ? '?' + keep.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&')
66
+ : '';
67
+ return u.toString();
68
+ } catch {
69
+ return raw;
70
+ }
71
+ }
72
+
73
+ export function computeStateId(normalizedUrl: string, hash: number): string {
74
+ let path = normalizedUrl.slice(0, 40).replace(/[^a-zA-Z0-9]/g, '_');
75
+ const hex = hash.toString(16).padStart(8, '0');
76
+ return `${path}_${hex}`;
77
+ }
78
+
79
+ // ---------------------------------------------------------------------------
80
+ // Public types
81
+ // ---------------------------------------------------------------------------
82
+
83
+ export interface UIStateNode {
84
+ id: string;
85
+ url: string;
86
+ normalizedUrl: string;
87
+ title: string;
88
+ interactiveElementCount: number;
89
+ domFingerprint: string;
90
+ simHashValue: number;
91
+ visitedAt: string;
92
+ }
93
+
94
+ export interface StateTransition {
95
+ fromId: string;
96
+ toId: string;
97
+ action: string;
98
+ label: string;
99
+ triggeredAt: string;
100
+ }
101
+
102
+ export interface CoverageReport {
103
+ totalStates: number;
104
+ totalTransitions: number;
105
+ uniqueUrls: number;
106
+ interactiveElementsTotal: number;
107
+ estimatedCoveragePercent: number;
108
+ }
109
+
110
+ // ---------------------------------------------------------------------------
111
+ // Page fingerprinting
112
+ // ---------------------------------------------------------------------------
113
+
114
+ export async function fingerprintPage(
115
+ page: Page,
116
+ visitedAt: string,
117
+ ): Promise<{
118
+ fingerprint: string;
119
+ visibleText: string;
120
+ interactiveCount: number;
121
+ simHashValue: number;
122
+ }> {
123
+ let visibleText = '';
124
+ let interactiveCount = 0;
125
+
126
+ try {
127
+ visibleText = await page.evaluate(() => {
128
+ const el = document.querySelector('main') ?? document.body;
129
+ return (el as HTMLElement).innerText ?? '';
130
+ });
131
+ } catch {
132
+ visibleText = '';
133
+ }
134
+
135
+ try {
136
+ interactiveCount = await page.evaluate(() =>
137
+ document.querySelectorAll(
138
+ 'a[href], button, input, select, textarea, [role="button"], [role="link"], [tabindex]',
139
+ ).length,
140
+ );
141
+ } catch {
142
+ interactiveCount = 0;
143
+ }
144
+
145
+ const simHashValue = simHash32(visibleText + visitedAt.slice(0, 10));
146
+ const fingerprint = simHashValue.toString(16).padStart(8, '0');
147
+
148
+ return { fingerprint, visibleText, interactiveCount, simHashValue };
149
+ }
150
+
151
+ // ---------------------------------------------------------------------------
152
+ // ScreenTransitionGraph
153
+ // ---------------------------------------------------------------------------
154
+
155
+ export class ScreenTransitionGraph {
156
+ private states = new Map<string, UIStateNode>();
157
+ private transitions: StateTransition[] = [];
158
+ /** Maps simHash value → array of state ids with that hash (for near-dup lookup) */
159
+ private hashIndex = new Map<number, string[]>();
160
+
161
+ // -------------------------------------------------------------------------
162
+ // State management
163
+ // -------------------------------------------------------------------------
164
+
165
+ addState(node: UIStateNode): { added: boolean; duplicateOf?: string } {
166
+ if (this.states.has(node.id)) {
167
+ return { added: false, duplicateOf: node.id };
168
+ }
169
+
170
+ // Check near-duplicate via hamming distance across all indexed hashes
171
+ for (const [indexedHash, ids] of this.hashIndex) {
172
+ if (hammingDistance32(node.simHashValue, indexedHash) < 3) {
173
+ return { added: false, duplicateOf: ids[0] };
174
+ }
175
+ }
176
+
177
+ this.states.set(node.id, node);
178
+
179
+ const bucket = this.hashIndex.get(node.simHashValue);
180
+ if (bucket) {
181
+ bucket.push(node.id);
182
+ } else {
183
+ this.hashIndex.set(node.simHashValue, [node.id]);
184
+ }
185
+
186
+ return { added: true };
187
+ }
188
+
189
+ addTransition(
190
+ fromId: string,
191
+ toId: string,
192
+ action: string,
193
+ label: string,
194
+ triggeredAt: string,
195
+ ): void {
196
+ this.transitions.push({ fromId, toId, action, label, triggeredAt });
197
+ }
198
+
199
+ isDuplicate(url: string, visibleText: string, threshold = 3): boolean {
200
+ const normalized = normalizeUrl(url);
201
+ const hash = simHash32(visibleText);
202
+ for (const [indexedHash] of this.hashIndex) {
203
+ if (hammingDistance32(hash, indexedHash) < threshold) return true;
204
+ }
205
+ // Also check exact normalized URL match
206
+ for (const node of this.states.values()) {
207
+ if (node.normalizedUrl === normalized) return true;
208
+ }
209
+ return false;
210
+ }
211
+
212
+ // -------------------------------------------------------------------------
213
+ // Reporting
214
+ // -------------------------------------------------------------------------
215
+
216
+ getCoverageReport(): CoverageReport {
217
+ const totalStates = this.states.size;
218
+ const totalTransitions = this.transitions.length;
219
+ const uniqueUrls = new Set(
220
+ Array.from(this.states.values()).map((n) => n.normalizedUrl),
221
+ ).size;
222
+ const interactiveElementsTotal = Array.from(this.states.values()).reduce(
223
+ (sum, n) => sum + n.interactiveElementCount,
224
+ 0,
225
+ );
226
+ const estimatedCoveragePercent = Math.min(
227
+ 100,
228
+ (totalTransitions / Math.max(1, totalStates)) * 50,
229
+ );
230
+ return {
231
+ totalStates,
232
+ totalTransitions,
233
+ uniqueUrls,
234
+ interactiveElementsTotal,
235
+ estimatedCoveragePercent,
236
+ };
237
+ }
238
+
239
+ // -------------------------------------------------------------------------
240
+ // Serialisation
241
+ // -------------------------------------------------------------------------
242
+
243
+ toJSON(): { states: UIStateNode[]; transitions: StateTransition[] } {
244
+ return {
245
+ states: Array.from(this.states.values()),
246
+ transitions: this.transitions,
247
+ };
248
+ }
249
+
250
+ static fromJSON(data: { states: UIStateNode[]; transitions: StateTransition[] }): ScreenTransitionGraph {
251
+ const graph = new ScreenTransitionGraph();
252
+ for (const node of data.states) {
253
+ graph.states.set(node.id, node);
254
+ const bucket = graph.hashIndex.get(node.simHashValue);
255
+ if (bucket) {
256
+ bucket.push(node.id);
257
+ } else {
258
+ graph.hashIndex.set(node.simHashValue, [node.id]);
259
+ }
260
+ }
261
+ graph.transitions = [...data.transitions];
262
+ return graph;
263
+ }
264
+
265
+ // -------------------------------------------------------------------------
266
+ // Accessors
267
+ // -------------------------------------------------------------------------
268
+
269
+ getState(id: string): UIStateNode | undefined {
270
+ return this.states.get(id);
271
+ }
272
+
273
+ getAllStates(): UIStateNode[] {
274
+ return Array.from(this.states.values());
275
+ }
276
+
277
+ getTransitionsFrom(id: string): StateTransition[] {
278
+ return this.transitions.filter((t) => t.fromId === id);
279
+ }
280
+ }