web-agent-bridge 2.3.1 → 2.5.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 (53) hide show
  1. package/README.ar.md +524 -31
  2. package/README.md +592 -47
  3. package/bin/agent-runner.js +10 -1
  4. package/package.json +1 -1
  5. package/public/agent-workspace.html +347 -0
  6. package/public/browser.html +484 -0
  7. package/public/css/agent-workspace.css +1713 -0
  8. package/public/index.html +94 -0
  9. package/public/js/agent-workspace.js +1740 -0
  10. package/sdk/index.d.ts +253 -0
  11. package/sdk/index.js +360 -1
  12. package/sdk/package.json +1 -1
  13. package/server/config/secrets.js +13 -5
  14. package/server/control-plane/index.js +301 -0
  15. package/server/data-plane/index.js +354 -0
  16. package/server/index.js +185 -4
  17. package/server/llm/index.js +404 -0
  18. package/server/middleware/adminAuth.js +6 -1
  19. package/server/middleware/auth.js +11 -2
  20. package/server/middleware/rateLimits.js +78 -2
  21. package/server/migrations/003_ads_integer_cents.sql +33 -0
  22. package/server/models/db.js +126 -25
  23. package/server/observability/index.js +394 -0
  24. package/server/protocol/capabilities.js +223 -0
  25. package/server/protocol/index.js +243 -0
  26. package/server/protocol/schema.js +584 -0
  27. package/server/registry/index.js +326 -0
  28. package/server/routes/admin.js +16 -2
  29. package/server/routes/ads.js +130 -0
  30. package/server/routes/agent-workspace.js +378 -0
  31. package/server/routes/api.js +21 -2
  32. package/server/routes/auth.js +26 -6
  33. package/server/routes/runtime.js +725 -0
  34. package/server/routes/sovereign.js +78 -0
  35. package/server/routes/universal.js +177 -0
  36. package/server/routes/wab-api.js +20 -5
  37. package/server/runtime/event-bus.js +210 -0
  38. package/server/runtime/index.js +233 -0
  39. package/server/runtime/sandbox.js +266 -0
  40. package/server/runtime/scheduler.js +395 -0
  41. package/server/runtime/state-manager.js +188 -0
  42. package/server/security/index.js +355 -0
  43. package/server/services/agent-chat.js +506 -0
  44. package/server/services/agent-symphony.js +6 -0
  45. package/server/services/agent-tasks.js +1807 -0
  46. package/server/services/fairness-engine.js +409 -0
  47. package/server/services/plugins.js +27 -3
  48. package/server/services/price-intelligence.js +565 -0
  49. package/server/services/price-shield.js +1137 -0
  50. package/server/services/search-engine.js +357 -0
  51. package/server/services/security.js +513 -0
  52. package/server/services/universal-scraper.js +661 -0
  53. package/server/ws.js +61 -1
@@ -0,0 +1,565 @@
1
+ /**
2
+ * WAB Price Intelligence Engine
3
+ * ═══════════════════════════════════════════════════════════════════
4
+ * Smart price analysis that works on ANY website:
5
+ *
6
+ * 1. Fraud Detection — detects fake discounts, price manipulation, hidden fees
7
+ * 2. Price Comparison — compares across competing sources
8
+ * 3. Hidden Deals — finds unadvertised deals, coupon codes, loyalty discounts
9
+ * 4. Historical Analysis — tracks price trends over time
10
+ * 5. Dynamic Pricing Shield — detects if a site changes prices based on user behavior
11
+ *
12
+ * Works without any script installation on target sites.
13
+ */
14
+
15
+ const crypto = require('crypto');
16
+ const { db } = require('../models/db');
17
+ const scraper = require('./universal-scraper');
18
+ const { getWabBridgeInfo } = require('./fairness-engine');
19
+
20
+ // ─── Schema ──────────────────────────────────────────────────────────
21
+
22
+ db.exec(`
23
+ CREATE TABLE IF NOT EXISTS price_alerts (
24
+ id TEXT PRIMARY KEY,
25
+ url_hash TEXT NOT NULL,
26
+ domain TEXT NOT NULL,
27
+ alert_type TEXT NOT NULL,
28
+ severity TEXT DEFAULT 'medium',
29
+ title TEXT NOT NULL,
30
+ description TEXT,
31
+ evidence TEXT DEFAULT '{}',
32
+ created_at TEXT DEFAULT (datetime('now'))
33
+ );
34
+
35
+ CREATE TABLE IF NOT EXISTS deal_cache (
36
+ id TEXT PRIMARY KEY,
37
+ query TEXT NOT NULL,
38
+ category TEXT,
39
+ results TEXT DEFAULT '[]',
40
+ sources_checked INTEGER DEFAULT 0,
41
+ best_price REAL,
42
+ best_source TEXT,
43
+ fraud_flags INTEGER DEFAULT 0,
44
+ created_at TEXT DEFAULT (datetime('now'))
45
+ );
46
+
47
+ CREATE INDEX IF NOT EXISTS idx_alerts_domain ON price_alerts(domain);
48
+ CREATE INDEX IF NOT EXISTS idx_deal_cache_query ON deal_cache(query);
49
+ `);
50
+
51
+ const stmts = {
52
+ insertAlert: db.prepare(`INSERT INTO price_alerts
53
+ (id, url_hash, domain, alert_type, severity, title, description, evidence) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`),
54
+ getAlerts: db.prepare('SELECT * FROM price_alerts WHERE domain = ? ORDER BY created_at DESC LIMIT ?'),
55
+ insertDeal: db.prepare(`INSERT OR REPLACE INTO deal_cache
56
+ (id, query, category, results, sources_checked, best_price, best_source, fraud_flags) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`),
57
+ getDeal: db.prepare('SELECT * FROM deal_cache WHERE query = ? ORDER BY created_at DESC LIMIT 1'),
58
+ };
59
+
60
+ // ─── Competing Sources Database ──────────────────────────────────────
61
+
62
+ const COMPETING_SOURCES = {
63
+ hotel: [
64
+ { name: 'Booking.com', domain: 'booking.com', type: 'platform', size: 'big', url: 'https://www.booking.com/searchresults.html?ss=' },
65
+ { name: 'Agoda', domain: 'agoda.com', type: 'platform', size: 'big', url: 'https://www.agoda.com/search?q=' },
66
+ { name: 'Hotels.com', domain: 'hotels.com', type: 'platform', size: 'big', url: 'https://www.hotels.com/search.do?q=' },
67
+ { name: 'Expedia', domain: 'expedia.com', type: 'platform', size: 'big', url: 'https://www.expedia.com/Hotel-Search?destination=' },
68
+ { name: 'TripAdvisor', domain: 'tripadvisor.com', type: 'aggregator', size: 'big', url: 'https://www.tripadvisor.com/Hotels?q=' },
69
+ { name: 'Kayak', domain: 'kayak.com', type: 'aggregator', size: 'medium', url: 'https://www.kayak.com/hotels?q=' },
70
+ { name: 'Trivago', domain: 'trivago.com', type: 'aggregator', size: 'medium', url: 'https://www.trivago.com/search?q=' },
71
+ { name: 'Hostelworld', domain: 'hostelworld.com', type: 'direct', size: 'small', url: 'https://www.hostelworld.com/find?q=' },
72
+ { name: 'Almosafer', domain: 'almosafer.com', type: 'direct', size: 'small', url: 'https://www.almosafer.com/en/hotels?q=' },
73
+ { name: 'Wego', domain: 'wego.com', type: 'aggregator', size: 'small', url: 'https://www.wego.com/hotels/search?q=' },
74
+ // Direct hotel chains — small/independent get priority
75
+ { name: 'Hotel Direct', domain: 'direct', type: 'direct', size: 'small', url: null },
76
+ ],
77
+ flight: [
78
+ { name: 'Google Flights', domain: 'google.com/travel', type: 'aggregator', size: 'big', url: 'https://www.google.com/travel/flights?q=' },
79
+ { name: 'Skyscanner', domain: 'skyscanner.com', type: 'aggregator', size: 'medium', url: 'https://www.skyscanner.com/transport/flights?q=' },
80
+ { name: 'Kayak', domain: 'kayak.com', type: 'aggregator', size: 'medium', url: 'https://www.kayak.com/flights?search=' },
81
+ { name: 'Kiwi.com', domain: 'kiwi.com', type: 'aggregator', size: 'small', url: 'https://www.kiwi.com/search?q=' },
82
+ { name: 'Momondo', domain: 'momondo.com', type: 'aggregator', size: 'small', url: 'https://www.momondo.com/flight-search?q=' },
83
+ { name: 'Wego', domain: 'wego.com', type: 'aggregator', size: 'small', url: 'https://www.wego.com/flights/search?q=' },
84
+ { name: 'Almosafer', domain: 'almosafer.com', type: 'direct', size: 'small', url: 'https://www.almosafer.com/en/flights?q=' },
85
+ { name: 'Flyin', domain: 'flyin.com', type: 'direct', size: 'small', url: 'https://www.flyin.com/flights?q=' },
86
+ ],
87
+ product: [
88
+ { name: 'Amazon', domain: 'amazon.com', type: 'marketplace', size: 'big', url: 'https://www.amazon.com/s?k=' },
89
+ { name: 'eBay', domain: 'ebay.com', type: 'marketplace', size: 'big', url: 'https://www.ebay.com/sch/?_nkw=' },
90
+ { name: 'AliExpress', domain: 'aliexpress.com', type: 'marketplace', size: 'big', url: 'https://www.aliexpress.com/wholesale?SearchText=' },
91
+ { name: 'Walmart', domain: 'walmart.com', type: 'marketplace', size: 'big', url: 'https://www.walmart.com/search?q=' },
92
+ { name: 'Google Shopping', domain: 'shopping.google.com', type: 'aggregator', size: 'big', url: 'https://shopping.google.com/search?q=' },
93
+ { name: 'PriceGrabber', domain: 'pricegrabber.com', type: 'aggregator', size: 'small', url: 'https://www.pricegrabber.com/search?q=' },
94
+ { name: 'Shopzilla', domain: 'shopzilla.com', type: 'aggregator', size: 'small', url: 'https://www.shopzilla.com/search?q=' },
95
+ { name: 'Etsy', domain: 'etsy.com', type: 'marketplace', size: 'medium', url: 'https://www.etsy.com/search?q=' },
96
+ ],
97
+ };
98
+
99
+ // ─── Fraud Detection ─────────────────────────────────────────────────
100
+
101
+ const FRAUD_PATTERNS = {
102
+ fakeDiscount: {
103
+ name: 'Fake Discount',
104
+ name_ar: 'خصم وهمي',
105
+ detect: (product, history) => {
106
+ // If "original price" is the same as what it's always been, the discount is fake
107
+ if (!product.originalPrice || !product.price) return null;
108
+ const discount = ((product.originalPrice - product.price) / product.originalPrice) * 100;
109
+
110
+ // Check: is the "original price" actually the normal price?
111
+ if (history.length >= 3) {
112
+ const avgHistorical = history.reduce((sum, h) => sum + h.price, 0) / history.length;
113
+ const originalNearAvg = Math.abs(product.originalPrice - avgHistorical) / avgHistorical < 0.1;
114
+ if (originalNearAvg && discount > 5) {
115
+ return {
116
+ severity: discount > 30 ? 'high' : 'medium',
117
+ title: `Fake ${Math.round(discount)}% discount detected`,
118
+ title_ar: `تم كشف خصم وهمي ${Math.round(discount)}%`,
119
+ description: `The "original price" $${product.originalPrice} is actually the normal price (avg: $${Math.round(avgHistorical)}). The real discount is ~0%.`,
120
+ description_ar: `"السعر الأصلي" $${product.originalPrice} هو السعر العادي فعلياً (المتوسط: $${Math.round(avgHistorical)}). الخصم الحقيقي ~0%.`,
121
+ };
122
+ }
123
+ }
124
+
125
+ // Suspiciously high discount
126
+ if (discount > 70) {
127
+ return {
128
+ severity: 'high',
129
+ title: `Suspicious ${Math.round(discount)}% discount`,
130
+ title_ar: `خصم مريب ${Math.round(discount)}%`,
131
+ description: `A ${Math.round(discount)}% discount is unusually high and may be deceptive.`,
132
+ description_ar: `خصم ${Math.round(discount)}% مرتفع بشكل غير عادي وقد يكون مخادعاً.`,
133
+ };
134
+ }
135
+ return null;
136
+ },
137
+ },
138
+
139
+ priceInflation: {
140
+ name: 'Price Inflation',
141
+ name_ar: 'تضخم الأسعار',
142
+ detect: (product, history) => {
143
+ if (history.length < 5 || !product.price) return null;
144
+ const recentAvg = history.slice(0, 3).reduce((s, h) => s + h.price, 0) / 3;
145
+ const olderAvg = history.slice(-3).reduce((s, h) => s + h.price, 0) / Math.min(3, history.length);
146
+ const increase = ((recentAvg - olderAvg) / olderAvg) * 100;
147
+
148
+ if (increase > 20) {
149
+ return {
150
+ severity: increase > 50 ? 'high' : 'medium',
151
+ title: `Price inflated ${Math.round(increase)}% recently`,
152
+ title_ar: `ارتفاع السعر ${Math.round(increase)}% مؤخراً`,
153
+ description: `Price jumped from ~$${Math.round(olderAvg)} to ~$${Math.round(recentAvg)}. May be demand-based surge pricing.`,
154
+ description_ar: `ارتفع السعر من ~$${Math.round(olderAvg)} إلى ~$${Math.round(recentAvg)}. قد يكون تسعيراً ديناميكياً.`,
155
+ };
156
+ }
157
+ return null;
158
+ },
159
+ },
160
+
161
+ hiddenFees: {
162
+ name: 'Hidden Fees',
163
+ name_ar: 'رسوم مخفية',
164
+ detect: (product) => {
165
+ // Check for common hidden fee indicators in product text
166
+ const text = (product.description || '').toLowerCase() + ' ' + (product.name || '').toLowerCase();
167
+ const feeWords = ['resort fee', 'cleaning fee', 'service fee', 'booking fee',
168
+ 'processing fee', 'facility fee', 'رسوم', 'ضريبة', 'خدمة'];
169
+ const found = feeWords.filter(w => text.includes(w));
170
+
171
+ if (found.length > 0) {
172
+ return {
173
+ severity: 'low',
174
+ title: `Possible hidden fees: ${found.join(', ')}`,
175
+ title_ar: `رسوم مخفية محتملة: ${found.join(', ')}`,
176
+ description: `This listing mentions additional fees that may not be included in the displayed price.`,
177
+ description_ar: `هذا العرض يذكر رسوماً إضافية قد لا تكون مضمنة في السعر المعروض.`,
178
+ };
179
+ }
180
+ return null;
181
+ },
182
+ },
183
+
184
+ dynamicPricing: {
185
+ name: 'Dynamic Pricing',
186
+ name_ar: 'تسعير ديناميكي',
187
+ detect: (product, history) => {
188
+ if (history.length < 3) return null;
189
+ // Check if price changes frequently (more than 3 changes in last 10 records)
190
+ let changes = 0;
191
+ for (let i = 1; i < Math.min(history.length, 10); i++) {
192
+ if (Math.abs(history[i].price - history[i - 1].price) > 1) changes++;
193
+ }
194
+ if (changes >= 3) {
195
+ return {
196
+ severity: 'medium',
197
+ title: `Dynamic pricing detected (${changes} price changes)`,
198
+ title_ar: `تسعير ديناميكي مكتشف (${changes} تغييرات)`,
199
+ description: `This site changes prices frequently. Use Ghost Mode for best results.`,
200
+ description_ar: `هذا الموقع يغير أسعاره بشكل متكرر. استخدم وضع الشبح للحصول على أفضل النتائج.`,
201
+ };
202
+ }
203
+ return null;
204
+ },
205
+ },
206
+
207
+ tooGoodToBeTrue: {
208
+ name: 'Too Good To Be True',
209
+ name_ar: 'أرخص من الطبيعي',
210
+ detect: (product, _history, comparisons) => {
211
+ if (!product.price || !comparisons || comparisons.length < 2) return null;
212
+ const avgPrice = comparisons.reduce((s, c) => s + (c.priceUsd || 0), 0) / comparisons.length;
213
+ if (avgPrice > 0 && product.price < avgPrice * 0.4) {
214
+ return {
215
+ severity: 'high',
216
+ title: `Price is ${Math.round((1 - product.price / avgPrice) * 100)}% below market average`,
217
+ title_ar: `السعر أقل من متوسط السوق بنسبة ${Math.round((1 - product.price / avgPrice) * 100)}%`,
218
+ description: `Average across ${comparisons.length} sources: $${Math.round(avgPrice)}. This price ($${product.price}) may be a scam or bait-and-switch.`,
219
+ description_ar: `المتوسط عبر ${comparisons.length} مصادر: $${Math.round(avgPrice)}. هذا السعر ($${product.price}) قد يكون احتيالاً.`,
220
+ };
221
+ }
222
+ return null;
223
+ },
224
+ },
225
+ };
226
+
227
+ // ─── Analyze a single product/URL ────────────────────────────────────
228
+
229
+ async function analyzePrice(url, extractedData = null) {
230
+ const domain = _extractDomain(url);
231
+ const urlHash = crypto.createHash('sha256').update(url).digest('hex').slice(0, 16);
232
+
233
+ // Get or extract product data
234
+ let products;
235
+ if (extractedData && extractedData.products) {
236
+ products = extractedData.products;
237
+ } else {
238
+ const result = await scraper.fetchAndExtract(url);
239
+ products = result.products || [];
240
+ }
241
+
242
+ if (products.length === 0) {
243
+ return { url, domain, products: [], alerts: [], message: 'No products found on this page' };
244
+ }
245
+
246
+ // Get price history
247
+ const history = scraper.getPriceHistory(url, 30);
248
+
249
+ // Run fraud detection on each product
250
+ const alerts = [];
251
+ for (const product of products) {
252
+ for (const [key, detector] of Object.entries(FRAUD_PATTERNS)) {
253
+ const alert = detector.detect(product, history, null);
254
+ if (alert) {
255
+ const id = crypto.randomUUID();
256
+ alerts.push({ id, type: key, ...alert });
257
+ try {
258
+ stmts.insertAlert.run(id, urlHash, domain, key, alert.severity, alert.title, alert.description, JSON.stringify(alert));
259
+ } catch (_) {}
260
+ }
261
+ }
262
+ }
263
+
264
+ return {
265
+ url, domain, products, alerts, history: history.slice(0, 10),
266
+ trustScore: _calculateTrustScore(domain, alerts, history),
267
+ };
268
+ }
269
+
270
+ // ─── Cross-source Price Comparison ───────────────────────────────────
271
+
272
+ async function compareAcrossSources(query, category = 'product', options = {}) {
273
+ const sources = COMPETING_SOURCES[category] || COMPETING_SOURCES.product;
274
+ const results = [];
275
+ const alerts = [];
276
+
277
+ // Try to fetch from each source
278
+ const fetchPromises = sources
279
+ .filter(s => s.url) // skip null-URL sources
280
+ .slice(0, options.maxSources || 8)
281
+ .map(async (source) => {
282
+ const searchUrl = source.url + encodeURIComponent(query);
283
+ try {
284
+ const data = await scraper.fetchAndExtract(searchUrl, { timeout: 8000 });
285
+ if (data.products && data.products.length > 0) {
286
+ // Check if this source has WAB bridge installed
287
+ let wabBridge = null;
288
+ try { wabBridge = getWabBridgeInfo(source.domain); } catch (_) {}
289
+
290
+ for (const p of data.products) {
291
+ results.push({
292
+ source: source.name,
293
+ domain: source.domain,
294
+ type: source.type,
295
+ size: source.size,
296
+ url: searchUrl,
297
+ name: p.name || query,
298
+ price: p.price,
299
+ currency: p.currency || 'USD',
300
+ priceUsd: scraper.toUSD(p.price || 0, p.currency || 'USD'),
301
+ rating: p.rating,
302
+ availability: p.availability,
303
+ method: p.method || 'fetch',
304
+ wabBridge: !!wabBridge,
305
+ canNegotiate: wabBridge?.hasNegotiation || false,
306
+ });
307
+ }
308
+ }
309
+ } catch (_) {
310
+ // Source unavailable — skip
311
+ }
312
+ });
313
+
314
+ await Promise.allSettled(fetchPromises);
315
+
316
+ // Cross-source fraud detection
317
+ if (results.length >= 2) {
318
+ const avgPrice = results.reduce((s, r) => s + (r.priceUsd || 0), 0) / results.length;
319
+ for (const r of results) {
320
+ const tooGood = FRAUD_PATTERNS.tooGoodToBeTrue.detect({ price: r.priceUsd }, [], results);
321
+ if (tooGood) alerts.push({ ...tooGood, source: r.source });
322
+ }
323
+ }
324
+
325
+ // Cache the comparison
326
+ const dealId = crypto.randomUUID();
327
+ const best = results.sort((a, b) => (a.priceUsd || Infinity) - (b.priceUsd || Infinity))[0];
328
+ try {
329
+ stmts.insertDeal.run(
330
+ dealId, query, category, JSON.stringify(results),
331
+ results.length, best?.priceUsd || null, best?.source || null, alerts.length
332
+ );
333
+ } catch (_) {}
334
+
335
+ return {
336
+ query, category, results, alerts,
337
+ best: best || null,
338
+ sourcesChecked: results.length,
339
+ avgPrice: results.length > 0 ? Math.round(results.reduce((s, r) => s + (r.priceUsd || 0), 0) / results.length) : null,
340
+ };
341
+ }
342
+
343
+ // ─── Smart Deal Finder ───────────────────────────────────────────────
344
+ // Finds the best deals by combining comparison + fraud detection + fairness
345
+
346
+ async function findBestDeals(query, category = 'product', options = {}) {
347
+ // Step 1: Compare across sources
348
+ const comparison = await compareAcrossSources(query, category, options);
349
+
350
+ // Step 2: Score each result
351
+ const scored = comparison.results.map(r => {
352
+ let score = 100;
353
+
354
+ // Price score (lower is better) — 40 points max
355
+ if (comparison.avgPrice && r.priceUsd) {
356
+ const priceRatio = r.priceUsd / comparison.avgPrice;
357
+ score += Math.round((1 - priceRatio) * 40);
358
+ }
359
+
360
+ // Source size bonus — small sites get +15, medium +5
361
+ if (r.size === 'small') score += 15;
362
+ else if (r.size === 'medium') score += 5;
363
+ else if (r.size === 'big') score -= 5;
364
+
365
+ // Direct booking bonus
366
+ if (r.type === 'direct') score += 10;
367
+
368
+ // Rating bonus
369
+ if (r.rating && r.rating >= 4.0) score += 5;
370
+ if (r.rating && r.rating >= 4.5) score += 5;
371
+
372
+ // Availability bonus
373
+ if (r.availability === 'InStock') score += 5;
374
+
375
+ // ── WAB Bridge Priority ─────────────────────────────────────────
376
+ // Sites with the WAB script installed get priority in deals ranking
377
+ let wabBridge = null;
378
+ try { wabBridge = getWabBridgeInfo(r.domain); } catch (_) {}
379
+
380
+ if (wabBridge) {
381
+ score += 20; // Base bridge bonus
382
+ if (wabBridge.hasNegotiation) score += 15; // Negotiation = potential better deal
383
+ if (wabBridge.isListed) score += 5; // Listed in WAB directory
384
+ r.wabBridge = true;
385
+ r.canNegotiate = wabBridge.hasNegotiation;
386
+ }
387
+
388
+ // Fraud penalty
389
+ const fraudAlerts = comparison.alerts.filter(a => a.source === r.source);
390
+ score -= fraudAlerts.length * 20;
391
+
392
+ return { ...r, score, fraudAlerts };
393
+ });
394
+
395
+ // Step 3: Sort by score (fairness-weighted)
396
+ scored.sort((a, b) => b.score - a.score);
397
+
398
+ // Step 4: Generate insights
399
+ const insights = _generateInsights(scored, comparison, options.lang || 'en');
400
+
401
+ return {
402
+ query,
403
+ category,
404
+ deals: scored,
405
+ best: scored[0] || null,
406
+ alerts: comparison.alerts,
407
+ insights,
408
+ sourcesChecked: comparison.sourcesChecked,
409
+ };
410
+ }
411
+
412
+ // ─── Insights Generator ─────────────────────────────────────────────
413
+
414
+ function _generateInsights(deals, comparison, lang) {
415
+ const insights = [];
416
+ const ar = lang === 'ar';
417
+
418
+ if (deals.length === 0) {
419
+ insights.push({
420
+ icon: '🔍',
421
+ text: ar ? 'لم يتم العثور على نتائج. جرب تعديل البحث.' : 'No results found. Try modifying your search.',
422
+ });
423
+ return insights;
424
+ }
425
+
426
+ // Price range insight
427
+ const prices = deals.filter(d => d.priceUsd > 0).map(d => d.priceUsd);
428
+ if (prices.length >= 2) {
429
+ const min = Math.min(...prices);
430
+ const max = Math.max(...prices);
431
+ const savings = max - min;
432
+ if (savings > 0) {
433
+ insights.push({
434
+ icon: '💰',
435
+ text: ar
436
+ ? `فارق الأسعار بين المصادر: $${Math.round(savings)} (من $${Math.round(min)} إلى $${Math.round(max)})`
437
+ : `Price range across sources: $${Math.round(savings)} spread ($${Math.round(min)} to $${Math.round(max)})`,
438
+ type: 'savings',
439
+ });
440
+ }
441
+ }
442
+
443
+ // Small business recommendation
444
+ const smallDeals = deals.filter(d => d.size === 'small' && d.priceUsd > 0);
445
+ if (smallDeals.length > 0 && comparison.avgPrice) {
446
+ const bestSmall = smallDeals[0];
447
+ if (bestSmall.priceUsd <= comparison.avgPrice * 1.05) {
448
+ insights.push({
449
+ icon: '🏪',
450
+ text: ar
451
+ ? `${bestSmall.source} (موقع مستقل) يقدم سعراً منافساً: $${Math.round(bestSmall.priceUsd)} — ادعم الأعمال الصغيرة!`
452
+ : `${bestSmall.source} (independent site) offers competitive pricing: $${Math.round(bestSmall.priceUsd)} — support small business!`,
453
+ type: 'fairness',
454
+ });
455
+ }
456
+ }
457
+
458
+ // Fraud warnings
459
+ if (comparison.alerts.length > 0) {
460
+ insights.push({
461
+ icon: '⚠️',
462
+ text: ar
463
+ ? `تم اكتشاف ${comparison.alerts.length} تحذير(ات) احتيال. تحقق من التفاصيل أدناه.`
464
+ : `${comparison.alerts.length} fraud warning(s) detected. Check details below.`,
465
+ type: 'warning',
466
+ });
467
+ }
468
+
469
+ // Direct booking tip
470
+ const directDeals = deals.filter(d => d.type === 'direct');
471
+ if (directDeals.length > 0) {
472
+ insights.push({
473
+ icon: '🔗',
474
+ text: ar
475
+ ? 'الحجز المباشر متاح — غالباً أرخص من المنصات الكبيرة وبدون عمولات مخفية.'
476
+ : 'Direct booking available — often cheaper than big platforms with no hidden commissions.',
477
+ type: 'tip',
478
+ });
479
+ }
480
+
481
+ // Ghost Mode tip if dynamic pricing detected
482
+ const dynamicAlert = comparison.alerts.find(a => a.type === 'dynamicPricing');
483
+ if (dynamicAlert) {
484
+ insights.push({
485
+ icon: '👻',
486
+ text: ar
487
+ ? 'تم اكتشاف تسعير ديناميكي! استخدم وضع الشبح (Ghost Mode) للحصول على أسعار أفضل.'
488
+ : 'Dynamic pricing detected! Use Ghost Mode to get better prices.',
489
+ type: 'ghost',
490
+ });
491
+ }
492
+
493
+ // WAB Bridge sites — negotiation available
494
+ const bridgeDeals = deals.filter(d => d.wabBridge);
495
+ if (bridgeDeals.length > 0) {
496
+ const negotiable = bridgeDeals.filter(d => d.canNegotiate);
497
+ if (negotiable.length > 0) {
498
+ insights.push({
499
+ icon: '🤝',
500
+ text: ar
501
+ ? `${negotiable.map(d => d.source).join(', ')} — مواقع متعاونة مع WAB! يمكن التفاوض على السعر تلقائياً للحصول على خصم أفضل.`
502
+ : `${negotiable.map(d => d.source).join(', ')} — WAB-enabled sites! Auto-negotiation available for better prices.`,
503
+ type: 'wab-bridge',
504
+ });
505
+ } else {
506
+ insights.push({
507
+ icon: '🌉',
508
+ text: ar
509
+ ? `${bridgeDeals.map(d => d.source).join(', ')} — مواقع مثبت عليها جسر WAB. بيانات أكثر دقة وموثوقية.`
510
+ : `${bridgeDeals.map(d => d.source).join(', ')} — WAB Bridge sites. More accurate and reliable data.`,
511
+ type: 'wab-bridge',
512
+ });
513
+ }
514
+ }
515
+
516
+ return insights;
517
+ }
518
+
519
+ // ─── Trust Score ─────────────────────────────────────────────────────
520
+
521
+ function _calculateTrustScore(domain, alerts, history) {
522
+ let score = 70; // neutral start
523
+
524
+ // More history = more trustworthy
525
+ if (history.length >= 10) score += 10;
526
+ else if (history.length >= 5) score += 5;
527
+
528
+ // Alerts reduce trust
529
+ for (const a of alerts) {
530
+ if (a.severity === 'high') score -= 25;
531
+ else if (a.severity === 'medium') score -= 15;
532
+ else score -= 5;
533
+ }
534
+
535
+ // Known trustworthy domains
536
+ const trusted = ['booking.com', 'airbnb.com', 'hotels.com', 'expedia.com', 'amazon.com'];
537
+ if (trusted.includes(domain)) score += 10;
538
+
539
+ // Local/small indicators
540
+ const smallTlds = ['.local', '.shop', '.store', '.boutique'];
541
+ if (smallTlds.some(t => domain.endsWith(t))) score += 5;
542
+
543
+ return Math.max(0, Math.min(100, score));
544
+ }
545
+
546
+ // ─── Helpers ─────────────────────────────────────────────────────────
547
+
548
+ function _extractDomain(url) {
549
+ try { return new URL(url).hostname.replace(/^www\./, ''); } catch (_) { return ''; }
550
+ }
551
+
552
+ function getAlerts(domain, limit = 20) {
553
+ return stmts.getAlerts.all(domain, limit);
554
+ }
555
+
556
+ // ─── Exports ─────────────────────────────────────────────────────────
557
+
558
+ module.exports = {
559
+ analyzePrice,
560
+ compareAcrossSources,
561
+ findBestDeals,
562
+ getAlerts,
563
+ COMPETING_SOURCES,
564
+ FRAUD_PATTERNS,
565
+ };