This repository has been archived by the owner on Jul 19, 2023. It is now read-only.
forked from callumacrae/gulp-w3cjs
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhtml-validator.ts
63 lines (55 loc) · 2.16 KB
/
html-validator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// gulp-w3c-html-validator
// Gulp plugin to validate HTML using the W3C Markup Validation Service
// https://github.com/center-key/gulp-w3c-html-validator
// MIT License
// Types
export type AnalyzerOptions = ValidatorOptions;
export type ReporterSettings = {
maxMessageLen: number,
throwErrors: boolean,
};
export type ReporterOptions = Partial<ReporterSettings>;
// Imports
import { Transform } from 'stream';
import { ValidatorOptions, ValidatorResults, w3cHtmlValidator } from 'w3c-html-validator';
import PluginError from 'plugin-error';
import through2 from 'through2';
// Setup
const pluginName = 'gulp-w3c-html-validator';
// Gulp plugin
const htmlValidator = {
analyzer(options: AnalyzerOptions): Transform {
const validate: through2.TransformFunction = (file, _encoding, done) => {
const handleValidation = (results: ValidatorResults) => {
file.w3cHtmlValidator = results;
done(null, file);
};
const validatorOptions = { ...options, ...{ html: file.contents.toString() } };
if (file.isNull())
done(null, file);
else if (file.isStream())
done(new PluginError(pluginName, 'Streaming not supported'));
else
w3cHtmlValidator.validate(validatorOptions).then(handleValidation);
};
return through2.obj(validate);
},
reporter(options: ReporterOptions): Transform {
const defaults = { maxMessageLen: null, throwErrors: false };
const settings = { ...defaults, ...options };
const report: through2.TransformFunction = (file, _encoding, done) => {
const reporterOptions = {
title: file.path,
maxMessageLen: settings.maxMessageLen,
continueOnFail: true,
};
if (file.w3cHtmlValidator)
w3cHtmlValidator.reporter(file.w3cHtmlValidator, reporterOptions);
done(null, file);
if (settings.throwErrors && file.w3cHtmlValidator && !file.w3cHtmlValidator.validates)
throw new PluginError(pluginName, 'HTML validation failed');
};
return through2.obj(report);
},
};
export { htmlValidator };