Aichatbot12321 commited on
Commit
e562fe9
·
verified ·
1 Parent(s): b9d10e9

Upload 3 files

Browse files
Files changed (3) hide show
  1. search.html +1 -1
  2. search.js +1 -1
  3. server.js +316 -354
search.html CHANGED
@@ -16939,7 +16939,7 @@ body.ai-dark-thinking .fill-empty-fill {
16939
  const isWinner = !!bestId && pt.platformId === bestId;
16940
  const itemsHtml = (pt.cartItems || []).map(function(ci) {
16941
  const directUrl = ci.directProductUrl || ci.url || '#';
16942
- const img = ci.snappedImage || ci.imageUrl || ci.fallbackImageUrl || ('https://tse1.mm.bing.net/th?q=' + encodeURIComponent((ci.title || ci.itemName || 'Product') + ' pack india') + '&w=360&h=360&c=7&rs=1&p=0');
16943
  const imgHtml = img
16944
  ? `<a href="${esc(directUrl)}" target="_blank" rel="noopener noreferrer" class="qc-prod-img-wrap" style="display:block;position:relative;" title="Screenshot taken by the live browser on ${esc(pt.platformName)}">
16945
  <span class="qc-img-affordable-badge">\uD83D\uDCF8 Live browser screenshot</span>
 
16939
  const isWinner = !!bestId && pt.platformId === bestId;
16940
  const itemsHtml = (pt.cartItems || []).map(function(ci) {
16941
  const directUrl = ci.directProductUrl || ci.url || '#';
16942
+ const img = ci.snappedImage || ci.imageUrl || '';
16943
  const imgHtml = img
16944
  ? `<a href="${esc(directUrl)}" target="_blank" rel="noopener noreferrer" class="qc-prod-img-wrap" style="display:block;position:relative;" title="Screenshot taken by the live browser on ${esc(pt.platformName)}">
16945
  <span class="qc-img-affordable-badge">\uD83D\uDCF8 Live browser screenshot</span>
search.js CHANGED
@@ -189,7 +189,7 @@
189
  const isWinner = !!bestId && pt.platformId === bestId;
190
  const itemsHtml = (pt.cartItems || []).map(function(ci) {
191
  const directUrl = ci.directProductUrl || ci.url || '#';
192
- const img = ci.snappedImage || ci.imageUrl || ci.fallbackImageUrl || ('https://tse1.mm.bing.net/th?q=' + encodeURIComponent((ci.title || ci.itemName || 'Product') + ' pack india') + '&w=360&h=360&c=7&rs=1&p=0');
193
  const imgHtml = img
194
  ? `<a href="${esc(directUrl)}" target="_blank" rel="noopener noreferrer" class="qc-prod-img-wrap" style="display:block;position:relative;" title="Screenshot taken by the live browser on ${esc(pt.platformName)}">
195
  <span class="qc-img-affordable-badge">\uD83D\uDCF8 Live browser screenshot</span>
 
189
  const isWinner = !!bestId && pt.platformId === bestId;
190
  const itemsHtml = (pt.cartItems || []).map(function(ci) {
191
  const directUrl = ci.directProductUrl || ci.url || '#';
192
+ const img = ci.snappedImage || ci.imageUrl || '';
193
  const imgHtml = img
194
  ? `<a href="${esc(directUrl)}" target="_blank" rel="noopener noreferrer" class="qc-prod-img-wrap" style="display:block;position:relative;" title="Screenshot taken by the live browser on ${esc(pt.platformName)}">
195
  <span class="qc-img-affordable-badge">\uD83D\uDCF8 Live browser screenshot</span>
server.js CHANGED
@@ -6334,14 +6334,16 @@ try {
6334
  // ==========================================================================================
6335
  // ===== SHOP-CORE BEGIN =====================================================================
6336
  // Live shopping agent logic:
6337
- // - Opens store directly with anti-bot stealth & pre-seeded Bihar pincode (avoids Google /sorry/ IP blocks)
6338
- // - Dismisses Flipkart/JioMart/Blinkit popups & login modals without false "website malfunctioned" skips
6339
- // - Focuses & clears search <input> via DOM (NEVER presses Control+A on document.body, so JioMart never selects all page text!)
6340
- // - Clicks search box, types product, submits search, extracts cards, scores & highlights best product, clicks it & captures screenshot
6341
- // - Includes a live store fallback renderer for Blinkit / stores that block Hugging Face datacenter IPs so Blinkit NEVER fails with an error!
 
 
6342
  const SHOP_MAX_ITEMS = 3;
6343
- const SHOP_PER_STORE_MS = parseInt(process.env.SHOP_PER_STORE_MS) || 65000;
6344
- const SHOP_TOTAL_BUDGET_MS = parseInt(process.env.SHOP_TOTAL_BUDGET_MS) || 190000;
6345
  const SHOP_HOME_URLS = {
6346
  flipkart: 'https://www.flipkart.com/', blinkit: 'https://blinkit.com/', jiomart: 'https://www.jiomart.com/',
6347
  amazon: 'https://www.amazon.in/', citymall: 'https://citymall.live/', meesho: 'https://www.meesho.com/',
@@ -6366,15 +6368,26 @@ function shopQueryTokens(q) {
6366
  toks.forEach(function (t) {
6367
  if (/^\d+(?:\.\d+)?(?:kg|g|l|ml)$/.test(t)) sizes.push(t);
6368
  else if (/^[\d.]+$/.test(t)) { /* bare number: ignore */ }
6369
- else if (t.length >= 3 && !SHOP_STOP.has(t)) words.push(t);
6370
  });
6371
  return { words: words, sizes: sizes };
6372
  }
6373
 
6374
- // Score every product card and choose the best-value *relevant* one. Pure function (unit-testable).
6375
  function shopPickBestProduct(cards, query, maxPrice) {
6376
  var qt = shopQueryTokens(query);
6377
- var usable = (cards || []).filter(function (c) { return c && c.price > 0 && !c.outOfStock; });
 
 
 
 
 
 
 
 
 
 
 
6378
  var rows = usable.map(function (c) {
6379
  var titleN = shopNormUnits(c.title || '');
6380
  var hayN = shopNormUnits((c.title || '') + ' ' + (c.text || ''));
@@ -6385,9 +6398,8 @@ function shopPickBestProduct(cards, query, maxPrice) {
6385
  return { c: c, rel: rel, sizeOk: sizeOk };
6386
  });
6387
  var tier = rows.filter(function (r) { return r.rel >= 0.99 && r.sizeOk !== false; }), tierName = 'exact';
6388
- if (!tier.length) { tier = rows.filter(function (r) { return r.rel >= 0.5 && r.sizeOk !== false; }); tierName = 'close'; }
6389
- if (!tier.length) { tier = rows.filter(function (r) { return r.rel >= 0.45; }); tierName = 'size-differs'; }
6390
- if (!tier.length && rows.length) { tier = rows; tierName = 'fallback-card'; }
6391
  if (!tier.length) {
6392
  return { best: null, ranked: [], overBudget: false, tier: 'none',
6393
  reason: rows.length ? ('none of the ' + rows.length + ' products on the results page matched "' + query + '"') : 'no in-stock priced products found on the results page' };
@@ -6408,11 +6420,11 @@ function shopPickBestProduct(cards, query, maxPrice) {
6408
  if (c.sponsored) s -= 12;
6409
  r.score = s;
6410
  });
6411
- if (overBudget) tier.sort(function (a, b) { return a.c.price - b.c.price; });
6412
  else tier.sort(function (a, b) { return b.score - a.score; });
6413
  return {
6414
  best: tier[0].c, overBudget: overBudget, tier: tierName,
6415
- ranked: tier.slice(0, 6).map(function (r) { return { idx: r.c.idx, title: r.c.title, price: r.c.price, score: Math.round(r.score * 10) / 10 }; })
6416
  };
6417
  }
6418
 
@@ -6422,12 +6434,15 @@ function SHOP_EXTRACT_CARDS_IN_PAGE(maxCards) {
6422
  var HAS_PRICE = /(?:₹|Rs\.?|INR)\s*\d/;
6423
  var PRICE_G = /(?:₹|Rs\.?|INR)\s*([0-9][0-9,]*(?:\.[0-9]{1,2})?)/g;
6424
  function vis(el) {
 
6425
  var r = el.getBoundingClientRect(); if (r.width < 2 || r.height < 2) return false;
6426
  var cs = getComputedStyle(el); return cs.visibility !== 'hidden' && cs.display !== 'none' && cs.opacity !== '0';
6427
  }
6428
  function struck(el, stopEl) {
6429
  for (var e = el; e && e !== document.body; e = e.parentElement) {
6430
  var tg = e.tagName; if (tg === 'DEL' || tg === 'S' || tg === 'STRIKE') return true;
 
 
6431
  var td = getComputedStyle(e).textDecorationLine || ''; if (td.indexOf('line-through') >= 0) return true;
6432
  if (e === stopEl) break;
6433
  }
@@ -6443,49 +6458,70 @@ function SHOP_EXTRACT_CARDS_IN_PAGE(maxCards) {
6443
  var v = parseFloat(m[1]); if (isNaN(v)) return null; var u = m[2].toLowerCase(); return Math.round(u === 'k' ? v * 1000 : u === 'm' ? v * 1e6 : v);
6444
  }
6445
  function isJunk(l) {
6446
- if (l.length < 4 || l.length > 170) return true;
6447
  if (HAS_PRICE.test(l)) return true;
6448
  if (/^\(?[\d.,]+\s*[kKmM]?\)?$/.test(l)) return true;
6449
  if (/^[★⭐\d.\s()\/*]+$/.test(l)) return true;
6450
  if (/%\s*off|^save\b|\boff$/i.test(l)) return true;
6451
- if (/^(sponsored|ad\b|add\b|buy\b|notify|out of stock|sold out|bestseller|best seller|new\b|free delivery|get it|prime|limited time|deal\b|only \d+ left|options?\b|view\b|wishlist|\d+\s*options?)/i.test(l)) return true;
6452
  if (/\b\d+\s*(?:mins?|minutes)\b/i.test(l) && l.length < 22) return true;
6453
  return false;
6454
  }
6455
 
6456
  Array.prototype.forEach.call(document.querySelectorAll('[data-shop-card]'), function (e) { e.removeAttribute('data-shop-card'); });
 
6457
  var all = document.body ? document.body.getElementsByTagName('*') : [];
6458
  var priceEls = [];
6459
  for (var i = 0; i < all.length; i++) {
6460
  var el = all[i], tg = el.tagName;
6461
  if (tg === 'SCRIPT' || tg === 'STYLE' || tg === 'NOSCRIPT' || tg === 'svg' || tg === 'path') continue;
6462
- if (el.childElementCount > 4) continue;
6463
- var t = el.textContent; if (!t || t.length > 70 || !HAS_PRICE.test(t)) continue;
6464
- var childHas = false;
6465
- for (var k = 0; k < el.children.length; k++) { var ch = el.children[k]; if (HAS_PRICE.test(ch.textContent || '') && vis(ch)) { childHas = true; break; } }
6466
- if (childHas) continue;
 
 
 
 
 
 
 
6467
  if (!vis(el)) continue;
6468
  priceEls.push(el);
6469
  }
 
6470
  var cardMap = new Map();
6471
  priceEls.forEach(function (pe) {
6472
- var c = pe, found = null;
6473
- for (var d = 0; d < 10 && c.parentElement && c.parentElement !== document.body; d++) {
6474
- c = c.parentElement;
6475
- var r = c.getBoundingClientRect();
6476
- if (r.width > vw * 0.68 || r.height > 780) break;
6477
- var np = (c.textContent.match(PRICE_G) || []).length; if (np > 5) break;
6478
- var hasImg = !!c.querySelector('img, picture, [style*="background-image"]');
6479
- var clickable = c.tagName === 'A' || !!c.querySelector('a[href], button, [role="button"], [tabindex]') || !!c.closest('a[href]') || getComputedStyle(c).cursor === 'pointer';
6480
- if (hasImg && clickable && r.width >= 95 && r.height >= 85) { found = c; break; }
 
 
 
 
 
 
 
 
 
 
 
6481
  }
6482
  if (!found) return;
6483
  if (!cardMap.has(found)) cardMap.set(found, []);
6484
  cardMap.get(found).push(pe);
6485
  });
 
6486
  var cards = Array.from(cardMap.keys());
6487
  cards.sort(function (a, b) { var ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect(); return (ra.top - rb.top) || (ra.left - rb.left); });
6488
- cards = cards.slice(0, maxCards || 24);
6489
 
6490
  var out = [];
6491
  cards.forEach(function (card, idx) {
@@ -6495,7 +6531,7 @@ function SHOP_EXTRACT_CARDS_IN_PAGE(maxCards) {
6495
  var cands = [];
6496
  pes.forEach(function (pe) {
6497
  var pt = (pe.textContent || '').replace(/\s+/g, ' ').trim();
6498
- if (/\/\s*(?:100\s*)?(?:g|gm|kg|ml|l|ltr|unit|pc|piece)\b|per\s*(?:100|kg|g|ml|l|unit|piece)|\bemi\b|cashback|coupon|\bfees?\b|delivery|minimum|\bextra\b|\boff\b|\bsave\b|^\(/i.test(pt)) return;
6499
  var ns = nums(pt); if (!ns.length) return;
6500
  cands.push({ v: ns[0], second: ns.length > 1 ? ns[1] : null, fs: parseFloat(getComputedStyle(pe).fontSize) || 0, st: struck(pe, card) });
6501
  });
@@ -6535,22 +6571,35 @@ function SHOP_EXTRACT_CARDS_IN_PAGE(maxCards) {
6535
  if (!m && rating !== null) m = text.match(/\(\s*([\d,.]+\s*[kKmM]?)\s*\)/);
6536
  if (m) reviews = toCount(m[1]);
6537
 
 
 
 
6538
  var alt = '';
6539
  Array.prototype.forEach.call(card.querySelectorAll('img'), function (im) {
6540
  var a = (im.getAttribute('alt') || '').trim();
6541
- if (a.length > alt.length && /[A-Za-z]{3}/.test(a) && !/^(product|image|photo|logo|banner|thumbnail)/i.test(a)) alt = a;
6542
  });
6543
  var cand = '';
6544
  for (var j = 0; j < lines.length; j++) { if (!isJunk(lines[j]) && /[A-Za-z]{3}/.test(lines[j])) { cand = lines[j]; break; } }
6545
- var title = (alt && alt.length >= 8) ? alt : cand;
6546
  if (alt && cand && cand.length > alt.length + 5 && cand.toLowerCase().indexOf(alt.toLowerCase()) >= 0) title = cand;
6547
- if (!title) title = cand || alt;
6548
 
6549
  var a = null;
6550
  if (card.tagName === 'A' && card.href) a = card;
6551
- else a = card.querySelector('a[href*="/p/"], a[href*="/dp/"], a[href*="/prn/"], a[href*="/prid/"], a[href*="/pd/"], a[href*="/pn/"], a[href*="/product"]') || card.querySelector('a[href]') || card.closest('a[href]');
6552
  var href = (a && a.href) ? a.href.split('#')[0] : '';
6553
  if (/^javascript:/i.test(href)) href = '';
 
 
 
 
 
 
 
 
 
 
6554
 
6555
  var etaM = text.match(/\b(\d{1,2})\s*(?:mins?|minutes)\b/i);
6556
  card.setAttribute('data-shop-card', String(idx));
@@ -6571,39 +6620,62 @@ function SHOP_HIGHLIGHT_IN_PAGE(idx) {
6571
  var el = document.querySelector('[data-shop-card="' + idx + '"]');
6572
  if (!el) return null;
6573
  try { el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' }); } catch (e) { el.scrollIntoView(); }
6574
- el.classList.add('ai-shop-hl'); el.style.outline = '4px solid #10b981'; el.style.outlineOffset = '3px'; el.style.boxShadow = '0 0 26px rgba(16,185,129,.55)';
6575
  if (el.tagName === 'A') el.removeAttribute('target');
 
 
6576
  Array.prototype.forEach.call(el.querySelectorAll('a[target]'), function (a) { a.removeAttribute('target'); });
6577
- var aLink = el.tagName === 'A' ? el : (el.querySelector('a[href*="/p/"], a[href*="/dp/"], a[href*="/prn/"], a[href*="/pd/"], a[href]') || el.querySelector('img') || el);
6578
- var r = aLink.getBoundingClientRect();
6579
- if (r.width < 10 || r.height < 10) r = el.getBoundingClientRect();
6580
- return { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + Math.min(r.height / 2, 110)) };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6581
  }
6582
 
6583
  function SHOP_READ_PDP_IN_PAGE(q) {
 
6584
  var HAS_PRICE = /(?:₹|Rs\.?|INR)\s*\d/;
6585
  function vis(el) { var r = el.getBoundingClientRect(); if (r.width < 2 || r.height < 2) return false; var cs = getComputedStyle(el); return cs.visibility !== 'hidden' && cs.display !== 'none' && cs.opacity !== '0'; }
6586
  function struck(el) {
6587
  for (var e = el; e && e !== document.body; e = e.parentElement) {
6588
  var tg = e.tagName; if (tg === 'DEL' || tg === 'S' || tg === 'STRIKE') return true;
 
 
6589
  if ((getComputedStyle(e).textDecorationLine || '').indexOf('line-through') >= 0) return true;
6590
  }
6591
  return false;
6592
  }
6593
  function numOf(t) { var m = t.match(/(?:₹|Rs\.?|INR)\s*([0-9][0-9,]*(?:\.[0-9]{1,2})?)/); return m ? parseFloat(m[1].replace(/,/g, '')) : null; }
6594
- var h1 = document.querySelector('h1');
6595
  var title = h1 ? (h1.innerText || '').trim() : '';
6596
  if (!title) { var og = document.querySelector('meta[property="og:title"]'); if (og) title = og.getAttribute('content') || ''; }
6597
  var cands = [], all = document.body.getElementsByTagName('*');
6598
  for (var i = 0; i < all.length; i++) {
6599
- var el = all[i]; if (el.childElementCount > 3) continue;
 
 
6600
  var t = (el.textContent || '').replace(/\s+/g, ' ').trim();
6601
- if (!t || t.length > 40 || !HAS_PRICE.test(t)) continue;
6602
- var childHas = false;
6603
- for (var k = 0; k < el.children.length; k++) { if (HAS_PRICE.test(el.children[k].textContent || '') && vis(el.children[k])) { childHas = true; break; } }
6604
- if (childHas || !vis(el)) continue;
 
 
 
6605
  var r = el.getBoundingClientRect(); if (r.top < 0 || r.top > 900) continue;
6606
- if (/\/\s*(?:100\s*)?(?:g|gm|kg|ml|l)\b|per\s*(?:100|kg|g|ml|l|unit)|\bemi\b|cashback|coupon|\bfees?\b|delivery|minimum|\boff\b|\bsave\b|\bextra\b|^get\s|^\(/i.test(t)) continue;
6607
  cands.push({ v: numOf(t), fs: parseFloat(getComputedStyle(el).fontSize) || 0, st: struck(el), top: r.top });
6608
  }
6609
  var sell = null;
@@ -6661,14 +6733,14 @@ function SHOP_FIND_UI_IN_PAGE(q) {
6661
  list = Array.prototype.filter.call(document.querySelectorAll('input, [contenteditable="true"]'), function (el) {
6662
  if (!vis(el)) return false; var ty = (el.type || 'text').toLowerCase(); if (BAD_TYPES.indexOf(ty) >= 0) return false;
6663
  var s = attrs(el);
6664
- if (/search|find|keyword|autocomplete-0-input|twotabsearchtextbox/.test(s)) return false;
 
6665
  return /pin\s*-?code|postal|zip|locat|locality|area|city|deliver|glux/.test(s);
6666
  });
6667
  list.sort(function (a, b) { return (inDialog(b) ? 1 : 0) - (inDialog(a) ? 1 : 0); });
6668
  return list.length ? box(list[0]) : null;
6669
  }
6670
  if (kind === 'locTrigger') {
6671
- // On Flipkart homepage, do NOT click random header buttons that cause full-page navigation/login modals!
6672
  if (/flipkart\.com/i.test(location.hostname) && !document.querySelector('input[placeholder*="pincode" i], input[placeholder*="pin code" i]')) {
6673
  return null;
6674
  }
@@ -6687,7 +6759,7 @@ function SHOP_FIND_UI_IN_PAGE(q) {
6687
  }
6688
  if (kind === 'suggestion') {
6689
  var ib = arg.box; if (!ib) return null;
6690
- var pool = document.querySelectorAll('li, [role="option"], [role="listitem"], div, span, a, p');
6691
  var best = null, bestScore = -1;
6692
  for (i = 0; i < pool.length; i++) {
6693
  e = pool[i]; if (e.childElementCount > 6 || !vis(e)) continue;
@@ -6697,8 +6769,10 @@ function SHOP_FIND_UI_IN_PAGE(q) {
6697
  var t = label(e); if (t.length < 3 || t.length > 140) continue;
6698
  if (/^(apply|check|confirm|submit|update|continue|done|save|proceed|use current location|detect|locate me)/i.test(t)) continue;
6699
  var sc = 0; if (e.tagName === 'LI' || e.getAttribute('role') === 'option' || e.getAttribute('role') === 'listitem') sc += 3;
6700
- if (arg.pin && t.indexOf(arg.pin) >= 0) sc += 2; if (getComputedStyle(e).cursor === 'pointer') sc += 1;
6701
- if (/suggest|result|address|locationsearch|option|list/i.test((e.className || '') + (e.parentElement && e.parentElement.className || ''))) sc += 1;
 
 
6702
  if (sc < 2) continue;
6703
  if (!best || sc > bestScore || (sc === bestScore && r.top < best.t)) { best = box(e, { text: t.slice(0, 60) }); bestScore = sc; }
6704
  }
@@ -6717,7 +6791,6 @@ function SHOP_FIND_UI_IN_PAGE(q) {
6717
  return box(list[0], { label: label(list[0]).slice(0, 20) });
6718
  }
6719
  if (kind === 'searchInput') {
6720
- // Explicit priority for JioMart (#autocomplete-0-input, .aa-Input), Flipkart (input[name="q"]), Amazon (#twotabsearchtextbox), Blinkit
6721
  var prioritySelectors = [
6722
  'input#autocomplete-0-input',
6723
  'input.aa-Input',
@@ -6735,7 +6808,7 @@ function SHOP_FIND_UI_IN_PAGE(q) {
6735
  var pel = pEls[j];
6736
  if (!vis(pel)) continue;
6737
  var ps = attrs(pel);
6738
- if (/pin\s*code|pincode|glux/.test(ps)) continue;
6739
  var pr = pel.getBoundingClientRect();
6740
  if (pr.top <= 340 && pr.width >= 60) return box(pel);
6741
  }
@@ -6750,7 +6823,7 @@ function SHOP_FIND_UI_IN_PAGE(q) {
6750
  return list.length ? box(list[0]) : null;
6751
  }
6752
  if (kind === 'searchTrigger') {
6753
- list = Array.prototype.filter.call(document.querySelectorAll('button, a, [role="button"], div, span, label'), function (el) {
6754
  if (!vis(el) || el.childElementCount > 6) return false; var r = el.getBoundingClientRect(); if (r.top > 220 || r.width < 40) return false;
6755
  var t = label(el) + ' ' + attrs(el);
6756
  return t.length <= 120 && (/^search\b|search\s+for|search\s+in\s+jiomart|search\s+products/i.test(label(el)) || /search.*trigger|search.*bar|search.*box|header.*search/i.test(attrs(el)));
@@ -6773,7 +6846,6 @@ function SHOP_FIND_UI_IN_PAGE(q) {
6773
  return hit;
6774
  }
6775
  if (kind === 'popup') {
6776
- // Explicit Flipkart login modal close button first
6777
  var fkClose = document.querySelector('button._2KpZ6l._2doB4z, span._30XB9F, [role="dialog"] button[aria-label*="close" i], [class*="modal" i] button[class*="close" i]');
6778
  if (fkClose && vis(fkClose)) return box(fkClose, { text: 'Close Modal' });
6779
  list = Array.prototype.filter.call(document.querySelectorAll('button, [role="button"], span[role="button"]'), function (el) {
@@ -6808,7 +6880,6 @@ async function shopDismissPopups(h) {
6808
  }
6809
 
6810
  // Safely focus & clear an <input> via DOM without EVER pressing Control+A on document.body!
6811
- // This completely fixes the JioMart bug where Control+A selected all text on the page.
6812
  async function shopFocusAndClearInput(h, box, selectorHint) {
6813
  await h.clickAt(box.x, box.y);
6814
  await h.sleep(180);
@@ -6832,7 +6903,7 @@ async function shopFocusAndClearInput(h, box, selectorHint) {
6832
  if (!target) {
6833
  var hit = document.elementFromPoint(arg.x, arg.y);
6834
  if (isTextInputEl(hit)) target = hit;
6835
- else if (hit) target = hit.querySelector('input, textarea') || hit.closest('label, form, div')?.querySelector('input, textarea');
6836
  }
6837
  if (!target && isTextInputEl(document.activeElement)) {
6838
  target = document.activeElement;
@@ -6844,23 +6915,23 @@ async function shopFocusAndClearInput(h, box, selectorHint) {
6844
  if (rk.width > 40 && rk.height > 12 && rk.top >= 0 && rk.top < 450) { target = allInputs[k]; break; }
6845
  }
6846
  }
6847
- // Clear any accidental document text selection!
6848
  try { if (window.getSelection) window.getSelection().removeAllRanges(); } catch (e) {}
6849
  if (!target) return false;
6850
  try {
6851
  target.focus();
6852
  target.click();
6853
- var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;
 
6854
  if (nativeInputValueSetter) nativeInputValueSetter.call(target, '');
6855
  else target.value = '';
6856
  target.dispatchEvent(new Event('input', { bubbles: true }));
6857
  } catch (e) {}
6858
  return true;
6859
- }, { x: box.x, y: box.y, selectorHint: selectorHint || '' }).catch(() => false);
6860
  return focusedOk;
6861
  }
6862
 
6863
- // Tightened block detector: NEVER falsely thinks Flipkart malfunctioned while loading or when search/product elements exist!
6864
  async function shopLooksBlocked(h) {
6865
  try {
6866
  var pg = h.getPage();
@@ -6868,7 +6939,6 @@ async function shopLooksBlocked(h) {
6868
  return await pg.evaluate(function () {
6869
  var url = String(location.href || '');
6870
  if (/\/sorry\/index|validateCaptcha/i.test(url)) return true;
6871
- // If the page has a search input or product prices, it is NOT blocked!
6872
  var hasSearchOrPrices = !!document.querySelector('input[name="q"], input#twotabsearchtextbox, input#autocomplete-0-input, input.aa-Input, input[type="search"]')
6873
  || /(?:₹|Rs\.?)\s*\d/.test((document.body && document.body.innerText) || '');
6874
  if (hasSearchOrPrices) return false;
@@ -6884,99 +6954,85 @@ async function shopLooksBlocked(h) {
6884
  async function shopRecoverFromBlock(h, plat) {
6885
  for (var a = 1; a <= 2; a++) {
6886
  if (!(await shopLooksBlocked(h))) return true;
6887
- h.log('⚠️ ' + plat.name + ' showed a verification screen (try ' + a + '/2) - recovering');
6888
  var link = await shopFind(h, 'homeLink');
6889
- await h.sleep(1500 * a);
6890
- if (link) { await h.clickAt(link.x, link.y); await h.sleep(1500); }
6891
- else { try { await h.goto(shopHomeUrl(plat)); } catch (e) {} await h.sleep(1500); }
6892
  await h.snap();
6893
  }
6894
  return !(await shopLooksBlocked(h));
6895
  }
6896
 
6897
- // Step 1: Open the store directly (avoids Google datacenter IP block "/sorry/" error!)
6898
  async function shopOpenStoreDirect(h, plat) {
6899
  var home = shopHomeUrl(plat);
6900
  h.log('🌐 Opening ' + plat.name + ' (' + home + ')');
6901
  try {
6902
  await h.goto(home);
6903
  } catch (e) {
6904
- return { ok: false, why: plat.name + ' did not finish initial load' };
6905
  }
6906
  await h.sleep(800);
6907
- // Pre-seed location storage for Blinkit, JioMart, Flipkart so location modals don't block search
6908
- try {
6909
- await h.getPage().evaluate(function (pin) {
6910
- try {
6911
- localStorage.setItem('pincode', pin);
6912
- localStorage.setItem('delivery_pincode', pin);
6913
- localStorage.setItem('nms_mgo_pincode', pin);
6914
- localStorage.setItem('location', JSON.stringify({ lat: 25.5941, lon: 85.1376, lng: 85.1376, city: 'Patna', state: 'Bihar', pincode: pin, locality: 'Patna, Bihar ' + pin }));
6915
- localStorage.setItem('user_location', JSON.stringify({ lat: 25.5941, lng: 85.1376, address: 'Patna, Bihar ' + pin, pincode: pin }));
6916
- document.cookie = 'pincode=' + pin + '; path=/; max-age=86400';
6917
- document.cookie = 'gr_1_lat=25.5941; path=/; max-age=86400';
6918
- document.cookie = 'gr_1_lon=85.1376; path=/; max-age=86400';
6919
- document.cookie = 'gr_1_locality=Patna; path=/; max-age=86400';
6920
- } catch (e) {}
6921
- }, String(h.pincode || '800001'));
6922
- } catch (e) {}
6923
  await h.snap();
6924
  return { ok: true };
6925
  }
6926
 
6927
- // Step 2: Enter the user's pincode safely (never uses Control+A and never clicks Flipkart nav links that break the page)
6928
  async function shopSetLocation(h, plat, pin) {
6929
  pin = String(pin);
6930
- // On Flipkart, pre-seeding cookie + setting pincode on product/search page avoids the homepage reload trap
6931
  if (plat.id === 'flipkart') {
6932
  var fkLocInput = await shopFind(h, 'locInput');
6933
  if (!fkLocInput) {
6934
- return { ok: true, how: 'Patna Bihar (' + pin + ') pre-configured for Flipkart', pinSeenOnPage: true };
6935
  }
6936
  }
6937
  var found = await shopFind(h, 'locInput');
6938
  if (!found) {
6939
  var trig = await shopFind(h, 'locTrigger');
6940
  if (trig) {
6941
- h.log('📍 Opening location selector ("' + (trig.text || '') + '")');
6942
  await h.clickAt(trig.x, trig.y);
6943
- await h.sleep(900);
6944
  try { await h.getPage().waitForLoadState('domcontentloaded', { timeout: 4000 }); } catch (e) {}
6945
  found = await shopFind(h, 'locInput');
6946
  }
6947
  }
6948
- if (!found) return { ok: true, how: 'location pre-seeded (' + pin + ')', pinSeenOnPage: true };
6949
- await shopFocusAndClearInput(h, found, 'input[placeholder*="pin" i], input[placeholder*="locat" i], input[placeholder*="area" i], input[id*="GLUX" i]');
6950
  var pg = h.getPage();
6951
- await pg.keyboard.type(pin, { delay: 65 });
 
6952
  h.log('📍 Typed pincode ' + pin);
6953
- await h.snap(); await h.sleep(1000);
6954
- var how = 'typed pincode ' + pin, acted = false;
6955
  var sug = await shopFind(h, 'suggestion', { pin: pin, box: found });
6956
- if (sug) { await h.clickAt(sug.x, sug.y); how += ' + picked suggestion'; acted = true; await h.sleep(1000); }
6957
- else { try { await pg.keyboard.press('Enter'); } catch (e) {} await h.sleep(800); }
6958
  for (var k = 0; k < 2; k++) {
6959
  var still = await shopFind(h, 'locInput');
6960
  var btn = await shopFind(h, 'confirm', { box: still || found });
6961
  if (!btn) break;
6962
- await h.clickAt(btn.x, btn.y); how += ' + clicked ' + btn.label; acted = true; await h.sleep(1000);
6963
  }
6964
- try { await pg.waitForLoadState('domcontentloaded', { timeout: 4000 }); } catch (e) {}
6965
- await h.sleep(600); await h.snap();
6966
- return { ok: true, how: how, pinSeenOnPage: true };
 
 
6967
  }
6968
 
6969
- // Step 3: Collect product cards
6970
  async function shopCollectCards(h, tries) {
6971
  for (var i = 0; i < tries; i++) {
6972
  var page = h.getPage();
6973
  try { await page.waitForLoadState('domcontentloaded', { timeout: 4000 }); } catch (e) {}
6974
- try { await page.waitForFunction(function () { return /(?:₹|Rs\.?)\s*\d/.test((document.body && document.body.innerText) || ''); }, null, { timeout: 4500 }); } catch (e) {}
6975
- await h.sleep(500);
6976
  try { await page.mouse.wheel(0, 220); } catch (e) {}
6977
- await h.sleep(400);
6978
  try { await page.evaluate(function () { window.scrollTo(0, 0); }); } catch (e) {}
6979
- await h.sleep(200);
6980
  var cards = [];
6981
  try { cards = await h.getPage().evaluate(SHOP_EXTRACT_CARDS_IN_PAGE, 28); } catch (e) { cards = []; }
6982
  if (cards && cards.length) return cards;
@@ -6984,15 +7040,14 @@ async function shopCollectCards(h, tries) {
6984
  return [];
6985
  }
6986
 
6987
- // Step 3b: Click search bar, focus & clear input via DOM (NEVER Control+A!), type product, submit & collect cards
6988
  async function shopSearchAndCollect(h, plat, item) {
6989
  var box = await shopFind(h, 'searchInput');
6990
  if (!box) {
6991
  var trig = await shopFind(h, 'searchTrigger');
6992
  if (trig) {
6993
- h.log('👆 Clicking ' + plat.name + ' search bar');
6994
  await h.clickAt(trig.x, trig.y);
6995
- await h.sleep(700);
6996
  box = await shopFind(h, 'searchInput');
6997
  }
6998
  }
@@ -7000,8 +7055,7 @@ async function shopSearchAndCollect(h, plat, item) {
7000
  var pg = h.getPage();
7001
  var beforeUrl = pg.url();
7002
  await shopFocusAndClearInput(h, box, 'input#autocomplete-0-input, input.aa-Input, input[name="q"], input#twotabsearchtextbox, input[type="search"]');
7003
- await pg.keyboard.type(item, { delay: 40 });
7004
- // Also ensure input value & events are synced for React/Algolia inputs (like JioMart & Blinkit)
7005
  await pg.evaluate(function (qText) {
7006
  try { if (window.getSelection) window.getSelection().removeAllRanges(); } catch (e) {}
7007
  var el = document.activeElement;
@@ -7009,29 +7063,27 @@ async function shopSearchAndCollect(h, plat, item) {
7009
  el = document.querySelector('input#autocomplete-0-input, input.aa-Input, input[name="q"], input#twotabsearchtextbox, input[type="search"]');
7010
  }
7011
  if (el) {
7012
- var setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;
 
7013
  if (setter && (!el.value || el.value.length < 2)) setter.call(el, qText);
7014
  el.dispatchEvent(new Event('input', { bubbles: true }));
7015
  el.dispatchEvent(new Event('change', { bubbles: true }));
7016
  }
7017
- }, item).catch(() => {});
7018
- h.log('🔎 Typed "' + item + '" in ' + plat.name + ' search box');
7019
- await h.snap();
7020
- await h.sleep(450);
7021
  await pg.keyboard.press('Enter');
7022
- await h.sleep(1300);
7023
- try { await pg.waitForLoadState('domcontentloaded', { timeout: 6500 }); } catch (e) {}
7024
  await h.snap();
7025
 
7026
- // On JioMart, if pressing Enter in the Algolia input didn't navigate to the search results grid yet,
7027
- // click the first autocomplete suggestion or navigate to JioMart's search URL
7028
  if (plat.id === 'jiomart' && pg.url() === beforeUrl) {
7029
  var jmClicked = await pg.evaluate(function () {
7030
  var sug = document.querySelector('.aa-Item a, .aa-Item, .autocomplete-list li, [class*="search" i] button[type="submit"]');
7031
  if (sug) { sug.click(); return true; }
7032
  return false;
7033
- }).catch(() => false);
7034
- if (jmClicked) await h.sleep(1200);
7035
  }
7036
 
7037
  var cards = await shopCollectCards(h, 2);
@@ -7039,9 +7091,9 @@ async function shopSearchAndCollect(h, plat, item) {
7039
  }
7040
  var url = typeof plat.searchUrlTpl === 'function' ? plat.searchUrlTpl(item) : '';
7041
  if (url) {
7042
- h.log('↪️ Opening ' + plat.name + ' search results for "' + item + '"');
7043
  try { await h.goto(url); } catch (e) {}
7044
- await h.sleep(1300);
7045
  await shopDismissPopups(h);
7046
  await h.snap();
7047
  return await shopCollectCards(h, 2);
@@ -7049,273 +7101,184 @@ async function shopSearchAndCollect(h, plat, item) {
7049
  return [];
7050
  }
7051
 
7052
- // Step 4/5: Select the best card, move AI cursor & click it, read real numbers, take screenshot
 
7053
  async function shopOpenBestAndCapture(h, best, plat, pin) {
7054
  var res = { navigated: false, pdp: null, shot: null, url: '' };
7055
  var pg = h.getPage(), before = pg.url(), beforePage = pg;
7056
  var pt = null;
7057
  try { pt = await pg.evaluate(SHOP_HIGHLIGHT_IN_PAGE, best.idx); } catch (e) {}
7058
- await h.sleep(450); await h.snap();
 
 
 
7059
  if (pt) {
7060
- h.log('👆 Clicking selected product on ' + plat.name + ': "' + String(best.title).slice(0, 50) + '"');
7061
  await h.clickAt(pt.x, pt.y);
7062
- await h.sleep(1300);
7063
  }
 
7064
  var p2 = h.getPage();
7065
- if (p2 === beforePage && p2.url() === before && best.href && /^https?:\/\//i.test(best.href)) {
7066
- try { await h.goto(best.href); } catch (e) {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7067
  p2 = h.getPage();
7068
  }
7069
- await h.sleep(500);
7070
- try { await p2.waitForLoadState('domcontentloaded', { timeout: 6000 }); } catch (e) {}
7071
- await h.sleep(700);
7072
- try { await p2.waitForFunction(function () { return /(?:₹|Rs\.?)\s*\d/.test((document.body && document.body.innerText) || ''); }, null, { timeout: 3500 }); } catch (e) {}
7073
- res.navigated = (p2 !== beforePage) || p2.url() !== before;
7074
- res.url = p2.url();
7075
- if (res.navigated) {
7076
- try { await p2.evaluate(function () { window.scrollTo(0, 0); }); } catch (e) {}
7077
- try { res.pdp = await p2.evaluate(SHOP_READ_PDP_IN_PAGE, { pin: String(pin) }); } catch (e) { res.pdp = null; }
7078
  }
7079
- res.shot = await h.shot({ clipTop: res.navigated });
7080
- await h.snap();
7081
- return res;
7082
- }
7083
 
7084
- // Safety fallback for Blinkit (or any store whose Cloudflare/WAF blocks Hugging Face datacenter IPs):
7085
- // Queries live web search for the store's product listing, renders an interactive store view in the live browser tab,
7086
- // moves the AI cursor to click the product card, and captures a real live screenshot so Blinkit never errors out!
7087
- async function shopFallbackRenderStoreInBrowser(h, plat, item, pin, maxPrice) {
7088
  try {
7089
- h.log('🛡️ ' + plat.name + ': activating live catalog safety fallback for "' + item + '"...');
7090
- var cleanQ = typeof toCleanStoreSearchQuery === 'function' ? toCleanStoreSearchQuery(item, false) : String(item || 'Sugar 1kg');
7091
- var searchUrl = typeof plat.searchUrlTpl === 'function' ? plat.searchUrlTpl(cleanQ) : shopHomeUrl(plat);
7092
- var liveTitle = '', livePrice = null, liveMrp = null, liveRating = 4.6, liveReviews = 1420, liveHref = searchUrl;
 
 
 
 
 
 
 
 
 
7093
 
7094
- // 1. Try quick live search for real store price/title
7095
- if (typeof performFreeLiveSearch === 'function') {
 
 
 
 
 
 
 
 
 
 
 
 
7096
  try {
7097
- await Promise.race([
7098
- performFreeLiveSearch('site:' + plat.domain + ' ' + cleanQ + ' price India'),
7099
- new Promise(function (r) { setTimeout(r, 4500); })
7100
- ]);
7101
- var lRes = Array.isArray(performFreeLiveSearch.lastResults) ? performFreeLiveSearch.lastResults : [];
7102
- for (var i = 0; i < lRes.length; i++) {
7103
- var r = lRes[i];
7104
- if (!r) continue;
7105
- var combined = (r.title || '') + ' ' + (r.snippet || '');
7106
- var pm = combined.match(/(?:₹|Rs\.?|INR)\s*([0-9]{2,5})/);
7107
- if (pm) {
7108
- var pv = parseInt(pm[1], 10);
7109
- if (pv >= 15 && pv <= (maxPrice || 100000)) {
7110
- livePrice = pv;
7111
- liveTitle = String(r.title || '').replace(/\s*[-|].*$/, '').trim();
7112
- if (r.url && r.url.indexOf(plat.domain) >= 0) liveHref = r.url;
7113
- break;
7114
- }
7115
- }
7116
  }
7117
  } catch (e) {}
7118
  }
7119
-
7120
- // 2. Smart realistic India grocery/product catalog defaults if live snippet didn't include ₹ symbol
7121
- var lowQ = cleanQ.toLowerCase();
7122
- var storeOffsets = { flipkart: -2, blinkit: 2, jiomart: -1, amazon: 1, citymall: -3, meesho: -2, bigbasket: 0 };
7123
- var off = storeOffsets[plat.id] || 0;
7124
- if (!livePrice) {
7125
- if (/sugar|cheeni|shakkar/i.test(lowQ)) {
7126
- liveTitle = plat.id === 'jiomart' ? 'Madhur Pure & Hygienic Sugar 1 kg' : (plat.id === 'blinkit' ? 'Uttam Refined Sulphurless Sugar 1 kg' : 'Parrys / Madhur Pure Sugar 1 kg');
7127
- livePrice = Math.max(42, 48 + off); liveMrp = 60;
7128
- } else if (/atta|flour/i.test(lowQ)) {
7129
- liveTitle = 'Aashirvaad Shudh Chakki Atta 5 kg';
7130
- livePrice = Math.max(215, 242 + off * 3); liveMrp = 285;
7131
- } else if (/mustard\s*oil|sarson/i.test(lowQ)) {
7132
- liveTitle = 'Fortune Premium Kachi Ghani Pure Mustard Oil 1 L';
7133
- livePrice = Math.max(145, 162 + off * 2); liveMrp = 195;
7134
- } else if (/oil/i.test(lowQ)) {
7135
- liveTitle = 'Fortune Sunlite Refined Sunflower Oil 1 L';
7136
- livePrice = Math.max(130, 145 + off * 2); liveMrp = 175;
7137
- } else if (/rice|chawal|basmati/i.test(lowQ)) {
7138
- liveTitle = 'India Gate Feast Rozzana Basmati Rice 5 kg';
7139
- livePrice = Math.max(380, 425 + off * 5); liveMrp = 540;
7140
- } else if (/dal|daal|toor|arhar/i.test(lowQ)) {
7141
- liveTitle = 'Tata Sampann Unpolished Toor Dal 1 kg';
7142
- livePrice = Math.max(145, 168 + off * 2); liveMrp = 210;
7143
- } else if (/salt|namak/i.test(lowQ)) {
7144
- liveTitle = 'Tata Salt Vacuum Evaporated Iodised Salt 1 kg';
7145
- livePrice = Math.max(24, 27 + (off > 0 ? 1 : 0)); liveMrp = 30;
7146
- } else if (/tea|chai/i.test(lowQ)) {
7147
- liveTitle = 'Tata Tea Gold Assam Teas with Gently Rolled Long Leaves 500 g';
7148
- livePrice = Math.max(240, 265 + off * 3); liveMrp = 310;
7149
- } else if (/ghee/i.test(lowQ)) {
7150
- liveTitle = 'Amul Pure Cow Ghee 1 L Pouch';
7151
- livePrice = Math.max(560, 595 + off * 4); liveMrp = 650;
7152
- } else if (/milk|doodh/i.test(lowQ)) {
7153
- liveTitle = 'Amul Taaza Homogenised Toned Milk 1 L';
7154
- livePrice = Math.max(68, 72 + off); liveMrp = 76;
7155
- } else if (/maggi|noodle/i.test(lowQ)) {
7156
- liveTitle = 'Maggi 2-Minute Masala Instant Noodles 560 g (8 Pack)';
7157
- livePrice = Math.max(98, 108 + off); liveMrp = 120;
7158
- } else if (/biscuit/i.test(lowQ)) {
7159
- liveTitle = 'Britannia Good Day Cashew Cookies 600 g';
7160
- livePrice = Math.max(95, 110 + off * 2); liveMrp = 150;
7161
- } else {
7162
- liveTitle = cleanQ + ' (Best Value Pack)';
7163
- livePrice = maxPrice ? Math.max(25, Math.round(maxPrice * 0.78) + off) : (99 + off * 2);
7164
- liveMrp = Math.round(livePrice * 1.22);
7165
- }
7166
- }
7167
- if (maxPrice && livePrice > maxPrice) {
7168
- livePrice = Math.max(20, maxPrice - Math.abs(off) - 2);
7169
- }
7170
- if (!liveMrp || liveMrp <= livePrice) liveMrp = Math.round(livePrice * 1.2);
7171
- var discPct = Math.round((liveMrp - livePrice) / liveMrp * 100);
7172
- var discInr = Math.round(liveMrp - livePrice);
7173
- var imgUrl = typeof buildProductImageFallbackUrl === 'function' ? buildProductImageFallbackUrl(liveTitle, cleanQ) : ('https://tse1.mm.bing.net/th?q=' + encodeURIComponent(liveTitle + ' product pack india') + '&w=360&h=360&c=7&rs=1&p=0');
7174
- var etaStr = plat.id === 'blinkit' ? '11 mins' : (plat.id === 'jiomart' ? '25 mins' : 'Tomorrow');
7175
-
7176
- var pg = h.getPage();
7177
- await pg.evaluate(function (cfg) {
7178
- document.title = cfg.platName + ' — ' + cfg.title + ' (Delivery to ' + cfg.pin + ')';
7179
- document.body.style.cssText = 'margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;background:#f8fafc;color:#0f172a;';
7180
- document.body.innerHTML =
7181
- '<div style="background:' + cfg.color + ';color:#fff;padding:14px 24px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 2px 10px rgba(0,0,0,0.1);">' +
7182
- '<div style="display:flex;align-items:center;gap:12px;">' +
7183
- '<span style="font-size:24px;">' + cfg.icon + '</span>' +
7184
- '<span style="font-size:20px;font-weight:900;letter-spacing:-0.3px;">' + cfg.platName + '</span>' +
7185
- '<span style="background:rgba(255,255,255,0.22);padding:4px 10px;border-radius:999px;font-size:12px;font-weight:700;">📍 Delivering to Patna, Bihar ' + cfg.pin + '</span>' +
7186
- '</div>' +
7187
- '<div style="background:#fff;color:#0f172a;padding:7px 16px;border-radius:8px;min-width:320px;font-size:13px;font-weight:600;">🔎 ' + cfg.query + '</div>' +
7188
- '</div>' +
7189
- '<div style="max-width:1080px;margin:22px auto;padding:0 20px;">' +
7190
- '<div style="font-size:13px;color:#475569;font-weight:700;margin-bottom:14px;">Showing verified results for <b>"' + cfg.query + '"</b> in <b>Patna (' + cfg.pin + ')</b></div>' +
7191
- '<div style="display:grid;grid-template-columns:repeat(3, 1fr);gap:18px;">' +
7192
- '<div id="fallback-best-card" data-shop-card="0" style="background:#fff;border:3px solid #10b981;border-radius:16px;padding:18px;box-shadow:0 12px 30px rgba(16,185,129,0.18);position:relative;cursor:pointer;">' +
7193
- '<div style="position:absolute;top:12px;left:12px;background:#16a34a;color:#fff;font-size:11px;font-weight:800;padding:3px 9px;border-radius:6px;">' + cfg.discPct + '% OFF · BEST MATCH</div>' +
7194
- '<div style="height:190px;display:flex;align-items:center;justify-content:center;margin:18px 0 12px;">' +
7195
- '<img src="' + cfg.imgUrl + '" alt="' + cfg.title + '" style="max-height:175px;max-width:100%;object-fit:contain;border-radius:10px;" />' +
7196
- '</div>' +
7197
- '<div style="font-size:11px;font-weight:800;color:#059669;margin-bottom:4px;">⚡ ' + cfg.eta + ' delivery · In Stock</div>' +
7198
- '<div style="font-size:15px;font-weight:800;color:#0f172a;line-height:1.35;margin-bottom:8px;">' + cfg.title + '</div>' +
7199
- '<div style="display:flex;align-items:baseline;gap:8px;margin-bottom:8px;">' +
7200
- '<span style="font-size:22px;font-weight:900;color:#0f172a;">₹' + cfg.price + '</span>' +
7201
- '<span style="font-size:14px;color:#64748b;text-decoration:line-through;">₹' + cfg.mrp + '</span>' +
7202
- '<span style="font-size:12px;font-weight:800;color:#16a34a;">Save ₹' + cfg.discInr + '</span>' +
7203
- '</div>' +
7204
- '<div style="font-size:12px;font-weight:800;color:#d97706;margin-bottom:12px;">⭐ ' + cfg.rating + ' (' + cfg.reviews + ' ratings)</div>' +
7205
- '<button id="fallback-add-btn" style="width:100%;background:#10b981;color:#fff;border:none;padding:10px 14px;border-radius:10px;font-size:13px;font-weight:800;cursor:pointer;">🛒 Added to Cart</button>' +
7206
- '</div>' +
7207
- '</div>' +
7208
- '</div>';
7209
- }, {
7210
- platName: plat.name,
7211
- color: plat.color || '#0f172a',
7212
- icon: plat.icon || '🛍️',
7213
- pin: String(pin),
7214
- query: cleanQ,
7215
- title: liveTitle,
7216
- price: livePrice,
7217
- mrp: liveMrp,
7218
- discPct: discPct,
7219
- discInr: discInr,
7220
- rating: liveRating.toFixed(1),
7221
- reviews: liveReviews,
7222
- eta: etaStr,
7223
- imgUrl: imgUrl
7224
- });
7225
-
7226
- await h.sleep(600);
7227
- await h.snap();
7228
- await h.clickAt(240, 340);
7229
- await h.sleep(450);
7230
- var shotData = await h.shot({ clipTop: true });
7231
- await h.snap();
7232
-
7233
- return {
7234
- platformId: plat.id,
7235
- platformName: plat.name,
7236
- item: item,
7237
- verified: true,
7238
- reason: '',
7239
- locationApplied: true,
7240
- locationHow: 'Patna, Bihar (' + pin + ')',
7241
- candidates: 1,
7242
- title: liveTitle,
7243
- priceInr: livePrice,
7244
- mrpInr: liveMrp,
7245
- discountPct: discPct,
7246
- discountInr: discInr,
7247
- rating: liveRating.toFixed(1) + ' ★',
7248
- reviewsCount: liveReviews,
7249
- eta: etaStr,
7250
- directProductUrl: liveHref || searchUrl,
7251
- snappedImage: shotData || imgUrl,
7252
- navigated: true,
7253
- addedToVirtualCart: true,
7254
- overBudget: false,
7255
- matchTier: 'exact'
7256
- };
7257
- } catch (fbErr) {
7258
- return null;
7259
  }
 
 
7260
  }
7261
 
7262
- // One store, one item. Never fails with Google IP errors, Flipkart false malfunctions, JioMart Ctrl+A text selection, or Blinkit blocks!
7263
  async function shopRunStore(h, plat, item, pin, maxPrice, deadlineAt) {
7264
  var out = { platformId: plat.id, platformName: plat.name, item: item, verified: false, reason: '', locationApplied: false, locationHow: '', candidates: 0 };
7265
- h.pincode = pin;
7266
  function tick(what) { if (Date.now() > deadlineAt) throw new Error('time limit reached while ' + what); if (h.cancelled && h.cancelled()) throw new Error('cancelled by a newer browser request'); }
7267
  try {
7268
  tick('opening ' + plat.name);
7269
- h.progress('🌐 ' + plat.name + ': opening ' + plat.name + ' directly (Patna ' + pin + ')…');
7270
- await shopOpenStoreDirect(h, plat);
7271
- await h.sleep(700);
 
 
 
 
 
 
7272
  await shopDismissPopups(h);
7273
- await h.snap();
7274
 
7275
- tick('setting location');
7276
- h.progress('📍 ' + plat.name + ': applying delivery pincode ' + pin + '…');
7277
  var loc = await shopSetLocation(h, plat, pin);
7278
  out.locationApplied = !!loc.ok; out.locationHow = loc.how || '';
7279
- h.log('✅ ' + plat.name + ' location ready (' + (loc.how || pin) + ')');
7280
  await shopDismissPopups(h);
7281
 
7282
  tick('searching');
7283
- h.progress('🔎 ' + plat.name + ': clicking search & looking up "' + item + '"…');
7284
  var cards = await shopSearchAndCollect(h, plat, item);
7285
  if (!cards.length) {
7286
- var directSearchUrl = typeof plat.searchUrlTpl === 'function' ? plat.searchUrlTpl(item) : '';
7287
- if (directSearchUrl) {
7288
- h.log('↻ Loading ' + plat.name + ' direct search page for "' + item + '"');
7289
- try { await h.goto(directSearchUrl); } catch (e) {}
7290
- await h.sleep(1400);
7291
- await shopDismissPopups(h);
7292
- cards = await shopCollectCards(h, 2);
7293
- }
7294
  }
7295
  out.candidates = cards.length;
7296
-
7297
- // If store (e.g. Blinkit / CityMall / WAF) blocked headless Chromium on Hugging Face IP, use live store fallback!
7298
  if (!cards.length) {
7299
- var fb = await shopFallbackRenderStoreInBrowser(h, plat, item, pin, maxPrice);
7300
- if (fb && fb.verified) return fb;
7301
- out.reason = 'no priced products appeared on ' + plat.name;
7302
- out.shot = await h.shot({});
7303
- return out;
7304
  }
7305
-
7306
- tick('choosing best product');
7307
  var pick = shopPickBestProduct(cards, item, maxPrice);
7308
- if (!pick.best) {
7309
- var fb2 = await shopFallbackRenderStoreInBrowser(h, plat, item, pin, maxPrice);
7310
- if (fb2 && fb2.verified) return fb2;
7311
- out.reason = pick.reason; out.shot = await h.shot({}); return out;
7312
- }
7313
  var best = pick.best;
7314
- h.progress('✅ ' + plat.name + ': selected "' + String(best.title).slice(0, 42) + '" ₹' + best.price);
7315
 
7316
- tick('clicking product');
7317
  var cap = await shopOpenBestAndCapture(h, best, plat, pin);
7318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7319
  var title = best.title, price = best.price, mrp = best.mrp, discountPct = best.discountPct, discountInr = best.discountInr;
7320
  var rating = best.rating, reviews = best.reviews, eta = best.eta;
7321
  if (cap.pdp && cap.navigated) {
@@ -7333,6 +7296,7 @@ async function shopRunStore(h, plat, item, pin, maxPrice, deadlineAt) {
7333
  if (d.rating && !rating) rating = d.rating;
7334
  if (d.ratingCount && !reviews) reviews = d.ratingCount;
7335
  if (d.eta && !eta) eta = d.eta;
 
7336
  }
7337
  if (mrp && mrp > price) { discountInr = Math.round(mrp - price); if (!discountPct) discountPct = Math.round(discountInr / mrp * 100); }
7338
  else { mrp = mrp && mrp > price ? mrp : null; }
@@ -7344,15 +7308,13 @@ async function shopRunStore(h, plat, item, pin, maxPrice, deadlineAt) {
7344
  out.rating = rating ? (rating.toFixed(1) + ' ★') : null; out.reviewsCount = reviews || null; out.eta = eta || '';
7345
  out.directProductUrl = productUrl; out.snappedImage = cap.shot; out.navigated = cap.navigated;
7346
  out.overBudget = !!pick.overBudget; out.matchTier = pick.tier; out.mrpDerived = !!(best.mrpDerived && !(cap.pdp && cap.pdp.mrp));
7347
- if (maxPrice && pick.overBudget) out.note = 'nothing relevant was under ₹' + maxPrice + ' - this is the cheapest match';
7348
  if (cap.navigated && h.addToCart !== false) {
7349
  var add = await shopFind(h, 'addBtn');
7350
- if (add) { await h.clickAt(add.x, add.y); out.addedToVirtualCart = true; await h.sleep(600); await h.snap(); }
7351
  }
7352
  return out;
7353
  } catch (e) {
7354
- var fbCatch = await shopFallbackRenderStoreInBrowser(h, plat, item, pin, maxPrice);
7355
- if (fbCatch && fbCatch.verified) return fbCatch;
7356
  out.reason = 'stopped: ' + String((e && e.message) || e).split('\n')[0];
7357
  try { out.shot = await h.shot({}); } catch (x) {}
7358
  return out;
@@ -8789,8 +8751,8 @@ const SHOPPING_PLATFORMS_CATALOG = [
8789
  color: "#0078ad",
8790
  badgeBg: "rgba(0, 120, 173, 0.14)",
8791
  icon: "🧺",
8792
- searchUrlTpl: (q) => `https://www.jiomart.com/catalogsearch/result?q=${encodeURIComponent(toCleanStoreSearchQuery(q, false))}`,
8793
- liveBrowserUrlTpl: (q) => `https://www.jiomart.com/catalogsearch/result?q=${encodeURIComponent(toCleanStoreSearchQuery(q, false))}`,
8794
  bypassUrlTpl: (q) => `https://www.google.com/search?q=site:jiomart.com+${encodeURIComponent(toCleanStoreSearchQuery(q, false))}&gl=in`,
8795
  cartUrl: "https://www.jiomart.com/checkout/cart"
8796
  },
 
6334
  // ==========================================================================================
6335
  // ===== SHOP-CORE BEGIN =====================================================================
6336
  // Live shopping agent logic:
6337
+ // 1. Opens each store in the live browser
6338
+ // 2. Enters the user's delivery pincode (without Control+A text-selection bugs or Flipkart reload traps)
6339
+ // 3. Searches the product using the store's search bar
6340
+ // 4. Extracts real in-stock product cards (supporting both grid cards and full-width horizontal phone/electronics rows)
6341
+ // 5. Filters out phone cases/screen guards when searching for a phone/device, scores & selects the best product
6342
+ // 6. Clicks the product card's title/image link to open the real Product Detail Page (PDP), verifies the PDP opened, and ONLY takes the screenshot on the opened Product Detail Page (NEVER snaps on the search results page!)
6343
+ // Nothing in here invents data: if something could not be read from the page it stays null.
6344
  const SHOP_MAX_ITEMS = 3;
6345
+ const SHOP_PER_STORE_MS = parseInt(process.env.SHOP_PER_STORE_MS) || 70000;
6346
+ const SHOP_TOTAL_BUDGET_MS = parseInt(process.env.SHOP_TOTAL_BUDGET_MS) || 200000;
6347
  const SHOP_HOME_URLS = {
6348
  flipkart: 'https://www.flipkart.com/', blinkit: 'https://blinkit.com/', jiomart: 'https://www.jiomart.com/',
6349
  amazon: 'https://www.amazon.in/', citymall: 'https://citymall.live/', meesho: 'https://www.meesho.com/',
 
6368
  toks.forEach(function (t) {
6369
  if (/^\d+(?:\.\d+)?(?:kg|g|l|ml)$/.test(t)) sizes.push(t);
6370
  else if (/^[\d.]+$/.test(t)) { /* bare number: ignore */ }
6371
+ else if (t.length >= 2 && !SHOP_STOP.has(t)) words.push(t);
6372
  });
6373
  return { words: words, sizes: sizes };
6374
  }
6375
 
6376
+ // Score every product card and choose the best-value *relevant* one. Pure function.
6377
  function shopPickBestProduct(cards, query, maxPrice) {
6378
  var qt = shopQueryTokens(query);
6379
+ var qLow = String(query || '').toLowerCase();
6380
+ var wantsAccessory = /\b(cover|case|glass|tempered|protector|guard|charger|cable|adapter|pouch|skin|stand|holder|strap)\b/i.test(qLow);
6381
+ var usable = (cards || []).filter(function (c) {
6382
+ if (!c || !(c.price > 0) || c.outOfStock) return false;
6383
+ // If user is searching for a phone/laptop/tablet (not a cover/glass), never pick a ₹150 back cover or tempered glass!
6384
+ if (!wantsAccessory && /\b(back\s*cover|flip\s*cover|case\s*for|cover\s*for|tempered\s*glass|screen\s*guard|screen\s*protector|camera\s*lens\s*protector|hydrogel\s*film|silicon[e]?\s*case|bumper\s*case|mobile\s*skin)\b/i.test(c.title || '')) {
6385
+ return false;
6386
+ }
6387
+ return true;
6388
+ });
6389
+ if (!usable.length) usable = (cards || []).filter(function (c) { return c && c.price > 0 && !c.outOfStock; });
6390
+
6391
  var rows = usable.map(function (c) {
6392
  var titleN = shopNormUnits(c.title || '');
6393
  var hayN = shopNormUnits((c.title || '') + ' ' + (c.text || ''));
 
6398
  return { c: c, rel: rel, sizeOk: sizeOk };
6399
  });
6400
  var tier = rows.filter(function (r) { return r.rel >= 0.99 && r.sizeOk !== false; }), tierName = 'exact';
6401
+ if (!tier.length) { tier = rows.filter(function (r) { return r.rel >= 0.6 && r.sizeOk !== false; }); tierName = 'close'; }
6402
+ if (!tier.length) { tier = rows.filter(function (r) { return r.rel >= 0.5; }); tierName = 'size-differs'; }
 
6403
  if (!tier.length) {
6404
  return { best: null, ranked: [], overBudget: false, tier: 'none',
6405
  reason: rows.length ? ('none of the ' + rows.length + ' products on the results page matched "' + query + '"') : 'no in-stock priced products found on the results page' };
 
6420
  if (c.sponsored) s -= 12;
6421
  r.score = s;
6422
  });
6423
+ if (overBudget) tier.sort(function (a, b) { return a.c.price - b.c.price; }); // nothing fits the budget -> show the cheapest relevant one
6424
  else tier.sort(function (a, b) { return b.score - a.score; });
6425
  return {
6426
  best: tier[0].c, overBudget: overBudget, tier: tierName,
6427
+ ranked: tier.slice(0, 6).map(function (r) { return { idx: r.c.idx, title: r.c.title, price: r.c.price, href: r.c.href, score: Math.round(r.score * 10) / 10, card: r.c }; })
6428
  };
6429
  }
6430
 
 
6434
  var HAS_PRICE = /(?:₹|Rs\.?|INR)\s*\d/;
6435
  var PRICE_G = /(?:₹|Rs\.?|INR)\s*([0-9][0-9,]*(?:\.[0-9]{1,2})?)/g;
6436
  function vis(el) {
6437
+ if (!el) return false;
6438
  var r = el.getBoundingClientRect(); if (r.width < 2 || r.height < 2) return false;
6439
  var cs = getComputedStyle(el); return cs.visibility !== 'hidden' && cs.display !== 'none' && cs.opacity !== '0';
6440
  }
6441
  function struck(el, stopEl) {
6442
  for (var e = el; e && e !== document.body; e = e.parentElement) {
6443
  var tg = e.tagName; if (tg === 'DEL' || tg === 'S' || tg === 'STRIKE') return true;
6444
+ var cl = (e.className && typeof e.className === 'string') ? e.className : '';
6445
+ if (/\ba-text-price\b/.test(cl) && e.getAttribute('data-a-strike') === 'true') return true;
6446
  var td = getComputedStyle(e).textDecorationLine || ''; if (td.indexOf('line-through') >= 0) return true;
6447
  if (e === stopEl) break;
6448
  }
 
6458
  var v = parseFloat(m[1]); if (isNaN(v)) return null; var u = m[2].toLowerCase(); return Math.round(u === 'k' ? v * 1000 : u === 'm' ? v * 1e6 : v);
6459
  }
6460
  function isJunk(l) {
6461
+ if (l.length < 4 || l.length > 180) return true;
6462
  if (HAS_PRICE.test(l)) return true;
6463
  if (/^\(?[\d.,]+\s*[kKmM]?\)?$/.test(l)) return true;
6464
  if (/^[★⭐\d.\s()\/*]+$/.test(l)) return true;
6465
  if (/%\s*off|^save\b|\boff$/i.test(l)) return true;
6466
+ if (/^(sponsored|ad\b|add\b|buy\b|notify|out of stock|sold out|bestseller|best seller|new\b|free delivery|get it|prime|limited time|deal\b|only \d+ left|options?\b|view\b|wishlist|compare|\d+\s*options?)/i.test(l)) return true;
6467
  if (/\b\d+\s*(?:mins?|minutes)\b/i.test(l) && l.length < 22) return true;
6468
  return false;
6469
  }
6470
 
6471
  Array.prototype.forEach.call(document.querySelectorAll('[data-shop-card]'), function (e) { e.removeAttribute('data-shop-card'); });
6472
+
6473
  var all = document.body ? document.body.getElementsByTagName('*') : [];
6474
  var priceEls = [];
6475
  for (var i = 0; i < all.length; i++) {
6476
  var el = all[i], tg = el.tagName;
6477
  if (tg === 'SCRIPT' || tg === 'STYLE' || tg === 'NOSCRIPT' || tg === 'svg' || tg === 'path') continue;
6478
+ var isAmzPrice = el.classList && (el.classList.contains('a-price') || el.classList.contains('a-text-price'));
6479
+ if (!isAmzPrice && el.childElementCount > 4) continue;
6480
+ var t = (el.textContent || '').replace(/\s+/g, ' ').trim();
6481
+ if (!t || t.length > 75 || !HAS_PRICE.test(t)) continue;
6482
+ if (!isAmzPrice) {
6483
+ var childHas = false;
6484
+ for (var k = 0; k < el.children.length; k++) {
6485
+ var ch = el.children[k];
6486
+ if (HAS_PRICE.test(ch.textContent || '') && vis(ch)) { childHas = true; break; }
6487
+ }
6488
+ if (childHas) continue;
6489
+ }
6490
  if (!vis(el)) continue;
6491
  priceEls.push(el);
6492
  }
6493
+
6494
  var cardMap = new Map();
6495
  priceEls.forEach(function (pe) {
6496
+ var explicitCard = pe.closest('[data-component-type="s-search-result"], [data-id], li.ais-InfiniteHits-item, .plp-card-container, [data-testid*="product-card" i]');
6497
+ var found = null;
6498
+ if (explicitCard && vis(explicitCard)) {
6499
+ var er = explicitCard.getBoundingClientRect();
6500
+ if (er.width >= 95 && er.height >= 85 && er.width <= vw * 0.95 && er.height <= 900) {
6501
+ found = explicitCard;
6502
+ }
6503
+ }
6504
+ if (!found) {
6505
+ var c = pe;
6506
+ for (var d = 0; d < 10 && c.parentElement && c.parentElement !== document.body; d++) {
6507
+ c = c.parentElement;
6508
+ var r = c.getBoundingClientRect();
6509
+ if (r.width > vw * 0.90 || r.height > 820) break;
6510
+ var np = (c.textContent.match(PRICE_G) || []).length;
6511
+ if (np > 9) break;
6512
+ var hasImg = !!c.querySelector('img, picture, [style*="background-image"]');
6513
+ var clickable = c.tagName === 'A' || !!c.querySelector('a[href], button, [role="button"], [tabindex]') || !!c.closest('a[href]') || getComputedStyle(c).cursor === 'pointer';
6514
+ if (hasImg && clickable && r.width >= 95 && r.height >= 85) { found = c; break; }
6515
+ }
6516
  }
6517
  if (!found) return;
6518
  if (!cardMap.has(found)) cardMap.set(found, []);
6519
  cardMap.get(found).push(pe);
6520
  });
6521
+
6522
  var cards = Array.from(cardMap.keys());
6523
  cards.sort(function (a, b) { var ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect(); return (ra.top - rb.top) || (ra.left - rb.left); });
6524
+ cards = cards.slice(0, maxCards || 28);
6525
 
6526
  var out = [];
6527
  cards.forEach(function (card, idx) {
 
6531
  var cands = [];
6532
  pes.forEach(function (pe) {
6533
  var pt = (pe.textContent || '').replace(/\s+/g, ' ').trim();
6534
+ if (/\/\s*(?:100\s*)?(?:g|gm|kg|ml|l|ltr|unit|pc|piece|mo|month)\b|per\s*(?:100|kg|g|ml|l|unit|piece|month)|\bemi\b|cashback|coupon|\bfees?\b|delivery|minimum|\bextra\b|\boff\b|\bsave\b|\bexchange\b|\bup\s*to\b|^\(/i.test(pt)) return;
6535
  var ns = nums(pt); if (!ns.length) return;
6536
  cands.push({ v: ns[0], second: ns.length > 1 ? ns[1] : null, fs: parseFloat(getComputedStyle(pe).fontSize) || 0, st: struck(pe, card) });
6537
  });
 
6571
  if (!m && rating !== null) m = text.match(/\(\s*([\d,.]+\s*[kKmM]?)\s*\)/);
6572
  if (m) reviews = toCount(m[1]);
6573
 
6574
+ var headingEl = card.querySelector('h2 a span, h2 span, h2, h3, .KzDlHZ, .wjcEIp, ._4rR01T, .s1Q9rs, .plp-card-details-name');
6575
+ var headingTxt = headingEl ? (headingEl.innerText || headingEl.textContent || '').replace(/\s+/g, ' ').trim() : '';
6576
+
6577
  var alt = '';
6578
  Array.prototype.forEach.call(card.querySelectorAll('img'), function (im) {
6579
  var a = (im.getAttribute('alt') || '').trim();
6580
+ if (a.length > alt.length && /[A-Za-z]{3}/.test(a) && !/^(product|image|photo|logo|banner|thumbnail|sponsored)/i.test(a)) alt = a;
6581
  });
6582
  var cand = '';
6583
  for (var j = 0; j < lines.length; j++) { if (!isJunk(lines[j]) && /[A-Za-z]{3}/.test(lines[j])) { cand = lines[j]; break; } }
6584
+ var title = (headingTxt && headingTxt.length >= 6 && !isJunk(headingTxt)) ? headingTxt : ((alt && alt.length >= 8) ? alt : cand);
6585
  if (alt && cand && cand.length > alt.length + 5 && cand.toLowerCase().indexOf(alt.toLowerCase()) >= 0) title = cand;
6586
+ if (!title) title = cand || alt || headingTxt;
6587
 
6588
  var a = null;
6589
  if (card.tagName === 'A' && card.href) a = card;
6590
+ else a = card.querySelector('a[href*="/dp/"], a[href*="%2Fdp%2F"], a[href*="/gp/product/"], a[href*="/p/"], a[href*="/prn/"], a[href*="/prid/"], a[href*="/pd/"], a[href*="/pn/"], a[href*="/product"], h2 a[href], a.a-link-normal[href]') || card.querySelector('a[href]') || card.closest('a[href]');
6591
  var href = (a && a.href) ? a.href.split('#')[0] : '';
6592
  if (/^javascript:/i.test(href)) href = '';
6593
+ // If Amazon ASIN data-asin attribute exists on card and href is missing, construct direct /dp/ URL
6594
+ var asin = card.getAttribute('data-asin');
6595
+ if (!href && asin && /^[A-Z0-9]{10}$/.test(asin)) {
6596
+ href = location.origin + '/dp/' + asin;
6597
+ }
6598
+
6599
+ if (card.tagName === 'A') card.removeAttribute('target');
6600
+ var parentLink = card.closest('a[target]');
6601
+ if (parentLink) parentLink.removeAttribute('target');
6602
+ Array.prototype.forEach.call(card.querySelectorAll('a[target]'), function (al) { al.removeAttribute('target'); });
6603
 
6604
  var etaM = text.match(/\b(\d{1,2})\s*(?:mins?|minutes)\b/i);
6605
  card.setAttribute('data-shop-card', String(idx));
 
6620
  var el = document.querySelector('[data-shop-card="' + idx + '"]');
6621
  if (!el) return null;
6622
  try { el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' }); } catch (e) { el.scrollIntoView(); }
 
6623
  if (el.tagName === 'A') el.removeAttribute('target');
6624
+ var parentA = el.closest('a');
6625
+ if (parentA) parentA.removeAttribute('target');
6626
  Array.prototype.forEach.call(el.querySelectorAll('a[target]'), function (a) { a.removeAttribute('target'); });
6627
+
6628
+ var linkEl = (el.tagName === 'A' ? el : null)
6629
+ || el.querySelector('h2 a[href], a[href*="/dp/"], a[href*="%2Fdp%2F"], a[href*="/p/"], a[href*="/prn/"], a[href*="/pd/"], a[href*="/product"]')
6630
+ || el.querySelector('a[href]')
6631
+ || parentA;
6632
+ var img = el.querySelector('img');
6633
+ var tgt = (img && img.getBoundingClientRect().width > 35 && img.getBoundingClientRect().height > 35) ? img : (linkEl || el);
6634
+ var r = tgt.getBoundingClientRect();
6635
+ var href = (linkEl && linkEl.href && /^https?:\/\//i.test(linkEl.href)) ? linkEl.href : '';
6636
+ var asin = el.getAttribute('data-asin');
6637
+ if (!href && asin && /^[A-Z0-9]{10}$/.test(asin)) {
6638
+ href = location.origin + '/dp/' + asin;
6639
+ }
6640
+ return {
6641
+ x: Math.round(r.left + r.width / 2),
6642
+ y: Math.round(r.top + Math.min(r.height / 2, 90)),
6643
+ href: href
6644
+ };
6645
  }
6646
 
6647
  function SHOP_READ_PDP_IN_PAGE(q) {
6648
+ Array.prototype.forEach.call(document.querySelectorAll('.ai-shop-hl'), function (e) { e.classList.remove('ai-shop-hl'); e.style.outline = ''; e.style.boxShadow = ''; });
6649
  var HAS_PRICE = /(?:₹|Rs\.?|INR)\s*\d/;
6650
  function vis(el) { var r = el.getBoundingClientRect(); if (r.width < 2 || r.height < 2) return false; var cs = getComputedStyle(el); return cs.visibility !== 'hidden' && cs.display !== 'none' && cs.opacity !== '0'; }
6651
  function struck(el) {
6652
  for (var e = el; e && e !== document.body; e = e.parentElement) {
6653
  var tg = e.tagName; if (tg === 'DEL' || tg === 'S' || tg === 'STRIKE') return true;
6654
+ var cl = (e.className && typeof e.className === 'string') ? e.className : '';
6655
+ if (/\ba-text-price\b/.test(cl) && e.getAttribute('data-a-strike') === 'true') return true;
6656
  if ((getComputedStyle(e).textDecorationLine || '').indexOf('line-through') >= 0) return true;
6657
  }
6658
  return false;
6659
  }
6660
  function numOf(t) { var m = t.match(/(?:₹|Rs\.?|INR)\s*([0-9][0-9,]*(?:\.[0-9]{1,2})?)/); return m ? parseFloat(m[1].replace(/,/g, '')) : null; }
6661
+ var h1 = document.querySelector('#productTitle, h1 span, h1');
6662
  var title = h1 ? (h1.innerText || '').trim() : '';
6663
  if (!title) { var og = document.querySelector('meta[property="og:title"]'); if (og) title = og.getAttribute('content') || ''; }
6664
  var cands = [], all = document.body.getElementsByTagName('*');
6665
  for (var i = 0; i < all.length; i++) {
6666
+ var el = all[i];
6667
+ var isAmzPrice = el.classList && (el.classList.contains('a-price') || el.classList.contains('a-text-price'));
6668
+ if (!isAmzPrice && el.childElementCount > 3) continue;
6669
  var t = (el.textContent || '').replace(/\s+/g, ' ').trim();
6670
+ if (!t || t.length > 45 || !HAS_PRICE.test(t)) continue;
6671
+ if (!isAmzPrice) {
6672
+ var childHas = false;
6673
+ for (var k = 0; k < el.children.length; k++) { if (HAS_PRICE.test(el.children[k].textContent || '') && vis(el.children[k])) { childHas = true; break; } }
6674
+ if (childHas) continue;
6675
+ }
6676
+ if (!vis(el)) continue;
6677
  var r = el.getBoundingClientRect(); if (r.top < 0 || r.top > 900) continue;
6678
+ if (/\/\s*(?:100\s*)?(?:g|gm|kg|ml|l|mo|month)\b|per\s*(?:100|kg|g|ml|l|unit|month)|\bemi\b|cashback|coupon|\bfees?\b|delivery|minimum|\boff\b|\bsave\b|\bextra\b|\bexchange\b|^get\s|^\(/i.test(t)) continue;
6679
  cands.push({ v: numOf(t), fs: parseFloat(getComputedStyle(el).fontSize) || 0, st: struck(el), top: r.top });
6680
  }
6681
  var sell = null;
 
6733
  list = Array.prototype.filter.call(document.querySelectorAll('input, [contenteditable="true"]'), function (el) {
6734
  if (!vis(el)) return false; var ty = (el.type || 'text').toLowerCase(); if (BAD_TYPES.indexOf(ty) >= 0) return false;
6735
  var s = attrs(el);
6736
+ if (/autocomplete-0-input|twotabsearchtextbox/.test(s)) return false;
6737
+ if (/search/.test(s) && !/locat|deliver|area|pin|city|address/.test(s)) return false;
6738
  return /pin\s*-?code|postal|zip|locat|locality|area|city|deliver|glux/.test(s);
6739
  });
6740
  list.sort(function (a, b) { return (inDialog(b) ? 1 : 0) - (inDialog(a) ? 1 : 0); });
6741
  return list.length ? box(list[0]) : null;
6742
  }
6743
  if (kind === 'locTrigger') {
 
6744
  if (/flipkart\.com/i.test(location.hostname) && !document.querySelector('input[placeholder*="pincode" i], input[placeholder*="pin code" i]')) {
6745
  return null;
6746
  }
 
6759
  }
6760
  if (kind === 'suggestion') {
6761
  var ib = arg.box; if (!ib) return null;
6762
+ var pool = document.querySelectorAll('li, [role="option"], [role="listitem"], [class*="LocationSearchList" i] div, [class*="address-container" i], div, span, a, p');
6763
  var best = null, bestScore = -1;
6764
  for (i = 0; i < pool.length; i++) {
6765
  e = pool[i]; if (e.childElementCount > 6 || !vis(e)) continue;
 
6769
  var t = label(e); if (t.length < 3 || t.length > 140) continue;
6770
  if (/^(apply|check|confirm|submit|update|continue|done|save|proceed|use current location|detect|locate me)/i.test(t)) continue;
6771
  var sc = 0; if (e.tagName === 'LI' || e.getAttribute('role') === 'option' || e.getAttribute('role') === 'listitem') sc += 3;
6772
+ if (arg.pin && t.indexOf(arg.pin) >= 0) sc += 2;
6773
+ if (/patna|bihar/i.test(t)) sc += 2;
6774
+ if (getComputedStyle(e).cursor === 'pointer') sc += 1;
6775
+ if (/suggest|result|address|locationsearch|option|list/i.test((e.className || '') + (e.parentElement && e.parentElement.className || ''))) sc += 2;
6776
  if (sc < 2) continue;
6777
  if (!best || sc > bestScore || (sc === bestScore && r.top < best.t)) { best = box(e, { text: t.slice(0, 60) }); bestScore = sc; }
6778
  }
 
6791
  return box(list[0], { label: label(list[0]).slice(0, 20) });
6792
  }
6793
  if (kind === 'searchInput') {
 
6794
  var prioritySelectors = [
6795
  'input#autocomplete-0-input',
6796
  'input.aa-Input',
 
6808
  var pel = pEls[j];
6809
  if (!vis(pel)) continue;
6810
  var ps = attrs(pel);
6811
+ if (/pin\s*code|pincode|glux|delivery\s*location|select-locality/.test(ps)) continue;
6812
  var pr = pel.getBoundingClientRect();
6813
  if (pr.top <= 340 && pr.width >= 60) return box(pel);
6814
  }
 
6823
  return list.length ? box(list[0]) : null;
6824
  }
6825
  if (kind === 'searchTrigger') {
6826
+ list = Array.prototype.filter.call(document.querySelectorAll('a[href*="/s/"], button, a, [role="button"], div, span, label'), function (el) {
6827
  if (!vis(el) || el.childElementCount > 6) return false; var r = el.getBoundingClientRect(); if (r.top > 220 || r.width < 40) return false;
6828
  var t = label(el) + ' ' + attrs(el);
6829
  return t.length <= 120 && (/^search\b|search\s+for|search\s+in\s+jiomart|search\s+products/i.test(label(el)) || /search.*trigger|search.*bar|search.*box|header.*search/i.test(attrs(el)));
 
6846
  return hit;
6847
  }
6848
  if (kind === 'popup') {
 
6849
  var fkClose = document.querySelector('button._2KpZ6l._2doB4z, span._30XB9F, [role="dialog"] button[aria-label*="close" i], [class*="modal" i] button[class*="close" i]');
6850
  if (fkClose && vis(fkClose)) return box(fkClose, { text: 'Close Modal' });
6851
  list = Array.prototype.filter.call(document.querySelectorAll('button, [role="button"], span[role="button"]'), function (el) {
 
6880
  }
6881
 
6882
  // Safely focus & clear an <input> via DOM without EVER pressing Control+A on document.body!
 
6883
  async function shopFocusAndClearInput(h, box, selectorHint) {
6884
  await h.clickAt(box.x, box.y);
6885
  await h.sleep(180);
 
6903
  if (!target) {
6904
  var hit = document.elementFromPoint(arg.x, arg.y);
6905
  if (isTextInputEl(hit)) target = hit;
6906
+ else if (hit) target = hit.querySelector('input, textarea') || (hit.closest('label, form, div') && hit.closest('label, form, div').querySelector('input, textarea'));
6907
  }
6908
  if (!target && isTextInputEl(document.activeElement)) {
6909
  target = document.activeElement;
 
6915
  if (rk.width > 40 && rk.height > 12 && rk.top >= 0 && rk.top < 450) { target = allInputs[k]; break; }
6916
  }
6917
  }
 
6918
  try { if (window.getSelection) window.getSelection().removeAllRanges(); } catch (e) {}
6919
  if (!target) return false;
6920
  try {
6921
  target.focus();
6922
  target.click();
6923
+ var desc = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value');
6924
+ var nativeInputValueSetter = desc && desc.set;
6925
  if (nativeInputValueSetter) nativeInputValueSetter.call(target, '');
6926
  else target.value = '';
6927
  target.dispatchEvent(new Event('input', { bubbles: true }));
6928
  } catch (e) {}
6929
  return true;
6930
+ }, { x: box.x, y: box.y, selectorHint: selectorHint || '' }).catch(function () { return false; });
6931
  return focusedOk;
6932
  }
6933
 
6934
+ // Tightened block detector
6935
  async function shopLooksBlocked(h) {
6936
  try {
6937
  var pg = h.getPage();
 
6939
  return await pg.evaluate(function () {
6940
  var url = String(location.href || '');
6941
  if (/\/sorry\/index|validateCaptcha/i.test(url)) return true;
 
6942
  var hasSearchOrPrices = !!document.querySelector('input[name="q"], input#twotabsearchtextbox, input#autocomplete-0-input, input.aa-Input, input[type="search"]')
6943
  || /(?:₹|Rs\.?)\s*\d/.test((document.body && document.body.innerText) || '');
6944
  if (hasSearchOrPrices) return false;
 
6954
  async function shopRecoverFromBlock(h, plat) {
6955
  for (var a = 1; a <= 2; a++) {
6956
  if (!(await shopLooksBlocked(h))) return true;
6957
+ h.log('⚠️ ' + plat.name + ' showed an error/blocked page (try ' + a + '/2) - recovering');
6958
  var link = await shopFind(h, 'homeLink');
6959
+ await h.sleep(2000 * a);
6960
+ if (link) { await h.clickAt(link.x, link.y); await h.sleep(1800); }
6961
+ else { try { await h.goto(shopHomeUrl(plat)); } catch (e) {} await h.sleep(1800); }
6962
  await h.snap();
6963
  }
6964
  return !(await shopLooksBlocked(h));
6965
  }
6966
 
6967
+ // Step 1: Open the store directly
6968
  async function shopOpenStoreDirect(h, plat) {
6969
  var home = shopHomeUrl(plat);
6970
  h.log('🌐 Opening ' + plat.name + ' (' + home + ')');
6971
  try {
6972
  await h.goto(home);
6973
  } catch (e) {
6974
+ return { ok: false, why: plat.name + ' did not load' };
6975
  }
6976
  await h.sleep(800);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6977
  await h.snap();
6978
  return { ok: true };
6979
  }
6980
 
6981
+ // Step 2: Enter the user's pincode on the store
6982
  async function shopSetLocation(h, plat, pin) {
6983
  pin = String(pin);
 
6984
  if (plat.id === 'flipkart') {
6985
  var fkLocInput = await shopFind(h, 'locInput');
6986
  if (!fkLocInput) {
6987
+ return { ok: false, how: 'Flipkart pincode box is on product page', pinSeenOnPage: false };
6988
  }
6989
  }
6990
  var found = await shopFind(h, 'locInput');
6991
  if (!found) {
6992
  var trig = await shopFind(h, 'locTrigger');
6993
  if (trig) {
6994
+ h.log('📍 Opening the location box ("' + (trig.text || '') + '")');
6995
  await h.clickAt(trig.x, trig.y);
6996
+ await h.sleep(1000);
6997
  try { await h.getPage().waitForLoadState('domcontentloaded', { timeout: 4000 }); } catch (e) {}
6998
  found = await shopFind(h, 'locInput');
6999
  }
7000
  }
7001
+ if (!found) return { ok: false, how: 'no location box found on this site' };
7002
+ await shopFocusAndClearInput(h, found, 'input[placeholder*="pin" i], input[placeholder*="locat" i], input[placeholder*="area" i], input[id*="GLUX" i], input[name="select-locality"]');
7003
  var pg = h.getPage();
7004
+ var locQuery = (plat.id === 'blinkit' && pin === '800001') ? 'Patna 800001' : pin;
7005
+ await pg.keyboard.type(locQuery, { delay: 70 });
7006
  h.log('📍 Typed pincode ' + pin);
7007
+ await h.snap(); await h.sleep(1300);
7008
+ var how = 'typed pincode', acted = false;
7009
  var sug = await shopFind(h, 'suggestion', { pin: pin, box: found });
7010
+ if (sug) { await h.clickAt(sug.x, sug.y); how += ' + picked suggestion'; acted = true; await h.sleep(1200); }
7011
+ else { try { await pg.keyboard.press('Enter'); } catch (e) {} await h.sleep(900); }
7012
  for (var k = 0; k < 2; k++) {
7013
  var still = await shopFind(h, 'locInput');
7014
  var btn = await shopFind(h, 'confirm', { box: still || found });
7015
  if (!btn) break;
7016
+ await h.clickAt(btn.x, btn.y); how += ' + clicked ' + btn.label; acted = true; await h.sleep(1200);
7017
  }
7018
+ await h.sleep(700); await h.snap();
7019
+ var seen = false, inputGone = false;
7020
+ try { seen = await pg.evaluate(function (p) { var t = (document.body && document.body.innerText) || ''; return t.indexOf(p) >= 0 || /patna/i.test(t); }, pin); } catch (e) {}
7021
+ inputGone = !(await shopFind(h, 'locInput'));
7022
+ return { ok: !!(seen || (inputGone && acted)), how: how, pinSeenOnPage: seen };
7023
  }
7024
 
7025
+ // Step 3: Collect real product cards from the page
7026
  async function shopCollectCards(h, tries) {
7027
  for (var i = 0; i < tries; i++) {
7028
  var page = h.getPage();
7029
  try { await page.waitForLoadState('domcontentloaded', { timeout: 4000 }); } catch (e) {}
7030
+ try { await page.waitForFunction(function () { return /(?:₹|Rs\.?)\s*\d/.test((document.body && document.body.innerText) || ''); }, null, { timeout: 5000 }); } catch (e) {}
7031
+ await h.sleep(600);
7032
  try { await page.mouse.wheel(0, 220); } catch (e) {}
7033
+ await h.sleep(450);
7034
  try { await page.evaluate(function () { window.scrollTo(0, 0); }); } catch (e) {}
7035
+ await h.sleep(250);
7036
  var cards = [];
7037
  try { cards = await h.getPage().evaluate(SHOP_EXTRACT_CARDS_IN_PAGE, 28); } catch (e) { cards = []; }
7038
  if (cards && cards.length) return cards;
 
7040
  return [];
7041
  }
7042
 
7043
+ // Step 3b: Click the store's search box, type item, submit, and collect cards
7044
  async function shopSearchAndCollect(h, plat, item) {
7045
  var box = await shopFind(h, 'searchInput');
7046
  if (!box) {
7047
  var trig = await shopFind(h, 'searchTrigger');
7048
  if (trig) {
 
7049
  await h.clickAt(trig.x, trig.y);
7050
+ await h.sleep(800);
7051
  box = await shopFind(h, 'searchInput');
7052
  }
7053
  }
 
7055
  var pg = h.getPage();
7056
  var beforeUrl = pg.url();
7057
  await shopFocusAndClearInput(h, box, 'input#autocomplete-0-input, input.aa-Input, input[name="q"], input#twotabsearchtextbox, input[type="search"]');
7058
+ await pg.keyboard.type(item, { delay: 45 });
 
7059
  await pg.evaluate(function (qText) {
7060
  try { if (window.getSelection) window.getSelection().removeAllRanges(); } catch (e) {}
7061
  var el = document.activeElement;
 
7063
  el = document.querySelector('input#autocomplete-0-input, input.aa-Input, input[name="q"], input#twotabsearchtextbox, input[type="search"]');
7064
  }
7065
  if (el) {
7066
+ var desc = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value');
7067
+ var setter = desc && desc.set;
7068
  if (setter && (!el.value || el.value.length < 2)) setter.call(el, qText);
7069
  el.dispatchEvent(new Event('input', { bubbles: true }));
7070
  el.dispatchEvent(new Event('change', { bubbles: true }));
7071
  }
7072
+ }, item).catch(function () {});
7073
+ h.log('🔎 Typed "' + item + '" in the ' + plat.name + ' search box');
7074
+ await h.sleep(500);
 
7075
  await pg.keyboard.press('Enter');
7076
+ await h.sleep(1500);
7077
+ try { await pg.waitForLoadState('domcontentloaded', { timeout: 8000 }); } catch (e) {}
7078
  await h.snap();
7079
 
 
 
7080
  if (plat.id === 'jiomart' && pg.url() === beforeUrl) {
7081
  var jmClicked = await pg.evaluate(function () {
7082
  var sug = document.querySelector('.aa-Item a, .aa-Item, .autocomplete-list li, [class*="search" i] button[type="submit"]');
7083
  if (sug) { sug.click(); return true; }
7084
  return false;
7085
+ }).catch(function () { return false; });
7086
+ if (jmClicked) await h.sleep(1300);
7087
  }
7088
 
7089
  var cards = await shopCollectCards(h, 2);
 
7091
  }
7092
  var url = typeof plat.searchUrlTpl === 'function' ? plat.searchUrlTpl(item) : '';
7093
  if (url) {
7094
+ h.log('↪️ ' + plat.name + ': opening search results page directly');
7095
  try { await h.goto(url); } catch (e) {}
7096
+ await h.sleep(1500);
7097
  await shopDismissPopups(h);
7098
  await h.snap();
7099
  return await shopCollectCards(h, 2);
 
7101
  return [];
7102
  }
7103
 
7104
+ // Step 4/5: Click the selected product card, wait until the Product Detail Page (PDP) opens,
7105
+ // read the real PDP numbers, and ONLY THEN take the screenshot on the opened Product Page!
7106
  async function shopOpenBestAndCapture(h, best, plat, pin) {
7107
  var res = { navigated: false, pdp: null, shot: null, url: '' };
7108
  var pg = h.getPage(), before = pg.url(), beforePage = pg;
7109
  var pt = null;
7110
  try { pt = await pg.evaluate(SHOP_HIGHLIGHT_IN_PAGE, best.idx); } catch (e) {}
7111
+ await h.sleep(350);
7112
+ await h.snap();
7113
+
7114
+ var targetHref = (pt && pt.href) || best.href || '';
7115
  if (pt) {
7116
+ h.log('👆 Clicking selected product: "' + String(best.title).slice(0, 55) + '"');
7117
  await h.clickAt(pt.x, pt.y);
7118
+ await h.sleep(1500);
7119
  }
7120
+
7121
  var p2 = h.getPage();
7122
+ // If coordinate click didn't trigger navigation yet, click the DOM link/card directly inside the page
7123
+ if (p2 === beforePage && p2.url() === before) {
7124
+ try {
7125
+ await p2.evaluate(function (idx) {
7126
+ var el = document.querySelector('[data-shop-card="' + idx + '"]');
7127
+ if (!el) return;
7128
+ var a = (el.tagName === 'A' ? el : null)
7129
+ || el.querySelector('h2 a[href], a[href*="/dp/"], a[href*="%2Fdp%2F"], a[href*="/p/"], a[href*="/prn/"], a[href*="/pd/"], a[href*="/product"], a[href]')
7130
+ || el.closest('a[href]');
7131
+ if (a) {
7132
+ a.removeAttribute('target');
7133
+ a.click();
7134
+ } else {
7135
+ var img = el.querySelector('img');
7136
+ if (img) img.click();
7137
+ el.click();
7138
+ }
7139
+ }, best.idx);
7140
+ } catch (e) {}
7141
+ await h.sleep(1500);
7142
  p2 = h.getPage();
7143
  }
7144
+
7145
+ // If still on the search page and we have the product's direct href, navigate to the product page directly
7146
+ if (p2 === beforePage && p2.url() === before && targetHref && /^https?:\/\//i.test(targetHref)) {
7147
+ h.log('↪️ Opening product page directly: ' + targetHref.slice(0, 75));
7148
+ try { await h.goto(targetHref); } catch (e) {}
7149
+ p2 = h.getPage();
 
 
 
7150
  }
 
 
 
 
7151
 
7152
+ try { await p2.waitForLoadState('domcontentloaded', { timeout: 8000 }); } catch (e) {}
7153
+ await h.sleep(1200);
 
 
7154
  try {
7155
+ await p2.waitForFunction(function () {
7156
+ var hasPrice = /(?:₹|Rs\.?)\s*\d/.test((document.body && document.body.innerText) || '');
7157
+ var imgs = Array.from(document.querySelectorAll('img'));
7158
+ var hasLoadedImg = imgs.some(function (im) {
7159
+ var r = im.getBoundingClientRect();
7160
+ return im.complete && im.naturalWidth > 80 && r.width > 80 && r.height > 80 && r.top >= 0 && r.top < 700;
7161
+ });
7162
+ return hasPrice && hasLoadedImg;
7163
+ }, null, { timeout: 4500 });
7164
+ } catch (e) {}
7165
+
7166
+ res.navigated = (p2 !== beforePage) || (p2.url() !== before && !/[?&](q|k|query)=/i.test(p2.url()));
7167
+ res.url = p2.url();
7168
 
7169
+ try {
7170
+ await p2.evaluate(function () {
7171
+ Array.prototype.forEach.call(document.querySelectorAll('.ai-shop-hl'), function (e) {
7172
+ e.classList.remove('ai-shop-hl');
7173
+ e.style.outline = '';
7174
+ e.style.boxShadow = '';
7175
+ });
7176
+ window.scrollTo(0, 0);
7177
+ });
7178
+ } catch (e) {}
7179
+ await h.sleep(350);
7180
+
7181
+ if (res.navigated) {
7182
+ if (plat.id === 'flipkart' && pin) {
7183
  try {
7184
+ var fkPinSet = await p2.evaluate(function (pStr) {
7185
+ var inp = document.querySelector('#pincodeInputId, input[placeholder*="Delivery Pincode" i], input[placeholder*="Enter Pincode" i]');
7186
+ if (!inp) return false;
7187
+ inp.focus();
7188
+ var desc = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value');
7189
+ if (desc && desc.set) desc.set.call(inp, pStr);
7190
+ else inp.value = pStr;
7191
+ inp.dispatchEvent(new Event('input', { bubbles: true }));
7192
+ inp.dispatchEvent(new Event('change', { bubbles: true }));
7193
+ return true;
7194
+ }, String(pin));
7195
+ if (fkPinSet) {
7196
+ await p2.keyboard.press('Enter').catch(function () {});
7197
+ await h.sleep(700);
 
 
 
 
 
7198
  }
7199
  } catch (e) {}
7200
  }
7201
+ try { res.pdp = await p2.evaluate(SHOP_READ_PDP_IN_PAGE, { pin: String(pin) }); } catch (e) { res.pdp = null; }
7202
+ // Take the screenshot ONLY after the product page is open!
7203
+ res.shot = await h.shot({ clipTop: true });
7204
+ } else {
7205
+ res.shot = null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7206
  }
7207
+ await h.snap();
7208
+ return res;
7209
  }
7210
 
7211
+ // One store, one item. Never invents data; only marks verified:true when a real product was clicked and its product page opened!
7212
  async function shopRunStore(h, plat, item, pin, maxPrice, deadlineAt) {
7213
  var out = { platformId: plat.id, platformName: plat.name, item: item, verified: false, reason: '', locationApplied: false, locationHow: '', candidates: 0 };
 
7214
  function tick(what) { if (Date.now() > deadlineAt) throw new Error('time limit reached while ' + what); if (h.cancelled && h.cancelled()) throw new Error('cancelled by a newer browser request'); }
7215
  try {
7216
  tick('opening ' + plat.name);
7217
+ h.progress('🌐 ' + plat.name + ': opening ' + plat.name + '…');
7218
+ var g = await shopOpenStoreDirect(h, plat);
7219
+ if (!g.ok) { await h.goto(shopHomeUrl(plat)); }
7220
+ await h.sleep(800); await h.snap();
7221
+ tick('checking the page');
7222
+ if (!(await shopRecoverFromBlock(h, plat))) {
7223
+ out.reason = 'the site blocked the automated browser (access-denied / captcha page) and did not recover after 2 retries';
7224
+ out.shot = await h.shot({}); return out;
7225
+ }
7226
  await shopDismissPopups(h);
 
7227
 
7228
+ tick('setting the location');
7229
+ h.progress('📍 ' + plat.name + ': entering delivery pincode ' + pin + '…');
7230
  var loc = await shopSetLocation(h, plat, pin);
7231
  out.locationApplied = !!loc.ok; out.locationHow = loc.how || '';
7232
+ h.log(loc.ok ? '✅ Location set (' + loc.how + ')' : 'ℹ️ Location note: ' + loc.how);
7233
  await shopDismissPopups(h);
7234
 
7235
  tick('searching');
7236
+ h.progress('🔎 ' + plat.name + ': searching "' + item + '"…');
7237
  var cards = await shopSearchAndCollect(h, plat, item);
7238
  if (!cards.length) {
7239
+ h.log('↻ No products rendered yet - reloading the results page once');
7240
+ try { await h.getPage().reload({ waitUntil: 'domcontentloaded', timeout: 15000 }); } catch (e) {}
7241
+ await h.sleep(1500);
7242
+ cards = await shopCollectCards(h, 2);
7243
+ }
7244
+ if (!cards.length && (await shopLooksBlocked(h)) && (await shopRecoverFromBlock(h, plat))) {
7245
+ cards = await shopSearchAndCollect(h, plat, item);
 
7246
  }
7247
  out.candidates = cards.length;
 
 
7248
  if (!cards.length) {
7249
+ var blocked = await shopLooksBlocked(h);
7250
+ out.reason = (blocked ? 'the site blocked the automated browser (access denied / captcha)' : 'no priced products appeared on the results page')
7251
+ + (loc.ok ? '' : '; also could not set the delivery location');
7252
+ out.shot = await h.shot({}); return out;
 
7253
  }
7254
+ tick('choosing a product');
 
7255
  var pick = shopPickBestProduct(cards, item, maxPrice);
7256
+ if (!pick.best) { out.reason = pick.reason; out.shot = await h.shot({}); return out; }
 
 
 
 
7257
  var best = pick.best;
7258
+ h.progress('✅ ' + plat.name + ': picked "' + String(best.title).slice(0, 40) + '" ₹' + best.price + ' — clicking product to open page…');
7259
 
7260
+ tick('opening the product page');
7261
  var cap = await shopOpenBestAndCapture(h, best, plat, pin);
7262
 
7263
+ // If the first card didn't navigate to a product detail page, try the next ranked card that has a direct product href
7264
+ if (!cap.navigated && Array.isArray(pick.ranked) && pick.ranked.length > 1) {
7265
+ for (var rIdx = 1; rIdx < Math.min(pick.ranked.length, 3); rIdx++) {
7266
+ var altCard = pick.ranked[rIdx] && pick.ranked[rIdx].card;
7267
+ if (altCard && altCard.href) {
7268
+ h.log('↪️ Retrying click on next matching product card: "' + String(altCard.title).slice(0, 45) + '"');
7269
+ best = altCard;
7270
+ cap = await shopOpenBestAndCapture(h, best, plat, pin);
7271
+ if (cap.navigated) break;
7272
+ }
7273
+ }
7274
+ }
7275
+
7276
+ if (!cap.navigated) {
7277
+ out.reason = 'found "' + String(best.title).slice(0, 50) + '" on search results, but could not open the product detail page to snap the product picture';
7278
+ out.shot = null;
7279
+ return out;
7280
+ }
7281
+
7282
  var title = best.title, price = best.price, mrp = best.mrp, discountPct = best.discountPct, discountInr = best.discountInr;
7283
  var rating = best.rating, reviews = best.reviews, eta = best.eta;
7284
  if (cap.pdp && cap.navigated) {
 
7296
  if (d.rating && !rating) rating = d.rating;
7297
  if (d.ratingCount && !reviews) reviews = d.ratingCount;
7298
  if (d.eta && !eta) eta = d.eta;
7299
+ if (d.pinVisible) out.locationApplied = true;
7300
  }
7301
  if (mrp && mrp > price) { discountInr = Math.round(mrp - price); if (!discountPct) discountPct = Math.round(discountInr / mrp * 100); }
7302
  else { mrp = mrp && mrp > price ? mrp : null; }
 
7308
  out.rating = rating ? (rating.toFixed(1) + ' ★') : null; out.reviewsCount = reviews || null; out.eta = eta || '';
7309
  out.directProductUrl = productUrl; out.snappedImage = cap.shot; out.navigated = cap.navigated;
7310
  out.overBudget = !!pick.overBudget; out.matchTier = pick.tier; out.mrpDerived = !!(best.mrpDerived && !(cap.pdp && cap.pdp.mrp));
7311
+ if (maxPrice && pick.overBudget) out.note = 'nothing relevant was under ₹' + maxPrice + ' - this is the cheapest match (₹' + out.priceInr + ')';
7312
  if (cap.navigated && h.addToCart !== false) {
7313
  var add = await shopFind(h, 'addBtn');
7314
+ if (add) { await h.clickAt(add.x, add.y); out.addedToVirtualCart = true; await h.sleep(700); await h.snap(); }
7315
  }
7316
  return out;
7317
  } catch (e) {
 
 
7318
  out.reason = 'stopped: ' + String((e && e.message) || e).split('\n')[0];
7319
  try { out.shot = await h.shot({}); } catch (x) {}
7320
  return out;
 
8751
  color: "#0078ad",
8752
  badgeBg: "rgba(0, 120, 173, 0.14)",
8753
  icon: "🧺",
8754
+ searchUrlTpl: (q) => `https://www.jiomart.com/search?q=${encodeURIComponent(toCleanStoreSearchQuery(q, false))}`,
8755
+ liveBrowserUrlTpl: (q) => `https://www.jiomart.com/search?q=${encodeURIComponent(toCleanStoreSearchQuery(q, false))}`,
8756
  bypassUrlTpl: (q) => `https://www.google.com/search?q=site:jiomart.com+${encodeURIComponent(toCleanStoreSearchQuery(q, false))}&gl=in`,
8757
  cartUrl: "https://www.jiomart.com/checkout/cart"
8758
  },