-
Notifications
You must be signed in to change notification settings - Fork 0
/
npmIndex.js
221 lines (192 loc) · 6.99 KB
/
npmIndex.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
import fs from 'fs';
import path from 'path';
import printMessage from 'print-message';
import { fileURLToPath } from 'url';
import constants from './constants/constants.js';
import {
deleteClonedProfiles,
getBrowserToRun,
getPlaywrightLaunchOptions,
submitForm
} from './constants/common.js'
import { createCrawleeSubFolders, filterAxeResults } from './crawlers/commonCrawlerFunc.js';
import {
createAndUpdateResultsFolders,
createDetailsAndLogs,
} from './utils.js';
import { generateArtifacts } from './mergeAxeResults.js';
import { takeScreenshotForHTMLElements } from './screenshotFunc/htmlScreenshotFunc.js';
import { silentLogger } from './logs.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export const init = async (
entryUrl,
testLabel,
name = "Your Name",
email = "[email protected]",
needsReview = false,
includeScreenshots = false,
viewportSettings = { width: 1000, height: 660 }, // cypress' default viewport settings
thresholds = {},
scanAboutMetadata = undefined,
) => {
console.log('Starting Purple HATS');
const [date, time] = new Date().toLocaleString('sv').replaceAll(/-|:/g, '').split(' ');
const domain = new URL(entryUrl).hostname;
const sanitisedLabel = testLabel
? `_${testLabel.replaceAll(' ', '_')}`
: '';
const randomToken = `${date}_${time}${sanitisedLabel}_${domain}`;
// max numbers of mustFix/goodToFix occurrences before test returns a fail
const {
mustFix: mustFixThreshold,
goodToFix: goodToFixThreshold,
} = thresholds;
process.env.CRAWLEE_STORAGE_DIR = randomToken;
const scanDetails = {
startTime: new Date().getTime(),
crawlType: 'Custom',
requestUrl: entryUrl,
urlsCrawled: { ...constants.urlsCrawledObj },
};
const urlsCrawled = { ...constants.urlsCrawledObj };
const { dataset } = await createCrawleeSubFolders(randomToken);
let mustFixIssues = 0;
let goodToFixIssues = 0;
let isInstanceTerminated = false;
let numPagesScanned = 0;
const throwErrorIfTerminated = () => {
if (isInstanceTerminated) {
throw new Error('This instance of Purple HATS was terminated. Please start a new instance.');
}
};
const getScripts = () => {
throwErrorIfTerminated();
const axeScript = fs.readFileSync(
path.join(__dirname, 'node_modules/axe-core/axe.min.js'),
'utf-8',
);
async function runA11yScan(elementsToScan = []) {
axe.configure({
branding: {
application: 'purple-hats',
},
});
const axeScanResults = await axe.run(elementsToScan, {
resultTypes: ['violations', 'passes', 'incomplete'],
});
return {
pageUrl: window.location.href,
pageTitle: document.title,
axeScanResults,
};
}
return `${axeScript} ${runA11yScan.toString()}`;
};
const pushScanResults = async (res, metadata, elementsToClick) => {
throwErrorIfTerminated();
if (includeScreenshots) {
// use chrome by default
const { browserToRun, clonedBrowserDataDir } = getBrowserToRun(constants.browserTypes.chrome);
const browserContext = await constants.launcher.launchPersistentContext(
clonedBrowserDataDir,
{ viewport: scanAboutMetadata.viewport,
...getPlaywrightLaunchOptions(browserToRun)}
);
const page = await browserContext.newPage();
await page.goto(res.pageUrl);
await page.waitForLoadState('networkidle');
// click on elements to reveal hidden elements so screenshots can be taken
elementsToClick?.forEach(async elem => {
try {
await page.locator(elem).click()
} catch (e) {
silentLogger.info(e);
}
});
res.axeScanResults.violations = await takeScreenshotForHTMLElements(res.axeScanResults.violations, page, randomToken, 3000);
if (needsReview) res.axeScanResults.incomplete = await takeScreenshotForHTMLElements(res.axeScanResults.incomplete, page, randomToken, 3000);
await browserContext.close();
deleteClonedProfiles(browserToRun);
}
const pageIndex = urlsCrawled.scanned.length + 1;
const filteredResults = filterAxeResults(needsReview, res.axeScanResults, res.pageTitle, { pageIndex , metadata });
urlsCrawled.scanned.push({ url: res.pageUrl, pageTitle: `${pageIndex}: ${res.pageTitle}` });
mustFixIssues += filteredResults.mustFix ? filteredResults.mustFix.totalItems : 0;
goodToFixIssues += filteredResults.goodToFix ? filteredResults.goodToFix.totalItems : 0;
await dataset.pushData(filteredResults);
// return counts for users to perform custom assertions if needed
return {
mustFix: filteredResults.mustFix ? filteredResults.mustFix.totalItems : 0,
goodToFix: filteredResults.goodToFix ? filteredResults.goodToFix.totalItems : 0,
};
};
const testThresholdsAndReset = () => {
// check against thresholds to fail tests
let isThresholdExceeded = false;
let thresholdFailMessage = "Exceeded thresholds:\n";
if (mustFixThreshold !== undefined && mustFixIssues > mustFixThreshold) {
isThresholdExceeded = true;
thresholdFailMessage += `mustFix occurrences found: ${mustFixIssues} > ${mustFixThreshold}\n`;
}
if (goodToFixThreshold !== undefined && goodToFixIssues > goodToFixThreshold) {
isThresholdExceeded = true;
thresholdFailMessage += `goodToFix occurrences found: ${goodToFixIssues} > ${goodToFixThreshold}\n`;
}
// reset counts
mustFixIssues = 0;
goodToFixIssues = 0;
if (isThresholdExceeded) {
throw new Error(thresholdFailMessage);
}
};
const terminate = async () => {
throwErrorIfTerminated();
console.log('Stopping Purple HATS');
isInstanceTerminated = true;
scanDetails.endTime = new Date().getTime();
scanDetails.urlsCrawled = urlsCrawled;
if (urlsCrawled.scanned.length === 0) {
printMessage([`No pages were scanned.`], constants.alertMessageOptions);
} else {
await createDetailsAndLogs(scanDetails, randomToken);
await createAndUpdateResultsFolders(randomToken);
const pagesNotScanned = [...scanDetails.urlsCrawled.error, ...scanDetails.urlsCrawled.invalid];
scanAboutMetadata = {
viewport: `${viewportSettings.width} x ${viewportSettings.height}`,
...scanAboutMetadata
};
const basicFormHTMLSnippet = await generateArtifacts(
randomToken,
scanDetails.requestUrl,
scanDetails.crawlType,
null,
scanDetails.urlsCrawled.scanned,
pagesNotScanned,
testLabel,
scanAboutMetadata
);
await submitForm(
constants.browserTypes.chromium,
'',
scanDetails.requestUrl,
scanDetails.crawlType,
email,
name,
JSON.stringify(basicFormHTMLSnippet),
urlsCrawled.scanned.length,
"{}",
);
}
return null;
};
return {
getScripts,
pushScanResults,
terminate,
scanDetails,
randomToken,
testThresholdsAndReset,
};
};
export default init