Repository navigation
Expand file tree
/
Copy pathstructured-data.ts
More file actions
349 lines (321 loc) · 8.79 KB
/
Copy pathstructured-data.ts
File metadata and controls
349 lines (321 loc) · 8.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import { absoluteUrl, SITE_NAME } from "./site";
/**
* JSON-LD builders, ported from the Next app's lib/structured-data.ts.
*
* The `schema-dts` types are deliberately not carried over — they cost a
* dependency and a great deal of type gymnastics (the Next version needed a
* triple cast to build a @graph) to describe objects that are serialized to
* a string immediately. The shapes below are the ones actually emitted.
*/
interface Node {
"@type": string;
"@id"?: string;
[key: string]: unknown;
}
export function buildGraph(nodes: Node[]) {
return {
"@context": "https://schema.org",
"@graph": nodes,
};
}
export const orgId = (origin: string) => `${origin}/#organization`;
export const websiteId = (origin: string) => `${origin}/#website`;
export function organizationSchema(origin: string, logoUrl?: string): Node {
return {
"@type": "Organization",
"@id": orgId(origin),
name: SITE_NAME,
url: origin,
...(logoUrl ? { logo: { "@type": "ImageObject", url: logoUrl } } : {}),
sameAs: [
"https://www.youtube.com/@CodingCatDev",
"https://twitter.com/CodingCatDev",
"https://github.com/codingcatdev",
"https://www.linkedin.com/company/codingcatdev",
"https://bsky.app/profile/codingcat.dev",
],
};
}
export function websiteSchema(origin: string): Node {
return {
"@type": "WebSite",
"@id": websiteId(origin),
name: SITE_NAME,
url: origin,
publisher: { "@id": orgId(origin) },
};
}
export function breadcrumbSchema(
origin: string,
crumbs: Array<{ name: string; path: string }>,
): Node {
return {
"@type": "BreadcrumbList",
itemListElement: crumbs.map((crumb, index) => ({
"@type": "ListItem",
position: index + 1,
name: crumb.name,
item: absoluteUrl(crumb.path, origin),
})),
};
}
interface ArticleInput {
title?: string | null;
excerpt?: string | null;
date?: string | null;
_updatedAt?: string | null;
imageUrl?: string;
authors?: Array<{ title?: string | null; slug?: string | null }> | null;
articleType?: "TechArticle" | "Article";
}
export function articleSchema(
origin: string,
content: ArticleInput,
path: string,
): Node {
const url = absoluteUrl(path, origin);
const authors = (content.authors ?? [])
.filter((a): a is { title: string; slug?: string | null } =>
Boolean(a?.title),
)
.map((a) => ({
"@type": "Person",
name: a.title,
...(a.slug ? { url: absoluteUrl(`/author/${a.slug}`, origin) } : {}),
}));
return {
"@type": content.articleType ?? "TechArticle",
"@id": `${url}#article`,
headline: content.title ?? undefined,
description: content.excerpt ?? undefined,
...(content.imageUrl ? { image: content.imageUrl } : {}),
...(content.date ? { datePublished: content.date } : {}),
...(content._updatedAt ? { dateModified: content._updatedAt } : {}),
...(authors.length ? { author: authors } : {}),
publisher: { "@id": orgId(origin) },
mainEntityOfPage: { "@type": "WebPage", "@id": url },
speakable: {
"@type": "SpeakableSpecification",
cssSelector: ["article h1", "article p:first-of-type"],
},
url,
};
}
interface PersonInput {
title?: string | null;
excerpt?: string | null;
imageUrl?: string;
socials?: Record<string, unknown> | null;
websites?: unknown[] | null;
}
/** Collect URL-like strings from the loosely-typed socials object and websites array. */
function collectProfileUrls(
socials?: Record<string, unknown> | null,
websites?: unknown[] | null,
): string[] {
const urls: string[] = [];
const pushIfUrl = (value: unknown) => {
if (typeof value === "string" && value.startsWith("http")) {
urls.push(value);
}
};
if (socials) {
for (const value of Object.values(socials)) {
pushIfUrl(value);
}
}
if (Array.isArray(websites)) {
for (const entry of websites) {
if (entry && typeof entry === "object") {
for (const value of Object.values(entry)) {
pushIfUrl(value);
}
}
}
}
return Array.from(new Set(urls));
}
export function personSchema(
origin: string,
content: PersonInput,
path: string,
): Node {
const url = absoluteUrl(path, origin);
const sameAs = collectProfileUrls(content.socials, content.websites);
return {
"@type": "Person",
"@id": `${url}#person`,
name: content.title ?? undefined,
description: content.excerpt ?? undefined,
...(content.imageUrl ? { image: content.imageUrl } : {}),
...(sameAs.length ? { sameAs } : {}),
url,
};
}
export function videoObjectSchema(
origin: string,
video: {
title?: string | null;
description?: string | null;
uploadDate?: string | null;
thumbnailUrl?: string;
youtubeUrl?: string | null;
durationSeconds?: number | null;
transcript?: string | null;
},
path: string,
): Node | null {
if (!video.youtubeUrl) {
return null;
}
const url = absoluteUrl(path, origin);
// Format ISO 8601 duration: PT#M#S or PT#S
let durationIso: string | undefined;
if (video.durationSeconds && video.durationSeconds > 0) {
const hours = Math.floor(video.durationSeconds / 3600);
const minutes = Math.floor((video.durationSeconds % 3600) / 60);
const seconds = Math.floor(video.durationSeconds % 60);
let d = "PT";
if (hours > 0) {
d += `${hours}H`;
}
if (minutes > 0) {
d += `${minutes}M`;
}
if (seconds > 0 || d === "PT") {
d += `${seconds}S`;
}
durationIso = d;
}
return {
"@type": "VideoObject",
"@id": `${url}#video`,
name: video.title ?? undefined,
description: video.description ?? undefined,
...(video.thumbnailUrl ? { thumbnailUrl: [video.thumbnailUrl] } : {}),
...(video.uploadDate ? { uploadDate: video.uploadDate } : {}),
...(durationIso ? { duration: durationIso } : {}),
...(video.transcript ? { transcript: video.transcript } : {}),
contentUrl: video.youtubeUrl,
embedUrl: video.youtubeUrl
.replace("watch?v=", "embed/")
.replace("youtu.be/", "www.youtube.com/embed/"),
};
}
export function faqSchema(
faqs: Array<{ question: string; answer: string }>,
): Node | null {
if (!faqs || faqs.length === 0) {
return null;
}
return {
"@type": "FAQPage",
mainEntity: faqs.map((faq) => ({
"@type": "Question",
name: faq.question,
acceptedAnswer: {
"@type": "Answer",
text: faq.answer,
},
})),
};
}
/**
* Automatically extracts Q&A pairs from Portable Text blocks where an H2/H3 heading
* is phrased as a question (ends with `?` or starts with How/Why/What/When/Where/Can/Should/Is).
*/
export function extractFaqsFromPortableText(
blocks: unknown,
): Array<{ question: string; answer: string }> {
if (!Array.isArray(blocks)) {
return [];
}
const faqs: Array<{ question: string; answer: string }> = [];
let currentQuestion: string | null = null;
let currentAnswerParts: string[] = [];
const flush = () => {
if (currentQuestion && currentAnswerParts.length > 0) {
const answer = currentAnswerParts.join(" ").trim();
if (answer.length >= 25) {
faqs.push({ question: currentQuestion, answer: answer.slice(0, 600) });
}
}
currentQuestion = null;
currentAnswerParts = [];
};
for (const block of blocks) {
if (!block || typeof block !== "object") {
continue;
}
const b = block as {
_type?: string;
style?: string;
children?: Array<{ text?: string }>;
};
if (b._type !== "block" || !Array.isArray(b.children)) {
continue;
}
const text = b.children
.map((c) => (typeof c?.text === "string" ? c.text : ""))
.join("")
.trim();
if (!text) {
continue;
}
if (b.style === "h2" || b.style === "h3" || b.style === "h4") {
flush();
const isQuestion =
text.endsWith("?") ||
/^(how|why|what|when|where|can|should|is|does|do)\b/i.test(text);
if (isQuestion) {
currentQuestion = text.endsWith("?") ? text : `${text}?`;
}
} else if (currentQuestion && currentAnswerParts.length < 3) {
currentAnswerParts.push(text);
}
}
flush();
return faqs.slice(0, 8);
}
interface PodcastEpisodeInput {
title?: string | null;
excerpt?: string | null;
date?: string | null;
imageUrl?: string;
season?: number | null;
episode?: number | null;
audioUrl?: string | null;
transcript?: string | null;
}
export function podcastEpisodeSchema(
origin: string,
content: PodcastEpisodeInput,
path: string,
): Node {
const url = absoluteUrl(path, origin);
return {
"@type": "PodcastEpisode",
"@id": `${url}#episode`,
url,
name: content.title ?? undefined,
description: content.excerpt ?? undefined,
...(content.date ? { datePublished: content.date } : {}),
...(content.imageUrl ? { image: content.imageUrl } : {}),
...(content.season ? { seasonNumber: content.season } : {}),
...(content.episode ? { episodeNumber: content.episode } : {}),
...(content.audioUrl
? {
associatedMedia: {
"@type": "AudioObject",
contentUrl: content.audioUrl,
},
}
: {}),
...(content.transcript ? { transcript: content.transcript } : {}),
partOfSeries: {
"@type": "PodcastSeries",
name: "CodingCat.dev Podcast",
url: `${origin}/podcasts`,
},
};
}