Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content-editor): give a category page its ItemList of the products it links (CE-054, part a) (#1499)
Cihan52f5fabb9ffb
diff --git a/web/messages/en.json b/web/messages/en.jsonindex b48323c78..193ef733a 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -4453,6 +4453,7 @@"quiet": "Before you publish has the author, dates and schema (JSON-LD) for your CMS.","quietOther": "Before you publish has the author and what your CMS adds for this page type.","quietProduct": "Before you publish has the Product schema (JSON-LD) with the page's price for your CMS.",+ "quietItemList": "Before you publish has the ItemList schema (JSON-LD) of the products the page links, for your CMS.","warnings": "Before you publish: {list}.","trust": "Trust {trust}, below 60","noAuthor": "no author yet",@@ -4616,6 +4617,13 @@"detailLive": "Often added by your CMS. If not, paste the code below into the page. It gives only the updated date: your page keeps the published date it has.","product": "Product schema with its price","productDetail": "Price read from the page: {price}. Check it's the product's. Often added by your shop's theme; if not, paste the code below into the page. Availability, SKU and reviews come from a product feed, once one is connected.",+ "itemList": "ItemList schema with {count, plural, one {# product} other {# products}}",+ "itemListDetail": "Often added by your shop's theme on a collection page. If not, paste the code below into the page. Each product's price and stock go in its own page's Product schema.",+ "itemListNone": "ItemList schema needs links to your products",+ "itemListNoneDetail": "{count, plural, =0 {Ansvisor finds no links to your product pages here} one {Ansvisor finds one link to your product pages here} other {Ansvisor finds # links to your product pages here}} (/products/…, /product/…): link at least two of the products it lists to their own pages on your site, and the code lists them in the page's order.",+ "itemListTitle": "ItemList schema",+ "itemListReading": "Reading the page's links to your product pages…",+ "itemListUnknown": "Your brand's domains couldn't be read, so its product links can't be told: check the ItemList your CMS adds.","productNoName": "Product schema needs the product's name","productNoNameDetail": "The title is empty or still has a placeholder in square brackets: write the product's name there. Without it, search engines show no product result.","productNoPrice": "Product schema needs the price",@@ -4623,7 +4631,8 @@"productSeveral": "Product schema needs one price","productSeveralDetail": "The page states more than one price ({prices}), so the code doesn't guess which is the product's. Write its price once, or its range as one (\"$119–$139\"), or connect your product feed.","other": "Schema for this page type",- "otherDetail": "Check what your CMS adds for it (Product, ItemList…). The code Ansvisor gives here is for articles."+ "otherDetail": "Check what your CMS adds for it (Product, ItemList…). The code Ansvisor gives here is for articles.",+ "otherDetailTyped": "Check what your CMS adds for it. The code Ansvisor gives here is for articles, product pages and category pages."},"disclosure": {"ok": "Disclosure",@@ -4641,7 +4650,9 @@"pageReading": "Still reading the page for claims that need your proof, so your to-dos may change.","productNote": "The price, its currency and the images are the page's own (a \"$\" reads as US dollars): check they match your shop before you paste it.","datesNote": "The dates are today's: change them if the page goes out on another day.",+ "itemListNote": "The products are the page's links to your product pages, in its order: check the list before you paste it.","headlineLeftOut": "The title still has a placeholder in square brackets, so the code leaves the headline out. Fill it in, and the headline comes back here.",+ "nameLeftOut": "The title still has a placeholder in square brackets, so the code leaves the list's name out. Fill it in, and the name comes back here.","states": {"ok": "done","check": "check it",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsxindex 2f9e0c651..6e94f9144 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx@@ -105,6 +105,7 @@ async function render(disclosureLine = null as string | null,disclosureAdded = false,product = null as Parameters<typeof BeforePublish>[0]['product'],+ category = null as Parameters<typeof BeforePublish>[0]['category'],} = {},) {await act(async () => {@@ -124,6 +125,7 @@ async function render(image={image}linksPending={linksPending}product={product}+ category={category}onMarkReady={onMarkReady}onFixFirst={onFixFirst}disclosureLine={disclosureLine}@@ -331,6 +333,66 @@ describe('BeforePublish', () => {expect(rows().some((row) => row.includes('without a disclosure'))).toBe(false);});+ it('gives a category page its ItemList of the products it links, and asks for two links where it has fewer (CE-054)', async () => {+ const items = [+ { url: 'https://acme.com/products/ridge-28', name: 'Ridge 28' },+ { url: 'https://acme.com/products/ridge-32', name: 'Ridge 32' },+ ];+ await render(quality(), {+ pageType: 'category_page',+ title: 'Daypacks',+ category: { items, status: 'read' },+ });+ expect(rows().some((row) => row.startsWith('ItemList schema with 2 products'))).toBe(true);+ expect(jsonLd()).toMatchObject({+ '@type': 'ItemList',+ name: 'Daypacks',+ numberOfItems: 2,+ itemListElement: [+ { position: 1, url: 'https://acme.com/products/ridge-28', name: 'Ridge 28' },+ { position: 2, url: 'https://acme.com/products/ridge-32', name: 'Ridge 32' },+ ],+ });+ expect(dialog().textContent).toContain(+ "The products are the page's links to your product pages",+ );+ // One product: no list, and it says what to link.+ await render(quality(), {+ pageType: 'category_page',+ title: 'Daypacks',+ category: { items: items.slice(0, 1), status: 'read' },+ });+ expect(+ rows().find((row) => row.startsWith('ItemList schema needs links to your products')),+ ).toContain('Ansvisor finds one link to your product pages here');+ expect(dialog().querySelector('pre')).toBeNull();+ // The brand's domains not read yet, or not read at all: no "none" said.+ await render(quality(), {+ pageType: 'category_page',+ title: 'Daypacks',+ category: { items: [], status: 'reading' },+ });+ expect(rows().find((row) => row.startsWith('ItemList schema'))).toContain(+ "Reading the page's links to your product pages",+ );+ await render(quality(), {+ pageType: 'category_page',+ title: 'Daypacks',+ category: { items: [], status: 'unknown' },+ });+ expect(rows().find((row) => row.startsWith('ItemList schema'))).toContain(+ "Your brand's domains couldn't be read",+ );+ // A placeholder in the title: the list's name is left out, and it says so.+ await render(quality(), {+ pageType: 'category_page',+ title: '[category name] daypacks',+ category: { items, status: 'read' },+ });+ expect(jsonLd()).not.toHaveProperty('name');+ expect(dialog().textContent).toContain("so the code leaves the list's name out");+ });+it('gives a product page its Product schema with the price it states, and asks for one it doesn’t (CE-053)', async () => {const product = {description: 'A daypack for wet hikes.',diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsxindex 8f75d2207..886324746 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx@@ -14,7 +14,10 @@ import {import {articleJsonLd,isArticlePage,+ itemListJsonLd,+ MIN_LISTED,productJsonLd,+ type ListedProduct,type PageOfferRead,jsonLdScript,localDate,@@ -22,6 +25,7 @@ import {pageName,titleHasPlaceholder,} from '@/lib/content/page-schema';+import { qualityPhase } from '@/lib/content/quality';import { checksOff } from '@/lib/content/quality-profiles';import { cn } from '@/lib/utils';import { copyToClipboard } from './_html-block';@@ -95,6 +99,7 @@ export function BeforePublish({disclosureAdded = false,onAddDisclosure,product = null,+ category = null,}: {/*** Phase 3 (CE-053): a product page's Product schema, from its opening@@ -102,6 +107,11 @@ export function BeforePublish({* other pages.*/product?: { description: string | null; images: string[]; offer: PageOfferRead } | null;+ /**+ * Phase 3 (CE-054): a category page's ItemList, from its links to the+ * brand's product pages (listedProducts); null on other pages.+ */+ category?: { items: ListedProduct[]; status: 'read' | 'reading' | 'unknown' } | null;/** Opened by Mark ready, by Export, or by Send to CMS. */mode?: 'markReady' | 'export' | 'send';paste: ReadyToPaste;@@ -156,7 +166,7 @@ export function BeforePublish({.filter((s) => s.gain > 0).sort((a, b) => b.gain - a.gain): [];- const article = !product && isArticlePage(pageType);+ const article = !product && !category && isArticlePage(pageType);// Product needs its name and price: without either, no code to paste.const productName = pageName(title);const offer = product?.offer && !('several' in product.offer) ? product.offer : null;@@ -173,26 +183,34 @@ export function BeforePublish({offer,}),);+ // An ItemList lists two products at least: one isn't a list.+ const itemListLd =+ category?.status === 'read' &&+ category.items.length >= MIN_LISTED &&+ jsonLdScript(itemListJsonLd({ name: productName, items: category.items }));const jsonLd = productLd? productLd- : article- ? jsonLdScript(- articleJsonLd({- title,- // An author only confirmed (00271) isn't named here: left out, as unknown.- author: authorsRead && !(!author && quality.authorConfirmed?.real) ? author : undefined,- authorUrl:- (author &&- siteTrust?.checks.authorPages.authors.find((a) => a.name === author.name)?.url) ||- null,- brandName,- brandUrl: siteTrust?.checks.organizationSchema.url ?? null,- image,- isNew,- today: localDate(new Date()),- }),- )- : null;+ : itemListLd+ ? itemListLd+ : article+ ? jsonLdScript(+ articleJsonLd({+ title,+ // An author only confirmed (00271) isn't named here: left out, as unknown.+ author:+ authorsRead && !(!author && quality.authorConfirmed?.real) ? author : undefined,+ authorUrl:+ (author &&+ siteTrust?.checks.authorPages.authors.find((a) => a.name === author.name)?.url) ||+ null,+ brandName,+ brandUrl: siteTrust?.checks.organizationSchema.url ?? null,+ image,+ isNew,+ today: localDate(new Date()),+ }),+ )+ : null;// Added here: it counts once the page is read again.const [added, setAdded] = useState(false);// Where the page's type counts it (CE-052): a product page is the brand's own.@@ -264,18 +282,49 @@ export function BeforePublish({},]),]- : article+ : category? [- { state: 'check' as const, title: t('dates.title'), detail: t('dates.detail') },- isNew- ? { state: 'check' as const, title: t('schema.title'), detail: t('schema.detail') }- : {+ category.status !== 'read'+ ? {state: 'check' as const,- title: t('schema.titleLive'),- detail: t('schema.detailLive'),- },+ title: t('schema.itemListTitle'),+ detail: t(+ category.status === 'reading'+ ? 'schema.itemListReading'+ : 'schema.itemListUnknown',+ ),+ }+ : itemListLd+ ? {+ state: 'check' as const,+ title: t('schema.itemList', { count: category.items.length }),+ detail: t('schema.itemListDetail'),+ }+ : {+ state: 'missing' as const,+ title: t('schema.itemListNone'),+ detail: t('schema.itemListNoneDetail', { count: category.items.length }),+ },]- : [{ state: 'check' as const, title: t('schema.other'), detail: t('schema.otherDetail') }]),+ : article+ ? [+ { state: 'check' as const, title: t('dates.title'), detail: t('dates.detail') },+ isNew+ ? { state: 'check' as const, title: t('schema.title'), detail: t('schema.detail') }+ : {+ state: 'check' as const,+ title: t('schema.titleLive'),+ detail: t('schema.detailLive'),+ },+ ]+ : [+ {+ state: 'check' as const,+ title: t('schema.other'),+ // Phase 3 gives product and category pages their code too.+ detail: t(qualityPhase() >= 3 ? 'schema.otherDetailTyped' : 'schema.otherDetail'),+ },+ ]),// Phase 2 (CE-050): where the page puts the brand forward....(disclosure? [@@ -426,11 +475,13 @@ export function BeforePublish({>{jsonLd}</pre>- {titleHasPlaceholder(title) && (- <p className="text-xs text-amber-700 dark:text-amber-300">{t('headlineLeftOut')}</p>+ {(article || itemListLd) && titleHasPlaceholder(title) && (+ <p className="text-xs text-amber-700 dark:text-amber-300">+ {t(itemListLd ? 'nameLeftOut' : 'headlineLeftOut')}+ </p>)}<p className="text-xs text-muted-foreground">- {t(productLd ? 'productNote' : 'datesNote')}+ {t(productLd ? 'productNote' : itemListLd ? 'itemListNote' : 'datesNote')}</p></div>)}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex 0ceefa217..1deeaefce 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx@@ -98,6 +98,8 @@ import {openingParagraph,pageName,pageOffer,+ listedProducts,+ MIN_LISTED,} from '@/lib/content/page-schema';import { PLACEHOLDER, pagePlaceholders, placeholderIn } from '@/lib/content/placeholders';import { HANDOFF_KEYS, handOffItems } from '@/lib/content/hand-off';@@ -135,6 +137,7 @@ import {} from '@/lib/content/quality-profiles';import { caseConfirmed, caseKey, proofKey, qualityTodos } from '@/lib/content/quality-todos';import { isByline, readability, sentencesOf, withTypeRules } from '@/lib/content/readability';+import { normalizeDomain } from '@/lib/citations/classify';import { brandFactsPath, factMismatches } from '@/lib/content/brand-facts';import { feedCheck, type CatalogMatch } from '@/lib/content/feed-match';import {@@ -1005,6 +1008,20 @@ export function DraftEditor({offer: pageOffer(pageBlocks.map((block) => block.text)),};}, [profile, images, ownImages, pageHtml, pageBlocks]);+ // Phase 3 (CE-054): a category page's ItemList in Before you publish, from+ // its links to the brand's product pages, read against its site.+ // The brand's domains as the sources read them; failing that, its site's.+ const sourcesFailed = !!reads.sources?.failed;+ const categorySchema = useMemo(() => {+ if (profile !== 'category') return null;+ const site = siteTrust?.checks.organizationSchema.url ?? null;+ const siteHost = site ? normalizeDomain(site) : '';+ const domains = brandDomains ?? (sourcesFailed && siteHost ? [siteHost] : null);+ if (!domains) {+ return { items: [], status: sourcesFailed ? ('unknown' as const) : ('reading' as const) };+ }+ return { items: listedProducts(pageHtml, domains, site), status: 'read' as const };+ }, [profile, pageHtml, brandDomains, sourcesFailed, siteTrust]);// The page's price, GTIN and stock against its product in the feed (CE-053).const feedRead = useMemo(() =>@@ -3564,6 +3581,8 @@ export function DraftEditor({// Only where Before you publish has its code: a name and one price.product:!!productSchema?.offer && !('several' in productSchema.offer) && !!pageName(title),+ itemList:+ categorySchema?.status === 'read' && categorySchema.items.length >= MIN_LISTED,onReview: () => {setExportOpen(null);openBeforePublish('export', exportOpen.destination);@@ -3617,6 +3636,7 @@ export function DraftEditor({disclosureAdded={disclosureOnPage}onAddDisclosure={addLineUnderAnswer}product={productSchema}+ category={categorySchema}onMarkReady={(anyway) => {setPublishOpen(null);void markReady(anyway ?? undefined);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.test.tsxindex c1d257a20..2c7c3b24e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.test.tsx@@ -153,6 +153,13 @@ describe('ExportDialog', () => {expect(dialog().textContent).toContain("Before you publish has the Product schema (JSON-LD) with the page's price for your CMS.Review",);+ // A category page (CE-054): its ItemList.+ await render({+ publish: { trustBelow: null, noAuthor: false, article: false, itemList: true, onReview },+ });+ expect(dialog().textContent).toContain(+ 'Before you publish has the ItemList schema (JSON-LD) of the products the page links, for your CMS.Review',+ );});it('holds the export while a placeholder is open, and fills it or leaves its sentence out', async () => {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.tsxindex bbaa51675..5c2c61cab 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_export-dialog.tsx@@ -208,6 +208,8 @@ export function ExportDialog({article: boolean;/** A product page (Phase 3, CE-053): Before you publish has its Product JSON-LD. */product?: boolean;+ /** A category page (Phase 3, CE-054): Before you publish has its ItemList JSON-LD. */+ itemList?: boolean;onReview: () => void;} | null;}) {@@ -639,6 +641,7 @@ function PublishLine({noDisclosure = false,article,product = false,+ itemList = false,onReview,}: {trustBelow: number | null;@@ -646,6 +649,7 @@ function PublishLine({noDisclosure?: boolean;article: boolean;product?: boolean;+ itemList?: boolean;onReview: () => void;}) {const t = useTranslations('contentEditor.editor.exportDialog.publish');@@ -667,7 +671,15 @@ function PublishLine({<p className="min-w-0 flex-1">{warnings.length? t('warnings', { list: warnings.join(' · ') })- : t(article ? 'quiet' : product ? 'quietProduct' : 'quietOther')}+ : t(+ article+ ? 'quiet'+ : product+ ? 'quietProduct'+ : itemList+ ? 'quietItemList'+ : 'quietOther',+ )}</p><Buttonvariant="outline"diff --git a/web/src/lib/content/page-schema.test.ts b/web/src/lib/content/page-schema.test.tsindex 1afaa7d8d..84a13add6 100644--- a/web/src/lib/content/page-schema.test.ts+++ b/web/src/lib/content/page-schema.test.ts@@ -4,7 +4,9 @@ import {articleJsonLd,firstImage,isArticlePage,+ itemListJsonLd,jsonLdScript,+ listedProducts,localDate,pageName,titleHasPlaceholder,@@ -399,3 +401,82 @@ describe('productJsonLd', () => {});});});++describe('listedProducts (Phase 3, CE-054)', () => {+ it('reads the page’s links to the brand’s product pages, in order, each once, with their names', () => {+ const html =+ '<h1>Daypacks</h1>' ++ '<ul><li><a href="https://www.acme.com/products/ridge-28?variant=1">Ridge 28</a></li>' ++ '<li><a href="/products/ridge-32#specs">Ridge 32</a></li>' ++ // The same products again: another form of the address, a collection's path.+ '<li><a href="https://acme.com/products/ridge-28/">Ridge 28 again</a></li>' ++ '<li><a href="/collections/daypacks/products/ridge-32">Ridge 32 again</a></li>' ++ '<li><a href="https://shop.acme.com/urun/kanyon"><img src="https://cdn.acme.com/k.jpg" alt="Kanyon"></a></li>' ++ '<li><a href="/product-page/summit">Summit</a></li></ul>' ++ // Another site's product (one that only starts like the brand's too), a+ // collection, a post, an image, a product's sub-page.+ '<p><a href="https://rival.com/products/peak">Peak</a> · <a href="https://acme.com.evil.com/products/x">X</a> · ' ++ '<a href="/collections/daypacks">All</a> · <a href="/blog/how-to-pack">Packing</a> · ' ++ '<a href="https://news.acme.com/p/how-to-pack">Post</a> · <a href="/cdn/shop/products/ridge.jpg">Photo</a> · ' ++ '<a href="/products/ridge-28/reviews">See 24 reviews</a></p>';+ expect(listedProducts(html, ['acme.com'], 'https://acme.com')).toEqual([+ { url: 'https://www.acme.com/products/ridge-28', name: 'Ridge 28' },+ { url: 'https://acme.com/products/ridge-32', name: 'Ridge 32' },+ { url: 'https://shop.acme.com/urun/kanyon', name: 'Kanyon' },+ { url: 'https://acme.com/product-page/summit', name: 'Summit' },+ ]);+ // A relative link with no site read: against the brand's first domain; none at all, left out.+ expect(listedProducts('<a href="/products/x">X</a>', ['acme.com'], null)).toEqual([+ { url: 'https://acme.com/products/x', name: 'X' },+ ]);+ expect(listedProducts('<a href="/products/x">X</a>', [], null)).toEqual([]);+ });++ it('names a product by its card’s words, without its price or a button’s word, an HTML block’s too', () => {+ const card = '<a href="/products/ridge-28"><h3>Ridge 28</h3><span>$129.00</span></a>';+ const block = btoa(+ '<div class="grid"><a href="/products/ridge-32">Shop now</a><a href="/products/ridge-32">Ridge 32</a></div>',+ );+ expect(+ listedProducts(+ `${card}<div data-html-block="${block}"></div><a href="/products/summit"><img src="s.jpg"></a><a href="/products/summit">Summit</a>`,+ ['acme.com'],+ 'https://acme.com',+ ),+ ).toEqual([+ { url: 'https://acme.com/products/ridge-28', name: 'Ridge 28' },+ // A later link's name fills one the first didn't give.+ { url: 'https://acme.com/products/ridge-32', name: 'Ridge 32' },+ { url: 'https://acme.com/products/summit', name: 'Summit' },+ ]);+ });+});++describe('itemListJsonLd', () => {+ it('lists the products in order under the page’s name, a placeholder name left out', () => {+ expect(+ itemListJsonLd({+ name: 'Daypacks',+ items: [+ { url: 'https://acme.com/products/ridge-28', name: 'Ridge 28' },+ { url: 'https://acme.com/products/ridge-32', name: '[product name]' },+ ],+ }),+ ).toEqual({+ '@context': 'https://schema.org',+ '@type': 'ItemList',+ name: 'Daypacks',+ numberOfItems: 2,+ itemListElement: [+ {+ '@type': 'ListItem',+ position: 1,+ url: 'https://acme.com/products/ridge-28',+ name: 'Ridge 28',+ },+ { '@type': 'ListItem', position: 2, url: 'https://acme.com/products/ridge-32' },+ ],+ });+ expect(itemListJsonLd({ name: null, items: [] })).not.toHaveProperty('name');+ });+});diff --git a/web/src/lib/content/page-schema.ts b/web/src/lib/content/page-schema.tsindex a2bdfb8a7..bee3af9b4 100644--- a/web/src/lib/content/page-schema.ts+++ b/web/src/lib/content/page-schema.ts@@ -1,7 +1,9 @@+import { classifyDomain, normalizeDomain } from '@/lib/citations/classify';import type { ContentAuthor } from './authors';import { factValueText, pagePrices, priceRanges } from './brand-facts';import type { PageType } from './drafts';import { PLACEHOLDER } from './placeholders';+import { cleanHref, decodeHtmlBlock } from './html-allowlist';import { isByline, sentencesOf } from './readability';/**@@ -363,6 +365,147 @@ export function productJsonLd({};}+/**+ * A path that is a product's page: the segment shops put before it, then+ * the product's own one, last ("/products/ridge-28", "/product/…",+ * "/product-page/…", "/urun/…", "/produkt/…", "/produit/…", "/producto/…",+ * "/prodotto/…"). Not a page under it ("/products/ridge-28/reviews").+ */+const PRODUCT_PATH =+ /\/(?:products?|product-page|urun|produkte?|produits?|productos?|prodott[oi])\/[^/?#]+\/?$/iu;+/** A file, not a page ("/cdn/shop/products/ridge.jpg"): only an .html page is one. */+const FILE_PATH = /\.(?!html?$)[a-z0-9]{2,5}$/iu;+/** A card's button, not a product's name ("Shop now", "Add to cart", "Sepete ekle"). */+const BUTTON_WORDS =+ /^(?:shop(?:\s+now)?|buy(?:\s+now)?|view(?:\s+(?:product|details))?|see\s+(?:details|more|product)|learn\s+more|details|more|add\s+to\s+(?:cart|bag|basket)|sepete\s+ekle|incele|satın\s+al|jetzt\s+kaufen|in\s+den\s+warenkorb|acheter|ajouter\s+au\s+panier|comprar|ver\s+más|añadir\s+al\s+carrito)$/iu;++/** A product a category page lists: its page and its name as the link gives it. */+export interface ListedProduct {+ url: string;+ name: string | null;+}++/** The fewest products an ItemList lists (CE-054): one isn't a list. */+export const MIN_LISTED = 2;+/** The most it lists: a category's first page of products. */+export const MAX_LISTED = 100;++/**+ * A link's name: its words, apart where its markup is ("Ridge 28" and+ * "$129.00" in a card), its prices out; else its image's alt text. Not a+ * button's word ("Shop now").+ */+function linkName(a: Element): string | null {+ const words: string[] = [];+ const walk = (node: Node) => {+ if (node.nodeType === Node.TEXT_NODE) words.push(node.textContent ?? '');+ else node.childNodes.forEach(walk);+ };+ walk(a);+ let text = words.join(' ').replace(/\s+/g, ' ').trim();+ for (const price of pagePrices(text, { rangeEnds: true }).reverse()) {+ text = `${text.slice(0, price.at)} ${text.slice(price.at + price.text.length)}`;+ }+ text = text+ .replace(/\s+/g, ' ')+ .replace(/^[\s·|,–—-]+|[\s·|,–—-]+$/gu, '')+ .trim();+ if (!text || BUTTON_WORDS.test(text))+ text = a.querySelector('img[alt]')?.getAttribute('alt')?.trim() ?? '';+ return text ? text.slice(0, 150) : null;+}++/**+ * The products a category page lists (Quality spec §11, CE-054): its links+ * to the brand's own product pages, an HTML block's too, in the page's+ * order, each once ("www.", a trailing slash, a query, a hash, and a+ * Shopify collection's path before "/products/" alike), MAX_LISTED at+ * most. A relative link is read against the brand's site, else its first+ * domain. A name a later link gives fills one the first didn't.+ */+export function listedProducts(+ html: string,+ brandDomains: readonly string[],+ base: string | null,+): ListedProduct[] {+ const own = brandDomains.map(normalizeDomain).filter(Boolean);+ const root = base ?? (own[0] ? `https://${own[0]}` : null);+ const doc = new DOMParser().parseFromString(html, 'text/html');+ const links: Element[] = [];+ for (const el of doc.body.querySelectorAll('a[href], [data-html-block]')) {+ if (el.tagName === 'A') {+ links.push(el);+ continue;+ }+ const inner = decodeHtmlBlock(el.getAttribute('data-html-block') ?? '');+ if (inner) {+ links.push(+ ...new DOMParser().parseFromString(inner, 'text/html').body.querySelectorAll('a[href]'),+ );+ }+ }+ const byKey = new Map<string, ListedProduct>();+ for (const a of links) {+ const href = cleanHref(a.getAttribute('href') ?? '');+ if (!href) continue;+ let url: URL;+ try {+ url = root ? new URL(href, root) : new URL(href);+ } catch {+ continue;+ }+ if (url.protocol !== 'https:' && url.protocol !== 'http:') continue;+ const host = normalizeDomain(url.href);+ if (!host || classifyDomain(host, { brandDomains: own, competitorDomains: [] }) !== 'you') {+ continue;+ }+ if (!PRODUCT_PATH.test(url.pathname) || FILE_PATH.test(url.pathname)) continue;+ url.search = '';+ url.hash = '';+ // One product however its address is written.+ const path = url.pathname+ .replace(/\/collections\/[^/]+(?=\/products\/)/iu, '')+ .replace(/\/+$/, '');+ const key = `${host}${path}`.toLowerCase();+ const name = linkName(a);+ const had = byKey.get(key);+ if (had) {+ if (!had.name && name) had.name = name;+ continue;+ }+ if (byKey.size >= MAX_LISTED) continue;+ byKey.set(key, { url: url.href, name });+ }+ return [...byKey.values()];+}++/**+ * A category page's ItemList (CE-054): the products it lists, in its order,+ * each its page and name, under the page's name. Only what the page links:+ * prices and stock are each product's own page's Product.+ */+export function itemListJsonLd({+ name,+ items,+}: {+ /** The page's title as pageName gives it; left out without one. */+ name: string | null;+ items: readonly ListedProduct[];+}): Record<string, unknown> {+ return {+ '@context': 'https://schema.org',+ '@type': 'ItemList',+ ...(name ? { name } : {}),+ numberOfItems: items.length,+ itemListElement: items.map((item, i) => ({+ '@type': 'ListItem',+ position: i + 1,+ url: item.url,+ ...(item.name && !ONE_PLACEHOLDER.test(item.name) ? { name: item.name } : {}),+ })),+ };+}+/*** The JSON-LD as a script tag to paste into the page. A "<" in it is* escaped, so a title can't close the tag.