@uxfront/site-checks 0.0.0-stage → 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/index.d.ts ADDED
@@ -0,0 +1,361 @@
1
+ /**
2
+ * Where a page's tags are read: `head` (everything before `</head>`, or the whole page without
3
+ * one), `head-element` (the `<head>` element, or nothing without one), `document`, or `markup`
4
+ * (the document without its `<script>` elements and comments).
5
+ */
6
+ export type Scope = "head" | "head-element" | "document" | "markup";
7
+
8
+ /** An entity the parser decodes: `numeric` for every `&#…;` and `&#x…;`, or a name like `amp` or `#x27`. */
9
+ export type Entity = "numeric" | "amp" | "lt" | "gt" | "quot" | "apos" | `#${string}`;
10
+
11
+ /**
12
+ * How a page and the site's files are read. Every rule reads through it, so a site's profile
13
+ * reads its HTML exactly as its own checker did. The README gives each setting's values.
14
+ */
15
+ export interface ParseProfile {
16
+ /** Where `<meta>` and `<link>` tags are read. Defaults to `document`. */
17
+ scope?: Scope;
18
+ /** Where `<title>` is read. Defaults to `head`. */
19
+ titleScope?: Scope;
20
+ /**
21
+ * The `<title>` elements read: `any` (attributes and any text), `plain-text` (attributes, and
22
+ * text without a `<`) or `bare` (no attributes, and text without a `<`). Defaults to `any`.
23
+ */
24
+ titleTag?: "any" | "plain-text" | "bare";
25
+ /** When a title is trimmed: `after-decode`, `before-decode` or `none`. Defaults to `after-decode`. */
26
+ trimTitle?: "after-decode" | "before-decode" | "none";
27
+ /** The attribute values read: `any` (double, single or no quotes) or `double` only. */
28
+ quotes?: "any" | "double";
29
+ /** Whether tag names match in lower case only, so `<META>` isn't a `<meta>`. Defaults to `false`. */
30
+ caseSensitiveTags?: boolean;
31
+ /**
32
+ * What ends a tag's name: `word` (a word boundary, so `<meta-card>` reads as a `<meta>`) or
33
+ * `space` (a space, `/` or `>`). Defaults to `word`.
34
+ */
35
+ tagEnd?: "word" | "space";
36
+ /**
37
+ * How a `<meta>` is found by key: `name-or-property` (either attribute), or `property-first`
38
+ * (its `property`, or else its `name`, leaving out a tag with no `content`).
39
+ */
40
+ metaKey?: "name-or-property" | "property-first";
41
+ /** Whether `<meta>` `content` and `<html lang>` values are trimmed. Defaults to `false`. */
42
+ trimValues?: boolean;
43
+ /** The entities decoded in attribute values, titles and sitemap URLs. */
44
+ decode?: readonly Entity[];
45
+ /**
46
+ * `one-pass` decodes each reference once, so `&amp;lt;` stays `&lt;`. `numeric-first` decodes
47
+ * numeric references before named ones, so `&#38;lt;` becomes `<`.
48
+ */
49
+ decodeOrder?: "one-pass" | "numeric-first";
50
+ /** Whether named entities decode in any case, like `&AMP;`. Defaults to `false`. */
51
+ decodeIgnoreCase?: boolean;
52
+ /** The units of a length: `code-points`, or `utf-16` code units like `String.length`. */
53
+ count?: "code-points" | "utf-16";
54
+ /**
55
+ * Where `<h1>` is counted: `anywhere`, `markup` (outside `<script>` and comments), or `rendered`
56
+ * (outside `<script>`, `<style>`, `<template>` and comments).
57
+ */
58
+ h1?: "anywhere" | "markup" | "rendered";
59
+ /**
60
+ * The JSON-LD nodes of a block: `graph-or-block` (the `@graph` members, or else the block),
61
+ * `block-and-graph` (the block and its `@graph` members), `all` (the block and its `@graph`
62
+ * members, recursively, arrays flattened) or `graph-deep` (the `@graph` members, recursively,
63
+ * or else the block, arrays flattened).
64
+ */
65
+ nodes?: "graph-or-block" | "block-and-graph" | "all" | "graph-deep";
66
+ /** Whether an array `@type` matches any of its members. */
67
+ typeArrays?: boolean;
68
+ /**
69
+ * The `<script>` elements read as JSON-LD: `exact` (`type="application/ld+json"`) or
70
+ * `prefix-any-case` (a `type` that starts with it, in any case). Defaults to `exact`.
71
+ */
72
+ jsonLdType?: "exact" | "prefix-any-case";
73
+ /**
74
+ * The lines of `llms.txt` that count as blank: `whitespace` (only spaces), or `empty` (nothing,
75
+ * so a CRLF file's `\r` counts as text). Defaults to `whitespace`.
76
+ */
77
+ blankLines?: "whitespace" | "empty";
78
+ /** Whether `<loc>` and `<lastmod>` values are trimmed. Defaults to `true`. */
79
+ trimSitemap?: boolean;
80
+ /** Whether a `<loc>` listed twice is checked once. Defaults to `false`. */
81
+ mergeDuplicateLocs?: boolean;
82
+ /**
83
+ * How `_headers` is read: `lines` (line by line, skipping `#` lines and the spaces at each
84
+ * line's ends) or `blocks` (each unindented line and the indented lines after it as one rule,
85
+ * where a `#` line is a rule of its own and a line that ends in `\r` isn't a header).
86
+ * Defaults to `lines`.
87
+ */
88
+ headersParser?: "lines" | "blocks";
89
+ }
90
+
91
+ /**
92
+ * What takes a page out of the index, for `sitemap-indexable` and `sitemap-coverage`.
93
+ *
94
+ * - `meta`: a `<meta>` named one of `names` whose `content` holds one of `values`. With
95
+ * `property`, a tag is found as the profile finds any `<meta>`, by `name` or `property`. With
96
+ * `anyCaseNames`, its `name` matches in any case. `scope` overrides the profile's.
97
+ * - `refresh`: a `<meta http-equiv="refresh">`.
98
+ * - `files`: the page's file is one of these paths in `dist`, like `404.html`.
99
+ * - `under`: the page's file is under one of these folders in `dist`, like `raw/`.
100
+ * - `redirects`: a `_redirects` rule starts at the page's path.
101
+ * - `headers`: a `_headers` rule sends an `X-Robots-Tag` that holds one of `values`. `hosts` says
102
+ * how rules with a host match: `ignore` them, `match` the host as Cloudflare does, or `drop` the
103
+ * host and match the path alone, reading only the last `X-Robots-Tag` of a rule.
104
+ */
105
+ export type IndexSource =
106
+ | {
107
+ type: "meta";
108
+ names: readonly string[];
109
+ /** Defaults to `["noindex"]`. */
110
+ values?: readonly string[];
111
+ /** Match whole words only. */
112
+ word?: boolean;
113
+ caseSensitive?: boolean;
114
+ property?: boolean;
115
+ anyCaseNames?: boolean;
116
+ scope?: Scope;
117
+ }
118
+ | { type: "refresh" }
119
+ | { type: "files"; files: readonly string[] }
120
+ | { type: "under"; paths: readonly string[] }
121
+ | { type: "redirects" }
122
+ | {
123
+ type: "headers";
124
+ hosts: "ignore" | "match" | "drop";
125
+ /** Defaults to `["noindex"]`. */
126
+ values?: readonly string[];
127
+ word?: boolean;
128
+ };
129
+
130
+ /**
131
+ * A set of site paths: `*` for every page, a path ending in `*` for every page under it, like
132
+ * `/docs/*`, or an exact path, like `/`.
133
+ */
134
+ export type PathPattern = string;
135
+
136
+ /** A rule that takes no options, only `true` or `false`. */
137
+ export type NoOptions = Record<string, never>;
138
+
139
+ /** The options of each rule. `true` turns a rule on with its defaults, `false` turns it off. */
140
+ export interface RuleOptions {
141
+ sitemap: NoOptions;
142
+ "sitemap-host": NoOptions;
143
+ "sitemap-duplicates": NoOptions;
144
+ lastmod: {
145
+ /** `loose`, `date` (`YYYY-MM-DD`) or `w3c`. Defaults to `w3c`. */
146
+ format?: "loose" | "date" | "w3c";
147
+ /** How a value is checked as a date. Defaults to `none`. */
148
+ realDate?: "none" | "date-only" | "parseable";
149
+ };
150
+ "lastmod-future": { skewHours?: number };
151
+ "sitemap-pages": {
152
+ /** How a `<loc>` maps to a file. Defaults to `exact`. */
153
+ paths?: "lookup" | "exact" | "exact-slash";
154
+ /** Fail a page whose file is the same text as `404.html`. */
155
+ notFoundCopy?: boolean;
156
+ };
157
+ "sitemap-indexable": { sources?: readonly IndexSource[] };
158
+ "sitemap-coverage": {
159
+ /** The files left out of the sitemap on purpose. Defaults to `sitemap-indexable`'s `sources`. */
160
+ exclude?: readonly IndexSource[];
161
+ };
162
+ title: { max?: number; exactlyOne?: boolean; nonEmpty?: boolean };
163
+ "title-unique": NoOptions;
164
+ description: { min?: number; max?: number; exactlyOne?: boolean };
165
+ "description-unique": NoOptions;
166
+ h1: NoOptions;
167
+ canonical: {
168
+ exactlyOne?: boolean;
169
+ /** `exact`, `exact-any-case` or `token`. */
170
+ rel?: "token" | "exact" | "exact-any-case";
171
+ /** Whether a canonical link with no `href` counts. */
172
+ requireHref?: boolean;
173
+ };
174
+ lang: {
175
+ /** The value `lang` must have. Set it to `false` to accept any value. Defaults to `"en"`. */
176
+ lang?: string | false;
177
+ };
178
+ "open-graph": { url?: "loc" | "canonical" };
179
+ "og-image-alt": NoOptions;
180
+ "meta-conflicts": { keys?: readonly string[] };
181
+ "og-image-host": NoOptions;
182
+ "og-image-size-tags": { onHostOnly?: boolean };
183
+ "og-image-file": {
184
+ types?: readonly ("png" | "jpeg")[];
185
+ /** How a PNG is told apart: `name` (bytes 1 to 3 spell `PNG`) or `signature` (all 8). */
186
+ png?: "name" | "signature";
187
+ };
188
+ twitter: { card?: "summary_large_image" | "any" };
189
+ "twitter-text": NoOptions;
190
+ "json-ld-parse": NoOptions;
191
+ "json-ld-present": NoOptions;
192
+ "json-ld-context": NoOptions;
193
+ "json-ld-ids": NoOptions;
194
+ "json-ld-types": { types?: Readonly<Record<PathPattern, readonly string[]>> };
195
+ "json-ld-breadcrumbs": {
196
+ scope?: readonly PathPattern[];
197
+ nodes?: "first" | "all";
198
+ item?: readonly ("url" | "id")[];
199
+ /** Whether a `BreadcrumbList` must have exactly that `@type`, whatever `typeArrays` says. */
200
+ exactType?: boolean;
201
+ /** What an `itemListElement` that isn't a list does: `skip`, or `iterate` it, failing when it can't. */
202
+ nonArray?: "skip" | "iterate";
203
+ };
204
+ "json-ld-article": { scope?: readonly PathPattern[] };
205
+ "json-ld-posting": { scope?: readonly PathPattern[] };
206
+ "json-ld-organization": {
207
+ /** The name no `Organization` may have, like `"Unframework"`. It has no default. */
208
+ name: string;
209
+ scope?: readonly PathPattern[];
210
+ };
211
+ "robots-sitemap": { match?: "loose" | "trimmed" | "anchored" | "exact" | "field" };
212
+ "robots-crawlers": {
213
+ crawlers?: readonly string[];
214
+ allow?: false | "first" | "all";
215
+ case?: "exact" | "insensitive";
216
+ /** Where agent names are read: `groups`, or every `User-agent` line as it is, `lines`. */
217
+ agents?: "groups" | "lines";
218
+ /** Which lines end a group's run of agents: `all`, `directives` or `allow-disallow`. */
219
+ groupRules?: "all" | "directives" | "allow-disallow";
220
+ };
221
+ "robots-no-disallow": { match?: "lines" | "groups" };
222
+ "robots-wildcard": NoOptions;
223
+ "robots-directives": NoOptions;
224
+ llms: { first?: "line" | "non-empty"; title?: string; nonEmpty?: boolean };
225
+ "llms-summary": { position?: "second" | "any"; nonEmpty?: boolean };
226
+ "llms-links": {
227
+ scope?: readonly PathPattern[];
228
+ links?: readonly string[];
229
+ form?: "markdown" | "parens";
230
+ minPages?: number;
231
+ };
232
+ "llms-docs-section": NoOptions;
233
+ "llms-full": NoOptions;
234
+ "markdown-clean": { files?: readonly string[]; tables?: "line-start" | "anywhere" };
235
+ "markdown-copy": { scope?: readonly PathPattern[] };
236
+ "markdown-heading": { scope?: readonly PathPattern[]; ogTitle?: readonly PathPattern[] };
237
+ "markdown-alternate": { scope?: readonly PathPattern[] };
238
+ "redirects-permanent": {
239
+ /** Whether a rule with no destination is left out. */
240
+ needsDestination?: boolean;
241
+ };
242
+ "headers-noindex": { patterns?: readonly string[]; urls?: readonly string[] };
243
+ "headers-duplicates": NoOptions;
244
+ "headers-markdown": { scope?: readonly PathPattern[] };
245
+ "not-found": NoOptions;
246
+ }
247
+
248
+ export type RuleId = keyof RuleOptions;
249
+
250
+ export type RuleSetting<Id extends RuleId> = RuleOptions[Id] extends NoOptions
251
+ ? boolean
252
+ : boolean | RuleOptions[Id];
253
+
254
+ export type Rules = {
255
+ [Id in Exclude<RuleId, "json-ld-organization">]?: RuleSetting<Id>;
256
+ } & {
257
+ /** It needs a `name`, so it takes `false` or its options, not `true`. */
258
+ "json-ld-organization"?: false | RuleOptions["json-ld-organization"];
259
+ };
260
+
261
+ /** A page the checks read: a `<loc>` of the sitemap, or a path in `pages`, and its file. */
262
+ export interface CheckedPage {
263
+ /** The page's URL, like `https://uxfront.com/docs/`. */
264
+ readonly loc: string;
265
+ /** The URL's path, like `/docs/`. */
266
+ readonly path: string;
267
+ /** The file's path in `dist`, like `docs/index.html`. */
268
+ readonly file: string;
269
+ readonly html: string;
270
+ /** The `content` of every `<meta>` whose `name` or `property` is `key`, in order. */
271
+ meta(key: string): string[];
272
+ /** The `<title>` elements' text, decoded and trimmed. */
273
+ readonly titles: readonly string[];
274
+ /** The JSON-LD nodes of the page, read as the profile's `nodes` says. */
275
+ readonly nodes: readonly Record<string, unknown>[];
276
+ }
277
+
278
+ /** A `<url>` of `sitemap.xml`. */
279
+ export interface SitemapEntry {
280
+ /** The decoded `<loc>`, or an empty string. */
281
+ readonly loc: string;
282
+ readonly lastmod: string | undefined;
283
+ }
284
+
285
+ /** What an extra rule gets: the parsed site and a way to report problems. */
286
+ export interface RuleContext {
287
+ readonly site: string;
288
+ readonly dist: string;
289
+ readonly pages: readonly CheckedPage[];
290
+ readonly sitemap: readonly SitemapEntry[];
291
+ /** A file in `dist` as text, or `undefined` when it doesn't exist. */
292
+ read: (file: string) => string | undefined;
293
+ /** The headers `_headers` gives a URL, as Cloudflare matches it, with lower-case names. */
294
+ headersFor: (url: string) => [name: string, value: string][];
295
+ /** Reports a problem with a page's path or a file's name. */
296
+ report: (target: string, message: string) => void;
297
+ }
298
+
299
+ /** A rule a site adds for itself, run and reported like the others. */
300
+ export interface ExtraRule {
301
+ id: string;
302
+ check: (context: RuleContext) => void;
303
+ }
304
+
305
+ export interface CheckOptions {
306
+ /** The production origin, like `https://uxfront.com`. */
307
+ site: string;
308
+ /** The build folder. */
309
+ dist: string;
310
+ /** Site paths to check, like `/` and `/docs/`. Defaults to every `<loc>` in `sitemap.xml`. */
311
+ pages?: readonly string[];
312
+ parse?: ParseProfile;
313
+ rules?: Rules;
314
+ extraRules?: readonly ExtraRule[];
315
+ /** The time `lastmod-future` compares with. Defaults to now. */
316
+ now?: Date;
317
+ }
318
+
319
+ /** The options a config file exports: everything but `dist`, which the CLI takes. */
320
+ export type SiteChecksConfig = Omit<CheckOptions, "dist">;
321
+
322
+ export interface Problem {
323
+ /** A page's path, or a file's name. */
324
+ target: string;
325
+ message: string;
326
+ }
327
+
328
+ export interface RuleResult {
329
+ id: string;
330
+ problems: Problem[];
331
+ }
332
+
333
+ export interface Report {
334
+ /** Every rule that ran, in order, with its problems. */
335
+ rules: RuleResult[];
336
+ /** The number of pages checked. */
337
+ pages: number;
338
+ /** The number of problems in all rules. */
339
+ problems: number;
340
+ }
341
+
342
+ /** The nine AI search and assistant crawlers `robots-crawlers` checks by default, like `GPTBot`. */
343
+ export declare const AI_CRAWLERS: readonly string[];
344
+
345
+ /** The 51 rule IDs, in order. */
346
+ export declare const RULE_IDS: readonly RuleId[];
347
+
348
+ /** The 20 rules that run when a config doesn't name them. */
349
+ export declare const CORE_RULES: readonly RuleId[];
350
+
351
+ /** The parsing profile a config gets when it doesn't set `parse`. */
352
+ export declare const DEFAULT_PARSE: Readonly<Required<ParseProfile>>;
353
+
354
+ /** Reads a built site and checks it. Throws on options it can't use, like an unknown rule ID. */
355
+ export declare function checkSeo(options: CheckOptions): Report;
356
+
357
+ /** One line per rule, `✓ <id>` or `✗ <id>` with its problems under it, then a summary. */
358
+ export declare function formatReport(report: Report): string;
359
+
360
+ /** Returns its argument, typed, for a config file. */
361
+ export declare function defineConfig(config: SiteChecksConfig): SiteChecksConfig;
package/index.js ADDED
@@ -0,0 +1,10 @@
1
+ export { AI_CRAWLERS } from "./lib/rules.js";
2
+ export { CORE_RULES, DEFAULT_PARSE, RULE_IDS, checkSeo, formatReport } from "./lib/check.js";
3
+
4
+ /** @import { SiteChecksConfig } from "./index.js" */
5
+
6
+ /**
7
+ * Returns its argument, typed, for a config file.
8
+ * @param {SiteChecksConfig} config
9
+ */
10
+ export const defineConfig = (config) => config;
package/lib/check.js ADDED
@@ -0,0 +1,234 @@
1
+ import { RULES, SCHEMAS } from "./rules.js";
2
+ import { Site } from "./site.js";
3
+ import { PARSE, isPlainObject, list, pattern } from "./validate.js";
4
+
5
+ /** @import { CheckOptions, ParseProfile, Problem, Report, RuleId, RuleOptions } from "../index.js" */
6
+ /** @import { Page } from "./site.js" */
7
+
8
+ /** @type {Readonly<Required<ParseProfile>>} */
9
+ export const DEFAULT_PARSE = Object.freeze({
10
+ scope: "document",
11
+ titleScope: "head",
12
+ titleTag: "any",
13
+ trimTitle: "after-decode",
14
+ quotes: "any",
15
+ caseSensitiveTags: false,
16
+ tagEnd: "word",
17
+ metaKey: "name-or-property",
18
+ trimValues: false,
19
+ decode: Object.freeze(/** @type {const} */ (["numeric", "quot", "apos", "lt", "gt", "amp"])),
20
+ decodeOrder: "one-pass",
21
+ decodeIgnoreCase: false,
22
+ count: "utf-16",
23
+ h1: "anywhere",
24
+ nodes: "graph-or-block",
25
+ typeArrays: true,
26
+ jsonLdType: "exact",
27
+ blankLines: "whitespace",
28
+ trimSitemap: true,
29
+ mergeDuplicateLocs: false,
30
+ headersParser: "lines",
31
+ });
32
+
33
+ /** @type {readonly RuleId[]} */
34
+ export const RULE_IDS = Object.freeze(RULES.map((rule) => rule.id));
35
+
36
+ /** @type {readonly RuleId[]} */
37
+ export const CORE_RULES = Object.freeze(RULES.filter((rule) => rule.core).map((rule) => rule.id));
38
+
39
+ /**
40
+ * The options of every rule, with the defaults filled in, and whether it runs. Throws on an
41
+ * unknown rule, an unknown option or a value an option doesn't take.
42
+ * @param {CheckOptions["rules"]} rules
43
+ */
44
+ function resolveRules(rules = {}) {
45
+ if (!isPlainObject(rules)) throw new TypeError("rules must be an object of rule IDs");
46
+ for (const id of Object.keys(rules)) {
47
+ if (!RULE_IDS.includes(/** @type {RuleId} */ (id))) {
48
+ throw new Error(`Unknown rule "${id}". The rules are: ${RULE_IDS.join(", ")}`);
49
+ }
50
+ }
51
+ /** @type {Map<RuleId, { enabled: boolean, options: Record<string, unknown> }>} */
52
+ const resolved = new Map();
53
+ for (const rule of RULES) {
54
+ const setting = /** @type {Record<string, unknown>} */ (rules)[rule.id];
55
+ if (setting !== undefined && typeof setting !== "boolean" && !isPlainObject(setting)) {
56
+ throw new TypeError(
57
+ `rules["${rule.id}"] must be true, false or an object of options, not ${JSON.stringify(setting)}`,
58
+ );
59
+ }
60
+ const given = isPlainObject(setting) ? setting : {};
61
+ const schema = SCHEMAS[rule.id] ?? {};
62
+ for (const [key, value] of Object.entries(given)) {
63
+ const check = schema[key];
64
+ if (!check) {
65
+ const known = Object.keys(schema);
66
+ throw new Error(
67
+ `Rule "${rule.id}" has no option "${key}"${known.length ? `. Its options are: ${known.join(", ")}` : ". It takes no options"}`,
68
+ );
69
+ }
70
+ check(value, `rules["${rule.id}"].${key}`);
71
+ }
72
+ const enabled = setting === undefined ? rule.core : setting !== false;
73
+ if (rule.id === "json-ld-organization" && enabled && !given.name) {
74
+ throw new TypeError(
75
+ 'rules["json-ld-organization"] needs a name, like { name: "Unframework" }',
76
+ );
77
+ }
78
+ resolved.set(rule.id, { enabled, options: { ...rule.defaults, ...given } });
79
+ }
80
+ // Pages left out of the sitemap on purpose are, by default, the ones out of the index.
81
+ const coverage = resolved.get("sitemap-coverage");
82
+ const given = /** @type {Record<string, unknown>} */ (rules)["sitemap-coverage"];
83
+ if (coverage && !(isPlainObject(given) && "exclude" in given)) {
84
+ coverage.options.exclude = resolved.get("sitemap-indexable")?.options.sources;
85
+ }
86
+ return resolved;
87
+ }
88
+
89
+ /** @param {unknown} error */
90
+ const messageOf = (error) => (error instanceof Error ? error.message : String(error));
91
+
92
+ /** @param {CheckOptions} options @returns {Report} */
93
+ export function checkSeo(options) {
94
+ if (!isPlainObject(options)) throw new TypeError("checkSeo takes an object of options");
95
+ const { site: origin, dist, pages: only, parse = {}, rules, extraRules = [], now } = options;
96
+ if (typeof origin !== "string" || !/^https?:\/\/[^/]+\/?$/.test(origin)) {
97
+ throw new TypeError(
98
+ `site must be an origin, like "https://uxfront.com", not ${JSON.stringify(origin)}`,
99
+ );
100
+ }
101
+ if (typeof dist !== "string" || !dist) throw new TypeError("dist must be the build folder");
102
+ if (!isPlainObject(parse)) throw new TypeError("parse must be an object of settings");
103
+ for (const [key, value] of Object.entries(parse)) {
104
+ const check = PARSE[key];
105
+ if (!check) {
106
+ throw new Error(
107
+ `parse has no option "${key}". Its options are: ${Object.keys(PARSE).join(", ")}`,
108
+ );
109
+ }
110
+ check(value, `parse.${key}`);
111
+ }
112
+ if (only !== undefined) list(pattern, { nonEmpty: true })(only, "pages");
113
+ if (now !== undefined && !(now instanceof Date && !Number.isNaN(now.getTime()))) {
114
+ throw new TypeError("now must be a Date");
115
+ }
116
+ const profile = /** @type {Required<ParseProfile>} */ ({ ...DEFAULT_PARSE, ...parse });
117
+ const resolved = resolveRules(rules);
118
+ if (!Array.isArray(extraRules)) throw new TypeError("extraRules must be a list");
119
+ const extraIds = new Set();
120
+ for (const extra of extraRules) {
121
+ if (!extra || typeof extra.id !== "string" || !extra.id || typeof extra.check !== "function") {
122
+ throw new TypeError("Each extra rule needs an id and a check function");
123
+ }
124
+ if (RULE_IDS.includes(/** @type {RuleId} */ (extra.id)) || extraIds.has(extra.id)) {
125
+ throw new Error(`Two rules have the ID "${extra.id}"`);
126
+ }
127
+ extraIds.add(extra.id);
128
+ }
129
+
130
+ /** @template {RuleId} Id @param {Id} id */
131
+ const optionsOf = (id) =>
132
+ /** @type {Required<RuleOptions[Id]>} */ (/** @type {unknown} */ (resolved.get(id)?.options));
133
+ const pageOptions = optionsOf("sitemap-pages");
134
+ const site = new Site({
135
+ site: origin,
136
+ dist,
137
+ profile,
138
+ paths: pageOptions.paths,
139
+ now: now ?? new Date(),
140
+ });
141
+
142
+ // The pages the page rules read: each `<loc>` served from an HTML file, or each path in `pages`.
143
+ const notFound = site.read("404.html");
144
+ /** @type {{ loc: string, path: string }[]} */
145
+ let targets = only
146
+ ? only.map((path) => ({ loc: `${site.site}${path}`, path }))
147
+ : site.sitemap.entries.flatMap(({ loc, url }) => (url ? [{ loc, path: url.pathname }] : []));
148
+ if (profile.mergeDuplicateLocs) {
149
+ targets = [...new Map(targets.map((target) => [target.loc, target])).values()];
150
+ }
151
+ /** @type {Page[]} */
152
+ const pages = [];
153
+ /** @type {string[]} */
154
+ const missing = [];
155
+ for (const { loc, path } of targets) {
156
+ const file = site.resolve(path);
157
+ if (!file) {
158
+ if (only) missing.push(path);
159
+ continue;
160
+ }
161
+ if (pageOptions.notFoundCopy && notFound !== undefined && site.read(file) === notFound)
162
+ continue;
163
+ pages.push(site.page(loc, path, file));
164
+ }
165
+ // A path in `pages` with no file is a problem of sitemap-pages, so it never passes quietly.
166
+ if (missing.length && !resolved.get("sitemap-pages")?.enabled) {
167
+ throw new Error(
168
+ `pages has paths with no HTML file in dist, ${missing.join(", ")}, and sitemap-pages, which reports them, is off`,
169
+ );
170
+ }
171
+
172
+ /** @type {Report["rules"]} */
173
+ const results = [];
174
+ /** @param {string} id @param {(report: (target: string, message: string) => void) => void} run */
175
+ const record = (id, run) => {
176
+ /** @type {Problem[]} */
177
+ const problems = [];
178
+ const report = (/** @type {string} */ target, /** @type {string} */ message) =>
179
+ problems.push({ target: String(target), message: String(message) });
180
+ try {
181
+ run(report);
182
+ } catch (error) {
183
+ // A file the rule can't read, like a value no decoder can read, is a problem with the
184
+ // build, so the rule reports it and the other rules still run.
185
+ report("(the rule)", `couldn't finish: ${messageOf(error)}`);
186
+ }
187
+ results.push({ id, problems });
188
+ };
189
+ for (const rule of RULES) {
190
+ const setting = resolved.get(rule.id);
191
+ if (!setting?.enabled) continue;
192
+ record(rule.id, (report) => {
193
+ /** @type {(context: object, options: object) => void} */ (rule.run)(
194
+ { site, pages, optionsOf, report },
195
+ setting.options,
196
+ );
197
+ if (rule.id === "sitemap-pages") {
198
+ for (const path of missing) report(path, "a path in pages has no HTML file in dist");
199
+ }
200
+ });
201
+ }
202
+ for (const extra of extraRules) {
203
+ record(extra.id, (report) =>
204
+ extra.check({
205
+ site: site.site,
206
+ dist,
207
+ pages,
208
+ sitemap: site.sitemap.entries.map(({ loc, lastmod }) => ({ loc, lastmod })),
209
+ read: (/** @type {string} */ file) => site.read(file),
210
+ headersFor: (/** @type {string} */ url) => site.headersFor(url),
211
+ report,
212
+ }),
213
+ );
214
+ }
215
+ return {
216
+ rules: results,
217
+ pages: pages.length,
218
+ problems: results.reduce((sum, result) => sum + result.problems.length, 0),
219
+ };
220
+ }
221
+
222
+ /** @param {Report} report */
223
+ export function formatReport({ rules, pages, problems }) {
224
+ const lines = [];
225
+ for (const { id, problems: own } of rules) {
226
+ lines.push(`${own.length ? "✗" : "✓"} ${id}`);
227
+ for (const { target, message } of own) lines.push(` ${target}: ${message}`);
228
+ }
229
+ lines.push(
230
+ "",
231
+ `${pages} ${pages === 1 ? "page" : "pages"} checked, ${problems} ${problems === 1 ? "problem" : "problems"}`,
232
+ );
233
+ return lines.join("\n");
234
+ }
package/lib/cli.js ADDED
@@ -0,0 +1,77 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+
5
+ import { checkSeo, formatReport } from "./check.js";
6
+
7
+ const USAGE = `Usage: site-checks seo [dist] [--config <file>]
8
+
9
+ Checks a built site for search and AI search: its tags, structured data, sitemap,
10
+ robots.txt and llms.txt. dist defaults to ./dist, and the config to
11
+ ./site-checks.config.mjs, whose default export holds the options.
12
+
13
+ Exits 0 when every rule passes, 1 on a problem, and 2 when it can't run.`;
14
+
15
+ /**
16
+ * Runs the CLI and returns its exit code.
17
+ * @param {string[]} args
18
+ * @param {{ out: (text: string) => void, err: (text: string) => void, cwd: string }} io
19
+ */
20
+ export async function main(args, { out, err, cwd }) {
21
+ const [command, ...rest] = args;
22
+ if (command === "--help" || command === "-h" || command === "help") {
23
+ out(`${USAGE}\n`);
24
+ return 0;
25
+ }
26
+ if (command !== "seo") {
27
+ err(`${USAGE}\n`);
28
+ return 2;
29
+ }
30
+ let dist;
31
+ let config = "site-checks.config.mjs";
32
+ for (let index = 0; index < rest.length; index++) {
33
+ const arg = rest[index] ?? "";
34
+ if (arg === "--config" || arg === "-c") {
35
+ const next = rest[++index];
36
+ if (!next) {
37
+ err("--config needs a file\n");
38
+ return 2;
39
+ }
40
+ config = next;
41
+ } else if (arg.startsWith("--config=")) config = arg.slice("--config=".length);
42
+ else if (arg.startsWith("-") || dist !== undefined) {
43
+ err(`Unexpected argument ${arg}\n\n${USAGE}\n`);
44
+ return 2;
45
+ } else dist = arg;
46
+ }
47
+ const folder = resolve(cwd, dist ?? "dist");
48
+ if (!existsSync(join(folder, "index.html"))) {
49
+ err(`No build in ${folder}: there's no index.html. Build the site first.\n`);
50
+ return 2;
51
+ }
52
+ const file = resolve(cwd, config);
53
+ if (!existsSync(file)) {
54
+ err(`No config at ${file}. Pass one with --config <file>.\n`);
55
+ return 2;
56
+ }
57
+ let options;
58
+ try {
59
+ options = (await import(pathToFileURL(file).href)).default;
60
+ } catch (error) {
61
+ err(`Couldn't load ${config}: ${error instanceof Error ? error.message : String(error)}\n`);
62
+ return 2;
63
+ }
64
+ if (!options || typeof options !== "object") {
65
+ err(`${config} has no default export of options\n`);
66
+ return 2;
67
+ }
68
+ let report;
69
+ try {
70
+ report = checkSeo({ ...options, dist: folder });
71
+ } catch (error) {
72
+ err(`${config}: ${error instanceof Error ? error.message : String(error)}\n`);
73
+ return 2;
74
+ }
75
+ out(`${formatReport(report)}\n`);
76
+ return report.problems ? 1 : 0;
77
+ }