agentic-commerce-readiness 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,259 @@
1
+ // Feed loading and normalization.
2
+ //
3
+ // Every input format is turned into the same record shape. Field names follow the
4
+ // OpenAI product feed schema where one exists (item_id, url, image_url, group_id ...),
5
+ // because it is the stricter of the two specs, and Google names are mapped onto them.
6
+ // The raw value is kept as-is: validation happens later, so problems are reported
7
+ // against what the merchant actually wrote.
8
+
9
+ import { readFile } from 'node:fs/promises';
10
+ import { extname } from 'node:path';
11
+
12
+ /** RFC 4180 CSV/TSV parser: quoted fields, escaped quotes, newlines inside quotes, BOM. */
13
+ export function parseDelimited(text, delimiter = ',') {
14
+ const rows = [];
15
+ let row = [];
16
+ let field = '';
17
+ let i = 0;
18
+ let inQuotes = false;
19
+ if (text.charCodeAt(0) === 0xfeff) i = 1;
20
+ for (; i < text.length; i++) {
21
+ const c = text[i];
22
+ if (inQuotes) {
23
+ if (c === '"') {
24
+ if (text[i + 1] === '"') { field += '"'; i++; } else inQuotes = false;
25
+ } else field += c;
26
+ } else if (c === '"' && field === '') inQuotes = true;
27
+ else if (c === delimiter) { row.push(field); field = ''; }
28
+ else if (c === '\n' || c === '\r') {
29
+ if (c === '\r' && text[i + 1] === '\n') i++;
30
+ row.push(field); field = '';
31
+ if (row.length > 1 || row[0] !== '') rows.push(row);
32
+ row = [];
33
+ } else field += c;
34
+ }
35
+ if (field !== '' || row.length) { row.push(field); if (row.length > 1 || row[0] !== '') rows.push(row); }
36
+ if (!rows.length) return [];
37
+ const header = rows[0].map((h) => h.trim());
38
+ return rows.slice(1).map((r) => Object.fromEntries(header.map((h, j) => [h, r[j] ?? ''])));
39
+ }
40
+
41
+ // Canonical field <- accepted input names (OpenAI names, OpenAI aliases, Google names).
42
+ const ALIASES = {
43
+ item_id: ['item_id', 'id', 'sku', 'g:id'],
44
+ group_id: ['group_id', 'item_group_id', 'g:item_group_id'],
45
+ title: ['title', 'g:title', 'structured_title'],
46
+ description: ['description', 'g:description', 'structured_description'],
47
+ url: ['url', 'link', 'g:link'],
48
+ image_url: ['image_url', 'image_link', 'g:image_link'],
49
+ additional_image_urls: ['additional_image_urls', 'additional_image_link', 'g:additional_image_link'],
50
+ brand: ['brand', 'g:brand'],
51
+ seller_name: ['seller_name'],
52
+ seller_url: ['seller_url'],
53
+ availability: ['availability', 'g:availability'],
54
+ availability_date: ['availability_date', 'g:availability_date'],
55
+ price: ['price', 'g:price'],
56
+ sale_price: ['sale_price', 'g:sale_price'],
57
+ gtin: ['gtin', 'g:gtin'],
58
+ mpn: ['mpn', 'g:mpn'],
59
+ identifier_exists: ['identifier_exists', 'g:identifier_exists'],
60
+ condition: ['condition', 'g:condition'],
61
+ product_category: ['product_category', 'google_product_category', 'g:google_product_category'],
62
+ product_type: ['product_type', 'g:product_type'],
63
+ item_group_title: ['item_group_title'],
64
+ color: ['color', 'g:color'],
65
+ size: ['size', 'g:size'],
66
+ material: ['material', 'g:material'],
67
+ gender: ['gender', 'g:gender'],
68
+ age_group: ['age_group', 'g:age_group'],
69
+ weight: ['weight'],
70
+ dimensions: ['dimensions'],
71
+ length: ['length'],
72
+ width: ['width'],
73
+ height: ['height'],
74
+ dimensions_unit: ['dimensions_unit'],
75
+ item_weight_unit: ['item_weight_unit'],
76
+ shipping_weight: ['shipping_weight', 'g:shipping_weight'],
77
+ shipping_price: ['shipping_price'],
78
+ shipping: ['shipping', 'g:shipping'],
79
+ accepts_returns: ['accepts_returns'],
80
+ return_deadline_in_days: ['return_deadline_in_days', 'return_window'],
81
+ return_policy: ['return_policy'],
82
+ review_count: ['review_count'],
83
+ star_rating: ['star_rating'],
84
+ target_countries: ['target_countries'],
85
+ store_country: ['store_country'],
86
+ listing_has_variations: ['listing_has_variations'],
87
+ variant_dict: ['variant_dict'],
88
+ is_eligible_search: ['is_eligible_search', 'enable_search'],
89
+ is_eligible_checkout: ['is_eligible_checkout', 'enable_checkout'],
90
+ seller_privacy_policy: ['seller_privacy_policy'],
91
+ seller_tos: ['seller_tos'],
92
+ adult: ['adult', 'g:adult'],
93
+ };
94
+
95
+ /** Map an input object (any supported naming) to the canonical record. Tracks which input names were used. */
96
+ export function normalizeRecord(obj, row) {
97
+ const rec = { _row: row, _fields: {} };
98
+ const lower = Object.fromEntries(Object.entries(obj).map(([k, v]) => [k.trim().toLowerCase(), v]));
99
+ for (const [canon, names] of Object.entries(ALIASES)) {
100
+ for (const n of names) {
101
+ if (lower[n] !== undefined && lower[n] !== null && !(typeof lower[n] === 'string' && lower[n].trim() === '')) {
102
+ rec[canon] = typeof lower[n] === 'string' ? lower[n].trim() : lower[n];
103
+ rec._fields[canon] = n;
104
+ break;
105
+ }
106
+ }
107
+ }
108
+ // Legacy OpenAI variant pairs -> variant_dict
109
+ if (rec.variant_dict === undefined) {
110
+ const vd = {};
111
+ for (let i = 1; i <= 3; i++) {
112
+ const k = lower[`custom_variant${i}_category`];
113
+ const v = lower[`custom_variant${i}_option`];
114
+ if (k && v) vd[String(k).trim()] = String(v).trim();
115
+ }
116
+ if (Object.keys(vd).length) { rec.variant_dict = vd; rec._fields.variant_dict = 'custom_variantN_*'; }
117
+ }
118
+ return rec;
119
+ }
120
+
121
+ /** Shopify "Export products" CSV: one row per variant; product-level columns only on the first row of a handle;
122
+ * extra image rows carry only Handle + Image Src. */
123
+ export function fromShopifyExport(rows, { site, currency, brandFallback } = {}) {
124
+ const records = [];
125
+ const parents = new Map();
126
+ rows.forEach((r, idx) => {
127
+ const handle = r['Handle'];
128
+ if (!handle) return;
129
+ if (!parents.has(handle)) parents.set(handle, { row: r, extraImages: [] });
130
+ const parent = parents.get(handle);
131
+ const p = parent.row;
132
+ if (r['Image Src'] && r !== p && r['Image Src'] !== p['Image Src']) parent.extraImages.push(r['Image Src']);
133
+ if (!r['Variant Price']) return;
134
+ const opt = {};
135
+ for (let i = 1; i <= 3; i++) {
136
+ const name = p[`Option${i} Name`];
137
+ const val = r[`Option${i} Value`];
138
+ if (name && val && !(name === 'Title' && val === 'Default Title')) opt[name] = val;
139
+ }
140
+ const hasVariants = Object.keys(opt).length > 0;
141
+ const qty = r['Variant Inventory Qty'];
142
+ const policy = (r['Variant Inventory Policy'] || '').toLowerCase();
143
+ let availability;
144
+ const tracked = (r['Variant Inventory Tracker'] ?? 'shopify') !== '' && qty !== undefined && qty !== '';
145
+ if (tracked) availability = Number(qty) > 0 ? 'in_stock' : policy === 'continue' ? 'backorder' : 'out_of_stock';
146
+ else if ('Variant Inventory Tracker' in r || qty === '') availability = 'in_stock'; // inventory not tracked: always purchasable
147
+ const money = (n) => `${Number(n).toFixed(2)}${currency ? ' ' + currency : ''}`;
148
+ const obj = {
149
+ item_id: r['Variant SKU'] || `${handle}-${idx + 2}`,
150
+ group_id: hasVariants ? handle : undefined,
151
+ title: [p['Title'], ...Object.values(opt)].filter(Boolean).join(' - '),
152
+ description: stripHtml(p['Body (HTML)'] || ''),
153
+ url: site ? `${site.replace(/\/$/, '')}/products/${handle}` : undefined,
154
+ image_url: r['Variant Image'] || p['Image Src'],
155
+ brand: p['Vendor'] || brandFallback,
156
+ price: money(r['Variant Price']),
157
+ gtin: r['Variant Barcode'],
158
+ product_category: p['Product Category'] || undefined,
159
+ product_type: p['Type'] || undefined,
160
+ availability,
161
+ listing_has_variations: hasVariants ? 'true' : undefined,
162
+ variant_dict: hasVariants ? opt : undefined,
163
+ };
164
+ const grams = Number(r['Variant Grams']);
165
+ if (grams > 0) { obj.weight = String(grams); obj.item_weight_unit = 'g'; }
166
+ // Shopify "Compare At Price" is the old (regular) price, so the variant price is the sale price.
167
+ const compare = Number(r['Variant Compare At Price']);
168
+ if (compare && compare > Number(r['Variant Price'])) {
169
+ obj.sale_price = obj.price;
170
+ obj.price = money(compare);
171
+ }
172
+ const rec = normalizeRecord(obj, idx + 2);
173
+ rec._status = (p['Status'] || '').toLowerCase() || undefined;
174
+ rec._parent = parent;
175
+ records.push(rec);
176
+ });
177
+ for (const rec of records) {
178
+ if (rec._parent.extraImages.length) rec.additional_image_urls = rec._parent.extraImages;
179
+ delete rec._parent;
180
+ }
181
+ return records;
182
+ }
183
+
184
+ export function stripHtml(html) {
185
+ return String(html)
186
+ .replace(/<(script|style)\b[\s\S]*?<\/\1>/gi, ' ')
187
+ .replace(/<br\s*\/?>|<\/p>|<\/li>|<\/h\d>/gi, '\n')
188
+ .replace(/<[^>]+>/g, ' ')
189
+ .replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>')
190
+ .replace(/[ \t]+/g, ' ')
191
+ .split('\n').map((l) => l.trim()).filter(Boolean).join('\n')
192
+ .trim();
193
+ }
194
+
195
+ /** Google Merchant Center RSS 2.0 / Atom XML feed. */
196
+ export function parseGoogleXml(xml) {
197
+ const items = xml.match(/<(item|entry)\b[\s\S]*?<\/\1>/gi) || [];
198
+ return items.map((itemWithTag, i) => {
199
+ const item = itemWithTag.replace(/^<(item|entry)\b[^>]*>/i, '').replace(/<\/(item|entry)>$/i, '');
200
+ const obj = {};
201
+ const re = /<((?:g:)?[a-z_]+)(?:\s[^>]*)?>([\s\S]*?)<\/\1>/gi;
202
+ let m;
203
+ while ((m = re.exec(item)) !== null) {
204
+ const key = m[1].toLowerCase().replace(/^g:/, '');
205
+ if (key === 'item' || key === 'entry') continue;
206
+ let val = m[2].replace(/^<!\[CDATA\[([\s\S]*)\]\]>$/, '$1').trim();
207
+ if (/<[a-z]/i.test(val) && key === 'shipping') val = val.replace(/\s+/g, ' ');
208
+ if (key === 'additional_image_link') (obj[key] ||= []).push(val);
209
+ else if (obj[key] === undefined) obj[key] = decodeXml(val);
210
+ }
211
+ // Atom uses <link href="...">
212
+ if (!obj.link) {
213
+ const l = /<link\b[^>]*href\s*=\s*["']([^"']+)["']/i.exec(item);
214
+ if (l) obj.link = l[1];
215
+ }
216
+ return normalizeRecord(obj, i + 1);
217
+ });
218
+ }
219
+
220
+ function decodeXml(s) {
221
+ return s.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, '&');
222
+ }
223
+
224
+ /** Detect the format and return { format, records }. */
225
+ export function parseFeedText(text, { filename = '', site, currency, brandFallback } = {}) {
226
+ const ext = extname(filename).toLowerCase();
227
+ const head = text.slice(0, 2000).trimStart();
228
+ if (ext === '.xml' || head.startsWith('<?xml') || /^<(rss|feed)\b/i.test(head)) {
229
+ return { format: 'google-xml', records: parseGoogleXml(text) };
230
+ }
231
+ const parseJsonl = () => {
232
+ const records = [];
233
+ const errors = [];
234
+ text.split(/\r?\n/).forEach((l, i) => {
235
+ if (!l.trim()) return;
236
+ try { records.push(normalizeRecord(JSON.parse(l), i + 1)); } catch (e) { errors.push({ row: i + 1, message: `Line ${i + 1} is not valid JSON: ${e.message}` }); }
237
+ });
238
+ return { format: 'jsonl', records, errors };
239
+ };
240
+ if (ext === '.jsonl' || ext === '.ndjson') return parseJsonl();
241
+ if (ext === '.json' || head.startsWith('[') || head.startsWith('{')) {
242
+ let data;
243
+ try { data = JSON.parse(text); } catch { return parseJsonl(); }
244
+ const arr = Array.isArray(data) ? data : data.products || data.items || data.entries || [data];
245
+ return { format: 'json', records: arr.map((o, i) => normalizeRecord(o, i + 1)) };
246
+ }
247
+ const firstLine = text.split(/\r?\n/, 1)[0];
248
+ const delimiter = ext === '.tsv' || ext === '.txt' || (firstLine.split('\t').length > firstLine.split(',').length) ? '\t' : ',';
249
+ const rows = parseDelimited(text, delimiter);
250
+ if (rows.length && 'Handle' in rows[0] && 'Variant Price' in rows[0]) {
251
+ return { format: 'shopify-export', records: fromShopifyExport(rows, { site, currency, brandFallback }) };
252
+ }
253
+ return { format: delimiter === '\t' ? 'tsv' : 'csv', records: rows.map((r, i) => normalizeRecord(r, i + 2)) };
254
+ }
255
+
256
+ export async function loadFeed(path, opts = {}) {
257
+ const text = await readFile(path, 'utf8');
258
+ return parseFeedText(text, { ...opts, filename: path });
259
+ }
@@ -0,0 +1,337 @@
1
+ // Feed validation against two specs:
2
+ // chatgpt: OpenAI product feed schema (Agentic Commerce Protocol), developers.openai.com/commerce/specs/file-upload/products
3
+ // google: Google Merchant Center product data specification, support.google.com/merchants/answer/7052112
4
+ //
5
+ // Severity:
6
+ // error - the item is rejected / disapproved on that channel
7
+ // warning - accepted, but shown less, shown wrongly, or at policy risk
8
+ // tip - improves how well AI shopping agents can match and recommend the item
9
+
10
+ import {
11
+ parseMoney, checkGtin, canonicalAvailability, OPENAI_AVAILABILITY, GOOGLE_AVAILABILITY,
12
+ isAbsoluteHttpUrl, parseBool, parseList, parseObject, PLACEHOLDERS, BRAND_PLACEHOLDERS,
13
+ } from './values.js';
14
+
15
+ const PROMO_RE = /\b(free shipping|free delivery|sale|on sale|\d+\s?% off|discount|best price|lowest price|cheapest|buy now|limited time|hot deal|clearance|offer ends|order now|shop now)\b/i;
16
+ const APPAREL_RE = /\b(apparel|clothing|clothes|shirt|t-shirt|tee|dress|jeans|trousers|pants|skirt|jacket|coat|hoodie|sweater|cardigan|shoe|shoes|sneaker|boot|sandal|kurta|shalwar|abaya|scarf|hat|cap|socks|underwear|bra|lingerie|swimwear|activewear)\b/i;
17
+ const SIZED_APPAREL_RE = /\b(clothing|clothes|shirt|t-shirt|tee|dress|jeans|trousers|pants|skirt|jacket|coat|hoodie|sweater|cardigan|shoe|shoes|sneaker|boot|sandal|kurta|shalwar|abaya|socks|underwear|bra|lingerie|swimwear|activewear)\b/i;
18
+ const MEDIA_RE = /\b(book|books|media|music|movie|movies|dvd|vinyl)\b/i;
19
+ const GOOGLE_APPAREL_COUNTRIES = new Set(['US', 'GB', 'UK', 'DE', 'FR', 'JP', 'BR']);
20
+ const BAD_COLOR_RE = /^(#?[0-9a-f]{3,8}|\d+|[a-z]|multi ?colou?r(ed)?|various|assorted|mixed|n\/?a|none|other|see (image|photo))$/i;
21
+
22
+ const BOTH = ['chatgpt', 'google'];
23
+
24
+ export function validateFeed(records, opts = {}) {
25
+ const channels = opts.channels || BOTH;
26
+ const defaults = opts.defaults || {};
27
+ const googleCountries = (opts.googleCountries || ['US']).map((c) => c.toUpperCase());
28
+ const issues = [];
29
+ const add = (rec, code, severity, chans, field, message, fix) => {
30
+ const ch = chans.filter((c) => channels.includes(c));
31
+ if (!ch.length) return;
32
+ issues.push({ code, severity, channels: ch, field, message, fix, item_id: rec?.item_id, row: rec?._row });
33
+ };
34
+
35
+ const ids = new Map();
36
+ const titleCounts = new Map();
37
+ const descCounts = new Map();
38
+ const groups = new Map();
39
+
40
+ for (const rec of records) {
41
+ const r = { ...defaults, ...stripUndefined(rec) };
42
+
43
+ // ---------- identity ----------
44
+ if (!r.item_id) add(rec, 'id-missing', 'error', BOTH, 'item_id', 'Missing item ID', 'Give every item or variant a stable, unique ID (your SKU works well).');
45
+ else {
46
+ ids.set(r.item_id, (ids.get(r.item_id) || 0) + 1);
47
+ if (String(r.item_id).length > 50) add(rec, 'id-too-long', 'error', ['google'], 'item_id', `ID is ${String(r.item_id).length} characters (Google max 50)`, 'Shorten the ID. Keep it stable once chosen.');
48
+ }
49
+
50
+ // ---------- title ----------
51
+ const title = r.title ? String(r.title) : '';
52
+ if (!title) add(rec, 'title-missing', 'error', BOTH, 'title', 'Missing title', 'Add the product name, including the variant (color, size) where relevant.');
53
+ else {
54
+ if (title.length > 150) {
55
+ add(rec, 'title-long', 'warning', ['chatgpt'], 'title', `Title is ${title.length} characters (aim for about 150)`, 'Put the most important words first and trim to about 150 characters.');
56
+ add(rec, 'title-long', 'error', ['google'], 'title', `Title is ${title.length} characters (Google max 150)`, 'Trim the title to 150 characters.');
57
+ }
58
+ const letters = title.replace(/[^A-Za-z]/g, '');
59
+ if (letters.length >= 10 && letters === letters.toUpperCase()) add(rec, 'title-caps', 'warning', BOTH, 'title', 'Title is written in capital letters', 'Use normal capitalization. All-caps titles are against Google policy and read as spam to shoppers.');
60
+ if (PROMO_RE.test(title)) add(rec, 'title-promo', 'warning', BOTH, 'title', `Title contains promotional text ("${PROMO_RE.exec(title)[0]}")`, 'Remove sales language from the title. Use sale_price and shipping fields for offers instead.');
61
+ titleCounts.set(title.toLowerCase(), (titleCounts.get(title.toLowerCase()) || 0) + 1);
62
+ }
63
+
64
+ // ---------- description ----------
65
+ const desc = r.description ? String(r.description) : '';
66
+ if (!desc) add(rec, 'description-missing', 'error', BOTH, 'description', 'Missing description', 'Write a plain-text, factual description: what it is, material, size, use, care.');
67
+ else {
68
+ if (desc.length > 5000) {
69
+ add(rec, 'description-long', 'warning', ['chatgpt'], 'description', `Description is ${desc.length} characters (aim for about 5,000)`, 'Trim to about 5,000 characters, keeping the facts.');
70
+ add(rec, 'description-long', 'error', ['google'], 'description', `Description is ${desc.length} characters (Google max 5,000)`, 'Trim to 5,000 characters.');
71
+ }
72
+ if (/<\/?[a-z][^>]*>/i.test(desc)) add(rec, 'description-html', 'warning', BOTH, 'description', 'Description contains HTML tags', 'Send plain text. Strip tags before export.');
73
+ if (/https?:\/\/|www\./i.test(desc)) add(rec, 'description-links', 'warning', ['google'], 'description', 'Description contains links', 'Remove links from the description; Google does not allow store links there.');
74
+ if (PROMO_RE.test(desc) && /\b(free shipping|% off|sale|discount|buy now|order now)\b/i.test(desc)) add(rec, 'description-promo', 'warning', ['google'], 'description', 'Description contains promotional text', 'Describe only the product. Move offers to sale_price and shipping fields.');
75
+ if (desc.length < 150) add(rec, 'description-thin', 'tip', BOTH, 'description', `Description is short (${desc.length} characters)`, 'AI shopping agents match on details. Add material, dimensions, use cases, care and what is included (300+ characters).');
76
+ if (title && desc.trim().toLowerCase() === title.trim().toLowerCase()) add(rec, 'description-equals-title', 'warning', BOTH, 'description', 'Description is the same as the title', 'Write a real description; repeating the title gives agents nothing to match on.');
77
+ descCounts.set(desc.toLowerCase().slice(0, 500), (descCounts.get(desc.toLowerCase().slice(0, 500)) || 0) + 1);
78
+ }
79
+
80
+ // ---------- links ----------
81
+ if (!r.url) add(rec, 'url-missing', 'error', BOTH, 'url', 'Missing product page URL', 'Add the full product page URL (https://...), with the variant selected if possible.');
82
+ else if (!isAbsoluteHttpUrl(r.url)) add(rec, 'url-invalid', 'error', BOTH, 'url', `URL is not an absolute http(s) URL: ${trunc(r.url)}`, 'Use the full URL, starting with https://');
83
+ else if (String(r.url).startsWith('http://')) add(rec, 'url-http', 'tip', ['chatgpt'], 'url', 'URL uses http, not https', 'Use https URLs.');
84
+
85
+ if (!r.image_url) add(rec, 'image-missing', 'error', BOTH, 'image_url', 'Missing main image URL', 'Add a direct link to the main product image (JPEG, PNG or WebP).');
86
+ else if (!isAbsoluteHttpUrl(r.image_url)) add(rec, 'image-invalid', 'error', BOTH, 'image_url', `Image URL is not an absolute http(s) URL: ${trunc(r.image_url)}`, 'Use the full public image URL.');
87
+ else if (/(placeholder|no[-_]?image|noimage|coming[-_]?soon|default[-_.]?(img|image|product))/i.test(r.image_url)) add(rec, 'image-placeholder', 'warning', BOTH, 'image_url', 'Main image looks like a placeholder', 'Use a real product photo. Placeholders get items disapproved on Google and look broken in AI answers.');
88
+ const extra = parseList(r.additional_image_urls);
89
+ if (extra === null) add(rec, 'additional-images-invalid', 'warning', ['chatgpt'], 'additional_image_urls', 'additional_image_urls is not a valid list', 'Use a JSON array, or commas between URLs (encode commas inside URLs as %2C).');
90
+ else {
91
+ if (extra.length > 10) add(rec, 'additional-images-many', 'warning', ['google'], 'additional_image_urls', `${extra.length} additional images (Google uses up to 10)`, 'Keep the 10 most useful images.');
92
+ if (extra.length === 0) add(rec, 'additional-images-none', 'tip', BOTH, 'additional_image_urls', 'No additional images', 'Add 2 to 5 more views (back, detail, in use). Visual answers in AI shopping use them.');
93
+ }
94
+
95
+ // ---------- brand ----------
96
+ const isMedia = MEDIA_RE.test(`${r.product_category || ''} ${r.product_type || ''}`);
97
+ if (!r.brand) {
98
+ add(rec, 'brand-missing', 'error', ['chatgpt'], 'brand', 'Missing brand (required by ChatGPT)', 'Use the brand shown on the product page. For your own products, your store brand is fine.');
99
+ if (!isMedia) add(rec, 'brand-missing', 'error', ['google'], 'brand', 'Missing brand (required for new products)', 'Add the brand. Do not use "Generic" or "N/A".');
100
+ } else {
101
+ if (BRAND_PLACEHOLDERS.has(String(r.brand).trim().toLowerCase())) add(rec, 'brand-placeholder', 'error', BOTH, 'brand', `Brand is a placeholder ("${r.brand}")`, 'Use a real brand name. If you make the product yourself, use your store brand.');
102
+ if (String(r.brand).length > 70) add(rec, 'brand-long', 'error', ['google'], 'brand', 'Brand is over 70 characters', 'Shorten the brand.');
103
+ }
104
+
105
+ // ---------- seller (ChatGPT) ----------
106
+ if (!r.seller_name) add(rec, 'seller-missing', 'error', ['chatgpt'], 'seller_name', 'Missing seller_name (required on every row)', 'Set seller_name to your store name (the CLI can fill it with --seller-name).');
107
+
108
+ // ---------- availability ----------
109
+ if (r.availability === undefined) add(rec, 'availability-missing', 'error', BOTH, 'availability', 'Missing availability', 'Use in_stock, out_of_stock, pre_order (ChatGPT) / preorder (Google), or backorder.');
110
+ else {
111
+ const raw = String(r.availability).trim();
112
+ const canon = canonicalAvailability(raw);
113
+ if (!OPENAI_AVAILABILITY.includes(raw)) {
114
+ add(rec, 'availability-invalid', 'error', ['chatgpt'], 'availability', `Availability "${raw}" is not a ChatGPT value (rows are rejected)`, canon ? `Use "${canon}".` : 'Use in_stock, out_of_stock, pre_order, backorder or unknown.');
115
+ }
116
+ if (!GOOGLE_AVAILABILITY.includes(raw)) {
117
+ const g = canon === 'pre_order' ? 'preorder' : canon === 'unknown' ? null : canon;
118
+ add(rec, 'availability-invalid', 'error', ['google'], 'availability', `Availability "${raw}" is not a Google value`, g ? `Use "${g}" in the Google feed.` : 'Google accepts in_stock, out_of_stock, preorder or backorder; "unknown" is not allowed.');
119
+ }
120
+ if ((canon === 'pre_order') && !r.availability_date) add(rec, 'availability-date-missing', 'error', ['google'], 'availability_date', 'Preorder item without availability_date', 'Add availability_date in ISO 8601 (for example 2027-01-15T00:00+05:00).');
121
+ if (canon === 'backorder' && !r.availability_date) add(rec, 'availability-date-missing', 'error', ['google'], 'availability_date', 'Backorder item without availability_date', 'Add the expected restock date in ISO 8601 (for example 2027-01-15T00:00+05:00). Google requires it for backorder.');
122
+ if (r.availability_date) {
123
+ const ad = String(r.availability_date).trim();
124
+ const t = Date.parse(ad);
125
+ if (!/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2})?(Z|[+-]\d{2}:?\d{2})?)?$/.test(ad) || Number.isNaN(t)) add(rec, 'availability-date-invalid', 'error', ['google'], 'availability_date', `availability_date "${trunc(ad, 30)}" is not ISO 8601`, 'Use YYYY-MM-DDThh:mm with a time zone, for example 2027-01-15T00:00+05:00.');
126
+ else if (t > Date.now() + 366 * 864e5) add(rec, 'availability-date-too-far', 'warning', ['google'], 'availability_date', 'availability_date is more than a year ahead', 'Google accepts dates up to one year in the future.');
127
+ }
128
+ }
129
+
130
+ // ---------- price ----------
131
+ const price = parseMoney(r.price);
132
+ if (!r.price) add(rec, 'price-missing', 'error', BOTH, 'price', 'Missing price', 'Add the regular price as "amount CURRENCY", for example 2500.00 PKR.');
133
+ else if (!price.ok) {
134
+ add(rec, 'price-format', 'error', BOTH, 'price', `Price "${r.price}" ${price.problems.join('; ')}`, price.suggestion ? `Write it as "${price.suggestion}".` : 'Use "amount CURRENCY", for example 79.99 USD.');
135
+ }
136
+ if (r.sale_price) {
137
+ const sale = parseMoney(r.sale_price);
138
+ if (!sale.ok) add(rec, 'sale-price-format', 'warning', BOTH, 'sale_price', `Sale price "${r.sale_price}" ${sale.problems.join('; ')}`, sale.suggestion ? `Write it as "${sale.suggestion}".` : 'Use "amount CURRENCY".');
139
+ // Compare whenever both amounts could be read, even if a format problem was reported above.
140
+ if (Number.isFinite(sale.amount) && Number.isFinite(price.amount) && sale.currency && price.currency) {
141
+ if (sale.currency !== price.currency) add(rec, 'sale-price-currency', 'warning', BOTH, 'sale_price', 'Sale price uses a different currency than price', 'Use the same currency; otherwise the sale price is ignored.');
142
+ else if (sale.amount >= price.amount) add(rec, 'sale-price-not-lower', 'warning', BOTH, 'sale_price', `Sale price (${r.sale_price}) is not lower than price (${r.price})`, 'price is the regular price and sale_price the lower current price. If there is no sale, leave sale_price empty.');
143
+ }
144
+ }
145
+
146
+ // ---------- identifiers ----------
147
+ let gtinOk = false;
148
+ if (r.gtin) {
149
+ const g = checkGtin(r.gtin);
150
+ if (g.problems.length) add(rec, 'gtin-invalid', g.problems.every((p) => p.includes('spaces')) ? 'warning' : 'error', ['chatgpt'], 'gtin', `GTIN ${trunc(r.gtin)} ${g.problems.join('; ')}`, g.problems.every((p) => p.includes('spaces')) ? `Send it as ${g.cleaned}.` : 'Use the barcode number printed on the product (GS1). If the product has none, leave gtin empty; never invent one.');
151
+ if (g.googleProblems.length) add(rec, 'gtin-invalid', 'error', ['google'], 'gtin', `GTIN ${trunc(r.gtin)} ${g.googleProblems.join('; ')}`, 'Submit only real GS1 GTINs. An incorrect GTIN gets the product disapproved.');
152
+ gtinOk = !g.problems.filter((p) => !p.includes('spaces')).length && !g.googleProblems.length;
153
+ }
154
+ if (r.mpn && String(r.mpn).length > 70) add(rec, 'mpn-long', 'error', ['google'], 'mpn', 'MPN is over 70 characters', 'Use the manufacturer part number only.');
155
+ const idExists = r.identifier_exists !== undefined ? String(r.identifier_exists).toLowerCase() : undefined;
156
+ if (idExists === 'no' || idExists === 'false') {
157
+ if (r.gtin) add(rec, 'identifier-exists-conflict', 'error', ['google'], 'identifier_exists', 'identifier_exists is "no" but a GTIN is given', 'Remove identifier_exists=no when the product has a GTIN.');
158
+ } else if (!r.gtin && !(r.mpn && r.brand)) {
159
+ add(rec, 'identifiers-missing', 'warning', BOTH, 'gtin', 'No GTIN, and no MPN with brand', 'Add the GTIN if the product has a barcode. For handmade or own-brand items without one, set identifier_exists to "no" (Google). Never invent identifiers: real ones help Google and ChatGPT match shopper questions to your product.');
160
+ }
161
+
162
+ // ---------- condition ----------
163
+ if (r.condition !== undefined && !['new', 'refurbished', 'used'].includes(String(r.condition).toLowerCase())) add(rec, 'condition-invalid', 'error', BOTH, 'condition', `Condition "${r.condition}" is not new, refurbished or used`, 'Use new, refurbished or used.');
164
+
165
+ // ---------- apparel and attributes ----------
166
+ const catText = `${r.product_category || ''} ${r.product_type || ''} ${title}`;
167
+ const apparel = APPAREL_RE.test(catText);
168
+ const googleApparelMarket = googleCountries.some((c) => GOOGLE_APPAREL_COUNTRIES.has(c));
169
+ if (apparel && googleApparelMarket) {
170
+ const needSize = SIZED_APPAREL_RE.test(catText) && !/clothing accessories|handbags|jewel(le)?ry/i.test(catText);
171
+ for (const f of ['color', 'gender', 'age_group', 'size']) {
172
+ if (f === 'size' && !needSize) continue;
173
+ if (!r[f] && !(f === 'size' && hasVariantKey(r, 'size')) && !(f === 'color' && hasVariantKey(r, 'colou?r'))) {
174
+ add(rec, `apparel-${f}-missing`, 'error', ['google'], f, `Apparel item missing ${f} (Google requires it for apparel${f === 'size' ? ' in clothing and shoe categories' : ''} in ${googleCountries.join(', ')})`, APPAREL_FIX[f]);
175
+ }
176
+ }
177
+ }
178
+ if (r.color && BAD_COLOR_RE.test(String(r.color).trim())) add(rec, 'color-invalid', 'warning', ['google'], 'color', `Color "${r.color}" is not a color name`, 'Use real color names; separate multiple colors with "/", primary first.');
179
+ if (r.gender && !['male', 'female', 'unisex'].includes(String(r.gender).toLowerCase())) add(rec, 'gender-invalid', 'error', BOTH, 'gender', `Gender "${r.gender}" is not male, female or unisex`, 'Use male, female or unisex.');
180
+ if (r.age_group && !['newborn', 'infant', 'toddler', 'kids', 'adult'].includes(String(r.age_group).toLowerCase())) add(rec, 'age-group-invalid', 'error', BOTH, 'age_group', `Age group "${r.age_group}" is not valid`, 'Use newborn, infant, toddler, kids or adult.');
181
+ if (!r.product_category) add(rec, 'category-missing', 'tip', BOTH, 'product_category', 'No product category', 'Add a category path such as "Apparel & Accessories > Clothing > Dresses". It helps agents place the item.');
182
+ if (r.weight && !r.item_weight_unit) add(rec, 'weight-unit-missing', 'warning', ['chatgpt'], 'item_weight_unit', 'weight given without item_weight_unit', 'Add g, kg, oz or lb.');
183
+
184
+ // ---------- dimensions (OpenAI) ----------
185
+ const DIM_UNITS = ['in', 'cm', 'ft', 'm', 'mm'];
186
+ const posDec = (v) => /^\d+(\.\d+)?$/.test(String(v).trim()) && Number(v) > 0;
187
+ if (r.dimensions !== undefined) {
188
+ const d = parseObject(r.dimensions);
189
+ const sides = d ? ['length', 'width', 'height'].filter((k) => d[k] !== undefined) : [];
190
+ const extra = d ? Object.keys(d).filter((k) => !['length', 'width', 'height', 'unit'].includes(k)) : [];
191
+ if (!d) add(rec, 'dimensions-invalid', 'error', ['chatgpt'], 'dimensions', 'dimensions is not a JSON object', 'Use an object such as {"length":"30","width":"20","unit":"cm"}.');
192
+ else if (sides.length < 2 || sides.some((k) => !posDec(d[k])) || !DIM_UNITS.includes(String(d.unit)) || extra.length) add(rec, 'dimensions-invalid', 'error', ['chatgpt'], 'dimensions', 'dimensions needs at least two positive values (length, width, height) and a unit (in, cm, ft, m or mm), with no other keys', 'Example: {"length":"30","width":"20","height":"5","unit":"cm"}. Values are strings with a decimal point, no units inside.');
193
+ } else if (['length', 'width', 'height'].some((k) => r[k] !== undefined)) {
194
+ if (!r.dimensions_unit) add(rec, 'dimensions-unit-missing', 'warning', ['chatgpt'], 'dimensions_unit', 'length, width or height given without dimensions_unit', 'Add dimensions_unit (in, cm, ft, m or mm), or switch to the dimensions object that new feeds should use.');
195
+ for (const k of ['length', 'width', 'height']) if (r[k] !== undefined && !posDec(r[k])) add(rec, 'dimension-value-invalid', 'error', ['chatgpt'], k, `${k} "${r[k]}" is not a positive number`, 'Use a plain decimal such as 30 or 12.5, with the unit in dimensions_unit.');
196
+ }
197
+ if (r.dimensions_unit !== undefined && !DIM_UNITS.includes(String(r.dimensions_unit))) add(rec, 'dimensions-unit-invalid', 'error', ['chatgpt'], 'dimensions_unit', `dimensions_unit "${r.dimensions_unit}" is not in, cm, ft, m or mm`, 'Use in, cm, ft, m or mm.');
198
+
199
+ // ---------- variants ----------
200
+ const lhv = parseBool(r.listing_has_variations);
201
+ const vd = parseObject(r.variant_dict);
202
+ if (r.variant_dict !== undefined && vd === null) add(rec, 'variant-dict-invalid', 'error', ['chatgpt'], 'variant_dict', 'variant_dict is not a JSON object', 'Use an object such as {"color":"Black","size":"M"}.');
203
+ if (vd && Object.entries(vd).some(([k, v]) => !String(k).trim() || !String(v).trim())) add(rec, 'variant-dict-empty-values', 'error', ['chatgpt'], 'variant_dict', 'variant_dict has empty keys or values', 'Every option name and value must be non-empty.');
204
+ if (r.group_id && r.item_id && String(r.group_id) === String(r.item_id) && (lhv === true || vd)) add(rec, 'group-equals-item', 'error', ['chatgpt'], 'group_id', 'group_id is the same as item_id, so variants are not grouped', 'Use the parent product ID as group_id, shared by all variants.');
205
+ if (vd && lhv !== true) add(rec, 'variants-flag-missing', 'warning', ['chatgpt'], 'listing_has_variations', 'variant_dict given but listing_has_variations is not true', 'Set listing_has_variations to true on every variant row, or the options are ignored.');
206
+ if (r.group_id) groups.set(r.group_id, [...(groups.get(r.group_id) || []), r]);
207
+
208
+ // ---------- geo (ChatGPT) ----------
209
+ const tc = parseList(r.target_countries);
210
+ if (!tc || !tc.length) add(rec, 'target-countries-missing', 'error', ['chatgpt'], 'target_countries', 'Missing target_countries', 'Set target_countries (for example ["US"]). The CLI can fill it with --country.');
211
+ else if (tc.every((c) => /^[A-Z]{2}$/.test(c)) && tc.some((c) => !CHATGPT_FEED_COUNTRIES.includes(c))) add(rec, 'target-countries-coverage', 'tip', ['chatgpt'], 'target_countries', `ChatGPT product feeds currently cover ${CHATGPT_FEED_COUNTRIES.join(', ')}; ${tc.filter((c) => !CHATGPT_FEED_COUNTRIES.includes(c)).join(', ')} may not be served yet`, 'Keep the countries you sell to, but check the OpenAI product feed spec for current coverage before relying on other markets.');
212
+ else if (tc.some((c) => !/^[A-Z]{2}$/.test(c))) add(rec, 'target-countries-invalid', 'error', ['chatgpt'], 'target_countries', `target_countries has invalid codes: ${tc.join(', ')}`, 'Use uppercase ISO 3166-1 alpha-2 codes, such as US.');
213
+ if (!r.store_country) add(rec, 'store-country-missing', 'error', ['chatgpt'], 'store_country', 'Missing store_country', "Set your store's country code (the CLI can fill it with --store-country).");
214
+
215
+ // ---------- flags and checkout (ChatGPT) ----------
216
+ for (const f of ['is_eligible_search', 'is_eligible_checkout', 'listing_has_variations', 'accepts_returns']) {
217
+ if (parseBool(r[f]) === 'invalid') add(rec, `${f}-invalid`, 'error', ['chatgpt'], f, `${f} must be true or false (got "${r[f]}")`, 'Use lowercase true or false.');
218
+ }
219
+ if (parseBool(r.is_eligible_checkout) === true) {
220
+ if (parseBool(r.is_eligible_search) === false) add(rec, 'checkout-without-search', 'error', ['chatgpt'], 'is_eligible_checkout', 'Checkout is enabled but search is disabled', 'Search must be enabled for checkout to work.');
221
+ if (!r.seller_privacy_policy) add(rec, 'checkout-privacy-missing', 'error', ['chatgpt'], 'seller_privacy_policy', 'Checkout enabled without seller_privacy_policy', 'Add the public URL of your privacy policy.');
222
+ if (!r.seller_tos) add(rec, 'checkout-tos-missing', 'error', ['chatgpt'], 'seller_tos', 'Checkout enabled without seller_tos', 'Add the public URL of your terms of service.');
223
+ }
224
+
225
+ // ---------- returns, shipping, reviews ----------
226
+ const ar = parseBool(r.accepts_returns);
227
+ if (r.return_deadline_in_days !== undefined && ar !== true) add(rec, 'return-window-without-returns', 'warning', ['chatgpt'], 'return_deadline_in_days', 'Return window given but accepts_returns is not true', 'Set accepts_returns to true, or the window is ignored.');
228
+ if (r.return_deadline_in_days !== undefined && !/^[1-9]\d*$/.test(String(r.return_deadline_in_days))) add(rec, 'return-window-invalid', 'error', ['chatgpt'], 'return_deadline_in_days', 'return_deadline_in_days must be a positive whole number', 'Use a number of days, such as 7 or 30.');
229
+ if (ar === undefined && !r.return_policy) add(rec, 'returns-missing', 'tip', ['chatgpt'], 'accepts_returns', 'No return information', 'Add accepts_returns, return_deadline_in_days and return_policy. Shoppers ask agents about returns before buying.');
230
+ if (r.shipping_price && r.shipping) add(rec, 'shipping-both', 'warning', ['chatgpt'], 'shipping', 'Both shipping_price and shipping are set', 'Send one of them for the same charge.');
231
+ if (!r.shipping_price && !r.shipping) add(rec, 'shipping-missing', 'tip', BOTH, 'shipping', 'No shipping cost information', 'Add shipping cost (or set it in Merchant Center). Omitted shipping is treated as unknown, not free.');
232
+ if (r.star_rating !== undefined) {
233
+ const sr = Number(r.star_rating);
234
+ if (!(sr >= 0 && sr <= 5)) add(rec, 'star-rating-invalid', 'error', ['chatgpt'], 'star_rating', `star_rating ${r.star_rating} is outside 0-5`, 'Use a 0 to 5 rating with up to two decimals.');
235
+ if (!(Number(r.review_count) > 0)) add(rec, 'star-rating-without-reviews', 'warning', ['chatgpt'], 'review_count', 'star_rating given without a positive review_count', 'Add review_count, or omit the rating.');
236
+ }
237
+
238
+ // ---------- placeholders anywhere ----------
239
+ for (const [k, v] of Object.entries(r)) {
240
+ if (k.startsWith('_') || k === 'availability' || typeof v !== 'string') continue;
241
+ if (PLACEHOLDERS.has(v.trim().toLowerCase()) && !['review_count', 'star_rating', 'return_deadline_in_days', 'shipping_price', 'weight'].includes(k)) {
242
+ add(rec, 'placeholder-value', 'warning', ['chatgpt'], k, `${k} contains a placeholder ("${v}")`, 'Leave the field empty instead of writing placeholder text.');
243
+ }
244
+ }
245
+ if (rec._status && rec._status !== 'active') add(rec, 'not-active', 'warning', BOTH, 'status', `Product status is "${rec._status}"`, 'Only active, purchasable products should be in the feed.');
246
+ }
247
+
248
+ // ---------- feed-level ----------
249
+ for (const [id, n] of ids) if (n > 1) add({ item_id: id }, 'id-duplicate', 'error', BOTH, 'item_id', `ID "${id}" is used by ${n} items`, 'IDs must be unique per item or variant.');
250
+ for (const [t, n] of titleCounts) {
251
+ if (n > 1) {
252
+ const sample = records.find((x) => String(x.title || '').toLowerCase() === t);
253
+ if (!sample?.group_id) add(sample, 'title-duplicate', 'warning', BOTH, 'title', `${n} items share the title "${trunc(t, 60)}"`, 'Include the variant (color, size) in each title and group variants with group_id.');
254
+ }
255
+ }
256
+ for (const [d, n] of descCounts) if (n >= 3 && d.length > 30) add(null, 'description-duplicate', 'tip', BOTH, 'description', `${n} items share the same description ("${trunc(d, 50)}")`, 'Unique descriptions help agents tell products apart.');
257
+ for (const [gid, members] of groups) {
258
+ if (members.length > 1 && members.some((m) => parseBool(m.listing_has_variations) !== true)) add(members[0], 'group-flag-missing', 'warning', ['chatgpt'], 'listing_has_variations', `Group "${gid}" has ${members.length} items but not all set listing_has_variations=true`, 'Set listing_has_variations=true and a variant_dict on every variant row.');
259
+ }
260
+
261
+ return { issues, stats: computeStats(records, issues, channels) };
262
+ }
263
+
264
+ function computeStats(records, issues, channels) {
265
+ const perChannel = {};
266
+ for (const ch of channels) {
267
+ const errs = issues.filter((i) => i.severity === 'error' && i.channels.includes(ch));
268
+ const byRow = new Set(errs.filter((i) => i.row !== undefined).map((i) => `${i.item_id}|${i.row}`));
269
+ const byIdOnly = new Set(errs.filter((i) => i.row === undefined && i.item_id !== undefined).map((i) => String(i.item_id)));
270
+ const total = records.length;
271
+ const eligible = records.filter((r) => !byRow.has(`${r.item_id}|${r._row}`) && !byIdOnly.has(String(r.item_id))).length;
272
+ perChannel[ch] = { total, eligible, eligiblePct: total ? Math.round((eligible / total) * 100) : 0 };
273
+ }
274
+ // AI-matching richness: share of items carrying the attributes agents use to match questions
275
+ const attrs = ['gtin_or_mpn', 'product_category', 'rich_description', 'additional_images', 'color_or_size_or_material', 'returns', 'shipping', 'reviews'];
276
+ const has = {
277
+ gtin_or_mpn: (r) => !!(r.gtin || r.mpn),
278
+ product_category: (r) => !!r.product_category,
279
+ rich_description: (r) => String(r.description || '').length >= 300,
280
+ additional_images: (r) => (parseList(r.additional_image_urls) || []).length >= 2,
281
+ color_or_size_or_material: (r) => !!(r.color || r.size || r.material || r.variant_dict),
282
+ returns: (r) => r.accepts_returns !== undefined || !!r.return_policy,
283
+ shipping: (r) => !!(r.shipping_price || r.shipping),
284
+ reviews: (r) => Number(r.review_count) > 0,
285
+ };
286
+ const coverage = {};
287
+ for (const a of attrs) coverage[a] = records.length ? Math.round((records.filter(has[a]).length / records.length) * 100) : 0;
288
+ const richness = Math.round(attrs.reduce((s, a) => s + coverage[a], 0) / attrs.length);
289
+ return { items: records.length, perChannel, coverage, richness };
290
+ }
291
+
292
+ function hasVariantKey(r, pattern) {
293
+ const vd = parseObject(r.variant_dict);
294
+ return !!(vd && Object.keys(vd).some((k) => new RegExp(`^${pattern}$`, 'i').test(k)));
295
+ }
296
+ function stripUndefined(o) {
297
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
298
+ }
299
+ function trunc(s, n = 80) {
300
+ s = String(s);
301
+ return s.length > n ? s.slice(0, n - 1) + '…' : s;
302
+ }
303
+
304
+ // Countries the OpenAI shared feed format covers (product feed spec, checked December 2026).
305
+ export const CHATGPT_FEED_COUNTRIES = ['US', 'CA', 'MX'];
306
+
307
+ const APPAREL_FIX = {
308
+ color: 'Add color as the shopper sees it (for example "Navy"; use / for multicolor, "Red/White").',
309
+ gender: 'Add gender: male, female or unisex.',
310
+ age_group: 'Add age_group: newborn, infant, toddler, kids or adult.',
311
+ size: 'Add size as shown on the product page (for example "M" or "42").',
312
+ };
313
+
314
+ /** Group issues by severity + code, merging channels, so big catalogs stay readable.
315
+ * Each group keeps up to `perGroup` examples with their own message and fix.
316
+ * `uniform` is true when every item in the group has the same message and fix. */
317
+ export function groupIssues(issues, { perGroup = 3 } = {}) {
318
+ const map = new Map();
319
+ for (const i of issues) {
320
+ const key = `${i.severity}|${i.code}`;
321
+ if (!map.has(key)) map.set(key, { severity: i.severity, code: i.code, field: i.field, channels: new Set(), items: new Set(), count: 0, examples: [], itemIds: [], uniform: true, message: i.message, fix: i.fix });
322
+ const g = map.get(key);
323
+ i.channels.forEach((c) => g.channels.add(c));
324
+ const itemKey = `${i.item_id ?? ""}|${i.row ?? g.count}`;
325
+ if (!g.items.has(itemKey)) {
326
+ g.items.add(itemKey);
327
+ g.count++;
328
+ if (g.examples.length < perGroup) g.examples.push({ item_id: i.item_id, row: i.row, message: i.message, fix: i.fix });
329
+ if (g.itemIds.length < 8) g.itemIds.push(i.item_id ?? (i.row != null ? `row ${i.row}` : '(feed)'));
330
+ if (i.message !== g.message || i.fix !== g.fix) g.uniform = false;
331
+ }
332
+ }
333
+ const order = { error: 0, warning: 1, tip: 2 };
334
+ return [...map.values()]
335
+ .map((g) => ({ ...g, channels: [...g.channels], items: undefined }))
336
+ .sort((a, b) => order[a.severity] - order[b.severity] || b.count - a.count);
337
+ }