Skip to content

Commit

Permalink
Convert to new flat config for eslint
Browse files Browse the repository at this point in the history
  • Loading branch information
dpilafian committed Aug 12, 2024
1 parent ec25f52 commit 00c8e28
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 52 deletions.
2 changes: 1 addition & 1 deletion bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const error =
cli.flagOn.trim && !trim ? 'Value of "trim" must be a positive whole number.' :
null;
if (error)
throw Error('[w3c-html-validator] ' + error);
throw new Error('[w3c-html-validator] ' + error);
if (dryRunMode)
w3cHtmlValidator.dryRunNotice();
if (filenames.length > 1 && !cli.flagOn.quiet)
Expand Down
22 changes: 22 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// @ts-check

import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';

export default [
eslint.configs.recommended,
...tseslint.configs.strictTypeChecked,
{ ignores: ['**/*.js'] },
{
languageOptions: { parserOptions: { projectService: true } },
rules: {
'@typescript-eslint/no-confusing-void-expression': 'off', //prefer minimal arrow functions
'@typescript-eslint/no-floating-promises': 'off', //annimations may be fire-and-forget
'@typescript-eslint/no-misused-promises': 'off', //annimations may be fire-and-forget
'@typescript-eslint/no-non-null-assertion': 'off', //ts cannot always know value exists
'@typescript-eslint/restrict-template-expressions': 'off', //numbers in templates are natural
'@typescript-eslint/unbound-method': 'off', //safer to not use 'this'
'@typescript-eslint/use-unknown-in-catch-callback-variable': 'off', //clarity over theoretical exceptions
},
},
];
39 changes: 10 additions & 29 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,32 +38,13 @@
"node": true,
"mocha": true
},
"eslintConfig": {
"ignorePatterns": [
"build",
"dist",
"node_modules"
],
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"@typescript-eslint/no-non-null-assertion": "off"
}
},
"runScriptsConfig": {
"clean": [
"rimraf build dist"
],
"lint": [
"jshint . --exclude-path .gitignore",
"eslint --max-warnings 0 . --ext .ts"
"eslint --max-warnings 0"
],
"build": [
"tsc",
Expand All @@ -79,26 +60,26 @@
"chalk": "~5.3",
"cli-argv-util": "~1.2",
"fancy-log": "~2.0",
"glob": "~10.4",
"glob": "~11.0",
"slash": "~5.1",
"superagent": "~9.0"
},
"devDependencies": {
"@eslint/js": "~9.3",
"@eslint/js": "~9.9",
"@types/fancy-log": "~2.0",
"@types/node": "~20.12",
"@types/node": "~22.2",
"@types/superagent": "~8.1",
"add-dist-header": "~1.4",
"assert-deep-strict-equal": "~1.2",
"copy-file-util": "~1.2",
"copy-folder-util": "~1.1",
"eslint": "8.57.0",
"eslint": "~9.9",
"jshint": "~2.13",
"merge-stream": "~2.0",
"mocha": "~10.4",
"rimraf": "~5.0",
"run-scripts-util": "~1.2",
"typescript": "~5.4",
"typescript-eslint": "~7.11"
"mocha": "~10.7",
"rimraf": "~6.0",
"run-scripts-util": "~1.3",
"typescript": "~5.5",
"typescript-eslint": "~8.0"
}
}
6 changes: 3 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,21 @@
"target": "ES2021",
"module": "ES2020",
"moduleResolution": "node",
"esModuleInterop": true,
"declaration": true,
"outDir": "build",
"newLine": "lf",
"removeComments": true,
"strict": true,
"allowSyntheticDefaultImports": true,
"alwaysStrict": true,
"esModuleInterop": true,
"exactOptionalPropertyTypes": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"removeComments": true
"noUnusedLocals": true
}
}
38 changes: 19 additions & 19 deletions w3c-html-validator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// W3C HTML Validator ~ MIT License

// Imports
import chalk from 'chalk';
import chalk, { ChalkInstance } from 'chalk';
import fs from 'fs';
import log from 'fancy-log';
import request from 'superagent';
Expand All @@ -28,7 +28,7 @@ export type ValidatorResultsMessage = {
type: 'info' | 'error' | 'non-document-error' | 'network-error',
subType?: 'warning' | 'fatal' | 'io' | 'schema' | 'internal',
message: string, //example: 'Section lacks heading.'
extract: string, //example: '<section>Hi</section>'
extract?: string, //example: '<section>Hi</section>'
lastLine: number,
firstColumn: number,
lastColumn: number,
Expand Down Expand Up @@ -73,11 +73,11 @@ const w3cHtmlValidator = {
};
const settings = { ...defaults, ...options };
if (!settings.html && !settings.filename && !settings.website)
throw Error('[w3c-html-validator] Must specify the "html", "filename", or "website" option.');
throw new Error('[w3c-html-validator] Must specify the "html", "filename", or "website" option.');
if (![null, 'info', 'warning'].includes(settings.ignoreLevel))
throw Error('[w3c-html-validator] Invalid ignoreLevel option: ' + settings.ignoreLevel);
throw new Error(`[w3c-html-validator] Invalid ignoreLevel option: ${settings.ignoreLevel}`);
if (settings.output !== 'json' && settings.output !== 'html')
throw Error('[w3c-html-validator] Option "output" must be "json" or "html".');
throw new Error('[w3c-html-validator] Option "output" must be "json" or "html".');
const filename = settings.filename ? slash(settings.filename) : null;
const mode = settings.html ? 'html' : filename ? 'filename' : 'website';
const readFile = (filename: string) => fs.readFileSync(filename, 'utf-8').replace(/\r/g, '');
Expand All @@ -93,7 +93,7 @@ const w3cHtmlValidator = {
const json = settings.output === 'json';
const success = '<p class="success">';
const titleLookup = {
html: 'HTML String (characters: ' + inputHtml?.length + ')',
html: `HTML String (characters: ${inputHtml?.length})`,
filename: filename,
website: settings.website,
};
Expand All @@ -108,28 +108,28 @@ const w3cHtmlValidator = {
const isImportant = (message: ValidatorResultsMessage): boolean =>
aboveIgnoreLevel(message) && !matchesSkipPattern(message.message);
if (json)
response.body.messages = response.body.messages?.filter(isImportant) ?? [];
response.body.messages = response.body.messages?.filter(isImportant) ?? []; //eslint-disable-line
return response;
};
const toValidatorResults = (response: request.Response): ValidatorResults => ({
validates: json ? !response.body.messages.length : !!response.text?.includes(success),
validates: json ? !response.body.messages.length : !!response.text?.includes(success), //eslint-disable-line
mode: mode,
title: <string>titleLookup[mode],
html: inputHtml,
filename: filename,
website: settings.website || null,
output: <ValidatorResultsOutput>settings.output,
status: response.statusCode || -1,
messages: json ? response.body.messages : null,
messages: json ? response.body.messages : null, //eslint-disable-line
display: json ? null : response.text,
dryRun: settings.dryRun,
});
type ReasonResponse = { request: { url: string }, res: { statusMessage: string }};
type ReasonError = Error & { errno: number, response: request.Response & ReasonResponse };
const handleError = (reason: ReasonError): ValidatorResults => {
const errRes = reason.response ?? <ReasonError['response']>{};
const errRes = reason.response ?? <ReasonError['response']>{}; //eslint-disable-line
const getMsg = () => [errRes.status, errRes.res.statusMessage, errRes.request.url];
const message = reason.response ? getMsg() : [reason.errno, reason.message];
const message = reason.response ? getMsg() : [reason.errno, reason.message]; //eslint-disable-line
errRes.body = { messages: [{ type: 'network-error', message: message.join(' ') }] };
return toValidatorResults(errRes);
};
Expand All @@ -150,7 +150,7 @@ const w3cHtmlValidator = {
},

summary(numFiles: number) {
log(chalk.gray('w3c-html-validator'), chalk.magenta('files: ' + numFiles));
log(chalk.gray('w3c-html-validator'), chalk.magenta('files: ' + String(numFiles)));
},

reporter(results: ValidatorResults, options?: Partial<ReporterSettings>): ValidatorResults {
Expand All @@ -161,21 +161,21 @@ const w3cHtmlValidator = {
title: null,
};
const settings = { ...defaults, ...options };
if (typeof results?.validates !== 'boolean')
throw Error('[w3c-html-validator] Invalid results for reporter(): ' + String(results));
if (typeof results?.validates !== 'boolean') //eslint-disable-line
throw new Error('[w3c-html-validator] Invalid results for reporter(): ' + String(results));
const messages = results.messages ?? [];
const title = settings.title ?? results.title;
const status = results.validates ? chalk.green.bold('✔ pass') : chalk.red.bold('✘ fail');
const count = results.validates ? '' : '(messages: ' + messages!.length + ')';
const count = results.validates ? '' : `(messages: ${messages.length})`;
if (!results.validates || !settings.quiet)
log(chalk.gray('w3c-html-validator'), status, chalk.blue.bold(title), chalk.white(count));
const typeColorMap = {
const typeColorMap = <{ [messageType: string]: ChalkInstance }>{
error: chalk.red.bold,
warning: chalk.yellow.bold,
info: chalk.white.bold,
};
const logMessage = (message: ValidatorResultsMessage) => {
const type = <keyof typeof typeColorMap>(message.subType ?? message.type);
const type = message.subType ?? message.type;
const typeColor = typeColorMap[type] ?? chalk.redBright.bold;
const location = `line ${message.lastLine}, column ${message.firstColumn}:`;
const lineText = message.extract?.replace(/\n/g, '\\n');
Expand All @@ -190,11 +190,11 @@ const w3cHtmlValidator = {
const toString = (message: ValidatorResultsMessage) =>
`${message.subType ?? message.type} line ${message.lastLine} column ${message.firstColumn}`;
const fileDetails = () =>
results.filename + ' -- ' + results.messages!.map(toString).join(', ');
`${results.filename} -- ${results.messages!.map(toString).join(', ')}`;
return !results.filename ? results.messages![0]!.message : fileDetails();
};
if (!settings.continueOnFail && !results.validates)
throw Error('[w3c-html-validator] Failed: ' + failDetails());
throw new Error('[w3c-html-validator] Failed: ' + failDetails());
return results;
},

Expand Down

0 comments on commit 00c8e28

Please sign in to comment.