Debian Codegraph @

www/src/lib/jsonld.js

raw symbols SCIP
1 /**
2 * @typedef {Object} ArticleMeta
3 * @property {string} [publishedTime] ISO 8601
4 * @property {string} [modifiedTime] ISO 8601
5 * @property {string[]} [authors]
6 * @property {string[]} [tags]
7 */
8
9 /**
10 * @typedef {Object} BreadcrumbItem
11 * @property {string} label
12 * @property {string} [href]
13 */
14
15 /**
16 * @typedef {Object} JsonLdOpts
17 * @property {string} title
18 * @property {string} description
19 * @property {string} image
20 * @property {URL} url
21 * @property {string} siteUrl
22 * @property {ArticleMeta} [article]
23 * @property {BreadcrumbItem[]} [breadcrumbs]
24 */
25
26 /**
27 * Build the JSON-LD structured-data payload for a page.
28 * Returns an array of schemas: WebSite or Article, plus BreadcrumbList when breadcrumbs are provided.
29 * @param {JsonLdOpts} opts
30 */
31 export function buildJsonLd({ title, description, image, url, siteUrl, article, breadcrumbs }) {
32 const desc = description.trim();
33 const schemas = [];
34
35 if (!article) {
36 schemas.push({
37 "@context": "https://schema.org",
38 "@type": "WebSite",
39 "name": "htmx",
40 "url": siteUrl,
41 "description": desc,
42 });
43 } else {
44 schemas.push({
45 "@context": "https://schema.org",
46 "@type": "Article",
47 "headline": title,
48 "description": desc,
49 "url": url.href,
50 "image": new URL(image, url).href,
51 ...(article.publishedTime && { "datePublished": article.publishedTime }),
52 ...(article.modifiedTime && { "dateModified": article.modifiedTime }),
53 ...(article.authors?.length && {
54 "author": article.authors.map(name => ({ "@type": "Person", name }))
55 }),
56 ...(article.tags?.length && { "keywords": article.tags.join(", ") }),
57 "publisher": { "@type": "Organization", "name": "htmx", "url": siteUrl },
58 });
59 }
60
61 if (breadcrumbs?.length) {
62 const allCrumbs = [{ label: 'Home', href: '/' }, ...breadcrumbs];
63 schemas.push({
64 "@context": "https://schema.org",
65 "@type": "BreadcrumbList",
66 "itemListElement": allCrumbs.map((crumb, i) => ({
67 "@type": "ListItem",
68 "position": i + 1,
69 "name": crumb.label.replace(/<[^>]*>/g, ''),
70 ...(crumb.href ? { "item": new URL(crumb.href, siteUrl).href } : {}),
71 })),
72 });
73 }
74
75 return schemas.length === 1 ? schemas[0] : schemas;
76 }