-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.ts
224 lines (198 loc) · 5.88 KB
/
cli.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#!/usr/bin/env node
import sade from "sade";
import { join, resolve } from "path";
import { readFileSync, existsSync } from "fs";
import { checkLinks } from "./index.js";
import { Entry, Options } from "./index.js";
import { DirectNavigationOptions } from "puppeteer";
interface CommandLineOptions {
"same-page": false | "err" | "warn";
"same-site": false | "err" | "warn";
"off-site": false | "err" | "warn";
fragments: false | "err" | "warn";
concurrency: number;
timeout: number;
"wait-until": DirectNavigationOptions["waitUntil"];
format: "json" | "pretty";
silent: boolean;
emoji: boolean;
}
const { version } = JSON.parse(
readFileSync(join(__dirname, "package.json"), "utf-8"),
) as { version: string };
sade("href-checker <url>", true)
.version(version)
.example("https://example.com")
.example("https://sidvishnoi.github.io/ --no-off-site --format=json")
.example("https://www.w3.org/ --no-same-site --no-same-page --fragments=err")
.option("--same-page", "Check same-page (fragment) links", "err")
.option("--same-site", "Check same-site links", "err")
.option("--off-site", "Check external links", "err")
.option("--fragments", "Check fragment anchors", "warn")
.option("--concurrency -c", "How many links to check at a time", 5)
.option("--timeout", "Timeout (in seconds) for navigation", 20)
.option(
"--wait-until",
'Wait until either "load", "domcontentloaded", "networkidle0", "networkidle2" events.',
"load",
)
.option("--format", "Format output as pretty or json", "pretty")
.option("--silent", "Show errors only", false)
.option("--emoji", "Use emoji in output (with --format=pretty)", true)
.action(async (url: string, options: CommandLineOptions) => {
try {
await main(url, options);
} catch (error) {
console.error(error.message);
process.exit(1);
}
})
.parse(process.argv);
async function main(input: string, opts: CommandLineOptions) {
const url = normalizeURL(input);
const LinkType = {
"same-page": "samePage",
"same-site": "sameSite",
"off-site": "offSite",
fragments: "fragments",
} as const;
for (const type of Object.keys(LinkType) as Array<keyof typeof LinkType>) {
if (![false, "err", "warn"].includes(opts[type])) {
throw new Error(
`Invalid value ${JSON.stringify(opts[type])} for --${type}.`,
);
}
}
const options: Options = {
samePage: opts["same-page"] !== false,
sameSite: opts["same-site"] !== false,
offSite: opts["off-site"] !== false,
fragments: opts.fragments !== false,
concurrency: opts.concurrency,
puppeteer: {
timeout: opts.timeout * 1000,
waitUntil: opts["wait-until"],
},
};
if (url.protocol === "file:" && options.sameSite) {
options.sameSite = false;
console.warn("Warning: --same-site is ignored with local files.");
}
const errorIf: OutputOptions["errorIf"] = new Set();
const warnIf: OutputOptions["warnIf"] = new Set();
for (const type of Object.keys(LinkType) as Array<keyof typeof LinkType>) {
const linkType = LinkType[type];
if (opts[type] === "err") {
errorIf.add(linkType);
} else if (opts[type] === "warn") {
warnIf.add(linkType);
}
}
const outputOptions: OutputOptions = {
silent: opts.silent,
format: opts.format || "pretty",
emoji: opts.format === "json" ? false : opts.emoji,
errorIf,
warnIf,
};
let hasFailures = false;
for await (const result of checkLinks(url, options)) {
const resultType = getResultType(result, outputOptions);
if (resultType === ResultType.fail) hasFailures = true;
const output = formatOutput(result, resultType, outputOptions);
if (output) console.log(output);
}
if (hasFailures) {
throw new Error("Broken links found.");
}
}
function normalizeURL(url: string) {
try {
return new URL(url);
} catch {
if (!existsSync(url)) {
throw new Error(`ENOENT (No such file): ${url}`);
}
url = resolve(url).replace(/\\/g, "/");
if (url[0] !== "/") {
url = "/" + url;
}
return new URL(encodeURI("file://" + url));
}
}
interface OutputOptions {
silent: CommandLineOptions["silent"];
format: CommandLineOptions["format"];
emoji: CommandLineOptions["emoji"];
errorIf: Set<"samePage" | "sameSite" | "offSite" | "fragments">;
warnIf: Set<"samePage" | "sameSite" | "offSite" | "fragments">;
}
function formatOutput(
result: Entry,
resultType: ResultType,
options: OutputOptions,
) {
const { input, output } = result;
if (options.silent && resultType === ResultType.ok) {
return null;
}
const statusSummary = getResultText(resultType, options.emoji);
if (options.format === "json") {
// @ts-ignore
result.output.summary = statusSummary;
if (result.output.error) {
const { name, message } = result.output.error;
result.output.error = { name, message };
}
return JSON.stringify(result);
}
const statusCode =
!output.error && !output.pageExists && output.status
? ` {${output.status}}`
: "";
let text = `[${result.type}]\t${statusSummary}\t${input.link} [x${input.count}]${statusCode}`;
if (output.error) {
text += ` (${output.error})`;
}
return text;
}
const enum ResultType {
ok,
fail,
warn,
err,
}
function getResultType(result: Entry, options: OutputOptions) {
const { pageExists, fragExists, error, status } = result.output;
if (error) {
return ResultType.err;
}
if (status === 429 /** Too many requests */) {
return ResultType.err;
}
if (
(!pageExists && options.errorIf.has(result.type)) ||
(fragExists === false && options.errorIf.has("fragments"))
) {
return ResultType.fail;
}
if (
(!pageExists && options.warnIf.has(result.type)) ||
(fragExists === false && options.warnIf.has("fragments"))
) {
return ResultType.warn;
}
return ResultType.ok;
}
function getResultText(resultType: ResultType, emoji: boolean) {
switch (resultType) {
case ResultType.ok:
return emoji ? "✅" : "ok";
case ResultType.fail:
return emoji ? "❌" : "fail";
case ResultType.warn:
return emoji ? "🚧" : "warn";
case ResultType.err:
return emoji ? "🚨" : "err";
}
}