1
2
3import { currencyFrom, parseAmount, parsePrice, round2 } from './price.js';
4
5export const clean = (s) => (s === null || s === undefined ? '' : String(s)).replace(/\s+/g, ' ').trim();
6const arr = (v) => (v === null || v === undefined ? [] : Array.isArray(v) ? v : [v]);
7const typeIs = (node, t) => arr(node?.['@type']).some((x) => String(x).toLowerCase() === t.toLowerCase());
8const abs = (u, base) => { try { return new URL(u, base).href; } catch { return ''; } };
9const stripHtml = (s) => clean(String(s || '').replace(/<[^>]+>/g, ' ').replace(/ /g, ' ').replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, "'"));
10
11
12export const RELIABILITY = { 'platform-api': 1, 'json-ld': 0.9, microdata: 0.8, meta: 0.6, heuristic: 0.4 };
13
14export function normalizeAvailability(v) {
15 const s = String(v || '').toLowerCase();
16 if (!s) return '';
17 if (/instock|in_stock|in stock|available|limitedavailability|onlineonly|instoreonly|^true$/.test(s) && !/unavailable|not available/.test(s)) return 'in_stock';
18 if (/outofstock|out_of_stock|out of stock|sold ?out|soldout|discontinued|unavailable|^false$/.test(s)) return 'out_of_stock';
19 if (/preorder|pre-order|presale/.test(s)) return 'preorder';
20 if (/backorder/.test(s)) return 'backorder';
21 return '';
22}
23
24
25export function jsonLdNodes($) {
26 const out = [];
27 const walk = (n) => {
28 if (!n || typeof n !== 'object') return;
29 if (Array.isArray(n)) { n.forEach(walk); return; }
30 out.push(n);
31 if (n['@graph']) walk(n['@graph']);
32 if (n.mainEntity) walk(n.mainEntity);
33 if (n.itemListElement) walk(n.itemListElement);
34 if (n.item && typeof n.item === 'object') walk(n.item);
35 };
36 $('script[type="application/ld+json"]').each((_, el) => {
37 const raw = $(el).contents().text().trim();
38 if (!raw) return;
39 try { walk(JSON.parse(raw)); } catch {
40
41 try { walk(JSON.parse(raw.replace(/,\s*([}\]])/g, '$1').replace(/[\u0000-\u001f]+/g, ' '))); } catch { }
42 }
43 });
44 return out;
45}
46
47function offerFields(offers) {
48 const list = arr(offers).flatMap((o) => (typeIs(o, 'AggregateOffer') && o.offers ? arr(o.offers) : [o])).filter(Boolean);
49 const agg = arr(offers).find((o) => typeIs(o, 'AggregateOffer'));
50 const first = list.find((o) => o.price !== undefined || o.lowPrice !== undefined || o.priceSpecification) || list[0] || agg;
51 if (!first) return {};
52 const spec = arr(first.priceSpecification);
53 const listPrice = spec.find((p) => /ListPrice|StrikethroughPrice|MSRP/i.test(String(p.priceType || '')));
54 const salePrice = spec.find((p) => !p.priceType || /SalePrice/i.test(String(p.priceType)));
55 const price = parseAmount(first.price ?? salePrice?.price ?? first.lowPrice ?? agg?.lowPrice);
56 return {
57 price,
58 maxPrice: parseAmount(agg?.highPrice) ?? null,
59 currency: first.priceCurrency || salePrice?.priceCurrency || agg?.priceCurrency || '',
60 previousPrice: parseAmount(listPrice?.price) ?? null,
61 availability: normalizeAvailability(first.availability || agg?.availability),
62 sku: first.sku || '',
63 gtin: first.gtin13 || first.gtin12 || first.gtin14 || first.gtin8 || first.gtin || '',
64 shipping: arr(first.shippingDetails).map((d) => ({
65 rate: parseAmount(d.shippingRate?.value), currency: d.shippingRate?.currency || '',
66 destination: arr(d.shippingDestination).map((x) => x.addressCountry || x.addressRegion).filter(Boolean).join(', '),
67 delivery_days: d.deliveryTime?.transitTime ? [d.deliveryTime.transitTime.minValue, d.deliveryTime.transitTime.maxValue].filter((v) => v !== undefined).join('-') : '',
68 })).filter((s) => s.rate !== null || s.destination),
69 sellerName: clean(first.seller?.name),
70 validUntil: first.priceValidUntil || '',
71 count: list.length,
72 list,
73 };
74}
75
76const imagesOf = (img, base) => arr(img).map((i) => (typeof i === 'string' ? i : i?.url || i?.contentUrl)).filter(Boolean).map((u) => abs(u, base));
77
78export function fromJsonLd($, url) {
79 const nodes = jsonLdNodes($);
80 const group = nodes.find((n) => typeIs(n, 'ProductGroup'));
81 const product = group || nodes.find((n) => typeIs(n, 'Product'));
82 const crumbs = nodes.find((n) => typeIs(n, 'BreadcrumbList'));
83 const breadcrumbs = crumbs ? arr(crumbs.itemListElement).sort((a, b) => (a.position || 0) - (b.position || 0))
84 .map((e) => clean(e.name || e.item?.name)).filter(Boolean) : [];
85 if (!product) return { breadcrumbs, productLinks: itemListLinks(nodes, url) };
86 const variantsRaw = group ? arr(group.hasVariant) : [];
87 const o = offerFields(product.offers || variantsRaw[0]?.offers);
88 const rating = product.aggregateRating || {};
89 return {
90 name: clean(product.name),
91 description: stripHtml(product.description),
92 brand: clean(typeof product.brand === 'string' ? product.brand : product.brand?.name || product.manufacturer?.name),
93 sku: clean(product.sku || o.sku || variantsRaw[0]?.sku),
94 gtin: clean(product.gtin13 || product.gtin12 || product.gtin14 || product.gtin8 || product.gtin || o.gtin),
95 mpn: clean(product.mpn),
96 price: o.price ?? null,
97 maxPrice: o.maxPrice ?? null,
98 currency: o.currency || '',
99 previousPrice: o.previousPrice ?? null,
100 availability: o.availability || '',
101 images: imagesOf(product.image, url),
102 ratingValue: parseAmount(rating.ratingValue),
103 ratingCount: parseAmount(rating.reviewCount ?? rating.ratingCount),
104 category: clean(Array.isArray(product.category) ? product.category.join(' > ') : product.category),
105 breadcrumbs,
106 shipping: o.shipping || [],
107 seller: o.sellerName || '',
108 condition: clean(String(arr(product.offers)[0]?.itemCondition || '').replace(/^https?:\/\/schema\.org\//, '')),
109 variants: variantsRaw.length ? variantsRaw.map((v) => {
110 const vo = offerFields(v.offers);
111 return { name: clean(v.name), sku: clean(v.sku), price: vo.price ?? null, currency: vo.currency || o.currency, previous_price: vo.previousPrice ?? null,
112 availability: vo.availability, options: Object.fromEntries(['color', 'size', 'material', 'pattern'].filter((k) => v[k]).map((k) => [k, clean(v[k])])), image: imagesOf(v.image, url)[0] || '' };
113 }) : (o.count > 1 ? o.list.map((x) => ({ name: clean(x.name), sku: clean(x.sku), price: parseAmount(x.price), currency: x.priceCurrency || o.currency, previous_price: null,
114 availability: normalizeAvailability(x.availability), options: {}, image: '' })) : []),
115 canonical: product.url ? abs(product.url, url) : '',
116 };
117}
118
119function itemListLinks(nodes, base) {
120 return nodes.filter((n) => typeIs(n, 'ListItem') || typeIs(n, 'Product'))
121 .map((n) => n.url || (typeof n.item === 'string' ? n.item : n.item?.url)).filter(Boolean).map((u) => abs(u, base));
122}
123
124
125export function fromMicrodata($, url) {
126 const root = $('[itemtype*="schema.org/Product"]').first();
127 if (!root.length) return null;
128 const prop = (name, scope = root) => {
129 const el = scope.find(`[itemprop="${name}"]`).first();
130 if (!el.length) return '';
131 return clean(el.attr('content') || el.attr('href') || el.attr('src') || el.text());
132 };
133 const offer = root.find('[itemprop="offers"]').first();
134 const brandEl = root.find('[itemprop="brand"]').first();
135 return {
136 name: prop('name'),
137 description: prop('description'),
138 brand: clean(brandEl.find('[itemprop="name"]').attr('content') || brandEl.find('[itemprop="name"]').text() || brandEl.attr('content') || brandEl.text()),
139 sku: prop('sku'),
140 gtin: prop('gtin13') || prop('gtin'),
141 price: parseAmount(prop('price', offer.length ? offer : root) || prop('lowPrice', offer.length ? offer : root)),
142 currency: prop('priceCurrency', offer.length ? offer : root),
143 availability: normalizeAvailability(prop('availability', offer.length ? offer : root)),
144 images: root.find('[itemprop="image"]').map((_, e) => abs($(e).attr('src') || $(e).attr('content') || $(e).attr('href'), url)).get().filter(Boolean),
145 ratingValue: parseAmount(prop('ratingValue')),
146 ratingCount: parseAmount(prop('reviewCount') || prop('ratingCount')),
147 };
148}
149
150
151export function fromMeta($, url) {
152 const m = (k) => clean($(`meta[property="${k}"]`).attr('content') || $(`meta[name="${k}"]`).attr('content'));
153 const isProduct = /product/i.test(m('og:type')) || !!m('product:price:amount') || !!m('og:price:amount');
154 return {
155 isProduct,
156 name: m('og:title') || clean($('title').text()),
157 description: m('og:description') || m('description'),
158 brand: m('product:brand') || m('og:brand'),
159 price: parseAmount(m('product:price:amount') || m('og:price:amount') || m('product:sale_price:amount')),
160 previousPrice: parseAmount(m('product:original_price:amount')),
161 currency: m('product:price:currency') || m('og:price:currency'),
162 availability: normalizeAvailability(m('product:availability') || m('og:availability')),
163 images: [m('og:image'), m('og:image:secure_url')].filter(Boolean).map((u) => abs(u, url)),
164 sku: m('product:retailer_item_id') || m('product:sku'),
165 canonical: abs($('link[rel="canonical"]').attr('href') || m('og:url'), url),
166 siteName: m('og:site_name'),
167 };
168}
169
170
171const PRICE_SEL = ['[data-price]', '[itemprop="price"]', '.price ins .amount', '.price .amount', '.product-price', '.price-current', '.current-price', '.sale-price',
172 '.special-price .price', '[class*="ProductPrice"]', '[class*="product-price"]', '[class*="price--sale"]', '.price'];
173const OLD_SEL = ['.price del .amount', 'del', 's', '.old-price', '.was-price', '.price--compare', '.compare-at-price', '[class*="old-price"]', '[class*="oldPrice"]', '[class*="strike"]', '.regular-price'];
174
175export function fromPage($, url, fallbackCurrency = '') {
176 const first = (sels) => {
177 for (const s of sels) {
178 const el = $(s).filter((_, e) => clean($(e).attr('data-price') || $(e).attr('content') || $(e).text()).length < 60).first();
179 if (!el.length) continue;
180 const txt = clean(el.attr('content') || el.attr('data-price') || el.text());
181 const p = parsePrice(txt, fallbackCurrency);
182 if (p) return { ...p, raw: txt };
183 }
184 return null;
185 };
186 const price = first(PRICE_SEL);
187 const old = first(OLD_SEL);
188 const bodyText = clean($("main").text() || $("body").text() || $.root().text()).slice(0, 20000);
189 const stockText = /out of stock|sold out|currently unavailable|not available/i.test(bodyText) ? 'out_of_stock'
190 : /in stock|available now|add to (cart|basket|bag)|buy now/i.test(bodyText) ? 'in_stock' : '';
191 const crumbs = $('nav[aria-label*="readcrumb"] a, .breadcrumb a, .breadcrumbs a, [class*="breadcrumb"] a, ol.breadcrumb li')
192 .map((_, e) => clean($(e).text())).get().filter((t) => t && t.length < 60);
193 const shippingText = (/(free (shipping|delivery)[^.]{0,60}|delivery[^.]{0,20}(within|in) \d+[^.]{0,30}|ships? (in|within) [^.]{0,40})/i.exec(bodyText) || [])[0] || '';
194 return {
195 name: clean($('h1').first().text()),
196 price: price?.amount ?? null,
197 maxPrice: price?.max ?? null,
198 currency: price?.currency || '',
199 previousPrice: old && price && old.amount > price.amount ? old.amount : null,
200 availability: stockText,
201 breadcrumbs: [...new Set(crumbs)],
202 shippingText: clean(shippingText),
203 images: $('img').map((_, e) => $(e).attr('data-src') || $(e).attr('src')).get().filter((u) => u && /product|catalog|media|upload|cdn|image/i.test(u) && !/logo|icon|sprite|placeholder|avatar|banner/i.test(u)).slice(0, 10).map((u) => abs(u, url)),
204 };
205}
206
207
208
209
210
211export function mergeLayers(layers, { url, defaultCurrency = '' }) {
212 const order = ['platform-api', 'json-ld', 'microdata', 'meta', 'heuristic'];
213 const sources = {};
214 const pick = (field, outName = field, valid = (v) => v !== null && v !== undefined && v !== '' && !(Array.isArray(v) && !v.length)) => {
215 for (const k of order) {
216 const v = layers[k]?.[field];
217 if (valid(v)) { sources[outName] = k; return v; }
218 }
219 return null;
220 };
221 const name = pick('name', 'product_name');
222 const price = pick('price', 'price', (v) => typeof v === 'number' && v >= 0);
223 let currency = pick('currency');
224 if (!currency) {
225 const fromText = layers.heuristic?.currency || currencyFrom(layers.meta?.siteName || '', '') || defaultCurrency;
226 if (fromText) { currency = fromText; sources.currency = layers.heuristic?.currency ? 'heuristic' : 'default'; }
227 }
228 let previousPrice = pick('previousPrice', 'previous_price', (v) => typeof v === 'number' && v > 0);
229 if (previousPrice !== null && price !== null && previousPrice <= price) { previousPrice = null; delete sources.previous_price; }
230 const availability = pick('availability') || 'unknown';
231 const images = [...new Set([...(layers['platform-api']?.images || []), ...(layers['json-ld']?.images || []), ...(layers.microdata?.images || []), ...(layers.meta?.images || []),
232 ...((layers['platform-api']?.images?.length || layers['json-ld']?.images?.length) ? [] : layers.heuristic?.images || [])])].slice(0, 20);
233 if (images.length) sources.images = order.find((k) => layers[k]?.images?.length);
234 const breadcrumbs = pick('breadcrumbs') || [];
235 const ratingValue = pick('ratingValue', 'rating');
236 const ratingCount = pick('ratingCount', 'review_count');
237 const variants = pick('variants') || [];
238 const shipping = pick('shipping') || [];
239 const shippingText = layers.heuristic?.shippingText || '';
240 const rec = {
241 product_name: name || '',
242 description: (pick('description') || '').slice(0, 5000),
243 brand: pick('brand') || '',
244 sku: pick('sku') || '',
245 gtin: pick('gtin') || '',
246 mpn: pick('mpn') || '',
247 price: round2(price),
248 max_price: round2(pick('maxPrice', 'max_price', (v) => typeof v === 'number' && v > (price ?? 0))),
249 currency: currency || '',
250 previous_price: round2(previousPrice),
251 discount_percent: previousPrice && price ? Math.round((1 - price / previousPrice) * 100) : null,
252 availability,
253 in_stock: availability === 'in_stock' ? true : availability === 'out_of_stock' ? false : null,
254 images,
255 variants,
256 variant_count: variants.length,
257 rating: ratingValue !== null ? round2(ratingValue) : null,
258 review_count: ratingCount,
259 shipping: shipping.length ? shipping : (shippingText ? [{ note: shippingText }] : []),
260 category: pick('category') || breadcrumbs[breadcrumbs.length - 1] || '',
261 breadcrumbs,
262 seller: pick('seller') || '',
263 condition: pick('condition') || '',
264 source_url: url,
265 canonical_url: pick('canonical', 'canonical_url') || '',
266 };
267 if (rec.shipping.length && !sources.shipping) sources.shipping = 'heuristic';
268 const unreliable = Object.entries(sources).filter(([, s]) => s === 'heuristic' || s === 'default').map(([k]) => k);
269 const KEY = ['product_name', 'price', 'currency', 'availability', 'images'];
270 const missing = KEY.filter((k) => (k === 'availability' ? rec.availability === 'unknown' : Array.isArray(rec[k]) ? !rec[k].length : rec[k] === null || rec[k] === ''));
271 const weights = { product_name: 0.25, price: 0.3, currency: 0.15, availability: 0.15, images: 0.15 };
272 const confidence = Object.entries(weights).reduce((acc, [k, w]) => acc + (missing.includes(k) ? 0 : w * (RELIABILITY[sources[k]] ?? (sources[k] === 'default' ? 0.3 : 0.5))), 0);
273 return { ...rec, field_sources: sources, unreliable_fields: unreliable, missing_fields: missing, confidence: Math.round(confidence * 100) / 100 };
274}