1pub struct BridgeCapacities {
3 pub console_logs: usize,
5 pub mutation_log: usize,
7 pub network_log: usize,
9 pub navigation_log: usize,
11 pub dialog_log: usize,
13 pub long_tasks: usize,
15}
16
17impl Default for BridgeCapacities {
18 fn default() -> Self {
19 Self {
20 console_logs: 1000,
21 mutation_log: 500,
22 network_log: 1000,
23 navigation_log: 200,
24 dialog_log: 100,
25 long_tasks: 100,
26 }
27 }
28}
29
30#[must_use]
32pub fn init_script(caps: &BridgeCapacities) -> String {
33 format!(
34 "\n(function() {{\
35 \n if (window.__VICTAURI__) return;\
36 \n\
37 \n var CAP_CONSOLE = {console_logs};\
38 \n var CAP_MUTATION = {mutation_log};\
39 \n var CAP_NETWORK = {network_log};\
40 \n var CAP_NAVIGATION = {navigation_log};\
41 \n var CAP_DIALOG = {dialog_log};\
42 \n var CAP_LONG_TASKS = {long_tasks};\
43 \n",
44 console_logs = caps.console_logs,
45 mutation_log = caps.mutation_log,
46 network_log = caps.network_log,
47 navigation_log = caps.navigation_log,
48 dialog_log = caps.dialog_log,
49 long_tasks = caps.long_tasks,
50 ) + INIT_SCRIPT_BODY
51}
52
53const INIT_SCRIPT_BODY: &str = r#"
56 var refMap = new Map();
57 var refCounter = 0;
58 var weakRefMap = new Map();
59
60 function resolveRef(refId) {
61 var direct = refMap.get(refId);
62 if (direct) {
63 if (direct.isConnected) return direct;
64 refMap.delete(refId);
65 return null;
66 }
67 var weak = weakRefMap.get(refId);
68 if (weak) {
69 var el = weak.deref();
70 if (el && el.isConnected) return el;
71 weakRefMap.delete(refId);
72 return null;
73 }
74 return null;
75 }
76
77 var REF_MAP_LIMIT = 10000;
78
79 function registerRef(node) {
80 var ref_id = 'e' + (refCounter++);
81 if (refMap.size >= REF_MAP_LIMIT) {
82 var oldest = refMap.keys().next().value;
83 refMap.delete(oldest);
84 weakRefMap.delete(oldest);
85 }
86 refMap.set(ref_id, node);
87 if (typeof WeakRef !== 'undefined') {
88 weakRefMap.set(ref_id, new WeakRef(node));
89 }
90 return ref_id;
91 }
92
93 function getStaleRefs() {
94 var stale = [];
95 weakRefMap.forEach(function(weak, refId) {
96 var el = weak.deref();
97 if (!el || !el.isConnected) {
98 stale.push(refId);
99 weakRefMap.delete(refId);
100 refMap.delete(refId);
101 }
102 });
103 return stale;
104 }
105 var consoleLogs = [];
106 var mutationLog = [];
107 var networkLog = [];
108 var networkCounter = 0;
109 var navigationLog = [];
110 var dialogLog = [];
111 var interactionLog = [];
112 var CAP_INTERACTION = 500;
113 var ipcWaiters = [];
114 var longTasks = [];
115 var listenerCount = 0;
116
117 function checkActionable(el) {
118 if (!el || !el.isConnected) return { error: 'element is detached from DOM', hint: 'RETRY_LATER' };
119 if (el.disabled) return { error: 'element is disabled (disabled attribute)', hint: 'RETRY_LATER' };
120 if (el.getAttribute && el.getAttribute('aria-disabled') === 'true') return { error: 'element is disabled (aria-disabled)', hint: 'RETRY_LATER' };
121 var cs = window.getComputedStyle(el);
122 if (cs.display === 'none') return { error: 'element is not visible (display: none)', hint: 'RETRY_LATER' };
123 if (cs.visibility === 'hidden') return { error: 'element is not visible (visibility: hidden)', hint: 'RETRY_LATER' };
124 if (parseFloat(cs.opacity) < 0.01) return { error: 'element is not visible (opacity: ' + cs.opacity + ')', hint: 'RETRY_LATER' };
125 var rect = el.getBoundingClientRect();
126 if (rect.width === 0 && rect.height === 0) return { error: 'element has zero size', hint: 'RETRY_LATER' };
127 if (cs.pointerEvents === 'none') return { error: 'element has pointer-events: none', hint: 'RETRY_LATER' };
128 var vw = window.innerWidth || document.documentElement.clientWidth;
129 var vh = window.innerHeight || document.documentElement.clientHeight;
130 if (rect.bottom < 0 || rect.top > vh || rect.right < 0 || rect.left > vw) {
131 el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
132 rect = el.getBoundingClientRect();
133 if (rect.bottom < 0 || rect.top > vh || rect.right < 0 || rect.left > vw) {
134 return { error: 'element is outside viewport after scroll attempt', hint: 'CHECK_INPUT' };
135 }
136 }
137 var cx = rect.left + rect.width / 2;
138 var cy = rect.top + rect.height / 2;
139 var topEl = document.elementFromPoint(cx, cy);
140 if (topEl && topEl !== el && !el.contains(topEl) && !topEl.contains(el)) {
141 var tag = topEl.tagName ? topEl.tagName.toLowerCase() : 'unknown';
142 var info = tag;
143 if (topEl.id) info += '#' + topEl.id;
144 else if (topEl.className && typeof topEl.className === 'string') {
145 var cls = topEl.className.trim().split(/\s+/)[0];
146 if (cls) info += '.' + cls;
147 }
148 return { error: 'element is covered by ' + info + ' at (' + Math.round(cx) + ',' + Math.round(cy) + ')', hint: 'RETRY_LATER' };
149 }
150 return null;
151 }
152
153 function withAutoWait(refId, timeoutMs, actionFn) {
154 return new Promise(function(resolve) {
155 var deadline = Date.now() + (timeoutMs || 5000);
156 function attempt() {
157 var el = resolveRef(refId);
158 if (!el) {
159 if (Date.now() >= deadline) { resolve({ ok: false, error: 'ref not found: ' + refId, hint: 'CHECK_INPUT' }); return; }
160 setTimeout(attempt, 50); return;
161 }
162 var check = checkActionable(el);
163 if (check) {
164 if (check.hint === 'CHECK_INPUT' || Date.now() >= deadline) {
165 var msg = Date.now() >= deadline ? 'timeout (' + (timeoutMs || 5000) + 'ms): ' + check.error : check.error;
166 resolve({ ok: false, error: msg, hint: check.hint || 'RETRY_LATER' }); return;
167 }
168 setTimeout(attempt, 50); return;
169 }
170 try { var r = actionFn(el); resolve(r || { ok: true }); }
171 catch (e) { resolve({ ok: false, error: 'action threw: ' + e.message, hint: 'CHECK_INPUT' }); }
172 }
173 attempt();
174 });
175 }
176
177 // ── Public API ───────────────────────────────────────────────────────────
178
179 window.__VICTAURI__ = {
180 version: '0.3.0',
181 _captureIpcBodies: true,
182
183 // ── DOM ──────────────────────────────────────────────────────────────
184
185 snapshot: function(format) {
186 var previousRefs = new Set(refMap.keys());
187 refMap.clear();
188 var fmt = format || 'compact';
189 var tree;
190 if (fmt === 'json') {
191 tree = walkDom(document.body);
192 } else {
193 tree = walkDomCompact(document.body, 0);
194 }
195 var currentRefs = new Set(refMap.keys());
196 var stale = [];
197 previousRefs.forEach(function(refId) {
198 if (!currentRefs.has(refId)) {
199 var weak = weakRefMap.get(refId);
200 if (weak) {
201 var el = weak.deref();
202 if (!el || !el.isConnected) {
203 stale.push(refId);
204 weakRefMap.delete(refId);
205 }
206 } else {
207 stale.push(refId);
208 }
209 }
210 });
211 return { tree: tree, stale_refs: stale, format: fmt };
212 },
213
214 getRef: function(refId) {
215 return resolveRef(refId);
216 },
217
218 getStaleRefs: function() {
219 return getStaleRefs();
220 },
221
222 findElements: function(query) {
223 var results = [];
224 var maxResults = query.max_results || 10;
225
226 function matches(el) {
227 if (query.text) {
228 var txt = (el.textContent || '').trim();
229 if (query.exact) {
230 if (txt !== query.text) return false;
231 } else {
232 if (txt.toLowerCase().indexOf(query.text.toLowerCase()) === -1) return false;
233 }
234 }
235 if (query.role) {
236 var role = el.getAttribute('role') || inferRole(el);
237 if (role !== query.role) return false;
238 }
239 if (query.test_id) {
240 if (el.getAttribute('data-testid') !== query.test_id) return false;
241 }
242 if (query.css) {
243 try { if (!el.matches(query.css)) return false; } catch(e) { return false; }
244 }
245 if (query.name) {
246 var name = el.getAttribute('aria-label')
247 || el.getAttribute('title')
248 || el.getAttribute('placeholder') || '';
249 if (name.toLowerCase().indexOf(query.name.toLowerCase()) === -1) return false;
250 }
251 if (query.tag) {
252 if (el.tagName.toLowerCase() !== query.tag.toLowerCase()) return false;
253 }
254 if (query.placeholder) {
255 if ((el.getAttribute('placeholder') || '').toLowerCase().indexOf(query.placeholder.toLowerCase()) === -1) return false;
256 }
257 if (query.alt) {
258 if ((el.getAttribute('alt') || '').toLowerCase().indexOf(query.alt.toLowerCase()) === -1) return false;
259 }
260 if (query.title_attr) {
261 if ((el.getAttribute('title') || '').toLowerCase().indexOf(query.title_attr.toLowerCase()) === -1) return false;
262 }
263 if (query.enabled === true && el.disabled) return false;
264 if (query.enabled === false && !el.disabled) return false;
265 return true;
266 }
267
268 function buildResult(node, style) {
269 var existingRef = null;
270 refMap.forEach(function(el, refId) {
271 if (el === node) existingRef = refId;
272 });
273 var ref_id = existingRef || registerRef(node);
274 var role = node.getAttribute('role') || inferRole(node);
275 var rect = node.getBoundingClientRect();
276 var vis = true;
277 if (style) {
278 vis = style.display !== 'none' && style.visibility !== 'hidden';
279 }
280 return {
281 ref_id: ref_id,
282 tag: node.tagName.toLowerCase(),
283 role: role,
284 name: node.getAttribute('aria-label') || node.getAttribute('title') || null,
285 text: (node.textContent || '').trim().substring(0, 100),
286 bounds: { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height) },
287 visible: vis,
288 enabled: !node.disabled,
289 value: node.value || null
290 };
291 }
292
293 if (query.label) {
294 var labels = document.querySelectorAll('label');
295 for (var li = 0; li < labels.length && results.length < maxResults; li++) {
296 var lbl = labels[li];
297 if ((lbl.textContent || '').toLowerCase().indexOf(query.label.toLowerCase()) === -1) continue;
298 var target = null;
299 var forAttr = lbl.getAttribute('for');
300 if (forAttr) {
301 target = document.getElementById(forAttr);
302 }
303 if (!target) {
304 target = lbl.querySelector('input, textarea, select');
305 }
306 if (target) {
307 var ts = window.getComputedStyle(target);
308 results.push(buildResult(target, ts));
309 }
310 }
311 return results;
312 }
313
314 function search(node) {
315 if (results.length >= maxResults) return;
316 if (!node || node.nodeType !== 1) return;
317 var style = window.getComputedStyle(node);
318 if (style.display === 'none' || style.visibility === 'hidden') return;
319
320 if (matches(node)) {
321 results.push(buildResult(node, style));
322 }
323
324 for (var c = 0; c < node.children.length; c++) {
325 search(node.children[c]);
326 }
327 if (node.shadowRoot) {
328 for (var s = 0; s < node.shadowRoot.children.length; s++) {
329 search(node.shadowRoot.children[s]);
330 }
331 }
332 }
333
334 search(document.body);
335 return results;
336 },
337
338 // ── Interactions ─────────────────────────────────────────────────────
339
340 click: function(refId, timeoutMs) {
341 return withAutoWait(refId, timeoutMs, function(el) {
342 el.click();
343 return { ok: true };
344 });
345 },
346
347 doubleClick: function(refId, timeoutMs) {
348 return withAutoWait(refId, timeoutMs, function(el) {
349 el.dispatchEvent(new MouseEvent('dblclick', { bubbles: true, cancelable: true }));
350 return { ok: true };
351 });
352 },
353
354 hover: function(refId, timeoutMs) {
355 return withAutoWait(refId, timeoutMs, function(el) {
356 el.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true }));
357 el.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
358 return { ok: true };
359 });
360 },
361
362 fill: function(refId, value, timeoutMs) {
363 return withAutoWait(refId, timeoutMs, function(el) {
364 if (!el.matches('input, textarea, [contenteditable="true"]')) {
365 return { ok: false, error: 'element is not fillable (not input, textarea, or contenteditable): ' + (el.tagName || '').toLowerCase(), hint: 'CHECK_INPUT' };
366 }
367 var proto = el instanceof HTMLTextAreaElement
368 ? HTMLTextAreaElement.prototype
369 : HTMLInputElement.prototype;
370 var desc = Object.getOwnPropertyDescriptor(proto, 'value');
371 if (desc && desc.set) {
372 desc.set.call(el, value);
373 } else {
374 el.value = value;
375 }
376 el.dispatchEvent(new Event('input', { bubbles: true }));
377 el.dispatchEvent(new Event('change', { bubbles: true }));
378 return { ok: true };
379 });
380 },
381
382 type: function(refId, text, timeoutMs) {
383 return withAutoWait(refId, timeoutMs, function(el) {
384 el.focus();
385 var proto = el instanceof HTMLTextAreaElement
386 ? HTMLTextAreaElement.prototype
387 : HTMLInputElement.prototype;
388 var desc = Object.getOwnPropertyDescriptor(proto, 'value');
389 for (var i = 0; i < text.length; i++) {
390 var ch = text[i];
391 el.dispatchEvent(new KeyboardEvent('keydown', { key: ch, bubbles: true }));
392 el.dispatchEvent(new KeyboardEvent('keypress', { key: ch, bubbles: true }));
393 var current = el.value || '';
394 if (desc && desc.set) {
395 desc.set.call(el, current + ch);
396 } else {
397 el.value = current + ch;
398 }
399 el.dispatchEvent(new InputEvent('input', { bubbles: true, data: ch, inputType: 'insertText' }));
400 el.dispatchEvent(new KeyboardEvent('keyup', { key: ch, bubbles: true }));
401 }
402 el.dispatchEvent(new Event('change', { bubbles: true }));
403 return { ok: true };
404 });
405 },
406
407 pressKey: function(key) {
408 var target = document.activeElement || document.body;
409 var parts = key.split('+');
410 if (parts.length === 1 || (parts.length === 2 && parts[0] === '' && parts[1] === '')) {
411 var k = parts.length === 1 ? key : '+';
412 target.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true }));
413 target.dispatchEvent(new KeyboardEvent('keyup', { key: k, bubbles: true }));
414 return { ok: true };
415 }
416 var finalKey = parts.pop();
417 var mods = { ctrlKey: false, shiftKey: false, altKey: false, metaKey: false };
418 for (var m = 0; m < parts.length; m++) {
419 var mod = parts[m];
420 if (mod === 'Control' || mod === 'Ctrl') mods.ctrlKey = true;
421 else if (mod === 'Shift') mods.shiftKey = true;
422 else if (mod === 'Alt') mods.altKey = true;
423 else if (mod === 'Meta' || mod === 'Command' || mod === 'Cmd') mods.metaKey = true;
424 }
425 var modKeys = [];
426 if (mods.ctrlKey) modKeys.push('Control');
427 if (mods.shiftKey) modKeys.push('Shift');
428 if (mods.altKey) modKeys.push('Alt');
429 if (mods.metaKey) modKeys.push('Meta');
430 for (var i = 0; i < modKeys.length; i++) {
431 target.dispatchEvent(new KeyboardEvent('keydown', { key: modKeys[i], bubbles: true, ctrlKey: mods.ctrlKey, shiftKey: mods.shiftKey, altKey: mods.altKey, metaKey: mods.metaKey }));
432 }
433 target.dispatchEvent(new KeyboardEvent('keydown', { key: finalKey, bubbles: true, ctrlKey: mods.ctrlKey, shiftKey: mods.shiftKey, altKey: mods.altKey, metaKey: mods.metaKey }));
434 target.dispatchEvent(new KeyboardEvent('keyup', { key: finalKey, bubbles: true, ctrlKey: mods.ctrlKey, shiftKey: mods.shiftKey, altKey: mods.altKey, metaKey: mods.metaKey }));
435 for (var j = modKeys.length - 1; j >= 0; j--) {
436 target.dispatchEvent(new KeyboardEvent('keyup', { key: modKeys[j], bubbles: true, ctrlKey: mods.ctrlKey, shiftKey: mods.shiftKey, altKey: mods.altKey, metaKey: mods.metaKey }));
437 }
438 return { ok: true };
439 },
440
441 selectOption: function(refId, values, timeoutMs) {
442 return withAutoWait(refId, timeoutMs, function(el) {
443 if (el.tagName !== 'SELECT') {
444 return { ok: false, error: 'element is not a <select>', hint: 'CHECK_INPUT' };
445 }
446 var valSet = new Set(values);
447 for (var i = 0; i < el.options.length; i++) {
448 el.options[i].selected = valSet.has(el.options[i].value);
449 }
450 el.dispatchEvent(new Event('change', { bubbles: true }));
451 return { ok: true };
452 });
453 },
454
455 scrollTo: function(refId, x, y, timeoutMs) {
456 if (refId) {
457 return withAutoWait(refId, timeoutMs, function(el) {
458 el.scrollIntoView({ behavior: 'smooth', block: 'center' });
459 return { ok: true };
460 });
461 } else {
462 window.scrollTo({ left: x || 0, top: y || 0, behavior: 'smooth' });
463 return Promise.resolve({ ok: true });
464 }
465 },
466
467 focusElement: function(refId, timeoutMs) {
468 return withAutoWait(refId, timeoutMs, function(el) {
469 el.focus();
470 return { ok: true, tag: el.tagName.toLowerCase() };
471 });
472 },
473
474 // ── IPC Log ──────────────────────────────────────────────────────────
475
476 getIpcLog: function(limit) {
477 var ipcPrefix = 'http://ipc.localhost/';
478 var victauriPrefix = 'plugin%3Avictauri%7C';
479 var entries = [];
480 for (var i = 0; i < networkLog.length; i++) {
481 var n = networkLog[i];
482 if (n.url.indexOf(ipcPrefix) !== 0) continue;
483 var raw = n.url.substring(ipcPrefix.length);
484 if (raw.indexOf(victauriPrefix) === 0) continue;
485 var command;
486 try { command = decodeURIComponent(raw); } catch(e) { command = raw; }
487 entries.push({
488 id: n.id,
489 command: command,
490 args: n.request_args || {},
491 timestamp: n.timestamp,
492 status: n.status === 200 ? 'ok' : (n.status === 'pending' ? 'pending' : 'error'),
493 duration_ms: n.duration_ms,
494 result: n.response_body || null,
495 error: n.status !== 200 && n.status !== 'pending' ? 'HTTP ' + n.status : null,
496 });
497 }
498 if (limit) return entries.slice(-limit);
499 return entries;
500 },
501
502 clearIpcLog: function() {
503 var ipcPrefix = 'http://ipc.localhost/';
504 for (var i = networkLog.length - 1; i >= 0; i--) {
505 if (networkLog[i].url.indexOf(ipcPrefix) === 0) networkLog.splice(i, 1);
506 }
507 },
508
509 waitForIpcComplete: function(timeoutMs) {
510 var log = window.__VICTAURI__.getIpcLog();
511 if (log.length > 0) {
512 var last = log[log.length - 1];
513 if (last.duration_ms !== null && last.duration_ms !== undefined && last.result !== null) {
514 return Promise.resolve(true);
515 }
516 }
517 return new Promise(function(resolve) {
518 var timer = setTimeout(function() {
519 var idx = ipcWaiters.indexOf(waiterFn);
520 if (idx !== -1) ipcWaiters.splice(idx, 1);
521 resolve(false);
522 }, timeoutMs || 500);
523 function waiterFn() {
524 clearTimeout(timer);
525 resolve(true);
526 }
527 ipcWaiters.push(waiterFn);
528 });
529 },
530
531 // ── Console ──────────────────────────────────────────────────────────
532
533 getConsoleLogs: function(since) {
534 if (since) return consoleLogs.filter(function(l) { return l.timestamp >= since; });
535 return consoleLogs;
536 },
537
538 clearConsoleLogs: function() {
539 consoleLogs.length = 0;
540 },
541
542 // ── Mutations ────────────────────────────────────────────────────────
543
544 getMutationLog: function(since) {
545 if (since) return mutationLog.filter(function(m) { return m.timestamp >= since; });
546 return mutationLog;
547 },
548
549 clearMutationLog: function() {
550 mutationLog.length = 0;
551 },
552
553 // ── Network ──────────────────────────────────────────────────────────
554
555 getNetworkLog: function(filter, limit) {
556 var log = networkLog;
557 if (filter) {
558 log = log.filter(function(e) { return e.url.indexOf(filter) !== -1; });
559 }
560 if (limit) log = log.slice(-limit);
561 return log;
562 },
563
564 clearNetworkLog: function() {
565 networkLog.length = 0;
566 },
567
568 // ── Storage ──────────────────────────────────────────────────────────
569
570 getLocalStorage: function(key) {
571 if (key !== undefined && key !== null) {
572 var v = localStorage.getItem(key);
573 try { return JSON.parse(v); } catch(e) { return v; }
574 }
575 var obj = {};
576 for (var i = 0; i < localStorage.length; i++) {
577 var k = localStorage.key(i);
578 var val = localStorage.getItem(k);
579 try { obj[k] = JSON.parse(val); } catch(e) { obj[k] = val; }
580 }
581 return obj;
582 },
583
584 setLocalStorage: function(key, value) {
585 localStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value));
586 return { ok: true };
587 },
588
589 deleteLocalStorage: function(key) {
590 localStorage.removeItem(key);
591 return { ok: true };
592 },
593
594 getSessionStorage: function(key) {
595 if (key !== undefined && key !== null) {
596 var v = sessionStorage.getItem(key);
597 try { return JSON.parse(v); } catch(e) { return v; }
598 }
599 var obj = {};
600 for (var i = 0; i < sessionStorage.length; i++) {
601 var k = sessionStorage.key(i);
602 var val = sessionStorage.getItem(k);
603 try { obj[k] = JSON.parse(val); } catch(e) { obj[k] = val; }
604 }
605 return obj;
606 },
607
608 setSessionStorage: function(key, value) {
609 sessionStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value));
610 return { ok: true };
611 },
612
613 deleteSessionStorage: function(key) {
614 sessionStorage.removeItem(key);
615 return { ok: true };
616 },
617
618 getCookies: function() {
619 if (!document.cookie) return [];
620 return document.cookie.split(';').map(function(c) {
621 var parts = c.trim().split('=');
622 return { name: parts[0], value: parts.slice(1).join('=') };
623 });
624 },
625
626 // ── Navigation ───────────────────────────────────────────────────────
627
628 getNavigationLog: function() {
629 return navigationLog;
630 },
631
632 navigate: function(url) {
633 window.location.href = url;
634 return { ok: true };
635 },
636
637 navigateBack: function() {
638 history.back();
639 return { ok: true };
640 },
641
642 // ── Dialogs ──────────────────────────────────────────────────────────
643
644 getDialogLog: function() {
645 return dialogLog;
646 },
647
648 clearDialogLog: function() {
649 dialogLog.length = 0;
650 },
651
652 setDialogAutoResponse: function(type, action, text) {
653 dialogAutoResponses[type] = { action: action, text: text };
654 return { ok: true };
655 },
656
657 // ── Combined Event Stream ────────────────────────────────────────────
658
659 getEventStream: function(since) {
660 var events = [];
661 var ts = since || 0;
662
663 consoleLogs.forEach(function(l) {
664 if (l.timestamp >= ts) {
665 events.push({ type: 'console', level: l.level, message: l.message, timestamp: l.timestamp });
666 }
667 });
668
669 mutationLog.forEach(function(m) {
670 if (m.timestamp >= ts) {
671 events.push({ type: 'dom_mutation', count: m.count, timestamp: m.timestamp });
672 }
673 });
674
675 var ipcPrefix = 'http://ipc.localhost/';
676 var victauriPrefix = 'plugin%3Avictauri%7C';
677 networkLog.forEach(function(n) {
678 if (n.timestamp >= ts && n.url.indexOf(ipcPrefix) === 0) {
679 var raw = n.url.substring(ipcPrefix.length);
680 if (raw.indexOf(victauriPrefix) === 0) return;
681 var cmd; try { cmd = decodeURIComponent(raw); } catch(e) { cmd = raw; }
682 events.push({ type: 'ipc', command: cmd, status: n.status === 200 ? 'ok' : (n.status === 'pending' ? 'pending' : 'error'), duration_ms: n.duration_ms, timestamp: n.timestamp });
683 }
684 });
685
686 networkLog.forEach(function(n) {
687 if (n.timestamp >= ts) {
688 events.push({ type: 'network', method: n.method, url: n.url, status: n.status, duration_ms: n.duration_ms, timestamp: n.timestamp });
689 }
690 });
691
692 navigationLog.forEach(function(n) {
693 if (n.timestamp >= ts) {
694 events.push({ type: 'navigation', url: n.url, nav_type: n.type, timestamp: n.timestamp });
695 }
696 });
697
698 interactionLog.forEach(function(i) {
699 if (i.timestamp >= ts) {
700 events.push({ type: 'dom_interaction', action: i.action, selector: i.selector, value: i.value, timestamp: i.timestamp });
701 }
702 });
703
704 events.sort(function(a, b) { return a.timestamp - b.timestamp; });
705 return events;
706 },
707
708 // ── Wait ─────────────────────────────────────────────────────────────
709
710 waitFor: function(opts) {
711 return new Promise(function(resolve) {
712 var timeout = opts.timeout_ms || 10000;
713 var poll = opts.poll_ms || 200;
714 var start = Date.now();
715
716 function check() {
717 var elapsed = Date.now() - start;
718 if (elapsed >= timeout) {
719 resolve({ ok: false, error: 'timeout after ' + timeout + 'ms', elapsed_ms: elapsed });
720 return;
721 }
722
723 function getFullText(root) {
724 var text = root.innerText || '';
725 var els = root.querySelectorAll('*');
726 for (var j = 0; j < els.length; j++) {
727 if (els[j].shadowRoot) text += ' ' + getFullText(els[j].shadowRoot);
728 }
729 return text;
730 }
731 var met = false;
732 if (opts.condition === 'text' && opts.value) {
733 met = getFullText(document.body).indexOf(opts.value) !== -1;
734 } else if (opts.condition === 'text_gone' && opts.value) {
735 met = getFullText(document.body).indexOf(opts.value) === -1;
736 } else if (opts.condition === 'selector' && opts.value) {
737 met = !!document.querySelector(opts.value);
738 } else if (opts.condition === 'selector_gone' && opts.value) {
739 met = !document.querySelector(opts.value);
740 } else if (opts.condition === 'url' && opts.value) {
741 met = window.location.href.indexOf(opts.value) !== -1;
742 } else if (opts.condition === 'ipc_idle') {
743 met = networkLog.filter(function(n) { return n.url.indexOf('http://ipc.localhost/') === 0; }).every(function(n) { return n.status !== 'pending'; });
744 } else if (opts.condition === 'network_idle') {
745 met = networkLog.every(function(n) { return n.status !== 'pending'; });
746 }
747
748 if (met) {
749 resolve({ ok: true, elapsed_ms: Date.now() - start });
750 } else {
751 setTimeout(check, poll);
752 }
753 }
754 check();
755 });
756 },
757 // ── CSS / Style Introspection ────────────────────────────────────────
758
759 getStyles: function(refId, properties) {
760 var el = resolveRef(refId);
761 if (!el) return { error: 'ref not found: ' + refId };
762 var computed = window.getComputedStyle(el);
763 var result = {};
764 if (properties && properties.length > 0) {
765 for (var i = 0; i < properties.length; i++) {
766 result[properties[i]] = computed.getPropertyValue(properties[i]);
767 }
768 } else {
769 var important = ['display','position','width','height','margin','padding',
770 'color','background-color','font-size','font-family','font-weight',
771 'border','border-radius','opacity','visibility','overflow','z-index',
772 'flex-direction','justify-content','align-items','gap','grid-template-columns',
773 'box-shadow','transform','transition','cursor','pointer-events','text-align',
774 'line-height','letter-spacing','white-space','text-overflow','max-width',
775 'max-height','min-width','min-height','top','right','bottom','left'];
776 for (var i = 0; i < important.length; i++) {
777 var v = computed.getPropertyValue(important[i]);
778 if (v && v !== '' && v !== 'none' && v !== 'normal' && v !== 'auto' && v !== '0px' && v !== 'rgba(0, 0, 0, 0)') {
779 result[important[i]] = v;
780 }
781 }
782 }
783 return { ref_id: refId, tag: el.tagName.toLowerCase(), styles: result };
784 },
785
786 getBoundingBoxes: function(refIds) {
787 var results = [];
788 for (var i = 0; i < refIds.length; i++) {
789 var el = resolveRef(refIds[i]);
790 if (!el) { results.push({ ref_id: refIds[i], error: 'ref not found' }); continue; }
791 var rect = el.getBoundingClientRect();
792 var computed = window.getComputedStyle(el);
793 results.push({
794 ref_id: refIds[i],
795 tag: el.tagName.toLowerCase(),
796 x: Math.round(rect.x),
797 y: Math.round(rect.y),
798 width: Math.round(rect.width),
799 height: Math.round(rect.height),
800 margin: {
801 top: parseInt(computed.marginTop) || 0,
802 right: parseInt(computed.marginRight) || 0,
803 bottom: parseInt(computed.marginBottom) || 0,
804 left: parseInt(computed.marginLeft) || 0,
805 },
806 padding: {
807 top: parseInt(computed.paddingTop) || 0,
808 right: parseInt(computed.paddingRight) || 0,
809 bottom: parseInt(computed.paddingBottom) || 0,
810 left: parseInt(computed.paddingLeft) || 0,
811 },
812 border: {
813 top: parseInt(computed.borderTopWidth) || 0,
814 right: parseInt(computed.borderRightWidth) || 0,
815 bottom: parseInt(computed.borderBottomWidth) || 0,
816 left: parseInt(computed.borderLeftWidth) || 0,
817 },
818 });
819 }
820 return results;
821 },
822
823 // ── Visual Debug Overlays ────────────────────────────────────────────
824
825 highlightElement: function(refId, color, label) {
826 var el = resolveRef(refId);
827 if (!el) return { error: 'ref not found: ' + refId };
828 var c = color || 'rgba(255, 0, 0, 0.3)';
829 var overlay = document.createElement('div');
830 overlay.className = '__victauri_highlight__';
831 overlay.setAttribute('data-victauri-ref', refId);
832 var rect = el.getBoundingClientRect();
833 overlay.style.cssText = 'position:fixed;pointer-events:none;z-index:2147483647;' +
834 'border:2px solid ' + c + ';background:' + c + ';' +
835 'left:' + rect.left + 'px;top:' + rect.top + 'px;' +
836 'width:' + rect.width + 'px;height:' + rect.height + 'px;' +
837 'transition:all 0.2s ease;';
838 if (label) {
839 var tag = document.createElement('span');
840 tag.textContent = label;
841 tag.style.cssText = 'position:absolute;top:-20px;left:0;background:#222;color:#fff;' +
842 'font-size:11px;padding:2px 6px;border-radius:3px;white-space:nowrap;font-family:monospace;';
843 overlay.appendChild(tag);
844 }
845 document.body.appendChild(overlay);
846 return { ok: true, ref_id: refId };
847 },
848
849 clearHighlights: function() {
850 var overlays = document.querySelectorAll('.__victauri_highlight__');
851 for (var i = 0; i < overlays.length; i++) overlays[i].remove();
852 return { ok: true, removed: overlays.length };
853 },
854
855 // ── CSS Injection ────────────────────────────────────────────────────
856
857 injectCss: function(css) {
858 var existing = document.getElementById('__victauri_injected_css__');
859 if (existing) existing.remove();
860 var style = document.createElement('style');
861 style.id = '__victauri_injected_css__';
862 style.textContent = css;
863 document.head.appendChild(style);
864 return { ok: true, length: css.length };
865 },
866
867 removeInjectedCss: function() {
868 var existing = document.getElementById('__victauri_injected_css__');
869 if (!existing) return { ok: true, removed: false };
870 existing.remove();
871 return { ok: true, removed: true };
872 },
873
874 // ── Accessibility Audit ──────────────────────────────────────────────
875
876 auditAccessibility: function() {
877 var violations = [];
878 var warnings = [];
879
880 // Images without alt text
881 var imgs = document.querySelectorAll('img');
882 for (var i = 0; i < imgs.length; i++) {
883 if (!imgs[i].hasAttribute('alt')) {
884 violations.push({ rule: 'img-alt', severity: 'critical', element: describeEl(imgs[i]),
885 message: 'Image missing alt attribute' });
886 } else if (imgs[i].alt.trim() === '') {
887 warnings.push({ rule: 'img-alt-empty', severity: 'minor', element: describeEl(imgs[i]),
888 message: 'Image has empty alt (ok if decorative)' });
889 }
890 }
891
892 // Form inputs without labels
893 var inputs = document.querySelectorAll('input, select, textarea');
894 for (var i = 0; i < inputs.length; i++) {
895 var inp = inputs[i];
896 if (inp.type === 'hidden') continue;
897 var hasLabel = false;
898 if (inp.id) {
899 try { hasLabel = !!document.querySelector('label[for=\"' + CSS.escape(inp.id) + '\"]'); }
900 catch(e) { /* malformed id — skip */ }
901 }
902 var hasAria = inp.getAttribute('aria-label') || inp.getAttribute('aria-labelledby');
903 var hasTitle = inp.title;
904 var hasPlaceholder = inp.placeholder;
905 if (!hasLabel && !hasAria && !hasTitle && !hasPlaceholder) {
906 violations.push({ rule: 'input-label', severity: 'serious', element: describeEl(inp),
907 message: 'Form input has no accessible label' });
908 }
909 }
910
911 // Buttons without accessible text
912 var buttons = document.querySelectorAll('button, [role="button"]');
913 for (var i = 0; i < buttons.length; i++) {
914 var btn = buttons[i];
915 var text = (btn.textContent || '').trim();
916 var ariaLabel = btn.getAttribute('aria-label');
917 var ariaLabelledBy = btn.getAttribute('aria-labelledby');
918 if (!text && !ariaLabel && !ariaLabelledBy && !btn.title) {
919 var hasImg = btn.querySelector('img[alt], svg[aria-label]');
920 if (!hasImg) {
921 violations.push({ rule: 'button-name', severity: 'serious', element: describeEl(btn),
922 message: 'Button has no accessible name' });
923 }
924 }
925 }
926
927 // Links without text
928 var links = document.querySelectorAll('a[href]');
929 for (var i = 0; i < links.length; i++) {
930 var link = links[i];
931 var text = (link.textContent || '').trim();
932 var ariaLabel = link.getAttribute('aria-label');
933 if (!text && !ariaLabel && !link.title) {
934 violations.push({ rule: 'link-name', severity: 'serious', element: describeEl(link),
935 message: 'Link has no accessible text' });
936 }
937 }
938
939 // Missing document language
940 if (!document.documentElement.lang) {
941 violations.push({ rule: 'html-lang', severity: 'serious', element: '<html>',
942 message: 'Document missing lang attribute' });
943 }
944
945 // Heading hierarchy
946 var headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
947 var prevLevel = 0;
948 for (var i = 0; i < headings.length; i++) {
949 var level = parseInt(headings[i].tagName.charAt(1));
950 if (level > prevLevel + 1 && prevLevel > 0) {
951 warnings.push({ rule: 'heading-order', severity: 'moderate', element: describeEl(headings[i]),
952 message: 'Heading level skipped from h' + prevLevel + ' to h' + level });
953 }
954 prevLevel = level;
955 }
956
957 // Missing page title
958 if (!document.title || document.title.trim() === '') {
959 violations.push({ rule: 'document-title', severity: 'serious', element: '<head>',
960 message: 'Document has no title' });
961 }
962
963 // Color contrast (simplified — checks text elements against backgrounds)
964 var textEls = document.querySelectorAll('p, span, a, button, h1, h2, h3, h4, h5, h6, li, td, th, label, div');
965 var contrastIssues = 0;
966 for (var i = 0; i < textEls.length && contrastIssues < 10; i++) {
967 var el = textEls[i];
968 if (!el.textContent || el.textContent.trim() === '') continue;
969 if (el.children.length > 0 && el.children[0].textContent === el.textContent) continue;
970 var cs = window.getComputedStyle(el);
971 var fg = parseColor(cs.color);
972 var bg = parseColor(cs.backgroundColor);
973 if (fg && bg && bg.a > 0) {
974 var ratio = contrastRatio(fg, bg);
975 var fontSize = parseFloat(cs.fontSize);
976 var isBold = parseInt(cs.fontWeight) >= 700;
977 var isLarge = fontSize >= 24 || (fontSize >= 18.66 && isBold);
978 var threshold = isLarge ? 3 : 4.5;
979 if (ratio < threshold) {
980 contrastIssues++;
981 warnings.push({ rule: 'color-contrast', severity: 'serious',
982 element: describeEl(el),
983 message: 'Contrast ratio ' + ratio.toFixed(2) + ':1 (needs ' + threshold + ':1)',
984 details: { fg: cs.color, bg: cs.backgroundColor, ratio: ratio.toFixed(2) } });
985 }
986 }
987 }
988
989 // ARIA role validity
990 var ariaEls = document.querySelectorAll('[role]');
991 var validRoles = new Set(['alert','alertdialog','application','article','banner','button',
992 'cell','checkbox','columnheader','combobox','complementary','contentinfo','definition',
993 'dialog','directory','document','feed','figure','form','grid','gridcell','group',
994 'heading','img','link','list','listbox','listitem','log','main','marquee','math',
995 'menu','menubar','menuitem','menuitemcheckbox','menuitemradio','meter','navigation',
996 'none','note','option','presentation','progressbar','radio','radiogroup','region',
997 'row','rowgroup','rowheader','scrollbar','search','searchbox','separator','slider',
998 'spinbutton','status','switch','tab','table','tablist','tabpanel','term','textbox',
999 'timer','toolbar','tooltip','tree','treegrid','treeitem']);
1000 for (var i = 0; i < ariaEls.length; i++) {
1001 var role = ariaEls[i].getAttribute('role');
1002 if (role && !validRoles.has(role)) {
1003 warnings.push({ rule: 'aria-role', severity: 'moderate', element: describeEl(ariaEls[i]),
1004 message: 'Invalid ARIA role: ' + role });
1005 }
1006 }
1007
1008 // Tab index > 0
1009 var tabbable = document.querySelectorAll('[tabindex]');
1010 for (var i = 0; i < tabbable.length; i++) {
1011 var ti = parseInt(tabbable[i].getAttribute('tabindex'));
1012 if (ti > 0) {
1013 warnings.push({ rule: 'tabindex-positive', severity: 'moderate', element: describeEl(tabbable[i]),
1014 message: 'Positive tabindex disrupts natural tab order (tabindex=' + ti + ')' });
1015 }
1016 }
1017
1018 return {
1019 violations: violations,
1020 warnings: warnings,
1021 summary: {
1022 critical: violations.filter(function(v) { return v.severity === 'critical'; }).length,
1023 serious: violations.filter(function(v) { return v.severity === 'serious'; }).length + warnings.filter(function(w) { return w.severity === 'serious'; }).length,
1024 moderate: warnings.filter(function(w) { return w.severity === 'moderate'; }).length,
1025 minor: warnings.filter(function(w) { return w.severity === 'minor'; }).length,
1026 total: violations.length + warnings.length,
1027 }
1028 };
1029 },
1030
1031 // ── Performance Metrics ──────────────────────────────────────────────
1032
1033 getPerformanceMetrics: function() {
1034 var result = {};
1035
1036 // Navigation timing
1037 var nav = performance.getEntriesByType('navigation')[0];
1038 if (nav) {
1039 result.navigation = {
1040 dns_ms: Math.round(nav.domainLookupEnd - nav.domainLookupStart),
1041 connect_ms: Math.round(nav.connectEnd - nav.connectStart),
1042 ttfb_ms: Math.round(nav.responseStart - nav.requestStart),
1043 response_ms: Math.round(nav.responseEnd - nav.responseStart),
1044 dom_interactive_ms: Math.round(nav.domInteractive - nav.startTime),
1045 dom_complete_ms: Math.round(nav.domComplete - nav.startTime),
1046 load_event_ms: Math.round(nav.loadEventEnd - nav.startTime),
1047 transfer_size: nav.transferSize,
1048 encoded_body_size: nav.encodedBodySize,
1049 decoded_body_size: nav.decodedBodySize,
1050 };
1051 }
1052
1053 // Resource summary
1054 var resources = performance.getEntriesByType('resource');
1055 var byType = {};
1056 var totalTransfer = 0;
1057 for (var i = 0; i < resources.length; i++) {
1058 var r = resources[i];
1059 var type = r.initiatorType || 'other';
1060 if (!byType[type]) byType[type] = { count: 0, total_ms: 0, total_bytes: 0 };
1061 byType[type].count++;
1062 byType[type].total_ms += r.duration;
1063 byType[type].total_bytes += r.transferSize || 0;
1064 totalTransfer += r.transferSize || 0;
1065 }
1066 result.resources = {
1067 total_count: resources.length,
1068 total_transfer_bytes: totalTransfer,
1069 by_type: byType,
1070 slowest: resources.sort(function(a, b) { return b.duration - a.duration; }).slice(0, 5).map(function(r) {
1071 return { name: r.name.split('/').pop().split('?')[0], duration_ms: Math.round(r.duration), size: r.transferSize || 0, type: r.initiatorType };
1072 }),
1073 };
1074
1075 // Paint timing
1076 var paints = performance.getEntriesByType('paint');
1077 result.paint = {};
1078 for (var i = 0; i < paints.length; i++) {
1079 result.paint[paints[i].name] = Math.round(paints[i].startTime);
1080 }
1081
1082 // Memory (Chrome/Edge)
1083 if (performance.memory) {
1084 result.js_heap = {
1085 used_mb: Math.round(performance.memory.usedJSHeapSize / 1048576 * 100) / 100,
1086 total_mb: Math.round(performance.memory.totalJSHeapSize / 1048576 * 100) / 100,
1087 limit_mb: Math.round(performance.memory.jsHeapSizeLimit / 1048576 * 100) / 100,
1088 };
1089 }
1090
1091 // Long tasks (if PerformanceObserver captured any)
1092 if (longTasks.length > 0) {
1093 result.long_tasks = {
1094 count: longTasks.length,
1095 total_ms: Math.round(longTasks.reduce(function(s, t) { return s + t.duration; }, 0)),
1096 worst_ms: Math.round(Math.max.apply(null, longTasks.map(function(t) { return t.duration; }))),
1097 };
1098 }
1099
1100 // DOM stats
1101 result.dom = {
1102 elements: document.querySelectorAll('*').length,
1103 max_depth: (function() { var d = 0; var walk = function(el, depth) { if (depth > d) d = depth; for (var i = 0; i < el.children.length && i < 5; i++) walk(el.children[i], depth + 1); }; walk(document.body, 0); return d; })(),
1104 event_listeners: listenerCount,
1105 };
1106
1107 return result;
1108 },
1109
1110 getDiagnostics: function() {
1111 var diag = { warnings: [], info: {} };
1112
1113 // Service worker detection
1114 if (navigator.serviceWorker && navigator.serviceWorker.controller) {
1115 diag.warnings.push({
1116 id: 'service-worker-active',
1117 severity: 'high',
1118 message: 'Active service worker detected — may intercept fetch calls to ipc.localhost, causing IPC log gaps',
1119 details: { scope: navigator.serviceWorker.controller.scriptURL }
1120 });
1121 }
1122
1123 // Closed shadow DOM detection
1124 var allEls = document.querySelectorAll('*');
1125 var closedShadowCount = 0;
1126 for (var i = 0; i < allEls.length; i++) {
1127 if (allEls[i].attachShadow && !allEls[i].shadowRoot) {
1128 var tagName = allEls[i].tagName.toLowerCase();
1129 if (tagName.includes('-')) closedShadowCount++;
1130 }
1131 }
1132 if (closedShadowCount > 0) {
1133 diag.warnings.push({
1134 id: 'closed-shadow-dom',
1135 severity: 'medium',
1136 message: closedShadowCount + ' custom element(s) may use closed shadow DOM — their contents are invisible to dom_snapshot',
1137 details: { count: closedShadowCount }
1138 });
1139 }
1140
1141 // iframe detection
1142 var iframes = document.querySelectorAll('iframe');
1143 if (iframes.length > 0) {
1144 diag.warnings.push({
1145 id: 'iframes-present',
1146 severity: 'medium',
1147 message: iframes.length + ' iframe(s) found — Victauri bridge is not injected inside iframes (Tauri limitation)',
1148 details: { count: iframes.length, srcs: Array.from(iframes).slice(0, 5).map(function(f) { return f.src || '(empty)'; }) }
1149 });
1150 }
1151
1152 // DOM size warning
1153 var elementCount = allEls.length;
1154 if (elementCount > 5000) {
1155 diag.warnings.push({
1156 id: 'large-dom',
1157 severity: 'low',
1158 message: 'DOM has ' + elementCount + ' elements — dom_snapshot may be slow (>100ms)',
1159 details: { count: elementCount }
1160 });
1161 }
1162
1163 // CSP detection (best-effort)
1164 var cspMeta = document.querySelector('meta[http-equiv="Content-Security-Policy"]');
1165 if (cspMeta) {
1166 var cspContent = cspMeta.getAttribute('content') || '';
1167 diag.info.csp_meta = cspContent;
1168 if (cspContent.indexOf('unsafe-eval') === -1 && cspContent.indexOf('script-src') !== -1) {
1169 diag.info.csp_note = 'CSP restricts eval — Victauri uses native webview.eval() which bypasses CSP on most platforms';
1170 }
1171 }
1172
1173 // Environment info
1174 diag.info.bridge_version = window.__VICTAURI__.version;
1175 diag.info.user_agent = navigator.userAgent;
1176 diag.info.url = window.location.href;
1177 diag.info.dom_elements = elementCount;
1178 diag.info.open_shadow_roots = (function() { var c = 0; for (var i = 0; i < allEls.length; i++) { if (allEls[i].shadowRoot) c++; } return c; })();
1179 diag.info.event_listeners = listenerCount;
1180 diag.info.protocol = window.location.protocol;
1181
1182 return diag;
1183 },
1184 };
1185
1186 try {
1187 Object.freeze(window.__VICTAURI__);
1188 Object.defineProperty(window, '__VICTAURI__', {
1189 value: window.__VICTAURI__,
1190 configurable: false,
1191 writable: false,
1192 });
1193 } catch(e) {}
1194
1195 // ── Accessibility Helpers ────────────────────────────────────────────────
1196
1197 function describeEl(el) {
1198 var s = '<' + el.tagName.toLowerCase();
1199 if (el.id) s += ' id="' + el.id + '"';
1200 if (el.className && typeof el.className === 'string') {
1201 var cls = el.className.trim();
1202 if (cls) s += ' class="' + cls.substring(0, 50) + '"';
1203 }
1204 s += '>';
1205 return s;
1206 }
1207
1208 function parseColor(str) {
1209 if (!str) return null;
1210 var m = str.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
1211 if (!m) return null;
1212 return { r: parseInt(m[1]), g: parseInt(m[2]), b: parseInt(m[3]), a: m[4] !== undefined ? parseFloat(m[4]) : 1 };
1213 }
1214
1215 function luminance(c) {
1216 var rs = c.r / 255, gs = c.g / 255, bs = c.b / 255;
1217 var r = rs <= 0.03928 ? rs / 12.92 : Math.pow((rs + 0.055) / 1.055, 2.4);
1218 var g = gs <= 0.03928 ? gs / 12.92 : Math.pow((gs + 0.055) / 1.055, 2.4);
1219 var b = bs <= 0.03928 ? bs / 12.92 : Math.pow((bs + 0.055) / 1.055, 2.4);
1220 return 0.2126 * r + 0.7152 * g + 0.0722 * b;
1221 }
1222
1223 function contrastRatio(fg, bg) {
1224 var l1 = luminance(fg), l2 = luminance(bg);
1225 var lighter = Math.max(l1, l2), darker = Math.min(l1, l2);
1226 return (lighter + 0.05) / (darker + 0.05);
1227 }
1228
1229 // ── Long Task Observer ──────────────────────────────────────────────────
1230
1231 try {
1232 var ltObserver = new PerformanceObserver(function(list) {
1233 var entries = list.getEntries();
1234 for (var i = 0; i < entries.length; i++) {
1235 longTasks.push({ duration: entries[i].duration, startTime: entries[i].startTime });
1236 if (longTasks.length > CAP_LONG_TASKS) longTasks.shift();
1237 }
1238 });
1239 ltObserver.observe({ type: 'longtask', buffered: true });
1240 } catch(e) {}
1241
1242 // ── Event Listener Counter ──────────────────────────────────────────────
1243
1244 (function() {
1245 var origAdd = EventTarget.prototype.addEventListener;
1246 var origRemove = EventTarget.prototype.removeEventListener;
1247 EventTarget.prototype.addEventListener = function() {
1248 listenerCount++;
1249 return origAdd.apply(this, arguments);
1250 };
1251 EventTarget.prototype.removeEventListener = function() {
1252 if (listenerCount > 0) listenerCount--;
1253 return origRemove.apply(this, arguments);
1254 };
1255 })();
1256
1257 // ── DOM Walking ──────────────────────────────────────────────────────────
1258
1259 function walkDom(node) {
1260 if (!node || node.nodeType !== 1) return null;
1261
1262 var style = window.getComputedStyle(node);
1263 var visible = style.display !== 'none'
1264 && style.visibility !== 'hidden'
1265 && style.opacity !== '0';
1266
1267 if (!visible) return null;
1268
1269 var ref_id = registerRef(node);
1270
1271 var rect = node.getBoundingClientRect();
1272 var role = node.getAttribute('role') || inferRole(node);
1273 var name = node.getAttribute('aria-label')
1274 || node.getAttribute('title')
1275 || node.getAttribute('placeholder')
1276 || (node.tagName === 'BUTTON' ? node.textContent.trim().substring(0, 80) : null)
1277 || (node.tagName === 'A' ? node.textContent.trim().substring(0, 80) : null);
1278
1279 var element = {
1280 ref_id: ref_id,
1281 tag: node.tagName.toLowerCase(),
1282 role: role,
1283 name: name,
1284 text: getDirectText(node),
1285 value: (node.tagName === 'INPUT' && (node.getAttribute('type') || '').toLowerCase() === 'password') ? '[REDACTED]' : (node.value || null),
1286 enabled: !node.disabled,
1287 visible: true,
1288 focusable: node.tabIndex >= 0 || ['INPUT','BUTTON','SELECT','TEXTAREA','A'].indexOf(node.tagName) !== -1,
1289 bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
1290 children: [],
1291 attributes: {}
1292 };
1293
1294 var interestingAttrs = ['data-testid', 'id', 'type', 'href', 'src', 'checked', 'selected'];
1295 for (var a = 0; a < interestingAttrs.length; a++) {
1296 if (node.hasAttribute(interestingAttrs[a])) {
1297 element.attributes[interestingAttrs[a]] = node.getAttribute(interestingAttrs[a]);
1298 }
1299 }
1300
1301 for (var c = 0; c < node.children.length; c++) {
1302 var childEl = walkDom(node.children[c]);
1303 if (childEl) element.children.push(childEl);
1304 }
1305
1306 if (node.shadowRoot) {
1307 for (var s = 0; s < node.shadowRoot.children.length; s++) {
1308 var shadowChild = walkDom(node.shadowRoot.children[s]);
1309 if (shadowChild) element.children.push(shadowChild);
1310 }
1311 }
1312
1313 return element;
1314 }
1315
1316 function walkDomCompact(node, depth) {
1317 if (!node || node.nodeType !== 1) return '';
1318
1319 var style = window.getComputedStyle(node);
1320 var visible = style.display !== 'none'
1321 && style.visibility !== 'hidden'
1322 && style.opacity !== '0';
1323
1324 if (!visible) return '';
1325
1326 var ref_id = registerRef(node);
1327 var indent = '';
1328 for (var d = 0; d < depth; d++) indent += ' ';
1329
1330 var role = node.getAttribute('role') || inferRole(node);
1331 var name = node.getAttribute('aria-label')
1332 || node.getAttribute('title')
1333 || node.getAttribute('placeholder')
1334 || '';
1335 var text = getDirectText(node) || '';
1336 var tag = node.tagName.toLowerCase();
1337
1338 var line = indent + '[' + ref_id + '] ';
1339
1340 if (role && role !== tag) {
1341 line += role;
1342 } else {
1343 line += tag;
1344 }
1345
1346 if (name) {
1347 line += ' "' + name.substring(0, 60) + '"';
1348 } else if (text && text.length <= 60) {
1349 line += ' "' + text + '"';
1350 } else if (text) {
1351 line += ' "' + text.substring(0, 57) + '..."';
1352 }
1353
1354 if (node.disabled) line += ' [disabled]';
1355 if (node.value) {
1356 var isPassword = node.tagName === 'INPUT' && (node.getAttribute('type') || '').toLowerCase() === 'password';
1357 line += ' value=' + JSON.stringify(isPassword ? '[REDACTED]' : node.value.substring(0, 40));
1358 }
1359
1360 var testId = node.getAttribute('data-testid');
1361 if (testId) line += ' @' + testId;
1362
1363 var type = node.getAttribute('type');
1364 if (type && tag === 'input') line += ' type=' + type;
1365
1366 var href = node.getAttribute('href');
1367 if (href && tag === 'a') line += ' href=' + href.substring(0, 60);
1368
1369 var result = line + '\n';
1370
1371 for (var c = 0; c < node.children.length; c++) {
1372 result += walkDomCompact(node.children[c], depth + 1);
1373 }
1374
1375 if (node.shadowRoot) {
1376 for (var s = 0; s < node.shadowRoot.children.length; s++) {
1377 result += walkDomCompact(node.shadowRoot.children[s], depth + 1);
1378 }
1379 }
1380
1381 return result;
1382 }
1383
1384 function inferRole(node) {
1385 var tag = node.tagName;
1386 var roles = {
1387 'BUTTON': 'button', 'A': 'link', 'INPUT': 'textbox',
1388 'SELECT': 'combobox', 'TEXTAREA': 'textbox', 'IMG': 'img',
1389 'NAV': 'navigation', 'MAIN': 'main', 'HEADER': 'banner',
1390 'FOOTER': 'contentinfo', 'ASIDE': 'complementary',
1391 'H1': 'heading', 'H2': 'heading', 'H3': 'heading',
1392 'H4': 'heading', 'H5': 'heading', 'H6': 'heading',
1393 'UL': 'list', 'OL': 'list', 'LI': 'listitem',
1394 'TABLE': 'table', 'FORM': 'form', 'DIALOG': 'dialog',
1395 };
1396 if (tag === 'INPUT') {
1397 var type = node.getAttribute('type');
1398 if (type === 'checkbox') return 'checkbox';
1399 if (type === 'radio') return 'radio';
1400 if (type === 'range') return 'slider';
1401 if (type === 'submit' || type === 'button') return 'button';
1402 }
1403 return roles[tag] || null;
1404 }
1405
1406 function getDirectText(node) {
1407 var text = '';
1408 for (var i = 0; i < node.childNodes.length; i++) {
1409 if (node.childNodes[i].nodeType === 3) text += node.childNodes[i].textContent;
1410 }
1411 text = text.trim();
1412 return text.length > 0 ? text.substring(0, 200) : null;
1413 }
1414
1415 // ── Console Hooking ──────────────────────────────────────────────────────
1416
1417 var originalConsole = {
1418 log: console.log, warn: console.warn,
1419 error: console.error, info: console.info, debug: console.debug
1420 };
1421
1422 var CTRL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F\x1B]/g;
1423
1424 function hookConsole(level) {
1425 console[level] = function() {
1426 var args = Array.prototype.slice.call(arguments);
1427 var msg = args.map(String).join(' ').replace(CTRL_RE, '');
1428 consoleLogs.push({ level: level, message: msg, timestamp: Date.now() });
1429 if (consoleLogs.length > CAP_CONSOLE) consoleLogs.shift();
1430 originalConsole[level].apply(console, args);
1431 };
1432 }
1433
1434 hookConsole('log');
1435 hookConsole('warn');
1436 hookConsole('error');
1437 hookConsole('info');
1438 hookConsole('debug');
1439
1440 // ── Global Error Capture ────────────────────────────────────────────────
1441
1442 window.addEventListener('error', function(e) {
1443 var msg = e.message || 'Unknown error';
1444 if (e.filename) msg += ' at ' + e.filename + ':' + e.lineno + ':' + e.colno;
1445 consoleLogs.push({ level: 'error', message: ('[uncaught] ' + msg).replace(CTRL_RE, ''), timestamp: Date.now() });
1446 if (consoleLogs.length > CAP_CONSOLE) consoleLogs.shift();
1447 });
1448
1449 window.addEventListener('unhandledrejection', function(e) {
1450 var msg = e.reason ? (e.reason.message || String(e.reason)) : 'Unhandled promise rejection';
1451 consoleLogs.push({ level: 'error', message: ('[unhandled rejection] ' + msg).replace(CTRL_RE, ''), timestamp: Date.now() });
1452 if (consoleLogs.length > CAP_CONSOLE) consoleLogs.shift();
1453 });
1454
1455 // ── Interaction Observer (for record mode) ────────────────────────────────
1456
1457 function bestSelector(el) {
1458 if (el.dataset && el.dataset.testid) return '[data-testid="' + el.dataset.testid + '"]';
1459 if (el.id) return '#' + el.id;
1460 if (el.getAttribute && el.getAttribute('role')) {
1461 var role = el.getAttribute('role');
1462 var text = (el.textContent || '').trim().substring(0, 50);
1463 if (text) return '[role="' + role + '"]:has-text("' + text + '")';
1464 return '[role="' + role + '"]';
1465 }
1466 var tag = (el.tagName || 'div').toLowerCase();
1467 var text = (el.textContent || '').trim().substring(0, 50);
1468 if (text && ['button', 'a', 'label', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'span'].indexOf(tag) !== -1) {
1469 return tag + ':has-text("' + text + '")';
1470 }
1471 if (el.name) return tag + '[name="' + el.name + '"]';
1472 if (el.className && typeof el.className === 'string') {
1473 var cls = el.className.trim().split(/\s+/).slice(0, 2).join('.');
1474 if (cls) return tag + '.' + cls;
1475 }
1476 return tag;
1477 }
1478
1479 function pushInteraction(action, el, value) {
1480 interactionLog.push({
1481 type: 'dom_interaction',
1482 action: action,
1483 selector: bestSelector(el),
1484 value: value || null,
1485 timestamp: Date.now()
1486 });
1487 if (interactionLog.length > CAP_INTERACTION) interactionLog.shift();
1488 }
1489
1490 document.addEventListener('click', function(e) {
1491 if (e.isTrusted && e.target) pushInteraction('click', e.target, null);
1492 }, true);
1493
1494 document.addEventListener('dblclick', function(e) {
1495 if (e.isTrusted && e.target) pushInteraction('double_click', e.target, null);
1496 }, true);
1497
1498 document.addEventListener('change', function(e) {
1499 if (!e.isTrusted || !e.target) return;
1500 var el = e.target;
1501 var tag = (el.tagName || '').toLowerCase();
1502 if (tag === 'select') {
1503 pushInteraction('select', el, el.value);
1504 } else if (tag === 'input' || tag === 'textarea') {
1505 var isPassword = tag === 'input' && el.type === 'password';
1506 pushInteraction('fill', el, isPassword ? '[REDACTED]' : el.value);
1507 }
1508 }, true);
1509
1510 document.addEventListener('keydown', function(e) {
1511 if (!e.isTrusted) return;
1512 if (['Enter', 'Escape', 'Tab', 'Backspace', 'Delete', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].indexOf(e.key) !== -1) {
1513 pushInteraction('key_press', e.target || document.body, e.key);
1514 }
1515 }, true);
1516
1517 // ── Mutation Observer (deferred) ─────────────────────────────────────────
1518
1519 var mutationBatchCount = 0;
1520 var mutationBatchTimer = null;
1521 var __mutationObserver = null;
1522
1523 function startMutationObserver() {
1524 if (!document.documentElement) return false;
1525 __mutationObserver = new MutationObserver(function(mutations) {
1526 mutationBatchCount += mutations.length;
1527 if (!mutationBatchTimer) {
1528 mutationBatchTimer = setTimeout(function() {
1529 mutationLog.push({ count: mutationBatchCount, timestamp: Date.now() });
1530 if (mutationLog.length > CAP_MUTATION) mutationLog.shift();
1531 mutationBatchCount = 0;
1532 mutationBatchTimer = null;
1533 }, 100);
1534 }
1535 });
1536 __mutationObserver.observe(document.documentElement, {
1537 childList: true, subtree: true, attributes: true, characterData: true,
1538 });
1539 return true;
1540 }
1541
1542 if (!startMutationObserver()) {
1543 document.addEventListener('DOMContentLoaded', startMutationObserver);
1544 }
1545
1546 // IPC logging is derived from the network log: Tauri 2.0 sends all IPC
1547 // via fetch to http://ipc.localhost/<command>. The fetch interceptor below
1548 // captures these, and getIpcLog() filters them from networkLog. This avoids
1549 // the need to patch __TAURI_INTERNALS__.invoke, which Tauri freezes with
1550 // configurable:false, writable:false.
1551
1552 // ── Network Interception ─────────────────────────────────────────────────
1553
1554 (function interceptNetwork() {
1555 // fetch
1556 var origFetch = window.fetch;
1557 if (origFetch) {
1558 window.fetch = function(input, init) {
1559 var id = ++networkCounter;
1560 var url = typeof input === 'string' ? input : (input && input.url ? input.url : String(input));
1561 var method = (init && init.method) || (input && input.method) || 'GET';
1562 var isIpc = url.indexOf('http://ipc.localhost/') === 0;
1563 var entry = { id: id, method: method.toUpperCase(), url: url, timestamp: Date.now(), status: 'pending', duration_ms: null };
1564
1565 if (isIpc && init && init.body && window.__VICTAURI__._captureIpcBodies !== false) {
1566 try {
1567 var bodyStr = typeof init.body === 'string' ? init.body : null;
1568 if (bodyStr) {
1569 var parsed = JSON.parse(bodyStr);
1570 entry.request_args = parsed;
1571 }
1572 } catch(e) {}
1573 }
1574
1575 networkLog.push(entry);
1576 if (networkLog.length > CAP_NETWORK) networkLog.shift();
1577
1578 return origFetch.call(this, input, init).then(function(response) {
1579 entry.status = response.status;
1580 entry.status_text = response.statusText;
1581 entry.duration_ms = Date.now() - entry.timestamp;
1582
1583 if (isIpc) {
1584 if (window.__VICTAURI__._captureIpcBodies !== false) {
1585 var cloned = response.clone();
1586 cloned.text().then(function(text) {
1587 try { entry.response_body = JSON.parse(text); } catch(e) { entry.response_body = text; }
1588 }).catch(function() {}).then(function() {
1589 for (var w = ipcWaiters.length - 1; w >= 0; w--) {
1590 ipcWaiters[w]();
1591 }
1592 ipcWaiters.length = 0;
1593 });
1594 } else {
1595 for (var w = ipcWaiters.length - 1; w >= 0; w--) {
1596 ipcWaiters[w]();
1597 }
1598 ipcWaiters.length = 0;
1599 }
1600 }
1601
1602 return response;
1603 }, function(err) {
1604 entry.status = 'error';
1605 entry.error = String(err);
1606 entry.duration_ms = Date.now() - entry.timestamp;
1607 for (var w = ipcWaiters.length - 1; w >= 0; w--) {
1608 ipcWaiters[w]();
1609 }
1610 ipcWaiters.length = 0;
1611 throw err;
1612 });
1613 };
1614 }
1615
1616 // XMLHttpRequest
1617 var origOpen = XMLHttpRequest.prototype.open;
1618 var origSend = XMLHttpRequest.prototype.send;
1619 XMLHttpRequest.prototype.open = function(method, url) {
1620 this.__victauri_net = { method: method, url: url };
1621 return origOpen.apply(this, arguments);
1622 };
1623 XMLHttpRequest.prototype.send = function() {
1624 if (this.__victauri_net) {
1625 var id = ++networkCounter;
1626 var entry = {
1627 id: id,
1628 method: this.__victauri_net.method.toUpperCase(),
1629 url: this.__victauri_net.url,
1630 timestamp: Date.now(),
1631 status: 'pending',
1632 duration_ms: null,
1633 };
1634 networkLog.push(entry);
1635 if (networkLog.length > CAP_NETWORK) networkLog.shift();
1636 var self = this;
1637 this.addEventListener('load', function() {
1638 entry.status = self.status;
1639 entry.status_text = self.statusText;
1640 entry.duration_ms = Date.now() - entry.timestamp;
1641 });
1642 this.addEventListener('error', function() {
1643 entry.status = 'error';
1644 entry.duration_ms = Date.now() - entry.timestamp;
1645 });
1646 }
1647 return origSend.apply(this, arguments);
1648 };
1649 })();
1650
1651 // ── Navigation Tracking ──────────────────────────────────────────────────
1652
1653 (function trackNavigation() {
1654 navigationLog.push({ url: window.location.href, timestamp: Date.now(), type: 'initial' });
1655
1656 var origPushState = history.pushState;
1657 var origReplaceState = history.replaceState;
1658 history.pushState = function() {
1659 var result = origPushState.apply(this, arguments);
1660 navigationLog.push({ url: window.location.href, timestamp: Date.now(), type: 'pushState' });
1661 if (navigationLog.length > CAP_NAVIGATION) navigationLog.shift();
1662 return result;
1663 };
1664 history.replaceState = function() {
1665 var result = origReplaceState.apply(this, arguments);
1666 navigationLog.push({ url: window.location.href, timestamp: Date.now(), type: 'replaceState' });
1667 if (navigationLog.length > CAP_NAVIGATION) navigationLog.shift();
1668 return result;
1669 };
1670 window.addEventListener('popstate', function() {
1671 navigationLog.push({ url: window.location.href, timestamp: Date.now(), type: 'popstate' });
1672 });
1673 window.addEventListener('hashchange', function(e) {
1674 navigationLog.push({ url: window.location.href, timestamp: Date.now(), type: 'hashchange', old_url: e.oldURL });
1675 });
1676 })();
1677
1678 // ── Dialog Capture ───────────────────────────────────────────────────────
1679
1680 var dialogAutoResponses = { alert: { action: 'accept' }, confirm: { action: 'accept' }, prompt: { action: 'accept', text: '' } };
1681
1682 // ── Resource Cleanup ────────────────────────────────────────────────────
1683
1684 window.addEventListener('pagehide', function() {
1685 if (__mutationObserver) { __mutationObserver.disconnect(); __mutationObserver = null; }
1686 if (mutationBatchTimer) { clearTimeout(mutationBatchTimer); mutationBatchTimer = null; }
1687 console.log = originalConsole.log;
1688 console.warn = originalConsole.warn;
1689 console.error = originalConsole.error;
1690 console.info = originalConsole.info;
1691 console.debug = originalConsole.debug;
1692 consoleLogs.length = 0;
1693 mutationLog.length = 0;
1694 networkLog.length = 0;
1695 navigationLog.length = 0;
1696 dialogLog.length = 0;
1697 interactionLog.length = 0;
1698 refMap.clear();
1699 weakRefMap.clear();
1700 refCounter = 0;
1701 });
1702
1703 (function captureDialogs() {
1704 window.alert = function(msg) {
1705 dialogLog.push({ type: 'alert', message: String(msg || ''), timestamp: Date.now() });
1706 if (dialogLog.length > CAP_DIALOG) dialogLog.shift();
1707 };
1708 window.confirm = function(msg) {
1709 var resp = dialogAutoResponses.confirm;
1710 var result = resp.action === 'accept';
1711 dialogLog.push({ type: 'confirm', message: String(msg || ''), timestamp: Date.now(), result: result });
1712 if (dialogLog.length > CAP_DIALOG) dialogLog.shift();
1713 return result;
1714 };
1715 window.prompt = function(msg, defaultValue) {
1716 var resp = dialogAutoResponses.prompt;
1717 var result = resp.action === 'accept' ? (resp.text || defaultValue || '') : null;
1718 dialogLog.push({ type: 'prompt', message: String(msg || ''), timestamp: Date.now(), result: result });
1719 if (dialogLog.length > CAP_DIALOG) dialogLog.shift();
1720 return result;
1721 };
1722 })();
1723})();
1724"#;