@dukebot/astro-html-validator 1.1.2 → 1.1.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dukebot/astro-html-validator",
3
- "version": "1.1.2",
3
+ "version": "1.1.4",
4
4
  "description": "Validate Astro-generated HTML output for SEO metadata, JSON-LD, and internal links.",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -19,6 +19,8 @@
19
19
  ],
20
20
  "scripts": {
21
21
  "check": "node ./bin/cli.mjs --help",
22
+ "test": "node --test",
23
+ "test:links": "node --test tests/links-utils.test.mjs",
22
24
  "validate:dist": "node ./bin/cli.mjs"
23
25
  },
24
26
  "keywords": [
@@ -35,5 +37,8 @@
35
37
  },
36
38
  "publishConfig": {
37
39
  "access": "public"
40
+ },
41
+ "dependencies": {
42
+ "parse5": "^8.0.0"
38
43
  }
39
44
  }
@@ -1,4 +1,5 @@
1
1
  import path from 'node:path';
2
+ import { parse } from 'parse5';
2
3
  import { pathExists } from './common.mjs';
3
4
 
4
5
  /**
@@ -30,15 +31,34 @@ function toLocalPathFromAbsolute(rawUrl, absolutePrefixes) {
30
31
  }
31
32
 
32
33
  /**
33
- * Removes non-rendered sections to avoid false positives when extracting links.
34
+ * Collects href/src attribute values from parsed HTML element nodes.
34
35
  */
35
- function sanitizeHtmlForLinkExtraction(html = '') {
36
- if (!html) return '';
36
+ function collectHtmlLinkAttributes(html = '') {
37
+ if (!html) return [];
38
+
39
+ const urls = [];
40
+ const document = parse(html, { sourceCodeLocationInfo: false });
41
+ const queue = [document];
42
+
43
+ while (queue.length > 0) {
44
+ const node = queue.shift();
45
+ if (!node) continue;
46
+
47
+ if (Array.isArray(node.attrs)) {
48
+ for (const attr of node.attrs) {
49
+ if (!attr?.name || !attr?.value) continue;
50
+ if (attr.name !== 'href' && attr.name !== 'src') continue;
51
+ urls.push(attr.value);
52
+ }
53
+ }
54
+
55
+ if (node.content) queue.push(node.content);
56
+ if (Array.isArray(node.childNodes) && node.childNodes.length > 0) {
57
+ queue.push(...node.childNodes);
58
+ }
59
+ }
37
60
 
38
- return html
39
- .replace(/<!--[\s\S]*?-->/g, '')
40
- .replace(/<script\b[\s\S]*?<\/script>/gi, '')
41
- .replace(/<style\b[\s\S]*?<\/style>/gi, '');
61
+ return urls;
42
62
  }
43
63
 
44
64
  /**
@@ -46,47 +66,35 @@ function sanitizeHtmlForLinkExtraction(html = '') {
46
66
  */
47
67
  export function extractInternalUrls(html, { absoluteUrlPrefixes = [] } = {}) {
48
68
  const urls = new Set();
49
- const tagRegex = /<[^>]+>/g;
50
- const attrRegex = /\b(?:href|src)\s*=\s*["']([^"']+)["']/gi;
51
69
  const absolutePrefixes = normalizeAbsolutePrefixes(absoluteUrlPrefixes);
52
- const safeHtml = sanitizeHtmlForLinkExtraction(html);
53
-
54
- let tagMatch;
55
- while ((tagMatch = tagRegex.exec(safeHtml)) !== null) {
56
- const tag = tagMatch[0];
57
- if (!tag || tag.startsWith('</')) continue;
58
-
59
- let attrMatch;
60
- while ((attrMatch = attrRegex.exec(tag)) !== null) {
61
- const raw = attrMatch[1]?.trim();
62
- if (!raw) continue;
63
-
64
- if (
65
- raw.startsWith('//') ||
66
- raw.startsWith('#') ||
67
- raw.startsWith('mailto:') ||
68
- raw.startsWith('tel:') ||
69
- raw.startsWith('javascript:') ||
70
- raw.startsWith('data:')
71
- ) {
72
- continue;
73
- }
74
70
 
75
- const clean = raw.split(/[?#]/)[0];
76
- if (!clean) continue;
71
+ for (const value of collectHtmlLinkAttributes(html)) {
72
+ const raw = value?.trim();
73
+ if (!raw) continue;
74
+
75
+ if (
76
+ raw.startsWith('//') ||
77
+ raw.startsWith('#') ||
78
+ raw.startsWith('mailto:') ||
79
+ raw.startsWith('tel:') ||
80
+ raw.startsWith('javascript:') ||
81
+ raw.startsWith('data:')
82
+ ) {
83
+ continue;
84
+ }
77
85
 
78
- if (clean.startsWith('/')) {
79
- urls.add(clean);
80
- continue;
81
- }
86
+ const clean = raw.split(/[?#]/)[0];
87
+ if (!clean) continue;
82
88
 
83
- if (clean.startsWith('http://') || clean.startsWith('https://')) {
84
- const localPath = toLocalPathFromAbsolute(clean, absolutePrefixes);
85
- if (localPath) urls.add(localPath);
86
- }
89
+ if (clean.startsWith('/')) {
90
+ urls.add(clean);
91
+ continue;
87
92
  }
88
93
 
89
- attrRegex.lastIndex = 0;
94
+ if (clean.startsWith('http://') || clean.startsWith('https://')) {
95
+ const localPath = toLocalPathFromAbsolute(clean, absolutePrefixes);
96
+ if (localPath) urls.add(localPath);
97
+ }
90
98
  }
91
99
 
92
100
  return [...urls];
@@ -1,122 +1,181 @@
1
- import { getAttr } from './common.mjs';
2
-
3
- // Core metadata tags expected on every page.
4
- export const REQUIRED_META_CHECKS = [
5
- { label: 'meta title', check: getTitleContent },
6
- { label: 'meta description', check: (html) => hasMeta(html, 'description') },
7
- { label: 'canonical', check: hasCanonical },
8
- { label: 'meta robots', check: (html) => hasMeta(html, 'robots') },
9
- { label: 'og:title', check: (html) => hasMeta(html, 'og:title', true) },
10
- { label: 'og:description', check: (html) => hasMeta(html, 'og:description', true) },
11
- { label: 'og:url', check: (html) => hasMeta(html, 'og:url', true) },
12
- { label: 'og:type', check: (html) => hasMeta(html, 'og:type', true) },
13
- ];
14
-
15
- /**
16
- * Returns whether a meta tag exists with the expected key and non-empty content.
17
- */
18
- export function hasMeta(html, name, isProperty = false) {
19
- const tags = html.match(/<meta\b[^>]*>/gi) || [];
20
- return tags.some((tag) => {
21
- const key = isProperty ? getAttr(tag, 'property') : getAttr(tag, 'name');
22
- if (!key || key !== name) return false;
23
- const content = getAttr(tag, 'content');
24
- return !!content;
25
- });
26
- }
27
-
28
- /**
29
- * Returns the `content` value for a meta tag by name/property.
30
- */
31
- export function getMetaContent(html, name, isProperty = false) {
32
- const tags = html.match(/<meta\b[^>]*>/gi) || [];
33
- for (const tag of tags) {
34
- const key = isProperty ? getAttr(tag, 'property') : getAttr(tag, 'name');
35
- if (!key || key !== name) continue;
36
- const content = getAttr(tag, 'content');
37
- if (content) return content;
38
- }
39
- return '';
40
- }
41
-
42
- /**
43
- * Checks that a canonical link tag exists with a non-empty href.
44
- */
45
- export function hasCanonical(html) {
46
- const links = html.match(/<link\b[^>]*>/gi) || [];
47
- return links.some((tag) => {
48
- const rel = getAttr(tag, 'rel');
49
- if (!rel || rel.toLowerCase() !== 'canonical') return false;
50
- const href = getAttr(tag, 'href');
51
- return !!href;
52
- });
53
- }
54
-
55
- /**
56
- * Extracts the document title text.
57
- */
58
- export function getTitleContent(html) {
59
- const match = html.match(/<title>([^<]+)<\/title>/i);
60
- return match?.[1]?.trim() ?? '';
61
- }
62
-
63
- /**
64
- * Validates optional length ranges for title/description fields.
65
- */
66
- export function validateLengthRange({ value, min = 1, max = Infinity, fieldLabel }) {
67
- if (!value) return;
68
- if (value.length >= min && value.length <= max) return;
69
- return `Recommended ${fieldLabel} length is ${min}-${max}. Current: ${value.length}.`;
70
- }
71
-
72
- /**
73
- * Evaluates all mandatory metadata checks for a page.
74
- */
75
- export function validateRequiredMeta(html) {
76
- const warnings = [];
77
-
78
- for (const item of REQUIRED_META_CHECKS) {
79
- if (!item.check(html)) {
80
- warnings.push(`Missing ${item.label}.`);
81
- }
82
- }
83
-
84
- return warnings;
85
- }
86
-
87
- /**
88
- * Runs required and optional SEO metadata checks for one HTML string.
89
- */
90
- export function validateHtmlMeta(
91
- html,
92
- {
93
- metaTitleMinLength,
94
- metaTitleMaxLength,
95
- metaDescriptionMinLength,
96
- metaDescriptionMaxLength,
97
- } = {}
98
- ) {
99
- const warnings = [];
100
-
101
- warnings.push(...validateRequiredMeta(html));
102
-
103
- warnings.push(
104
- validateLengthRange({
105
- value: getTitleContent(html),
106
- min: metaTitleMinLength,
107
- max: metaTitleMaxLength,
108
- fieldLabel: 'meta title',
109
- })
110
- );
111
-
112
- warnings.push(
113
- validateLengthRange({
114
- value: getMetaContent(html, 'description'),
115
- min: metaDescriptionMinLength,
116
- max: metaDescriptionMaxLength,
117
- fieldLabel: 'meta description',
118
- })
119
- );
120
-
121
- return warnings.filter(Boolean);
122
- }
1
+ import { parse } from 'parse5';
2
+
3
+ function parseHtmlDocument(html = '') {
4
+ if (!html) return null;
5
+ return parse(html, { sourceCodeLocationInfo: false });
6
+ }
7
+
8
+ function getAttrValue(node, attrName) {
9
+ if (!Array.isArray(node?.attrs)) return '';
10
+ const attr = node.attrs.find((item) => item?.name?.toLowerCase() === attrName.toLowerCase());
11
+ return attr?.value?.trim() ?? '';
12
+ }
13
+
14
+ function findFirstNode(root, predicate) {
15
+ if (!root) return null;
16
+
17
+ const queue = [root];
18
+ while (queue.length > 0) {
19
+ const node = queue.shift();
20
+ if (!node) continue;
21
+ if (predicate(node)) return node;
22
+
23
+ if (node.content) queue.push(node.content);
24
+ if (Array.isArray(node.childNodes) && node.childNodes.length > 0) {
25
+ queue.push(...node.childNodes);
26
+ }
27
+ }
28
+
29
+ return null;
30
+ }
31
+
32
+ function getNodeText(node) {
33
+ if (!node) return '';
34
+
35
+ let text = '';
36
+ const queue = [node];
37
+ while (queue.length > 0) {
38
+ const current = queue.shift();
39
+ if (!current) continue;
40
+
41
+ if (current.nodeName === '#text' && typeof current.value === 'string') {
42
+ text += current.value;
43
+ }
44
+
45
+ if (current.content) queue.push(current.content);
46
+ if (Array.isArray(current.childNodes) && current.childNodes.length > 0) {
47
+ queue.push(...current.childNodes);
48
+ }
49
+ }
50
+
51
+ return text.replace(/\s+/g, ' ').trim();
52
+ }
53
+
54
+ function getMetaNode(document, name, isProperty = false) {
55
+ const attrName = isProperty ? 'property' : 'name';
56
+ const normalizedExpected = String(name).trim().toLowerCase();
57
+
58
+ return findFirstNode(document, (node) => {
59
+ if (node?.tagName !== 'meta') return false;
60
+ const key = getAttrValue(node, attrName).toLowerCase();
61
+ return key === normalizedExpected;
62
+ });
63
+ }
64
+
65
+ function getStringLength(value) {
66
+ return Array.from(value.normalize('NFC')).length;
67
+ }
68
+
69
+ // Core metadata tags expected on every page.
70
+ export const REQUIRED_META_CHECKS = [
71
+ { label: 'meta title', check: getTitleContent },
72
+ { label: 'meta description', check: (html) => hasMeta(html, 'description') },
73
+ { label: 'canonical', check: hasCanonical },
74
+ { label: 'meta robots', check: (html) => hasMeta(html, 'robots') },
75
+ { label: 'og:title', check: (html) => hasMeta(html, 'og:title', true) },
76
+ { label: 'og:description', check: (html) => hasMeta(html, 'og:description', true) },
77
+ { label: 'og:url', check: (html) => hasMeta(html, 'og:url', true) },
78
+ { label: 'og:type', check: (html) => hasMeta(html, 'og:type', true) },
79
+ ];
80
+
81
+ /**
82
+ * Returns whether a meta tag exists with the expected key and non-empty content.
83
+ */
84
+ export function hasMeta(html, name, isProperty = false) {
85
+ return !!getMetaContent(html, name, isProperty);
86
+ }
87
+
88
+ /**
89
+ * Returns the `content` value for a meta tag by name/property.
90
+ */
91
+ export function getMetaContent(html, name, isProperty = false) {
92
+ const document = parseHtmlDocument(html);
93
+ const node = getMetaNode(document, name, isProperty);
94
+ return getAttrValue(node, 'content');
95
+ }
96
+
97
+ /**
98
+ * Checks that a canonical link tag exists with a non-empty href.
99
+ */
100
+ export function hasCanonical(html) {
101
+ const document = parseHtmlDocument(html);
102
+
103
+ return !!findFirstNode(document, (node) => {
104
+ if (node?.tagName !== 'link') return false;
105
+ const rel = getAttrValue(node, 'rel').toLowerCase();
106
+ if (rel !== 'canonical') return false;
107
+ return !!getAttrValue(node, 'href');
108
+ });
109
+ }
110
+
111
+ /**
112
+ * Extracts the document title text.
113
+ */
114
+ export function getTitleContent(html) {
115
+ const document = parseHtmlDocument(html);
116
+ const titleNode = findFirstNode(document, (node) => node?.tagName === 'title');
117
+ return getNodeText(titleNode);
118
+ }
119
+
120
+ /**
121
+ * Validates optional length ranges for title/description fields.
122
+ */
123
+ export function validateLengthRange({ value, min = 1, max = Infinity, fieldLabel }) {
124
+ if (!value) return;
125
+
126
+ const length = getStringLength(value);
127
+ if (length >= min && length <= max) return;
128
+ return `Recommended ${fieldLabel} length is ${min}-${max}. Current: ${length}.`;
129
+ }
130
+
131
+ /**
132
+ * Evaluates all mandatory metadata checks for a page.
133
+ */
134
+ export function validateRequiredMeta(html) {
135
+ const warnings = [];
136
+
137
+ for (const item of REQUIRED_META_CHECKS) {
138
+ if (!item.check(html)) {
139
+ warnings.push(`Missing ${item.label}.`);
140
+ }
141
+ }
142
+
143
+ return warnings;
144
+ }
145
+
146
+ /**
147
+ * Runs required and optional SEO metadata checks for one HTML string.
148
+ */
149
+ export function validateHtmlMeta(
150
+ html,
151
+ {
152
+ metaTitleMinLength,
153
+ metaTitleMaxLength,
154
+ metaDescriptionMinLength,
155
+ metaDescriptionMaxLength,
156
+ } = {}
157
+ ) {
158
+ const warnings = [];
159
+
160
+ warnings.push(...validateRequiredMeta(html));
161
+
162
+ warnings.push(
163
+ validateLengthRange({
164
+ value: getTitleContent(html),
165
+ min: metaTitleMinLength,
166
+ max: metaTitleMaxLength,
167
+ fieldLabel: 'meta title',
168
+ })
169
+ );
170
+
171
+ warnings.push(
172
+ validateLengthRange({
173
+ value: getMetaContent(html, 'description'),
174
+ min: metaDescriptionMinLength,
175
+ max: metaDescriptionMaxLength,
176
+ fieldLabel: 'meta description',
177
+ })
178
+ );
179
+
180
+ return warnings.filter(Boolean);
181
+ }