@uxfront/site-checks 0.0.0 → 0.1.0

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/lib/html.js ADDED
@@ -0,0 +1,259 @@
1
+ /** @import { Entity, ParseProfile, Scope } from "../index.js" */
2
+
3
+ /** @typedef {Required<ParseProfile>} Profile */
4
+
5
+ /** @type {Readonly<Record<string, string>>} */
6
+ const NAMED = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
7
+
8
+ /**
9
+ * The character a numeric reference like `#x27` or `#39` stands for. A reference past the last
10
+ * code point throws, as `String.fromCodePoint` does, so the page's rule reports it.
11
+ * @param {string} code
12
+ */
13
+ const numeric = (code) =>
14
+ String.fromCodePoint(
15
+ code[1]?.toLowerCase() === "x"
16
+ ? Number.parseInt(code.slice(2), 16)
17
+ : Number.parseInt(code.slice(1), 10),
18
+ );
19
+
20
+ /** @param {string} text */
21
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
22
+
23
+ /**
24
+ * A decoder for the profile's entities. `one-pass` decodes each reference once, so `&amp;lt;`
25
+ * stays `&lt;`. `numeric-first` decodes numeric references before named ones, so `&#38;lt;`
26
+ * becomes `<`.
27
+ * @param {Pick<Profile, "decode" | "decodeOrder" | "decodeIgnoreCase">} profile
28
+ * @returns {(text: string) => string}
29
+ */
30
+ export function decoder({ decode: entities, decodeOrder, decodeIgnoreCase }) {
31
+ const named = entities.filter((entity) => entity !== "numeric");
32
+ const flags = decodeIgnoreCase ? "gi" : "g";
33
+ const NUMERIC = "#[xX][\\da-fA-F]+|#\\d+";
34
+ /** @param {string} code */
35
+ const value = (code) =>
36
+ code.startsWith("#") && entities.includes("numeric")
37
+ ? numeric(code)
38
+ : (NAMED[decodeIgnoreCase ? code.toLowerCase() : code] ??
39
+ (code.startsWith("#") ? numeric(code) : `&${code};`));
40
+ /** @param {string[]} alternatives */
41
+ const replacer = (alternatives) => {
42
+ if (!alternatives.length) return (/** @type {string} */ text) => text;
43
+ const pattern = new RegExp(`&(${alternatives.join("|")});`, flags);
44
+ return (/** @type {string} */ text) =>
45
+ text.replace(pattern, (_, /** @type {string} */ code) => value(code));
46
+ };
47
+ const numerics = entities.includes("numeric") ? [NUMERIC] : [];
48
+ const names = named.map(escapeRegExp);
49
+ if (decodeOrder === "numeric-first") {
50
+ const first = replacer(numerics);
51
+ const second = replacer(names);
52
+ return (text) => second(first(text));
53
+ }
54
+ return replacer([...numerics, ...names]);
55
+ }
56
+
57
+ /**
58
+ * The part of a page that a scope reads.
59
+ * @param {string} html
60
+ * @param {Scope} scope
61
+ */
62
+ export function scoped(html, scope) {
63
+ if (scope === "document") return html;
64
+ if (scope === "markup") return html.replace(/<script\b[\s\S]*?<\/script>|<!--[\s\S]*?-->/gi, "");
65
+ if (scope === "head-element") return html.match(/<head[\s>][\s\S]*?<\/head>/i)?.[0] ?? "";
66
+ const end = html.indexOf("</head>");
67
+ return end > 0 ? html.slice(0, end) : html;
68
+ }
69
+
70
+ // A tag's attributes, where a quoted value may hold a `>`, as in `content="<component is>"`.
71
+ const ATTRS = `(?:[^>"']|"[^"]*"|'[^']*')*`;
72
+
73
+ /**
74
+ * The regular expression that finds a tag by name, as the profile reads tags.
75
+ * @param {string} name
76
+ * @param {Pick<Profile, "quotes" | "caseSensitiveTags" | "tagEnd">} profile
77
+ * @param {string} [after] What follows the tag, like its body and end tag.
78
+ */
79
+ export function tagPattern(name, { quotes, caseSensitiveTags, tagEnd }, after = "") {
80
+ const end = tagEnd === "word" ? "\\b" : "(?=[\\s/>])";
81
+ const attributes = quotes === "double" ? "[^>]*" : ATTRS;
82
+ return new RegExp(`<${name}${end}(${attributes})>${after}`, caseSensitiveTags ? "g" : "gi");
83
+ }
84
+
85
+ /**
86
+ * The attributes in a tag's source, with lower-case names and decoded values. With `double`, only
87
+ * double-quoted values are read.
88
+ * @param {string} source
89
+ * @param {Profile["quotes"]} quotes
90
+ * @param {(text: string) => string} decode
91
+ */
92
+ export function attributes(source, quotes, decode) {
93
+ /** @type {Record<string, string>} */
94
+ const found = {};
95
+ if (quotes === "double") {
96
+ for (const [, key = "", value = ""] of source.matchAll(/([\w:-]+)="([^"]*)"/g)) {
97
+ found[key.toLowerCase()] = decode(value);
98
+ }
99
+ return found;
100
+ }
101
+ for (const [, key = "", double, single, bare] of source.matchAll(
102
+ /([^\s=/>"']+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+)))?/g,
103
+ )) {
104
+ found[key.toLowerCase()] = decode(double ?? single ?? bare ?? "");
105
+ }
106
+ return found;
107
+ }
108
+
109
+ /**
110
+ * The attributes of every `<name …>` tag, as the profile reads them.
111
+ * @param {string} html
112
+ * @param {string} name
113
+ * @param {Profile} profile
114
+ * @param {(text: string) => string} decode
115
+ * @returns {Record<string, string>[]}
116
+ */
117
+ export function tags(html, name, profile, decode) {
118
+ return [...html.matchAll(tagPattern(name, profile))].map(([, source = ""]) =>
119
+ attributes(source, profile.quotes, decode),
120
+ );
121
+ }
122
+
123
+ /**
124
+ * The text of each `<title>`, as the profile's `titleTag` finds them: `any` takes attributes and
125
+ * any text, `plain-text` attributes and text without a `<`, and `bare` neither.
126
+ * @param {string} html
127
+ * @param {Profile} profile
128
+ */
129
+ export function titleTexts(html, { titleTag, caseSensitiveTags }) {
130
+ const source =
131
+ titleTag === "any"
132
+ ? "<title\\b[^>]*>([\\s\\S]*?)</title>"
133
+ : titleTag === "plain-text"
134
+ ? "<title[^>]*>([^<]*)</title>"
135
+ : "<title>([^<]*)</title>";
136
+ return [...html.matchAll(new RegExp(source, caseSensitiveTags ? "g" : "gi"))].map(
137
+ ([, text = ""]) => text,
138
+ );
139
+ }
140
+
141
+ /**
142
+ * The number of `<h1>` elements where the profile counts them.
143
+ * @param {string} html
144
+ * @param {Pick<Profile, "h1" | "caseSensitiveTags">} profile
145
+ */
146
+ export function countH1(html, { h1: where, caseSensitiveTags }) {
147
+ if (where === "markup") {
148
+ return scoped(html, "markup").match(/<h1\b/gi)?.length ?? 0;
149
+ }
150
+ const text =
151
+ where === "rendered"
152
+ ? html.replace(/<(script|style|template)\b[\s\S]*?<\/\1>|<!--[\s\S]*?-->/gi, "")
153
+ : html;
154
+ return text.match(new RegExp("<h1[\\s>]", caseSensitiveTags ? "g" : "gi"))?.length ?? 0;
155
+ }
156
+
157
+ /**
158
+ * The body of each JSON-LD `<script>`. `exact` takes a `type` of exactly `application/ld+json`,
159
+ * and `prefix-any-case` one that starts with it, in any case.
160
+ * @param {string} html
161
+ * @param {Profile} profile
162
+ * @param {(text: string) => string} decode
163
+ */
164
+ export function jsonLdBodies(html, profile, decode) {
165
+ if (profile.jsonLdType === "prefix-any-case") {
166
+ return [
167
+ ...html.matchAll(
168
+ /<script\b[^>]*type=["']?application\/ld\+json["']?[^>]*>([\s\S]*?)<\/script>/gi,
169
+ ),
170
+ ].map(([, body = ""]) => body);
171
+ }
172
+ return [...html.matchAll(tagPattern("script", profile, "([\\s\\S]*?)</script>"))]
173
+ .filter(
174
+ ([, source = ""]) =>
175
+ attributes(source, profile.quotes, decode).type === "application/ld+json",
176
+ )
177
+ .map(([, , body = ""]) => body);
178
+ }
179
+
180
+ /**
181
+ * The nodes of the JSON-LD blocks of a page, as the profile reads them.
182
+ * @param {unknown[]} blocks
183
+ * @param {Profile["nodes"]} mode
184
+ * @returns {Record<string, unknown>[]}
185
+ */
186
+ export function jsonLdNodes(blocks, mode) {
187
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
188
+ const isObject = (value) => Boolean(value) && typeof value === "object";
189
+ /** @param {unknown} value @returns {Record<string, unknown>[]} */
190
+ const all = (value) => {
191
+ if (Array.isArray(value)) return value.flatMap(all);
192
+ if (!isObject(value)) return [];
193
+ const graph = value["@graph"];
194
+ return [value, ...(Array.isArray(graph) ? graph.flatMap(all) : [])];
195
+ };
196
+ /** @param {unknown} value @returns {Record<string, unknown>[]} */
197
+ const deep = (value) => {
198
+ if (Array.isArray(value)) return value.flatMap(deep);
199
+ if (!isObject(value)) return [];
200
+ return value["@graph"] ? deep(value["@graph"]) : [value];
201
+ };
202
+ return blocks.flatMap((block) => {
203
+ if (mode === "all") return all(block);
204
+ if (mode === "graph-deep") return deep(block);
205
+ if (!isObject(block)) return [];
206
+ const graph = block["@graph"];
207
+ const members = Array.isArray(graph) ? graph.filter(isObject) : [];
208
+ if (mode === "block-and-graph") return [block, ...members];
209
+ return Array.isArray(graph) ? members : [block];
210
+ });
211
+ }
212
+
213
+ /**
214
+ * Whether a JSON-LD node has this `@type`. With `typeArrays`, an array matches any member.
215
+ * @param {Record<string, unknown>} node
216
+ * @param {string} type
217
+ * @param {boolean} typeArrays
218
+ */
219
+ export const isType = (node, type, typeArrays) =>
220
+ typeArrays ? [node["@type"]].flat().includes(type) : node["@type"] === type;
221
+
222
+ /**
223
+ * The width, height and type of a PNG or JPEG, from its header. With `name`, a PNG is any file
224
+ * whose bytes 1 to 3 spell `PNG`, and with `signature` one that starts with the whole signature.
225
+ * @param {Uint8Array} bytes
226
+ * @param {"signature" | "name"} [png]
227
+ * @returns {{ type: "png" | "jpeg", width: number, height: number } | undefined}
228
+ */
229
+ export function imageSize(bytes, png = "signature") {
230
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
231
+ const SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
232
+ const isPng =
233
+ png === "name"
234
+ ? bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47
235
+ : SIGNATURE.every((byte, index) => bytes[index] === byte);
236
+ if (isPng) {
237
+ return bytes.length >= 24
238
+ ? { type: "png", width: view.getUint32(16), height: view.getUint32(20) }
239
+ : undefined;
240
+ }
241
+ if (bytes[0] === 0xff && bytes[1] === 0xd8) {
242
+ for (let offset = 2; offset + 9 < bytes.length;) {
243
+ if (bytes[offset] !== 0xff) break;
244
+ const marker = bytes[offset + 1] ?? 0;
245
+ // Start-of-frame markers hold the size. C4, C8 and CC are other segments.
246
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
247
+ return {
248
+ type: "jpeg",
249
+ height: view.getUint16(offset + 5),
250
+ width: view.getUint16(offset + 7),
251
+ };
252
+ }
253
+ offset += 2 + view.getUint16(offset + 2);
254
+ }
255
+ }
256
+ return undefined;
257
+ }
258
+
259
+ export { escapeRegExp };