-
Notifications
You must be signed in to change notification settings - Fork 22
/
checker-chromium.js
221 lines (194 loc) · 8.54 KB
/
checker-chromium.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
'use strict';
const fileUrl = require('file-url');
const fs = require('fs-extra');
const path = require('path');
const pMap = require('p-map');
const tmp = require('tmp');
const winston = require('winston');
const axe2ace = require('@daisy/ace-report-axe');
const { getRawResourcesForCurrentLanguage } = require('../l10n/localize').localizer;
const DISABLE_CONCURRENT_TO_DEBUG_INDIVIDUAL_SPINE_ITEM = false;
// const encodeURIComponent_RFC3986 = require('@daisy/epub-utils').encodeURIComponent_RFC3986;
function encodeURIComponent_RFC3986(str) {
return encodeURIComponent(str)
.replace(/[!'()*]/g, (c) => {
return "%" + c.charCodeAt(0).toString(16);
});
}
tmp.setGracefulCleanup();
const scripts = [
// require.resolve('../scripts/function-bind-bound-object.js'),
// require.resolve('../scripts/vendor/outliner.min.js'),
path.resolve(require.resolve('@daisy/axe-core-for-ace'), '../axe.js'),
// require.resolve('../scripts/axe-patch-aria-roles.js'),
// require.resolve('../scripts/axe-patch-is-aria-role-allowed.js'),
// require.resolve('../scripts/axe-patch-only-list-items.js'),
// require.resolve('../scripts/axe-patch-listitem.js'),
require.resolve('../scripts/ace-axe.js'),
require.resolve('../scripts/ace-extraction.js'),
];
const LOG_DEBUG_URLS = process.env.LOG_DEBUG_URLS === "1";
async function checkSingle(spineItem, epub, lang, axeRunner) {
winston.verbose(`- Processing ${spineItem.relpath}`);
try {
if (LOG_DEBUG_URLS) {
console.log("....... URL 1");
console.log(spineItem.url);
console.log(spineItem.filepath);
console.log(spineItem.relpath);
}
let url = spineItem.url;
let ext = path.extname(spineItem.filepath);
// File extensions other than 'xhtml' or 'html' are not propertly loaded
// by puppeteer, so we copy the file to a new `.xhtml` temp file.
if (!process.versions['electron'] && // The Electron-based Axe runner handles .xml files just fine
ext !== '.xhtml' && ext !== '.html') {
winston.warn(`Copying document with extension '${ext}' to a temporary '.xhtml' file…`);
const tmpdir = tmp.dirSync({ unsafeCleanup: true }).name;
const tmpFile = path.join(tmpdir, `${path.basename(spineItem.filepath, ext)}.xhtml`)
fs.copySync(spineItem.filepath, tmpFile);
// does encodeURI() as per https://tools.ietf.org/html/rfc3986#section-3.3 in a nutshell: encodeURI(`file://${tmpFile}`).replace(/[?#]/g, encodeURIComponent)
url = fileUrl(tmpFile);
// url = "file://" + encodeURI(tmpFile);
winston.debug(`checking copied file at ${tmpFile}`)
}
if (LOG_DEBUG_URLS) {
console.log("....... URL 2");
console.log(url);
}
const scriptContents = [];
let localePath = "";
try {
winston.debug(`- Axe locale: [${lang}]`);
// https://github.com/dequelabs/axe-core#localization
// https://github.com/dequelabs/axe-core/tree/develop/locales
if (lang && lang !== "en" && lang.indexOf("en-") !== 0) { // default English built into Axe source code
localePath = path.resolve(require.resolve('@daisy/axe-core-for-ace'), `../locales/${lang}.json`);
if (fs.existsSync(localePath)) {
const localeStr = fs.readFileSync(localePath, { encoding: "utf8" });
const localeScript = `window.__axeLocale__=${localeStr};`;
scriptContents.push(localeScript);
} else {
winston.debug(`- Axe locale missing? [${lang}] => ${localePath}`);
}
}
// let localizedScript = "";
// const rawJson = getRawResourcesForCurrentLanguage();
// ["axecheck", "axerule"].forEach((checkOrRule) => {
// const checkOrRuleKeys = Object.keys(rawJson[checkOrRule]);
// for (const checkOrRuleKey of checkOrRuleKeys) {
// const msgs = Object.keys(rawJson[checkOrRule][checkOrRuleKey]);
// for (const msg of msgs) {
// const k = `_xx_aceLocalize__${checkOrRule}_${checkOrRuleKey}_${msg}`;
// let v = rawJson[checkOrRule][checkOrRuleKey][msg];
// if (v) {
// v = v.replace(/"/g, '\\"');
// }
// localizedScript += `window['${k}']="${v}";\n`;
// }
// }
// });
// scriptContents.push(localizedScript);
} catch (err) {
console.log(err);
winston.verbose(err);
winston.debug(`- Axe locale problem? [${lang}] => ${localePath}`);
}
if (DISABLE_CONCURRENT_TO_DEBUG_INDIVIDUAL_SPINE_ITEM) console.log("BEFORE axeRunner... ", lang, url, JSON.stringify(spineItem, null, 4), JSON.stringify(scripts, null, 4), JSON.stringify(scriptContents, null, 4)); // JSON.stringify(epub, null, 4)
const results = await axeRunner.run(url, scripts, scriptContents, epub.basedir);
if (DISABLE_CONCURRENT_TO_DEBUG_INDIVIDUAL_SPINE_ITEM) console.log("AFTER axeRunner. ", url);
// Post-process results
if (!results.axe) {
results.assertions = [];
} else {
results.assertions = await axe2ace.axe2ace(spineItem, results.axe, lang);
delete results.axe;
}
winston.info(`- ${spineItem.relpath}: ${
(results.assertions && results.assertions.assertions && results.assertions.assertions.length > 0)
? results.assertions.assertions.length
: 'No'} issues found`);
// Resolve path and locators for extracted data
if (results.data != null) {
Object.getOwnPropertyNames(results.data).forEach((key) => {
if (!Array.isArray(results.data[key])) return;
results.data[key].forEach((item) => {
if (item.src) {
if (Array.isArray(item.src)) {
item.src = item.src.map((srcItem) => {
if (srcItem.src) {
if (LOG_DEBUG_URLS) {
console.log("----- ITEMs SRC 1");
console.log(srcItem.src);
}
srcItem.path = path.resolve(path.dirname(spineItem.filepath), decodeURIComponent(srcItem.src.toString()));
if (LOG_DEBUG_URLS) {
console.log("----- ITEMs SRC 2");
console.log(srcItem.path);
}
srcItem.src = path.relative(epub.basedir, srcItem.path).replace(/\\/g, "/");
if (LOG_DEBUG_URLS) {
console.log("----- ITEMs SRC 3");
console.log(srcItem.src);
}
}
return srcItem;
});
} else {
if (LOG_DEBUG_URLS) {
console.log("----- ITEM SRC 1");
console.log(item.src);
}
item.path = path.resolve(path.dirname(spineItem.filepath), decodeURIComponent(item.src.toString()));
if (LOG_DEBUG_URLS) {
console.log("----- ITEM SRC 2");
console.log(item.path);
}
item.src = path.relative(epub.basedir, item.path).replace(/\\/g, "/");
if (LOG_DEBUG_URLS) {
console.log("----- ITEM SRC 3");
console.log(item.src);
}
}
if (item.cfi) {
if (LOG_DEBUG_URLS) {
console.log("----- CFI 1");
console.log(spineItem.relpath);
console.log(item.cfi);
}
// encodeURIComponent_RFC3986
item.location = `${encodeURI(spineItem.relpath)}#epubcfi(${encodeURI(item.cfi)})`;
if (LOG_DEBUG_URLS) {
console.log("----- CFI 2");
console.log(item.location);
}
delete item.cfi;
}
}
});
});
}
return results;
} catch (err) {
console.log(err);
winston.debug(`Error when running HTML checks: ${err.message ? err.message : err}`);
if (err.stack) winston.debug(err.stack);
throw new Error(`Failed to check Content Document '${spineItem.relpath}': ${err.message ? err.message : err}`);
}
}
module.exports.check = async (epub, lang, axeRunner) => {
await axeRunner.launch();
winston.info('Checking documents...');
return pMap(epub.contentDocs, (doc) => {
return checkSingle(doc, epub, lang, axeRunner); // not AWAIT'ed! (pMap takes the Promise)
}, { concurrency: DISABLE_CONCURRENT_TO_DEBUG_INDIVIDUAL_SPINE_ITEM ? 1 : axeRunner.concurrency })
.then(async (results) => {
await axeRunner.close();
return results;
}).catch(async (err) => {
winston.error(`Ace HTML check error: ${err.message ? err.message : err}`);
if (err.stack) winston.debug(err.stack);
await axeRunner.close();
throw new Error(err);
});
};