@uxfront/site-checks 0.0.0 → 0.1.1

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.
@@ -0,0 +1,211 @@
1
+ // Checks a config's values, so a typo in one fails the run instead of turning a check off.
2
+
3
+ /** @typedef {(value: unknown, path: string) => void} Validator */
4
+
5
+ /** @param {unknown} value */
6
+ const show = (value) => {
7
+ try {
8
+ return JSON.stringify(value) ?? String(value);
9
+ } catch {
10
+ return String(value);
11
+ }
12
+ };
13
+
14
+ /** @param {string} path @param {string} expected @param {unknown} value */
15
+ const fail = (path, expected, value) => {
16
+ throw new TypeError(`${path} must be ${expected}, not ${show(value)}`);
17
+ };
18
+
19
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
20
+ export const isPlainObject = (value) =>
21
+ Boolean(value) && typeof value === "object" && !Array.isArray(value);
22
+
23
+ /**
24
+ * One of these values.
25
+ * @param {...(string | boolean)} values
26
+ * @returns {Validator}
27
+ */
28
+ export const oneOf =
29
+ (...values) =>
30
+ (value, path) => {
31
+ if (!values.some((allowed) => allowed === value)) {
32
+ fail(path, `one of ${values.map(show).join(", ")}`, value);
33
+ }
34
+ };
35
+
36
+ /** @type {Validator} */
37
+ export const bool = (value, path) => {
38
+ if (typeof value !== "boolean") {
39
+ fail(path, "true or false", value);
40
+ }
41
+ };
42
+
43
+ /** @type {Validator} */
44
+ export const count = (value, path) => {
45
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
46
+ fail(path, "a number of 0 or more", value);
47
+ }
48
+ };
49
+
50
+ /** @type {Validator} */
51
+ export const text = (value, path) => {
52
+ if (typeof value !== "string" || !value) {
53
+ fail(path, "a string that isn't empty", value);
54
+ }
55
+ };
56
+
57
+ /**
58
+ * A list whose every item passes the validator.
59
+ * @param {Validator} item
60
+ * @param {{ nonEmpty?: boolean }} [options]
61
+ * @returns {Validator}
62
+ */
63
+ export const list =
64
+ (item, { nonEmpty = false } = {}) =>
65
+ (value, path) => {
66
+ if (!Array.isArray(value)) {
67
+ return fail(path, "a list", value);
68
+ }
69
+ if (nonEmpty && !value.length) {
70
+ fail(path, "a list that isn't empty", value);
71
+ }
72
+ value.forEach((entry, index) => item(entry, `${path}[${index}]`));
73
+ };
74
+
75
+ /** A site path, like `/docs/`, or a pattern, like `/docs/*` or `*`. @type {Validator} */
76
+ export const pattern = (value, path) => {
77
+ if (typeof value !== "string" || !(value.startsWith("/") || value === "*")) {
78
+ fail(path, 'a path that starts with "/", or "*"', value);
79
+ }
80
+ };
81
+
82
+ /** @type {Validator} */
83
+ export const url = (value, path) => {
84
+ try {
85
+ if (typeof value !== "string") {
86
+ throw new TypeError();
87
+ }
88
+ new URL(value);
89
+ } catch {
90
+ fail(path, "a URL", value);
91
+ }
92
+ };
93
+
94
+ /**
95
+ * An object with these keys, the required ones first.
96
+ * @param {Record<string, Validator>} required
97
+ * @param {Record<string, Validator>} [optional]
98
+ * @returns {Validator}
99
+ */
100
+ export const shape =
101
+ (required, optional = {}) =>
102
+ (value, path) => {
103
+ if (!isPlainObject(value)) {
104
+ return fail(path, "an object", value);
105
+ }
106
+ for (const [key, check] of Object.entries(required)) {
107
+ if (!(key in value)) {
108
+ throw new TypeError(`${path} needs ${key}`);
109
+ }
110
+ check(value[key], `${path}.${key}`);
111
+ }
112
+ for (const [key, entry] of Object.entries(value)) {
113
+ if (key in required) {
114
+ continue;
115
+ }
116
+ const check = optional[key];
117
+ if (!check) {
118
+ const known = [...Object.keys(required), ...Object.keys(optional)];
119
+ throw new TypeError(`${path} has no option "${key}". Its options are: ${known.join(", ")}`);
120
+ }
121
+ check(entry, `${path}.${key}`);
122
+ }
123
+ };
124
+
125
+ const SCOPES = ["head", "head-element", "document", "markup"];
126
+
127
+ /** A source of `sitemap-indexable` or `sitemap-coverage`. @type {Validator} */
128
+ export const source = (value, path) => {
129
+ if (!isPlainObject(value)) {
130
+ return fail(path, "an object with a type", value);
131
+ }
132
+ const types = new Map(
133
+ Object.entries({
134
+ meta: shape(
135
+ { type: text, names: list(text, { nonEmpty: true }) },
136
+ {
137
+ values: list(text, { nonEmpty: true }),
138
+ word: bool,
139
+ caseSensitive: bool,
140
+ property: bool,
141
+ anyCaseNames: bool,
142
+ scope: oneOf(...SCOPES),
143
+ },
144
+ ),
145
+ refresh: shape({ type: text }),
146
+ files: shape({ type: text, files: list(text) }),
147
+ under: shape({ type: text, paths: list(text) }),
148
+ redirects: shape({ type: text }),
149
+ headers: shape(
150
+ { type: text, hosts: oneOf("ignore", "match", "drop") },
151
+ { values: list(text, { nonEmpty: true }), word: bool },
152
+ ),
153
+ }),
154
+ );
155
+ // A Map, so a type like "constructor" or "toString" finds no check on Object.prototype.
156
+ const check = types.get(String(value.type));
157
+ if (!check) {
158
+ return fail(`${path}.type`, `one of ${[...types.keys()].map(show).join(", ")}`, value.type);
159
+ }
160
+ check(value, path);
161
+ };
162
+
163
+ /** `json-ld-types`'s map of path patterns to `@type`s. @type {Validator} */
164
+ export const typesByPath = (value, path) => {
165
+ if (!isPlainObject(value)) {
166
+ return fail(path, 'an object of path patterns, like { "/docs/*": ["TechArticle"] }', value);
167
+ }
168
+ for (const [key, types] of Object.entries(value)) {
169
+ pattern(key, `${path} key`);
170
+ list(text)(types, `${path}["${key}"]`);
171
+ }
172
+ };
173
+
174
+ /** The parsing profile's settings. @type {Record<string, Validator>} */
175
+ export const PARSE = {
176
+ scope: oneOf(...SCOPES),
177
+ titleScope: oneOf(...SCOPES),
178
+ titleTag: oneOf("any", "plain-text", "bare"),
179
+ trimTitle: oneOf("after-decode", "before-decode", "none"),
180
+ quotes: oneOf("any", "double"),
181
+ caseSensitiveTags: bool,
182
+ tagEnd: oneOf("word", "space"),
183
+ metaKey: oneOf("name-or-property", "property-first"),
184
+ trimValues: bool,
185
+ decode: list((value, path) => {
186
+ if (
187
+ typeof value !== "string" ||
188
+ !(
189
+ ["numeric", "amp", "lt", "gt", "quot", "apos"].includes(value) ||
190
+ /^#(x[\da-f]+|\d+)$/i.test(value)
191
+ )
192
+ ) {
193
+ fail(
194
+ path,
195
+ 'an entity: "numeric", "amp", "lt", "gt", "quot", "apos" or a reference like "#x27"',
196
+ value,
197
+ );
198
+ }
199
+ }),
200
+ decodeOrder: oneOf("one-pass", "numeric-first"),
201
+ decodeIgnoreCase: bool,
202
+ count: oneOf("utf-16", "code-points"),
203
+ h1: oneOf("anywhere", "markup", "rendered"),
204
+ nodes: oneOf("graph-or-block", "block-and-graph", "all", "graph-deep"),
205
+ typeArrays: bool,
206
+ jsonLdType: oneOf("exact", "prefix-any-case"),
207
+ blankLines: oneOf("whitespace", "empty"),
208
+ trimSitemap: bool,
209
+ mergeDuplicateLocs: bool,
210
+ headersParser: oneOf("lines", "blocks"),
211
+ };
@@ -0,0 +1,45 @@
1
+ /** A Lighthouse category the preset asserts a score for. */
2
+ export type Category = "performance" | "accessibility" | "best-practices" | "seo";
3
+
4
+ /** How a category's score is asserted: `error` and a `minScore` of 0.95, or 1 for `seo`, unless set. */
5
+ export interface CategoryAssertion {
6
+ level?: "error" | "warn" | "off";
7
+ minScore?: number;
8
+ }
9
+
10
+ export interface LighthouseOptions {
11
+ /** Lighthouse CI's `collect` settings, like `staticDistDir` and `url`. `numberOfRuns` defaults to 3. */
12
+ // oxlint-disable-next-line quality/no-unsafe-dictionary-type -- Lighthouse CI owns these settings
13
+ collect: Record<string, unknown>;
14
+ /** Changes to a category's assertion, like `{ seo: { minScore: 0.95 } }`. */
15
+ categories?: Partial<Record<Category, CategoryAssertion>>;
16
+ /**
17
+ * Asserts each category only on the URLs that match a pattern, as Lighthouse CI's
18
+ * `assertMatrix`, like `{ matchingUrlPattern: "^http://localhost:8799/$", categories: ["performance"] }`.
19
+ */
20
+ matrix?: ReadonlyArray<{ matchingUrlPattern: string; categories: ReadonlyArray<Category> }>;
21
+ }
22
+
23
+ type Assertion = [level: "error" | "warn" | "off", options: { minScore: number }];
24
+
25
+ export interface LighthouseConfig {
26
+ ci: {
27
+ // oxlint-disable-next-line quality/no-unsafe-dictionary-type -- Lighthouse CI owns these settings
28
+ collect: Record<string, unknown>;
29
+ assert:
30
+ | { assertions: Partial<Record<`categories:${Category}`, Assertion>> }
31
+ | {
32
+ assertMatrix: Array<{
33
+ matchingUrlPattern: string;
34
+ assertions: Partial<Record<`categories:${Category}`, Assertion>>;
35
+ }>;
36
+ };
37
+ upload: { target: "filesystem"; outputDir: ".lighthouseci" };
38
+ };
39
+ }
40
+
41
+ /** The four categories, in the order the preset asserts them. */
42
+ export declare const CATEGORIES: ReadonlyArray<Category>;
43
+
44
+ /** A full Lighthouse CI config: the shared thresholds, with the site's `collect` merged in. */
45
+ export declare function lighthouseConfig(options: LighthouseOptions): LighthouseConfig;
package/lighthouse.js ADDED
@@ -0,0 +1,88 @@
1
+ import { isPlainObject, list, oneOf, shape } from "./lib/validate.js";
2
+
3
+ /** @import { Category, CategoryAssertion, LighthouseConfig, LighthouseOptions } from "./lighthouse.js" */
4
+ /** @import { Validator } from "./lib/validate.js" */
5
+
6
+ /** @type {readonly Category[]} */
7
+ export const CATEGORIES = Object.freeze(["performance", "accessibility", "best-practices", "seo"]);
8
+
9
+ /** @type {(value: unknown, path: string) => asserts value is object} */
10
+ const isObject = (value, path) => {
11
+ if (!isPlainObject(value)) {
12
+ throw new TypeError(`${path} must be an object of settings`);
13
+ }
14
+ };
15
+
16
+ /** @type {Validator} */
17
+ const minScore = (value, path) => {
18
+ if (typeof value !== "number" || !(value >= 0 && value <= 1)) {
19
+ throw new TypeError(`${path} must be a score from 0 to 1, not ${JSON.stringify(value)}`);
20
+ }
21
+ };
22
+
23
+ const category = oneOf(...CATEGORIES);
24
+
25
+ /** @type {Validator} */
26
+ const categoryChanges = (value, path) => {
27
+ isObject(value, path);
28
+ for (const [key, change] of Object.entries(value)) {
29
+ category(key, `${path} key`);
30
+ shape({}, { level: oneOf("error", "warn", "off"), minScore })(change, `${path}.${key}`);
31
+ }
32
+ };
33
+
34
+ const matrixEntries = list(
35
+ shape({
36
+ matchingUrlPattern: (value, path) => {
37
+ if (typeof value !== "string" || !value) {
38
+ throw new TypeError(`${path} must be a pattern`);
39
+ }
40
+ },
41
+ categories: list(category, { nonEmpty: true }),
42
+ }),
43
+ { nonEmpty: true },
44
+ );
45
+
46
+ // Every site errors below 0.95, and below 1 in SEO, unless it says otherwise.
47
+ /** @type {Readonly<Record<Category, Required<CategoryAssertion>>>} */
48
+ const BASE = {
49
+ performance: { level: "error", minScore: 0.95 },
50
+ accessibility: { level: "error", minScore: 0.95 },
51
+ "best-practices": { level: "error", minScore: 0.95 },
52
+ seo: { level: "error", minScore: 1 },
53
+ };
54
+
55
+ /**
56
+ * A full Lighthouse CI config: the shared thresholds, with the site's `collect` merged in.
57
+ * @param {LighthouseOptions} options
58
+ * @returns {LighthouseConfig}
59
+ */
60
+ export function lighthouseConfig(options) {
61
+ shape({ collect: isObject }, { categories: categoryChanges, matrix: matrixEntries })(
62
+ options,
63
+ "lighthouseConfig's options",
64
+ );
65
+ const { collect, categories = {}, matrix } = options;
66
+ /** @param {readonly Category[]} list */
67
+ const assertions = (list) =>
68
+ Object.fromEntries(
69
+ CATEGORIES.filter((category) => list.includes(category)).map((category) => {
70
+ const { level, minScore } = { ...BASE[category], ...categories[category] };
71
+ return [`categories:${category}`, [level, { minScore }]];
72
+ }),
73
+ );
74
+ return {
75
+ ci: {
76
+ collect: { numberOfRuns: 3, ...collect },
77
+ assert: matrix
78
+ ? {
79
+ assertMatrix: matrix.map(({ matchingUrlPattern, categories: list }) => ({
80
+ matchingUrlPattern,
81
+ assertions: assertions(list),
82
+ })),
83
+ }
84
+ : { assertions: assertions(CATEGORIES) },
85
+ upload: { target: "filesystem", outputDir: ".lighthouseci" },
86
+ },
87
+ };
88
+ }
package/package.json CHANGED
@@ -1,12 +1,56 @@
1
1
  {
2
2
  "name": "@uxfront/site-checks",
3
- "version": "0.0.0",
4
- "description": "Placeholder that reserves the name for trusted publishing. Install 0.1.0 or later.",
3
+ "version": "0.1.1",
4
+ "description": "The search and AI search checks and the Lighthouse CI preset shared by the uxfront.com family of sites.",
5
+ "keywords": [
6
+ "lighthouse",
7
+ "llms-txt",
8
+ "seo",
9
+ "sitemap"
10
+ ],
11
+ "homepage": "https://uxfront.com",
12
+ "bugs": "https://github.com/uxfront-com/uxfront/issues",
5
13
  "license": "MIT",
6
14
  "repository": {
7
15
  "type": "git",
8
16
  "url": "git+https://github.com/uxfront-com/uxfront.git",
9
17
  "directory": "packages/site-checks"
10
18
  },
11
- "publishConfig": { "access": "public" }
12
- }
19
+ "bin": {
20
+ "site-checks": "./bin/site-checks.js"
21
+ },
22
+ "files": [
23
+ "bin",
24
+ "lib",
25
+ "*.js",
26
+ "*.d.ts"
27
+ ],
28
+ "type": "module",
29
+ "sideEffects": false,
30
+ "exports": {
31
+ ".": {
32
+ "types": "./index.d.ts",
33
+ "default": "./index.js"
34
+ },
35
+ "./lighthouse": {
36
+ "types": "./lighthouse.d.ts",
37
+ "default": "./lighthouse.js"
38
+ },
39
+ "./package.json": "./package.json"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "^26.4.1",
46
+ "@uxfront/typescript-config": "0.2.1",
47
+ "vitest": "^5.0.1"
48
+ },
49
+ "engines": {
50
+ "node": ">=24"
51
+ },
52
+ "scripts": {
53
+ "check-types": "tsc --noEmit",
54
+ "test": "vitest run"
55
+ }
56
+ }