-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinjected_api.js
More file actions
1473 lines (1275 loc) · 63.8 KB
/
injected_api.js
File metadata and controls
1473 lines (1275 loc) · 63.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// injected_api.js - MAIN WORLD (NO WASM! CSP-Resistant!)
// This script ONLY collects raw DOM data and sends it to background for processing
(async () => {
// console.log('[SentienceAPI] Initializing (CSP-Resistant Mode)...');
// Wait for Extension ID from content.js
const getExtensionId = () => document.documentElement.dataset.sentienceExtensionId;
let extId = getExtensionId();
if (!extId) {
await new Promise(resolve => {
const check = setInterval(() => {
extId = getExtensionId();
if (extId) { clearInterval(check); resolve(); }
}, 50);
setTimeout(() => resolve(), 5000); // Max 5s wait
});
}
if (!extId) {
console.error('[SentienceAPI] Failed to get extension ID');
return;
}
// console.log('[SentienceAPI] Extension ID:', extId);
// Registry for click actions (still needed for click() function)
window.sentience_registry = [];
// --- HELPER: Deep Walker with Native Filter ---
function getAllElements(root = document) {
const elements = [];
const filter = {
acceptNode: function(node) {
// Skip metadata and script/style tags
if (['SCRIPT', 'STYLE', 'NOSCRIPT', 'META', 'LINK', 'HEAD'].includes(node.tagName)) {
return NodeFilter.FILTER_REJECT;
}
// Skip deep SVG children
if (node.parentNode && node.parentNode.tagName === 'SVG' && node.tagName !== 'SVG') {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
};
const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, filter);
while(walker.nextNode()) {
const node = walker.currentNode;
if (node.isConnected) {
elements.push(node);
if (node.shadowRoot) elements.push(...getAllElements(node.shadowRoot));
}
}
return elements;
}
// --- HELPER: Smart Text Extractor ---
function getText(el) {
if (el.getAttribute('aria-label')) return el.getAttribute('aria-label');
if (el.tagName === 'INPUT') return el.value || el.placeholder || '';
if (el.tagName === 'IMG') return el.alt || '';
return (el.innerText || '').replace(/\s+/g, ' ').trim().substring(0, 100);
}
// --- HELPER: Safe Class Name Extractor (Handles SVGAnimatedString) ---
function getClassName(el) {
if (!el || !el.className) return '';
// Handle string (HTML elements)
if (typeof el.className === 'string') return el.className;
// Handle SVGAnimatedString (SVG elements)
if (typeof el.className === 'object') {
if ('baseVal' in el.className && typeof el.className.baseVal === 'string') {
return el.className.baseVal;
}
if ('animVal' in el.className && typeof el.className.animVal === 'string') {
return el.className.animVal;
}
// Fallback: convert to string
try {
return String(el.className);
} catch (e) {
return '';
}
}
return '';
}
// --- HELPER: Paranoid String Converter (Handles SVGAnimatedString) ---
function toSafeString(value) {
if (value === null || value === undefined) return null;
// 1. If it's already a primitive string, return it
if (typeof value === 'string') return value;
// 2. Handle SVG objects (SVGAnimatedString, SVGAnimatedNumber, etc.)
if (typeof value === 'object') {
// Try extracting baseVal (standard SVG property)
if ('baseVal' in value && typeof value.baseVal === 'string') {
return value.baseVal;
}
// Try animVal as fallback
if ('animVal' in value && typeof value.animVal === 'string') {
return value.animVal;
}
// Fallback: Force to string (prevents WASM crash even if data is less useful)
// This prevents the "Invalid Type" crash, even if the data is "[object SVGAnimatedString]"
try {
return String(value);
} catch (e) {
return null;
}
}
// 3. Last resort cast for primitives
try {
return String(value);
} catch (e) {
return null;
}
}
// --- HELPER: Get SVG Fill/Stroke Color ---
// For SVG elements, get the fill or stroke color (SVGs use fill/stroke, not backgroundColor)
function getSVGColor(el) {
if (!el || el.tagName !== 'SVG') return null;
const style = window.getComputedStyle(el);
// Try fill first (most common for SVG icons)
const fill = style.fill;
if (fill && fill !== 'none' && fill !== 'transparent' && fill !== 'rgba(0, 0, 0, 0)') {
// Convert fill to rgb() format if needed
const rgbaMatch = fill.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
if (rgbaMatch) {
const alpha = rgbaMatch[4] ? parseFloat(rgbaMatch[4]) : 1.0;
if (alpha >= 0.9) {
return `rgb(${rgbaMatch[1]}, ${rgbaMatch[2]}, ${rgbaMatch[3]})`;
}
} else if (fill.startsWith('rgb(')) {
return fill;
}
}
// Fallback to stroke if fill is not available
const stroke = style.stroke;
if (stroke && stroke !== 'none' && stroke !== 'transparent' && stroke !== 'rgba(0, 0, 0, 0)') {
const rgbaMatch = stroke.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
if (rgbaMatch) {
const alpha = rgbaMatch[4] ? parseFloat(rgbaMatch[4]) : 1.0;
if (alpha >= 0.9) {
return `rgb(${rgbaMatch[1]}, ${rgbaMatch[2]}, ${rgbaMatch[3]})`;
}
} else if (stroke.startsWith('rgb(')) {
return stroke;
}
}
return null;
}
// --- HELPER: Get Effective Background Color ---
// Traverses up the DOM tree to find the nearest non-transparent background color
// For SVGs, also checks fill/stroke properties
// This handles rgba(0,0,0,0) and transparent values that browsers commonly return
function getEffectiveBackgroundColor(el) {
if (!el) return null;
// For SVG elements, use fill/stroke instead of backgroundColor
if (el.tagName === 'SVG') {
const svgColor = getSVGColor(el);
if (svgColor) return svgColor;
}
let current = el;
const maxDepth = 10; // Prevent infinite loops
let depth = 0;
while (current && depth < maxDepth) {
const style = window.getComputedStyle(current);
// For SVG elements in the tree, also check fill/stroke
if (current.tagName === 'SVG') {
const svgColor = getSVGColor(current);
if (svgColor) return svgColor;
}
const bgColor = style.backgroundColor;
if (bgColor && bgColor !== 'transparent' && bgColor !== 'rgba(0, 0, 0, 0)') {
// Check if it's rgba with alpha < 1 (semi-transparent)
const rgbaMatch = bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
if (rgbaMatch) {
const alpha = rgbaMatch[4] ? parseFloat(rgbaMatch[4]) : 1.0;
// If alpha is high enough (>= 0.9), consider it opaque enough
if (alpha >= 0.9) {
// Convert to rgb() format for Gateway compatibility
return `rgb(${rgbaMatch[1]}, ${rgbaMatch[2]}, ${rgbaMatch[3]})`;
}
// If semi-transparent, continue up the tree
} else if (bgColor.startsWith('rgb(')) {
// Already in rgb() format, use it
return bgColor;
} else {
// Named color or other format, return as-is
return bgColor;
}
}
// Move up the DOM tree
current = current.parentElement;
depth++;
}
// Fallback: return null if nothing found
return null;
}
// --- HELPER: Viewport Check ---
function isInViewport(rect) {
return (
rect.top < window.innerHeight && rect.bottom > 0 &&
rect.left < window.innerWidth && rect.right > 0
);
}
// --- HELPER: Occlusion Check (Optimized to avoid layout thrashing) ---
// Only checks occlusion for elements likely to be occluded (high z-index, positioned)
// This avoids forced reflow for most elements, dramatically improving performance
function isOccluded(el, rect, style) {
// Fast path: Skip occlusion check for most elements
// Only check for elements that are likely to be occluded (overlays, modals, tooltips)
const zIndex = parseInt(style.zIndex, 10);
const position = style.position;
// Skip occlusion check for normal flow elements (vast majority)
// Only check for positioned elements or high z-index (likely overlays)
if (position === 'static' && (isNaN(zIndex) || zIndex <= 10)) {
return false; // Assume not occluded for performance
}
// For positioned/high z-index elements, do the expensive check
const cx = rect.x + rect.width / 2;
const cy = rect.y + rect.height / 2;
if (cx < 0 || cx > window.innerWidth || cy < 0 || cy > window.innerHeight) return false;
const topEl = document.elementFromPoint(cx, cy);
if (!topEl) return false;
return !(el === topEl || el.contains(topEl) || topEl.contains(el));
}
// --- HELPER: Screenshot Bridge ---
function captureScreenshot(options) {
return new Promise(resolve => {
const requestId = Math.random().toString(36).substring(7);
const listener = (e) => {
if (e.data.type === 'SENTIENCE_SCREENSHOT_RESULT' && e.data.requestId === requestId) {
window.removeEventListener('message', listener);
resolve(e.data.screenshot);
}
};
window.addEventListener('message', listener);
window.postMessage({ type: 'SENTIENCE_SCREENSHOT_REQUEST', requestId, options }, '*');
setTimeout(() => {
window.removeEventListener('message', listener);
resolve(null);
}, 10000); // 10s timeout
});
}
// --- HELPER: Snapshot Processing Bridge (NEW!) ---
function processSnapshotInBackground(rawData, options) {
return new Promise((resolve, reject) => {
const requestId = Math.random().toString(36).substring(7);
const TIMEOUT_MS = 25000; // 25 seconds (longer than content.js timeout)
let resolved = false;
const timeout = setTimeout(() => {
if (!resolved) {
resolved = true;
window.removeEventListener('message', listener);
reject(new Error('WASM processing timeout - extension may be unresponsive. Try reloading the extension.'));
}
}, TIMEOUT_MS);
const listener = (e) => {
if (e.data.type === 'SENTIENCE_SNAPSHOT_RESULT' && e.data.requestId === requestId) {
if (resolved) return; // Already handled
resolved = true;
clearTimeout(timeout);
window.removeEventListener('message', listener);
if (e.data.error) {
reject(new Error(e.data.error));
} else {
resolve({
elements: e.data.elements,
raw_elements: e.data.raw_elements,
duration: e.data.duration
});
}
}
};
window.addEventListener('message', listener);
try {
window.postMessage({
type: 'SENTIENCE_SNAPSHOT_REQUEST',
requestId,
rawData,
options
}, '*');
} catch (error) {
if (!resolved) {
resolved = true;
clearTimeout(timeout);
window.removeEventListener('message', listener);
reject(new Error(`Failed to send snapshot request: ${error.message}`));
}
}
});
}
// --- HELPER: Raw HTML Extractor (unchanged) ---
function getRawHTML(root) {
const sourceRoot = root || document.body;
const clone = sourceRoot.cloneNode(true);
const unwantedTags = ['nav', 'footer', 'header', 'script', 'style', 'noscript', 'iframe', 'svg'];
unwantedTags.forEach(tag => {
const elements = clone.querySelectorAll(tag);
elements.forEach(el => {
if (el.parentNode) el.parentNode.removeChild(el);
});
});
// Remove invisible elements
const invisibleSelectors = [];
const walker = document.createTreeWalker(sourceRoot, NodeFilter.SHOW_ELEMENT, null, false);
let node;
while (node = walker.nextNode()) {
const tag = node.tagName.toLowerCase();
if (tag === 'head' || tag === 'title') continue;
const style = window.getComputedStyle(node);
if (style.display === 'none' || style.visibility === 'hidden' ||
(node.offsetWidth === 0 && node.offsetHeight === 0)) {
let selector = tag;
if (node.id) {
selector = `#${node.id}`;
} else if (node.className && typeof node.className === 'string') {
const classes = node.className.trim().split(/\s+/).filter(c => c);
if (classes.length > 0) {
selector = `${tag}.${classes.join('.')}`;
}
}
invisibleSelectors.push(selector);
}
}
invisibleSelectors.forEach(selector => {
try {
const elements = clone.querySelectorAll(selector);
elements.forEach(el => {
if (el.parentNode) el.parentNode.removeChild(el);
});
} catch (e) {
// Invalid selector, skip
}
});
// Resolve relative URLs
const links = clone.querySelectorAll('a[href]');
links.forEach(link => {
const href = link.getAttribute('href');
if (href && !href.startsWith('http://') && !href.startsWith('https://') && !href.startsWith('#')) {
try {
link.setAttribute('href', new URL(href, document.baseURI).href);
} catch (e) {}
}
});
const images = clone.querySelectorAll('img[src]');
images.forEach(img => {
const src = img.getAttribute('src');
if (src && !src.startsWith('http://') && !src.startsWith('https://') && !src.startsWith('data:')) {
try {
img.setAttribute('src', new URL(src, document.baseURI).href);
} catch (e) {}
}
});
return clone.innerHTML;
}
// --- HELPER: Markdown Converter (unchanged) ---
function convertToMarkdown(root) {
const rawHTML = getRawHTML(root);
const tempDiv = document.createElement('div');
tempDiv.innerHTML = rawHTML;
let markdown = '';
let insideLink = false;
function walk(node) {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent.replace(/[\r\n]+/g, ' ').replace(/\s+/g, ' ');
if (text.trim()) markdown += text;
return;
}
if (node.nodeType !== Node.ELEMENT_NODE) return;
const tag = node.tagName.toLowerCase();
// Prefix
if (tag === 'h1') markdown += '\n# ';
if (tag === 'h2') markdown += '\n## ';
if (tag === 'h3') markdown += '\n### ';
if (tag === 'li') markdown += '\n- ';
if (!insideLink && (tag === 'p' || tag === 'div' || tag === 'br')) markdown += '\n';
if (tag === 'strong' || tag === 'b') markdown += '**';
if (tag === 'em' || tag === 'i') markdown += '_';
if (tag === 'a') {
markdown += '[';
insideLink = true;
}
// Children
if (node.shadowRoot) {
Array.from(node.shadowRoot.childNodes).forEach(walk);
} else {
node.childNodes.forEach(walk);
}
// Suffix
if (tag === 'a') {
const href = node.getAttribute('href');
if (href) markdown += `](${href})`;
else markdown += ']';
insideLink = false;
}
if (tag === 'strong' || tag === 'b') markdown += '**';
if (tag === 'em' || tag === 'i') markdown += '_';
if (!insideLink && (tag === 'h1' || tag === 'h2' || tag === 'h3' || tag === 'p' || tag === 'div')) markdown += '\n';
}
walk(tempDiv);
return markdown.replace(/\n{3,}/g, '\n\n').trim();
}
// --- HELPER: Text Extractor (unchanged) ---
function convertToText(root) {
let text = '';
function walk(node) {
if (node.nodeType === Node.TEXT_NODE) {
text += node.textContent;
return;
}
if (node.nodeType === Node.ELEMENT_NODE) {
const tag = node.tagName.toLowerCase();
if (['nav', 'footer', 'header', 'script', 'style', 'noscript', 'iframe', 'svg'].includes(tag)) return;
const style = window.getComputedStyle(node);
if (style.display === 'none' || style.visibility === 'hidden') return;
const isBlock = style.display === 'block' || style.display === 'flex' || node.tagName === 'P' || node.tagName === 'DIV';
if (isBlock) text += ' ';
if (node.shadowRoot) {
Array.from(node.shadowRoot.childNodes).forEach(walk);
} else {
node.childNodes.forEach(walk);
}
if (isBlock) text += '\n';
}
}
walk(root || document.body);
return text.replace(/\n{3,}/g, '\n\n').trim();
}
// --- HELPER: Clean null/undefined fields ---
function cleanElement(obj) {
if (Array.isArray(obj)) {
return obj.map(cleanElement);
}
if (obj !== null && typeof obj === 'object') {
const cleaned = {};
for (const [key, value] of Object.entries(obj)) {
if (value !== null && value !== undefined) {
if (typeof value === 'object') {
const deepClean = cleanElement(value);
if (Object.keys(deepClean).length > 0) {
cleaned[key] = deepClean;
}
} else {
cleaned[key] = value;
}
}
}
return cleaned;
}
return obj;
}
// --- HELPER: Extract Raw Element Data (for Golden Set) ---
function extractRawElementData(el) {
const style = window.getComputedStyle(el);
const rect = el.getBoundingClientRect();
return {
tag: el.tagName,
rect: {
x: Math.round(rect.x),
y: Math.round(rect.y),
width: Math.round(rect.width),
height: Math.round(rect.height)
},
styles: {
cursor: style.cursor || null,
backgroundColor: style.backgroundColor || null,
color: style.color || null,
fontWeight: style.fontWeight || null,
fontSize: style.fontSize || null,
display: style.display || null,
position: style.position || null,
zIndex: style.zIndex || null,
opacity: style.opacity || null,
visibility: style.visibility || null
},
attributes: {
role: el.getAttribute('role') || null,
type: el.getAttribute('type') || null,
ariaLabel: el.getAttribute('aria-label') || null,
id: el.id || null,
className: el.className || null
}
};
}
// --- HELPER: Generate Unique CSS Selector (for Golden Set) ---
function getUniqueSelector(el) {
if (!el || !el.tagName) return '';
// If element has a unique ID, use it
if (el.id) {
return `#${el.id}`;
}
// Try data attributes or aria-label for uniqueness
for (const attr of el.attributes) {
if (attr.name.startsWith('data-') || attr.name === 'aria-label') {
const value = attr.value ? attr.value.replace(/"/g, '\\"') : '';
return `${el.tagName.toLowerCase()}[${attr.name}="${value}"]`;
}
}
// Build path with classes and nth-child for uniqueness
const path = [];
let current = el;
while (current && current !== document.body && current !== document.documentElement) {
let selector = current.tagName.toLowerCase();
// If current element has ID, use it and stop
if (current.id) {
selector = `#${current.id}`;
path.unshift(selector);
break;
}
// Add class if available
if (current.className && typeof current.className === 'string') {
const classes = current.className.trim().split(/\s+/).filter(c => c);
if (classes.length > 0) {
// Use first class for simplicity
selector += `.${classes[0]}`;
}
}
// Add nth-of-type if needed for uniqueness
if (current.parentElement) {
const siblings = Array.from(current.parentElement.children);
const sameTagSiblings = siblings.filter(s => s.tagName === current.tagName);
const index = sameTagSiblings.indexOf(current);
if (index > 0 || sameTagSiblings.length > 1) {
selector += `:nth-of-type(${index + 1})`;
}
}
path.unshift(selector);
current = current.parentElement;
}
return path.join(' > ') || el.tagName.toLowerCase();
}
// --- HELPER: Wait for DOM Stability (SPA Hydration) ---
// Waits for the DOM to stabilize before taking a snapshot
// Useful for React/Vue apps that render empty skeletons before hydration
async function waitForStability(options = {}) {
const {
minNodeCount = 500,
quietPeriod = 200, // milliseconds
maxWait = 5000 // maximum wait time
} = options;
const startTime = Date.now();
return new Promise((resolve) => {
// Check if DOM already has enough nodes
const nodeCount = document.querySelectorAll('*').length;
if (nodeCount >= minNodeCount) {
// DOM seems ready, but wait for quiet period to ensure stability
let lastChange = Date.now();
const observer = new MutationObserver(() => {
lastChange = Date.now();
});
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: false
});
const checkStable = () => {
const timeSinceLastChange = Date.now() - lastChange;
const totalWait = Date.now() - startTime;
if (timeSinceLastChange >= quietPeriod) {
observer.disconnect();
resolve();
} else if (totalWait >= maxWait) {
observer.disconnect();
console.warn('[SentienceAPI] DOM stability timeout - proceeding anyway');
resolve();
} else {
setTimeout(checkStable, 50);
}
};
checkStable();
} else {
// DOM doesn't have enough nodes yet, wait for them
const observer = new MutationObserver(() => {
const currentCount = document.querySelectorAll('*').length;
const totalWait = Date.now() - startTime;
if (currentCount >= minNodeCount) {
observer.disconnect();
// Now wait for quiet period
let lastChange = Date.now();
const quietObserver = new MutationObserver(() => {
lastChange = Date.now();
});
quietObserver.observe(document.body, {
childList: true,
subtree: true,
attributes: false
});
const checkQuiet = () => {
const timeSinceLastChange = Date.now() - lastChange;
const totalWait = Date.now() - startTime;
if (timeSinceLastChange >= quietPeriod) {
quietObserver.disconnect();
resolve();
} else if (totalWait >= maxWait) {
quietObserver.disconnect();
console.warn('[SentienceAPI] DOM stability timeout - proceeding anyway');
resolve();
} else {
setTimeout(checkQuiet, 50);
}
};
checkQuiet();
} else if (totalWait >= maxWait) {
observer.disconnect();
console.warn('[SentienceAPI] DOM node count timeout - proceeding anyway');
resolve();
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: false
});
// Timeout fallback
setTimeout(() => {
observer.disconnect();
console.warn('[SentienceAPI] DOM stability max wait reached - proceeding');
resolve();
}, maxWait);
}
});
}
// --- HELPER: Collect Iframe Snapshots (Frame Stitching) ---
// Recursively collects snapshot data from all child iframes
// This enables detection of elements inside iframes (e.g., Stripe forms)
//
// NOTE: Cross-origin iframes cannot be accessed due to browser security (Same-Origin Policy).
// Only same-origin iframes will return snapshot data. Cross-origin iframes will be skipped
// with a warning. For cross-origin iframes, users must manually switch frames using
// Playwright's page.frame() API.
async function collectIframeSnapshots(options = {}) {
const iframeData = new Map(); // Map of iframe element -> snapshot data
// Find all iframe elements in current document
const iframes = Array.from(document.querySelectorAll('iframe'));
if (iframes.length === 0) {
return iframeData;
}
console.log(`[SentienceAPI] Found ${iframes.length} iframe(s), requesting snapshots...`);
// Request snapshot from each iframe
const iframePromises = iframes.map((iframe, idx) => {
// OPTIMIZATION: Skip common ad domains to save time
const src = iframe.src || '';
if (src.includes('doubleclick') || src.includes('googleadservices') || src.includes('ads system')) {
console.log(`[SentienceAPI] Skipping ad iframe: ${src.substring(0, 30)}...`);
return Promise.resolve(null);
}
return new Promise((resolve) => {
const requestId = `iframe-${idx}-${Date.now()}`;
// 1. EXTENDED TIMEOUT (Handle slow children)
const timeout = setTimeout(() => {
console.warn(`[SentienceAPI] ⚠️ Iframe ${idx} snapshot TIMEOUT (id: ${requestId})`);
resolve(null);
}, 5000); // Increased to 5s to handle slow processing
// 2. ROBUST LISTENER with debugging
const listener = (event) => {
// Debug: Log all SENTIENCE_IFRAME_SNAPSHOT_RESPONSE messages to see what's happening
if (event.data?.type === 'SENTIENCE_IFRAME_SNAPSHOT_RESPONSE') {
// Only log if it's not our request (for debugging)
if (event.data?.requestId !== requestId) {
// console.log(`[SentienceAPI] Received response for different request: ${event.data.requestId} (expected: ${requestId})`);
}
}
// Check if this is the response we're waiting for
if (event.data?.type === 'SENTIENCE_IFRAME_SNAPSHOT_RESPONSE' &&
event.data?.requestId === requestId) {
clearTimeout(timeout);
window.removeEventListener('message', listener);
if (event.data.error) {
console.warn(`[SentienceAPI] Iframe ${idx} returned error:`, event.data.error);
resolve(null);
} else {
const elementCount = event.data.snapshot?.raw_elements?.length || 0;
console.log(`[SentienceAPI] ✓ Received ${elementCount} elements from Iframe ${idx} (id: ${requestId})`);
resolve({
iframe: iframe,
data: event.data.snapshot,
error: null
});
}
}
};
window.addEventListener('message', listener);
// 3. SEND REQUEST with error handling
try {
if (iframe.contentWindow) {
// console.log(`[SentienceAPI] Sending request to Iframe ${idx} (id: ${requestId})`);
iframe.contentWindow.postMessage({
type: 'SENTIENCE_IFRAME_SNAPSHOT_REQUEST',
requestId: requestId,
options: {
...options,
collectIframes: true // Enable recursion for nested iframes
}
}, '*'); // Use '*' for cross-origin, but browser will enforce same-origin policy
} else {
console.warn(`[SentienceAPI] Iframe ${idx} contentWindow is inaccessible (Cross-Origin?)`);
clearTimeout(timeout);
window.removeEventListener('message', listener);
resolve(null);
}
} catch (error) {
console.error(`[SentienceAPI] Failed to postMessage to Iframe ${idx}:`, error);
clearTimeout(timeout);
window.removeEventListener('message', listener);
resolve(null);
}
});
});
// Wait for all iframe responses
const results = await Promise.all(iframePromises);
// Store iframe data
results.forEach((result, idx) => {
if (result && result.data && !result.error) {
iframeData.set(iframes[idx], result.data);
console.log(`[SentienceAPI] ✓ Collected snapshot from iframe ${idx}`);
} else if (result && result.error) {
console.warn(`[SentienceAPI] Iframe ${idx} snapshot error:`, result.error);
} else if (!result) {
console.warn(`[SentienceAPI] Iframe ${idx} returned no data (timeout or error)`);
}
});
return iframeData;
}
// --- HELPER: Handle Iframe Snapshot Request (for child frames) ---
// When a parent frame requests snapshot, this handler responds with local snapshot
// NOTE: Recursion is safe because querySelectorAll('iframe') only finds direct children.
// Iframe A can ask Iframe B, but won't go back up to parent (no circular dependency risk).
function setupIframeSnapshotHandler() {
window.addEventListener('message', async (event) => {
// Security: only respond to snapshot requests from parent frames
if (event.data?.type === 'SENTIENCE_IFRAME_SNAPSHOT_REQUEST') {
const { requestId, options } = event.data;
try {
// Generate snapshot for this iframe's content
// Allow recursive collection - querySelectorAll('iframe') only finds direct children,
// so Iframe A will ask Iframe B, but won't go back up to parent (safe recursion)
// waitForStability: false makes performance better - i.e. don't wait for children frames
const snapshotOptions = { ...options, collectIframes: true, waitForStability: options.waitForStability === false ? false : false };
const snapshot = await window.sentience.snapshot(snapshotOptions);
// Send response back to parent
if (event.source && event.source.postMessage) {
event.source.postMessage({
type: 'SENTIENCE_IFRAME_SNAPSHOT_RESPONSE',
requestId: requestId,
snapshot: snapshot,
error: null
}, '*');
}
} catch (error) {
// Send error response
if (event.source && event.source.postMessage) {
event.source.postMessage({
type: 'SENTIENCE_IFRAME_SNAPSHOT_RESPONSE',
requestId: requestId,
snapshot: null,
error: error.message
}, '*');
}
}
}
});
}
// Setup iframe handler when script loads (only once)
if (!window.sentience_iframe_handler_setup) {
setupIframeSnapshotHandler();
window.sentience_iframe_handler_setup = true;
}
// --- GLOBAL API ---
window.sentience = {
// 1. Geometry snapshot (NEW ARCHITECTURE - No WASM in Main World!)
snapshot: async (options = {}) => {
try {
// Step 0: Wait for DOM stability if requested (for SPA hydration)
if (options.waitForStability !== false) {
await waitForStability(options.waitForStability || {});
}
// Step 1: Collect raw DOM data (Main World - CSP can't block this!)
const rawData = [];
window.sentience_registry = [];
const nodes = getAllElements();
nodes.forEach((el, idx) => {
if (!el.getBoundingClientRect) return;
const rect = el.getBoundingClientRect();
if (rect.width < 5 || rect.height < 5) return;
window.sentience_registry[idx] = el;
const textVal = getText(el);
const inView = isInViewport(rect);
// Get computed style once (needed for both occlusion check and data collection)
const style = window.getComputedStyle(el);
// Only check occlusion for elements likely to be occluded (optimized)
// This avoids layout thrashing for the vast majority of elements
const occluded = inView ? isOccluded(el, rect, style) : false;
// Get effective background color (traverses DOM to find non-transparent color)
const effectiveBgColor = getEffectiveBackgroundColor(el);
rawData.push({
id: idx,
tag: el.tagName.toLowerCase(),
rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
styles: {
display: toSafeString(style.display),
visibility: toSafeString(style.visibility),
opacity: toSafeString(style.opacity),
z_index: toSafeString(style.zIndex || "auto"),
position: toSafeString(style.position),
bg_color: toSafeString(effectiveBgColor || style.backgroundColor),
color: toSafeString(style.color),
cursor: toSafeString(style.cursor),
font_weight: toSafeString(style.fontWeight),
font_size: toSafeString(style.fontSize)
},
attributes: {
role: toSafeString(el.getAttribute('role')),
type_: toSafeString(el.getAttribute('type')),
aria_label: toSafeString(el.getAttribute('aria-label')),
href: toSafeString(el.href || el.getAttribute('href') || null),
class: toSafeString(getClassName(el)),
// Capture dynamic input state (not just initial attributes)
value: el.value !== undefined ? toSafeString(el.value) : toSafeString(el.getAttribute('value')),
checked: el.checked !== undefined ? String(el.checked) : null
},
text: toSafeString(textVal),
in_viewport: inView,
is_occluded: occluded
});
});
console.log(`[SentienceAPI] Collected ${rawData.length} elements from main frame`);
// Step 1.5: Collect iframe snapshots and FLATTEN immediately
// "Flatten Early" architecture: Merge iframe elements into main array before WASM
// This allows WASM to process all elements uniformly (no recursion needed)
let allRawElements = [...rawData]; // Start with main frame elements
let totalIframeElements = 0;
if (options.collectIframes !== false) {
try {
console.log(`[SentienceAPI] Starting iframe collection...`);
const iframeSnapshots = await collectIframeSnapshots(options);
console.log(`[SentienceAPI] Iframe collection complete. Received ${iframeSnapshots.size} snapshot(s)`);
if (iframeSnapshots.size > 0) {
// FLATTEN IMMEDIATELY: Don't nest them. Just append them with coordinate translation.
iframeSnapshots.forEach((iframeSnapshot, iframeEl) => {
// Debug: Log structure to verify data is correct
// console.log(`[SentienceAPI] Processing iframe snapshot:`, iframeSnapshot);
if (iframeSnapshot && iframeSnapshot.raw_elements) {
const rawElementsCount = iframeSnapshot.raw_elements.length;
console.log(`[SentienceAPI] Processing ${rawElementsCount} elements from iframe (src: ${iframeEl.src || 'unknown'})`);
// Get iframe's bounding rect (offset for coordinate translation)
const iframeRect = iframeEl.getBoundingClientRect();
const offset = { x: iframeRect.x, y: iframeRect.y };
// Get iframe context for frame switching (Playwright needs this)
const iframeSrc = iframeEl.src || iframeEl.getAttribute('src') || '';
let isSameOrigin = false;
try {
// Try to access contentWindow to check if same-origin
isSameOrigin = iframeEl.contentWindow !== null;
} catch (e) {
isSameOrigin = false;
}
// Adjust coordinates and add iframe context to each element
const adjustedElements = iframeSnapshot.raw_elements.map(el => {
const adjusted = { ...el };
// Adjust rect coordinates to parent viewport
if (adjusted.rect) {
adjusted.rect = {
...adjusted.rect,
x: adjusted.rect.x + offset.x,
y: adjusted.rect.y + offset.y
};
}
// Add iframe context so agents can switch frames in Playwright
adjusted.iframe_context = {
src: iframeSrc,
is_same_origin: isSameOrigin
};
return adjusted;
});