web-agent-bridge 1.2.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/LICENSE +21 -21
  2. package/README.ar.md +572 -446
  3. package/README.md +968 -933
  4. package/bin/agent-runner.js +465 -0
  5. package/bin/cli.js +138 -80
  6. package/bin/wab.js +80 -80
  7. package/examples/bidi-agent.js +119 -119
  8. package/examples/mcp-agent.js +94 -94
  9. package/examples/next-app-router/README.md +44 -0
  10. package/examples/puppeteer-agent.js +108 -108
  11. package/examples/saas-dashboard/README.md +55 -0
  12. package/examples/shopify-hydrogen/README.md +74 -0
  13. package/examples/vision-agent.js +171 -171
  14. package/examples/wordpress-elementor/README.md +77 -0
  15. package/package.json +71 -78
  16. package/public/.well-known/ai-assets.json +59 -0
  17. package/public/admin/login.html +84 -84
  18. package/public/ai.html +196 -0
  19. package/public/cookies.html +208 -208
  20. package/public/css/premium.css +317 -0
  21. package/public/css/styles.css +1235 -1235
  22. package/public/dashboard.html +704 -704
  23. package/public/demo.html +259 -0
  24. package/public/docs.html +585 -585
  25. package/public/feed.xml +89 -0
  26. package/public/index.html +581 -332
  27. package/public/js/auth-nav.js +31 -31
  28. package/public/js/auth-redirect.js +12 -12
  29. package/public/js/cookie-consent.js +56 -56
  30. package/public/js/wab-demo-page.js +721 -0
  31. package/public/js/ws-client.js +74 -74
  32. package/public/llms-full.txt +309 -0
  33. package/public/llms.txt +85 -0
  34. package/public/login.html +83 -83
  35. package/public/openapi.json +580 -0
  36. package/public/premium-dashboard.html +2487 -0
  37. package/public/premium.html +791 -0
  38. package/public/privacy.html +295 -295
  39. package/public/register.html +103 -103
  40. package/public/robots.txt +87 -0
  41. package/public/script/wab-consent.d.ts +36 -0
  42. package/public/script/wab-consent.js +104 -0
  43. package/public/script/wab-schema.js +131 -0
  44. package/public/script/wab.d.ts +108 -0
  45. package/public/script/wab.min.js +405 -0
  46. package/public/sitemap.xml +93 -0
  47. package/public/sovereign.html +660 -0
  48. package/public/terms.html +254 -254
  49. package/public/video/tutorial.mp4 +0 -0
  50. package/script/ai-agent-bridge.js +1558 -1513
  51. package/sdk/README.md +55 -55
  52. package/sdk/index.d.ts +118 -0
  53. package/sdk/index.js +257 -203
  54. package/sdk/package.json +14 -14
  55. package/sdk/schema-discovery.js +83 -0
  56. package/server/config/secrets.js +94 -92
  57. package/server/index.js +2 -9
  58. package/server/middleware/adminAuth.js +30 -30
  59. package/server/middleware/auth.js +41 -41
  60. package/server/middleware/rateLimits.js +24 -24
  61. package/server/migrations/001_add_analytics_indexes.sql +7 -7
  62. package/server/migrations/002_premium_features.sql +418 -0
  63. package/server/models/adapters/index.js +33 -33
  64. package/server/models/adapters/mysql.js +183 -183
  65. package/server/models/adapters/postgresql.js +172 -172
  66. package/server/models/adapters/sqlite.js +7 -7
  67. package/server/models/db.js +561 -561
  68. package/server/routes/admin-premium.js +671 -0
  69. package/server/routes/admin.js +247 -247
  70. package/server/routes/api.js +131 -138
  71. package/server/routes/auth.js +51 -51
  72. package/server/routes/billing.js +45 -45
  73. package/server/routes/discovery.js +406 -329
  74. package/server/routes/license.js +240 -240
  75. package/server/routes/noscript.js +543 -543
  76. package/server/routes/premium-v2.js +686 -0
  77. package/server/routes/premium.js +724 -0
  78. package/server/routes/sovereign.js +307 -0
  79. package/server/routes/wab-api.js +476 -476
  80. package/server/services/agent-memory.js +625 -0
  81. package/server/services/email.js +204 -204
  82. package/server/services/fairness.js +420 -420
  83. package/server/services/negotiation.js +439 -0
  84. package/server/services/plugins.js +747 -0
  85. package/server/services/premium.js +1883 -0
  86. package/server/services/reputation.js +465 -0
  87. package/server/services/self-healing.js +843 -0
  88. package/server/services/stripe.js +192 -192
  89. package/server/services/swarm.js +788 -0
  90. package/server/services/verification.js +481 -0
  91. package/server/services/vision.js +871 -0
  92. package/server/utils/cache.js +125 -125
  93. package/server/utils/migrate.js +81 -81
  94. package/server/utils/secureFields.js +50 -50
  95. package/server/ws.js +101 -101
  96. package/templates/artisan-marketplace.yaml +104 -0
  97. package/templates/book-price-scout.yaml +98 -0
  98. package/templates/electronics-price-tracker.yaml +108 -0
  99. package/templates/flight-deal-hunter.yaml +113 -0
  100. package/templates/freelancer-direct.yaml +116 -0
  101. package/templates/grocery-price-compare.yaml +93 -0
  102. package/templates/hotel-direct-booking.yaml +113 -0
  103. package/templates/local-services.yaml +98 -0
  104. package/templates/olive-oil-tunisia.yaml +88 -0
  105. package/templates/organic-farm-fresh.yaml +101 -0
  106. package/templates/restaurant-direct.yaml +97 -0
  107. package/docs/DEPLOY.md +0 -118
  108. package/docs/SPEC.md +0 -1540
  109. package/wab-mcp-adapter/README.md +0 -136
  110. package/wab-mcp-adapter/index.js +0 -555
  111. package/wab-mcp-adapter/package.json +0 -17
@@ -1,1513 +1,1558 @@
1
- /**
2
- * Web Agent Bridge v1.1.2
3
- * Open protocol + runtime for AI agent ↔ website interaction
4
- * https://github.com/web-agent-bridge
5
- * License: MIT
6
- */
7
- (function (global) {
8
- 'use strict';
9
-
10
- const VERSION = '1.2.0';
11
- const PROTOCOL_VERSION = '1.0';
12
- const LICENSING_SERVER = 'https://api.webagentbridge.com';
13
- const DISCOVERY_PATHS = ['/agent-bridge.json', '/.well-known/wab.json'];
14
-
15
- // ─── Default Configuration ────────────────────────────────────────────
16
- const DEFAULT_CONFIG = {
17
- agentPermissions: {
18
- readContent: true,
19
- click: true,
20
- fillForms: false,
21
- scroll: true,
22
- navigate: false,
23
- apiAccess: false,
24
- automatedLogin: false,
25
- extractData: false
26
- },
27
- restrictions: {
28
- allowedSelectors: [],
29
- blockedSelectors: ['.private', '[data-private]', '[data-no-agent]'],
30
- requireLoginForActions: [],
31
- rateLimit: { maxCallsPerMinute: 60 }
32
- },
33
- logging: {
34
- enabled: false,
35
- level: 'basic'
36
- },
37
- subscriptionTier: 'free',
38
- licenseKey: null,
39
- /** Public site id from dashboard (preferred). Used with configEndpoint for token exchange — license key stays off the page. */
40
- siteId: null,
41
- /** Base URL for /api/license/* (verify, track). Default: current origin, else LICENSING_SERVER. */
42
- apiBaseUrl: null,
43
- features: {
44
- advancedAnalytics: false,
45
- realTimeUpdates: false,
46
- customActions: false,
47
- webhooks: false,
48
- /** Send execute events to POST /api/license/track (populates admin analytics). */
49
- reportUsage: true
50
- }
51
- };
52
-
53
- // ─── Rate Limiter ─────────────────────────────────────────────────────
54
- class RateLimiter {
55
- constructor(maxPerMinute) {
56
- this.maxPerMinute = maxPerMinute;
57
- this.calls = [];
58
- }
59
-
60
- check() {
61
- const now = Date.now();
62
- this.calls = this.calls.filter(t => now - t < 60000);
63
- if (this.calls.length >= this.maxPerMinute) {
64
- return false;
65
- }
66
- this.calls.push(now);
67
- return true;
68
- }
69
-
70
- get remaining() {
71
- const now = Date.now();
72
- this.calls = this.calls.filter(t => now - t < 60000);
73
- return Math.max(0, this.maxPerMinute - this.calls.length);
74
- }
75
- }
76
-
77
- // ─── Logger ───────────────────────────────────────────────────────────
78
- class BridgeLogger {
79
- constructor(config) {
80
- this.enabled = config.enabled;
81
- this.level = config.level;
82
- this.logs = [];
83
- }
84
-
85
- log(action, details, level = 'basic') {
86
- if (!this.enabled) return;
87
- if (level === 'detailed' && this.level !== 'detailed') return;
88
-
89
- const entry = {
90
- timestamp: new Date().toISOString(),
91
- action,
92
- details,
93
- level
94
- };
95
- this.logs.push(entry);
96
-
97
- if (this.logs.length > 1000) {
98
- this.logs = this.logs.slice(-500);
99
- }
100
- }
101
-
102
- getLogs(filter) {
103
- if (!filter) return [...this.logs];
104
- return this.logs.filter(l => l.action === filter);
105
- }
106
-
107
- clear() {
108
- this.logs = [];
109
- }
110
- }
111
-
112
- // ─── Security Sandbox ──────────────────────────────────────────────────
113
- // Isolates the bridge with origin validation, session tokens, and audit log
114
- class SecuritySandbox {
115
- constructor(config) {
116
- this._sessionToken = this._generateToken();
117
- this._allowedOrigins = config.security?.allowedOrigins || [location.origin];
118
- this._auditLog = [];
119
- this._maxAuditEntries = 500;
120
- this._commandCounter = 0;
121
- this._blockedCommands = new Set();
122
- this._escalationAttempts = 0;
123
- this._maxEscalationAttempts = 5;
124
- this._locked = false;
125
- }
126
-
127
- _generateToken() {
128
- const arr = new Uint8Array(32);
129
- if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
130
- crypto.getRandomValues(arr);
131
- } else {
132
- for (let i = 0; i < 32; i++) arr[i] = Math.floor(Math.random() * 256);
133
- }
134
- return Array.from(arr, b => b.toString(16).padStart(2, '0')).join('');
135
- }
136
-
137
- get sessionToken() { return this._sessionToken; }
138
-
139
- validateOrigin(origin) {
140
- if (!origin) return this._allowedOrigins.includes(location.origin);
141
- return this._allowedOrigins.includes(origin);
142
- }
143
-
144
- audit(action, details, status = 'ok') {
145
- const entry = {
146
- id: ++this._commandCounter,
147
- timestamp: Date.now(),
148
- action,
149
- status,
150
- fingerprint: details?.agentId || 'anonymous'
151
- };
152
- this._auditLog.push(entry);
153
- if (this._auditLog.length > this._maxAuditEntries) {
154
- this._auditLog = this._auditLog.slice(-250);
155
- }
156
- return entry;
157
- }
158
-
159
- getAuditLog(limit = 50) {
160
- return this._auditLog.slice(-limit);
161
- }
162
-
163
- checkEscalation(requestedTier, currentTier) {
164
- const tierLevel = { free: 0, starter: 1, pro: 2, enterprise: 3 };
165
- if ((tierLevel[requestedTier] || 0) > (tierLevel[currentTier] || 0)) {
166
- this._escalationAttempts++;
167
- this.audit('escalation_attempt', { requestedTier, currentTier }, 'blocked');
168
- if (this._escalationAttempts >= this._maxEscalationAttempts) {
169
- this._locked = true;
170
- this.audit('bridge_locked', { reason: 'Too many escalation attempts' }, 'critical');
171
- }
172
- return false;
173
- }
174
- return true;
175
- }
176
-
177
- get isLocked() { return this._locked; }
178
-
179
- validateCommand(command) {
180
- if (this._locked) return { valid: false, error: 'Bridge is locked due to security violations' };
181
- if (typeof command !== 'object' || !command) return { valid: false, error: 'Invalid command format' };
182
- if (typeof command.method !== 'string') return { valid: false, error: 'Command method must be a string' };
183
- if (command.method.length > 200) return { valid: false, error: 'Command method too long' };
184
- if (this._blockedCommands.has(command.method)) return { valid: false, error: 'Command is blocked' };
185
- return { valid: true };
186
- }
187
- }
188
-
189
- // ─── Self-Healing Selectors ───────────────────────────────────────────
190
- // Resilient element resolution for SPAs with dynamic DOM
191
- class SelfHealingSelector {
192
- constructor() {
193
- this._fingerprints = new Map(); // name → element fingerprint
194
- this._healingStats = { healed: 0, failed: 0 };
195
- }
196
-
197
- fingerprint(el) {
198
- if (!el) return null;
199
- return {
200
- tag: el.tagName.toLowerCase(),
201
- id: el.id || null,
202
- classes: Array.from(el.classList),
203
- text: (el.textContent || '').trim().slice(0, 100),
204
- ariaLabel: el.getAttribute('aria-label') || null,
205
- name: el.getAttribute('name') || null,
206
- type: el.getAttribute('type') || null,
207
- role: el.getAttribute('role') || null,
208
- dataTestId: el.getAttribute('data-testid') || null,
209
- dataWabId: el.getAttribute('data-wab-id') || null,
210
- href: el.tagName === 'A' ? el.getAttribute('href') : null,
211
- placeholder: el.getAttribute('placeholder') || null,
212
- parentTag: el.parentElement ? el.parentElement.tagName.toLowerCase() : null,
213
- index: el.parentElement ? Array.from(el.parentElement.children).indexOf(el) : -1
214
- };
215
- }
216
-
217
- store(actionName, selector) {
218
- const el = safeQuerySelector(selector);
219
- if (el) {
220
- this._fingerprints.set(actionName, {
221
- selector,
222
- fp: this.fingerprint(el),
223
- storedAt: Date.now()
224
- });
225
- }
226
- }
227
-
228
- resolve(actionName, originalSelector) {
229
- // Try original selector first
230
- const el = safeQuerySelector(originalSelector);
231
- if (el) return { element: el, selector: originalSelector, healed: false };
232
-
233
- // Try self-healing
234
- const stored = this._fingerprints.get(actionName);
235
- if (!stored || !stored.fp) {
236
- this._healingStats.failed++;
237
- return null;
238
- }
239
-
240
- const healed = this._heal(stored.fp);
241
- if (healed) {
242
- this._healingStats.healed++;
243
- return healed;
244
- }
245
-
246
- this._healingStats.failed++;
247
- return null;
248
- }
249
-
250
- _heal(fp) {
251
- // Strategy 1: data-wab-id (most stable)
252
- if (fp.dataWabId) {
253
- const el = safeQuerySelector(`[data-wab-id="${fp.dataWabId}"]`);
254
- if (el) return { element: el, selector: `[data-wab-id="${fp.dataWabId}"]`, healed: true, strategy: 'data-wab-id' };
255
- }
256
-
257
- // Strategy 2: data-testid
258
- if (fp.dataTestId) {
259
- const el = safeQuerySelector(`[data-testid="${fp.dataTestId}"]`);
260
- if (el) return { element: el, selector: `[data-testid="${fp.dataTestId}"]`, healed: true, strategy: 'data-testid' };
261
- }
262
-
263
- // Strategy 3: id (may have changed)
264
- if (fp.id) {
265
- const el = safeQuerySelector(`#${CSS.escape(fp.id)}`);
266
- if (el) return { element: el, selector: `#${CSS.escape(fp.id)}`, healed: true, strategy: 'id' };
267
- }
268
-
269
- // Strategy 4: aria-label (semantic, usually stable)
270
- if (fp.ariaLabel) {
271
- const sel = `${fp.tag}[aria-label="${CSS.escape(fp.ariaLabel)}"]`;
272
- const el = safeQuerySelector(sel);
273
- if (el) return { element: el, selector: sel, healed: true, strategy: 'aria-label' };
274
- }
275
-
276
- // Strategy 5: name attribute
277
- if (fp.name) {
278
- const sel = `${fp.tag}[name="${CSS.escape(fp.name)}"]`;
279
- const el = safeQuerySelector(sel);
280
- if (el) return { element: el, selector: sel, healed: true, strategy: 'name' };
281
- }
282
-
283
- // Strategy 6: text content matching (fuzzy)
284
- if (fp.text && fp.text.length > 0) {
285
- const candidates = safeQuerySelectorAll(fp.tag);
286
- const target = fp.text.toLowerCase();
287
- let bestMatch = null;
288
- let bestScore = 0;
289
-
290
- for (const candidate of candidates) {
291
- const candidateText = (candidate.textContent || '').trim().toLowerCase();
292
- if (!candidateText) continue;
293
-
294
- const score = this._textSimilarity(target, candidateText);
295
- if (score > 0.7 && score > bestScore) {
296
- bestScore = score;
297
- bestMatch = candidate;
298
- }
299
- }
300
-
301
- if (bestMatch) {
302
- const healedSel = this._buildSelectorFor(bestMatch);
303
- return { element: bestMatch, selector: healedSel, healed: true, strategy: 'text-fuzzy', confidence: bestScore };
304
- }
305
- }
306
-
307
- // Strategy 7: role + position heuristic
308
- if (fp.role && fp.parentTag) {
309
- const candidates = safeQuerySelectorAll(`${fp.parentTag} > ${fp.tag}[role="${fp.role}"]`);
310
- if (candidates.length > 0 && fp.index >= 0 && fp.index < candidates.length) {
311
- const el = candidates[fp.index];
312
- const sel = this._buildSelectorFor(el);
313
- return { element: el, selector: sel, healed: true, strategy: 'role-position' };
314
- }
315
- }
316
-
317
- return null;
318
- }
319
-
320
- _textSimilarity(a, b) {
321
- if (a === b) return 1;
322
- const longer = a.length > b.length ? a : b;
323
- const shorter = a.length > b.length ? b : a;
324
- if (longer.length === 0) return 1;
325
- if (longer.includes(shorter) || shorter.includes(longer)) {
326
- return shorter.length / longer.length;
327
- }
328
- // Simple bigram similarity
329
- const bigramsA = new Set();
330
- for (let i = 0; i < a.length - 1; i++) bigramsA.add(a.slice(i, i + 2));
331
- let matches = 0;
332
- for (let i = 0; i < b.length - 1; i++) {
333
- if (bigramsA.has(b.slice(i, i + 2))) matches++;
334
- }
335
- const total = Math.max(bigramsA.size, b.length - 1);
336
- return total > 0 ? matches / total : 0;
337
- }
338
-
339
- _buildSelectorFor(el) {
340
- if (el.id) return `#${CSS.escape(el.id)}`;
341
- if (el.dataset.wabId) return `[data-wab-id="${el.dataset.wabId}"]`;
342
- const tag = el.tagName.toLowerCase();
343
- const attrs = ['data-testid', 'aria-label', 'name'];
344
- for (const attr of attrs) {
345
- const val = el.getAttribute(attr);
346
- if (val && document.querySelectorAll(`${tag}[${attr}="${CSS.escape(val)}"]`).length === 1) {
347
- return `${tag}[${attr}="${CSS.escape(val)}"]`;
348
- }
349
- }
350
- return null;
351
- }
352
-
353
- getStats() {
354
- return { ...this._healingStats, tracked: this._fingerprints.size };
355
- }
356
- }
357
-
358
- // ─── Stealth / Human-like Interaction ─────────────────────────────────
359
- // ⚠️ ETHICAL USE POLICY:
360
- // Stealth mode simulates human-like interaction patterns for LEGITIMATE uses:
361
- // - Accessibility testing - QA automation on YOUR OWN sites
362
- // - UX research with consent - Authorized penetration testing
363
- // DO NOT use to bypass anti-bot protections on sites you do not own or control.
364
- // Misuse violates the MIT license terms and is the user's legal responsibility.
365
- const Stealth = {
366
- _enabled: false,
367
- _consentGiven: false,
368
-
369
- enable(consent) {
370
- if (consent !== true) {
371
- console.warn('[WAB] Stealth mode requires explicit consent: stealth.enable(true)');
372
- return;
373
- }
374
- this._consentGiven = true;
375
- this._enabled = true;
376
- },
377
- disable() { this._enabled = false; },
378
- get isEnabled() { return this._enabled; },
379
-
380
- // Random delay between min and max ms
381
- delay(min = 50, max = 300) {
382
- if (!this._enabled) return Promise.resolve();
383
- const duration = min + Math.floor(Math.random() * (max - min));
384
- return new Promise(resolve => setTimeout(resolve, duration));
385
- },
386
-
387
- // Simulate a full mouse event chain: mouseover → mouseenter → mousemove → mousedown → mouseup → click
388
- async simulateClick(el) {
389
- if (!el) return;
390
- const rect = el.getBoundingClientRect();
391
- const x = rect.left + rect.width * (0.3 + Math.random() * 0.4);
392
- const y = rect.top + rect.height * (0.3 + Math.random() * 0.4);
393
- const eventOpts = { bubbles: true, cancelable: true, clientX: x, clientY: y, view: window };
394
-
395
- el.dispatchEvent(new MouseEvent('mouseover', eventOpts));
396
- el.dispatchEvent(new MouseEvent('mouseenter', { ...eventOpts, bubbles: false }));
397
- await this.delay(30, 80);
398
- el.dispatchEvent(new MouseEvent('mousemove', eventOpts));
399
- await this.delay(40, 120);
400
- el.dispatchEvent(new MouseEvent('mousedown', eventOpts));
401
- await this.delay(50, 150);
402
- el.dispatchEvent(new MouseEvent('mouseup', eventOpts));
403
- el.dispatchEvent(new MouseEvent('click', eventOpts));
404
- },
405
-
406
- // Simulate human-like typing with variable delays
407
- async simulateTyping(el, text) {
408
- if (!el) return;
409
- el.focus();
410
- el.dispatchEvent(new Event('focus', { bubbles: true }));
411
- el.value = '';
412
-
413
- for (let i = 0; i < text.length; i++) {
414
- const char = text[i];
415
- el.dispatchEvent(new KeyboardEvent('keydown', { key: char, bubbles: true }));
416
- el.value += char;
417
- el.dispatchEvent(new Event('input', { bubbles: true }));
418
- el.dispatchEvent(new KeyboardEvent('keyup', { key: char, bubbles: true }));
419
- await this.delay(30, 120); // Human typing speed: 30-120ms per key
420
- }
421
-
422
- el.dispatchEvent(new Event('change', { bubbles: true }));
423
- },
424
-
425
- // Simulate natural scrolling (variable speed, easing)
426
- async simulateScroll(el, direction = 'down') {
427
- const target = el || document.documentElement;
428
- const distance = 300 + Math.floor(Math.random() * 400);
429
- const steps = 5 + Math.floor(Math.random() * 5);
430
- const stepSize = distance / steps;
431
-
432
- for (let i = 0; i < steps; i++) {
433
- const delta = direction === 'down' ? stepSize : -stepSize;
434
- if (el && el !== document.documentElement) {
435
- el.scrollTop += delta;
436
- } else {
437
- window.scrollBy(0, delta);
438
- }
439
- await this.delay(15, 50);
440
- }
441
- }
442
- };
443
-
444
- // ─── Element Utilities ────────────────────────────────────────────────
445
- function isElementAllowed(selector, config) {
446
- const { allowedSelectors, blockedSelectors } = config.restrictions;
447
-
448
- if (blockedSelectors.length > 0) {
449
- const el = document.querySelector(selector);
450
- if (el) {
451
- for (const blocked of blockedSelectors) {
452
- if (el.matches(blocked) || el.closest(blocked)) return false;
453
- }
454
- }
455
- }
456
-
457
- if (allowedSelectors.length > 0) {
458
- const el = document.querySelector(selector);
459
- if (el) {
460
- for (const allowed of allowedSelectors) {
461
- if (el.matches(allowed) || el.closest(allowed)) return true;
462
- }
463
- return false;
464
- }
465
- }
466
-
467
- return true;
468
- }
469
-
470
- function safeQuerySelector(selector) {
471
- try {
472
- return document.querySelector(selector);
473
- } catch (e) {
474
- return null;
475
- }
476
- }
477
-
478
- function safeQuerySelectorAll(selector) {
479
- try {
480
- return Array.from(document.querySelectorAll(selector));
481
- } catch (e) {
482
- return [];
483
- }
484
- }
485
-
486
- // ─── Action Registry ──────────────────────────────────────────────────
487
- class ActionRegistry {
488
- constructor() {
489
- this.actions = new Map();
490
- }
491
-
492
- register(action) {
493
- if (!action.name || !action.description) {
494
- throw new Error('Action must have a name and description');
495
- }
496
- this.actions.set(action.name, {
497
- name: action.name,
498
- description: action.description,
499
- trigger: action.trigger || 'click',
500
- selector: action.selector || null,
501
- fields: action.fields || null,
502
- submitSelector: action.submitSelector || null,
503
- endpoint: action.endpoint || null,
504
- method: action.method || 'GET',
505
- requiresAuth: action.requiresAuth || false,
506
- category: action.category || 'general',
507
- params: action.params || null,
508
- handler: action.handler || null,
509
- metadata: action.metadata || {}
510
- });
511
- }
512
-
513
- unregister(name) {
514
- return this.actions.delete(name);
515
- }
516
-
517
- get(name) {
518
- return this.actions.get(name) || null;
519
- }
520
-
521
- list() {
522
- return Array.from(this.actions.values()).map(a => ({
523
- name: a.name,
524
- description: a.description,
525
- trigger: a.trigger,
526
- category: a.category,
527
- requiresAuth: a.requiresAuth,
528
- params: a.params,
529
- fields: a.fields ? a.fields.map(f => ({ name: f.name, type: f.type, required: f.required !== false })) : null
530
- }));
531
- }
532
-
533
- getByCategory(category) {
534
- return this.list().filter(a => a.category === category);
535
- }
536
-
537
- toJSON() {
538
- return this.list();
539
- }
540
- }
541
-
542
- // ─── Event Emitter ────────────────────────────────────────────────────
543
- class BridgeEventEmitter {
544
- constructor() {
545
- this.listeners = {};
546
- }
547
-
548
- on(event, callback) {
549
- if (!this.listeners[event]) this.listeners[event] = [];
550
- this.listeners[event].push(callback);
551
- return () => this.off(event, callback);
552
- }
553
-
554
- off(event, callback) {
555
- if (!this.listeners[event]) return;
556
- this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
557
- }
558
-
559
- emit(event, data) {
560
- if (!this.listeners[event]) return;
561
- this.listeners[event].forEach(cb => {
562
- try { cb(data); } catch (e) { console.error(`[WAB] Event handler error for "${event}":`, e); }
563
- });
564
- }
565
- }
566
-
567
- // ─── Main Bridge Class ────────────────────────────────────────────────
568
- class WebAgentBridge {
569
- constructor(userConfig) {
570
- this.config = this._mergeConfig(DEFAULT_CONFIG, userConfig || {});
571
- this.registry = new ActionRegistry();
572
- this.rateLimiter = new RateLimiter(this.config.restrictions.rateLimit.maxCallsPerMinute);
573
- this.logger = new BridgeLogger(this.config.logging);
574
- this.events = new BridgeEventEmitter();
575
- this.security = new SecuritySandbox(this.config);
576
- this.healer = new SelfHealingSelector();
577
- this.stealth = Stealth;
578
- this.authenticated = false;
579
- this.agentInfo = null;
580
- this._licenseVerified = null;
581
- this._discoveryDoc = null;
582
- this._ready = false;
583
- this._readyCallbacks = [];
584
- this._mutationObserver = null;
585
- this._eventSubscriptions = new Map();
586
-
587
- // Enable stealth mode if configured (requires consent: true)
588
- if (this.config.stealth?.enabled && this.config.stealth?.consent === true) {
589
- this.stealth.enable(true);
590
- }
591
-
592
- this._init();
593
- }
594
-
595
- // ── Initialization ──────────────────────────────────────────────────
596
- async _init() {
597
- await this._fetchDiscoveryDocument();
598
-
599
- if (this.config.configEndpoint && (this.config.siteId || this.config._licenseKey || this.config.licenseKey)) {
600
- await this._secureLicenseExchange();
601
- } else if (this.config.licenseKey) {
602
- await this._verifyLicense();
603
- } else {
604
- this._licenseVerified = { tier: 'free', valid: true };
605
- }
606
-
607
- this._autoDiscoverActions();
608
- this._storeFingerprints();
609
- this._setupSPAObserver();
610
- this._ready = true;
611
- this._readyCallbacks.forEach(cb => cb());
612
- this._readyCallbacks = [];
613
- this.events.emit('ready', { version: VERSION, protocol: PROTOCOL_VERSION, tier: this.getEffectiveTier() });
614
- this.logger.log('init', { version: VERSION, protocol: PROTOCOL_VERSION, tier: this.getEffectiveTier(), security: 'sandbox-active' });
615
- }
616
-
617
- async _fetchDiscoveryDocument() {
618
- var base = this._getLicenseApiBase();
619
- for (var i = 0; i < DISCOVERY_PATHS.length; i++) {
620
- try {
621
- var res = await fetch(base + DISCOVERY_PATHS[i], { method: 'GET', credentials: 'omit' });
622
- if (res.ok) {
623
- this._discoveryDoc = await res.json();
624
- this.logger.log('discovery', { path: DISCOVERY_PATHS[i], provider: this._discoveryDoc.provider });
625
- this.events.emit('discovery', this._discoveryDoc);
626
- return;
627
- }
628
- } catch (_) {}
629
- }
630
- }
631
-
632
- // Secure license exchange: POST license key to server, get session token back
633
- // License key is transmitted once via POST (not visible in page source)
634
- async _secureLicenseExchange() {
635
- try {
636
- const endpoint = this.config.configEndpoint;
637
- const body = this.config.siteId
638
- ? { siteId: this.config.siteId }
639
- : { licenseKey: this.config._licenseKey || this.config.licenseKey };
640
- const res = await fetch(endpoint, {
641
- method: 'POST',
642
- headers: { 'Content-Type': 'application/json' },
643
- body: JSON.stringify(body)
644
- });
645
- if (res.ok) {
646
- const data = await res.json();
647
- this._licenseVerified = { tier: data.tier, valid: true, sessionToken: data.sessionToken };
648
- delete this.config._licenseKey;
649
- if (data.expiresIn) {
650
- if (this._tokenRefreshTimer) clearTimeout(this._tokenRefreshTimer);
651
- this._tokenRefreshTimer = setTimeout(() => {
652
- this._secureLicenseExchange();
653
- }, Math.floor(data.expiresIn * 800));
654
- }
655
- } else {
656
- this._licenseVerified = { tier: 'free', valid: false, error: 'Token exchange failed' };
657
- }
658
- } catch (e) {
659
- this._licenseVerified = { tier: this.config.subscriptionTier || 'free', valid: false, error: 'Offline' };
660
- }
661
- }
662
-
663
- // Store fingerprints for all discovered actions (self-healing)
664
- _storeFingerprints() {
665
- for (const action of this.registry.actions.values()) {
666
- if (action.selector) {
667
- this.healer.store(action.name, action.selector);
668
- }
669
- }
670
- }
671
-
672
- // Watch for SPA DOM changes and re-discover actions
673
- _setupSPAObserver() {
674
- if (this._mutationObserver) this._mutationObserver.disconnect();
675
-
676
- let debounceTimer = null;
677
- this._mutationObserver = new MutationObserver(() => {
678
- if (debounceTimer) clearTimeout(debounceTimer);
679
- debounceTimer = setTimeout(() => {
680
- this._autoDiscoverActions();
681
- this._storeFingerprints();
682
- this.events.emit('dom:changed', { actionsCount: this.registry.actions.size });
683
- }, 500);
684
- });
685
-
686
- this._mutationObserver.observe(document.body, {
687
- childList: true,
688
- subtree: true,
689
- attributes: false
690
- });
691
- }
692
-
693
- onReady(callback) {
694
- if (this._ready) {
695
- callback();
696
- } else {
697
- this._readyCallbacks.push(callback);
698
- }
699
- }
700
-
701
- _mergeConfig(defaults, overrides) {
702
- const result = {};
703
- for (const key of Object.keys(defaults)) {
704
- if (typeof defaults[key] === 'object' && defaults[key] !== null && !Array.isArray(defaults[key])) {
705
- result[key] = this._mergeConfig(defaults[key], overrides[key] || {});
706
- } else {
707
- result[key] = overrides[key] !== undefined ? overrides[key] : defaults[key];
708
- }
709
- }
710
- for (const key of Object.keys(overrides)) {
711
- if (!(key in defaults)) {
712
- result[key] = overrides[key];
713
- }
714
- }
715
- return result;
716
- }
717
-
718
- _getLicenseApiBase() {
719
- const c = this.config;
720
- if (c.apiBaseUrl) return String(c.apiBaseUrl).replace(/\/$/, '');
721
- if (typeof global.location !== 'undefined' && location && location.origin) return location.origin;
722
- return LICENSING_SERVER;
723
- }
724
-
725
- /**
726
- * Report action execution to WAB (fills platform analytics in admin).
727
- */
728
- _maybeReportUsage(actionName, triggerType, success) {
729
- try {
730
- const sessionToken = this._licenseVerified && this._licenseVerified.sessionToken;
731
- if (!sessionToken || (this.config.features && this.config.features.reportUsage === false)) return;
732
- const base = this._getLicenseApiBase();
733
- const payload = JSON.stringify({
734
- sessionToken,
735
- actionName,
736
- triggerType: triggerType || 'unknown',
737
- success: success !== false
738
- });
739
- fetch(`${base}/api/license/track`, {
740
- method: 'POST',
741
- headers: { 'Content-Type': 'application/json' },
742
- body: payload,
743
- keepalive: true,
744
- mode: 'cors',
745
- credentials: 'omit'
746
- }).catch(function () {});
747
- } catch (e) { /* ignore */ }
748
- }
749
-
750
- // ── License Verification ────────────────────────────────────────────
751
- async _verifyLicense() {
752
- try {
753
- const res = await fetch(`${this._getLicenseApiBase()}/api/license/verify`, {
754
- method: 'POST',
755
- headers: { 'Content-Type': 'application/json' },
756
- body: JSON.stringify({
757
- domain: location.hostname,
758
- licenseKey: this.config.licenseKey
759
- })
760
- });
761
- if (res.ok) {
762
- this._licenseVerified = await res.json();
763
- } else {
764
- this._licenseVerified = { tier: 'free', valid: false, error: 'License verification failed' };
765
- }
766
- } catch (e) {
767
- this._licenseVerified = { tier: this.config.subscriptionTier || 'free', valid: false, error: 'Offline' };
768
- }
769
- }
770
-
771
- getEffectiveTier() {
772
- if (this._licenseVerified && this._licenseVerified.valid) {
773
- return this._licenseVerified.tier;
774
- }
775
- return 'free';
776
- }
777
-
778
- // ── Auto-discover Page Actions ──────────────────────────────────────
779
- _autoDiscoverActions() {
780
- const buttons = safeQuerySelectorAll('button, [role="button"], input[type="submit"], a.btn, a.button');
781
- buttons.forEach((el, i) => {
782
- const text = (el.textContent || el.value || '').trim();
783
- if (!text) return;
784
-
785
- const selector = this._generateSelector(el);
786
- if (!selector || !isElementAllowed(selector, this.config)) return;
787
-
788
- const name = this._slugify(text) || `action_${i}`;
789
- if (!this.registry.get(name)) {
790
- this.registry.register({
791
- name,
792
- description: `Click: ${text}`,
793
- trigger: 'click',
794
- selector,
795
- category: 'auto-discovered'
796
- });
797
- }
798
- });
799
-
800
- const forms = safeQuerySelectorAll('form');
801
- forms.forEach((form, i) => {
802
- const formSelector = this._generateSelector(form);
803
- if (!formSelector || !isElementAllowed(formSelector, this.config)) return;
804
-
805
- const fields = Array.from(form.querySelectorAll('input, textarea, select'))
806
- .filter(f => f.type !== 'hidden' && f.type !== 'submit')
807
- .map(f => ({
808
- name: f.name || f.id || f.placeholder || `field_${Math.random().toString(36).slice(2, 6)}`,
809
- selector: this._generateSelector(f),
810
- type: f.type || 'text',
811
- required: f.required,
812
- placeholder: f.placeholder || ''
813
- }));
814
-
815
- const submitBtn = form.querySelector('[type="submit"], button:not([type])');
816
- const formName = form.id || form.name || `form_${i}`;
817
-
818
- this.registry.register({
819
- name: `fill_${this._slugify(formName)}`,
820
- description: `Fill and submit form: ${formName}`,
821
- trigger: 'fill_and_submit',
822
- selector: formSelector,
823
- fields,
824
- submitSelector: submitBtn ? this._generateSelector(submitBtn) : null,
825
- category: 'auto-discovered'
826
- });
827
- });
828
-
829
- const links = safeQuerySelectorAll('nav a, [role="navigation"] a');
830
- links.forEach((el, i) => {
831
- const text = (el.textContent || '').trim();
832
- if (!text) return;
833
-
834
- const selector = this._generateSelector(el);
835
- if (!selector || !isElementAllowed(selector, this.config)) return;
836
-
837
- const name = `nav_${this._slugify(text)}` || `nav_${i}`;
838
- if (!this.registry.get(name)) {
839
- this.registry.register({
840
- name,
841
- description: `Navigate: ${text}`,
842
- trigger: 'click',
843
- selector,
844
- category: 'navigation'
845
- });
846
- }
847
- });
848
- }
849
-
850
- _generateSelector(el) {
851
- if (el.id) return `#${CSS.escape(el.id)}`;
852
- if (el.dataset.wabId) return `[data-wab-id="${el.dataset.wabId}"]`;
853
-
854
- const classes = Array.from(el.classList).filter(c => !c.match(/^(js-|is-|has-)/));
855
- if (classes.length > 0) {
856
- const sel = `${el.tagName.toLowerCase()}.${classes.map(c => CSS.escape(c)).join('.')}`;
857
- if (document.querySelectorAll(sel).length === 1) return sel;
858
- }
859
-
860
- const attrs = ['name', 'data-testid', 'aria-label', 'title', 'role'];
861
- for (const attr of attrs) {
862
- const val = el.getAttribute(attr);
863
- if (val) {
864
- const sel = `${el.tagName.toLowerCase()}[${attr}="${CSS.escape(val)}"]`;
865
- if (document.querySelectorAll(sel).length === 1) return sel;
866
- }
867
- }
868
-
869
- const path = [];
870
- let current = el;
871
- while (current && current !== document.body) {
872
- let tag = current.tagName.toLowerCase();
873
- if (current.id) {
874
- path.unshift(`#${CSS.escape(current.id)}`);
875
- break;
876
- }
877
- const parent = current.parentElement;
878
- if (parent) {
879
- const siblings = Array.from(parent.children).filter(c => c.tagName === current.tagName);
880
- if (siblings.length > 1) {
881
- tag += `:nth-of-type(${siblings.indexOf(current) + 1})`;
882
- }
883
- }
884
- path.unshift(tag);
885
- current = parent;
886
- }
887
- return path.join(' > ');
888
- }
889
-
890
- _slugify(text) {
891
- return text
892
- .toLowerCase()
893
- .replace(/[^\w\s-]/g, '')
894
- .replace(/[\s_]+/g, '_')
895
- .replace(/^-+|-+$/g, '')
896
- .slice(0, 40);
897
- }
898
-
899
- // ── Agent Authentication ────────────────────────────────────────────
900
- authenticate(agentKey, agentMeta = {}) {
901
- this.logger.log('authenticate', { agentKey: agentKey ? '***' : null });
902
- this.events.emit('agent:authenticate', { agentMeta });
903
- this.authenticated = true;
904
- this.agentInfo = { key: agentKey, ...agentMeta, authenticatedAt: new Date().toISOString() };
905
- return { success: true, permissions: this._getEffectivePermissions() };
906
- }
907
-
908
- // ── Permission Checks ───────────────────────────────────────────────
909
- _getEffectivePermissions() {
910
- const perms = { ...this.config.agentPermissions };
911
- const tier = this.getEffectiveTier();
912
-
913
- if (tier === 'free') {
914
- perms.apiAccess = false;
915
- perms.automatedLogin = false;
916
- perms.extractData = false;
917
- }
918
-
919
- return perms;
920
- }
921
-
922
- _checkPermission(action) {
923
- const perms = this._getEffectivePermissions();
924
-
925
- switch (action) {
926
- case 'click': return perms.click;
927
- case 'fill_and_submit': return perms.fillForms;
928
- case 'scroll': return perms.scroll;
929
- case 'navigate': return perms.navigate;
930
- case 'api': return perms.apiAccess;
931
- case 'read': return perms.readContent;
932
- case 'extract': return perms.extractData;
933
- default: return perms.click;
934
- }
935
- }
936
-
937
- // ── Core: Execute Action ────────────────────────────────────────────
938
- async execute(actionName, params = {}) {
939
- // Security: check if bridge is locked
940
- if (this.security.isLocked) {
941
- return { success: false, error: 'Bridge locked due to security violations' };
942
- }
943
-
944
- if (!this.rateLimiter.check()) {
945
- const error = { success: false, error: 'Rate limit exceeded', retryAfter: 60 };
946
- this.logger.log('rate_limit', { action: actionName });
947
- this.security.audit('rate_limit', { action: actionName }, 'blocked');
948
- this.events.emit('error', error);
949
- return error;
950
- }
951
-
952
- const action = this.registry.get(actionName);
953
- if (!action) {
954
- return { success: false, error: `Action "${actionName}" not found`, available: this.registry.list().map(a => a.name) };
955
- }
956
-
957
- if (!this._checkPermission(action.trigger)) {
958
- this.security.audit('permission_denied', { action: actionName, trigger: action.trigger }, 'blocked');
959
- return { success: false, error: `Permission denied for trigger type: ${action.trigger}`, tier: this.getEffectiveTier() };
960
- }
961
-
962
- if (action.requiresAuth && !this.authenticated) {
963
- return { success: false, error: 'Authentication required for this action' };
964
- }
965
-
966
- const loginRequired = this.config.restrictions.requireLoginForActions || [];
967
- if (loginRequired.includes(action.trigger) && !this.authenticated) {
968
- return { success: false, error: 'Login required for this action type' };
969
- }
970
-
971
- // Self-healing: resolve selector if original is broken
972
- if (action.selector) {
973
- const resolved = this.healer.resolve(actionName, action.selector);
974
- if (resolved && resolved.healed) {
975
- action.selector = resolved.selector;
976
- this.logger.log('self_heal', { action: actionName, strategy: resolved.strategy, confidence: resolved.confidence }, 'detailed');
977
- this.events.emit('selector:healed', { action: actionName, strategy: resolved.strategy });
978
- }
979
- }
980
-
981
- this.logger.log('execute', { action: actionName, params }, 'basic');
982
- this.security.audit('execute', { action: actionName, agentId: this.agentInfo?.key });
983
- this.events.emit('action:before', { action: actionName, params });
984
-
985
- try {
986
- let result;
987
-
988
- if (action.handler) {
989
- result = await action.handler(params);
990
- } else {
991
- switch (action.trigger) {
992
- case 'click':
993
- result = await this._executeClick(action);
994
- break;
995
- case 'fill_and_submit':
996
- result = await this._executeFillAndSubmit(action, params);
997
- break;
998
- case 'scroll':
999
- result = await this._executeScroll(action);
1000
- break;
1001
- case 'api':
1002
- result = await this._executeApi(action, params);
1003
- break;
1004
- default:
1005
- result = { success: false, error: `Unknown trigger: ${action.trigger}` };
1006
- }
1007
- }
1008
-
1009
- this.events.emit('action:after', { action: actionName, result });
1010
- this.logger.log('execute_result', { action: actionName, success: result.success }, 'detailed');
1011
- this._maybeReportUsage(actionName, action.trigger, !!(result && result.success !== false));
1012
- return result;
1013
-
1014
- } catch (err) {
1015
- const error = { success: false, error: err.message };
1016
- this.events.emit('error', { action: actionName, error: err.message });
1017
- this.logger.log('execute_error', { action: actionName, error: err.message });
1018
- this._maybeReportUsage(actionName, action.trigger, false);
1019
- return error;
1020
- }
1021
- }
1022
-
1023
- async _executeClick(action) {
1024
- if (!action.selector) return { success: false, error: 'No selector defined' };
1025
- if (!isElementAllowed(action.selector, this.config)) {
1026
- return { success: false, error: 'Element is blocked by restrictions' };
1027
- }
1028
-
1029
- // Self-healing: try to find element even if selector is stale
1030
- let el = safeQuerySelector(action.selector);
1031
- if (!el) {
1032
- const resolved = this.healer.resolve(action.name, action.selector);
1033
- if (resolved) {
1034
- el = resolved.element;
1035
- } else {
1036
- return { success: false, error: `Element not found: ${action.selector}` };
1037
- }
1038
- }
1039
-
1040
- // Stealth: use human-like click simulation
1041
- if (this.stealth.isEnabled) {
1042
- await this.stealth.delay(100, 400);
1043
- await this.stealth.simulateClick(el);
1044
- } else {
1045
- el.click();
1046
- }
1047
-
1048
- return { success: true, action: 'click', selector: action.selector };
1049
- }
1050
-
1051
- async _executeFillAndSubmit(action, params) {
1052
- if (!action.fields) return { success: false, error: 'No fields defined' };
1053
-
1054
- const results = [];
1055
- for (const field of action.fields) {
1056
- if (!isElementAllowed(field.selector, this.config)) {
1057
- results.push({ field: field.name, success: false, error: 'Element blocked' });
1058
- continue;
1059
- }
1060
-
1061
- let el = safeQuerySelector(field.selector);
1062
- if (!el) {
1063
- // Self-healing: try to find field by name/placeholder
1064
- const healedField = this.healer.resolve(`field_${field.name}`, field.selector);
1065
- if (healedField) {
1066
- el = healedField.element;
1067
- } else {
1068
- results.push({ field: field.name, success: false, error: 'Element not found' });
1069
- continue;
1070
- }
1071
- }
1072
-
1073
- const value = params[field.name];
1074
- if (value !== undefined) {
1075
- if (this.stealth.isEnabled) {
1076
- await this.stealth.delay(200, 600);
1077
- await this.stealth.simulateTyping(el, String(value));
1078
- } else {
1079
- el.focus();
1080
- el.value = value;
1081
- el.dispatchEvent(new Event('input', { bubbles: true }));
1082
- el.dispatchEvent(new Event('change', { bubbles: true }));
1083
- }
1084
- results.push({ field: field.name, success: true });
1085
- } else if (field.required !== false) {
1086
- results.push({ field: field.name, success: false, error: 'Value required but not provided' });
1087
- }
1088
- }
1089
-
1090
- if (action.submitSelector) {
1091
- let submitEl = safeQuerySelector(action.submitSelector);
1092
- if (submitEl) {
1093
- if (this.stealth.isEnabled) {
1094
- await this.stealth.delay(300, 800);
1095
- await this.stealth.simulateClick(submitEl);
1096
- } else {
1097
- submitEl.click();
1098
- }
1099
- results.push({ field: '_submit', success: true });
1100
- }
1101
- }
1102
-
1103
- return { success: results.every(r => r.success), results };
1104
- }
1105
-
1106
- async _executeScroll(action) {
1107
- if (action.selector) {
1108
- const el = safeQuerySelector(action.selector);
1109
- if (el) {
1110
- if (this.stealth.isEnabled) {
1111
- await this.stealth.simulateScroll(el);
1112
- } else {
1113
- el.scrollIntoView({ behavior: 'smooth', block: 'center' });
1114
- }
1115
- return { success: true, action: 'scroll', selector: action.selector };
1116
- }
1117
- return { success: false, error: `Element not found: ${action.selector}` };
1118
- }
1119
- if (this.stealth.isEnabled) {
1120
- await this.stealth.simulateScroll(null, 'down');
1121
- } else {
1122
- window.scrollBy({ top: 500, behavior: 'smooth' });
1123
- }
1124
- return { success: true, action: 'scroll', direction: 'down' };
1125
- }
1126
-
1127
- async _executeApi(action, params) {
1128
- if (this.getEffectiveTier() === 'free') {
1129
- return { success: false, error: 'API access requires a premium subscription' };
1130
- }
1131
-
1132
- const url = new URL(action.endpoint, location.origin);
1133
- const options = { method: action.method || 'GET', headers: { 'Content-Type': 'application/json' } };
1134
-
1135
- if (action.method !== 'GET' && params) {
1136
- options.body = JSON.stringify(params);
1137
- }
1138
-
1139
- const res = await fetch(url.toString(), options);
1140
- const data = await res.json().catch(() => null);
1141
- return { success: res.ok, status: res.status, data };
1142
- }
1143
-
1144
- // ── Content Reading ─────────────────────────────────────────────────
1145
- readContent(selector) {
1146
- if (!this._checkPermission('read')) {
1147
- return { success: false, error: 'readContent permission denied' };
1148
- }
1149
-
1150
- if (!isElementAllowed(selector, this.config)) {
1151
- return { success: false, error: 'Element is blocked by restrictions' };
1152
- }
1153
-
1154
- const el = safeQuerySelector(selector);
1155
- if (!el) return { success: false, error: 'Element not found' };
1156
-
1157
- return {
1158
- success: true,
1159
- text: el.textContent.trim(),
1160
- html: el.innerHTML,
1161
- attributes: Object.fromEntries(
1162
- Array.from(el.attributes).map(a => [a.name, a.value])
1163
- )
1164
- };
1165
- }
1166
-
1167
- getPageInfo() {
1168
- return {
1169
- title: document.title,
1170
- url: location.href,
1171
- domain: location.hostname,
1172
- lang: document.documentElement.lang || 'unknown',
1173
- bridgeVersion: VERSION,
1174
- tier: this.getEffectiveTier(),
1175
- permissions: this._getEffectivePermissions(),
1176
- actionsCount: this.registry.actions.size,
1177
- rateLimitRemaining: this.rateLimiter.remaining,
1178
- security: {
1179
- sandboxActive: true,
1180
- locked: this.security.isLocked,
1181
- sessionToken: this.security.sessionToken
1182
- },
1183
- selfHealing: this.healer.getStats(),
1184
- stealthMode: this.stealth.isEnabled
1185
- };
1186
- }
1187
-
1188
- // ── Custom Action Registration ──────────────────────────────────────
1189
- registerAction(actionDef) {
1190
- this.registry.register(actionDef);
1191
- this.events.emit('action:registered', { name: actionDef.name });
1192
- this.logger.log('register_action', { name: actionDef.name });
1193
- }
1194
-
1195
- unregisterAction(name) {
1196
- this.registry.unregister(name);
1197
- this.events.emit('action:unregistered', { name });
1198
- }
1199
-
1200
- // ── Protocol Discovery ──────────────────────────────────────────────
1201
- discover() {
1202
- return {
1203
- wab_version: PROTOCOL_VERSION,
1204
- runtime_version: VERSION,
1205
- discovery_document: this._discoveryDoc,
1206
- page: this.getPageInfo(),
1207
- actions: this.getActions(),
1208
- fairness: this._discoveryDoc ? this._discoveryDoc.fairness : null,
1209
- transport: {
1210
- js_global: { enabled: true, interface: 'window.AICommands' },
1211
- bidi: { enabled: true, interface: 'window.__wab_bidi' },
1212
- noscript: { enabled: !!(this.config.siteId) }
1213
- }
1214
- };
1215
- }
1216
-
1217
- subscribe(eventName, callback) {
1218
- if (typeof callback !== 'function') return { success: false, error: 'callback must be a function' };
1219
- var id = 'sub_' + (++this.security._commandCounter);
1220
- this._eventSubscriptions.set(id, { event: eventName, callback });
1221
- this.events.on(eventName, callback);
1222
- return { success: true, subscriptionId: id, event: eventName };
1223
- }
1224
-
1225
- unsubscribe(subscriptionId) {
1226
- var sub = this._eventSubscriptions.get(subscriptionId);
1227
- if (!sub) return { success: false, error: 'Subscription not found' };
1228
- this.events.off(sub.event, sub.callback);
1229
- this._eventSubscriptions.delete(subscriptionId);
1230
- return { success: true };
1231
- }
1232
-
1233
- ping() {
1234
- return {
1235
- pong: true,
1236
- version: VERSION,
1237
- protocol: PROTOCOL_VERSION,
1238
- timestamp: Date.now(),
1239
- ready: this._ready,
1240
- locked: this.security.isLocked
1241
- };
1242
- }
1243
-
1244
- // ── Discovery / Info ────────────────────────────────────────────────
1245
- getActions(category) {
1246
- if (category) return this.registry.getByCategory(category);
1247
- return this.registry.list();
1248
- }
1249
-
1250
- getAction(name) {
1251
- return this.registry.get(name);
1252
- }
1253
-
1254
- // ── Waiting Utilities for Agents ────────────────────────────────────
1255
- waitForElement(selector, timeout = 10000) {
1256
- return new Promise((resolve, reject) => {
1257
- const el = safeQuerySelector(selector);
1258
- if (el) return resolve(el);
1259
-
1260
- const observer = new MutationObserver(() => {
1261
- const found = safeQuerySelector(selector);
1262
- if (found) {
1263
- observer.disconnect();
1264
- clearTimeout(timer);
1265
- resolve(found);
1266
- }
1267
- });
1268
-
1269
- observer.observe(document.body, { childList: true, subtree: true });
1270
-
1271
- const timer = setTimeout(() => {
1272
- observer.disconnect();
1273
- reject(new Error(`Timeout: element "${selector}" not found within ${timeout}ms`));
1274
- }, timeout);
1275
- });
1276
- }
1277
-
1278
- waitForNavigation(timeout = 15000) {
1279
- return new Promise((resolve) => {
1280
- const start = location.href;
1281
- const check = setInterval(() => {
1282
- if (location.href !== start) {
1283
- clearInterval(check);
1284
- clearTimeout(timer);
1285
- resolve({ from: start, to: location.href });
1286
- }
1287
- }, 200);
1288
- const timer = setTimeout(() => {
1289
- clearInterval(check);
1290
- resolve({ from: start, to: start, timedOut: true });
1291
- }, timeout);
1292
- });
1293
- }
1294
-
1295
- // ── Lifecycle ───────────────────────────────────────────────────────
1296
- refresh() {
1297
- this.registry = new ActionRegistry();
1298
- this._autoDiscoverActions();
1299
- this._storeFingerprints();
1300
- this.events.emit('refresh');
1301
- this.logger.log('refresh', {});
1302
- }
1303
-
1304
- destroy() {
1305
- this.events.emit('destroy');
1306
- if (this._mutationObserver) {
1307
- this._mutationObserver.disconnect();
1308
- this._mutationObserver = null;
1309
- }
1310
- this.registry = new ActionRegistry();
1311
- this.logger.clear();
1312
- delete global.AICommands;
1313
- delete global.WebAgentBridge;
1314
- delete global.__wab_bidi;
1315
- }
1316
-
1317
- // ── Serialization ───────────────────────────────────────────────────
1318
- toJSON() {
1319
- return {
1320
- version: VERSION,
1321
- protocol: PROTOCOL_VERSION,
1322
- page: this.getPageInfo(),
1323
- actions: this.getActions(),
1324
- discovery: this._discoveryDoc ? {
1325
- provider: this._discoveryDoc.provider,
1326
- fairness: this._discoveryDoc.fairness
1327
- } : null
1328
- };
1329
- }
1330
-
1331
- // ── WebDriver BiDi Compatibility ────────────────────────────────────
1332
- // Exposes a standardized protocol for agents using WebDriver BiDi
1333
- toBiDi() {
1334
- return {
1335
- type: 'wab:context',
1336
- version: VERSION,
1337
- protocol: PROTOCOL_VERSION,
1338
- context: {
1339
- url: location.href,
1340
- title: document.title,
1341
- browsingContext: typeof window !== 'undefined' ? window.name || 'default' : 'default'
1342
- },
1343
- capabilities: {
1344
- actions: this.getActions().map(a => ({
1345
- id: a.name,
1346
- type: a.trigger === 'click' ? 'pointerDown' : a.trigger === 'fill_and_submit' ? 'key' : a.trigger,
1347
- description: a.description,
1348
- parameters: a.fields ? a.fields.map(f => ({ name: f.name, type: f.type, required: f.required })) : undefined
1349
- })),
1350
- permissions: this._getEffectivePermissions(),
1351
- tier: this.getEffectiveTier()
1352
- },
1353
- discovery: this._discoveryDoc || null,
1354
- fairness: this._discoveryDoc ? this._discoveryDoc.fairness : null
1355
- };
1356
- }
1357
-
1358
- // Execute via BiDi-style command
1359
- async executeBiDi(command) {
1360
- // Security: validate command
1361
- const validation = this.security.validateCommand(command || {});
1362
- if (!validation.valid) {
1363
- return { id: command?.id, error: { code: 'security error', message: validation.error } };
1364
- }
1365
-
1366
- if (!command || !command.method) {
1367
- return { id: command?.id, error: { code: 'invalid argument', message: 'Missing method' } };
1368
- }
1369
-
1370
- this.security.audit('bidi_command', { method: command.method });
1371
- const responseBase = { id: command.id || null, type: 'success' };
1372
-
1373
- switch (command.method) {
1374
- case 'wab.getContext':
1375
- return { ...responseBase, result: this.toBiDi() };
1376
-
1377
- case 'wab.getActions':
1378
- return { ...responseBase, result: this.getActions(command.params?.category) };
1379
-
1380
- case 'wab.executeAction':
1381
- if (!command.params?.name) {
1382
- return { id: command.id, error: { code: 'invalid argument', message: 'Action name required' } };
1383
- }
1384
- const result = await this.execute(command.params.name, command.params.data || {});
1385
- return { ...responseBase, result };
1386
-
1387
- case 'wab.readContent':
1388
- if (!command.params?.selector) {
1389
- return { id: command.id, error: { code: 'invalid argument', message: 'Selector required' } };
1390
- }
1391
- return { ...responseBase, result: this.readContent(command.params.selector) };
1392
-
1393
- case 'wab.getPageInfo':
1394
- return { ...responseBase, result: this.getPageInfo() };
1395
-
1396
- case 'wab.discover':
1397
- return { ...responseBase, result: this.discover() };
1398
-
1399
- case 'wab.authenticate':
1400
- if (!command.params?.key) {
1401
- return { id: command.id, error: { code: 'invalid argument', message: 'Agent key required' } };
1402
- }
1403
- return { ...responseBase, result: this.authenticate(command.params.key, command.params.meta || {}) };
1404
-
1405
- case 'wab.subscribe':
1406
- if (!command.params?.event) {
1407
- return { id: command.id, error: { code: 'invalid argument', message: 'Event name required' } };
1408
- }
1409
- return { ...responseBase, result: this.subscribe(command.params.event, command.params.callback || function() {}) };
1410
-
1411
- case 'wab.ping':
1412
- return { ...responseBase, result: this.ping() };
1413
-
1414
- default:
1415
- return { id: command.id, error: { code: 'unknown command', message: `Unknown method: ${command.method}` } };
1416
- }
1417
- }
1418
- }
1419
-
1420
- // ─── Auto-initialize ──────────────────────────────────────────────────
1421
- function autoInit() {
1422
- const config = global.AIBridgeConfig || {};
1423
-
1424
- const scriptTag = document.currentScript || document.querySelector('script[data-wab-config]');
1425
- if (scriptTag) {
1426
- const dataConfig = scriptTag.getAttribute('data-config') || scriptTag.getAttribute('data-wab-config');
1427
- if (dataConfig) {
1428
- try {
1429
- Object.assign(config, JSON.parse(dataConfig));
1430
- } catch (e) {
1431
- console.error('[WAB] Invalid data-config JSON:', e);
1432
- }
1433
- }
1434
- }
1435
-
1436
- const bridge = new WebAgentBridge(config);
1437
-
1438
- global.AICommands = bridge;
1439
- global.WebAgentBridge = WebAgentBridge;
1440
-
1441
- // WAB Protocol interface
1442
- global.__wab_protocol = {
1443
- version: VERSION,
1444
- protocol: PROTOCOL_VERSION,
1445
- discover: () => bridge.discover(),
1446
- ping: () => bridge.ping()
1447
- };
1448
-
1449
- // WebDriver BiDi compatibility: expose via __wab_bidi channel
1450
- global.__wab_bidi = {
1451
- version: VERSION,
1452
- protocol: PROTOCOL_VERSION,
1453
- send: async (command) => bridge.executeBiDi(command),
1454
- getContext: () => bridge.toBiDi()
1455
- };
1456
-
1457
- // Inject NoJS fallback elements for pages that might disable JS later or
1458
- // for hybrid environments (SSR, partial hydration, headless crawlers).
1459
- if (config.siteId) {
1460
- injectNoScriptFallback(config);
1461
- }
1462
-
1463
- if (typeof CustomEvent !== 'undefined') {
1464
- document.dispatchEvent(new CustomEvent('wab:ready', { detail: { version: VERSION } }));
1465
- }
1466
- }
1467
-
1468
- function injectNoScriptFallback(config) {
1469
- try {
1470
- var siteId = config.siteId;
1471
- var base = config.apiBaseUrl || '';
1472
-
1473
- // Add <noscript> block if not already present
1474
- if (!document.querySelector('noscript [src*="noscript/pixel/' + siteId + '"]')) {
1475
- var ns = document.createElement('noscript');
1476
- ns.innerHTML =
1477
- '<link rel="stylesheet" href="' + base + '/api/noscript/css/' + siteId + '">' +
1478
- '<img src="' + base + '/api/noscript/pixel/' + siteId + '?action=pageview&t=noscript" width="1" height="1" alt="" style="position:absolute;opacity:0">';
1479
- document.body.appendChild(ns);
1480
- }
1481
-
1482
- // Expose noscript endpoints on the bridge for AI agents
1483
- global.__wab_noscript = {
1484
- pixel: base + '/api/noscript/pixel/' + siteId,
1485
- css: base + '/api/noscript/css/' + siteId,
1486
- bridge: base + '/api/noscript/bridge/' + siteId,
1487
- embed: base + '/api/noscript/embed/' + siteId,
1488
- serverTrack: base + '/api/noscript/server-track',
1489
- status: base + '/api/noscript/status/' + siteId
1490
- };
1491
-
1492
- // Add meta tags for crawlers/agents that read HTML
1493
- if (!document.querySelector('meta[name="wab:noscript"]')) {
1494
- var meta1 = document.createElement('meta');
1495
- meta1.name = 'wab:noscript';
1496
- meta1.content = 'true';
1497
- document.head.appendChild(meta1);
1498
-
1499
- var meta2 = document.createElement('meta');
1500
- meta2.name = 'wab:bridge';
1501
- meta2.content = base + '/api/noscript/bridge/' + siteId;
1502
- document.head.appendChild(meta2);
1503
- }
1504
- } catch (_) {}
1505
- }
1506
-
1507
- if (document.readyState === 'loading') {
1508
- document.addEventListener('DOMContentLoaded', autoInit);
1509
- } else {
1510
- autoInit();
1511
- }
1512
-
1513
- })(typeof window !== 'undefined' ? window : globalThis);
1
+ /**
2
+ * Web Agent Bridge v2.0.0
3
+ * Open-source middleware for AI agent ↔ website interaction
4
+ * https://github.com/web-agent-bridge
5
+ * License: MIT
6
+ */
7
+ (function (global) {
8
+ 'use strict';
9
+
10
+ const VERSION = '2.0.0';
11
+ const LICENSING_SERVER = 'https://api.webagentbridge.com';
12
+
13
+ // ─── Default Configuration ────────────────────────────────────────────
14
+ const DEFAULT_CONFIG = {
15
+ agentPermissions: {
16
+ readContent: true,
17
+ click: true,
18
+ fillForms: false,
19
+ scroll: true,
20
+ navigate: false,
21
+ apiAccess: false,
22
+ automatedLogin: false,
23
+ extractData: false
24
+ },
25
+ restrictions: {
26
+ allowedSelectors: [],
27
+ blockedSelectors: ['.private', '[data-private]', '[data-no-agent]'],
28
+ requireLoginForActions: [],
29
+ rateLimit: { maxCallsPerMinute: 60 }
30
+ },
31
+ logging: {
32
+ enabled: false,
33
+ level: 'basic'
34
+ },
35
+ subscriptionTier: 'free',
36
+ licenseKey: null,
37
+ /** Public site id from dashboard (preferred). Used with configEndpoint for token exchange — license key stays off the page. */
38
+ siteId: null,
39
+ /** Base URL for /api/license/* (verify, track). Default: current origin, else LICENSING_SERVER. */
40
+ apiBaseUrl: null,
41
+ features: {
42
+ advancedAnalytics: false,
43
+ realTimeUpdates: false,
44
+ customActions: false,
45
+ webhooks: false,
46
+ /** Send execute events to POST /api/license/track (populates admin analytics). */
47
+ reportUsage: true
48
+ }
49
+ };
50
+
51
+ // ─── Rate Limiter ─────────────────────────────────────────────────────
52
+ class RateLimiter {
53
+ constructor(maxPerMinute) {
54
+ this.maxPerMinute = maxPerMinute;
55
+ this.calls = [];
56
+ }
57
+
58
+ check() {
59
+ const now = Date.now();
60
+ this.calls = this.calls.filter(t => now - t < 60000);
61
+ if (this.calls.length >= this.maxPerMinute) {
62
+ return false;
63
+ }
64
+ this.calls.push(now);
65
+ return true;
66
+ }
67
+
68
+ get remaining() {
69
+ const now = Date.now();
70
+ this.calls = this.calls.filter(t => now - t < 60000);
71
+ return Math.max(0, this.maxPerMinute - this.calls.length);
72
+ }
73
+ }
74
+
75
+ // ─── Logger ───────────────────────────────────────────────────────────
76
+ class BridgeLogger {
77
+ constructor(config) {
78
+ this.enabled = config.enabled;
79
+ this.level = config.level;
80
+ this.logs = [];
81
+ }
82
+
83
+ log(action, details, level = 'basic') {
84
+ if (!this.enabled) return;
85
+ if (level === 'detailed' && this.level !== 'detailed') return;
86
+
87
+ const entry = {
88
+ timestamp: new Date().toISOString(),
89
+ action,
90
+ details,
91
+ level
92
+ };
93
+ this.logs.push(entry);
94
+
95
+ if (this.logs.length > 1000) {
96
+ this.logs = this.logs.slice(-500);
97
+ }
98
+ }
99
+
100
+ getLogs(filter) {
101
+ if (!filter) return [...this.logs];
102
+ return this.logs.filter(l => l.action === filter);
103
+ }
104
+
105
+ clear() {
106
+ this.logs = [];
107
+ }
108
+ }
109
+
110
+ // ─── Security Sandbox ──────────────────────────────────────────────────
111
+ // Isolates the bridge with origin validation, session tokens, and audit log
112
+ class SecuritySandbox {
113
+ constructor(config) {
114
+ this._sessionToken = this._generateToken();
115
+ this._allowedOrigins = config.security?.allowedOrigins || [location.origin];
116
+ this._auditLog = [];
117
+ this._maxAuditEntries = 500;
118
+ this._commandCounter = 0;
119
+ this._blockedCommands = new Set();
120
+ this._escalationAttempts = 0;
121
+ this._maxEscalationAttempts = 5;
122
+ this._locked = false;
123
+ }
124
+
125
+ _generateToken() {
126
+ const arr = new Uint8Array(32);
127
+ if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
128
+ crypto.getRandomValues(arr);
129
+ } else {
130
+ for (let i = 0; i < 32; i++) arr[i] = Math.floor(Math.random() * 256);
131
+ }
132
+ return Array.from(arr, b => b.toString(16).padStart(2, '0')).join('');
133
+ }
134
+
135
+ get sessionToken() { return this._sessionToken; }
136
+
137
+ validateOrigin(origin) {
138
+ if (!origin) return this._allowedOrigins.includes(location.origin);
139
+ return this._allowedOrigins.includes(origin);
140
+ }
141
+
142
+ audit(action, details, status = 'ok') {
143
+ const entry = {
144
+ id: ++this._commandCounter,
145
+ timestamp: Date.now(),
146
+ action,
147
+ status,
148
+ fingerprint: details?.agentId || 'anonymous'
149
+ };
150
+ this._auditLog.push(entry);
151
+ if (this._auditLog.length > this._maxAuditEntries) {
152
+ this._auditLog = this._auditLog.slice(-250);
153
+ }
154
+ return entry;
155
+ }
156
+
157
+ getAuditLog(limit = 50) {
158
+ return this._auditLog.slice(-limit);
159
+ }
160
+
161
+ checkEscalation(requestedTier, currentTier) {
162
+ const tierLevel = { free: 0, starter: 1, pro: 2, enterprise: 3 };
163
+ if ((tierLevel[requestedTier] || 0) > (tierLevel[currentTier] || 0)) {
164
+ this._escalationAttempts++;
165
+ this.audit('escalation_attempt', { requestedTier, currentTier }, 'blocked');
166
+ if (this._escalationAttempts >= this._maxEscalationAttempts) {
167
+ this._locked = true;
168
+ this.audit('bridge_locked', { reason: 'Too many escalation attempts' }, 'critical');
169
+ }
170
+ return false;
171
+ }
172
+ return true;
173
+ }
174
+
175
+ get isLocked() { return this._locked; }
176
+
177
+ validateCommand(command) {
178
+ if (this._locked) return { valid: false, error: 'Bridge is locked due to security violations' };
179
+ if (typeof command !== 'object' || !command) return { valid: false, error: 'Invalid command format' };
180
+ if (typeof command.method !== 'string') return { valid: false, error: 'Command method must be a string' };
181
+ if (command.method.length > 200) return { valid: false, error: 'Command method too long' };
182
+ if (this._blockedCommands.has(command.method)) return { valid: false, error: 'Command is blocked' };
183
+ return { valid: true };
184
+ }
185
+ }
186
+
187
+ // ─── Self-Healing Selectors ───────────────────────────────────────────
188
+ // Resilient element resolution for SPAs with dynamic DOM
189
+ class SelfHealingSelector {
190
+ constructor() {
191
+ this._fingerprints = new Map(); // name → element fingerprint
192
+ this._healingStats = { healed: 0, failed: 0 };
193
+ }
194
+
195
+ fingerprint(el) {
196
+ if (!el) return null;
197
+ return {
198
+ tag: el.tagName.toLowerCase(),
199
+ id: el.id || null,
200
+ classes: Array.from(el.classList),
201
+ text: (el.textContent || '').trim().slice(0, 100),
202
+ ariaLabel: el.getAttribute('aria-label') || null,
203
+ name: el.getAttribute('name') || null,
204
+ type: el.getAttribute('type') || null,
205
+ role: el.getAttribute('role') || null,
206
+ dataTestId: el.getAttribute('data-testid') || null,
207
+ dataWabId: el.getAttribute('data-wab-id') || null,
208
+ href: el.tagName === 'A' ? el.getAttribute('href') : null,
209
+ placeholder: el.getAttribute('placeholder') || null,
210
+ parentTag: el.parentElement ? el.parentElement.tagName.toLowerCase() : null,
211
+ index: el.parentElement ? Array.from(el.parentElement.children).indexOf(el) : -1
212
+ };
213
+ }
214
+
215
+ store(actionName, selector) {
216
+ const el = safeQuerySelector(selector);
217
+ if (el) {
218
+ this._fingerprints.set(actionName, {
219
+ selector,
220
+ fp: this.fingerprint(el),
221
+ storedAt: Date.now()
222
+ });
223
+ }
224
+ }
225
+
226
+ resolve(actionName, originalSelector) {
227
+ // Try original selector first
228
+ const el = safeQuerySelector(originalSelector);
229
+ if (el) return { element: el, selector: originalSelector, healed: false };
230
+
231
+ // Try self-healing
232
+ const stored = this._fingerprints.get(actionName);
233
+ if (!stored || !stored.fp) {
234
+ this._healingStats.failed++;
235
+ return null;
236
+ }
237
+
238
+ const healed = this._heal(stored.fp);
239
+ if (healed) {
240
+ this._healingStats.healed++;
241
+ return healed;
242
+ }
243
+
244
+ this._healingStats.failed++;
245
+ return null;
246
+ }
247
+
248
+ _heal(fp) {
249
+ // Strategy 1: data-wab-id (most stable)
250
+ if (fp.dataWabId) {
251
+ const el = safeQuerySelector(`[data-wab-id="${fp.dataWabId}"]`);
252
+ if (el) return { element: el, selector: `[data-wab-id="${fp.dataWabId}"]`, healed: true, strategy: 'data-wab-id' };
253
+ }
254
+
255
+ // Strategy 2: data-testid
256
+ if (fp.dataTestId) {
257
+ const el = safeQuerySelector(`[data-testid="${fp.dataTestId}"]`);
258
+ if (el) return { element: el, selector: `[data-testid="${fp.dataTestId}"]`, healed: true, strategy: 'data-testid' };
259
+ }
260
+
261
+ // Strategy 3: id (may have changed)
262
+ if (fp.id) {
263
+ const el = safeQuerySelector(`#${CSS.escape(fp.id)}`);
264
+ if (el) return { element: el, selector: `#${CSS.escape(fp.id)}`, healed: true, strategy: 'id' };
265
+ }
266
+
267
+ // Strategy 4: aria-label (semantic, usually stable)
268
+ if (fp.ariaLabel) {
269
+ const sel = `${fp.tag}[aria-label="${CSS.escape(fp.ariaLabel)}"]`;
270
+ const el = safeQuerySelector(sel);
271
+ if (el) return { element: el, selector: sel, healed: true, strategy: 'aria-label' };
272
+ }
273
+
274
+ // Strategy 5: name attribute
275
+ if (fp.name) {
276
+ const sel = `${fp.tag}[name="${CSS.escape(fp.name)}"]`;
277
+ const el = safeQuerySelector(sel);
278
+ if (el) return { element: el, selector: sel, healed: true, strategy: 'name' };
279
+ }
280
+
281
+ // Strategy 6: text content matching (fuzzy)
282
+ if (fp.text && fp.text.length > 0) {
283
+ const candidates = safeQuerySelectorAll(fp.tag);
284
+ const target = fp.text.toLowerCase();
285
+ let bestMatch = null;
286
+ let bestScore = 0;
287
+
288
+ for (const candidate of candidates) {
289
+ const candidateText = (candidate.textContent || '').trim().toLowerCase();
290
+ if (!candidateText) continue;
291
+
292
+ const score = this._textSimilarity(target, candidateText);
293
+ if (score > 0.7 && score > bestScore) {
294
+ bestScore = score;
295
+ bestMatch = candidate;
296
+ }
297
+ }
298
+
299
+ if (bestMatch) {
300
+ const healedSel = this._buildSelectorFor(bestMatch);
301
+ return { element: bestMatch, selector: healedSel, healed: true, strategy: 'text-fuzzy', confidence: bestScore };
302
+ }
303
+ }
304
+
305
+ // Strategy 7: role + position heuristic
306
+ if (fp.role && fp.parentTag) {
307
+ const candidates = safeQuerySelectorAll(`${fp.parentTag} > ${fp.tag}[role="${fp.role}"]`);
308
+ if (candidates.length > 0 && fp.index >= 0 && fp.index < candidates.length) {
309
+ const el = candidates[fp.index];
310
+ const sel = this._buildSelectorFor(el);
311
+ return { element: el, selector: sel, healed: true, strategy: 'role-position' };
312
+ }
313
+ }
314
+
315
+ return null;
316
+ }
317
+
318
+ _textSimilarity(a, b) {
319
+ if (a === b) return 1;
320
+ const longer = a.length > b.length ? a : b;
321
+ const shorter = a.length > b.length ? b : a;
322
+ if (longer.length === 0) return 1;
323
+ if (longer.includes(shorter) || shorter.includes(longer)) {
324
+ return shorter.length / longer.length;
325
+ }
326
+ // Simple bigram similarity
327
+ const bigramsA = new Set();
328
+ for (let i = 0; i < a.length - 1; i++) bigramsA.add(a.slice(i, i + 2));
329
+ let matches = 0;
330
+ for (let i = 0; i < b.length - 1; i++) {
331
+ if (bigramsA.has(b.slice(i, i + 2))) matches++;
332
+ }
333
+ const total = Math.max(bigramsA.size, b.length - 1);
334
+ return total > 0 ? matches / total : 0;
335
+ }
336
+
337
+ _buildSelectorFor(el) {
338
+ if (el.id) return `#${CSS.escape(el.id)}`;
339
+ if (el.dataset.wabId) return `[data-wab-id="${el.dataset.wabId}"]`;
340
+ const tag = el.tagName.toLowerCase();
341
+ const attrs = ['data-testid', 'aria-label', 'name'];
342
+ for (const attr of attrs) {
343
+ const val = el.getAttribute(attr);
344
+ if (val && document.querySelectorAll(`${tag}[${attr}="${CSS.escape(val)}"]`).length === 1) {
345
+ return `${tag}[${attr}="${CSS.escape(val)}"]`;
346
+ }
347
+ }
348
+ return null;
349
+ }
350
+
351
+ getStats() {
352
+ return { ...this._healingStats, tracked: this._fingerprints.size };
353
+ }
354
+ }
355
+
356
+ // ─── Stealth / Human-like Interaction ─────────────────────────────────
357
+ // ⚠️ ETHICAL USE POLICY:
358
+ // Stealth mode simulates human-like interaction patterns for LEGITIMATE uses:
359
+ // - Accessibility testing - QA automation on YOUR OWN sites
360
+ // - UX research with consent - Authorized penetration testing
361
+ // DO NOT use to bypass anti-bot protections on sites you do not own or control.
362
+ // Misuse violates the MIT license terms and is the user's legal responsibility.
363
+ const Stealth = {
364
+ _enabled: false,
365
+ _consentGiven: false,
366
+
367
+ enable(consent) {
368
+ if (consent !== true) {
369
+ console.warn('[WAB] Stealth mode requires explicit consent: stealth.enable(true)');
370
+ return;
371
+ }
372
+ this._consentGiven = true;
373
+ this._enabled = true;
374
+ },
375
+ disable() { this._enabled = false; },
376
+ get isEnabled() { return this._enabled; },
377
+
378
+ // Random delay between min and max ms
379
+ delay(min = 50, max = 300) {
380
+ if (!this._enabled) return Promise.resolve();
381
+ const duration = min + Math.floor(Math.random() * (max - min));
382
+ return new Promise(resolve => setTimeout(resolve, duration));
383
+ },
384
+
385
+ // Simulate a full mouse event chain: mouseover → mouseenter → mousemove → mousedown → mouseup → click
386
+ async simulateClick(el) {
387
+ if (!el) return;
388
+ const rect = el.getBoundingClientRect();
389
+ const x = rect.left + rect.width * (0.3 + Math.random() * 0.4);
390
+ const y = rect.top + rect.height * (0.3 + Math.random() * 0.4);
391
+ const eventOpts = { bubbles: true, cancelable: true, clientX: x, clientY: y, view: window };
392
+
393
+ el.dispatchEvent(new MouseEvent('mouseover', eventOpts));
394
+ el.dispatchEvent(new MouseEvent('mouseenter', { ...eventOpts, bubbles: false }));
395
+ await this.delay(30, 80);
396
+ el.dispatchEvent(new MouseEvent('mousemove', eventOpts));
397
+ await this.delay(40, 120);
398
+ el.dispatchEvent(new MouseEvent('mousedown', eventOpts));
399
+ await this.delay(50, 150);
400
+ el.dispatchEvent(new MouseEvent('mouseup', eventOpts));
401
+ el.dispatchEvent(new MouseEvent('click', eventOpts));
402
+ },
403
+
404
+ // Simulate human-like typing with variable delays
405
+ async simulateTyping(el, text) {
406
+ if (!el) return;
407
+ el.focus();
408
+ el.dispatchEvent(new Event('focus', { bubbles: true }));
409
+ el.value = '';
410
+
411
+ for (let i = 0; i < text.length; i++) {
412
+ const char = text[i];
413
+ el.dispatchEvent(new KeyboardEvent('keydown', { key: char, bubbles: true }));
414
+ el.value += char;
415
+ el.dispatchEvent(new Event('input', { bubbles: true }));
416
+ el.dispatchEvent(new KeyboardEvent('keyup', { key: char, bubbles: true }));
417
+ await this.delay(30, 120); // Human typing speed: 30-120ms per key
418
+ }
419
+
420
+ el.dispatchEvent(new Event('change', { bubbles: true }));
421
+ },
422
+
423
+ // Simulate natural scrolling (variable speed, easing)
424
+ async simulateScroll(el, direction = 'down') {
425
+ const target = el || document.documentElement;
426
+ const distance = 300 + Math.floor(Math.random() * 400);
427
+ const steps = 5 + Math.floor(Math.random() * 5);
428
+ const stepSize = distance / steps;
429
+
430
+ for (let i = 0; i < steps; i++) {
431
+ const delta = direction === 'down' ? stepSize : -stepSize;
432
+ if (el && el !== document.documentElement) {
433
+ el.scrollTop += delta;
434
+ } else {
435
+ window.scrollBy(0, delta);
436
+ }
437
+ await this.delay(15, 50);
438
+ }
439
+ }
440
+ };
441
+
442
+ // ─── Element Utilities ────────────────────────────────────────────────
443
+ function isElementAllowed(selector, config) {
444
+ const { allowedSelectors, blockedSelectors } = config.restrictions;
445
+
446
+ if (blockedSelectors.length > 0) {
447
+ const el = document.querySelector(selector);
448
+ if (el) {
449
+ for (const blocked of blockedSelectors) {
450
+ if (el.matches(blocked) || el.closest(blocked)) return false;
451
+ }
452
+ }
453
+ }
454
+
455
+ if (allowedSelectors.length > 0) {
456
+ const el = document.querySelector(selector);
457
+ if (el) {
458
+ for (const allowed of allowedSelectors) {
459
+ if (el.matches(allowed) || el.closest(allowed)) return true;
460
+ }
461
+ return false;
462
+ }
463
+ }
464
+
465
+ return true;
466
+ }
467
+
468
+ function safeQuerySelector(selector) {
469
+ try {
470
+ return document.querySelector(selector);
471
+ } catch (e) {
472
+ return null;
473
+ }
474
+ }
475
+
476
+ function safeQuerySelectorAll(selector) {
477
+ try {
478
+ return Array.from(document.querySelectorAll(selector));
479
+ } catch (e) {
480
+ return [];
481
+ }
482
+ }
483
+
484
+ // ─── Action Registry ──────────────────────────────────────────────────
485
+ class ActionRegistry {
486
+ constructor() {
487
+ this.actions = new Map();
488
+ }
489
+
490
+ register(action) {
491
+ if (!action.name || !action.description) {
492
+ throw new Error('Action must have a name and description');
493
+ }
494
+ this.actions.set(action.name, {
495
+ name: action.name,
496
+ description: action.description,
497
+ trigger: action.trigger || 'click',
498
+ selector: action.selector || null,
499
+ fields: action.fields || null,
500
+ submitSelector: action.submitSelector || null,
501
+ endpoint: action.endpoint || null,
502
+ method: action.method || 'GET',
503
+ requiresAuth: action.requiresAuth || false,
504
+ category: action.category || 'general',
505
+ params: action.params || null,
506
+ handler: action.handler || null,
507
+ metadata: action.metadata || {}
508
+ });
509
+ }
510
+
511
+ unregister(name) {
512
+ return this.actions.delete(name);
513
+ }
514
+
515
+ get(name) {
516
+ return this.actions.get(name) || null;
517
+ }
518
+
519
+ list() {
520
+ return Array.from(this.actions.values()).map(a => ({
521
+ name: a.name,
522
+ description: a.description,
523
+ trigger: a.trigger,
524
+ category: a.category,
525
+ requiresAuth: a.requiresAuth,
526
+ params: a.params,
527
+ fields: a.fields ? a.fields.map(f => ({ name: f.name, type: f.type, required: f.required !== false })) : null
528
+ }));
529
+ }
530
+
531
+ getByCategory(category) {
532
+ return this.list().filter(a => a.category === category);
533
+ }
534
+
535
+ toJSON() {
536
+ return this.list();
537
+ }
538
+ }
539
+
540
+ // ─── Event Emitter ────────────────────────────────────────────────────
541
+ class BridgeEventEmitter {
542
+ constructor() {
543
+ this.listeners = {};
544
+ }
545
+
546
+ on(event, callback) {
547
+ if (!this.listeners[event]) this.listeners[event] = [];
548
+ this.listeners[event].push(callback);
549
+ return () => this.off(event, callback);
550
+ }
551
+
552
+ off(event, callback) {
553
+ if (!this.listeners[event]) return;
554
+ this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
555
+ }
556
+
557
+ emit(event, data) {
558
+ if (!this.listeners[event]) return;
559
+ this.listeners[event].forEach(cb => {
560
+ try { cb(data); } catch (e) { console.error(`[WAB] Event handler error for "${event}":`, e); }
561
+ });
562
+ }
563
+ }
564
+
565
+ // ─── Main Bridge Class ────────────────────────────────────────────────
566
+ class WebAgentBridge {
567
+ constructor(userConfig) {
568
+ this.config = this._mergeConfig(DEFAULT_CONFIG, userConfig || {});
569
+ this.registry = new ActionRegistry();
570
+ this.rateLimiter = new RateLimiter(this.config.restrictions.rateLimit.maxCallsPerMinute);
571
+ this.logger = new BridgeLogger(this.config.logging);
572
+ this.events = new BridgeEventEmitter();
573
+ this.security = new SecuritySandbox(this.config);
574
+ this.healer = new SelfHealingSelector();
575
+ this.stealth = Stealth;
576
+ this.authenticated = false;
577
+ this.agentInfo = null;
578
+ this._licenseVerified = null;
579
+ this._ready = false;
580
+ this._readyCallbacks = [];
581
+ this._mutationObserver = null;
582
+
583
+ // Enable stealth mode if configured (requires consent: true)
584
+ if (this.config.stealth?.enabled && this.config.stealth?.consent === true) {
585
+ this.stealth.enable(true);
586
+ }
587
+
588
+ this._init();
589
+ }
590
+
591
+ // ── Initialization ──────────────────────────────────────────────────
592
+ async _init() {
593
+ if (this.config.configEndpoint && (this.config.siteId || this.config._licenseKey || this.config.licenseKey)) {
594
+ await this._secureLicenseExchange();
595
+ } else if (this.config.licenseKey) {
596
+ await this._verifyLicense();
597
+ } else {
598
+ this._licenseVerified = { tier: 'free', valid: true };
599
+ }
600
+
601
+ this._autoDiscoverActions();
602
+ this._storeFingerprints();
603
+ this._setupSPAObserver();
604
+ this._ready = true;
605
+ this._readyCallbacks.forEach(cb => cb());
606
+ this._readyCallbacks = [];
607
+ this.events.emit('ready', { version: VERSION, tier: this.getEffectiveTier() });
608
+ this.logger.log('init', { version: VERSION, tier: this.getEffectiveTier(), security: 'sandbox-active' });
609
+ }
610
+
611
+ // Secure license exchange: POST license key to server, get session token back
612
+ // License key is transmitted once via POST (not visible in page source)
613
+ async _secureLicenseExchange() {
614
+ try {
615
+ const endpoint = this.config.configEndpoint;
616
+ const body = this.config.siteId
617
+ ? { siteId: this.config.siteId }
618
+ : { licenseKey: this.config._licenseKey || this.config.licenseKey };
619
+ const res = await fetch(endpoint, {
620
+ method: 'POST',
621
+ headers: { 'Content-Type': 'application/json' },
622
+ body: JSON.stringify(body)
623
+ });
624
+ if (res.ok) {
625
+ const data = await res.json();
626
+ this._licenseVerified = { tier: data.tier, valid: true, sessionToken: data.sessionToken };
627
+ delete this.config._licenseKey;
628
+ if (data.expiresIn) {
629
+ if (this._tokenRefreshTimer) clearTimeout(this._tokenRefreshTimer);
630
+ this._tokenRefreshTimer = setTimeout(() => {
631
+ this._secureLicenseExchange();
632
+ }, Math.floor(data.expiresIn * 800));
633
+ }
634
+ } else {
635
+ this._licenseVerified = { tier: 'free', valid: false, error: 'Token exchange failed' };
636
+ }
637
+ } catch (e) {
638
+ this._licenseVerified = { tier: this.config.subscriptionTier || 'free', valid: false, error: 'Offline' };
639
+ }
640
+ }
641
+
642
+ // Store fingerprints for all discovered actions (self-healing)
643
+ _storeFingerprints() {
644
+ for (const action of this.registry.actions.values()) {
645
+ if (action.selector) {
646
+ this.healer.store(action.name, action.selector);
647
+ }
648
+ }
649
+ }
650
+
651
+ // Watch for SPA DOM changes and re-discover actions
652
+ _setupSPAObserver() {
653
+ if (this._mutationObserver) this._mutationObserver.disconnect();
654
+
655
+ let debounceTimer = null;
656
+ this._mutationObserver = new MutationObserver(() => {
657
+ if (debounceTimer) clearTimeout(debounceTimer);
658
+ debounceTimer = setTimeout(() => {
659
+ this._autoDiscoverActions();
660
+ this._storeFingerprints();
661
+ this.events.emit('dom:changed', { actionsCount: this.registry.actions.size });
662
+ }, 500);
663
+ });
664
+
665
+ this._mutationObserver.observe(document.body, {
666
+ childList: true,
667
+ subtree: true,
668
+ attributes: false
669
+ });
670
+ }
671
+
672
+ onReady(callback) {
673
+ if (this._ready) {
674
+ callback();
675
+ } else {
676
+ this._readyCallbacks.push(callback);
677
+ }
678
+ }
679
+
680
+ _mergeConfig(defaults, overrides) {
681
+ const result = {};
682
+ for (const key of Object.keys(defaults)) {
683
+ if (typeof defaults[key] === 'object' && defaults[key] !== null && !Array.isArray(defaults[key])) {
684
+ result[key] = this._mergeConfig(defaults[key], overrides[key] || {});
685
+ } else {
686
+ result[key] = overrides[key] !== undefined ? overrides[key] : defaults[key];
687
+ }
688
+ }
689
+ for (const key of Object.keys(overrides)) {
690
+ if (!(key in defaults)) {
691
+ result[key] = overrides[key];
692
+ }
693
+ }
694
+ return result;
695
+ }
696
+
697
+ _getLicenseApiBase() {
698
+ const c = this.config;
699
+ if (c.apiBaseUrl) return String(c.apiBaseUrl).replace(/\/$/, '');
700
+ if (typeof global.location !== 'undefined' && location && location.origin) return location.origin;
701
+ return LICENSING_SERVER;
702
+ }
703
+
704
+ /**
705
+ * Report action execution to WAB (fills platform analytics in admin).
706
+ */
707
+ _maybeReportUsage(actionName, triggerType, success) {
708
+ try {
709
+ const sessionToken = this._licenseVerified && this._licenseVerified.sessionToken;
710
+ if (!sessionToken || (this.config.features && this.config.features.reportUsage === false)) return;
711
+ const base = this._getLicenseApiBase();
712
+ const payload = JSON.stringify({
713
+ sessionToken,
714
+ actionName,
715
+ triggerType: triggerType || 'unknown',
716
+ success: success !== false
717
+ });
718
+ fetch(`${base}/api/license/track`, {
719
+ method: 'POST',
720
+ headers: { 'Content-Type': 'application/json' },
721
+ body: payload,
722
+ keepalive: true,
723
+ mode: 'cors',
724
+ credentials: 'omit'
725
+ }).catch(function () {});
726
+ } catch (e) { /* ignore */ }
727
+ }
728
+
729
+ // ── License Verification ────────────────────────────────────────────
730
+ async _verifyLicense() {
731
+ try {
732
+ const res = await fetch(`${this._getLicenseApiBase()}/api/license/verify`, {
733
+ method: 'POST',
734
+ headers: { 'Content-Type': 'application/json' },
735
+ body: JSON.stringify({
736
+ domain: location.hostname,
737
+ licenseKey: this.config.licenseKey
738
+ })
739
+ });
740
+ if (res.ok) {
741
+ this._licenseVerified = await res.json();
742
+ } else {
743
+ this._licenseVerified = { tier: 'free', valid: false, error: 'License verification failed' };
744
+ }
745
+ } catch (e) {
746
+ this._licenseVerified = { tier: this.config.subscriptionTier || 'free', valid: false, error: 'Offline' };
747
+ }
748
+ }
749
+
750
+ getEffectiveTier() {
751
+ if (this._licenseVerified && this._licenseVerified.valid) {
752
+ return this._licenseVerified.tier;
753
+ }
754
+ return 'free';
755
+ }
756
+
757
+ // ── Auto-discover Page Actions ──────────────────────────────────────
758
+ _autoDiscoverActions() {
759
+ const buttons = safeQuerySelectorAll('button, [role="button"], input[type="submit"], a.btn, a.button');
760
+ buttons.forEach((el, i) => {
761
+ const text = (el.textContent || el.value || '').trim();
762
+ if (!text) return;
763
+
764
+ const selector = this._generateSelector(el);
765
+ if (!selector || !isElementAllowed(selector, this.config)) return;
766
+
767
+ const name = this._slugify(text) || `action_${i}`;
768
+ if (!this.registry.get(name)) {
769
+ this.registry.register({
770
+ name,
771
+ description: `Click: ${text}`,
772
+ trigger: 'click',
773
+ selector,
774
+ category: 'auto-discovered'
775
+ });
776
+ }
777
+ });
778
+
779
+ const forms = safeQuerySelectorAll('form');
780
+ forms.forEach((form, i) => {
781
+ const formSelector = this._generateSelector(form);
782
+ if (!formSelector || !isElementAllowed(formSelector, this.config)) return;
783
+
784
+ const fields = Array.from(form.querySelectorAll('input, textarea, select'))
785
+ .filter(f => f.type !== 'hidden' && f.type !== 'submit')
786
+ .map(f => ({
787
+ name: f.name || f.id || f.placeholder || `field_${Math.random().toString(36).slice(2, 6)}`,
788
+ selector: this._generateSelector(f),
789
+ type: f.type || 'text',
790
+ required: f.required,
791
+ placeholder: f.placeholder || ''
792
+ }));
793
+
794
+ const submitBtn = form.querySelector('[type="submit"], button:not([type])');
795
+ const formName = form.id || form.name || `form_${i}`;
796
+
797
+ this.registry.register({
798
+ name: `fill_${this._slugify(formName)}`,
799
+ description: `Fill and submit form: ${formName}`,
800
+ trigger: 'fill_and_submit',
801
+ selector: formSelector,
802
+ fields,
803
+ submitSelector: submitBtn ? this._generateSelector(submitBtn) : null,
804
+ category: 'auto-discovered'
805
+ });
806
+ });
807
+
808
+ const links = safeQuerySelectorAll('nav a, [role="navigation"] a');
809
+ links.forEach((el, i) => {
810
+ const text = (el.textContent || '').trim();
811
+ if (!text) return;
812
+
813
+ const selector = this._generateSelector(el);
814
+ if (!selector || !isElementAllowed(selector, this.config)) return;
815
+
816
+ const name = `nav_${this._slugify(text)}` || `nav_${i}`;
817
+ if (!this.registry.get(name)) {
818
+ this.registry.register({
819
+ name,
820
+ description: `Navigate: ${text}`,
821
+ trigger: 'click',
822
+ selector,
823
+ category: 'navigation'
824
+ });
825
+ }
826
+ });
827
+
828
+ this._autoDiscoverCommerceAndBookingActions();
829
+ this._autoDiscoverStructuredActions();
830
+ }
831
+
832
+ _autoDiscoverCommerceAndBookingActions() {
833
+ const clickable = safeQuerySelectorAll('button, [role="button"], a, input[type="submit"], input[type="button"]');
834
+ clickable.forEach((el, i) => {
835
+ const text = (el.textContent || el.value || el.getAttribute('aria-label') || '').trim();
836
+ if (!text) return;
837
+
838
+ const intent = this._inferActionIntent(text);
839
+ if (!intent) return;
840
+
841
+ const selector = this._generateSelector(el);
842
+ if (!selector || !isElementAllowed(selector, this.config)) return;
843
+
844
+ const name = `${intent}_${this._slugify(text) || i}`;
845
+ if (this.registry.get(name)) return;
846
+
847
+ this.registry.register({
848
+ name,
849
+ description: `${intent.replace(/_/g, ' ')}: ${text}`,
850
+ trigger: 'click',
851
+ selector,
852
+ category: intent.startsWith('book') ? 'booking' : 'commerce',
853
+ metadata: { discoveredBy: 'intent' }
854
+ });
855
+ });
856
+
857
+ const forms = safeQuerySelectorAll('form');
858
+ forms.forEach((form, i) => {
859
+ const formText = `${form.id || ''} ${form.name || ''} ${form.className || ''} ${(form.getAttribute('aria-label') || '')}`.toLowerCase();
860
+ const hasBookingSignals = /(book|reservation|reserve|appointment|schedule)/.test(formText)
861
+ || !!form.querySelector('input[type="date"], input[type="time"], input[name*="date" i], input[name*="time" i]');
862
+ if (!hasBookingSignals) return;
863
+
864
+ const formSelector = this._generateSelector(form);
865
+ if (!formSelector || !isElementAllowed(formSelector, this.config)) return;
866
+
867
+ const fields = Array.from(form.querySelectorAll('input, textarea, select'))
868
+ .filter(f => f.type !== 'hidden' && f.type !== 'submit')
869
+ .map(f => ({
870
+ name: f.name || f.id || f.placeholder || `field_${Math.random().toString(36).slice(2, 6)}`,
871
+ selector: this._generateSelector(f),
872
+ type: f.type || 'text',
873
+ required: f.required,
874
+ placeholder: f.placeholder || ''
875
+ }));
876
+
877
+ const submitBtn = form.querySelector('[type="submit"], button:not([type])');
878
+ const actionName = `book_${this._slugify(form.id || form.name || `form_${i}`)}`;
879
+ if (this.registry.get(actionName)) return;
880
+
881
+ this.registry.register({
882
+ name: actionName,
883
+ description: `Book or reserve via form: ${form.id || form.name || `form_${i}`}`,
884
+ trigger: 'fill_and_submit',
885
+ selector: formSelector,
886
+ fields,
887
+ submitSelector: submitBtn ? this._generateSelector(submitBtn) : null,
888
+ category: 'booking',
889
+ metadata: { discoveredBy: 'booking-form-signals' }
890
+ });
891
+ });
892
+ }
893
+
894
+ _autoDiscoverStructuredActions() {
895
+ const products = this._scanStructuredProducts();
896
+ if (!products.length) return;
897
+
898
+ if (!this.registry.get('get_structured_products')) {
899
+ this.registry.register({
900
+ name: 'get_structured_products',
901
+ description: 'Return product entities discovered from schema.org and microdata',
902
+ trigger: 'read',
903
+ category: 'structured-data',
904
+ params: [
905
+ { name: 'limit', type: 'number', required: false }
906
+ ],
907
+ handler: (params) => {
908
+ const limit = Number(params?.limit || products.length);
909
+ const safeLimit = Number.isFinite(limit) && limit > 0 ? Math.min(limit, products.length) : products.length;
910
+ return { success: true, count: products.length, products: products.slice(0, safeLimit) };
911
+ },
912
+ metadata: { discoveredBy: 'schema' }
913
+ });
914
+ }
915
+
916
+ if (!this.registry.get('get_structured_prices')) {
917
+ this.registry.register({
918
+ name: 'get_structured_prices',
919
+ description: 'Return normalized offer prices discovered from structured product data',
920
+ trigger: 'read',
921
+ category: 'structured-data',
922
+ handler: () => {
923
+ const prices = products
924
+ .map(p => ({
925
+ name: p.name || null,
926
+ sku: p.sku || null,
927
+ price: p.price || null,
928
+ priceCurrency: p.priceCurrency || null,
929
+ availability: p.availability || null,
930
+ source: p.source
931
+ }))
932
+ .filter(p => p.price != null || p.availability != null);
933
+ return { success: true, count: prices.length, offers: prices };
934
+ },
935
+ metadata: { discoveredBy: 'schema' }
936
+ });
937
+ }
938
+ }
939
+
940
+ _scanStructuredProducts() {
941
+ const products = [];
942
+
943
+ const jsonLdScripts = safeQuerySelectorAll('script[type="application/ld+json"]');
944
+ jsonLdScripts.forEach((script, idx) => {
945
+ const text = script.textContent;
946
+ if (!text || !text.trim()) return;
947
+ try {
948
+ const parsed = JSON.parse(text);
949
+ const graph = Array.isArray(parsed) ? parsed : (Array.isArray(parsed?.['@graph']) ? parsed['@graph'] : [parsed]);
950
+ graph.forEach(node => {
951
+ if (!node || typeof node !== 'object') return;
952
+ const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']];
953
+ if (!types.includes('Product')) return;
954
+ const offer = Array.isArray(node.offers) ? node.offers[0] : node.offers;
955
+ products.push({
956
+ name: node.name || null,
957
+ sku: node.sku || null,
958
+ price: offer?.price || null,
959
+ priceCurrency: offer?.priceCurrency || null,
960
+ availability: offer?.availability || null,
961
+ source: `jsonld:${idx}`
962
+ });
963
+ });
964
+ } catch (e) {
965
+ // Ignore invalid JSON-LD blocks.
966
+ }
967
+ });
968
+
969
+ const microProducts = safeQuerySelectorAll('[itemtype*="schema.org/Product"]');
970
+ microProducts.forEach((el, idx) => {
971
+ const readProp = (prop) => {
972
+ const propEl = el.querySelector(`[itemprop="${prop}"]`);
973
+ if (!propEl) return null;
974
+ if (propEl.content) return propEl.content;
975
+ if (propEl.getAttribute('content')) return propEl.getAttribute('content');
976
+ if (propEl.value) return propEl.value;
977
+ return (propEl.textContent || '').trim() || null;
978
+ };
979
+
980
+ const offerRoot = el.querySelector('[itemprop="offers"]');
981
+ const readOfferProp = (prop) => {
982
+ if (!offerRoot) return null;
983
+ const node = offerRoot.querySelector(`[itemprop="${prop}"]`);
984
+ if (!node) return null;
985
+ return node.getAttribute('content') || node.content || (node.textContent || '').trim() || null;
986
+ };
987
+
988
+ products.push({
989
+ name: readProp('name'),
990
+ sku: readProp('sku'),
991
+ price: readOfferProp('price') || readProp('price'),
992
+ priceCurrency: readOfferProp('priceCurrency'),
993
+ availability: readOfferProp('availability'),
994
+ source: `microdata:${idx}`
995
+ });
996
+ });
997
+
998
+ const unique = [];
999
+ const seen = new Set();
1000
+ for (const item of products) {
1001
+ const key = `${item.name || ''}|${item.sku || ''}|${item.price || ''}|${item.source}`;
1002
+ if (seen.has(key)) continue;
1003
+ seen.add(key);
1004
+ unique.push(item);
1005
+ }
1006
+ return unique;
1007
+ }
1008
+
1009
+ _inferActionIntent(text) {
1010
+ const t = String(text || '').toLowerCase();
1011
+ if (!t) return null;
1012
+ if (/(add\s*to\s*cart|buy\s*now|add\s*bag|add\s*basket)/.test(t)) return 'add_to_cart';
1013
+ if (/(checkout|proceed\s*to\s*checkout|pay\s*now)/.test(t)) return 'checkout';
1014
+ if (/(book\s*now|reserve|reservation|schedule|appointment)/.test(t)) return 'book_now';
1015
+ if (/(get\s*price|check\s*price|view\s*price)/.test(t)) return 'get_price';
1016
+ return null;
1017
+ }
1018
+
1019
+ _generateSelector(el) {
1020
+ if (el.id) return `#${CSS.escape(el.id)}`;
1021
+ if (el.dataset.wabId) return `[data-wab-id="${el.dataset.wabId}"]`;
1022
+
1023
+ const classes = Array.from(el.classList).filter(c => !c.match(/^(js-|is-|has-)/));
1024
+ if (classes.length > 0) {
1025
+ const sel = `${el.tagName.toLowerCase()}.${classes.map(c => CSS.escape(c)).join('.')}`;
1026
+ if (document.querySelectorAll(sel).length === 1) return sel;
1027
+ }
1028
+
1029
+ const attrs = ['name', 'data-testid', 'aria-label', 'title', 'role'];
1030
+ for (const attr of attrs) {
1031
+ const val = el.getAttribute(attr);
1032
+ if (val) {
1033
+ const sel = `${el.tagName.toLowerCase()}[${attr}="${CSS.escape(val)}"]`;
1034
+ if (document.querySelectorAll(sel).length === 1) return sel;
1035
+ }
1036
+ }
1037
+
1038
+ const path = [];
1039
+ let current = el;
1040
+ while (current && current !== document.body) {
1041
+ let tag = current.tagName.toLowerCase();
1042
+ if (current.id) {
1043
+ path.unshift(`#${CSS.escape(current.id)}`);
1044
+ break;
1045
+ }
1046
+ const parent = current.parentElement;
1047
+ if (parent) {
1048
+ const siblings = Array.from(parent.children).filter(c => c.tagName === current.tagName);
1049
+ if (siblings.length > 1) {
1050
+ tag += `:nth-of-type(${siblings.indexOf(current) + 1})`;
1051
+ }
1052
+ }
1053
+ path.unshift(tag);
1054
+ current = parent;
1055
+ }
1056
+ return path.join(' > ');
1057
+ }
1058
+
1059
+ _slugify(text) {
1060
+ return text
1061
+ .toLowerCase()
1062
+ .replace(/[^\w\s-]/g, '')
1063
+ .replace(/[\s_]+/g, '_')
1064
+ .replace(/^-+|-+$/g, '')
1065
+ .slice(0, 40);
1066
+ }
1067
+
1068
+ // ── Agent Authentication ────────────────────────────────────────────
1069
+ authenticate(agentKey, agentMeta = {}) {
1070
+ this.logger.log('authenticate', { agentKey: agentKey ? '***' : null });
1071
+ this.events.emit('agent:authenticate', { agentMeta });
1072
+ this.authenticated = true;
1073
+ this.agentInfo = { key: agentKey, ...agentMeta, authenticatedAt: new Date().toISOString() };
1074
+ return { success: true, permissions: this._getEffectivePermissions() };
1075
+ }
1076
+
1077
+ // ── Permission Checks ───────────────────────────────────────────────
1078
+ _getEffectivePermissions() {
1079
+ const perms = { ...this.config.agentPermissions };
1080
+ const tier = this.getEffectiveTier();
1081
+
1082
+ if (tier === 'free') {
1083
+ perms.apiAccess = false;
1084
+ perms.automatedLogin = false;
1085
+ perms.extractData = false;
1086
+ }
1087
+
1088
+ return perms;
1089
+ }
1090
+
1091
+ _checkPermission(action) {
1092
+ const perms = this._getEffectivePermissions();
1093
+
1094
+ switch (action) {
1095
+ case 'click': return perms.click;
1096
+ case 'fill_and_submit': return perms.fillForms;
1097
+ case 'scroll': return perms.scroll;
1098
+ case 'navigate': return perms.navigate;
1099
+ case 'api': return perms.apiAccess;
1100
+ case 'read': return perms.readContent;
1101
+ case 'extract': return perms.extractData;
1102
+ default: return perms.click;
1103
+ }
1104
+ }
1105
+
1106
+ // ── Core: Execute Action ────────────────────────────────────────────
1107
+ async execute(actionName, params = {}) {
1108
+ // Security: check if bridge is locked
1109
+ if (this.security.isLocked) {
1110
+ return { success: false, error: 'Bridge locked due to security violations' };
1111
+ }
1112
+
1113
+ if (!this.rateLimiter.check()) {
1114
+ const error = { success: false, error: 'Rate limit exceeded', retryAfter: 60 };
1115
+ this.logger.log('rate_limit', { action: actionName });
1116
+ this.security.audit('rate_limit', { action: actionName }, 'blocked');
1117
+ this.events.emit('error', error);
1118
+ return error;
1119
+ }
1120
+
1121
+ const action = this.registry.get(actionName);
1122
+ if (!action) {
1123
+ return { success: false, error: `Action "${actionName}" not found`, available: this.registry.list().map(a => a.name) };
1124
+ }
1125
+
1126
+ if (!this._checkPermission(action.trigger)) {
1127
+ this.security.audit('permission_denied', { action: actionName, trigger: action.trigger }, 'blocked');
1128
+ return { success: false, error: `Permission denied for trigger type: ${action.trigger}`, tier: this.getEffectiveTier() };
1129
+ }
1130
+
1131
+ if (action.requiresAuth && !this.authenticated) {
1132
+ return { success: false, error: 'Authentication required for this action' };
1133
+ }
1134
+
1135
+ const loginRequired = this.config.restrictions.requireLoginForActions || [];
1136
+ if (loginRequired.includes(action.trigger) && !this.authenticated) {
1137
+ return { success: false, error: 'Login required for this action type' };
1138
+ }
1139
+
1140
+ // Self-healing: resolve selector if original is broken
1141
+ if (action.selector) {
1142
+ const resolved = this.healer.resolve(actionName, action.selector);
1143
+ if (resolved && resolved.healed) {
1144
+ action.selector = resolved.selector;
1145
+ this.logger.log('self_heal', { action: actionName, strategy: resolved.strategy, confidence: resolved.confidence }, 'detailed');
1146
+ this.events.emit('selector:healed', { action: actionName, strategy: resolved.strategy });
1147
+ }
1148
+ }
1149
+
1150
+ this.logger.log('execute', { action: actionName, params }, 'basic');
1151
+ this.security.audit('execute', { action: actionName, agentId: this.agentInfo?.key });
1152
+ this.events.emit('action:before', { action: actionName, params });
1153
+
1154
+ try {
1155
+ let result;
1156
+
1157
+ if (action.handler) {
1158
+ result = await action.handler(params);
1159
+ } else {
1160
+ switch (action.trigger) {
1161
+ case 'click':
1162
+ result = await this._executeClick(action);
1163
+ break;
1164
+ case 'fill_and_submit':
1165
+ result = await this._executeFillAndSubmit(action, params);
1166
+ break;
1167
+ case 'scroll':
1168
+ result = await this._executeScroll(action);
1169
+ break;
1170
+ case 'api':
1171
+ result = await this._executeApi(action, params);
1172
+ break;
1173
+ default:
1174
+ result = { success: false, error: `Unknown trigger: ${action.trigger}` };
1175
+ }
1176
+ }
1177
+
1178
+ this.events.emit('action:after', { action: actionName, result });
1179
+ this.logger.log('execute_result', { action: actionName, success: result.success }, 'detailed');
1180
+ this._maybeReportUsage(actionName, action.trigger, !!(result && result.success !== false));
1181
+ return result;
1182
+
1183
+ } catch (err) {
1184
+ const error = { success: false, error: err.message };
1185
+ this.events.emit('error', { action: actionName, error: err.message });
1186
+ this.logger.log('execute_error', { action: actionName, error: err.message });
1187
+ this._maybeReportUsage(actionName, action.trigger, false);
1188
+ return error;
1189
+ }
1190
+ }
1191
+
1192
+ async _executeClick(action) {
1193
+ if (!action.selector) return { success: false, error: 'No selector defined' };
1194
+ if (!isElementAllowed(action.selector, this.config)) {
1195
+ return { success: false, error: 'Element is blocked by restrictions' };
1196
+ }
1197
+
1198
+ // Self-healing: try to find element even if selector is stale
1199
+ let el = safeQuerySelector(action.selector);
1200
+ if (!el) {
1201
+ const resolved = this.healer.resolve(action.name, action.selector);
1202
+ if (resolved) {
1203
+ el = resolved.element;
1204
+ } else {
1205
+ return { success: false, error: `Element not found: ${action.selector}` };
1206
+ }
1207
+ }
1208
+
1209
+ // Stealth: use human-like click simulation
1210
+ if (this.stealth.isEnabled) {
1211
+ await this.stealth.delay(100, 400);
1212
+ await this.stealth.simulateClick(el);
1213
+ } else {
1214
+ el.click();
1215
+ }
1216
+
1217
+ return { success: true, action: 'click', selector: action.selector };
1218
+ }
1219
+
1220
+ async _executeFillAndSubmit(action, params) {
1221
+ if (!action.fields) return { success: false, error: 'No fields defined' };
1222
+
1223
+ const results = [];
1224
+ for (const field of action.fields) {
1225
+ if (!isElementAllowed(field.selector, this.config)) {
1226
+ results.push({ field: field.name, success: false, error: 'Element blocked' });
1227
+ continue;
1228
+ }
1229
+
1230
+ let el = safeQuerySelector(field.selector);
1231
+ if (!el) {
1232
+ // Self-healing: try to find field by name/placeholder
1233
+ const healedField = this.healer.resolve(`field_${field.name}`, field.selector);
1234
+ if (healedField) {
1235
+ el = healedField.element;
1236
+ } else {
1237
+ results.push({ field: field.name, success: false, error: 'Element not found' });
1238
+ continue;
1239
+ }
1240
+ }
1241
+
1242
+ const value = params[field.name];
1243
+ if (value !== undefined) {
1244
+ if (this.stealth.isEnabled) {
1245
+ await this.stealth.delay(200, 600);
1246
+ await this.stealth.simulateTyping(el, String(value));
1247
+ } else {
1248
+ el.focus();
1249
+ el.value = value;
1250
+ el.dispatchEvent(new Event('input', { bubbles: true }));
1251
+ el.dispatchEvent(new Event('change', { bubbles: true }));
1252
+ }
1253
+ results.push({ field: field.name, success: true });
1254
+ } else if (field.required !== false) {
1255
+ results.push({ field: field.name, success: false, error: 'Value required but not provided' });
1256
+ }
1257
+ }
1258
+
1259
+ if (action.submitSelector) {
1260
+ let submitEl = safeQuerySelector(action.submitSelector);
1261
+ if (submitEl) {
1262
+ if (this.stealth.isEnabled) {
1263
+ await this.stealth.delay(300, 800);
1264
+ await this.stealth.simulateClick(submitEl);
1265
+ } else {
1266
+ submitEl.click();
1267
+ }
1268
+ results.push({ field: '_submit', success: true });
1269
+ }
1270
+ }
1271
+
1272
+ return { success: results.every(r => r.success), results };
1273
+ }
1274
+
1275
+ async _executeScroll(action) {
1276
+ if (action.selector) {
1277
+ const el = safeQuerySelector(action.selector);
1278
+ if (el) {
1279
+ if (this.stealth.isEnabled) {
1280
+ await this.stealth.simulateScroll(el);
1281
+ } else {
1282
+ el.scrollIntoView({ behavior: 'smooth', block: 'center' });
1283
+ }
1284
+ return { success: true, action: 'scroll', selector: action.selector };
1285
+ }
1286
+ return { success: false, error: `Element not found: ${action.selector}` };
1287
+ }
1288
+ if (this.stealth.isEnabled) {
1289
+ await this.stealth.simulateScroll(null, 'down');
1290
+ } else {
1291
+ window.scrollBy({ top: 500, behavior: 'smooth' });
1292
+ }
1293
+ return { success: true, action: 'scroll', direction: 'down' };
1294
+ }
1295
+
1296
+ async _executeApi(action, params) {
1297
+ if (this.getEffectiveTier() === 'free') {
1298
+ return { success: false, error: 'API access requires a premium subscription' };
1299
+ }
1300
+
1301
+ const url = new URL(action.endpoint, location.origin);
1302
+ const options = { method: action.method || 'GET', headers: { 'Content-Type': 'application/json' } };
1303
+
1304
+ if (action.method !== 'GET' && params) {
1305
+ options.body = JSON.stringify(params);
1306
+ }
1307
+
1308
+ const res = await fetch(url.toString(), options);
1309
+ const data = await res.json().catch(() => null);
1310
+ return { success: res.ok, status: res.status, data };
1311
+ }
1312
+
1313
+ // ── Content Reading ─────────────────────────────────────────────────
1314
+ readContent(selector) {
1315
+ if (!this._checkPermission('read')) {
1316
+ return { success: false, error: 'readContent permission denied' };
1317
+ }
1318
+
1319
+ if (!isElementAllowed(selector, this.config)) {
1320
+ return { success: false, error: 'Element is blocked by restrictions' };
1321
+ }
1322
+
1323
+ const el = safeQuerySelector(selector);
1324
+ if (!el) return { success: false, error: 'Element not found' };
1325
+
1326
+ return {
1327
+ success: true,
1328
+ text: el.textContent.trim(),
1329
+ html: el.innerHTML,
1330
+ attributes: Object.fromEntries(
1331
+ Array.from(el.attributes).map(a => [a.name, a.value])
1332
+ )
1333
+ };
1334
+ }
1335
+
1336
+ getPageInfo() {
1337
+ return {
1338
+ title: document.title,
1339
+ url: location.href,
1340
+ domain: location.hostname,
1341
+ lang: document.documentElement.lang || 'unknown',
1342
+ bridgeVersion: VERSION,
1343
+ tier: this.getEffectiveTier(),
1344
+ permissions: this._getEffectivePermissions(),
1345
+ actionsCount: this.registry.actions.size,
1346
+ rateLimitRemaining: this.rateLimiter.remaining,
1347
+ security: {
1348
+ sandboxActive: true,
1349
+ locked: this.security.isLocked,
1350
+ sessionToken: this.security.sessionToken
1351
+ },
1352
+ selfHealing: this.healer.getStats(),
1353
+ stealthMode: this.stealth.isEnabled
1354
+ };
1355
+ }
1356
+
1357
+ // ── Custom Action Registration ──────────────────────────────────────
1358
+ registerAction(actionDef) {
1359
+ this.registry.register(actionDef);
1360
+ this.events.emit('action:registered', { name: actionDef.name });
1361
+ this.logger.log('register_action', { name: actionDef.name });
1362
+ }
1363
+
1364
+ unregisterAction(name) {
1365
+ this.registry.unregister(name);
1366
+ this.events.emit('action:unregistered', { name });
1367
+ }
1368
+
1369
+ // ── Discovery / Info ────────────────────────────────────────────────
1370
+ getActions(category) {
1371
+ if (category) return this.registry.getByCategory(category);
1372
+ return this.registry.list();
1373
+ }
1374
+
1375
+ getAction(name) {
1376
+ return this.registry.get(name);
1377
+ }
1378
+
1379
+ // ── Waiting Utilities for Agents ────────────────────────────────────
1380
+ waitForElement(selector, timeout = 10000) {
1381
+ return new Promise((resolve, reject) => {
1382
+ const el = safeQuerySelector(selector);
1383
+ if (el) return resolve(el);
1384
+
1385
+ const observer = new MutationObserver(() => {
1386
+ const found = safeQuerySelector(selector);
1387
+ if (found) {
1388
+ observer.disconnect();
1389
+ clearTimeout(timer);
1390
+ resolve(found);
1391
+ }
1392
+ });
1393
+
1394
+ observer.observe(document.body, { childList: true, subtree: true });
1395
+
1396
+ const timer = setTimeout(() => {
1397
+ observer.disconnect();
1398
+ reject(new Error(`Timeout: element "${selector}" not found within ${timeout}ms`));
1399
+ }, timeout);
1400
+ });
1401
+ }
1402
+
1403
+ waitForNavigation(timeout = 15000) {
1404
+ return new Promise((resolve) => {
1405
+ const start = location.href;
1406
+ const check = setInterval(() => {
1407
+ if (location.href !== start) {
1408
+ clearInterval(check);
1409
+ clearTimeout(timer);
1410
+ resolve({ from: start, to: location.href });
1411
+ }
1412
+ }, 200);
1413
+ const timer = setTimeout(() => {
1414
+ clearInterval(check);
1415
+ resolve({ from: start, to: start, timedOut: true });
1416
+ }, timeout);
1417
+ });
1418
+ }
1419
+
1420
+ // ── Lifecycle ───────────────────────────────────────────────────────
1421
+ refresh() {
1422
+ this.registry = new ActionRegistry();
1423
+ this._autoDiscoverActions();
1424
+ this._storeFingerprints();
1425
+ this.events.emit('refresh');
1426
+ this.logger.log('refresh', {});
1427
+ }
1428
+
1429
+ destroy() {
1430
+ this.events.emit('destroy');
1431
+ if (this._mutationObserver) {
1432
+ this._mutationObserver.disconnect();
1433
+ this._mutationObserver = null;
1434
+ }
1435
+ this.registry = new ActionRegistry();
1436
+ this.logger.clear();
1437
+ delete global.AICommands;
1438
+ delete global.WebAgentBridge;
1439
+ delete global.__wab_bidi;
1440
+ }
1441
+
1442
+ // ── Serialization ───────────────────────────────────────────────────
1443
+ toJSON() {
1444
+ return {
1445
+ version: VERSION,
1446
+ page: this.getPageInfo(),
1447
+ actions: this.getActions()
1448
+ };
1449
+ }
1450
+
1451
+ // ── WebDriver BiDi Compatibility ────────────────────────────────────
1452
+ // Exposes a standardized protocol for agents using WebDriver BiDi
1453
+ toBiDi() {
1454
+ return {
1455
+ type: 'wab:context',
1456
+ version: VERSION,
1457
+ context: {
1458
+ url: location.href,
1459
+ title: document.title,
1460
+ browsingContext: typeof window !== 'undefined' ? window.name || 'default' : 'default'
1461
+ },
1462
+ capabilities: {
1463
+ actions: this.getActions().map(a => ({
1464
+ id: a.name,
1465
+ type: a.trigger === 'click' ? 'pointerDown' : a.trigger === 'fill_and_submit' ? 'key' : a.trigger,
1466
+ description: a.description,
1467
+ parameters: a.fields ? a.fields.map(f => ({ name: f.name, type: f.type, required: f.required })) : undefined
1468
+ })),
1469
+ permissions: this._getEffectivePermissions(),
1470
+ tier: this.getEffectiveTier()
1471
+ }
1472
+ };
1473
+ }
1474
+
1475
+ // Execute via BiDi-style command
1476
+ async executeBiDi(command) {
1477
+ // Security: validate command
1478
+ const validation = this.security.validateCommand(command || {});
1479
+ if (!validation.valid) {
1480
+ return { id: command?.id, error: { code: 'security error', message: validation.error } };
1481
+ }
1482
+
1483
+ if (!command || !command.method) {
1484
+ return { id: command?.id, error: { code: 'invalid argument', message: 'Missing method' } };
1485
+ }
1486
+
1487
+ this.security.audit('bidi_command', { method: command.method });
1488
+ const responseBase = { id: command.id || null, type: 'success' };
1489
+
1490
+ switch (command.method) {
1491
+ case 'wab.getContext':
1492
+ return { ...responseBase, result: this.toBiDi() };
1493
+
1494
+ case 'wab.getActions':
1495
+ return { ...responseBase, result: this.getActions(command.params?.category) };
1496
+
1497
+ case 'wab.executeAction':
1498
+ if (!command.params?.name) {
1499
+ return { id: command.id, error: { code: 'invalid argument', message: 'Action name required' } };
1500
+ }
1501
+ const result = await this.execute(command.params.name, command.params.data || {});
1502
+ return { ...responseBase, result };
1503
+
1504
+ case 'wab.readContent':
1505
+ if (!command.params?.selector) {
1506
+ return { id: command.id, error: { code: 'invalid argument', message: 'Selector required' } };
1507
+ }
1508
+ return { ...responseBase, result: this.readContent(command.params.selector) };
1509
+
1510
+ case 'wab.getPageInfo':
1511
+ return { ...responseBase, result: this.getPageInfo() };
1512
+
1513
+ default:
1514
+ return { id: command.id, error: { code: 'unknown command', message: `Unknown method: ${command.method}` } };
1515
+ }
1516
+ }
1517
+ }
1518
+
1519
+ // ─── Auto-initialize ──────────────────────────────────────────────────
1520
+ function autoInit() {
1521
+ const config = global.AIBridgeConfig || {};
1522
+
1523
+ const scriptTag = document.currentScript || document.querySelector('script[data-wab-config]');
1524
+ if (scriptTag) {
1525
+ const dataConfig = scriptTag.getAttribute('data-config') || scriptTag.getAttribute('data-wab-config');
1526
+ if (dataConfig) {
1527
+ try {
1528
+ Object.assign(config, JSON.parse(dataConfig));
1529
+ } catch (e) {
1530
+ console.error('[WAB] Invalid data-config JSON:', e);
1531
+ }
1532
+ }
1533
+ }
1534
+
1535
+ const bridge = new WebAgentBridge(config);
1536
+
1537
+ global.AICommands = bridge;
1538
+ global.WebAgentBridge = WebAgentBridge;
1539
+
1540
+ // WebDriver BiDi compatibility: expose via __wab_bidi channel
1541
+ global.__wab_bidi = {
1542
+ version: VERSION,
1543
+ send: async (command) => bridge.executeBiDi(command),
1544
+ getContext: () => bridge.toBiDi()
1545
+ };
1546
+
1547
+ if (typeof CustomEvent !== 'undefined') {
1548
+ document.dispatchEvent(new CustomEvent('wab:ready', { detail: { version: VERSION } }));
1549
+ }
1550
+ }
1551
+
1552
+ if (document.readyState === 'loading') {
1553
+ document.addEventListener('DOMContentLoaded', autoInit);
1554
+ } else {
1555
+ autoInit();
1556
+ }
1557
+
1558
+ })(typeof window !== 'undefined' ? window : globalThis);