@detiq/crawler 1.1.13 → 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 (112) 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 +1071 -142
  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/http-engine.ts +29 -15
  73. package/src/index.ts +14 -1
  74. package/src/job-queue.ts +3 -1
  75. package/src/locator-extractor.ts +45 -0
  76. package/src/multi-context-handler.ts +296 -0
  77. package/src/nested-window-crawler.ts +310 -0
  78. package/src/network-action-correlator.ts +320 -0
  79. package/src/performance-metrics-collector.ts +243 -0
  80. package/src/performance-metrics.ts +1 -1
  81. package/src/screen-reader.ts +4 -1
  82. package/src/service-worker-interceptor.ts +185 -0
  83. package/src/session-capture.ts +3 -0
  84. package/src/shadow-dom-crawler.ts +198 -0
  85. package/src/sitemap.ts +17 -10
  86. package/src/state-graph.ts +280 -0
  87. package/src/stealth/human-behavior.ts +38 -4
  88. package/src/url-pattern-completer.ts +61 -15
  89. package/tsconfig.json +1 -1
  90. package/types/accessibility-tree-crawler.d.ts +44 -0
  91. package/types/advanced-ui-probes.d.ts +47 -0
  92. package/types/crawl-session-manager.d.ts +44 -0
  93. package/types/crawler.d.ts +3 -1
  94. package/types/crud-interaction.d.ts +31 -0
  95. package/types/dropdown-enumerator.d.ts +20 -0
  96. package/types/filter-pagination-crawler.d.ts +52 -0
  97. package/types/gap-pass.d.ts +1 -0
  98. package/types/index.d.ts +14 -1
  99. package/types/job-queue.d.ts +18 -9
  100. package/types/locator-extractor.d.ts +7 -0
  101. package/types/multi-context-handler.d.ts +55 -0
  102. package/types/nested-window-crawler.d.ts +41 -0
  103. package/types/network-action-correlator.d.ts +47 -0
  104. package/types/performance-metrics-collector.d.ts +50 -0
  105. package/types/performance-metrics.d.ts +1 -2
  106. package/types/screen-reader.d.ts +1 -2
  107. package/types/service-worker-interceptor.d.ts +36 -0
  108. package/types/session-capture.d.ts +1 -1
  109. package/types/shadow-dom-crawler.d.ts +35 -0
  110. package/types/sitemap.d.ts +2 -2
  111. package/types/state-graph.d.ts +59 -0
  112. package/types/stealth/human-behavior.d.ts +1 -1
@@ -0,0 +1,386 @@
1
+ import type { Page, Locator } from 'playwright';
2
+
3
+ // ── Types ─────────────────────────────────────────────────────────────────────
4
+
5
+ export type EditFlowType = 'inline' | 'modal' | 'navigation' | 'unknown';
6
+
7
+ export interface CrudFlowCapture {
8
+ entityName: string;
9
+ createTrigger?: string;
10
+ editFlowType: EditFlowType;
11
+ editFields: Array<{ name: string; type: string; prefilledValue?: string }>;
12
+ deleteConfirmation?: { message: string; confirmLabel: string; cancelLabel: string };
13
+ createSuccessToast?: string;
14
+ editSuccessToast?: string;
15
+ rowCount: number;
16
+ hasDeleteButton: boolean;
17
+ hasEditButton: boolean;
18
+ }
19
+
20
+ export interface CrudProbeResult {
21
+ flows: CrudFlowCapture[];
22
+ toastsObserved: Array<{ action: string; text: string; role: string }>;
23
+ }
24
+
25
+ // ── Internal: Toast observer ──────────────────────────────────────────────────
26
+
27
+ function injectToastObserver(page: Page): void {
28
+ page.evaluate(() => {
29
+ if ((window as any).__toastObserver) return;
30
+
31
+ (window as any).__capturedToasts = [] as Array<{ text: string; role: string }>;
32
+
33
+ const TOAST_CLASSES = ['toast', 'snackbar', 'notification'];
34
+
35
+ function matchesToast(el: Element): boolean {
36
+ const role = el.getAttribute('role') ?? '';
37
+ if (role === 'alert' || role === 'status') return true;
38
+ const cls = (el.getAttribute('class') ?? '').toLowerCase();
39
+ return TOAST_CLASSES.some((t) => cls.includes(t));
40
+ }
41
+
42
+ function captureNode(node: Node): void {
43
+ if (!(node instanceof Element)) return;
44
+ if (matchesToast(node)) {
45
+ const text = ((node as HTMLElement).innerText ?? '').replace(/\s+/g, ' ').trim();
46
+ const role = node.getAttribute('role') ?? 'alert';
47
+ if (text) (window as any).__capturedToasts.push({ text, role });
48
+ }
49
+ node.querySelectorAll('[role="alert"],[role="status"],[class*="toast"],[class*="Toast"],[class*="snackbar"],[class*="notification"]').forEach((child) => {
50
+ const text = ((child as HTMLElement).innerText ?? '').replace(/\s+/g, ' ').trim();
51
+ const role = child.getAttribute('role') ?? 'alert';
52
+ if (text) (window as any).__capturedToasts.push({ text, role });
53
+ });
54
+ }
55
+
56
+ const observer = new MutationObserver((mutations) => {
57
+ for (const m of mutations) {
58
+ m.addedNodes.forEach(captureNode);
59
+ }
60
+ });
61
+
62
+ observer.observe(document.body, { childList: true, subtree: true });
63
+ (window as any).__toastObserver = observer;
64
+ }).catch(() => undefined);
65
+ }
66
+
67
+ async function collectCapturedToasts(page: Page): Promise<Array<{ text: string; role: string }>> {
68
+ try {
69
+ return await page.evaluate(() => {
70
+ const toasts: Array<{ text: string; role: string }> = (window as any).__capturedToasts ?? [];
71
+ (window as any).__capturedToasts = [];
72
+ return toasts;
73
+ });
74
+ } catch {
75
+ return [];
76
+ }
77
+ }
78
+
79
+ // ── Internal: Button discovery ────────────────────────────────────────────────
80
+
81
+ interface CrudButtons {
82
+ editBtns: Locator[];
83
+ deleteBtns: Locator[];
84
+ createBtn: Locator | null;
85
+ }
86
+
87
+ async function findCrudButtons(page: Page): Promise<CrudButtons> {
88
+ const editLocator = page.locator(
89
+ 'button[aria-label*="edit" i], button[aria-label*="Edit"], button:has-text("Edit")'
90
+ );
91
+ const deleteLocator = page.locator(
92
+ 'button[aria-label*="delete" i], button[aria-label*="Delete"], button:has-text("Delete")'
93
+ );
94
+ const createLocator = page.locator(
95
+ 'button:has-text("New"), button:has-text("Create"), button:has-text("Add")'
96
+ );
97
+
98
+ const [editCount, deleteCount, createCount] = await Promise.all([
99
+ editLocator.count().catch(() => 0),
100
+ deleteLocator.count().catch(() => 0),
101
+ createLocator.count().catch(() => 0),
102
+ ]);
103
+
104
+ const editBtns: Locator[] = [];
105
+ for (let i = 0; i < Math.min(editCount, 3); i++) {
106
+ editBtns.push(editLocator.nth(i));
107
+ }
108
+
109
+ const deleteBtns: Locator[] = [];
110
+ for (let i = 0; i < Math.min(deleteCount, 3); i++) {
111
+ deleteBtns.push(deleteLocator.nth(i));
112
+ }
113
+
114
+ const createBtn = createCount > 0 ? createLocator.first() : null;
115
+
116
+ return { editBtns, deleteBtns, createBtn };
117
+ }
118
+
119
+ // ── Internal: Edit flow detection ─────────────────────────────────────────────
120
+
121
+ async function detectEditFlowType(page: Page, editButton: Locator): Promise<EditFlowType> {
122
+ try {
123
+ const urlBefore = page.url();
124
+ await editButton.click({ timeout: 2000 });
125
+ await page.waitForTimeout(600);
126
+
127
+ const urlAfter = page.url();
128
+ if (urlAfter !== urlBefore) {
129
+ await page.goBack().catch(() => undefined);
130
+ await page.waitForTimeout(300);
131
+ return 'navigation';
132
+ }
133
+
134
+ const dialogVisible = await page.locator('[role="dialog"]').first().isVisible().catch(() => false);
135
+ if (dialogVisible) {
136
+ await page.keyboard.press('Escape');
137
+ await page.waitForTimeout(300);
138
+ return 'modal';
139
+ }
140
+
141
+ const inlineInputCount = await page.locator('input:visible, textarea:visible').count().catch(() => 0);
142
+ if (inlineInputCount > 0) {
143
+ await page.keyboard.press('Escape');
144
+ await page.waitForTimeout(300);
145
+ return 'inline';
146
+ }
147
+
148
+ await page.keyboard.press('Escape');
149
+ await page.waitForTimeout(300);
150
+ return 'unknown';
151
+ } catch {
152
+ try {
153
+ await page.keyboard.press('Escape');
154
+ } catch { /* ignore */ }
155
+ return 'unknown';
156
+ }
157
+ }
158
+
159
+ // ── Internal: Modal field capture ─────────────────────────────────────────────
160
+
161
+ async function captureEditModal(
162
+ page: Page
163
+ ): Promise<Array<{ name: string; type: string; prefilledValue?: string }>> {
164
+ try {
165
+ const dialog = page.locator('[role="dialog"]').first();
166
+ const fields = dialog.locator('input, textarea, select');
167
+ const count = Math.min(await fields.count().catch(() => 0), 20);
168
+
169
+ const results: Array<{ name: string; type: string; prefilledValue?: string }> = [];
170
+
171
+ for (let i = 0; i < count; i++) {
172
+ try {
173
+ const field = fields.nth(i);
174
+ const tagName = await field.evaluate((el) => el.tagName.toLowerCase()).catch(() => 'input');
175
+ const inputType = await field.getAttribute('type').catch(() => null) ?? tagName;
176
+ const name =
177
+ (await field.getAttribute('name').catch(() => null)) ??
178
+ (await field.getAttribute('id').catch(() => null)) ??
179
+ (await field.getAttribute('aria-label').catch(() => null)) ??
180
+ `field_${i}`;
181
+ const prefilledValue = await field.inputValue().catch(() => undefined);
182
+
183
+ results.push({
184
+ name,
185
+ type: inputType,
186
+ prefilledValue: prefilledValue || undefined,
187
+ });
188
+ } catch { /* skip individual field errors */ }
189
+ }
190
+
191
+ return results;
192
+ } catch {
193
+ return [];
194
+ }
195
+ }
196
+
197
+ // ── Internal: Delete confirmation capture ─────────────────────────────────────
198
+
199
+ async function captureDeleteConfirmation(
200
+ page: Page,
201
+ deleteBtn: Locator
202
+ ): Promise<{ message: string; confirmLabel: string; cancelLabel: string } | null> {
203
+ try {
204
+ await deleteBtn.click({ timeout: 2000 });
205
+
206
+ const confirmDialog = page.locator('[role="alertdialog"], [role="dialog"]').first();
207
+ try {
208
+ await confirmDialog.waitFor({ state: 'visible', timeout: 2000 });
209
+ } catch {
210
+ await page.keyboard.press('Escape');
211
+ return null;
212
+ }
213
+
214
+ const dialogText = await confirmDialog.evaluate((el) =>
215
+ (el as HTMLElement).innerText?.replace(/\s+/g, ' ').trim()
216
+ ).catch(() => '');
217
+
218
+ const isDeleteDialog =
219
+ /delete|remove|are you sure|confirm/i.test(dialogText);
220
+
221
+ if (!isDeleteDialog) {
222
+ await page.keyboard.press('Escape');
223
+ return null;
224
+ }
225
+
226
+ // Capture button labels inside the dialog
227
+ const buttons = confirmDialog.locator('button');
228
+ const btnCount = await buttons.count().catch(() => 0);
229
+ const btnLabels: string[] = [];
230
+ for (let i = 0; i < btnCount; i++) {
231
+ try {
232
+ const label = await buttons.nth(i).innerText();
233
+ btnLabels.push(label.trim());
234
+ } catch { /* skip */ }
235
+ }
236
+
237
+ // Heuristic: confirm = first destructive-looking label, cancel = cancel/no label
238
+ const confirmLabel =
239
+ btnLabels.find((l) => /delete|remove|yes|confirm/i.test(l)) ??
240
+ btnLabels[0] ??
241
+ 'Confirm';
242
+ const cancelLabel =
243
+ btnLabels.find((l) => /cancel|no|keep|dismiss/i.test(l)) ??
244
+ btnLabels[btnLabels.length - 1] ??
245
+ 'Cancel';
246
+
247
+ // CRITICAL: Always cancel — never actually delete data
248
+ await page.keyboard.press('Escape');
249
+ await page.waitForTimeout(300);
250
+
251
+ return {
252
+ message: dialogText,
253
+ confirmLabel,
254
+ cancelLabel,
255
+ };
256
+ } catch {
257
+ try {
258
+ await page.keyboard.press('Escape');
259
+ } catch { /* ignore */ }
260
+ return null;
261
+ }
262
+ }
263
+
264
+ // ── Internal: Row count ───────────────────────────────────────────────────────
265
+
266
+ async function detectRowCount(page: Page): Promise<number> {
267
+ try {
268
+ // Try common table row patterns
269
+ const tableRows = await page.locator('table tbody tr').count().catch(() => 0);
270
+ if (tableRows > 0) return tableRows;
271
+
272
+ const listItems = await page.locator('[role="row"]').count().catch(() => 0);
273
+ if (listItems > 0) return listItems;
274
+
275
+ const dataItems = await page
276
+ .locator('[data-testid*="row"], [class*="row" i], [class*="item" i]')
277
+ .count()
278
+ .catch(() => 0);
279
+ return dataItems;
280
+ } catch {
281
+ return 0;
282
+ }
283
+ }
284
+
285
+ // ── Internal: Create trigger label ────────────────────────────────────────────
286
+
287
+ async function getCreateTriggerLabel(createBtn: Locator | null): Promise<string | undefined> {
288
+ if (!createBtn) return undefined;
289
+ try {
290
+ const label = await createBtn.innerText();
291
+ return label.trim() || undefined;
292
+ } catch {
293
+ return undefined;
294
+ }
295
+ }
296
+
297
+ // ── Public: probeCrudFlows ────────────────────────────────────────────────────
298
+
299
+ export async function probeCrudFlows(
300
+ page: Page,
301
+ entityName = 'Entity'
302
+ ): Promise<CrudProbeResult> {
303
+ const toastsObserved: Array<{ action: string; text: string; role: string }> = [];
304
+
305
+ // Step 1: Inject toast observer
306
+ injectToastObserver(page);
307
+
308
+ // Step 2: Find CRUD buttons
309
+ const { editBtns, deleteBtns, createBtn } = await findCrudButtons(page);
310
+
311
+ // Step 3: Row count
312
+ const rowCount = await detectRowCount(page);
313
+
314
+ // Step 4: Create trigger label
315
+ const createTrigger = await getCreateTriggerLabel(createBtn);
316
+
317
+ // Step 5: Probe edit flow (use first edit button)
318
+ let editFlowType: EditFlowType = 'unknown';
319
+ let editFields: Array<{ name: string; type: string; prefilledValue?: string }> = [];
320
+
321
+ if (editBtns.length > 0) {
322
+ try {
323
+ editFlowType = await detectEditFlowType(page, editBtns[0]);
324
+
325
+ if (editFlowType === 'modal') {
326
+ // Re-open to capture fields
327
+ try {
328
+ await editBtns[0].click({ timeout: 2000 });
329
+ await page.waitForTimeout(400);
330
+ const dialogVisible = await page
331
+ .locator('[role="dialog"]')
332
+ .first()
333
+ .isVisible()
334
+ .catch(() => false);
335
+ if (dialogVisible) {
336
+ editFields = await captureEditModal(page);
337
+ const editToasts = await collectCapturedToasts(page);
338
+ for (const t of editToasts) {
339
+ toastsObserved.push({ action: 'edit_open', ...t });
340
+ }
341
+ }
342
+ await page.keyboard.press('Escape');
343
+ await page.waitForTimeout(300);
344
+ } catch { /* non-fatal */ }
345
+ }
346
+ } catch { /* non-fatal */ }
347
+ }
348
+
349
+ // Step 6: Probe delete confirmation (NEVER actually delete)
350
+ let deleteConfirmation: CrudFlowCapture['deleteConfirmation'];
351
+
352
+ if (deleteBtns.length > 0) {
353
+ try {
354
+ const result = await captureDeleteConfirmation(page, deleteBtns[0]);
355
+ if (result) {
356
+ deleteConfirmation = result;
357
+ const deleteToasts = await collectCapturedToasts(page);
358
+ for (const t of deleteToasts) {
359
+ toastsObserved.push({ action: 'delete_cancel', ...t });
360
+ }
361
+ }
362
+ } catch { /* non-fatal */ }
363
+ }
364
+
365
+ // Step 7: Collect any remaining toasts
366
+ const remainingToasts = await collectCapturedToasts(page);
367
+ for (const t of remainingToasts) {
368
+ toastsObserved.push({ action: 'ambient', ...t });
369
+ }
370
+
371
+ const flow: CrudFlowCapture = {
372
+ entityName,
373
+ createTrigger,
374
+ editFlowType,
375
+ editFields,
376
+ deleteConfirmation,
377
+ rowCount,
378
+ hasDeleteButton: deleteBtns.length > 0,
379
+ hasEditButton: editBtns.length > 0,
380
+ };
381
+
382
+ return {
383
+ flows: [flow],
384
+ toastsObserved,
385
+ };
386
+ }
@@ -0,0 +1,312 @@
1
+ import type { Page } from 'playwright';
2
+
3
+ export interface DropdownOption {
4
+ value: string;
5
+ label: string;
6
+ disabled?: boolean;
7
+ }
8
+
9
+ export interface DropdownDef {
10
+ kind: 'native-select' | 'combobox' | 'listbox' | 'multiselect';
11
+ label: string;
12
+ locatorHint: string;
13
+ options: DropdownOption[];
14
+ defaultValue?: string;
15
+ cascadesFrom?: string;
16
+ }
17
+
18
+ export interface DropdownEnumerationResult {
19
+ dropdowns: DropdownDef[];
20
+ conditionalRevealMap: Record<string, string[]>;
21
+ totalOptionsFound: number;
22
+ }
23
+
24
+ async function enumerateNativeSelects(page: Page): Promise<DropdownDef[]> {
25
+ const selects = await page.$$('select:not([multiple])');
26
+ const limited = selects.slice(0, 50);
27
+ const results: DropdownDef[] = [];
28
+
29
+ for (const handle of limited) {
30
+ try {
31
+ const data = await handle.evaluate((el: HTMLSelectElement) => {
32
+ const name = el.name || el.id || '';
33
+ const ariaLabel = el.getAttribute('aria-label') || '';
34
+ let labelText = ariaLabel;
35
+ if (!labelText && el.id) {
36
+ const lbl = document.querySelector(`label[for="${el.id}"]`);
37
+ if (lbl) labelText = lbl.textContent?.trim() || '';
38
+ }
39
+ if (!labelText && name) labelText = name;
40
+ const options = Array.from(el.options).map((o) => ({
41
+ value: o.value,
42
+ label: o.text.trim(),
43
+ disabled: o.disabled || undefined,
44
+ }));
45
+ const selectedOption = el.options[el.selectedIndex];
46
+ const defaultValue = selectedOption ? selectedOption.value : undefined;
47
+ const locatorHint = name
48
+ ? `select[name="${name}"]`
49
+ : el.id
50
+ ? `select#${el.id}`
51
+ : 'select';
52
+ return { label: labelText, locatorHint, options, defaultValue };
53
+ });
54
+
55
+ results.push({
56
+ kind: 'native-select',
57
+ label: data.label,
58
+ locatorHint: data.locatorHint,
59
+ options: data.options,
60
+ defaultValue: data.defaultValue,
61
+ });
62
+ } catch {
63
+ // skip unresponsive handle
64
+ }
65
+ }
66
+
67
+ return results;
68
+ }
69
+
70
+ async function enumerateCustomDropdowns(page: Page): Promise<DropdownDef[]> {
71
+ const selectors = [
72
+ '[role="combobox"]',
73
+ '[aria-haspopup="listbox"]:not([role="combobox"])',
74
+ '[data-radix-select-trigger]',
75
+ ];
76
+
77
+ const seen = new Set<string>();
78
+ const handles: { handle: Awaited<ReturnType<Page['$$']>>[0]; hint: string }[] = [];
79
+
80
+ for (const sel of selectors) {
81
+ const els = await page.$$(sel);
82
+ for (const el of els) {
83
+ const hint = await el
84
+ .evaluate((e: Element) => {
85
+ const id = e.id ? `#${e.id}` : '';
86
+ const aria = e.getAttribute('aria-label') || '';
87
+ return id || aria || e.tagName.toLowerCase();
88
+ })
89
+ .catch(() => '');
90
+ if (!seen.has(hint)) {
91
+ seen.add(hint);
92
+ handles.push({ handle: el, hint });
93
+ }
94
+ }
95
+ }
96
+
97
+ const limited = handles.slice(0, 20);
98
+ const results: DropdownDef[] = [];
99
+
100
+ for (const { handle, hint } of limited) {
101
+ try {
102
+ const ariaLabel = await handle
103
+ .evaluate((e: Element) => e.getAttribute('aria-label') || e.textContent?.trim() || '')
104
+ .catch(() => '');
105
+
106
+ await handle.click();
107
+ await page.waitForSelector('[role="listbox"]', { timeout: 2000 });
108
+
109
+ const options = await page.$$eval('[role="listbox"] [role="option"]', (els) =>
110
+ els.map((el) => ({
111
+ value: el.getAttribute('data-value') || el.getAttribute('value') || el.textContent?.trim() || '',
112
+ label: el.textContent?.trim() || '',
113
+ disabled: el.getAttribute('aria-disabled') === 'true' || undefined,
114
+ }))
115
+ );
116
+
117
+ await page.keyboard.press('Escape');
118
+ await page.waitForTimeout(300);
119
+
120
+ results.push({
121
+ kind: 'combobox',
122
+ label: ariaLabel,
123
+ locatorHint: hint,
124
+ options,
125
+ });
126
+ } catch {
127
+ try {
128
+ await page.keyboard.press('Escape');
129
+ await page.waitForTimeout(300);
130
+ } catch {
131
+ // ignore cleanup failure
132
+ }
133
+ }
134
+ }
135
+
136
+ return results;
137
+ }
138
+
139
+ async function enumerateMultiSelects(page: Page): Promise<DropdownDef[]> {
140
+ const results: DropdownDef[] = [];
141
+
142
+ const nativeMulti = await page.$$('select[multiple]');
143
+ for (const handle of nativeMulti) {
144
+ try {
145
+ const data = await handle.evaluate((el: HTMLSelectElement) => {
146
+ const name = el.name || el.id || '';
147
+ const ariaLabel = el.getAttribute('aria-label') || '';
148
+ let labelText = ariaLabel;
149
+ if (!labelText && el.id) {
150
+ const lbl = document.querySelector(`label[for="${el.id}"]`);
151
+ if (lbl) labelText = lbl.textContent?.trim() || '';
152
+ }
153
+ if (!labelText && name) labelText = name;
154
+ const options = Array.from(el.options).map((o) => ({
155
+ value: o.value,
156
+ label: o.text.trim(),
157
+ disabled: o.disabled || undefined,
158
+ }));
159
+ const locatorHint = name
160
+ ? `select[multiple][name="${name}"]`
161
+ : el.id
162
+ ? `select[multiple]#${el.id}`
163
+ : 'select[multiple]';
164
+ return { label: labelText, locatorHint, options };
165
+ });
166
+
167
+ results.push({
168
+ kind: 'multiselect',
169
+ label: data.label,
170
+ locatorHint: data.locatorHint,
171
+ options: data.options,
172
+ });
173
+ } catch {
174
+ // skip
175
+ }
176
+ }
177
+
178
+ const ariaMulti = await page.$$('[role="listbox"][aria-multiselectable="true"]');
179
+ for (const handle of ariaMulti) {
180
+ try {
181
+ const data = await handle.evaluate((el: Element) => {
182
+ const ariaLabel = el.getAttribute('aria-label') || el.id || '';
183
+ const locatorHint = el.id
184
+ ? `[role="listbox"]#${el.id}`
185
+ : '[role="listbox"][aria-multiselectable="true"]';
186
+ const optionEls = el.querySelectorAll('[role="option"]');
187
+ const options = Array.from(optionEls).map((o) => ({
188
+ value: o.getAttribute('data-value') || o.getAttribute('value') || o.textContent?.trim() || '',
189
+ label: o.textContent?.trim() || '',
190
+ disabled: o.getAttribute('aria-disabled') === 'true' || undefined,
191
+ }));
192
+ return { label: ariaLabel, locatorHint, options };
193
+ });
194
+
195
+ results.push({
196
+ kind: 'multiselect',
197
+ label: data.label,
198
+ locatorHint: data.locatorHint,
199
+ options: data.options,
200
+ });
201
+ } catch {
202
+ // skip
203
+ }
204
+ }
205
+
206
+ return results;
207
+ }
208
+
209
+ async function detectCascading(
210
+ page: Page,
211
+ dropdowns: DropdownDef[]
212
+ ): Promise<Record<string, string[]>> {
213
+ const cascadeMap: Record<string, string[]> = {};
214
+
215
+ const nativeParents = dropdowns.filter(
216
+ (d) => d.kind === 'native-select' && d.options.length <= 8
217
+ );
218
+
219
+ for (const parent of nativeParents) {
220
+ const parentName = parent.locatorHint.match(/name="([^"]+)"/)?.[1];
221
+ if (!parentName) continue;
222
+
223
+ const otherNatives = dropdowns.filter(
224
+ (d) => d.kind === 'native-select' && d.locatorHint !== parent.locatorHint
225
+ );
226
+ if (otherNatives.length === 0) continue;
227
+
228
+ const baselineCounts = await page
229
+ .$$eval('select:not([multiple])', (els) =>
230
+ (els as HTMLSelectElement[]).map((el) => ({ name: el.name || el.id, count: el.options.length }))
231
+ )
232
+ .catch(() => [] as { name: string; count: number }[]);
233
+
234
+ let foundChildren: string[] = [];
235
+
236
+ for (let i = 0; i < parent.options.length; i++) {
237
+ try {
238
+ await page.selectOption(`select[name="${parentName}"]`, { index: i });
239
+ await page.waitForTimeout(500);
240
+
241
+ const newCounts = await page
242
+ .$$eval('select:not([multiple])', (els) =>
243
+ (els as HTMLSelectElement[]).map((el) => ({ name: el.name || el.id, count: el.options.length }))
244
+ )
245
+ .catch(() => [] as { name: string; count: number }[]);
246
+
247
+ for (const curr of newCounts) {
248
+ const base = baselineCounts.find((b) => b.name === curr.name);
249
+ if (base && base.count !== curr.count && curr.name !== parentName) {
250
+ const childHint = `select[name="${curr.name}"]`;
251
+ const childDef = dropdowns.find((d) => d.locatorHint === childHint);
252
+ if (childDef && !foundChildren.includes(childHint)) {
253
+ foundChildren.push(childHint);
254
+ }
255
+ }
256
+ }
257
+ } catch {
258
+ // skip option that fails
259
+ }
260
+ }
261
+
262
+ // reset to index 0
263
+ try {
264
+ await page.selectOption(`select[name="${parentName}"]`, { index: 0 });
265
+ } catch {
266
+ // ignore reset failure
267
+ }
268
+
269
+ if (foundChildren.length > 0) {
270
+ cascadeMap[parent.locatorHint] = foundChildren;
271
+ }
272
+ }
273
+
274
+ return cascadeMap;
275
+ }
276
+
277
+ export async function enumerateDropdowns(page: Page): Promise<DropdownEnumerationResult> {
278
+ try {
279
+ const [native, custom, multi] = await Promise.all([
280
+ enumerateNativeSelects(page).catch(() => [] as DropdownDef[]),
281
+ enumerateCustomDropdowns(page).catch(() => [] as DropdownDef[]),
282
+ enumerateMultiSelects(page).catch(() => [] as DropdownDef[]),
283
+ ]);
284
+
285
+ const seen = new Set<string>();
286
+ const dropdowns: DropdownDef[] = [];
287
+
288
+ for (const d of [...native, ...custom, ...multi]) {
289
+ if (!seen.has(d.locatorHint)) {
290
+ seen.add(d.locatorHint);
291
+ dropdowns.push(d);
292
+ }
293
+ }
294
+
295
+ const conditionalRevealMap = await detectCascading(page, dropdowns).catch(
296
+ () => ({} as Record<string, string[]>)
297
+ );
298
+
299
+ for (const [parent, children] of Object.entries(conditionalRevealMap)) {
300
+ for (const childHint of children) {
301
+ const child = dropdowns.find((d) => d.locatorHint === childHint);
302
+ if (child) child.cascadesFrom = parent;
303
+ }
304
+ }
305
+
306
+ const totalOptionsFound = dropdowns.reduce((sum, d) => sum + d.options.length, 0);
307
+
308
+ return { dropdowns, conditionalRevealMap, totalOptionsFound };
309
+ } catch {
310
+ return { dropdowns: [], conditionalRevealMap: {}, totalOptionsFound: 0 };
311
+ }
312
+ }