w3c-html-validator 1.9.1 → 2.0.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.
package/README.md CHANGED
@@ -52,17 +52,17 @@ Command-line flags:
52
52
  | Flag | Description | Value |
53
53
  | ----------------- | ------------------------------------------------------------------- | ---------- |
54
54
  | `--continue` | Report messages but do not throw an error if validation failed. | N/A |
55
+ | `--default-rules` | Apply additional built-in opinionated ignore list. | N/A |
55
56
  | `--delay` | Debounce pause in milliseconds between each file validation. | **number** |
56
57
  | `--dry-run` | Bypass validation (for usage while building your CI). | N/A |
57
58
  | `--exclude` | Comma separated list of strings to match in paths to skip. | **string** |
58
- | `--ignore` | Skip validation messages containing a string or matching a regex. | **string** |
59
59
  | `--ignore-config` | File containing strings and regexes of validation messages to skip. | **string** |
60
+ | `--ignore` | Skip validation messages containing a string or matching a regex. | **string** |
60
61
  | `--note` | Place to add a comment only for humans. | **string** |
61
62
  | `--quiet` | Suppress messages for successful validations. | N/A |
62
63
  | `--trim` | Truncate validation messages to not exceed a maximum length. | **number** |
63
64
 
64
- ### 4. Example CLI usage
65
- Examples:
65
+ ### 4. Examples
66
66
  - `html-validator`<br>
67
67
  Validates all HTML files in the project.
68
68
 
@@ -81,8 +81,8 @@ Examples:
81
81
  - `html-validator docs --ignore-config=spec/ignore-config.txt`<br>
82
82
  Similar to the pervious command but strings and regexes are stored in a configuration file (see the _Configuration File for Ignore Patterns_ section below).
83
83
 
84
- - `html-validator --quiet`<br>
85
- Suppresses all the "pass" status messages.
84
+ - `html-validator --default-rules --quiet`<br>
85
+ Skip all HTML validation messages in the built-in opinionated ignore list and also suppresses all the "pass" status messages.
86
86
 
87
87
  - `html-validator docs --delay=200`<br>
88
88
  Validates all HTML files in the "docs" folder at a rate of 1 file per 200 ms (default is 500 ms).
@@ -108,6 +108,16 @@ Example configuration file with 3 regexes:
108
108
  The caret (`^`) regex operator says to match from the beginning of the validation message.&nbsp;
109
109
  The dot (`.`) regex operator says to match any one character, which is a handy way to avoid typing the special curly quote characters in some of the validation messages.
110
110
 
111
+ ### 6. Default Ignore List
112
+ The optional `--default-rules` flag causes HTML validation messages to be skipped if they are on the opinionated pre-defined list of unhelpful messages.&nbsp;
113
+
114
+ Default ignore list:
115
+ | Pattern | Level | Explanation |
116
+ | ------------------------ | ----------- | ----------- |
117
+ | `Section lacks heading.` | **warning** | Rule is sensible for traditional print publishing but absurd for modern UI components not burning in nested `<div>` hell. |
118
+
119
+ If there is an additional W3C validation message you think is ridiculous, open an issue with a note explaining why the message should be ignored.&nbsp;
120
+
111
121
  ## D) Application Code and Testing Frameworks
112
122
  In addition to the CLI interface, the **w3c-html-validator** package can also be imported and called directly in ESM and TypeScript projects.
113
123
 
@@ -137,6 +147,7 @@ $ node examples.js
137
147
  | Name (key) | Type | Default | Description |
138
148
  | :--------------- | :---------------------- | :------------------------------- | :------------------------------------------------------ |
139
149
  | `checkUrl` | **string** | `'https://validator.w3.org/nu/'` | W3C validation API endpoint. |
150
+ | `defaultRules` | **boolean** | `false` | Apply additional built-in opinionated ignore list. |
140
151
  | `dryRun` | **boolean** | `false` | Bypass validation (for usage while building your CI). |
141
152
  | `filename` | **string** | `null` | HTML file to validate. |
142
153
  | `html` | **string** | `null` | HTML string to validate. |
package/bin/cli.js CHANGED
@@ -21,62 +21,6 @@
21
21
  // $ npm test
22
22
  // $ node bin/cli.js spec --continue
23
23
 
24
- // Imports
25
- import { cliArgvUtil } from 'cli-argv-util';
26
- import { globSync } from 'glob';
27
24
  import { w3cHtmlValidator } from '../dist/w3c-html-validator.js';
28
- import fs from 'fs';
29
- import slash from 'slash';
30
25
 
31
- // Parameters and flags
32
- const validFlags =
33
- ['continue', 'delay', 'dry-run', 'exclude', 'ignore', 'ignore-config', 'note', 'quiet', 'trim'];
34
- const cli = cliArgvUtil.parse(validFlags);
35
- const files = cli.params.length ? cli.params.map(cliArgvUtil.cleanPath) : ['.'];
36
- const excludeList = cli.flagMap.exclude ? cli.flagMap.exclude.split(',') : [];
37
- const ignore = cli.flagMap.ignore ?? null;
38
- const ignoreConfig = cli.flagMap.ignoreConfig ?? null;
39
- const delay = Number(cli.flagMap.delay) || 500; //default half second debounce pause
40
- const trim = Number(cli.flagMap.trim) || null;
41
- const dryRunMode = cli.flagOn.dryRun || process.env.w3cHtmlValidator === 'dry-run'; //bash: export w3cHtmlValidator=dry-run
42
-
43
- const getFilenames = () => {
44
- const readFilenames = (file) => globSync(file, { ignore: '**/node_modules/**/*' }).map(slash);
45
- const readHtmlFiles = (folder) => readFilenames(folder + '/**/*.html');
46
- const addHtml = (file) => fs.lstatSync(file).isDirectory() ? readHtmlFiles(file) : file;
47
- const keep = (file) => excludeList.every(exclude => !file.includes(exclude));
48
- return files.map(readFilenames).flat().map(addHtml).flat().filter(keep).sort();
49
- };
50
- const filenames = getFilenames();
51
- const error =
52
- cli.invalidFlag ? cli.invalidFlagMsg :
53
- !filenames.length ? 'No files to validate.' :
54
- cli.flagOn.trim && !trim ? 'Value of "trim" must be a positive whole number.' :
55
- null;
56
- if (error)
57
- throw new Error('[w3c-html-validator] ' + error);
58
- if (dryRunMode)
59
- w3cHtmlValidator.dryRunNotice();
60
- if (filenames.length > 1 && !cli.flagOn.quiet)
61
- w3cHtmlValidator.summary(filenames.length);
62
- const reporterOptions = {
63
- continueOnFail: cli.flagOn.continue,
64
- quiet: cli.flagOn.quiet,
65
- maxMessageLen: trim,
66
- };
67
- const getIgnoreMessages = () => {
68
- const toArray = (text) => text.replace(/\r/g, '').split('\n').map(line => line.trim());
69
- const notComment = (line) => line.length > 1 && !line.startsWith('#');
70
- const readLines = (file) => toArray(fs.readFileSync(file).toString()).filter(notComment);
71
- const rawLines = ignoreConfig ? readLines(ignoreConfig) : [];
72
- if (ignore)
73
- rawLines.push(ignore);
74
- const isRegex = /^\/.*\/$/; //starts and ends with a slash indicating it's a regex
75
- return rawLines.map(line => isRegex.test(line) ? new RegExp(line.slice(1, -1)) : line);
76
- };
77
- const baseOptions = { ignoreMessages: getIgnoreMessages(), dryRun: dryRunMode };
78
- const options = (filename) => ({ filename: filename, ...baseOptions });
79
- const handleResults = (results) => w3cHtmlValidator.reporter(results, reporterOptions);
80
- const getReport = (filename) => w3cHtmlValidator.validate(options(filename)).then(handleResults);
81
- const processFile = (filename, i) => globalThis.setTimeout(() => getReport(filename), i * delay);
82
- filenames.forEach(processFile);
26
+ w3cHtmlValidator.cli();
@@ -1,15 +1,17 @@
1
- //! w3c-html-validator v1.9.1 ~~ https://github.com/center-key/w3c-html-validator ~~ MIT License
1
+ //! w3c-html-validator v2.0.1 ~~ https://github.com/center-key/w3c-html-validator ~~ MIT License
2
2
 
3
3
  export type ValidatorSettings = {
4
- html: string;
5
- filename: string;
6
- website: string;
7
- checkUrl: string;
8
- ignoreLevel: 'info' | 'warning';
9
- ignoreMessages: (string | RegExp)[];
10
- output: ValidatorResultsOutput;
4
+ html: string | null;
5
+ filename: string | null;
6
+ website: string | null;
7
+ checkUrl: string | null;
8
+ ignoreLevel: 'info' | 'warning' | null;
9
+ ignoreMessages: ValidatorIgnorePattern[];
10
+ defaultRules: boolean;
11
+ output: 'json' | 'html' | null;
11
12
  dryRun: boolean;
12
13
  };
14
+ export type ValidatorIgnorePattern = string | RegExp;
13
15
  export type ValidatorResultsMessage = {
14
16
  type: 'info' | 'error' | 'non-document-error' | 'network-error';
15
17
  subType?: 'warning' | 'fatal' | 'io' | 'schema' | 'internal';
@@ -36,7 +38,6 @@ export type ValidatorResults = {
36
38
  display: string | null;
37
39
  dryRun: boolean;
38
40
  };
39
- export type ValidatorResultsOutput = ValidatorResults['output'];
40
41
  export type ReporterSettings = {
41
42
  continueOnFail: boolean;
42
43
  maxMessageLen: number | null;
@@ -45,6 +46,9 @@ export type ReporterSettings = {
45
46
  };
46
47
  declare const w3cHtmlValidator: {
47
48
  version: string;
49
+ defaultIgnoreList: string[];
50
+ assert(ok: unknown, message: string | null): void;
51
+ cli(): void;
48
52
  validate(options: Partial<ValidatorSettings>): Promise<ValidatorResults>;
49
53
  dryRunNotice(): void;
50
54
  summary(numFiles: number): void;
@@ -1,30 +1,98 @@
1
- //! w3c-html-validator v1.9.1 ~~ https://github.com/center-key/w3c-html-validator ~~ MIT License
1
+ //! w3c-html-validator v2.0.1 ~~ https://github.com/center-key/w3c-html-validator ~~ MIT License
2
2
 
3
+ import { cliArgvUtil } from 'cli-argv-util';
4
+ import { globSync } from 'glob';
3
5
  import chalk from 'chalk';
4
6
  import fs from 'fs';
5
7
  import log from 'fancy-log';
6
8
  import request from 'superagent';
7
9
  import slash from 'slash';
8
10
  const w3cHtmlValidator = {
9
- version: '1.9.1',
11
+ version: '2.0.1',
12
+ defaultIgnoreList: [
13
+ 'Section lacks heading.'
14
+ ],
15
+ assert(ok, message) {
16
+ if (!ok)
17
+ throw new Error(`[w3c-html-validator] ${message}`);
18
+ },
19
+ cli() {
20
+ const validFlags = ['continue', 'default-rules', 'delay', 'dry-run', 'exclude',
21
+ 'ignore', 'ignore-config', 'note', 'quiet', 'trim'];
22
+ const cli = cliArgvUtil.parse(validFlags);
23
+ const files = cli.params.length ? cli.params.map(cliArgvUtil.cleanPath) : ['.'];
24
+ const excludeList = cli.flagMap.exclude?.split(',') ?? [];
25
+ const ignore = cli.flagMap.ignore ?? null;
26
+ const ignoreConfig = cli.flagMap.ignoreConfig ?? null;
27
+ const defaultRules = cli.flagOn.defaultRules;
28
+ const delay = Number(cli.flagMap.delay) || 500;
29
+ const trim = Number(cli.flagMap.trim) || null;
30
+ const dryRun = cli.flagOn.dryRun || process.env.w3cHtmlValidator === 'dry-run';
31
+ const getFilenames = () => {
32
+ const readFilenames = (file) => globSync(file, { ignore: '**/node_modules/**/*' }).map(slash);
33
+ const readHtmlFiles = (folder) => readFilenames(folder + '/**/*.html');
34
+ const addHtml = (file) => fs.lstatSync(file).isDirectory() ? readHtmlFiles(file) : file;
35
+ const keep = (file) => excludeList.every(exclude => !file.includes(exclude));
36
+ return files.map(readFilenames).flat().map(addHtml).flat().filter(keep).sort();
37
+ };
38
+ const filenames = getFilenames();
39
+ const error = cli.invalidFlag ? cli.invalidFlagMsg :
40
+ !filenames.length ? 'No files to validate.' :
41
+ cli.flagOn.trim && !trim ? 'Value of "trim" must be a positive whole number.' :
42
+ null;
43
+ w3cHtmlValidator.assert(!error, error);
44
+ if (dryRun)
45
+ w3cHtmlValidator.dryRunNotice();
46
+ if (filenames.length > 1 && !cli.flagOn.quiet)
47
+ w3cHtmlValidator.summary(filenames.length);
48
+ const reporterOptions = {
49
+ continueOnFail: cli.flagOn.continue,
50
+ maxMessageLen: trim,
51
+ quiet: cli.flagOn.quiet,
52
+ title: null,
53
+ };
54
+ const getIgnoreMessages = () => {
55
+ const toArray = (text) => text.replace(/\r/g, '').split('\n').map(line => line.trim());
56
+ const notComment = (line) => line.length > 1 && !line.startsWith('#');
57
+ const readLines = (file) => toArray(fs.readFileSync(file).toString()).filter(notComment);
58
+ const rawLines = ignoreConfig ? readLines(ignoreConfig) : [];
59
+ if (ignore)
60
+ rawLines.push(ignore);
61
+ const isRegex = /^\/.*\/$/;
62
+ return rawLines.map(line => isRegex.test(line) ? new RegExp(line.slice(1, -1)) : line);
63
+ };
64
+ const ignoreMessages = getIgnoreMessages();
65
+ const options = (filename) => ({ filename, ignoreMessages, defaultRules, dryRun });
66
+ const handleResults = (results) => w3cHtmlValidator.reporter(results, reporterOptions);
67
+ const getReport = (filename) => w3cHtmlValidator.validate(options(filename)).then(handleResults);
68
+ const processFile = (filename, i) => globalThis.setTimeout(() => getReport(filename), i * delay);
69
+ filenames.forEach(processFile);
70
+ },
10
71
  validate(options) {
11
72
  const defaults = {
12
73
  checkUrl: 'https://validator.w3.org/nu/',
74
+ defaultRules: false,
13
75
  dryRun: false,
76
+ filename: null,
77
+ html: null,
14
78
  ignoreLevel: null,
15
79
  ignoreMessages: [],
16
80
  output: 'json',
81
+ website: null,
17
82
  };
18
83
  const settings = { ...defaults, ...options };
19
- if (!settings.html && !settings.filename && !settings.website)
20
- throw new Error('[w3c-html-validator] Must specify the "html", "filename", or "website" option.');
21
- if (![null, 'info', 'warning'].includes(settings.ignoreLevel))
22
- throw new Error(`[w3c-html-validator] Invalid ignoreLevel option: ${settings.ignoreLevel}`);
23
- if (settings.output !== 'json' && settings.output !== 'html')
24
- throw new Error('[w3c-html-validator] Option "output" must be "json" or "html".');
84
+ const missingInput = !settings.html && !settings.filename && !settings.website;
85
+ const badLevel = ![null, 'info', 'warning'].includes(settings.ignoreLevel);
86
+ const invalidOutput = settings.output !== 'json' && settings.output !== 'html';
87
+ const error = missingInput ? 'Must specify the "html", "filename", or "website" option.' :
88
+ badLevel ? `Invalid ignoreLevel option: ${settings.ignoreLevel}` :
89
+ invalidOutput ? 'Option "output" must be "json" or "html".' :
90
+ null;
91
+ w3cHtmlValidator.assert(!error, error);
25
92
  const filename = settings.filename ? slash(settings.filename) : null;
26
93
  const mode = settings.html ? 'html' : filename ? 'filename' : 'website';
27
- const readFile = (filename) => fs.readFileSync(filename, 'utf-8').replace(/\r/g, '');
94
+ const unixify = (text) => text.replace(/\r/g, '');
95
+ const readFile = (filename) => unixify(fs.readFileSync(filename, 'utf-8'));
28
96
  const inputHtml = settings.html ?? (filename ? readFile(filename) : null);
29
97
  const makePostRequest = () => request.post(settings.checkUrl)
30
98
  .set('Content-Type', 'text/html; encoding=utf-8')
@@ -32,7 +100,8 @@ const w3cHtmlValidator = {
32
100
  const makeGetRequest = () => request.get(settings.checkUrl)
33
101
  .query({ doc: settings.website });
34
102
  const w3cRequest = inputHtml ? makePostRequest() : makeGetRequest();
35
- w3cRequest.set('User-Agent', 'W3C HTML Validator ~ github.com/center-key/w3c-html-validator');
103
+ const userAgent = 'W3C HTML Validator ~ github.com/center-key/w3c-html-validator';
104
+ w3cRequest.set('User-Agent', userAgent);
36
105
  w3cRequest.query({ out: settings.output });
37
106
  const json = settings.output === 'json';
38
107
  const success = '<p class="success">';
@@ -44,8 +113,11 @@ const w3cHtmlValidator = {
44
113
  const filterMessages = (response) => {
45
114
  const aboveInfo = (subType) => settings.ignoreLevel === 'info' && !!subType;
46
115
  const aboveIgnoreLevel = (message) => !settings.ignoreLevel || message.type !== 'info' || aboveInfo(message.subType);
47
- const matchesSkipPattern = (title) => settings.ignoreMessages.some(pattern => typeof pattern === 'string' ? title.includes(pattern) : pattern.test(title));
48
- const isImportant = (message) => aboveIgnoreLevel(message) && !matchesSkipPattern(message.message);
116
+ const defaultList = settings.defaultRules ? w3cHtmlValidator.defaultIgnoreList : [];
117
+ const ignoreList = [...settings.ignoreMessages, ...defaultList];
118
+ const tester = (title) => (pattern) => typeof pattern === 'string' ? title.includes(pattern) : pattern.test(title);
119
+ const skipMatchFound = (title) => ignoreList.some(tester(title));
120
+ const isImportant = (message) => aboveIgnoreLevel(message) && !skipMatchFound(message.message);
49
121
  if (json)
50
122
  response.body.messages = response.body.messages?.filter(isImportant) ?? [];
51
123
  return response;
@@ -93,8 +165,8 @@ const w3cHtmlValidator = {
93
165
  title: null,
94
166
  };
95
167
  const settings = { ...defaults, ...options };
96
- if (typeof results?.validates !== 'boolean')
97
- throw new Error(`[w3c-html-validator] Invalid results for reporter(): ${results}`);
168
+ const hasResults = 'validates' in results && typeof results.validates === 'boolean';
169
+ w3cHtmlValidator.assert(hasResults, `Invalid results for reporter(): ${results}`);
98
170
  const messages = results.messages ?? [];
99
171
  const title = settings.title ?? results.title;
100
172
  const status = results.validates ? chalk.green.bold('✔ pass') : chalk.red.bold('✘ fail');
@@ -122,8 +194,8 @@ const w3cHtmlValidator = {
122
194
  const fileDetails = () => `${results.filename} -- ${results.messages.map(toString).join(', ')}`;
123
195
  return !results.filename ? results.messages[0].message : fileDetails();
124
196
  };
125
- if (!settings.continueOnFail && !results.validates)
126
- throw new Error(`[w3c-html-validator] Failed: ${failDetails()}`);
197
+ const failed = !settings.continueOnFail && !results.validates;
198
+ w3cHtmlValidator.assert(!failed, `Failed: ${failDetails()}`);
127
199
  return results;
128
200
  },
129
201
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "w3c-html-validator",
3
- "version": "1.9.1",
3
+ "version": "2.0.1",
4
4
  "description": "Check the markup validity of HTML files using the W3C validator",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -53,11 +53,11 @@
53
53
  },
54
54
  "scripts": {
55
55
  "pretest": "run-scripts clean lint build",
56
- "test": "mocha spec/*.spec.js --timeout 7000",
56
+ "test": "mocha spec --timeout 7000",
57
57
  "examples": "node examples.js"
58
58
  },
59
59
  "dependencies": {
60
- "chalk": "~5.5",
60
+ "chalk": "~5.6",
61
61
  "cli-argv-util": "~1.3",
62
62
  "fancy-log": "~2.0",
63
63
  "glob": "~11.0",
@@ -65,21 +65,20 @@
65
65
  "superagent": "~10.2"
66
66
  },
67
67
  "devDependencies": {
68
- "@eslint/js": "~9.33",
68
+ "@eslint/js": "~9.39",
69
69
  "@types/fancy-log": "~2.0",
70
- "@types/node": "~24.2",
70
+ "@types/node": "~24.10",
71
71
  "@types/superagent": "~8.1",
72
- "add-dist-header": "~1.5",
72
+ "add-dist-header": "~1.6",
73
73
  "assert-deep-strict-equal": "~1.2",
74
74
  "copy-file-util": "~1.3",
75
75
  "copy-folder-util": "~1.1",
76
- "eslint": "~9.33",
76
+ "eslint": "~9.39",
77
77
  "jshint": "~2.13",
78
- "merge-stream": "~2.0",
79
78
  "mocha": "~11.7",
80
- "rimraf": "~6.0",
79
+ "rimraf": "~6.1",
81
80
  "run-scripts-util": "~1.3",
82
81
  "typescript": "~5.9",
83
- "typescript-eslint": "~8.39"
82
+ "typescript-eslint": "~8.46"
84
83
  }
85
84
  }