-
-
Notifications
You must be signed in to change notification settings - Fork 441
/
Copy pathindex.js
executable file
·357 lines (305 loc) · 10.6 KB
/
index.js
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const safeRequire = (name) => {
try {
return require(name);
} catch (error) {
if (error && error.code === 'MODULE_NOT_FOUND') {
console.log(`Error: Cannot find module '${name}', have you installed the dependencies?`);
process.exit(1);
}
throw error;
}
};
const Ajv = safeRequire('ajv').default;
const betterAjvErrors = safeRequire('better-ajv-errors').default;
const chalk = safeRequire('chalk');
const YAML = safeRequire('yaml');
const addFormats = safeRequire('ajv-formats');
// https://www.peterbe.com/plog/nodejs-fs-walk-or-glob-or-fast-glob
function walk(directory, ext, filepaths = []) {
const files = fs.readdirSync(directory);
for (const filename of files) {
const filepath = path.join(directory, filename);
if (fs.statSync(filepath).isDirectory()) {
walk(filepath, ext, filepaths);
} else if (path.extname(filename) === ext) {
filepaths.push(filepath);
}
}
return filepaths;
}
// https://stackoverflow.com/a/53833620
const isSorted = arr => arr.every((v,i,a) => !i || a[i-1] <= v);
class Validator {
constructor(flags) {
this.allowDeprecations = flags.includes('-d');
this.stopOnError = !flags.includes('-a');
this.sortedURLs = flags.includes('-s');
this.verbose = flags.includes('-v');
const schemaPath = path.resolve(__dirname, './scraper.schema.json');
this.schema = JSON.parse(fs.readFileSync(schemaPath, 'utf8'));
this.ajv = new Ajv({
// allErrors: true,
ignoreKeywordsWithRef: true, // should be 'fail' with ajv v7
strict: true,
});
addFormats(this.ajv);
this.mappingPattern = /^([a-z]+)By(Fragment|Name|URL)$/;
}
run(files) {
let scrapers;
if (files && Array.isArray(files) && files.length > 0) {
scrapers = files.map(file => path.resolve(file));
} else {
const scrapersDir = path.resolve(__dirname, '../scrapers');
scrapers = walk(scrapersDir, '.yml');
}
const yamlLoadOptions = {
prettyErrors: true,
version: '1.2',
merge: true,
};
let result = true;
const validate = this.ajv.compile(this.schema);
for (const file of scrapers) {
const relPath = path.relative(process.cwd(), file);
let contents, data;
try {
contents = fs.readFileSync(file, 'utf8');
data = YAML.parse(contents, yamlLoadOptions);
} catch (error) {
console.error(`${chalk.red(chalk.bold('ERROR'))} in: ${relPath}:`);
error.stack = null;
console.error(error);
result = result && false;
if (this.stopOnError) break;
else continue;
}
let valid = validate(data);
// If schema validation did not pass, don't try to validate mappings.
if (valid) {
const mappingErrors = this.getMappingErrors(data);
const validMapping = mappingErrors.length === 0;
if (!validMapping) {
validate.errors = (validate.errors || []).concat(mappingErrors);
}
valid = valid && validMapping;
}
// Output validation errors
if (!valid) {
const output = betterAjvErrors('scraper', data, validate.errors, { indent: 2 });
console.log(output);
}
if (this.verbose || !valid) {
const validColor = valid ? chalk.green : chalk.red;
console.log(`${relPath} Valid: ${validColor(valid)}`);
}
result = result && valid;
if (!valid && this.stopOnError) break;
}
if (!this.verbose && result) {
console.log(chalk.green('Validation passed!'));
}
return result;
}
getMappingErrors(data) {
return [].concat(
this._collectConfigMappingErrors(data),
this._collectScraperDefinitionErrors(data),
this._collectCookieErrors(data),
);
}
_collectConfigMappingErrors(data) {
const errors = [];
if (data.sceneByName && !data.sceneByQueryFragment) {
errors.push({
keyword: 'sceneByName',
message: `a \`sceneByQueryFragment\` configuration is required for \`sceneByName\` to work`,
params: { keyword: 'sceneByName' },
dataPath: '/sceneByName',
});
}
return errors;
}
_collectScraperDefinitionErrors(data) {
const hasStashServer = Object.keys(data).includes('stashServer');
const xPathScrapers = data.xPathScrapers ? Object.keys(data.xPathScrapers) : [];
const jsonScrapers = data.jsonScrapers ? Object.keys(data.jsonScrapers) : [];
let needsStashServer = false;
const configuredXPathScrapers = [];
const configuredJsonScrapers = [];
const errors = [];
Object.entries(data).forEach(([key, value]) => {
const match = this.mappingPattern.exec(key);
if (!match) {
return;
}
const seenURLs = {};
const type = match[1];
const multiple = value instanceof Array;
(multiple ? value : [value]).forEach(({ action, scraper, url }, idx) => {
const dataPath = `/${key}${multiple ? `/${idx}` : ''}`;
if (action === 'stash') {
needsStashServer = true;
if (!hasStashServer) {
errors.push({
keyword: 'action',
message: `root object should contain a \`stashServer\` definition`,
params: { keyword: 'action' },
dataPath: dataPath + '/action',
});
}
return;
}
if (action === 'scrapeXPath') {
configuredXPathScrapers.push(scraper);
if (!xPathScrapers.includes(scraper)) {
errors.push({
keyword: 'scraper',
message: `xPathScrapers should contain a XPath scraper definition for \`${scraper}\``,
params: { keyword: 'scraper' },
dataPath: dataPath + '/scraper',
});
} else if (!data.xPathScrapers || !data.xPathScrapers[scraper][type]) {
errors.push({
keyword: scraper,
message: `\`${scraper}\` should create an object of type \`${type}\``,
params: { keyword: scraper },
dataPath: `/xPathScrapers/${scraper}`,
});
}
if (url) {
url.forEach((u, uIdx) => {
const exists = seenURLs[u];
if (exists) {
errors.push({
keyword: 'url',
message: `URLs for type \`${type}\` should be unique, already exists on ${exists}`,
params: { keyword: 'url' },
dataPath: `${dataPath}/url/${uIdx}`,
});
} else {
seenURLs[u] = `${dataPath}/url/${uIdx}`;
}
});
if (this.sortedURLs && !isSorted(url)) {
errors.push({
keyword: 'url',
message: 'URL list should be sorted in ascending alphabetical order',
params: { keyword: 'url' },
dataPath: dataPath + '/url',
});
}
}
return;
}
if (action === 'scrapeJson') {
configuredJsonScrapers.push(scraper);
if (!jsonScrapers.includes(scraper)) {
errors.push({
keyword: 'scraper',
message: `jsonScrapers should contain a JSON scraper definition for \`${scraper}\``,
params: { keyword: 'scraper' },
dataPath: dataPath + '/scraper',
});
} else if (!data.jsonScrapers || !data.jsonScrapers[scraper][type]) {
errors.push({
keyword: scraper,
message: `\`${scraper}\` should create an object of type \`${type}\``,
params: { keyword: scraper },
dataPath: `/jsonScrapers/${scraper}`,
});
}
if (url) {
url.forEach((u, uIdx) => {
const exists = seenURLs[u];
if (exists) {
errors.push({
keyword: 'url',
message: `URLs for type \`${type}\` should be unique, already exists on ${exists}`,
params: { keyword: 'url' },
dataPath: `${dataPath}/url/${uIdx}`,
});
} else {
seenURLs[u] = `${dataPath}/url/${uIdx}`;
}
});
if (this.sortedURLs && !isSorted(url)) {
errors.push({
keyword: 'url',
message: 'URL list should be sorted in ascending alphabetical order',
params: { keyword: 'url' },
dataPath: dataPath + '/url',
});
}
}
return;
}
// if (action === 'script') {
// return;
// }
//
// errors.push({
// keyword: 'action',
// message: `unsupported action \`${action}\``,
// params: { keyword: 'action' },
// dataPath: dataPath + '/action',
// });
});
});
// Check for unused definitions
if (!needsStashServer && hasStashServer) {
errors.unshift({
keyword: 'stashServer',
message: '`stashServer` is defined, but never used',
params: { keyword: 'stashServer' },
dataPath: '/stashServer',
});
}
return errors;
}
_collectCookieErrors(data) {
const errors = [];
const cookies = data.driver && data.driver.cookies;
if (cookies) {
const usesCDP = Boolean(data.driver && data.driver.useCDP);
cookies.forEach((cookieItem, idx) => {
const hasCookieURL = 'CookieURL' in cookieItem;
if (!usesCDP && !hasCookieURL) {
errors.push({
keyword: 'CookieURL',
message: '`CookieURL` is required because useCDP is `false`',
params: { keyword: 'CookieURL' },
dataPath: `/driver/cookies/${idx}`,
});
} else if (usesCDP && hasCookieURL) {
errors.push({
keyword: 'CookieURL',
message: 'Should not have `CookieURL` because useCDP is `true`',
params: { keyword: 'CookieURL' },
dataPath: `/driver/cookies/${idx}/CookieURL`,
});
}
});
}
return errors;
}
}
function main(flags, files) {
const args = process.argv.slice(2)
flags = (flags === undefined) ? args.filter(arg => arg.startsWith('-')) : flags;
files = (files === undefined) ? args.filter(arg => !arg.startsWith('-')) : files;
const validator = new Validator(flags);
const result = validator.run(files);
if (flags.includes('--ci')) {
process.exit(result ? 0 : 1);
}
}
if (require.main === module) {
main();
}
module.exports = main;
module.exports.Validator = Validator;