astro-helmet 1.3.0 → 1.4.0-beta.2

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.
package/src/main.ts CHANGED
@@ -4,23 +4,237 @@ const DEFAULT_VIEWPORT = {
4
4
  content: 'width=device-width, initial-scale=1'
5
5
  }
6
6
 
7
+ const VALID_PRELOAD_AS_VALUES = new Set([
8
+ 'audio',
9
+ 'document',
10
+ 'embed',
11
+ 'fetch',
12
+ 'font',
13
+ 'image',
14
+ 'object',
15
+ 'provider',
16
+ 'script',
17
+ 'style',
18
+ 'track',
19
+ 'video',
20
+ 'worker'
21
+ ])
22
+
7
23
  type TagName =
8
- | 'title'
9
- | 'base'
10
- | 'meta'
11
- | 'link'
12
- | 'style'
13
- | 'script'
14
- | 'noscript'
24
+ 'title' | 'base' | 'meta' | 'link' | 'style' | 'script' | 'noscript'
15
25
 
16
26
  type BaseItem = {
17
27
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
28
  [key: string]: any
29
+ key?: string
19
30
  priority?: number
20
31
  }
21
32
 
22
33
  type ContentItem = BaseItem & {
23
34
  innerHTML?: string
35
+ textContent?: string
36
+ }
37
+
38
+ export type HelmetOptions = {
39
+ omitHeadTags?: boolean
40
+ applyPriority?: (tag: Tag) => Required<Tag>
41
+ csp?: boolean
42
+ validate?: boolean | HeadValidationOptions
43
+ }
44
+
45
+ export type CrossOrigin = 'anonymous' | 'use-credentials' | ''
46
+
47
+ export type FetchPriority = 'high' | 'low' | 'auto'
48
+
49
+ export type ReferrerPolicy =
50
+ | 'no-referrer'
51
+ | 'no-referrer-when-downgrade'
52
+ | 'origin'
53
+ | 'origin-when-cross-origin'
54
+ | 'same-origin'
55
+ | 'strict-origin'
56
+ | 'strict-origin-when-cross-origin'
57
+ | 'unsafe-url'
58
+
59
+ export type MetaItem = BaseItem & {
60
+ name?: string
61
+ property?: string
62
+ content?: string | number | boolean
63
+ charset?: string
64
+ 'http-equiv'?: string
65
+ media?: string
66
+ }
67
+
68
+ export type LinkItem = BaseItem & {
69
+ rel?: string
70
+ href?: string | URL
71
+ as?: string
72
+ type?: string
73
+ crossorigin?: CrossOrigin
74
+ integrity?: string
75
+ media?: string
76
+ fetchpriority?: FetchPriority
77
+ referrerpolicy?: ReferrerPolicy
78
+ imagesrcset?: string
79
+ imagesizes?: string
80
+ }
81
+
82
+ export type ScriptItem = ContentItem & {
83
+ src?: string | URL
84
+ type?: string
85
+ async?: boolean
86
+ defer?: boolean
87
+ crossorigin?: CrossOrigin
88
+ integrity?: string
89
+ nonce?: string
90
+ referrerpolicy?: ReferrerPolicy
91
+ fetchpriority?: FetchPriority
92
+ }
93
+
94
+ export type StyleItem = ContentItem & {
95
+ media?: string
96
+ nonce?: string
97
+ }
98
+
99
+ export type NoscriptItem = ContentItem
100
+
101
+ export type HeadValidationSeverity = 'warning' | 'error'
102
+
103
+ export type HeadValidationCode =
104
+ | 'missing-title'
105
+ | 'missing-description'
106
+ | 'duplicate-canonical'
107
+ | 'relative-canonical'
108
+ | 'canonical-with-noindex'
109
+ | 'invalid-url'
110
+ | 'missing-preload-source'
111
+ | 'invalid-preload-as'
112
+ | 'missing-preload-as'
113
+ | 'responsive-image-missing-sizes'
114
+ | 'font-preload-missing-crossorigin'
115
+ | 'modulepreload-with-as'
116
+ | 'preconnect-missing-href'
117
+ | 'dns-prefetch-missing-href'
118
+ | 'sri-missing-crossorigin'
119
+ | 'missing-sri'
120
+ | 'unsafe-inner-html'
121
+ | 'unsafe-event-attribute'
122
+ | 'missing-og-required'
123
+ | 'relative-og-url'
124
+ | 'relative-og-image'
125
+ | 'relative-twitter-image'
126
+ | 'invalid-json-ld'
127
+
128
+ export type HeadValidationIssue = {
129
+ code: HeadValidationCode
130
+ severity: HeadValidationSeverity
131
+ message: string
132
+ tagName?: TagName | 'jsonLd' | 'title'
133
+ path?: string
134
+ }
135
+
136
+ export type HeadValidationOptions = {
137
+ baseUrl?: string | URL
138
+ requireDescription?: boolean
139
+ requireOpenGraphImage?: boolean
140
+ requireSri?: boolean
141
+ warnOnInnerHTML?: boolean
142
+ warnOnEventAttributes?: boolean
143
+ }
144
+
145
+ export type ResourceHintOptions = Omit<LinkItem, 'rel' | 'href' | 'as'> & {
146
+ key?: string
147
+ }
148
+
149
+ export type PreloadOptions = ResourceHintOptions & {
150
+ as: string
151
+ }
152
+
153
+ export type PreloadFontOptions = ResourceHintOptions & {
154
+ type?: string
155
+ crossorigin?: CrossOrigin | false
156
+ }
157
+
158
+ export type PreloadImageOptions = ResourceHintOptions & {
159
+ imagesrcset?: string
160
+ imagesizes?: string
161
+ fetchpriority?: FetchPriority
162
+ }
163
+
164
+ export type ResponsivePreloadImageOptions = PreloadImageOptions & {
165
+ href?: string | URL
166
+ imagesrcset: string
167
+ }
168
+
169
+ export type StylesheetOptions = Omit<LinkItem, 'rel' | 'href'>
170
+
171
+ export type ExternalScriptOptions = Omit<ScriptItem, 'src'>
172
+
173
+ export type RobotsOptions = {
174
+ index?: boolean
175
+ follow?: boolean
176
+ noarchive?: boolean
177
+ nosnippet?: boolean
178
+ noimageindex?: boolean
179
+ nocache?: boolean
180
+ maxSnippet?: number
181
+ maxImagePreview?: 'none' | 'standard' | 'large'
182
+ maxVideoPreview?: number
183
+ extra?: string | string[]
184
+ }
185
+
186
+ export type SeoImage =
187
+ | string
188
+ | URL
189
+ | {
190
+ url: string | URL
191
+ alt?: string
192
+ width?: number
193
+ height?: number
194
+ type?: string
195
+ }
196
+
197
+ export type OpenGraphOptions = {
198
+ title?: string
199
+ description?: string
200
+ type?: string
201
+ url?: string | URL
202
+ siteName?: string
203
+ locale?: string
204
+ image?: SeoImage | SeoImage[]
205
+ }
206
+
207
+ export type TwitterOptions = {
208
+ card?: 'summary' | 'summary_large_image' | 'app' | 'player' | string
209
+ site?: string
210
+ creator?: string
211
+ title?: string
212
+ description?: string
213
+ image?: string | URL
214
+ imageAlt?: string
215
+ }
216
+
217
+ export type AlternateLink = {
218
+ hrefLang: string
219
+ href: string | URL
220
+ }
221
+
222
+ export type SeoHeadOptions = {
223
+ title: string
224
+ titleTemplate?: string | ((title: string) => string)
225
+ description?: string
226
+ canonical?: string | URL
227
+ site?: string | URL
228
+ path?: string
229
+ robots?: string | RobotsOptions
230
+ noindex?: boolean
231
+ nofollow?: boolean
232
+ openGraph?: OpenGraphOptions
233
+ twitter?: TwitterOptions
234
+ alternates?: AlternateLink[]
235
+ jsonLd?: JsonLdItem | JsonLdItem[]
236
+ meta?: MetaItem[]
237
+ link?: LinkItem[]
24
238
  }
25
239
 
26
240
  export type Tag = (BaseItem | ContentItem) & {
@@ -39,11 +253,11 @@ export type JsonLdItem = {
39
253
  export type HeadItems = {
40
254
  title?: string
41
255
  base?: BaseItem[]
42
- meta?: BaseItem[]
43
- link?: BaseItem[]
44
- style?: ContentItem[]
45
- script?: ContentItem[]
46
- noscript?: ContentItem[]
256
+ meta?: MetaItem[]
257
+ link?: LinkItem[]
258
+ style?: StyleItem[]
259
+ script?: ScriptItem[]
260
+ noscript?: NoscriptItem[]
47
261
  jsonLd?: JsonLdItem | JsonLdItem[]
48
262
  }
49
263
 
@@ -69,6 +283,10 @@ export function renderHead(
69
283
  if (!items.title?.length) throw new Error('Missing title tag.')
70
284
 
71
285
  items.meta = deduplicateMetaItems(items.meta)
286
+ items.link = deduplicateLinkItems(items.link)
287
+ items.style = deduplicateKeyedItems(items.style)
288
+ items.script = deduplicateKeyedItems(items.script)
289
+ items.noscript = deduplicateKeyedItems(items.noscript)
72
290
  items.base = items.base.slice(-1)
73
291
 
74
292
  const { title: _title, jsonLd: _jsonLd, ...rest } = items
@@ -130,10 +348,18 @@ function mergeHeadItems(items: NormalisedHeadItems[]): NormalisedHeadItems {
130
348
 
131
349
  function getDefaultTags(tags: Tag[]): Tag[] {
132
350
  const defaultTags: Tag[] = []
133
- if (!tags.some((tag) => tag.tagName === 'meta' && tag.charset))
351
+ if (
352
+ tags.every(
353
+ (tag) => tag.tagName !== 'meta' || !hasNonEmptyAttr(tag, 'charset')
354
+ )
355
+ )
134
356
  defaultTags.push({ ...DEFAULT_CHARSET, tagName: 'meta' })
135
357
 
136
- if (!tags.some((tag) => tag.tagName === 'meta' && tag.name === 'viewport'))
358
+ if (
359
+ tags.every(
360
+ (tag) => tag.tagName !== 'meta' || !attrEquals(tag.name, 'viewport')
361
+ )
362
+ )
137
363
  defaultTags.push({ ...DEFAULT_VIEWPORT, tagName: 'meta' })
138
364
 
139
365
  return defaultTags
@@ -152,22 +378,25 @@ function applyPriorityDefault(tag: Tag): Required<Tag> {
152
378
  break
153
379
 
154
380
  case 'meta':
155
- if (tag.charset) priority = -4
156
- else if (tag.name === 'viewport') priority = -3
157
- else if (tag['http-equiv']) priority = -1
381
+ if (hasNonEmptyAttr(tag, 'charset')) priority = -4
382
+ else if (attrEquals(tag.name, 'viewport')) priority = -3
383
+ else if (hasNonEmptyAttr(tag, 'http-equiv')) priority = -1
158
384
  else priority = 100
159
385
  break
160
386
 
161
387
  case 'link':
162
- if (tag.rel === 'preconnect') priority = 10
163
- else if (tag.rel === 'preload') priority = 60
164
- else if (tag.rel === 'prefetch') priority = 80
165
- else if (tag.rel === 'stylesheet') priority = 50
388
+ if (hasRel(tag, 'preconnect')) priority = 10
389
+ else if (hasRel(tag, 'dns-prefetch')) priority = 11
390
+ else if (hasRel(tag, 'preload') || hasRel(tag, 'modulepreload'))
391
+ priority = 60
392
+ else if (hasRel(tag, 'prefetch') || hasRel(tag, 'prerender'))
393
+ priority = 80
394
+ else if (hasRel(tag, 'stylesheet')) priority = 50
166
395
  else priority = 90
167
396
  break
168
397
 
169
398
  case 'style':
170
- priority = tag.innerHTML?.includes('@import') ? 30 : 51
399
+ priority = getTagContent(tag).includes('@import') ? 30 : 51
171
400
  break
172
401
 
173
402
  case 'script':
@@ -180,7 +409,7 @@ function applyPriorityDefault(tag: Tag): Required<Tag> {
180
409
  default:
181
410
  priority = 110
182
411
  }
183
- return { ...tag, priority }
412
+ return { ...tag, priority } as Required<Tag>
184
413
  }
185
414
 
186
415
  export function getInlineContent(
@@ -189,16 +418,19 @@ export function getInlineContent(
189
418
  const items = Array.isArray(headItems)
190
419
  ? mergeHeadItems(headItems.map((i) => normaliseHeadItems(i)))
191
420
  : normaliseHeadItems(headItems)
421
+ items.style = deduplicateKeyedItems(items.style)
422
+ items.script = deduplicateKeyedItems(items.script)
192
423
 
193
424
  const result: { type: 'script' | 'style'; content: string }[] = []
194
425
 
195
426
  for (const style of items.style) {
196
- if (style.innerHTML) result.push({ type: 'style', content: style.innerHTML })
427
+ const content = getTagContent({ ...style, tagName: 'style' })
428
+ if (content) result.push({ type: 'style', content })
197
429
  }
198
430
 
199
431
  for (const script of items.script) {
200
- if (script.innerHTML)
201
- result.push({ type: 'script', content: script.innerHTML })
432
+ const content = getTagContent({ ...script, tagName: 'script' })
433
+ if (content) result.push({ type: 'script', content })
202
434
  }
203
435
 
204
436
  for (const item of items.jsonLd) {
@@ -219,28 +451,917 @@ export function getExternalResources(
219
451
  const items = Array.isArray(headItems)
220
452
  ? mergeHeadItems(headItems.map((i) => normaliseHeadItems(i)))
221
453
  : normaliseHeadItems(headItems)
454
+ items.link = deduplicateLinkItems(items.link)
455
+ items.script = deduplicateKeyedItems(items.script)
222
456
 
223
457
  const result: { type: 'script' | 'style'; url: string }[] = []
224
458
 
225
459
  for (const script of items.script) {
226
- if (script.src) result.push({ type: 'script', url: script.src })
460
+ if (script.src)
461
+ result.push({ type: 'script', url: toUrlString(script.src) })
227
462
  }
228
463
 
229
464
  for (const link of items.link) {
230
- if (link.rel === 'stylesheet' && link.href)
231
- result.push({ type: 'style', url: link.href })
232
- else if (link.rel === 'preload' && link.href) {
233
- if (link.as === 'script') result.push({ type: 'script', url: link.href })
234
- else if (link.as === 'style')
235
- result.push({ type: 'style', url: link.href })
465
+ if (hasRel(link, 'stylesheet') && link.href)
466
+ result.push({ type: 'style', url: toUrlString(link.href) })
467
+ else if (hasRel(link, 'modulepreload') && link.href) {
468
+ result.push({ type: 'script', url: toUrlString(link.href) })
469
+ } else if (hasRel(link, 'preload') && link.href) {
470
+ if (attrEquals(link.as, 'script'))
471
+ result.push({ type: 'script', url: toUrlString(link.href) })
472
+ else if (attrEquals(link.as, 'style'))
473
+ result.push({ type: 'style', url: toUrlString(link.href) })
236
474
  }
237
475
  }
238
476
 
239
477
  return result
240
478
  }
241
479
 
480
+ export function preconnect(
481
+ href: string | URL,
482
+ options: ResourceHintOptions = {}
483
+ ): LinkItem {
484
+ return { ...options, rel: 'preconnect', href: toUrlString(href) }
485
+ }
486
+
487
+ export function dnsPrefetch(
488
+ href: string | URL,
489
+ options: ResourceHintOptions = {}
490
+ ): LinkItem {
491
+ return { ...options, rel: 'dns-prefetch', href: toUrlString(href) }
492
+ }
493
+
494
+ export function preload(href: string | URL, options: PreloadOptions): LinkItem {
495
+ const { as, ...rest } = options
496
+ return { ...rest, rel: 'preload', href: toUrlString(href), as }
497
+ }
498
+
499
+ export function preloadFont(
500
+ href: string | URL,
501
+ options: PreloadFontOptions = {}
502
+ ): LinkItem {
503
+ const { crossorigin = 'anonymous', type, ...rest } = options
504
+ const link: LinkItem = {
505
+ ...rest,
506
+ rel: 'preload',
507
+ href: toUrlString(href),
508
+ as: 'font'
509
+ }
510
+ if (type) link.type = type
511
+ if (crossorigin !== false) link.crossorigin = crossorigin
512
+ return link
513
+ }
514
+
515
+ export function preloadImage(
516
+ href: string | URL,
517
+ options?: PreloadImageOptions
518
+ ): LinkItem
519
+ export function preloadImage(options: ResponsivePreloadImageOptions): LinkItem
520
+ export function preloadImage(
521
+ hrefOrOptions: string | URL | ResponsivePreloadImageOptions,
522
+ options: PreloadImageOptions = {}
523
+ ): LinkItem {
524
+ if (typeof hrefOrOptions === 'string' || hrefOrOptions instanceof URL) {
525
+ return {
526
+ ...options,
527
+ rel: 'preload',
528
+ href: toUrlString(hrefOrOptions),
529
+ as: 'image'
530
+ }
531
+ }
532
+
533
+ const { href, ...rest } = hrefOrOptions
534
+ const link: LinkItem = { ...rest, rel: 'preload', as: 'image' }
535
+ if (href !== undefined) link.href = toUrlString(href)
536
+ return link
537
+ }
538
+
539
+ export function modulepreload(
540
+ href: string | URL,
541
+ options: ResourceHintOptions = {}
542
+ ): LinkItem {
543
+ return { ...options, rel: 'modulepreload', href: toUrlString(href) }
544
+ }
545
+
546
+ export function stylesheet(
547
+ href: string | URL,
548
+ options: StylesheetOptions = {}
549
+ ): LinkItem {
550
+ return { ...options, rel: 'stylesheet', href: toUrlString(href) }
551
+ }
552
+
553
+ export function externalScript(
554
+ src: string | URL,
555
+ options: ExternalScriptOptions = {}
556
+ ): ScriptItem {
557
+ return { ...options, src: toUrlString(src) }
558
+ }
559
+
560
+ export function createSeoHead(options: SeoHeadOptions): HeadItems {
561
+ const title = applyTitleTemplate(options.title, options.titleTemplate)
562
+ const canonical =
563
+ options.canonical !== undefined
564
+ ? resolveUrlString(options.canonical, options.site)
565
+ : options.site && options.path
566
+ ? resolveUrlString(options.path, options.site)
567
+ : undefined
568
+
569
+ const meta: MetaItem[] = []
570
+ const link: LinkItem[] = []
571
+
572
+ if (options.description)
573
+ meta.push({
574
+ name: 'description',
575
+ content: options.description
576
+ })
577
+
578
+ const robots = createRobotsContent(options)
579
+ if (robots) meta.push({ name: 'robots', content: robots })
580
+
581
+ if (canonical) link.push({ rel: 'canonical', href: canonical })
582
+
583
+ for (const alternate of options.alternates || []) {
584
+ link.push({
585
+ key: `alternate:${alternate.hrefLang}`,
586
+ rel: 'alternate',
587
+ hreflang: alternate.hrefLang,
588
+ href: resolveUrlString(alternate.href, options.site)
589
+ })
590
+ }
591
+
592
+ if (options.openGraph) {
593
+ meta.push(
594
+ ...createOpenGraphMeta(options.openGraph, {
595
+ title,
596
+ description: options.description,
597
+ url: canonical,
598
+ site: options.site
599
+ })
600
+ )
601
+ }
602
+
603
+ if (options.twitter) {
604
+ meta.push(
605
+ ...createTwitterMeta(options.twitter, {
606
+ title,
607
+ description: options.description,
608
+ site: options.site
609
+ })
610
+ )
611
+ }
612
+
613
+ meta.push(...(options.meta || []))
614
+ link.push(...(options.link || []))
615
+
616
+ return {
617
+ title,
618
+ meta,
619
+ link,
620
+ jsonLd: options.jsonLd
621
+ }
622
+ }
623
+
624
+ export function validateHeadItems(
625
+ headItems: HeadItems | HeadItems[],
626
+ options: HeadValidationOptions = {}
627
+ ): HeadValidationIssue[] {
628
+ const validationOptions: Required<
629
+ Omit<HeadValidationOptions, 'baseUrl' | 'requireSri'>
630
+ > &
631
+ Pick<HeadValidationOptions, 'baseUrl' | 'requireSri'> = {
632
+ baseUrl: options.baseUrl,
633
+ requireSri: options.requireSri,
634
+ requireDescription: options.requireDescription ?? true,
635
+ requireOpenGraphImage: options.requireOpenGraphImage ?? false,
636
+ warnOnInnerHTML: options.warnOnInnerHTML ?? true,
637
+ warnOnEventAttributes: options.warnOnEventAttributes ?? true
638
+ }
639
+ const items = Array.isArray(headItems)
640
+ ? mergeHeadItems(headItems.map((i) => normaliseHeadItems(i)))
641
+ : normaliseHeadItems(headItems)
642
+ items.meta = deduplicateMetaItems(items.meta)
643
+ items.link = deduplicateLinkItems(items.link)
644
+ items.style = deduplicateKeyedItems(items.style)
645
+ items.script = deduplicateKeyedItems(items.script)
646
+ items.noscript = deduplicateKeyedItems(items.noscript)
647
+ const issues: HeadValidationIssue[] = []
648
+
649
+ if (!items.title.trim()) {
650
+ issues.push({
651
+ code: 'missing-title',
652
+ severity: 'error',
653
+ tagName: 'title',
654
+ path: 'title',
655
+ message: 'At least one non-empty title is required.'
656
+ })
657
+ }
658
+
659
+ if (
660
+ validationOptions.requireDescription &&
661
+ !items.meta.some((meta) => attrEquals(meta.name, 'description'))
662
+ ) {
663
+ issues.push({
664
+ code: 'missing-description',
665
+ severity: 'warning',
666
+ tagName: 'meta',
667
+ path: 'meta[name="description"]',
668
+ message: 'Add a meta description for search and sharing previews.'
669
+ })
670
+ }
671
+
672
+ const hasNoindex = hasRobotsDirective(items.meta, 'noindex')
673
+ validateMetaItems(items.meta, issues, validationOptions)
674
+ validateLinkItems(items.link, issues, validationOptions, hasNoindex)
675
+ validateScriptItems(items.script, issues, validationOptions)
676
+ validateContentItems(items.style, 'style', issues, validationOptions)
677
+ validateContentItems(items.script, 'script', issues, validationOptions)
678
+ validateContentItems(items.noscript, 'noscript', issues, validationOptions)
679
+ validateJsonLd(items.jsonLd, issues)
680
+
681
+ return issues
682
+ }
683
+
684
+ function validateMetaItems(
685
+ metaItems: MetaItem[],
686
+ issues: HeadValidationIssue[],
687
+ options: HeadValidationOptions
688
+ ): void {
689
+ const ogProperties = new Set<string>()
690
+
691
+ metaItems.forEach((meta, index) => {
692
+ validateUnsafeAttributes(meta, 'meta', `meta[${index}]`, issues, options)
693
+ const property = normaliseAttrValue(meta.property).toLowerCase()
694
+ const name = normaliseAttrValue(meta.name).toLowerCase()
695
+ const content = normaliseAttrValue(meta.content)
696
+
697
+ if (property.startsWith('og:')) ogProperties.add(property)
698
+
699
+ const ogUrlValid =
700
+ property === 'og:url'
701
+ ? validateUrlValue(content, 'meta', `meta[${index}]`, issues, options)
702
+ : true
703
+
704
+ if (property === 'og:url' && ogUrlValid && isRelativeUrl(content)) {
705
+ issues.push({
706
+ code: 'relative-og-url',
707
+ severity: 'warning',
708
+ tagName: 'meta',
709
+ path: `meta[${index}]`,
710
+ message: 'Open Graph URLs should be absolute.'
711
+ })
712
+ }
713
+
714
+ const ogImageValid =
715
+ property === 'og:image'
716
+ ? validateUrlValue(content, 'meta', `meta[${index}]`, issues, options)
717
+ : true
718
+
719
+ if (property === 'og:image' && ogImageValid && isRelativeUrl(content)) {
720
+ issues.push({
721
+ code: 'relative-og-image',
722
+ severity: 'warning',
723
+ tagName: 'meta',
724
+ path: `meta[${index}]`,
725
+ message: 'Open Graph images should use absolute URLs.'
726
+ })
727
+ }
728
+
729
+ const twitterImageValid =
730
+ name === 'twitter:image'
731
+ ? validateUrlValue(content, 'meta', `meta[${index}]`, issues, options)
732
+ : true
733
+
734
+ if (
735
+ name === 'twitter:image' &&
736
+ twitterImageValid &&
737
+ isRelativeUrl(content)
738
+ ) {
739
+ issues.push({
740
+ code: 'relative-twitter-image',
741
+ severity: 'warning',
742
+ tagName: 'meta',
743
+ path: `meta[${index}]`,
744
+ message: 'Twitter images should use absolute URLs.'
745
+ })
746
+ }
747
+ })
748
+
749
+ const hasActiveOpenGraph =
750
+ ogProperties.size > 1 ||
751
+ [...ogProperties].some((property) => property !== 'og:type')
752
+
753
+ if (hasActiveOpenGraph) {
754
+ const requiredProperties = [
755
+ 'og:title',
756
+ 'og:type',
757
+ 'og:url',
758
+ ...(options.requireOpenGraphImage ? ['og:image'] : [])
759
+ ]
760
+ for (const property of requiredProperties) {
761
+ if (!ogProperties.has(property)) {
762
+ issues.push({
763
+ code: 'missing-og-required',
764
+ severity: 'warning',
765
+ tagName: 'meta',
766
+ path: `meta[property="${property}"]`,
767
+ message: `Open Graph metadata is missing ${property}.`
768
+ })
769
+ }
770
+ }
771
+ }
772
+ }
773
+
774
+ function validateLinkItems(
775
+ linkItems: LinkItem[],
776
+ issues: HeadValidationIssue[],
777
+ options: HeadValidationOptions,
778
+ hasNoindex: boolean
779
+ ): void {
780
+ let canonicalCount = 0
781
+
782
+ linkItems.forEach((link, index) => {
783
+ validateUnsafeAttributes(link, 'link', `link[${index}]`, issues, options)
784
+ const rels = getRelTokens(link)
785
+ const href = normaliseAttrValue(link.href)
786
+ const path = `link[${index}]`
787
+
788
+ if (rels.includes('canonical')) {
789
+ canonicalCount += 1
790
+ const hrefValid = validateUrlValue(href, 'link', path, issues, options)
791
+ if (href && hrefValid && isRelativeUrl(href)) {
792
+ issues.push({
793
+ code: 'relative-canonical',
794
+ severity: 'warning',
795
+ tagName: 'link',
796
+ path,
797
+ message: 'Canonical links should be absolute URLs.'
798
+ })
799
+ }
800
+
801
+ if (hasNoindex) {
802
+ issues.push({
803
+ code: 'canonical-with-noindex',
804
+ severity: 'warning',
805
+ tagName: 'link',
806
+ path,
807
+ message: 'Avoid publishing a canonical URL on noindex pages.'
808
+ })
809
+ }
810
+ }
811
+
812
+ if (rels.includes('preconnect') && !href) {
813
+ issues.push({
814
+ code: 'preconnect-missing-href',
815
+ severity: 'warning',
816
+ tagName: 'link',
817
+ path,
818
+ message: 'Preconnect links need an href.'
819
+ })
820
+ }
821
+
822
+ if (rels.includes('dns-prefetch') && !href) {
823
+ issues.push({
824
+ code: 'dns-prefetch-missing-href',
825
+ severity: 'warning',
826
+ tagName: 'link',
827
+ path,
828
+ message: 'DNS-prefetch links need an href.'
829
+ })
830
+ }
831
+
832
+ if (rels.includes('preload')) validatePreload(link, issues, path)
833
+
834
+ if (rels.includes('modulepreload') && hasNonEmptyAttr(link, 'as')) {
835
+ issues.push({
836
+ code: 'modulepreload-with-as',
837
+ severity: 'warning',
838
+ tagName: 'link',
839
+ path,
840
+ message: 'modulepreload does not use an as attribute.'
841
+ })
842
+ }
843
+
844
+ validateSubresourceIntegrity(
845
+ link,
846
+ 'link',
847
+ path,
848
+ issues,
849
+ options,
850
+ isSriRelevantLink(link)
851
+ )
852
+ })
853
+
854
+ if (canonicalCount > 1) {
855
+ issues.push({
856
+ code: 'duplicate-canonical',
857
+ severity: 'warning',
858
+ tagName: 'link',
859
+ path: 'link[rel="canonical"]',
860
+ message: 'Multiple canonical links were provided; the last one wins.'
861
+ })
862
+ }
863
+ }
864
+
865
+ function validatePreload(
866
+ link: LinkItem,
867
+ issues: HeadValidationIssue[],
868
+ path: string
869
+ ): void {
870
+ const as = normaliseAttrValue(link.as).toLowerCase()
871
+ const href = normaliseAttrValue(link.href)
872
+ const imagesrcset = normaliseAttrValue(link.imagesrcset)
873
+ const hasResponsiveImageSource = as === 'image' && !!imagesrcset
874
+
875
+ if (!href && !hasResponsiveImageSource) {
876
+ issues.push({
877
+ code: 'missing-preload-source',
878
+ severity: 'warning',
879
+ tagName: 'link',
880
+ path,
881
+ message:
882
+ 'Preload links need an href, except responsive image preloads with imagesrcset.'
883
+ })
884
+ }
885
+
886
+ if (!as) {
887
+ issues.push({
888
+ code: 'missing-preload-as',
889
+ severity: 'warning',
890
+ tagName: 'link',
891
+ path,
892
+ message: 'Preload links need an as attribute.'
893
+ })
894
+ return
895
+ }
896
+
897
+ if (!VALID_PRELOAD_AS_VALUES.has(as)) {
898
+ issues.push({
899
+ code: 'invalid-preload-as',
900
+ severity: 'warning',
901
+ tagName: 'link',
902
+ path,
903
+ message: `Preload as="${as}" is not a standard destination.`
904
+ })
905
+ }
906
+
907
+ if (
908
+ as === 'image' &&
909
+ hasWidthDescriptorImageSrcset(imagesrcset) &&
910
+ !hasNonEmptyAttr(link, 'imagesizes')
911
+ ) {
912
+ issues.push({
913
+ code: 'responsive-image-missing-sizes',
914
+ severity: 'warning',
915
+ tagName: 'link',
916
+ path,
917
+ message:
918
+ 'Responsive image preloads with width descriptors need imagesizes.'
919
+ })
920
+ }
921
+
922
+ if (as === 'font' && !hasAttr(link, 'crossorigin')) {
923
+ issues.push({
924
+ code: 'font-preload-missing-crossorigin',
925
+ severity: 'warning',
926
+ tagName: 'link',
927
+ path,
928
+ message: 'Font preloads should include crossorigin, usually anonymous.'
929
+ })
930
+ }
931
+ }
932
+
933
+ function validateScriptItems(
934
+ scriptItems: ScriptItem[],
935
+ issues: HeadValidationIssue[],
936
+ options: HeadValidationOptions
937
+ ): void {
938
+ scriptItems.forEach((script, index) => {
939
+ const path = `script[${index}]`
940
+ validateUnsafeAttributes(script, 'script', path, issues, options)
941
+ validateSubresourceIntegrity(script, 'script', path, issues, options, true)
942
+ })
943
+ }
944
+
945
+ function validateContentItems(
946
+ items: ContentItem[],
947
+ tagName: 'style' | 'script' | 'noscript',
948
+ issues: HeadValidationIssue[],
949
+ options: HeadValidationOptions
950
+ ): void {
951
+ items.forEach((item, index) => {
952
+ const path = `${tagName}[${index}]`
953
+ validateUnsafeAttributes(item, tagName, path, issues, options)
954
+ if (options.warnOnInnerHTML !== false && item.innerHTML !== undefined) {
955
+ issues.push({
956
+ code: 'unsafe-inner-html',
957
+ severity: 'warning',
958
+ tagName,
959
+ path,
960
+ message: `${tagName}.innerHTML is rendered as trusted raw HTML. Prefer textContent where possible.`
961
+ })
962
+ }
963
+ })
964
+ }
965
+
966
+ function validateJsonLd(
967
+ jsonLdItems: JsonLdItem[],
968
+ issues: HeadValidationIssue[]
969
+ ): void {
970
+ jsonLdItems.forEach((item, index) => {
971
+ let serializable = true
972
+ try {
973
+ JSON.stringify({ ...item, '@context': 'https://schema.org' })
974
+ } catch {
975
+ serializable = false
976
+ issues.push({
977
+ code: 'invalid-json-ld',
978
+ severity: 'error',
979
+ tagName: 'jsonLd',
980
+ path: `jsonLd[${index}]`,
981
+ message: 'JSON-LD must be serializable with JSON.stringify().'
982
+ })
983
+ }
984
+
985
+ if (serializable && !normaliseAttrValue(item['@type'])) {
986
+ issues.push({
987
+ code: 'invalid-json-ld',
988
+ severity: 'warning',
989
+ tagName: 'jsonLd',
990
+ path: `jsonLd[${index}].@type`,
991
+ message: 'JSON-LD items should include @type.'
992
+ })
993
+ }
994
+ })
995
+ }
996
+
997
+ function validateUnsafeAttributes(
998
+ item: BaseItem,
999
+ tagName: TagName,
1000
+ path: string,
1001
+ issues: HeadValidationIssue[],
1002
+ options: HeadValidationOptions
1003
+ ): void {
1004
+ if (options.warnOnEventAttributes === false) return
1005
+
1006
+ for (const key of Object.keys(item)) {
1007
+ if (/^on/i.test(key)) {
1008
+ issues.push({
1009
+ code: 'unsafe-event-attribute',
1010
+ severity: 'warning',
1011
+ tagName,
1012
+ path: `${path}.${key}`,
1013
+ message: `Inline event attribute ${key} is allowed but should only contain trusted code.`
1014
+ })
1015
+ }
1016
+ }
1017
+ }
1018
+
1019
+ function validateSubresourceIntegrity(
1020
+ item: BaseItem,
1021
+ tagName: 'link' | 'script',
1022
+ path: string,
1023
+ issues: HeadValidationIssue[],
1024
+ options: HeadValidationOptions,
1025
+ relevant: boolean
1026
+ ): void {
1027
+ if (!relevant) return
1028
+ const url = normaliseAttrValue(tagName === 'script' ? item.src : item.href)
1029
+ if (!url) return
1030
+ validateUrlValue(url, tagName, path, issues, options)
1031
+ if (!isExternalHttpUrl(url, options.baseUrl)) return
1032
+
1033
+ if (hasNonEmptyAttr(item, 'integrity') && !hasAttr(item, 'crossorigin')) {
1034
+ issues.push({
1035
+ code: 'sri-missing-crossorigin',
1036
+ severity: 'warning',
1037
+ tagName,
1038
+ path,
1039
+ message: 'Cross-origin SRI resources should include crossorigin.'
1040
+ })
1041
+ }
1042
+
1043
+ if (options.requireSri && !hasNonEmptyAttr(item, 'integrity')) {
1044
+ issues.push({
1045
+ code: 'missing-sri',
1046
+ severity: 'warning',
1047
+ tagName,
1048
+ path,
1049
+ message:
1050
+ 'External scripts and stylesheets should include integrity when requireSri is enabled.'
1051
+ })
1052
+ }
1053
+ }
1054
+
1055
+ function validateUrlValue(
1056
+ value: string,
1057
+ tagName: 'meta' | 'link' | 'script',
1058
+ path: string,
1059
+ issues: HeadValidationIssue[],
1060
+ options: HeadValidationOptions
1061
+ ): boolean {
1062
+ if (!value || value.startsWith('//')) return true
1063
+ if (/\s/.test(value)) {
1064
+ issues.push({
1065
+ code: 'invalid-url',
1066
+ severity: 'warning',
1067
+ tagName,
1068
+ path,
1069
+ message: `Invalid URL: ${value}.`
1070
+ })
1071
+ return false
1072
+ }
1073
+ try {
1074
+ if (isRelativeUrl(value)) {
1075
+ if (options.baseUrl) new URL(value, toUrlString(options.baseUrl))
1076
+ return true
1077
+ }
1078
+ const parsed = new URL(value)
1079
+ if (parsed.protocol === 'http:' || parsed.protocol === 'https:') return true
1080
+ if (parsed.protocol === 'data:' || parsed.protocol === 'blob:') return true
1081
+ issues.push({
1082
+ code: 'invalid-url',
1083
+ severity: 'warning',
1084
+ tagName,
1085
+ path,
1086
+ message: `Unsupported URL protocol in ${value}.`
1087
+ })
1088
+ return false
1089
+ } catch {
1090
+ issues.push({
1091
+ code: 'invalid-url',
1092
+ severity: 'warning',
1093
+ tagName,
1094
+ path,
1095
+ message: `Invalid URL: ${value}.`
1096
+ })
1097
+ return false
1098
+ }
1099
+ }
1100
+
1101
+ function isSriRelevantLink(link: LinkItem): boolean {
1102
+ if (hasRel(link, 'stylesheet') || hasRel(link, 'modulepreload')) return true
1103
+ if (!hasRel(link, 'preload')) return false
1104
+ const as = normaliseAttrValue(link.as).toLowerCase()
1105
+ return as === 'script' || as === 'style'
1106
+ }
1107
+
1108
+ function hasWidthDescriptorImageSrcset(imagesrcset: string): boolean {
1109
+ return imagesrcset.split(',').some((candidate) => {
1110
+ const descriptor = candidate.trim().split(/\s+/).at(-1) || ''
1111
+ return /^\d+w$/.test(descriptor)
1112
+ })
1113
+ }
1114
+
1115
+ function hasRobotsDirective(metaItems: MetaItem[], directive: string): boolean {
1116
+ return metaItems.some(
1117
+ (meta) =>
1118
+ attrEquals(meta.name, 'robots') &&
1119
+ normaliseAttrValue(meta.content)
1120
+ .toLowerCase()
1121
+ .split(',')
1122
+ .map((token) => token.trim())
1123
+ .includes(directive)
1124
+ )
1125
+ }
1126
+
1127
+ function applyTitleTemplate(
1128
+ title: string,
1129
+ template: SeoHeadOptions['titleTemplate']
1130
+ ): string {
1131
+ if (!template) return title
1132
+ if (typeof template === 'function') return template(title)
1133
+ return template.includes('%s')
1134
+ ? template.replace(/%s/g, title)
1135
+ : title + template
1136
+ }
1137
+
1138
+ function createRobotsContent(options: SeoHeadOptions): string | undefined {
1139
+ if (typeof options.robots === 'string') return options.robots
1140
+ const robots: RobotsOptions = {
1141
+ ...(typeof options.robots === 'object' ? options.robots : {})
1142
+ }
1143
+
1144
+ if (options.noindex !== undefined) robots.index = !options.noindex
1145
+ if (options.nofollow !== undefined) robots.follow = !options.nofollow
1146
+
1147
+ const tokens: string[] = []
1148
+ if (robots.index === false) tokens.push('noindex')
1149
+ else if (robots.index === true) tokens.push('index')
1150
+
1151
+ if (robots.follow === false) tokens.push('nofollow')
1152
+ else if (robots.follow === true) tokens.push('follow')
1153
+
1154
+ if (robots.noarchive) tokens.push('noarchive')
1155
+ if (robots.nosnippet) tokens.push('nosnippet')
1156
+ if (robots.noimageindex) tokens.push('noimageindex')
1157
+ if (robots.nocache) tokens.push('nocache')
1158
+ if (typeof robots.maxSnippet === 'number')
1159
+ tokens.push(`max-snippet:${robots.maxSnippet}`)
1160
+ if (robots.maxImagePreview)
1161
+ tokens.push(`max-image-preview:${robots.maxImagePreview}`)
1162
+ if (typeof robots.maxVideoPreview === 'number')
1163
+ tokens.push(`max-video-preview:${robots.maxVideoPreview}`)
1164
+ if (Array.isArray(robots.extra)) tokens.push(...robots.extra)
1165
+ else if (robots.extra) tokens.push(robots.extra)
1166
+
1167
+ return tokens.length ? tokens.join(', ') : undefined
1168
+ }
1169
+
1170
+ function createOpenGraphMeta(
1171
+ openGraph: OpenGraphOptions,
1172
+ defaults: {
1173
+ title: string
1174
+ description?: string
1175
+ url?: string
1176
+ site?: string | URL
1177
+ }
1178
+ ): MetaItem[] {
1179
+ const meta: MetaItem[] = [
1180
+ {
1181
+ property: 'og:title',
1182
+ content: openGraph.title || defaults.title
1183
+ },
1184
+ {
1185
+ property: 'og:type',
1186
+ content: openGraph.type || 'website'
1187
+ }
1188
+ ]
1189
+
1190
+ const description = openGraph.description || defaults.description
1191
+ if (description)
1192
+ meta.push({
1193
+ property: 'og:description',
1194
+ content: description
1195
+ })
1196
+
1197
+ const url = openGraph.url
1198
+ ? resolveUrlString(openGraph.url, defaults.site)
1199
+ : defaults.url
1200
+ if (url) meta.push({ property: 'og:url', content: url })
1201
+
1202
+ if (openGraph.siteName)
1203
+ meta.push({
1204
+ property: 'og:site_name',
1205
+ content: openGraph.siteName
1206
+ })
1207
+
1208
+ if (openGraph.locale)
1209
+ meta.push({
1210
+ property: 'og:locale',
1211
+ content: openGraph.locale
1212
+ })
1213
+
1214
+ const images = Array.isArray(openGraph.image)
1215
+ ? openGraph.image
1216
+ : openGraph.image
1217
+ ? [openGraph.image]
1218
+ : []
1219
+ images.forEach((image, index) => {
1220
+ const normalised = normaliseSeoImage(image, defaults.site)
1221
+ const key = `og:image:${index}`
1222
+ meta.push({ key, property: 'og:image', content: normalised.url })
1223
+ if (normalised.alt)
1224
+ meta.push({
1225
+ key: `${key}:alt`,
1226
+ property: 'og:image:alt',
1227
+ content: normalised.alt
1228
+ })
1229
+ if (normalised.width)
1230
+ meta.push({
1231
+ key: `${key}:width`,
1232
+ property: 'og:image:width',
1233
+ content: normalised.width
1234
+ })
1235
+ if (normalised.height)
1236
+ meta.push({
1237
+ key: `${key}:height`,
1238
+ property: 'og:image:height',
1239
+ content: normalised.height
1240
+ })
1241
+ if (normalised.type)
1242
+ meta.push({
1243
+ key: `${key}:type`,
1244
+ property: 'og:image:type',
1245
+ content: normalised.type
1246
+ })
1247
+ })
1248
+
1249
+ return meta
1250
+ }
1251
+
1252
+ function createTwitterMeta(
1253
+ twitter: TwitterOptions,
1254
+ defaults: { title: string; description?: string; site?: string | URL }
1255
+ ): MetaItem[] {
1256
+ const meta: MetaItem[] = [
1257
+ {
1258
+ name: 'twitter:card',
1259
+ content:
1260
+ twitter.card || (twitter.image ? 'summary_large_image' : 'summary')
1261
+ },
1262
+ {
1263
+ name: 'twitter:title',
1264
+ content: twitter.title || defaults.title
1265
+ }
1266
+ ]
1267
+
1268
+ const description = twitter.description || defaults.description
1269
+ if (description)
1270
+ meta.push({
1271
+ name: 'twitter:description',
1272
+ content: description
1273
+ })
1274
+
1275
+ if (twitter.image)
1276
+ meta.push({
1277
+ name: 'twitter:image',
1278
+ content: resolveUrlString(twitter.image, defaults.site)
1279
+ })
1280
+
1281
+ if (twitter.imageAlt)
1282
+ meta.push({
1283
+ name: 'twitter:image:alt',
1284
+ content: twitter.imageAlt
1285
+ })
1286
+
1287
+ if (twitter.site)
1288
+ meta.push({
1289
+ name: 'twitter:site',
1290
+ content: twitter.site
1291
+ })
1292
+
1293
+ if (twitter.creator)
1294
+ meta.push({
1295
+ name: 'twitter:creator',
1296
+ content: twitter.creator
1297
+ })
1298
+
1299
+ return meta
1300
+ }
1301
+
1302
+ function normaliseSeoImage(
1303
+ image: SeoImage,
1304
+ baseUrl?: string | URL
1305
+ ): {
1306
+ url: string
1307
+ alt?: string
1308
+ width?: number
1309
+ height?: number
1310
+ type?: string
1311
+ } {
1312
+ if (typeof image === 'string' || image instanceof URL)
1313
+ return { url: resolveUrlString(image, baseUrl) }
1314
+
1315
+ return {
1316
+ ...image,
1317
+ url: resolveUrlString(image.url, baseUrl)
1318
+ }
1319
+ }
1320
+
1321
+ function toUrlString(value: string | URL): string {
1322
+ return value instanceof URL ? value.toString() : String(value)
1323
+ }
1324
+
1325
+ function resolveUrlString(value: string | URL, baseUrl?: string | URL): string {
1326
+ const url = toUrlString(value)
1327
+ if (!baseUrl) return url
1328
+ try {
1329
+ return new URL(url, toUrlString(baseUrl)).toString()
1330
+ } catch {
1331
+ return url
1332
+ }
1333
+ }
1334
+
1335
+ function isRelativeUrl(value: string): boolean {
1336
+ if (!value) return false
1337
+ try {
1338
+ new URL(value)
1339
+ return false
1340
+ } catch {
1341
+ return true
1342
+ }
1343
+ }
1344
+
1345
+ function isExternalHttpUrl(value: string, baseUrl?: string | URL): boolean {
1346
+ let url: URL
1347
+ try {
1348
+ url = baseUrl ? new URL(value, toUrlString(baseUrl)) : new URL(value)
1349
+ } catch {
1350
+ return false
1351
+ }
1352
+
1353
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return false
1354
+ if (!baseUrl) return true
1355
+
1356
+ try {
1357
+ return url.origin !== new URL(toUrlString(baseUrl)).origin
1358
+ } catch {
1359
+ return true
1360
+ }
1361
+ }
1362
+
242
1363
  function escapeJsonLd(json: string): string {
243
- return json.replace(/<\//g, '<\\/')
1364
+ return json.replace(/<\//gi, '<\\/')
244
1365
  }
245
1366
 
246
1367
  function deduplicateMetaItems(metaItems: BaseItem[]): BaseItem[] {
@@ -267,25 +1388,116 @@ function deduplicateMetaItems(metaItems: BaseItem[]): BaseItem[] {
267
1388
  }
268
1389
 
269
1390
  function getMetaDeduplicationKey(meta: BaseItem): string | undefined {
270
- const media = String(meta.media || '')
271
- if (meta.property) return `property:${meta.property}:${media}`
272
- if (meta.name) return `name:${meta.name}:${media}`
273
- if (meta['http-equiv']) return `http-equiv:${meta['http-equiv']}:${media}`
274
- if (meta.charset) return `charset::${media}`
1391
+ const explicitKey = getExplicitDeduplicationKey(meta)
1392
+ if (explicitKey) return explicitKey
1393
+
1394
+ const media = normaliseAttrValue(meta.media)
1395
+ if (hasNonEmptyAttr(meta, 'property'))
1396
+ return `property:${normaliseAttrValue(meta.property)}:${media}`
1397
+ if (hasNonEmptyAttr(meta, 'name'))
1398
+ return `name:${normaliseAttrValue(meta.name).toLowerCase()}:${media}`
1399
+ if (hasNonEmptyAttr(meta, 'http-equiv'))
1400
+ return `http-equiv:${normaliseAttrValue(meta['http-equiv']).toLowerCase()}:${media}`
1401
+ if (hasNonEmptyAttr(meta, 'charset')) return `charset::${media}`
1402
+ }
1403
+
1404
+ function deduplicateLinkItems(linkItems: BaseItem[]): BaseItem[] {
1405
+ const deduplicated: BaseItem[] = []
1406
+ const itemIndexByKey = new Map<string, number>()
1407
+
1408
+ for (const link of linkItems) {
1409
+ const key = getLinkDeduplicationKey(link)
1410
+ if (!key) {
1411
+ deduplicated.push(link)
1412
+ continue
1413
+ }
1414
+
1415
+ const existingIndex = itemIndexByKey.get(key)
1416
+ if (existingIndex === undefined) {
1417
+ itemIndexByKey.set(key, deduplicated.length)
1418
+ deduplicated.push(link)
1419
+ } else {
1420
+ deduplicated[existingIndex] = link
1421
+ }
1422
+ }
1423
+
1424
+ return deduplicated
1425
+ }
1426
+
1427
+ function deduplicateKeyedItems<T extends BaseItem>(items: T[]): T[] {
1428
+ const deduplicated: T[] = []
1429
+ const itemIndexByKey = new Map<string, number>()
1430
+
1431
+ for (const item of items) {
1432
+ const key = getExplicitDeduplicationKey(item)
1433
+ if (!key) {
1434
+ deduplicated.push(item)
1435
+ continue
1436
+ }
1437
+
1438
+ const existingIndex = itemIndexByKey.get(key)
1439
+ if (existingIndex === undefined) {
1440
+ itemIndexByKey.set(key, deduplicated.length)
1441
+ deduplicated.push(item)
1442
+ } else {
1443
+ deduplicated[existingIndex] = item
1444
+ }
1445
+ }
1446
+
1447
+ return deduplicated
1448
+ }
1449
+
1450
+ function getLinkDeduplicationKey(link: BaseItem): string | undefined {
1451
+ const explicitKey = getExplicitDeduplicationKey(link)
1452
+ if (explicitKey) return explicitKey
1453
+
1454
+ const rels = getRelTokens(link)
1455
+ const href = normaliseAttrValue(link.href)
1456
+ const media = normaliseAttrValue(link.media)
1457
+ const as = normaliseAttrValue(link.as).toLowerCase()
1458
+ const type = normaliseAttrValue(link.type).toLowerCase()
1459
+ const crossorigin = normaliseAttrValue(link.crossorigin).toLowerCase()
1460
+ const imagesrcset = normaliseAttrValue(link.imagesrcset)
1461
+ const imagesizes = normaliseAttrValue(link.imagesizes)
1462
+
1463
+ if (rels.includes('canonical')) return 'canonical'
1464
+
1465
+ if ((rels.includes('preconnect') || rels.includes('dns-prefetch')) && href)
1466
+ return `${rels.join(' ')}:${href}`
1467
+
1468
+ if (rels.includes('preload') || rels.includes('modulepreload')) {
1469
+ if (!href && !(rels.includes('preload') && as === 'image' && imagesrcset))
1470
+ return undefined
1471
+ return [
1472
+ rels.join(' '),
1473
+ href,
1474
+ as,
1475
+ type,
1476
+ crossorigin,
1477
+ media,
1478
+ imagesrcset,
1479
+ imagesizes
1480
+ ].join(':')
1481
+ }
275
1482
  }
276
1483
 
277
1484
  function renderHeadTag(item: BaseItem | ContentItem): string {
278
1485
  const attrs = renderAttrs(item)
279
1486
  return ['meta', 'link', 'base'].includes(item.tagName)
280
1487
  ? `<${item.tagName}${attrs ? ' ' + attrs : ''}>`
281
- : `<${item.tagName}${attrs && ' '}${attrs}>${item.innerHTML || ''}</${
1488
+ : `<${item.tagName}${attrs && ' '}${attrs}>${getTagContent(item)}</${
282
1489
  item.tagName
283
1490
  }>`
284
1491
  }
285
1492
 
286
1493
  export function renderAttrs(item: BaseItem | ContentItem): string {
287
1494
  return Object.entries(item)
288
- .filter(([key]) => !['innerHTML', 'priority', 'tagName'].includes(key))
1495
+ .filter(
1496
+ ([key]) =>
1497
+ !['innerHTML', 'textContent', 'priority', 'tagName', 'key'].includes(
1498
+ key
1499
+ )
1500
+ )
289
1501
  .filter(([key]) => isValidAttributeName(key))
290
1502
  .map(([key, value]) => {
291
1503
  if (typeof value === 'boolean') return value ? key : ''
@@ -300,6 +1512,56 @@ function isValidAttributeName(key: string): boolean {
300
1512
  return /^[^\s"'<>/=]+$/.test(key)
301
1513
  }
302
1514
 
1515
+ function getTagContent(item: BaseItem | ContentItem): string {
1516
+ if ('textContent' in item && item.textContent !== undefined) {
1517
+ const content = String(item.textContent)
1518
+ if (item.tagName === 'script') return escapeRawText(content, 'script')
1519
+ if (item.tagName === 'style') return escapeRawText(content, 'style')
1520
+ return escapeHtml(content)
1521
+ }
1522
+
1523
+ return 'innerHTML' in item && item.innerHTML !== undefined
1524
+ ? String(item.innerHTML)
1525
+ : ''
1526
+ }
1527
+
1528
+ function escapeRawText(content: string, tagName: 'script' | 'style'): string {
1529
+ return content.replace(new RegExp(`</${tagName}`, 'gi'), `<\\/${tagName}`)
1530
+ }
1531
+
1532
+ function hasAttr(item: BaseItem | ContentItem, key: string): boolean {
1533
+ return item[key] !== null && item[key] !== undefined
1534
+ }
1535
+
1536
+ function hasNonEmptyAttr(item: BaseItem | ContentItem, key: string): boolean {
1537
+ return normaliseAttrValue(item[key]) !== ''
1538
+ }
1539
+
1540
+ function attrEquals(value: unknown, expected: string): boolean {
1541
+ return normaliseAttrValue(value).toLowerCase() === expected
1542
+ }
1543
+
1544
+ function hasRel(item: BaseItem | ContentItem, rel: string): boolean {
1545
+ return getRelTokens(item).includes(rel)
1546
+ }
1547
+
1548
+ function getRelTokens(item: BaseItem | ContentItem): string[] {
1549
+ return normaliseAttrValue(item.rel)
1550
+ .toLowerCase()
1551
+ .split(/\s+/)
1552
+ .filter(Boolean)
1553
+ .sort()
1554
+ }
1555
+
1556
+ function normaliseAttrValue(value: unknown): string {
1557
+ return value === null || value === undefined ? '' : String(value).trim()
1558
+ }
1559
+
1560
+ function getExplicitDeduplicationKey(item: BaseItem): string | undefined {
1561
+ const key = normaliseAttrValue(item.key)
1562
+ return key ? `key:${key}` : undefined
1563
+ }
1564
+
303
1565
  function escapeHtml(str: string): string {
304
1566
  const escapeMap: Record<string, string> = {
305
1567
  '"': '&quot;',