This repository was archived by the owner on Mar 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathseo.ts
More file actions
594 lines (520 loc) · 16.1 KB
/
seo.ts
File metadata and controls
594 lines (520 loc) · 16.1 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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import type {Maybe} from './storefront-api-types.js';
import type {WithContext, Thing} from 'schema-dts';
import type {ComponentPropsWithoutRef, HTMLAttributes} from 'react';
export interface Seo {
/**
* The <title> HTML element defines the document's title that is shown in a browser's title bar or a page's tab. It
* only contains text; tags within the element are ignored.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title
*/
title: Maybe<string> | undefined;
/**
* Generate the title from a template that includes a `%s` placeholder for the title.
*
* @example
* ```js
* {
* title: 'My Page',
* titleTemplate: 'My Site - %s',
* }
* ```
*/
titleTemplate: Maybe<string> | undefined | null;
/**
* The media associated with the given page (images, videos, etc). If you pass a string, it will be used as the
* `og:image` meta tag. If you pass an object or an array of objects, that will be used to generate
* `og:<type of media>` meta tags. The `url` property should be the URL of the media. The `height` and `width`
* properties are optional and should be the height and width of the media. The `altText` property is optional and
* should be a description of the media.
*
* @example
* ```js
* {
* media: [
* {
* url: 'https://example.com/image.jpg',
* type: 'image',
* height: '400',
* width: '400',
* altText: 'A custom snowboard with an alpine color pallet.',
* }
* ]
* }
* ```
*
*/
media: Maybe<string> | undefined | SeoMedia | SeoMedia[];
/**
* The description of the page. This is used in the `name="description"` meta tag as well as the `og:description` meta
* tag.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta
*/
description: Maybe<string> | undefined;
/**
* The canonical URL of the page. This is used to tell search engines which URL is the canonical version of a page.
* This is useful when you have multiple URLs that point to the same page. The value here will be used in the
* `rel="canonical"` link tag as well as the `og:url` meta tag.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link
*/
url: Maybe<string> | undefined;
/**
* The handle is used to generate the `twitter:site` and `twitter:creator` meta tags. Include the `@` symbol in the
* handle.
*
* @example
* ```js
* {
* handle: '@shopify'
* }
* ```
*/
handle: Maybe<string> | undefined;
/**
* The `ldJson` property is used to generate the `application/ld+json` script tag. This is used to provide structured
* data to search engines. The value should be an object that conforms to the schema.org spec. The `type` property
* should be the type of schema you are using. The `type` property is required and should be one of the following:
*
* - `Product`
* - `ItemList`
* - `Organization`
* - `WebSite`
* - `WebPage`
* - `BlogPosting`
* - `Thing`
*
* @example
* ```js
* {
* ldJson: {
* '@context': 'https://schema.org',
* '@type': 'Product',
* name: 'My Product',
* image: 'https://hydrogen.shop/image.jpg',
* description: 'A product that is great',
* sku: '12345',
* mpn: '12345',
* brand: {
* '@type': 'Thing',
* name: 'My Brand',
* },
* aggregateRating: {
* '@type': 'AggregateRating',
* ratingValue: '4.5',
* reviewCount: '100',
* },
* offers: {
* '@type': 'Offer',
* priceCurrency: 'USD',
* price: '100',
* priceValidUntil: '2020-11-05',
* itemCondition: 'https://schema.org/NewCondition',
* availability: 'https://schema.org/InStock',
* seller: {
* '@type': 'Organization',
* name: 'My Brand',
* },
* },
* }
* }
* ```
*
* @see https://schema.org/docs/schemas.html
* @see https://developers.google.com/search/docs/guides/intro-structured-data
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script
*
*/
ldJson: <T extends SchemaType>(type: T) => WithContext<T>;
/**
* The `alternates` property is used to specify the language and geographical targeting when you have multiple
* versions of the same page in different languages. The `url` property tells search engines about these variations
* and helps them to serve the correct version to their users.
*
* @example
* ```js
* {
* alternates: [
* {
* language: 'en-US',
* url: 'https://hydrogen.shop/en-us',
* default: true,
* },
* {
* language: 'fr-CA',
* url: 'https://hydrogen.shop/fr-ca',
* },
* {
* media: 'only screen and (max-width: 640px)',
* url: 'https://m.hydrogen.shop/en-ca',
* },
* ]
* }
* ```
* @see https://support.google.com/webmasters/answer/189077?hl=en
*/
alternates: (LanguageAlternate | MobileAlternate)[];
}
export interface LanguageAlternate {
// Language code for the alternate page. This is used to generate the hreflang meta tag property.
language: string;
// Whether or not the alternate page is the default page. This will add the `x-default` attribution to the language
// code.
default?: boolean;
// The url of the alternate page. This is used to generate the hreflang meta tag property.
url: string;
}
export interface MobileAlternate {
// The media attribute specifies what media/device the target url is optimized for.
media: string;
// The url of the alternate page. This is used to generate the hreflang meta tag property.
url: string;
}
export type SeoMedia = {
// Used to generate og:<type of media> meta tag
type: 'image' | 'video' | 'audio';
// The url value populates both url and secure_url and is used to infer the og:<type of media>:type meta tag.
url: Maybe<string> | undefined;
// The height in pixels of the media. This is used to generate the og:<type of media>:height meta tag.
height: Maybe<number> | undefined;
// The width in pixels of the media. This is used to generate the og:<type of media>:width meta tag/
width: Maybe<number> | undefined;
// The alt text for the media. This is used to generate the og:<type of media>:alt meta tag.
altText: Maybe<string> | undefined;
};
export type TagKey = 'title' | 'base' | 'meta' | 'link' | 'script';
export interface CustomHeadTagObject {
tag: TagKey;
props: Record<string, unknown>;
children?: string;
key: string;
}
export type SchemaType =
| 'Product'
| 'ItemList'
| 'Organization'
| 'WebSite'
| 'WebPage'
| 'BlogPosting'
| 'Thing';
/**
* The `generateSeoTags` function generates the SEO title, meta, link and script (JSON Linking Data) tags for a page. It
* pairs well with the SEO component in `@shopify/hydrogen` when building a Hydrogen Remix app, but can be used on its
* own if you want to generate the tags yourself.
*/
export function generateSeoTags<T extends Seo = Seo>(
seoInput: T
): CustomHeadTagObject[] {
const output: CustomHeadTagObject[] = [];
// https://github.com/google/schema-dts/issues/98
let ldJson: WithContext<Exclude<Thing, string>> = {
'@context': 'https://schema.org',
'@type': 'Thing',
};
for (const seoKey of Object.keys(seoInput) as (keyof T)[]) {
const values = Array.isArray(seoInput[seoKey])
? (seoInput[seoKey] as T[keyof T][])
: [seoInput[seoKey]];
const tags = values.map((value) => {
const tagResults: CustomHeadTagObject[] = [];
if (!value) {
return tagResults;
}
switch (seoKey) {
case 'title': {
const title = renderTitle(seoInput?.titleTemplate, value);
tagResults.push(
generateTag('title', {title}),
generateTag('meta', {property: 'og:title', content: title}),
generateTag('meta', {name: 'twitter:title', content: title})
);
ldJson.name = title;
break;
}
case 'description':
tagResults.push(
generateTag('meta', {name: 'description', content: value}),
generateTag('meta', {property: 'og:description', content: value}),
generateTag('meta', {name: 'twitter:description', content: value})
);
ldJson.description = value;
break;
case 'url':
tagResults.push(
generateTag('meta', {property: 'og:url', content: value}),
generateTag('link', {rel: 'canonical', href: value})
);
ldJson.url = value;
ldJson['@type'] = inferSchemaType(value as string);
break;
case 'handle':
tagResults.push(
generateTag('meta', {name: 'twitter:site', content: value}),
generateTag('meta', {name: 'twitter:creator', content: value})
);
break;
case 'ldJson':
ldJson = {...ldJson, ...value};
break;
case 'media': {
const values = Array.isArray(value) ? value : [value];
for (const media of values) {
if (typeof media === 'string') {
tagResults.push(
generateTag('meta', {name: 'og:image', content: value})
);
ldJson.image = value;
}
if (media && typeof media === 'object') {
const type = media.type || 'image';
// Order matters here when adding multiple media tags @see https://ogp.me/#array
const normalizedMedia = media
? {
url: media?.url,
secure_url: media?.url,
type: inferMimeType(media?.url),
width: media?.width,
height: media?.height,
alt: media?.altText,
}
: {};
for (const key of Object.keys(normalizedMedia)) {
if (normalizedMedia[key as keyof typeof normalizedMedia]) {
tagResults.push(
generateTag(
'meta',
{
property: `og:${type}:${key}`,
content:
normalizedMedia[key as keyof typeof normalizedMedia],
},
normalizedMedia.url
)
);
}
}
}
}
break;
}
case 'alternates': {
const alternates = Array.isArray(value) ? value : [value];
for (const alternate of alternates) {
const {
language,
media,
url,
default: defaultLang,
} = alternate as Seo['alternates'][0];
const hreflang = language
? `${language}${defaultLang ? '-default' : ''}`
: undefined;
tagResults.push(
generateTag('link', {
rel: 'alternate',
hreflang,
media,
href: url,
})
);
}
break;
}
}
return tagResults;
});
const entries = tags.flat();
output.push(
// @ts-expect-error untyped
entries.filter((value) => !!value)
);
}
const additionalTags = [
generateTag('meta', {property: 'og:type', content: 'website'}),
generateTag('meta', {
name: 'twitter:card',
content: 'summary_large_image',
}),
];
return [...output, ...additionalTags]
.flat()
.sort((a, b) => a.key.localeCompare(b.key))
.concat(
// move ld+json to the end
generateTag('script', {
type: 'application/ld+json',
children: JSON.stringify(ldJson),
})
)
.flat();
}
type MetaTagProps =
| ComponentPropsWithoutRef<'title'>
| ComponentPropsWithoutRef<'base'>
| ComponentPropsWithoutRef<'meta'>
| ComponentPropsWithoutRef<'link'>
| ComponentPropsWithoutRef<'script'>;
function generateTag(
tagName: 'title',
input: ComponentPropsWithoutRef<'title'>,
group?: string
): CustomHeadTagObject;
function generateTag(
tagName: 'base',
input: ComponentPropsWithoutRef<'base'>,
group?: string
): CustomHeadTagObject;
function generateTag(
tagName: 'meta',
input: ComponentPropsWithoutRef<'meta'>,
group?: string
): CustomHeadTagObject;
function generateTag(
tagName: 'link',
input: ComponentPropsWithoutRef<'link'>,
group?: string
): CustomHeadTagObject;
function generateTag(
tagName: 'script',
input: ComponentPropsWithoutRef<'script'>,
group?: string
): CustomHeadTagObject;
function generateTag(
tagName: TagKey,
input: MetaTagProps,
group?: string
): CustomHeadTagObject {
const tag: CustomHeadTagObject = {tag: tagName, props: {}, key: ''};
// title tags don't have props so move to children
if (tagName === 'title') {
tag.children = JSON.stringify(input);
tag.key = generateKey(tag);
return tag;
}
// also move the input children to children and delete it
if (tagName === 'script') {
tag.children = JSON.stringify(input.children);
delete input.children;
}
// the rest goes on props
tag.props = input;
// remove empty props
Object.keys(tag.props).forEach(
(key) => !tag.props[key] && delete tag.props[key]
);
tag.key = generateKey(tag, group);
return tag;
}
function generateKey(tag: CustomHeadTagObject, group?: string) {
const {tag: tagName, props} = tag;
if (tagName === 'title') {
// leading 0 moves title to the top when sorting
return '0-title';
}
if (tagName === 'meta') {
// leading 0 moves meta to the top when sorting exclude secure_url from the logic because the content is the same as
// url
const priority =
props.content === group && !props.property.endsWith('secure_url') && '0';
const groupName = [group, priority];
return [tagName, ...groupName, props.property || props.name]
.filter((x) => x)
.join('-');
}
if (tagName === 'link') {
const key = [tagName, props.rel, props.hreflang || props.media]
.filter((x) => x)
.join('-');
// replace spaces with dashes, needed for media prop
return key.replace(/\s+/g, '-');
}
return `${tagName}-${props.type}`;
}
function renderTitle<T extends CustomHeadTagObject['children']>(
template?:
| string
| ((title?: string) => string | undefined)
| undefined
| null,
title?: T
): string | undefined {
if (!template) {
return title;
}
if (typeof template === 'function') {
return template(title);
}
return template.replace('%s', title ?? '');
}
function inferMimeType(url: string) {
const ext = url.split('.').pop();
if (ext === 'svg') {
return 'image/svg+xml';
}
if (ext === 'png') {
return 'image/png';
}
if (ext === 'jpg' || ext === 'jpeg') {
return 'image/jpeg';
}
if (ext === 'gif') {
return 'image/gif';
}
if (ext === 'swf') {
return 'application/x-shockwave-flash';
}
if (ext === 'mp3') {
return 'audio/mpeg';
}
return 'image/jpeg';
}
function inferSchemaType(url: string): SchemaType {
const defaultType = 'Thing';
const routes: {type: SchemaType; pattern: RegExp | string}[] = [
{
type: 'WebSite',
pattern: '^/$',
},
{
type: 'Product',
pattern: '/products/.*',
},
{
type: 'ItemList',
pattern: /\/collections$/,
},
{
type: 'ItemList',
pattern: /\/collections\/([^/]+)/,
},
{
type: 'WebPage',
pattern: /\/pages\/([^/]+)/,
},
{
type: 'WebSite',
pattern: /\/blogs\/([^/]+)/,
},
{
type: 'BlogPosting',
pattern: /\/blogs\/([^/]+)\/([^/]+)/,
},
{
type: 'Organization',
pattern: '/policies',
},
{
type: 'Organization',
pattern: /\/policies\/([^/]+)/,
},
];
const typeMatches = routes.filter((route) => {
const {pattern} = route;
const regex = new RegExp(pattern);
return regex.test(url);
});
return typeMatches.length > 0
? typeMatches[typeMatches.length - 1].type
: defaultType;
}