@runtypelabs/persona 3.21.2 → 3.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +67 -0
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/{types-CWPIj66R.d.cts → types-BZVr1YOV.d.cts} +10 -0
  5. package/dist/animations/{types-CWPIj66R.d.ts → types-BZVr1YOV.d.ts} +10 -0
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/index.cjs +50 -43
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +474 -6
  11. package/dist/index.d.ts +474 -6
  12. package/dist/index.global.js +98 -88
  13. package/dist/index.global.js.map +1 -1
  14. package/dist/index.js +48 -41
  15. package/dist/index.js.map +1 -1
  16. package/dist/smart-dom-reader.cjs +1875 -0
  17. package/dist/smart-dom-reader.d.cts +4521 -0
  18. package/dist/smart-dom-reader.d.ts +4521 -0
  19. package/dist/smart-dom-reader.js +1848 -0
  20. package/dist/theme-editor.cjs +2282 -90
  21. package/dist/theme-editor.d.cts +348 -1
  22. package/dist/theme-editor.d.ts +348 -1
  23. package/dist/theme-editor.js +2267 -90
  24. package/package.json +9 -2
  25. package/src/client.test.ts +165 -0
  26. package/src/client.ts +144 -23
  27. package/src/components/composer-parts.test.ts +34 -0
  28. package/src/components/composer-parts.ts +9 -6
  29. package/src/index.ts +26 -0
  30. package/src/session.test.ts +258 -0
  31. package/src/session.ts +886 -30
  32. package/src/session.webmcp.test.ts +815 -0
  33. package/src/smart-dom-reader.test.ts +135 -0
  34. package/src/smart-dom-reader.ts +135 -0
  35. package/src/theme-editor/color-utils.test.ts +59 -0
  36. package/src/theme-editor/color-utils.ts +38 -2
  37. package/src/theme-editor/index.ts +35 -0
  38. package/src/theme-editor/webmcp/coerce.test.ts +86 -0
  39. package/src/theme-editor/webmcp/coerce.ts +286 -0
  40. package/src/theme-editor/webmcp/index.ts +45 -0
  41. package/src/theme-editor/webmcp/summary.ts +324 -0
  42. package/src/theme-editor/webmcp/tools.test.ts +205 -0
  43. package/src/theme-editor/webmcp/tools.ts +795 -0
  44. package/src/theme-editor/webmcp/types.ts +87 -0
  45. package/src/types.ts +186 -0
  46. package/src/ui.composer-keyboard.test.ts +229 -0
  47. package/src/ui.ts +127 -5
  48. package/src/utils/composer-history.test.ts +128 -0
  49. package/src/utils/composer-history.ts +113 -0
  50. package/src/utils/message-fingerprint.test.ts +20 -0
  51. package/src/utils/message-fingerprint.ts +2 -0
  52. package/src/utils/smart-dom-adapter.test.ts +257 -0
  53. package/src/utils/smart-dom-adapter.ts +217 -0
  54. package/{LICENSE → src/vendor/smart-dom-reader/LICENSE} +2 -2
  55. package/src/vendor/smart-dom-reader/README.md +61 -0
  56. package/src/vendor/smart-dom-reader/index.d.ts +476 -0
  57. package/src/vendor/smart-dom-reader/index.js +1618 -0
  58. package/src/webmcp-bridge.test.ts +429 -0
  59. package/src/webmcp-bridge.ts +547 -0
@@ -0,0 +1,1618 @@
1
+ /**
2
+ * VENDORED — @mcp-b/smart-dom-reader v2.3.1 (MIT, (c) 2025 mcp-b contributors).
3
+ * Source: https://github.com/WebMCP-org/npm-packages/tree/main/packages/smart-dom-reader
4
+ *
5
+ * Vendored rather than installed as a dependency because every published version
6
+ * (2.3.1, 2.3.2, 3.0.0) is mis-published: package.json exports/main/types point to
7
+ * dist/index.js + dist/index.d.ts, but the build only ships dist/index.mjs +
8
+ * dist/index.d.mts, so the package cannot be imported by name in Node or any bundler.
9
+ * See LICENSE in this directory and ./README.md for provenance and update steps.
10
+ *
11
+ * Local modifications (the ONLY edits to upstream dist/index.mjs):
12
+ * 1. Removed top-level `import { createRequire } from "node:module";` (browser-hostile).
13
+ * 2. Replaced `var __require = createRequire(import.meta.url);` with `var __require = void 0;`.
14
+ * __require is referenced only inside a guarded `typeof __require === "function"`
15
+ * Node fallback in resolveSmartDomReader(); the browser path returns earlier, so
16
+ * this is a no-op at runtime in the browser.
17
+ * Everything else is byte-for-byte upstream.
18
+ */
19
+ /* eslint-disable */
20
+ //#region \0rolldown/runtime.js
21
+ var __defProp = Object.defineProperty;
22
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
23
+ var __getOwnPropNames = Object.getOwnPropertyNames;
24
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
25
+ var __esmMin = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
26
+ var __exportAll = (all, no_symbols) => {
27
+ let target = {};
28
+ for (var name in all) __defProp(target, name, {
29
+ get: all[name],
30
+ enumerable: true
31
+ });
32
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
33
+ return target;
34
+ };
35
+ var __copyProps = (to, from, except, desc) => {
36
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
37
+ key = keys[i];
38
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
39
+ get: ((k) => from[k]).bind(null, key),
40
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
41
+ });
42
+ }
43
+ return to;
44
+ };
45
+ var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
+ var __require = void 0;
47
+ //#endregion
48
+ //#region src/content-detection.ts
49
+ var ContentDetection;
50
+ var init_content_detection = __esmMin((() => {
51
+ ContentDetection = class ContentDetection {
52
+ /**
53
+ * Find the main content area of a page
54
+ * Inspired by dom-to-semantic-markdown's approach
55
+ */
56
+ static findMainContent(doc) {
57
+ const mainElement = doc.querySelector("main, [role=\"main\"]");
58
+ if (mainElement) return mainElement;
59
+ if (!doc.body) return doc.documentElement;
60
+ return ContentDetection.detectMainContent(doc.body);
61
+ }
62
+ /**
63
+ * Detect main content using scoring algorithm
64
+ */
65
+ static detectMainContent(rootElement) {
66
+ const candidates = [];
67
+ ContentDetection.collectCandidates(rootElement, candidates, 15);
68
+ if (candidates.length === 0) return rootElement;
69
+ candidates.sort((a, b) => ContentDetection.calculateContentScore(b) - ContentDetection.calculateContentScore(a));
70
+ let bestCandidate = candidates[0];
71
+ for (let i = 1; i < candidates.length; i++) {
72
+ const candidate = candidates[i];
73
+ if (!candidates.some((other, j) => j !== i && other.contains(candidate)) && ContentDetection.calculateContentScore(candidate) > ContentDetection.calculateContentScore(bestCandidate)) bestCandidate = candidate;
74
+ }
75
+ return bestCandidate;
76
+ }
77
+ /**
78
+ * Collect content candidates
79
+ */
80
+ static collectCandidates(element, candidates, minScore) {
81
+ if (ContentDetection.calculateContentScore(element) >= minScore) candidates.push(element);
82
+ Array.from(element.children).forEach((child) => {
83
+ ContentDetection.collectCandidates(child, candidates, minScore);
84
+ });
85
+ }
86
+ /**
87
+ * Calculate content score for an element
88
+ */
89
+ static calculateContentScore(element) {
90
+ let score = 0;
91
+ const semanticClasses = [
92
+ "article",
93
+ "content",
94
+ "main-container",
95
+ "main",
96
+ "main-content",
97
+ "post",
98
+ "entry"
99
+ ];
100
+ const semanticIds = [
101
+ "content",
102
+ "main",
103
+ "article",
104
+ "post",
105
+ "entry"
106
+ ];
107
+ semanticClasses.forEach((cls) => {
108
+ if (element.classList.contains(cls)) score += 10;
109
+ });
110
+ semanticIds.forEach((id) => {
111
+ if (element.id?.toLowerCase().includes(id)) score += 10;
112
+ });
113
+ const tag = element.tagName.toLowerCase();
114
+ if ([
115
+ "article",
116
+ "main",
117
+ "section"
118
+ ].includes(tag)) score += 8;
119
+ const paragraphs = element.getElementsByTagName("p").length;
120
+ score += Math.min(paragraphs * 2, 10);
121
+ const headings = element.querySelectorAll("h1, h2, h3").length;
122
+ score += Math.min(headings * 3, 9);
123
+ const textLength = element.textContent?.trim().length || 0;
124
+ if (textLength > 300) score += Math.min(Math.floor(textLength / 300) * 2, 10);
125
+ const linkDensity = ContentDetection.calculateLinkDensity(element);
126
+ if (linkDensity < .3) score += 5;
127
+ else if (linkDensity > .5) score -= 5;
128
+ if (element.hasAttribute("data-main") || element.hasAttribute("data-content") || element.hasAttribute("itemprop")) score += 8;
129
+ const role = element.getAttribute("role");
130
+ if (role === "main" || role === "article") score += 10;
131
+ if (element.matches("aside, nav, header, footer, .sidebar, .navigation, .menu, .ad, .advertisement")) score -= 10;
132
+ if (element.getElementsByTagName("form").length > 2) score -= 5;
133
+ return Math.max(0, score);
134
+ }
135
+ /**
136
+ * Calculate link density in an element
137
+ */
138
+ static calculateLinkDensity(element) {
139
+ const links = element.getElementsByTagName("a");
140
+ let linkTextLength = 0;
141
+ for (const link of Array.from(links)) linkTextLength += link.textContent?.length || 0;
142
+ const totalTextLength = element.textContent?.length || 1;
143
+ return linkTextLength / totalTextLength;
144
+ }
145
+ /**
146
+ * Check if an element is likely navigation
147
+ */
148
+ static isNavigation(element) {
149
+ if (element.tagName.toLowerCase() === "nav" || element.getAttribute("role") === "navigation") return true;
150
+ const navPatterns = [
151
+ /nav/i,
152
+ /menu/i,
153
+ /sidebar/i,
154
+ /toolbar/i
155
+ ];
156
+ const classesAndId = `${element.className} ${element.id}`.toLowerCase();
157
+ return navPatterns.some((pattern) => pattern.test(classesAndId));
158
+ }
159
+ /**
160
+ * Check if element is likely supplementary content
161
+ */
162
+ static isSupplementary(element) {
163
+ if (element.tagName.toLowerCase() === "aside" || element.getAttribute("role") === "complementary") return true;
164
+ const supplementaryPatterns = [
165
+ /sidebar/i,
166
+ /widget/i,
167
+ /related/i,
168
+ /advertisement/i,
169
+ /social/i
170
+ ];
171
+ const classesAndId = `${element.className} ${element.id}`.toLowerCase();
172
+ return supplementaryPatterns.some((pattern) => pattern.test(classesAndId));
173
+ }
174
+ /**
175
+ * Detect page landmarks
176
+ */
177
+ static detectLandmarks(doc) {
178
+ const landmarks = {
179
+ navigation: [],
180
+ main: [],
181
+ complementary: [],
182
+ contentinfo: [],
183
+ banner: [],
184
+ search: [],
185
+ form: [],
186
+ region: []
187
+ };
188
+ for (const [landmark, selector] of Object.entries({
189
+ navigation: "nav, [role=\"navigation\"]",
190
+ main: "main, [role=\"main\"]",
191
+ complementary: "aside, [role=\"complementary\"]",
192
+ contentinfo: "footer, [role=\"contentinfo\"]",
193
+ banner: "header, [role=\"banner\"]",
194
+ search: "[role=\"search\"]",
195
+ form: "form[aria-label], form[aria-labelledby], [role=\"form\"]",
196
+ region: "section[aria-label], section[aria-labelledby], [role=\"region\"]"
197
+ })) {
198
+ const elements = doc.querySelectorAll(selector);
199
+ landmarks[landmark] = Array.from(elements);
200
+ }
201
+ return landmarks;
202
+ }
203
+ };
204
+ }));
205
+ //#endregion
206
+ //#region src/selectors.ts
207
+ var SelectorGenerator;
208
+ var init_selectors = __esmMin((() => {
209
+ SelectorGenerator = class SelectorGenerator {
210
+ /**
211
+ * Generate multiple selector strategies for an element
212
+ */
213
+ static generateSelectors(element) {
214
+ const doc = element.ownerDocument || document;
215
+ const candidates = [];
216
+ if (element.id && SelectorGenerator.isUniqueId(element.id, doc)) candidates.push({
217
+ type: "id",
218
+ value: `#${CSS.escape(element.id)}`,
219
+ score: 100
220
+ });
221
+ const testId = SelectorGenerator.getDataTestId(element);
222
+ if (testId) {
223
+ const v = `[data-testid="${CSS.escape(testId)}"]`;
224
+ candidates.push({
225
+ type: "data-testid",
226
+ value: v,
227
+ score: 90 + (SelectorGenerator.isUniqueSelectorSafe(v, doc) ? 5 : 0)
228
+ });
229
+ }
230
+ const role = element.getAttribute("role");
231
+ const aria = element.getAttribute("aria-label");
232
+ if (role && aria) {
233
+ const v = `[role="${CSS.escape(role)}"][aria-label="${CSS.escape(aria)}"]`;
234
+ candidates.push({
235
+ type: "role-aria",
236
+ value: v,
237
+ score: 85 + (SelectorGenerator.isUniqueSelectorSafe(v, doc) ? 5 : 0)
238
+ });
239
+ }
240
+ const nameAttr = element.getAttribute("name");
241
+ if (nameAttr) {
242
+ const v = `[name="${CSS.escape(nameAttr)}"]`;
243
+ candidates.push({
244
+ type: "name",
245
+ value: v,
246
+ score: 78 + (SelectorGenerator.isUniqueSelectorSafe(v, doc) ? 5 : 0)
247
+ });
248
+ }
249
+ const pathCss = SelectorGenerator.generateCSSSelector(element, doc);
250
+ const structuralPenalty = (pathCss.match(/:nth-child\(/g) || []).length * 10;
251
+ const classBonus = pathCss.includes(".") ? 8 : 0;
252
+ const pathScore = Math.max(0, 70 + classBonus - structuralPenalty);
253
+ candidates.push({
254
+ type: "class-path",
255
+ value: pathCss,
256
+ score: pathScore
257
+ });
258
+ const xpath = SelectorGenerator.generateXPath(element, doc);
259
+ candidates.push({
260
+ type: "xpath",
261
+ value: xpath,
262
+ score: 40
263
+ });
264
+ const textBased = SelectorGenerator.generateTextBasedSelector(element);
265
+ if (textBased) candidates.push({
266
+ type: "text",
267
+ value: textBased,
268
+ score: 30
269
+ });
270
+ candidates.sort((a, b) => b.score - a.score);
271
+ const selector = {
272
+ css: candidates.find((c) => c.type !== "xpath" && c.type !== "text")?.value || pathCss,
273
+ xpath,
274
+ candidates
275
+ };
276
+ if (textBased) selector.textBased = textBased;
277
+ if (testId) selector.dataTestId = testId;
278
+ if (aria) selector.ariaLabel = aria;
279
+ return selector;
280
+ }
281
+ /**
282
+ * Generate a unique CSS selector for an element
283
+ */
284
+ static generateCSSSelector(element, doc) {
285
+ if (element.id && SelectorGenerator.isUniqueId(element.id, doc)) return `#${CSS.escape(element.id)}`;
286
+ const testId = SelectorGenerator.getDataTestId(element);
287
+ if (testId) return `[data-testid="${CSS.escape(testId)}"]`;
288
+ const path = [];
289
+ let current = element;
290
+ while (current && current.nodeType === Node.ELEMENT_NODE) {
291
+ let selector = current.nodeName.toLowerCase();
292
+ if (current.id && SelectorGenerator.isUniqueId(current.id, doc)) {
293
+ selector = `#${CSS.escape(current.id)}`;
294
+ path.unshift(selector);
295
+ break;
296
+ }
297
+ const classes = SelectorGenerator.getMeaningfulClasses(current);
298
+ if (classes.length > 0) selector += `.${classes.map((c) => CSS.escape(c)).join(".")}`;
299
+ const siblings = current.parentElement?.children;
300
+ if (siblings && siblings.length > 1) {
301
+ const index = Array.from(siblings).indexOf(current);
302
+ if (index > 0 || !SelectorGenerator.isUniqueSelector(selector, current.parentElement)) selector += `:nth-child(${index + 1})`;
303
+ }
304
+ path.unshift(selector);
305
+ current = current.parentElement;
306
+ }
307
+ return SelectorGenerator.optimizePath(path, element, doc);
308
+ }
309
+ /**
310
+ * Generate XPath for an element
311
+ */
312
+ static generateXPath(element, doc) {
313
+ if (element.id && SelectorGenerator.isUniqueId(element.id, doc)) return `//*[@id="${element.id}"]`;
314
+ const path = [];
315
+ let current = element;
316
+ while (current && current.nodeType === Node.ELEMENT_NODE) {
317
+ const tagName = current.nodeName.toLowerCase();
318
+ if (current.id && SelectorGenerator.isUniqueId(current.id, doc)) {
319
+ path.unshift(`//*[@id="${current.id}"]`);
320
+ break;
321
+ }
322
+ let xpath = tagName;
323
+ const siblings = current.parentElement?.children;
324
+ if (siblings) {
325
+ const sameTagSiblings = Array.from(siblings).filter((s) => s.nodeName.toLowerCase() === tagName);
326
+ if (sameTagSiblings.length > 1) {
327
+ const index = sameTagSiblings.indexOf(current) + 1;
328
+ xpath += `[${index}]`;
329
+ }
330
+ }
331
+ path.unshift(xpath);
332
+ current = current.parentElement;
333
+ }
334
+ return `//${path.join("/")}`;
335
+ }
336
+ /**
337
+ * Generate a text-based selector for buttons and links
338
+ */
339
+ static generateTextBasedSelector(element) {
340
+ const text = element.textContent?.trim();
341
+ if (!text || text.length > 50) return void 0;
342
+ const tag = element.nodeName.toLowerCase();
343
+ if ([
344
+ "button",
345
+ "a",
346
+ "label"
347
+ ].includes(tag)) return `${tag}:contains("${text.replace(/['"\\]/g, "\\$&")}")`;
348
+ }
349
+ /**
350
+ * Get data-testid or similar attributes
351
+ */
352
+ static getDataTestId(element) {
353
+ return element.getAttribute("data-testid") || element.getAttribute("data-test-id") || element.getAttribute("data-test") || element.getAttribute("data-cy") || void 0;
354
+ }
355
+ /**
356
+ * Check if an ID is unique in the document
357
+ */
358
+ static isUniqueId(id, doc) {
359
+ return doc.querySelectorAll(`#${CSS.escape(id)}`).length === 1;
360
+ }
361
+ /**
362
+ * Check if a selector is unique within a container
363
+ */
364
+ static isUniqueSelector(selector, container) {
365
+ try {
366
+ return container.querySelectorAll(selector).length === 1;
367
+ } catch {
368
+ return false;
369
+ }
370
+ }
371
+ static isUniqueSelectorSafe(selector, doc) {
372
+ try {
373
+ return doc.querySelectorAll(selector).length === 1;
374
+ } catch {
375
+ return false;
376
+ }
377
+ }
378
+ /**
379
+ * Get meaningful classes (filtering out utility classes)
380
+ */
381
+ static getMeaningfulClasses(element) {
382
+ const classes = Array.from(element.classList);
383
+ const utilityPatterns = [
384
+ /^(p|m|w|h|text|bg|border|flex|grid|col|row)-/,
385
+ /^(xs|sm|md|lg|xl|2xl):/,
386
+ /^(hover|focus|active|disabled|checked):/,
387
+ /^js-/,
388
+ /^is-/,
389
+ /^has-/
390
+ ];
391
+ return classes.filter((cls) => {
392
+ if (cls.length < 3) return false;
393
+ return !utilityPatterns.some((pattern) => pattern.test(cls));
394
+ }).slice(0, 2);
395
+ }
396
+ /**
397
+ * Optimize the selector path by removing unnecessary parts
398
+ */
399
+ static optimizePath(path, element, doc) {
400
+ for (let i = 0; i < path.length - 1; i++) {
401
+ const shortPath = path.slice(i).join(" > ");
402
+ try {
403
+ const matches = doc.querySelectorAll(shortPath);
404
+ if (matches.length === 1 && matches[0] === element) return shortPath;
405
+ } catch {}
406
+ }
407
+ return path.join(" > ");
408
+ }
409
+ /**
410
+ * Get a human-readable path description
411
+ */
412
+ static getContextPath(element) {
413
+ const path = [];
414
+ let current = element;
415
+ let depth = 0;
416
+ const maxDepth = 5;
417
+ while (current && current !== element.ownerDocument?.body && depth < maxDepth) {
418
+ const tag = current.nodeName.toLowerCase();
419
+ let descriptor = tag;
420
+ if (current.id) descriptor = `${tag}#${current.id}`;
421
+ else if (current.className && typeof current.className === "string") {
422
+ const firstClass = current.className.split(" ")[0];
423
+ if (firstClass) descriptor = `${tag}.${firstClass}`;
424
+ }
425
+ const role = current.getAttribute("role");
426
+ if (role) descriptor += `[role="${role}"]`;
427
+ path.unshift(descriptor);
428
+ current = current.parentElement;
429
+ depth++;
430
+ }
431
+ return path;
432
+ }
433
+ };
434
+ }));
435
+ //#endregion
436
+ //#region src/traversal.ts
437
+ var DOMTraversal;
438
+ var init_traversal = __esmMin((() => {
439
+ init_selectors();
440
+ DOMTraversal = class DOMTraversal {
441
+ static INTERACTIVE_SELECTORS = [
442
+ "button",
443
+ "a[href]",
444
+ "input:not([type=\"hidden\"])",
445
+ "textarea",
446
+ "select",
447
+ "[role=\"button\"]",
448
+ "[onclick]",
449
+ "[contenteditable=\"true\"]",
450
+ "summary",
451
+ "[tabindex]:not([tabindex=\"-1\"])"
452
+ ];
453
+ static SEMANTIC_SELECTORS = [
454
+ "h1",
455
+ "h2",
456
+ "h3",
457
+ "h4",
458
+ "h5",
459
+ "h6",
460
+ "article",
461
+ "section",
462
+ "nav",
463
+ "aside",
464
+ "main",
465
+ "header",
466
+ "footer",
467
+ "form",
468
+ "table",
469
+ "ul",
470
+ "ol",
471
+ "img[alt]",
472
+ "figure",
473
+ "video",
474
+ "audio",
475
+ "[role=\"navigation\"]",
476
+ "[role=\"main\"]",
477
+ "[role=\"complementary\"]",
478
+ "[role=\"contentinfo\"]"
479
+ ];
480
+ /**
481
+ * Check if element is visible
482
+ */
483
+ static isVisible(element, computedStyle) {
484
+ const rect = element.getBoundingClientRect();
485
+ const style = computedStyle || element.ownerDocument?.defaultView?.getComputedStyle(element);
486
+ if (!style) return false;
487
+ return !!(rect.width > 0 && rect.height > 0 && style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0" && element.offsetParent !== null);
488
+ }
489
+ /**
490
+ * Check if element is in viewport
491
+ */
492
+ static isInViewport(element, viewport) {
493
+ const rect = element.getBoundingClientRect();
494
+ const view = viewport || {
495
+ width: element.ownerDocument?.defaultView?.innerWidth || 0,
496
+ height: element.ownerDocument?.defaultView?.innerHeight || 0
497
+ };
498
+ return rect.top < view.height && rect.bottom > 0 && rect.left < view.width && rect.right > 0;
499
+ }
500
+ /**
501
+ * Check if element passes filter criteria
502
+ */
503
+ static passesFilter(element, filter) {
504
+ if (!filter) return true;
505
+ const htmlElement = element;
506
+ if (filter.excludeSelectors?.length) {
507
+ for (const selector of filter.excludeSelectors) if (element.matches(selector)) return false;
508
+ }
509
+ if (filter.includeSelectors?.length) {
510
+ let matches = false;
511
+ for (const selector of filter.includeSelectors) if (element.matches(selector)) {
512
+ matches = true;
513
+ break;
514
+ }
515
+ if (!matches) return false;
516
+ }
517
+ if (filter.tags?.length && !filter.tags.includes(element.tagName.toLowerCase())) return false;
518
+ const textContent = htmlElement.textContent?.toLowerCase() || "";
519
+ if (filter.textContains?.length) {
520
+ let hasText = false;
521
+ for (const text of filter.textContains) if (textContent.includes(text.toLowerCase())) {
522
+ hasText = true;
523
+ break;
524
+ }
525
+ if (!hasText) return false;
526
+ }
527
+ if (filter.textMatches?.length) {
528
+ let matches = false;
529
+ for (const pattern of filter.textMatches) if (pattern.test(textContent)) {
530
+ matches = true;
531
+ break;
532
+ }
533
+ if (!matches) return false;
534
+ }
535
+ if (filter.hasAttributes?.length) {
536
+ for (const attr of filter.hasAttributes) if (!element.hasAttribute(attr)) return false;
537
+ }
538
+ if (filter.attributeValues) for (const [attr, value] of Object.entries(filter.attributeValues)) {
539
+ const attrValue = element.getAttribute(attr);
540
+ if (!attrValue) return false;
541
+ if (typeof value === "string") {
542
+ if (attrValue !== value) return false;
543
+ } else if (value instanceof RegExp) {
544
+ if (!value.test(attrValue)) return false;
545
+ }
546
+ }
547
+ if (filter.withinSelectors?.length) {
548
+ let isWithin = false;
549
+ for (const selector of filter.withinSelectors) if (element.closest(selector)) {
550
+ isWithin = true;
551
+ break;
552
+ }
553
+ if (!isWithin) return false;
554
+ }
555
+ if (filter.interactionTypes?.length) {
556
+ const interaction = DOMTraversal.getInteractionInfo(element);
557
+ let hasInteraction = false;
558
+ for (const type of filter.interactionTypes) if (interaction[type]) {
559
+ hasInteraction = true;
560
+ break;
561
+ }
562
+ if (!hasInteraction) return false;
563
+ }
564
+ if (filter.nearText) {
565
+ const parent = element.parentElement;
566
+ if (!parent || !parent.textContent?.toLowerCase().includes(filter.nearText.toLowerCase())) return false;
567
+ }
568
+ return true;
569
+ }
570
+ /**
571
+ * Extract element information
572
+ */
573
+ static extractElement(element, options, depth = 0) {
574
+ if (options.maxDepth && depth > options.maxDepth) return null;
575
+ if (!options.includeHidden && !DOMTraversal.isVisible(element)) return null;
576
+ if (options.viewportOnly && !DOMTraversal.isInViewport(element)) return null;
577
+ if (!DOMTraversal.passesFilter(element, options.filter)) return null;
578
+ const htmlElement = element;
579
+ const extracted = {
580
+ tag: element.tagName.toLowerCase(),
581
+ text: DOMTraversal.getElementText(element, options),
582
+ selector: SelectorGenerator.generateSelectors(element),
583
+ attributes: DOMTraversal.getRelevantAttributes(element, options),
584
+ context: DOMTraversal.getElementContext(element),
585
+ interaction: DOMTraversal.getInteractionInfo(element)
586
+ };
587
+ if (options.mode === "full" && DOMTraversal.isSemanticContainer(element)) {
588
+ const children = [];
589
+ if (options.includeShadowDOM && htmlElement.shadowRoot) {
590
+ const shadowChildren = DOMTraversal.extractChildren(htmlElement.shadowRoot, options, depth + 1);
591
+ children.push(...shadowChildren);
592
+ }
593
+ const regularChildren = DOMTraversal.extractChildren(element, options, depth + 1);
594
+ children.push(...regularChildren);
595
+ if (children.length > 0) extracted.children = children;
596
+ }
597
+ return extracted;
598
+ }
599
+ /**
600
+ * Extract children elements
601
+ */
602
+ static extractChildren(container, options, depth) {
603
+ const children = [];
604
+ const elements = container.querySelectorAll("*");
605
+ for (const child of Array.from(elements)) {
606
+ if (DOMTraversal.hasExtractedAncestor(child, elements)) continue;
607
+ const extracted = DOMTraversal.extractElement(child, options, depth);
608
+ if (extracted) children.push(extracted);
609
+ }
610
+ return children;
611
+ }
612
+ /**
613
+ * Check if element has an ancestor that was already extracted
614
+ */
615
+ static hasExtractedAncestor(element, extractedElements) {
616
+ let parent = element.parentElement;
617
+ while (parent) {
618
+ if (Array.from(extractedElements).includes(parent)) return true;
619
+ parent = parent.parentElement;
620
+ }
621
+ return false;
622
+ }
623
+ /**
624
+ * Get relevant attributes for an element
625
+ */
626
+ static getRelevantAttributes(element, options) {
627
+ const relevant = [
628
+ "id",
629
+ "class",
630
+ "name",
631
+ "type",
632
+ "value",
633
+ "placeholder",
634
+ "href",
635
+ "src",
636
+ "alt",
637
+ "title",
638
+ "action",
639
+ "method",
640
+ "aria-label",
641
+ "aria-describedby",
642
+ "aria-controls",
643
+ "role",
644
+ "disabled",
645
+ "readonly",
646
+ "required",
647
+ "checked",
648
+ "min",
649
+ "max",
650
+ "pattern",
651
+ "step",
652
+ "autocomplete",
653
+ "data-testid",
654
+ "data-test",
655
+ "data-cy"
656
+ ];
657
+ const attributes = {};
658
+ const attrTruncate = options.attributeTruncateLength ?? 100;
659
+ const dataAttrTruncate = options.dataAttributeTruncateLength ?? 50;
660
+ for (const attr of relevant) {
661
+ const value = element.getAttribute(attr);
662
+ if (value) attributes[attr] = value.length > attrTruncate ? `${value.substring(0, attrTruncate)}...` : value;
663
+ }
664
+ for (const attr of element.attributes) if (attr.name.startsWith("data-") && !relevant.includes(attr.name)) attributes[attr.name] = attr.value.length > dataAttrTruncate ? `${attr.value.substring(0, dataAttrTruncate)}...` : attr.value;
665
+ return attributes;
666
+ }
667
+ /**
668
+ * Get element context information
669
+ */
670
+ static getElementContext(element) {
671
+ const context = { parentChain: SelectorGenerator.getContextPath(element) };
672
+ const form = element.closest("form");
673
+ if (form) context.nearestForm = SelectorGenerator.generateSelectors(form).css;
674
+ const section = element.closest("section, [role=\"region\"]");
675
+ if (section) context.nearestSection = SelectorGenerator.generateSelectors(section).css;
676
+ const main = element.closest("main, [role=\"main\"]");
677
+ if (main) context.nearestMain = SelectorGenerator.generateSelectors(main).css;
678
+ const nav = element.closest("nav, [role=\"navigation\"]");
679
+ if (nav) context.nearestNav = SelectorGenerator.generateSelectors(nav).css;
680
+ return context;
681
+ }
682
+ /**
683
+ * Get interaction information for an element (compact format)
684
+ */
685
+ static getInteractionInfo(element) {
686
+ const htmlElement = element;
687
+ const interaction = {};
688
+ if (!!(htmlElement.onclick || element.getAttribute("onclick") || element.matches("button, a[href], [role=\"button\"], [tabindex]:not([tabindex=\"-1\"])"))) interaction.click = true;
689
+ if (!!(htmlElement.onchange || element.getAttribute("onchange") || element.matches("input, select, textarea"))) interaction.change = true;
690
+ if (!!(htmlElement.onsubmit || element.getAttribute("onsubmit") || element.matches("form"))) interaction.submit = true;
691
+ if (element.matches("a[href], button[type=\"submit\"]")) interaction.nav = true;
692
+ if (htmlElement.hasAttribute("disabled") || htmlElement.getAttribute("aria-disabled") === "true") interaction.disabled = true;
693
+ if (!DOMTraversal.isVisible(element)) interaction.hidden = true;
694
+ const ariaRole = element.getAttribute("role");
695
+ if (ariaRole) interaction.role = ariaRole;
696
+ if (element.matches("input, textarea, select, button")) {
697
+ const form = element.form || element.closest("form");
698
+ if (form) interaction.form = SelectorGenerator.generateSelectors(form).css;
699
+ }
700
+ return interaction;
701
+ }
702
+ /**
703
+ * Get text content of an element (limited length)
704
+ */
705
+ static getElementText(element, options) {
706
+ if (element.matches("input, textarea")) {
707
+ const input = element;
708
+ return input.value || input.placeholder || "";
709
+ }
710
+ if (element.matches("img")) return element.alt || "";
711
+ const text = element.textContent?.trim() || "";
712
+ const maxLength = options?.textTruncateLength;
713
+ if (maxLength && text.length > maxLength) return `${text.substring(0, maxLength)}...`;
714
+ return text;
715
+ }
716
+ /**
717
+ * Check if element is a semantic container
718
+ */
719
+ static isSemanticContainer(element) {
720
+ return element.matches("article, section, nav, aside, main, header, footer, form, table, ul, ol, dl, figure, details, dialog, [role=\"region\"], [role=\"navigation\"], [role=\"main\"], [role=\"complementary\"]");
721
+ }
722
+ /**
723
+ * Get interactive elements
724
+ */
725
+ static getInteractiveElements(container, options) {
726
+ const elements = [];
727
+ const selector = DOMTraversal.INTERACTIVE_SELECTORS.join(", ");
728
+ const found = container.querySelectorAll(selector);
729
+ for (const element of Array.from(found)) {
730
+ const extracted = DOMTraversal.extractElement(element, options);
731
+ if (extracted) elements.push(extracted);
732
+ }
733
+ if (options.customSelectors) for (const customSelector of options.customSelectors) try {
734
+ const customFound = container.querySelectorAll(customSelector);
735
+ for (const element of Array.from(customFound)) {
736
+ const extracted = DOMTraversal.extractElement(element, options);
737
+ if (extracted) elements.push(extracted);
738
+ }
739
+ } catch (_e) {
740
+ console.warn(`Invalid custom selector: ${customSelector}`);
741
+ }
742
+ return elements;
743
+ }
744
+ /**
745
+ * Get semantic elements (for full mode)
746
+ */
747
+ static getSemanticElements(container, options) {
748
+ const elements = [];
749
+ const selector = DOMTraversal.SEMANTIC_SELECTORS.join(", ");
750
+ const found = container.querySelectorAll(selector);
751
+ for (const element of Array.from(found)) {
752
+ const extracted = DOMTraversal.extractElement(element, options);
753
+ if (extracted) elements.push(extracted);
754
+ }
755
+ return elements;
756
+ }
757
+ };
758
+ }));
759
+ //#endregion
760
+ //#region src/markdown-formatter.ts
761
+ function truncate(text, len) {
762
+ const t = (text ?? "").trim();
763
+ if (!len || t.length <= len) return t;
764
+ const keywords = [
765
+ "login",
766
+ "log in",
767
+ "sign in",
768
+ "sign up",
769
+ "submit",
770
+ "search",
771
+ "filter",
772
+ "add to cart",
773
+ "next",
774
+ "continue"
775
+ ];
776
+ const lower = t.toLowerCase();
777
+ const hit = keywords.map((k) => ({
778
+ k,
779
+ i: lower.indexOf(k)
780
+ })).find((x) => x.i > -1);
781
+ const head = Math.max(0, Math.floor(len * .66));
782
+ if (hit && hit.i > head) {
783
+ const tailWindow = Math.max(12, len - head - 5);
784
+ const start = Math.max(0, hit.i - Math.floor(tailWindow / 2));
785
+ const end = Math.min(t.length, start + tailWindow);
786
+ return `${t.slice(0, head).trimEnd()} … ${t.slice(start, end).trim()}…`;
787
+ }
788
+ const slice = t.slice(0, len);
789
+ const lastSpace = slice.lastIndexOf(" ");
790
+ return `${lastSpace > 32 ? slice.slice(0, lastSpace) : slice}…`;
791
+ }
792
+ function bestSelector(el) {
793
+ return el.selector?.css || "";
794
+ }
795
+ function hashId(input) {
796
+ let h = 5381;
797
+ for (let i = 0; i < input.length; i++) h = h * 33 ^ input.charCodeAt(i);
798
+ return `sec-${(h >>> 0).toString(36)}`;
799
+ }
800
+ function iconForRegion(key) {
801
+ switch (key) {
802
+ case "header": return "🧭";
803
+ case "navigation": return "📑";
804
+ case "main": return "📄";
805
+ case "sections": return "🗂️";
806
+ case "sidebar": return "📚";
807
+ case "footer": return "🔻";
808
+ case "modals": return "💬";
809
+ default: return "🔹";
810
+ }
811
+ }
812
+ function elementLine(el, opts) {
813
+ const txt = truncate(el.text || el.attributes?.ariaLabel, opts?.maxTextLength ?? 80);
814
+ const sel = bestSelector(el);
815
+ const tag = el.tag.toLowerCase();
816
+ const action = el.interaction?.submit ? "submit" : el.interaction?.click ? "click" : el.interaction?.change ? "change" : void 0;
817
+ const actionText = action ? ` (${action})` : "";
818
+ return `- ${tag.toUpperCase()}: ${txt || "(no text)"} → \`${sel}\`${actionText}`;
819
+ }
820
+ function selectorQualitySummary(inter) {
821
+ const all = [];
822
+ all.push(...inter.buttons.map((e) => e.selector?.css || ""));
823
+ all.push(...inter.links.map((e) => e.selector?.css || ""));
824
+ all.push(...inter.inputs.map((e) => e.selector?.css || ""));
825
+ all.push(...inter.clickable.map((e) => e.selector?.css || ""));
826
+ const total = all.length || 1;
827
+ const idCount = all.filter((s) => s.startsWith("#")).length;
828
+ const testIdCount = all.filter((s) => /\[data-testid=/.test(s)).length;
829
+ const nthCount = all.filter((s) => /:nth-child\(/.test(s)).length;
830
+ const stable = idCount + testIdCount;
831
+ return `Selector quality: ${Math.round(stable / total * 100)}% stable (ID/data-testid), ${Math.round(nthCount / total * 100)}% structural (:nth-child)`;
832
+ }
833
+ function renderInteractive(inter, opts) {
834
+ const parts = [];
835
+ const limit = (arr) => typeof opts?.maxElements === "number" ? arr.slice(0, opts.maxElements) : arr;
836
+ if (inter.buttons.length) {
837
+ parts.push("Buttons:");
838
+ for (const el of limit(inter.buttons)) parts.push(elementLine(el, opts));
839
+ }
840
+ if (inter.links.length) {
841
+ parts.push("Links:");
842
+ for (const el of limit(inter.links)) parts.push(elementLine(el, opts));
843
+ }
844
+ if (inter.inputs.length) {
845
+ parts.push("Inputs:");
846
+ for (const el of limit(inter.inputs)) parts.push(elementLine(el, opts));
847
+ }
848
+ if (inter.clickable.length) {
849
+ parts.push("Other Clickable:");
850
+ for (const el of limit(inter.clickable)) parts.push(elementLine(el, opts));
851
+ }
852
+ if (inter.forms.length) {
853
+ parts.push("Forms:");
854
+ for (const f of limit(inter.forms)) parts.push(`- FORM: action=${f.action ?? "-"} method=${f.method ?? "-"} → \`${f.selector}\``);
855
+ }
856
+ return parts.join("\n");
857
+ }
858
+ function renderRegionInfo(region) {
859
+ const icon = iconForRegion("region");
860
+ const id = hashId(`${region.selector}|${region.label ?? ""}|${region.role ?? ""}`);
861
+ const label = region.label ? ` ${region.label}` : "";
862
+ const stats = [];
863
+ if (region.buttonCount) stats.push(`${region.buttonCount} buttons`);
864
+ if (region.linkCount) stats.push(`${region.linkCount} links`);
865
+ if (region.inputCount) stats.push(`${region.inputCount} inputs`);
866
+ if (region.textPreview) stats.push(`“${truncate(region.textPreview, 80)}”`);
867
+ const statsLine = stats.length ? ` — ${stats.join(", ")}` : "";
868
+ return `${icon} ${label} → \`${region.selector}\` [${id}]${statsLine}`;
869
+ }
870
+ function wrapXml(body, meta, type = "section") {
871
+ return `<page ${[meta?.title ? `title="${escapeXml(meta?.title)}"` : null, meta?.url ? `url="${escapeXml(meta?.url)}"` : null].filter(Boolean).join(" ")}>\n <${type}><![CDATA[\n${body}\n]]></${type}>\n</page>`;
872
+ }
873
+ function escapeXml(s) {
874
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
875
+ }
876
+ function capitalize(s) {
877
+ return s.charAt(0).toUpperCase() + s.slice(1);
878
+ }
879
+ var MarkdownFormatter;
880
+ var init_markdown_formatter = __esmMin((() => {
881
+ MarkdownFormatter = class {
882
+ static structure(overview, _opts = {}, meta) {
883
+ const lines = [];
884
+ lines.push("# Page Outline");
885
+ if (meta?.title || meta?.url) {
886
+ lines.push(`Title: ${meta?.title ?? ""}`.trim());
887
+ lines.push(`URL: ${meta?.url ?? ""}`.trim());
888
+ }
889
+ lines.push("");
890
+ const regions = overview.regions;
891
+ const entries = [
892
+ ["header", regions.header],
893
+ ["navigation", regions.navigation],
894
+ ["main", regions.main],
895
+ ["sections", regions.sections],
896
+ ["sidebar", regions.sidebar],
897
+ ["footer", regions.footer],
898
+ ["modals", regions.modals]
899
+ ];
900
+ for (const [key, value] of entries) {
901
+ if (!value) continue;
902
+ const icon = iconForRegion(key);
903
+ if (Array.isArray(value)) {
904
+ if (!value.length) continue;
905
+ lines.push(`## ${icon} ${capitalize(key)}`);
906
+ for (const region of value) lines.push(renderRegionInfo(region));
907
+ } else {
908
+ lines.push(`## ${icon} ${capitalize(key)}`);
909
+ lines.push(renderRegionInfo(value));
910
+ }
911
+ lines.push("");
912
+ }
913
+ if (overview.suggestions?.length) {
914
+ lines.push("## Suggestions");
915
+ for (const s of overview.suggestions) lines.push(`- ${s}`);
916
+ lines.push("");
917
+ }
918
+ lines.push("Next: choose a region (by selector or [sectionId]) and call dom_extract_region for actionable details.");
919
+ return wrapXml(lines.join("\n"), meta, "outline");
920
+ }
921
+ static region(result, opts = {}, meta) {
922
+ const lines = [];
923
+ lines.push("# Region Details");
924
+ if (meta?.title || meta?.url) {
925
+ lines.push(`Title: ${meta?.title ?? ""}`.trim());
926
+ lines.push(`URL: ${meta?.url ?? ""}`.trim());
927
+ }
928
+ lines.push("");
929
+ const inter = result.interactive;
930
+ if (result.page) {
931
+ const ps = [
932
+ result.page.hasErrors ? "errors: yes" : "errors: no",
933
+ result.page.isLoading ? "loading: yes" : "loading: no",
934
+ result.page.hasModals ? "modals: yes" : "modals: no"
935
+ ];
936
+ lines.push(`Page state: ${ps.join(", ")}`);
937
+ }
938
+ const summary = [];
939
+ const count = (arr) => arr ? arr.length : 0;
940
+ summary.push(`${count(inter.buttons)} buttons`);
941
+ summary.push(`${count(inter.links)} links`);
942
+ summary.push(`${count(inter.inputs)} inputs`);
943
+ if (inter.forms?.length) summary.push(`${count(inter.forms)} forms`);
944
+ lines.push(`Summary: ${summary.join(", ")}`);
945
+ lines.push(selectorQualitySummary(inter));
946
+ lines.push("");
947
+ lines.push(renderInteractive(inter, opts));
948
+ lines.push("");
949
+ lines.push("Next: write a script using the most stable selectors above. If selectors look unstable, rerun dom_extract_region with higher detail or call dom_extract_content for text context.");
950
+ return wrapXml(lines.join("\n"), meta, "section");
951
+ }
952
+ static content(content, opts = {}, meta) {
953
+ const lines = [];
954
+ lines.push("# Content");
955
+ lines.push(`Selector: \`${content.selector}\``);
956
+ lines.push("");
957
+ if (content.text.headings?.length) {
958
+ lines.push("Headings:");
959
+ for (const h of content.text.headings) lines.push(`- H${h.level}: ${truncate(h.text, opts.maxTextLength ?? 120)}`);
960
+ lines.push("");
961
+ }
962
+ if (content.text.paragraphs?.length) {
963
+ const limit = typeof opts.maxElements === "number" ? opts.maxElements : content.text.paragraphs.length;
964
+ lines.push("Paragraphs:");
965
+ for (const p of content.text.paragraphs.slice(0, limit)) lines.push(`- ${truncate(p, opts.maxTextLength ?? 200)}`);
966
+ lines.push("");
967
+ }
968
+ if (content.text.lists?.length) {
969
+ lines.push("Lists:");
970
+ for (const list of content.text.lists) {
971
+ lines.push(`- ${list.type.toUpperCase()}:`);
972
+ const limit = typeof opts.maxElements === "number" ? opts.maxElements : list.items.length;
973
+ for (const item of list.items.slice(0, limit)) lines.push(` - ${truncate(item, opts.maxTextLength ?? 120)}`);
974
+ }
975
+ lines.push("");
976
+ }
977
+ if (content.tables?.length) {
978
+ lines.push("Tables:");
979
+ for (const t of content.tables) {
980
+ lines.push(`- Headers: ${t.headers.join(" | ")}`);
981
+ const limit = typeof opts.maxElements === "number" ? opts.maxElements : t.rows.length;
982
+ for (const row of t.rows.slice(0, limit)) lines.push(` - ${row.join(" | ")}`);
983
+ }
984
+ lines.push("");
985
+ }
986
+ if (content.media?.length) {
987
+ lines.push("Media:");
988
+ const limit = typeof opts.maxElements === "number" ? opts.maxElements : content.media.length;
989
+ for (const m of content.media.slice(0, limit)) lines.push(`- ${m.type.toUpperCase()}: ${m.alt ?? ""} ${m.src ? `→ ${m.src}` : ""}`.trim());
990
+ lines.push("");
991
+ }
992
+ lines.push("Next: if text is insufficient for targeting, call dom_extract_region for interactive selectors.");
993
+ return wrapXml(lines.join("\n"), meta, "content");
994
+ }
995
+ };
996
+ }));
997
+ //#endregion
998
+ //#region src/progressive.ts
999
+ function resolveSmartDomReader() {
1000
+ if (typeof window !== "undefined") {
1001
+ const globalWindow = window;
1002
+ const direct = globalWindow.SmartDOMReader;
1003
+ if (typeof direct === "function") return direct;
1004
+ const namespace = globalWindow.SmartDOMReaderNamespace;
1005
+ if (namespace && typeof namespace.SmartDOMReader === "function") return namespace.SmartDOMReader;
1006
+ }
1007
+ try {
1008
+ if (typeof __require === "function") {
1009
+ const moduleExports = (init_src(), __toCommonJS(src_exports));
1010
+ if (moduleExports && typeof moduleExports.SmartDOMReader === "function") return moduleExports.SmartDOMReader;
1011
+ if (moduleExports && typeof moduleExports.default === "function") return moduleExports.default;
1012
+ }
1013
+ } catch {}
1014
+ }
1015
+ var ProgressiveExtractor;
1016
+ var init_progressive = __esmMin((() => {
1017
+ init_content_detection();
1018
+ init_selectors();
1019
+ init_traversal();
1020
+ ProgressiveExtractor = class ProgressiveExtractor {
1021
+ /**
1022
+ * Step 1: Extract high-level structural overview
1023
+ * This provides a "map" of the page for the AI to understand structure
1024
+ */
1025
+ static extractStructure(root) {
1026
+ const regions = {};
1027
+ const header = root.querySelector("header, [role=\"banner\"], .header, #header");
1028
+ if (header) regions.header = ProgressiveExtractor.analyzeRegion(header);
1029
+ const navs = root.querySelectorAll("nav, [role=\"navigation\"], .nav, .navigation");
1030
+ if (navs.length > 0) regions.navigation = Array.from(navs).map((nav) => ProgressiveExtractor.analyzeRegion(nav));
1031
+ if (root instanceof Document) {
1032
+ const main = ContentDetection.findMainContent(root);
1033
+ if (main) {
1034
+ regions.main = ProgressiveExtractor.analyzeRegion(main);
1035
+ const sections = main.querySelectorAll("section, article, [role=\"region\"]");
1036
+ if (sections.length > 0) regions.sections = Array.from(sections).filter((section) => !section.closest("nav, header, footer")).map((section) => ProgressiveExtractor.analyzeRegion(section));
1037
+ }
1038
+ } else {
1039
+ regions.main = ProgressiveExtractor.analyzeRegion(root);
1040
+ const sections = root.querySelectorAll("section, article, [role=\"region\"]");
1041
+ if (sections.length > 0) regions.sections = Array.from(sections).filter((section) => !section.closest("nav, header, footer")).map((section) => ProgressiveExtractor.analyzeRegion(section));
1042
+ }
1043
+ const sidebars = root.querySelectorAll("aside, [role=\"complementary\"], .sidebar, #sidebar");
1044
+ if (sidebars.length > 0) regions.sidebar = Array.from(sidebars).map((sidebar) => ProgressiveExtractor.analyzeRegion(sidebar));
1045
+ const footer = root.querySelector("footer, [role=\"contentinfo\"], .footer, #footer");
1046
+ if (footer) regions.footer = ProgressiveExtractor.analyzeRegion(footer);
1047
+ const modals = root.querySelectorAll("[role=\"dialog\"], .modal, .popup, .overlay");
1048
+ const visibleModals = Array.from(modals).filter((modal) => DOMTraversal.isVisible(modal));
1049
+ if (visibleModals.length > 0) regions.modals = visibleModals.map((modal) => ProgressiveExtractor.analyzeRegion(modal));
1050
+ const forms = ProgressiveExtractor.extractFormOverview(root);
1051
+ const summary = ProgressiveExtractor.calculateSummary(root, regions, forms);
1052
+ return {
1053
+ regions,
1054
+ forms,
1055
+ summary,
1056
+ suggestions: ProgressiveExtractor.generateSuggestions(regions, summary)
1057
+ };
1058
+ }
1059
+ /**
1060
+ * Step 2: Extract detailed information from a specific region
1061
+ */
1062
+ static extractRegion(selector, doc, options = {}, smartDomReaderCtor) {
1063
+ const element = doc.querySelector(selector);
1064
+ if (!element) return null;
1065
+ const SmartDOMReaderCtor = smartDomReaderCtor ?? resolveSmartDomReader();
1066
+ if (!SmartDOMReaderCtor) throw new Error("SmartDOMReader is unavailable. Ensure the Smart DOM Reader module is loaded before calling extractRegion.");
1067
+ return new SmartDOMReaderCtor(options).extract(element, options);
1068
+ }
1069
+ /**
1070
+ * Step 3: Extract readable content from a region
1071
+ */
1072
+ static extractContent(selector, doc, options = {}) {
1073
+ const element = doc.querySelector(selector);
1074
+ if (!element) return null;
1075
+ const result = {
1076
+ selector,
1077
+ text: {},
1078
+ metadata: {
1079
+ wordCount: 0,
1080
+ hasInteractive: false
1081
+ }
1082
+ };
1083
+ if (options.includeHeadings !== false) {
1084
+ const headings = element.querySelectorAll("h1, h2, h3, h4, h5, h6");
1085
+ result.text.headings = Array.from(headings).map((h) => ({
1086
+ level: Number.parseInt(h.tagName[1], 10),
1087
+ text: ProgressiveExtractor.getTextContent(h, options.maxTextLength)
1088
+ }));
1089
+ }
1090
+ const paragraphs = element.querySelectorAll("p");
1091
+ if (paragraphs.length > 0) result.text.paragraphs = Array.from(paragraphs).map((p) => ProgressiveExtractor.getTextContent(p, options.maxTextLength)).filter((text) => text.length > 0);
1092
+ if (options.includeLists !== false) {
1093
+ const lists = element.querySelectorAll("ul, ol");
1094
+ result.text.lists = Array.from(lists).map((list) => ({
1095
+ type: list.tagName.toLowerCase(),
1096
+ items: Array.from(list.querySelectorAll("li")).map((li) => ProgressiveExtractor.getTextContent(li, options.maxTextLength))
1097
+ }));
1098
+ }
1099
+ if (options.includeTables !== false) {
1100
+ const tables = element.querySelectorAll("table");
1101
+ result.tables = Array.from(tables).map((table) => {
1102
+ return {
1103
+ headers: Array.from(table.querySelectorAll("th")).map((th) => ProgressiveExtractor.getTextContent(th)),
1104
+ rows: Array.from(table.querySelectorAll("tr")).filter((tr) => tr.querySelector("td")).map((tr) => Array.from(tr.querySelectorAll("td")).map((td) => ProgressiveExtractor.getTextContent(td)))
1105
+ };
1106
+ });
1107
+ }
1108
+ if (options.includeMedia !== false) {
1109
+ const images = element.querySelectorAll("img");
1110
+ const videos = element.querySelectorAll("video");
1111
+ const audios = element.querySelectorAll("audio");
1112
+ result.media = [
1113
+ ...Array.from(images).map((img) => {
1114
+ const item = { type: "img" };
1115
+ const alt = img.getAttribute("alt");
1116
+ const src = img.getAttribute("src");
1117
+ if (alt) item.alt = alt;
1118
+ if (src) item.src = src;
1119
+ return item;
1120
+ }),
1121
+ ...Array.from(videos).map((video) => {
1122
+ const item = { type: "video" };
1123
+ const src = video.getAttribute("src");
1124
+ if (src) item.src = src;
1125
+ return item;
1126
+ }),
1127
+ ...Array.from(audios).map((audio) => {
1128
+ const item = { type: "audio" };
1129
+ const src = audio.getAttribute("src");
1130
+ if (src) item.src = src;
1131
+ return item;
1132
+ })
1133
+ ];
1134
+ }
1135
+ const allText = element.textContent || "";
1136
+ result.metadata.wordCount = allText.trim().split(/\s+/).length;
1137
+ result.metadata.hasInteractive = element.querySelectorAll("button, a, input, textarea, select").length > 0;
1138
+ return result;
1139
+ }
1140
+ /**
1141
+ * Analyze a region and extract summary information
1142
+ */
1143
+ static analyzeRegion(element) {
1144
+ const selector = SelectorGenerator.generateSelectors(element).css;
1145
+ const buttons = element.querySelectorAll("button, [role=\"button\"]");
1146
+ const links = element.querySelectorAll("a[href]");
1147
+ const inputs = element.querySelectorAll("input, textarea, select");
1148
+ const forms = element.querySelectorAll("form");
1149
+ const lists = element.querySelectorAll("ul, ol");
1150
+ const tables = element.querySelectorAll("table");
1151
+ const media = element.querySelectorAll("img, video, audio");
1152
+ const interactiveCount = buttons.length + links.length + inputs.length;
1153
+ let label;
1154
+ const ariaLabel = element.getAttribute("aria-label");
1155
+ if (ariaLabel) label = ariaLabel;
1156
+ else if (element.getAttribute("aria-labelledby")) {
1157
+ const labelId = element.getAttribute("aria-labelledby");
1158
+ if (labelId) {
1159
+ const labelElement = element.ownerDocument?.getElementById(labelId);
1160
+ if (labelElement) label = labelElement.textContent?.trim();
1161
+ }
1162
+ } else {
1163
+ const heading = element.querySelector("h1, h2, h3");
1164
+ if (heading) label = heading.textContent?.trim();
1165
+ }
1166
+ const textContent = element.textContent?.trim() || "";
1167
+ const textPreview = textContent.length > 50 ? `${textContent.substring(0, 50)}...` : textContent;
1168
+ const regionInfo = {
1169
+ selector,
1170
+ interactiveCount,
1171
+ hasForm: forms.length > 0,
1172
+ hasList: lists.length > 0,
1173
+ hasTable: tables.length > 0,
1174
+ hasMedia: media.length > 0
1175
+ };
1176
+ if (label) regionInfo.label = label;
1177
+ const role = element.getAttribute("role");
1178
+ if (role) regionInfo.role = role;
1179
+ if (buttons.length > 0) regionInfo.buttonCount = buttons.length;
1180
+ if (links.length > 0) regionInfo.linkCount = links.length;
1181
+ if (inputs.length > 0) regionInfo.inputCount = inputs.length;
1182
+ if (textPreview.length > 0) regionInfo.textPreview = textPreview;
1183
+ return regionInfo;
1184
+ }
1185
+ /**
1186
+ * Extract overview of forms on the page
1187
+ */
1188
+ static extractFormOverview(root) {
1189
+ const forms = root.querySelectorAll("form");
1190
+ return Array.from(forms).map((form) => {
1191
+ const inputs = form.querySelectorAll("input, textarea, select");
1192
+ const selector = SelectorGenerator.generateSelectors(form).css;
1193
+ let location = "unknown";
1194
+ if (form.closest("header, [role=\"banner\"]")) location = "header";
1195
+ else if (form.closest("nav, [role=\"navigation\"]")) location = "navigation";
1196
+ else if (form.closest("main, [role=\"main\"]")) location = "main";
1197
+ else if (form.closest("aside, [role=\"complementary\"]")) location = "sidebar";
1198
+ else if (form.closest("footer, [role=\"contentinfo\"]")) location = "footer";
1199
+ let purpose;
1200
+ const formId = form.getAttribute("id")?.toLowerCase();
1201
+ const formClass = form.getAttribute("class")?.toLowerCase();
1202
+ const formAction = form.getAttribute("action")?.toLowerCase();
1203
+ const hasEmail = form.querySelector("input[type=\"email\"]");
1204
+ const hasPassword = form.querySelector("input[type=\"password\"]");
1205
+ if (form.querySelector("input[type=\"search\"]") || formId?.includes("search") || formClass?.includes("search")) purpose = "search";
1206
+ else if (hasPassword && hasEmail) purpose = "login";
1207
+ else if (hasPassword) purpose = "authentication";
1208
+ else if (formId?.includes("contact") || formClass?.includes("contact")) purpose = "contact";
1209
+ else if (formId?.includes("subscribe") || formClass?.includes("subscribe")) purpose = "subscription";
1210
+ else if (formAction?.includes("checkout") || formClass?.includes("checkout")) purpose = "checkout";
1211
+ const formOverview = {
1212
+ selector,
1213
+ location,
1214
+ inputCount: inputs.length
1215
+ };
1216
+ if (purpose) formOverview.purpose = purpose;
1217
+ return formOverview;
1218
+ });
1219
+ }
1220
+ /**
1221
+ * Calculate summary statistics
1222
+ */
1223
+ static calculateSummary(root, regions, forms) {
1224
+ const allInteractive = root.querySelectorAll("button, a[href], input, textarea, select");
1225
+ const allSections = root.querySelectorAll("section, article, [role=\"region\"]");
1226
+ const hasModals = (regions.modals?.length || 0) > 0;
1227
+ const hasErrors = [
1228
+ ".error",
1229
+ ".alert-danger",
1230
+ "[role=\"alert\"]"
1231
+ ].some((sel) => {
1232
+ const element = root.querySelector(sel);
1233
+ return element ? DOMTraversal.isVisible(element) : false;
1234
+ });
1235
+ const isLoading = [
1236
+ ".loading",
1237
+ ".spinner",
1238
+ "[aria-busy=\"true\"]"
1239
+ ].some((sel) => {
1240
+ const element = root.querySelector(sel);
1241
+ return element ? DOMTraversal.isVisible(element) : false;
1242
+ });
1243
+ const summary = {
1244
+ totalInteractive: allInteractive.length,
1245
+ totalForms: forms.length,
1246
+ totalSections: allSections.length,
1247
+ hasModals,
1248
+ hasErrors,
1249
+ isLoading
1250
+ };
1251
+ const mainContentSelector = regions.main?.selector;
1252
+ if (mainContentSelector) summary.mainContentSelector = mainContentSelector;
1253
+ return summary;
1254
+ }
1255
+ /**
1256
+ * Generate AI-friendly suggestions
1257
+ */
1258
+ static generateSuggestions(regions, summary) {
1259
+ const suggestions = [];
1260
+ if (summary.hasErrors) suggestions.push("Page has error indicators - check error messages before interacting");
1261
+ if (summary.isLoading) suggestions.push("Page appears to be loading - wait or check loading state");
1262
+ if (summary.hasModals) suggestions.push("Modal/dialog is open - may need to interact with or close it first");
1263
+ if (regions.main && regions.main.interactiveCount > 10) suggestions.push(`Main content has ${regions.main.interactiveCount} interactive elements - consider filtering`);
1264
+ if (summary.totalForms > 0) suggestions.push(`Found ${summary.totalForms} form(s) on the page`);
1265
+ if (!regions.main) suggestions.push("No clear main content area detected - may need to explore regions");
1266
+ return suggestions;
1267
+ }
1268
+ /**
1269
+ * Get text content with optional truncation
1270
+ */
1271
+ static getTextContent(element, maxLength) {
1272
+ const text = element.textContent?.trim() || "";
1273
+ if (maxLength && text.length > maxLength) return `${text.substring(0, maxLength)}...`;
1274
+ return text;
1275
+ }
1276
+ };
1277
+ }));
1278
+ //#endregion
1279
+ //#region src/types.ts
1280
+ var init_types = __esmMin((() => {}));
1281
+ //#endregion
1282
+ //#region src/index.ts
1283
+ var src_exports = /* @__PURE__ */ __exportAll({
1284
+ ContentDetection: () => ContentDetection,
1285
+ MarkdownFormatter: () => MarkdownFormatter,
1286
+ ProgressiveExtractor: () => ProgressiveExtractor,
1287
+ SelectorGenerator: () => SelectorGenerator,
1288
+ SmartDOMReader: () => SmartDOMReader,
1289
+ default: () => SmartDOMReader
1290
+ });
1291
+ var SmartDOMReader;
1292
+ var init_src = __esmMin((() => {
1293
+ init_content_detection();
1294
+ init_selectors();
1295
+ init_traversal();
1296
+ init_markdown_formatter();
1297
+ init_progressive();
1298
+ init_types();
1299
+ SmartDOMReader = class SmartDOMReader {
1300
+ options;
1301
+ constructor(options = {}) {
1302
+ this.options = {
1303
+ mode: options.mode || "interactive",
1304
+ maxDepth: options.maxDepth || 5,
1305
+ includeHidden: options.includeHidden || false,
1306
+ includeShadowDOM: options.includeShadowDOM ?? true,
1307
+ includeIframes: options.includeIframes || false,
1308
+ viewportOnly: options.viewportOnly || false,
1309
+ mainContentOnly: options.mainContentOnly || false,
1310
+ customSelectors: options.customSelectors || [],
1311
+ ...options.attributeTruncateLength !== void 0 && { attributeTruncateLength: options.attributeTruncateLength },
1312
+ ...options.dataAttributeTruncateLength !== void 0 && { dataAttributeTruncateLength: options.dataAttributeTruncateLength },
1313
+ ...options.textTruncateLength !== void 0 && { textTruncateLength: options.textTruncateLength },
1314
+ ...options.filter !== void 0 && { filter: options.filter }
1315
+ };
1316
+ }
1317
+ /**
1318
+ * Main extraction method - extracts all data in one pass
1319
+ * @param rootElement The document or element to extract from
1320
+ * @param runtimeOptions Options to override constructor options
1321
+ */
1322
+ extract(rootElement = document, runtimeOptions) {
1323
+ const startTime = Date.now();
1324
+ const doc = rootElement instanceof Document ? rootElement : rootElement.ownerDocument;
1325
+ const options = {
1326
+ ...this.options,
1327
+ ...runtimeOptions
1328
+ };
1329
+ let container = rootElement instanceof Document ? doc : rootElement;
1330
+ if (options.mainContentOnly && rootElement instanceof Document) container = ContentDetection.findMainContent(doc);
1331
+ const pageState = this.extractPageState(doc);
1332
+ const landmarks = this.extractLandmarks(doc);
1333
+ const interactive = this.extractInteractiveElements(container, options);
1334
+ const result = {
1335
+ mode: options.mode,
1336
+ timestamp: startTime,
1337
+ page: pageState,
1338
+ landmarks,
1339
+ interactive
1340
+ };
1341
+ if (options.mode === "full") {
1342
+ const semantic = this.extractSemanticElements(container, options);
1343
+ const metadata = this.extractMetadata(doc, container, options);
1344
+ return {
1345
+ ...result,
1346
+ semantic,
1347
+ metadata
1348
+ };
1349
+ }
1350
+ return result;
1351
+ }
1352
+ /**
1353
+ * Extract page state information
1354
+ */
1355
+ extractPageState(doc) {
1356
+ const hasFocus = this.getFocusedElement(doc);
1357
+ return {
1358
+ url: doc.location?.href || "",
1359
+ title: doc.title || "",
1360
+ hasErrors: this.detectErrors(doc),
1361
+ isLoading: this.detectLoading(doc),
1362
+ hasModals: this.detectModals(doc),
1363
+ ...hasFocus !== void 0 && { hasFocus }
1364
+ };
1365
+ }
1366
+ /**
1367
+ * Extract page landmarks
1368
+ */
1369
+ extractLandmarks(doc) {
1370
+ const detected = ContentDetection.detectLandmarks(doc);
1371
+ return {
1372
+ navigation: this.elementsToSelectors(detected.navigation || []),
1373
+ main: this.elementsToSelectors(detected.main || []),
1374
+ forms: this.elementsToSelectors(detected.form || []),
1375
+ headers: this.elementsToSelectors(detected.banner || []),
1376
+ footers: this.elementsToSelectors(detected.contentinfo || []),
1377
+ articles: this.elementsToSelectors(detected.region || []),
1378
+ sections: this.elementsToSelectors(detected.region || [])
1379
+ };
1380
+ }
1381
+ /**
1382
+ * Convert elements to selector strings
1383
+ */
1384
+ elementsToSelectors(elements) {
1385
+ return elements.map((el) => SelectorGenerator.generateSelectors(el).css);
1386
+ }
1387
+ /**
1388
+ * Extract interactive elements
1389
+ */
1390
+ extractInteractiveElements(container, options) {
1391
+ const buttons = [];
1392
+ const links = [];
1393
+ const inputs = [];
1394
+ const clickable = [];
1395
+ container.querySelectorAll("button, [role=\"button\"], input[type=\"button\"], input[type=\"submit\"]").forEach((el) => {
1396
+ if (this.shouldIncludeElement(el, options)) {
1397
+ const extracted = DOMTraversal.extractElement(el, options);
1398
+ if (extracted) buttons.push(extracted);
1399
+ }
1400
+ });
1401
+ container.querySelectorAll("a[href]").forEach((el) => {
1402
+ if (this.shouldIncludeElement(el, options)) {
1403
+ const extracted = DOMTraversal.extractElement(el, options);
1404
+ if (extracted) links.push(extracted);
1405
+ }
1406
+ });
1407
+ container.querySelectorAll("input:not([type=\"button\"]):not([type=\"submit\"]), textarea, select").forEach((el) => {
1408
+ if (this.shouldIncludeElement(el, options)) {
1409
+ const extracted = DOMTraversal.extractElement(el, options);
1410
+ if (extracted) inputs.push(extracted);
1411
+ }
1412
+ });
1413
+ if (options.customSelectors) options.customSelectors.forEach((selector) => {
1414
+ container.querySelectorAll(selector).forEach((el) => {
1415
+ if (this.shouldIncludeElement(el, options)) {
1416
+ const extracted = DOMTraversal.extractElement(el, options);
1417
+ if (extracted) clickable.push(extracted);
1418
+ }
1419
+ });
1420
+ });
1421
+ return {
1422
+ buttons,
1423
+ links,
1424
+ inputs,
1425
+ forms: this.extractForms(container, options),
1426
+ clickable
1427
+ };
1428
+ }
1429
+ /**
1430
+ * Extract form information
1431
+ */
1432
+ extractForms(container, options) {
1433
+ const forms = [];
1434
+ container.querySelectorAll("form").forEach((form) => {
1435
+ if (!this.shouldIncludeElement(form, options)) return;
1436
+ const formInputs = [];
1437
+ const formButtons = [];
1438
+ form.querySelectorAll("input:not([type=\"button\"]):not([type=\"submit\"]), textarea, select").forEach((input) => {
1439
+ const extracted = DOMTraversal.extractElement(input, options);
1440
+ if (extracted) formInputs.push(extracted);
1441
+ });
1442
+ form.querySelectorAll("button, input[type=\"button\"], input[type=\"submit\"]").forEach((button) => {
1443
+ const extracted = DOMTraversal.extractElement(button, options);
1444
+ if (extracted) formButtons.push(extracted);
1445
+ });
1446
+ const action = form.getAttribute("action");
1447
+ const method = form.getAttribute("method");
1448
+ const formInfo = {
1449
+ selector: SelectorGenerator.generateSelectors(form).css,
1450
+ inputs: formInputs,
1451
+ buttons: formButtons
1452
+ };
1453
+ if (action) formInfo.action = action;
1454
+ if (method) formInfo.method = method;
1455
+ forms.push(formInfo);
1456
+ });
1457
+ return forms;
1458
+ }
1459
+ /**
1460
+ * Extract semantic elements (full mode only)
1461
+ */
1462
+ extractSemanticElements(container, options) {
1463
+ const headings = [];
1464
+ const images = [];
1465
+ const tables = [];
1466
+ const lists = [];
1467
+ const articles = [];
1468
+ container.querySelectorAll("h1, h2, h3, h4, h5, h6").forEach((el) => {
1469
+ if (this.shouldIncludeElement(el, options)) {
1470
+ const extracted = DOMTraversal.extractElement(el, options);
1471
+ if (extracted) headings.push(extracted);
1472
+ }
1473
+ });
1474
+ container.querySelectorAll("img").forEach((el) => {
1475
+ if (this.shouldIncludeElement(el, options)) {
1476
+ const extracted = DOMTraversal.extractElement(el, options);
1477
+ if (extracted) images.push(extracted);
1478
+ }
1479
+ });
1480
+ container.querySelectorAll("table").forEach((el) => {
1481
+ if (this.shouldIncludeElement(el, options)) {
1482
+ const extracted = DOMTraversal.extractElement(el, options);
1483
+ if (extracted) tables.push(extracted);
1484
+ }
1485
+ });
1486
+ container.querySelectorAll("ul, ol").forEach((el) => {
1487
+ if (this.shouldIncludeElement(el, options)) {
1488
+ const extracted = DOMTraversal.extractElement(el, options);
1489
+ if (extracted) lists.push(extracted);
1490
+ }
1491
+ });
1492
+ container.querySelectorAll("article, [role=\"article\"]").forEach((el) => {
1493
+ if (this.shouldIncludeElement(el, options)) {
1494
+ const extracted = DOMTraversal.extractElement(el, options);
1495
+ if (extracted) articles.push(extracted);
1496
+ }
1497
+ });
1498
+ return {
1499
+ headings,
1500
+ images,
1501
+ tables,
1502
+ lists,
1503
+ articles
1504
+ };
1505
+ }
1506
+ /**
1507
+ * Extract metadata
1508
+ */
1509
+ extractMetadata(doc, container, options) {
1510
+ const allElements = container.querySelectorAll("*");
1511
+ const extractedElements = container.querySelectorAll("button, a, input, textarea, select, h1, h2, h3, h4, h5, h6, img, table, ul, ol, article").length;
1512
+ const metadata = {
1513
+ totalElements: allElements.length,
1514
+ extractedElements
1515
+ };
1516
+ if (options.mainContentOnly && container instanceof Element) metadata.mainContent = SelectorGenerator.generateSelectors(container).css;
1517
+ const language = doc.documentElement.getAttribute("lang");
1518
+ if (language) metadata.language = language;
1519
+ return metadata;
1520
+ }
1521
+ /**
1522
+ * Check if element should be included based on options
1523
+ */
1524
+ shouldIncludeElement(element, options) {
1525
+ if (!options.includeHidden && !DOMTraversal.isVisible(element)) return false;
1526
+ if (options.viewportOnly && !DOMTraversal.isInViewport(element)) return false;
1527
+ if (options.filter && !DOMTraversal.passesFilter(element, options.filter)) return false;
1528
+ return true;
1529
+ }
1530
+ /**
1531
+ * Detect errors on the page
1532
+ */
1533
+ detectErrors(doc) {
1534
+ return [
1535
+ ".error",
1536
+ ".alert-danger",
1537
+ "[role=\"alert\"]",
1538
+ ".error-message"
1539
+ ].some((sel) => {
1540
+ const element = doc.querySelector(sel);
1541
+ return element ? DOMTraversal.isVisible(element) : false;
1542
+ });
1543
+ }
1544
+ /**
1545
+ * Detect if page is loading
1546
+ */
1547
+ detectLoading(doc) {
1548
+ return [
1549
+ ".loading",
1550
+ ".spinner",
1551
+ "[aria-busy=\"true\"]",
1552
+ ".loader"
1553
+ ].some((sel) => {
1554
+ const element = doc.querySelector(sel);
1555
+ return element ? DOMTraversal.isVisible(element) : false;
1556
+ });
1557
+ }
1558
+ /**
1559
+ * Detect modal dialogs
1560
+ */
1561
+ detectModals(doc) {
1562
+ return [
1563
+ "[role=\"dialog\"]",
1564
+ ".modal",
1565
+ ".popup",
1566
+ ".overlay"
1567
+ ].some((sel) => {
1568
+ const element = doc.querySelector(sel);
1569
+ return element ? DOMTraversal.isVisible(element) : false;
1570
+ });
1571
+ }
1572
+ /**
1573
+ * Get currently focused element
1574
+ */
1575
+ getFocusedElement(doc) {
1576
+ const focused = doc.activeElement;
1577
+ if (focused && focused !== doc.body) return SelectorGenerator.generateSelectors(focused).css;
1578
+ }
1579
+ /**
1580
+ * Quick extraction for interactive elements only
1581
+ * @param doc The document to extract from
1582
+ * @param options Extraction options
1583
+ */
1584
+ static extractInteractive(doc, options = {}) {
1585
+ return new SmartDOMReader({
1586
+ ...options,
1587
+ mode: "interactive"
1588
+ }).extract(doc);
1589
+ }
1590
+ /**
1591
+ * Quick extraction for full content
1592
+ * @param doc The document to extract from
1593
+ * @param options Extraction options
1594
+ */
1595
+ static extractFull(doc, options = {}) {
1596
+ return new SmartDOMReader({
1597
+ ...options,
1598
+ mode: "full"
1599
+ }).extract(doc);
1600
+ }
1601
+ /**
1602
+ * Extract from a specific element
1603
+ * @param element The element to extract from
1604
+ * @param mode The extraction mode
1605
+ * @param options Additional options
1606
+ */
1607
+ static extractFromElement(element, mode = "interactive", options = {}) {
1608
+ return new SmartDOMReader({
1609
+ ...options,
1610
+ mode
1611
+ }).extract(element);
1612
+ }
1613
+ };
1614
+ }));
1615
+ //#endregion
1616
+ init_src();
1617
+ export { ContentDetection, MarkdownFormatter, ProgressiveExtractor, SelectorGenerator, SmartDOMReader, SmartDOMReader as default };
1618
+