wu-framework 1.1.15 → 1.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +52 -20
  2. package/dist/wu-framework.cjs.js +1 -1
  3. package/dist/wu-framework.cjs.js.map +1 -1
  4. package/dist/wu-framework.dev.js +15511 -15146
  5. package/dist/wu-framework.dev.js.map +1 -1
  6. package/dist/wu-framework.esm.js +1 -1
  7. package/dist/wu-framework.esm.js.map +1 -1
  8. package/dist/wu-framework.umd.js +1 -1
  9. package/dist/wu-framework.umd.js.map +1 -1
  10. package/package.json +166 -161
  11. package/src/adapters/angular/ai.js +30 -30
  12. package/src/adapters/angular/index.d.ts +154 -154
  13. package/src/adapters/angular/index.js +932 -932
  14. package/src/adapters/angular.d.ts +3 -3
  15. package/src/adapters/angular.js +3 -3
  16. package/src/adapters/index.js +168 -168
  17. package/src/adapters/lit/ai.js +20 -20
  18. package/src/adapters/lit/index.d.ts +120 -120
  19. package/src/adapters/lit/index.js +721 -721
  20. package/src/adapters/lit.d.ts +3 -3
  21. package/src/adapters/lit.js +3 -3
  22. package/src/adapters/preact/ai.js +33 -33
  23. package/src/adapters/preact/index.d.ts +108 -108
  24. package/src/adapters/preact/index.js +661 -661
  25. package/src/adapters/preact.d.ts +3 -3
  26. package/src/adapters/preact.js +3 -3
  27. package/src/adapters/react/index.js +48 -54
  28. package/src/adapters/react.d.ts +3 -3
  29. package/src/adapters/react.js +3 -3
  30. package/src/adapters/shared.js +64 -64
  31. package/src/adapters/solid/ai.js +32 -32
  32. package/src/adapters/solid/index.d.ts +101 -101
  33. package/src/adapters/solid/index.js +586 -586
  34. package/src/adapters/solid.d.ts +3 -3
  35. package/src/adapters/solid.js +3 -3
  36. package/src/adapters/svelte/ai.js +31 -31
  37. package/src/adapters/svelte/index.d.ts +166 -166
  38. package/src/adapters/svelte/index.js +798 -798
  39. package/src/adapters/svelte.d.ts +3 -3
  40. package/src/adapters/svelte.js +3 -3
  41. package/src/adapters/vanilla/ai.js +30 -30
  42. package/src/adapters/vanilla/index.d.ts +179 -179
  43. package/src/adapters/vanilla/index.js +785 -785
  44. package/src/adapters/vanilla.d.ts +3 -3
  45. package/src/adapters/vanilla.js +3 -3
  46. package/src/adapters/vue/ai.js +52 -52
  47. package/src/adapters/vue/index.d.ts +299 -299
  48. package/src/adapters/vue/index.js +610 -610
  49. package/src/adapters/vue.d.ts +3 -3
  50. package/src/adapters/vue.js +3 -3
  51. package/src/ai/wu-ai-actions.js +261 -261
  52. package/src/ai/wu-ai-agent.js +546 -546
  53. package/src/ai/wu-ai-browser-primitives.js +354 -354
  54. package/src/ai/wu-ai-browser.js +380 -380
  55. package/src/ai/wu-ai-context.js +332 -332
  56. package/src/ai/wu-ai-conversation.js +613 -613
  57. package/src/ai/wu-ai-orchestrate.js +1021 -1021
  58. package/src/ai/wu-ai-permissions.js +381 -381
  59. package/src/ai/wu-ai-provider.js +700 -700
  60. package/src/ai/wu-ai-schema.js +225 -225
  61. package/src/ai/wu-ai-triggers.js +396 -396
  62. package/src/ai/wu-ai.js +804 -804
  63. package/src/core/wu-app.js +236 -236
  64. package/src/core/wu-cache.js +498 -477
  65. package/src/core/wu-core.js +1412 -1398
  66. package/src/core/wu-error-boundary.js +396 -382
  67. package/src/core/wu-event-bus.js +390 -348
  68. package/src/core/wu-hooks.js +350 -350
  69. package/src/core/wu-html-parser.js +199 -190
  70. package/src/core/wu-iframe-sandbox.js +328 -328
  71. package/src/core/wu-loader.js +385 -273
  72. package/src/core/wu-logger.js +142 -134
  73. package/src/core/wu-manifest.js +532 -509
  74. package/src/core/wu-mcp-bridge.js +432 -432
  75. package/src/core/wu-overrides.js +510 -510
  76. package/src/core/wu-performance.js +228 -228
  77. package/src/core/wu-plugin.js +401 -348
  78. package/src/core/wu-prefetch.js +414 -414
  79. package/src/core/wu-proxy-sandbox.js +477 -476
  80. package/src/core/wu-sandbox.js +779 -779
  81. package/src/core/wu-script-executor.js +161 -113
  82. package/src/core/wu-snapshot-sandbox.js +227 -227
  83. package/src/core/wu-store.js +13 -3
  84. package/src/core/wu-strategies.js +256 -256
  85. package/src/core/wu-style-bridge.js +477 -477
  86. package/src/index.d.ts +317 -0
  87. package/src/index.js +234 -224
  88. package/src/utils/dependency-resolver.js +327 -327
@@ -1,354 +1,354 @@
1
- /**
2
- * WU-AI Browser Primitives
3
- *
4
- * Shared browser capabilities used by both wu-ai-browser.js (Paradigm 1/2)
5
- * and wu-mcp-bridge.js (Paradigm 3). Single source of truth to avoid
6
- * duplicating interceptors, DOM traversal, and Canvas rendering.
7
- */
8
-
9
- // ── Shared capture buffers (singleton) ──
10
-
11
- export const networkLog = [];
12
- export const MAX_NETWORK_LOG = 300;
13
- export const consoleLog = [];
14
- export const MAX_CONSOLE_LOG = 500;
15
-
16
- let _interceptorsInstalled = false;
17
-
18
- /**
19
- * Install network + console interceptors (idempotent — only runs once).
20
- */
21
- export function ensureInterceptors() {
22
- if (_interceptorsInstalled) return;
23
- _installNetworkInterceptor();
24
- _installConsoleInterceptor();
25
- _interceptorsInstalled = true;
26
- }
27
-
28
- /**
29
- * Build an accessibility tree representation of a DOM element.
30
- * Traverses into Shadow DOM if present.
31
- */
32
- export function buildA11yTree(el, depth = 0, maxDepth = 5) {
33
- if (depth > maxDepth || !el) return '';
34
-
35
- const indent = ' '.repeat(depth);
36
- const tag = el.tagName?.toLowerCase() || '';
37
- const role = el.getAttribute?.('role') || '';
38
- const ariaLabel = el.getAttribute?.('aria-label') || '';
39
- const text = el.childNodes?.length === 1 && el.childNodes[0].nodeType === 3
40
- ? el.textContent?.trim().slice(0, 80) : '';
41
-
42
- let line = `${indent}<${tag}`;
43
- if (el.id) line += ` id="${el.id}"`;
44
- if (role) line += ` role="${role}"`;
45
- if (ariaLabel) line += ` aria-label="${ariaLabel}"`;
46
- if (el.className && typeof el.className === 'string') {
47
- const cls = el.className.trim().slice(0, 60);
48
- if (cls) line += ` class="${cls}"`;
49
- }
50
- line += '>';
51
- if (text) line += ` "${text}"`;
52
-
53
- let result = line + '\n';
54
- const root = el.shadowRoot || el;
55
- const children = root.children || [];
56
-
57
- for (let i = 0; i < children.length && i < 50; i++) {
58
- result += buildA11yTree(children[i], depth + 1, maxDepth);
59
- }
60
- return result;
61
- }
62
-
63
- /**
64
- * Recursively inline computed styles from source to clone for Canvas rendering.
65
- */
66
- export function inlineComputedStyles(source, clone) {
67
- const props = ['color', 'background', 'background-color', 'font-family',
68
- 'font-size', 'font-weight', 'border', 'border-radius', 'padding', 'margin',
69
- 'display', 'flex-direction', 'align-items', 'justify-content', 'gap',
70
- 'width', 'height', 'max-width', 'max-height', 'overflow', 'opacity',
71
- 'box-shadow', 'text-align', 'line-height', 'position', 'top', 'left',
72
- 'right', 'bottom', 'z-index', 'transform', 'visibility'];
73
-
74
- try {
75
- const style = window.getComputedStyle(source);
76
- for (const prop of props) {
77
- const val = style.getPropertyValue(prop);
78
- if (val) clone.style?.setProperty(prop, val);
79
- }
80
- } catch (_) { /* skip */ }
81
-
82
- const srcKids = source.children || [];
83
- const cloneKids = clone.children || [];
84
- const max = Math.min(srcKids.length, cloneKids.length, 200);
85
- for (let i = 0; i < max; i++) {
86
- inlineComputedStyles(srcKids[i], cloneKids[i]);
87
- }
88
- }
89
-
90
- /**
91
- * Capture a screenshot of a DOM element via Canvas API (SVG foreignObject).
92
- * @returns {Promise<{ width, height, format, base64, sizeKB } | { error: string }>}
93
- */
94
- export async function captureScreenshot(selector, quality = 0.8) {
95
- const target = selector
96
- ? document.querySelector(selector)
97
- : document.documentElement;
98
-
99
- if (!target) return { error: `Element not found: ${selector}` };
100
-
101
- const rect = target.getBoundingClientRect();
102
- const w = Math.ceil(Math.min(rect.width || window.innerWidth, 1920));
103
- const h = Math.ceil(Math.min(rect.height || window.innerHeight, 1080));
104
-
105
- const clone = target.cloneNode(true);
106
- inlineComputedStyles(target, clone);
107
-
108
- const serializer = new XMLSerializer();
109
- const xhtml = serializer.serializeToString(clone);
110
-
111
- const svgStr = [
112
- `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}">`,
113
- '<foreignObject width="100%" height="100%">',
114
- `<div xmlns="http://www.w3.org/1999/xhtml" style="width:${w}px;height:${h}px;overflow:hidden;">`,
115
- xhtml,
116
- '</div>',
117
- '</foreignObject>',
118
- '</svg>',
119
- ].join('');
120
-
121
- const svgBlob = new Blob([svgStr], { type: 'image/svg+xml;charset=utf-8' });
122
- const url = URL.createObjectURL(svgBlob);
123
-
124
- const dataUrl = await new Promise((resolve) => {
125
- const img = new Image();
126
- img.onload = () => {
127
- const canvas = document.createElement('canvas');
128
- canvas.width = w;
129
- canvas.height = h;
130
- const ctx = canvas.getContext('2d');
131
- ctx.drawImage(img, 0, 0);
132
- URL.revokeObjectURL(url);
133
- resolve(canvas.toDataURL('image/png', quality));
134
- };
135
- img.onerror = () => {
136
- URL.revokeObjectURL(url);
137
- resolve(null);
138
- };
139
- img.src = url;
140
- });
141
-
142
- if (!dataUrl) return { error: 'Canvas rendering failed' };
143
-
144
- const base64 = dataUrl.split(',')[1];
145
- return {
146
- width: w,
147
- height: h,
148
- format: 'png',
149
- base64,
150
- sizeKB: Math.round((base64.length * 3) / 4 / 1024),
151
- };
152
- }
153
-
154
- /**
155
- * Click an element by CSS selector or visible text content.
156
- * @returns {{ clicked, text } | { error }}
157
- */
158
- export function clickElement(selector, text) {
159
- let el = null;
160
-
161
- if (selector) {
162
- el = document.querySelector(selector);
163
- }
164
-
165
- if (!el && text) {
166
- const candidates = document.querySelectorAll(
167
- 'button, a, [role="button"], input[type="submit"], input[type="button"], [data-click], label, [onclick]'
168
- );
169
- const searchText = text.toLowerCase();
170
- for (const candidate of candidates) {
171
- if (candidate.textContent?.trim().toLowerCase().includes(searchText)) {
172
- el = candidate;
173
- break;
174
- }
175
- }
176
- }
177
-
178
- if (!el) return { error: `Element not found: ${selector || `text="${text}"`}` };
179
-
180
- el.scrollIntoView({ behavior: 'instant', block: 'center' });
181
- el.click();
182
-
183
- const tag = el.tagName?.toLowerCase();
184
- const id = el.id ? `#${el.id}` : '';
185
- return {
186
- clicked: `${tag}${id}`,
187
- text: el.textContent?.trim().slice(0, 100) || '',
188
- rect: el.getBoundingClientRect().toJSON?.() || null,
189
- };
190
- }
191
-
192
- /**
193
- * Type into an input, textarea, or contenteditable element.
194
- * Works with React, Vue, Angular, and other frameworks.
195
- * @returns {{ selector, typed, currentValue, submitted } | { error }}
196
- */
197
- export function typeIntoElement(selector, text, { clear = false, submit = false } = {}) {
198
- if (!selector) return { error: 'selector is required' };
199
- if (text === undefined) return { error: 'text is required' };
200
-
201
- const el = document.querySelector(selector);
202
- if (!el) return { error: `Element not found: ${selector}` };
203
-
204
- el.focus();
205
-
206
- if (clear) {
207
- el.value = '';
208
- el.dispatchEvent(new Event('input', { bubbles: true }));
209
- }
210
-
211
- // Use native setter to trigger framework reactivity (React, Vue, etc.)
212
- const nativeSetter = Object.getOwnPropertyDescriptor(
213
- window.HTMLInputElement.prototype, 'value'
214
- )?.set || Object.getOwnPropertyDescriptor(
215
- window.HTMLTextAreaElement.prototype, 'value'
216
- )?.set;
217
-
218
- const newValue = clear ? text : (el.value || '') + text;
219
- if (nativeSetter) {
220
- nativeSetter.call(el, newValue);
221
- } else {
222
- el.value = newValue;
223
- }
224
-
225
- el.dispatchEvent(new Event('input', { bubbles: true }));
226
- el.dispatchEvent(new Event('change', { bubbles: true }));
227
-
228
- if (submit) {
229
- const form = el.closest('form');
230
- if (form) {
231
- form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
232
- } else {
233
- el.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', bubbles: true }));
234
- }
235
- }
236
-
237
- return {
238
- selector,
239
- typed: text,
240
- currentValue: el.value?.slice(0, 200),
241
- submitted: !!submit,
242
- };
243
- }
244
-
245
- /**
246
- * Filter and return network log entries.
247
- */
248
- export function getFilteredNetwork(method, status, limit = 30) {
249
- let filtered = networkLog;
250
- if (method) {
251
- filtered = filtered.filter((r) => r.method === method.toUpperCase());
252
- }
253
- if (status) {
254
- if (status === 'error') {
255
- filtered = filtered.filter((r) => r.status === 0 || r.status >= 400);
256
- } else {
257
- filtered = filtered.filter((r) => String(r.status).startsWith(String(status)));
258
- }
259
- }
260
- return {
261
- requests: filtered.slice(-limit),
262
- total: networkLog.length,
263
- showing: Math.min(filtered.length, limit),
264
- };
265
- }
266
-
267
- /**
268
- * Filter and return console log entries.
269
- */
270
- export function getFilteredConsole(level, limit = 30) {
271
- const filtered = level && level !== 'all'
272
- ? consoleLog.filter((m) => m.level === level)
273
- : consoleLog;
274
- return {
275
- messages: filtered.slice(-limit),
276
- total: consoleLog.length,
277
- showing: Math.min(filtered.length, limit),
278
- };
279
- }
280
-
281
- // ── Private: Interceptors ──
282
-
283
- function _installNetworkInterceptor() {
284
- // Intercept fetch
285
- const originalFetch = window.fetch;
286
- window.fetch = async function (...args) {
287
- const start = Date.now();
288
- const req = args[0];
289
- const url = typeof req === 'string' ? req : req?.url || '';
290
- const method = (args[1]?.method || req?.method || 'GET').toUpperCase();
291
-
292
- try {
293
- const response = await originalFetch.apply(window, args);
294
- const size = parseInt(response.headers?.get('content-length') || '0', 10);
295
- networkLog.push({
296
- type: 'fetch', method, url,
297
- status: response.status, statusText: response.statusText,
298
- duration: Date.now() - start, size, timestamp: start,
299
- });
300
- if (networkLog.length > MAX_NETWORK_LOG) networkLog.shift();
301
- return response;
302
- } catch (err) {
303
- networkLog.push({
304
- type: 'fetch', method, url,
305
- status: 0, error: err.message,
306
- duration: Date.now() - start, timestamp: start,
307
- });
308
- if (networkLog.length > MAX_NETWORK_LOG) networkLog.shift();
309
- throw err;
310
- }
311
- };
312
-
313
- // Intercept XMLHttpRequest
314
- const origOpen = XMLHttpRequest.prototype.open;
315
- const origSend = XMLHttpRequest.prototype.send;
316
-
317
- XMLHttpRequest.prototype.open = function (method, url, ...rest) {
318
- this._wuAi = { method: (method || 'GET').toUpperCase(), url: String(url) };
319
- return origOpen.call(this, method, url, ...rest);
320
- };
321
-
322
- XMLHttpRequest.prototype.send = function (...args) {
323
- if (this._wuAi) {
324
- this._wuAi.start = Date.now();
325
- this.addEventListener('loadend', () => {
326
- networkLog.push({
327
- type: 'xhr', method: this._wuAi.method, url: this._wuAi.url,
328
- status: this.status, statusText: this.statusText,
329
- duration: Date.now() - this._wuAi.start,
330
- size: parseInt(this.getResponseHeader('content-length') || '0', 10),
331
- timestamp: this._wuAi.start,
332
- });
333
- if (networkLog.length > MAX_NETWORK_LOG) networkLog.shift();
334
- });
335
- }
336
- return origSend.apply(this, args);
337
- };
338
- }
339
-
340
- function _installConsoleInterceptor() {
341
- const levels = ['log', 'warn', 'error'];
342
- for (const level of levels) {
343
- const original = console[level];
344
- console[level] = (...args) => {
345
- consoleLog.push({
346
- level,
347
- message: args.map((a) => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' '),
348
- timestamp: Date.now(),
349
- });
350
- if (consoleLog.length > MAX_CONSOLE_LOG) consoleLog.shift();
351
- original.apply(console, args);
352
- };
353
- }
354
- }
1
+ /**
2
+ * WU-AI Browser Primitives
3
+ *
4
+ * Shared browser capabilities used by both wu-ai-browser.js (Paradigm 1/2)
5
+ * and wu-mcp-bridge.js (Paradigm 3). Single source of truth to avoid
6
+ * duplicating interceptors, DOM traversal, and Canvas rendering.
7
+ */
8
+
9
+ // ── Shared capture buffers (singleton) ──
10
+
11
+ export const networkLog = [];
12
+ export const MAX_NETWORK_LOG = 300;
13
+ export const consoleLog = [];
14
+ export const MAX_CONSOLE_LOG = 500;
15
+
16
+ let _interceptorsInstalled = false;
17
+
18
+ /**
19
+ * Install network + console interceptors (idempotent — only runs once).
20
+ */
21
+ export function ensureInterceptors() {
22
+ if (_interceptorsInstalled) return;
23
+ _installNetworkInterceptor();
24
+ _installConsoleInterceptor();
25
+ _interceptorsInstalled = true;
26
+ }
27
+
28
+ /**
29
+ * Build an accessibility tree representation of a DOM element.
30
+ * Traverses into Shadow DOM if present.
31
+ */
32
+ export function buildA11yTree(el, depth = 0, maxDepth = 5) {
33
+ if (depth > maxDepth || !el) return '';
34
+
35
+ const indent = ' '.repeat(depth);
36
+ const tag = el.tagName?.toLowerCase() || '';
37
+ const role = el.getAttribute?.('role') || '';
38
+ const ariaLabel = el.getAttribute?.('aria-label') || '';
39
+ const text = el.childNodes?.length === 1 && el.childNodes[0].nodeType === 3
40
+ ? el.textContent?.trim().slice(0, 80) : '';
41
+
42
+ let line = `${indent}<${tag}`;
43
+ if (el.id) line += ` id="${el.id}"`;
44
+ if (role) line += ` role="${role}"`;
45
+ if (ariaLabel) line += ` aria-label="${ariaLabel}"`;
46
+ if (el.className && typeof el.className === 'string') {
47
+ const cls = el.className.trim().slice(0, 60);
48
+ if (cls) line += ` class="${cls}"`;
49
+ }
50
+ line += '>';
51
+ if (text) line += ` "${text}"`;
52
+
53
+ let result = line + '\n';
54
+ const root = el.shadowRoot || el;
55
+ const children = root.children || [];
56
+
57
+ for (let i = 0; i < children.length && i < 50; i++) {
58
+ result += buildA11yTree(children[i], depth + 1, maxDepth);
59
+ }
60
+ return result;
61
+ }
62
+
63
+ /**
64
+ * Recursively inline computed styles from source to clone for Canvas rendering.
65
+ */
66
+ export function inlineComputedStyles(source, clone) {
67
+ const props = ['color', 'background', 'background-color', 'font-family',
68
+ 'font-size', 'font-weight', 'border', 'border-radius', 'padding', 'margin',
69
+ 'display', 'flex-direction', 'align-items', 'justify-content', 'gap',
70
+ 'width', 'height', 'max-width', 'max-height', 'overflow', 'opacity',
71
+ 'box-shadow', 'text-align', 'line-height', 'position', 'top', 'left',
72
+ 'right', 'bottom', 'z-index', 'transform', 'visibility'];
73
+
74
+ try {
75
+ const style = window.getComputedStyle(source);
76
+ for (const prop of props) {
77
+ const val = style.getPropertyValue(prop);
78
+ if (val) clone.style?.setProperty(prop, val);
79
+ }
80
+ } catch (_) { /* skip */ }
81
+
82
+ const srcKids = source.children || [];
83
+ const cloneKids = clone.children || [];
84
+ const max = Math.min(srcKids.length, cloneKids.length, 200);
85
+ for (let i = 0; i < max; i++) {
86
+ inlineComputedStyles(srcKids[i], cloneKids[i]);
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Capture a screenshot of a DOM element via Canvas API (SVG foreignObject).
92
+ * @returns {Promise<{ width, height, format, base64, sizeKB } | { error: string }>}
93
+ */
94
+ export async function captureScreenshot(selector, quality = 0.8) {
95
+ const target = selector
96
+ ? document.querySelector(selector)
97
+ : document.documentElement;
98
+
99
+ if (!target) return { error: `Element not found: ${selector}` };
100
+
101
+ const rect = target.getBoundingClientRect();
102
+ const w = Math.ceil(Math.min(rect.width || window.innerWidth, 1920));
103
+ const h = Math.ceil(Math.min(rect.height || window.innerHeight, 1080));
104
+
105
+ const clone = target.cloneNode(true);
106
+ inlineComputedStyles(target, clone);
107
+
108
+ const serializer = new XMLSerializer();
109
+ const xhtml = serializer.serializeToString(clone);
110
+
111
+ const svgStr = [
112
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}">`,
113
+ '<foreignObject width="100%" height="100%">',
114
+ `<div xmlns="http://www.w3.org/1999/xhtml" style="width:${w}px;height:${h}px;overflow:hidden;">`,
115
+ xhtml,
116
+ '</div>',
117
+ '</foreignObject>',
118
+ '</svg>',
119
+ ].join('');
120
+
121
+ const svgBlob = new Blob([svgStr], { type: 'image/svg+xml;charset=utf-8' });
122
+ const url = URL.createObjectURL(svgBlob);
123
+
124
+ const dataUrl = await new Promise((resolve) => {
125
+ const img = new Image();
126
+ img.onload = () => {
127
+ const canvas = document.createElement('canvas');
128
+ canvas.width = w;
129
+ canvas.height = h;
130
+ const ctx = canvas.getContext('2d');
131
+ ctx.drawImage(img, 0, 0);
132
+ URL.revokeObjectURL(url);
133
+ resolve(canvas.toDataURL('image/png', quality));
134
+ };
135
+ img.onerror = () => {
136
+ URL.revokeObjectURL(url);
137
+ resolve(null);
138
+ };
139
+ img.src = url;
140
+ });
141
+
142
+ if (!dataUrl) return { error: 'Canvas rendering failed' };
143
+
144
+ const base64 = dataUrl.split(',')[1];
145
+ return {
146
+ width: w,
147
+ height: h,
148
+ format: 'png',
149
+ base64,
150
+ sizeKB: Math.round((base64.length * 3) / 4 / 1024),
151
+ };
152
+ }
153
+
154
+ /**
155
+ * Click an element by CSS selector or visible text content.
156
+ * @returns {{ clicked, text } | { error }}
157
+ */
158
+ export function clickElement(selector, text) {
159
+ let el = null;
160
+
161
+ if (selector) {
162
+ el = document.querySelector(selector);
163
+ }
164
+
165
+ if (!el && text) {
166
+ const candidates = document.querySelectorAll(
167
+ 'button, a, [role="button"], input[type="submit"], input[type="button"], [data-click], label, [onclick]'
168
+ );
169
+ const searchText = text.toLowerCase();
170
+ for (const candidate of candidates) {
171
+ if (candidate.textContent?.trim().toLowerCase().includes(searchText)) {
172
+ el = candidate;
173
+ break;
174
+ }
175
+ }
176
+ }
177
+
178
+ if (!el) return { error: `Element not found: ${selector || `text="${text}"`}` };
179
+
180
+ el.scrollIntoView({ behavior: 'instant', block: 'center' });
181
+ el.click();
182
+
183
+ const tag = el.tagName?.toLowerCase();
184
+ const id = el.id ? `#${el.id}` : '';
185
+ return {
186
+ clicked: `${tag}${id}`,
187
+ text: el.textContent?.trim().slice(0, 100) || '',
188
+ rect: el.getBoundingClientRect().toJSON?.() || null,
189
+ };
190
+ }
191
+
192
+ /**
193
+ * Type into an input, textarea, or contenteditable element.
194
+ * Works with React, Vue, Angular, and other frameworks.
195
+ * @returns {{ selector, typed, currentValue, submitted } | { error }}
196
+ */
197
+ export function typeIntoElement(selector, text, { clear = false, submit = false } = {}) {
198
+ if (!selector) return { error: 'selector is required' };
199
+ if (text === undefined) return { error: 'text is required' };
200
+
201
+ const el = document.querySelector(selector);
202
+ if (!el) return { error: `Element not found: ${selector}` };
203
+
204
+ el.focus();
205
+
206
+ if (clear) {
207
+ el.value = '';
208
+ el.dispatchEvent(new Event('input', { bubbles: true }));
209
+ }
210
+
211
+ // Use native setter to trigger framework reactivity (React, Vue, etc.)
212
+ const nativeSetter = Object.getOwnPropertyDescriptor(
213
+ window.HTMLInputElement.prototype, 'value'
214
+ )?.set || Object.getOwnPropertyDescriptor(
215
+ window.HTMLTextAreaElement.prototype, 'value'
216
+ )?.set;
217
+
218
+ const newValue = clear ? text : (el.value || '') + text;
219
+ if (nativeSetter) {
220
+ nativeSetter.call(el, newValue);
221
+ } else {
222
+ el.value = newValue;
223
+ }
224
+
225
+ el.dispatchEvent(new Event('input', { bubbles: true }));
226
+ el.dispatchEvent(new Event('change', { bubbles: true }));
227
+
228
+ if (submit) {
229
+ const form = el.closest('form');
230
+ if (form) {
231
+ form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
232
+ } else {
233
+ el.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', bubbles: true }));
234
+ }
235
+ }
236
+
237
+ return {
238
+ selector,
239
+ typed: text,
240
+ currentValue: el.value?.slice(0, 200),
241
+ submitted: !!submit,
242
+ };
243
+ }
244
+
245
+ /**
246
+ * Filter and return network log entries.
247
+ */
248
+ export function getFilteredNetwork(method, status, limit = 30) {
249
+ let filtered = networkLog;
250
+ if (method) {
251
+ filtered = filtered.filter((r) => r.method === method.toUpperCase());
252
+ }
253
+ if (status) {
254
+ if (status === 'error') {
255
+ filtered = filtered.filter((r) => r.status === 0 || r.status >= 400);
256
+ } else {
257
+ filtered = filtered.filter((r) => String(r.status).startsWith(String(status)));
258
+ }
259
+ }
260
+ return {
261
+ requests: filtered.slice(-limit),
262
+ total: networkLog.length,
263
+ showing: Math.min(filtered.length, limit),
264
+ };
265
+ }
266
+
267
+ /**
268
+ * Filter and return console log entries.
269
+ */
270
+ export function getFilteredConsole(level, limit = 30) {
271
+ const filtered = level && level !== 'all'
272
+ ? consoleLog.filter((m) => m.level === level)
273
+ : consoleLog;
274
+ return {
275
+ messages: filtered.slice(-limit),
276
+ total: consoleLog.length,
277
+ showing: Math.min(filtered.length, limit),
278
+ };
279
+ }
280
+
281
+ // ── Private: Interceptors ──
282
+
283
+ function _installNetworkInterceptor() {
284
+ // Intercept fetch
285
+ const originalFetch = window.fetch;
286
+ window.fetch = async function (...args) {
287
+ const start = Date.now();
288
+ const req = args[0];
289
+ const url = typeof req === 'string' ? req : req?.url || '';
290
+ const method = (args[1]?.method || req?.method || 'GET').toUpperCase();
291
+
292
+ try {
293
+ const response = await originalFetch.apply(window, args);
294
+ const size = parseInt(response.headers?.get('content-length') || '0', 10);
295
+ networkLog.push({
296
+ type: 'fetch', method, url,
297
+ status: response.status, statusText: response.statusText,
298
+ duration: Date.now() - start, size, timestamp: start,
299
+ });
300
+ if (networkLog.length > MAX_NETWORK_LOG) networkLog.shift();
301
+ return response;
302
+ } catch (err) {
303
+ networkLog.push({
304
+ type: 'fetch', method, url,
305
+ status: 0, error: err.message,
306
+ duration: Date.now() - start, timestamp: start,
307
+ });
308
+ if (networkLog.length > MAX_NETWORK_LOG) networkLog.shift();
309
+ throw err;
310
+ }
311
+ };
312
+
313
+ // Intercept XMLHttpRequest
314
+ const origOpen = XMLHttpRequest.prototype.open;
315
+ const origSend = XMLHttpRequest.prototype.send;
316
+
317
+ XMLHttpRequest.prototype.open = function (method, url, ...rest) {
318
+ this._wuAi = { method: (method || 'GET').toUpperCase(), url: String(url) };
319
+ return origOpen.call(this, method, url, ...rest);
320
+ };
321
+
322
+ XMLHttpRequest.prototype.send = function (...args) {
323
+ if (this._wuAi) {
324
+ this._wuAi.start = Date.now();
325
+ this.addEventListener('loadend', () => {
326
+ networkLog.push({
327
+ type: 'xhr', method: this._wuAi.method, url: this._wuAi.url,
328
+ status: this.status, statusText: this.statusText,
329
+ duration: Date.now() - this._wuAi.start,
330
+ size: parseInt(this.getResponseHeader('content-length') || '0', 10),
331
+ timestamp: this._wuAi.start,
332
+ });
333
+ if (networkLog.length > MAX_NETWORK_LOG) networkLog.shift();
334
+ });
335
+ }
336
+ return origSend.apply(this, args);
337
+ };
338
+ }
339
+
340
+ function _installConsoleInterceptor() {
341
+ const levels = ['log', 'warn', 'error'];
342
+ for (const level of levels) {
343
+ const original = console[level];
344
+ console[level] = (...args) => {
345
+ consoleLog.push({
346
+ level,
347
+ message: args.map((a) => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' '),
348
+ timestamp: Date.now(),
349
+ });
350
+ if (consoleLog.length > MAX_CONSOLE_LOG) consoleLog.shift();
351
+ original.apply(console, args);
352
+ };
353
+ }
354
+ }