-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
1637 lines (1637 loc) · 61.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
index.js
autotest main script.
*/
// ########## IMPORTS
// Module to access files.
const fs = require('fs/promises');
// Module to keep secrets local.
require('dotenv').config();
// Module to create an HTTP server and client.
const http = require('http');
// Module to create an HTTPS server and client.
const https = require('https');
// Requirements for commands.
const {commands} = require('./commands');
// ########## CONSTANTS
// Set debug to true to add debugging features.
const debug = false;
// Set waits to a positive number to insert delays (in ms).
const waits = 0;
const protocol = process.env.PROTOCOL || 'https';
// Files servable without modification.
const statics = {
'/index.html': 'text/html',
'/style.css': 'text/css'
};
// URLs to be redirected.
const redirects = {
'/': '/autotest/index.html',
'/which.html': '/autotest/run.html'
};
// Pages to be served as error notifications.
const customErrorPageStart = [
'<html lang="en-US">',
' <head>',
' <meta charset="utf-8">',
' <title>ERROR</title>',
' </head>',
' <body><main>',
' <h1>ERROR</h1>',
' <p>__msg__</p>'
];
const systemErrorPageStart = customErrorPageStart.concat(...[
' <p>Location:</p>',
' <pre>__stack__</pre>'
]);
const errorPageEnd = [
' </main></body>',
'</html>',
''
];
const customErrorPage = customErrorPageStart.concat(...errorPageEnd);
const systemErrorPage = systemErrorPageStart.concat(...errorPageEnd);
// CSS selectors for targets of moves.
const moves = {
button: 'button',
checkbox: 'input[type=checkbox]',
focus: true,
link: 'a',
radio: 'input[type=radio]',
select: 'select',
text: 'input[type=text]'
};
// Names and descriptions of tests.
const tests = {
aatt: 'AATT with HTML CodeSniffer WCAG 2.1 AA ruleset',
alfa: 'alfa',
autocom: 'autocomplete attributes of inputs',
axe: 'Axe',
bodyText: 'text content of the page body',
bulk: 'count of visible elements',
embAc: 'active elements embedded in links or buttons',
focAll: 'focusable and Tab-focused elements',
focInd: 'focus indicators',
focOp: 'focusability and operability',
hover: 'hover-caused content additions',
ibm: 'IBM Accessibility Checker',
imgAlt: 'alt attributes of img elements',
imgBg: 'background images and their texts',
imgDec: 'decorative images and their texts',
imgInf: 'informative images and their texts',
inLab: 'input labels',
labClash: 'labeling inconsistencies',
linkUl: 'inline-link underlining',
menuNav: 'keyboard navigation between focusable menu items',
motion: 'motion',
radioSet: 'fieldset grouping of radio buttons',
roleList: 'role attributes',
role: 'roles',
simple: 'nothing',
state: 'focus and hover states',
styleDiff: 'style inconsistencies',
tabNav: 'keyboard navigation between tab elements',
tblAc: 'active elements contained by tables',
visibles: 'visible elements',
wave: 'WAVE',
zIndex: 'z indexes'
};
// Tests that may change the DOM.
const domChangers = new Set([
'axe', 'focAll', 'focInd', 'focOp', 'hover', 'ibm', 'menuNav', 'state', 'wave'
]);
// Browser types available in PlayWright.
const browserTypeNames = {
'chromium': 'Chrome',
'webkit': 'Safari',
'firefox': 'Firefox'
};
// Items that may be waited for.
const waitables = ['url', 'title', 'body'];
// ########## VARIABLES
// Facts about the current session.
let logCount = 0;
let logSize = 0;
let prohibitedCount = 0;
let visitTimeoutCount = 0;
let visitRejectionCount = 0;
let actCount = 0;
// Facts about the current browser.
let browserContext;
let browserTypeName;
let requestedURL = '';
// ########## FUNCTIONS
// Serves a redirection.
const redirect = (url, response) => {
response.statusCode = 303;
response.setHeader('Location', url);
response.end();
};
// Closes any existing browser.
const closeBrowser = async () => {
const browser = browserContext && browserContext.browser();
if (browser) {
await browser.close();
}
};
// Launches a browser.
const launch = async typeName => {
const browserType = require('playwright')[typeName];
// If the specified browser type exists:
if (browserType) {
// Close any existing browser.
await closeBrowser();
// Launch a browser of the specified type.
const browserOptions = {};
if (debug) {
browserOptions.headless = false;
}
if (waits) {
browserOptions.slowMo = waits;
}
const browser = await browserType.launch(browserOptions);
// Create a new context (window) in it, taller if debugging is on.
const viewport = debug ? {
viewPort: {
width: 1280,
height: 1120
}
} : {};
browserContext = await browser.newContext(viewport);
// When a page is added to the browser context:
browserContext.on('page', page => {
// Make its console messages appear in the Playwright console.
page.on('console', msg => {
const msgText = msg.text();
console.log(msgText);
logCount++;
logSize += msgText.length;
const msgLC = msgText.toLowerCase();
if (msgText.includes('403') && (msgLC.includes('status') || msgLC.includes('prohibited'))) {
prohibitedCount++;
}
});
});
// Open the first page of the context.
const page = await browserContext.newPage();
if (debug) {
page.setViewportSize({
width: 1280,
height: 1120
});
}
// Wait until it is stable.
await page.waitForLoadState('domcontentloaded');
// Update the name of the current browser type and store it in the page.
page.browserTypeName = browserTypeName = typeName;
}
};
// Serves a system error message.
const serveError = (error, response) => {
if (response.writableEnded) {
console.log(error.message);
console.log(error.stack);
}
else {
response.statusCode = 400;
response.write(
systemErrorPage
.join('\n')
.replace('__msg__', error.message)
.replace('__stack__', error.stack)
);
response.end();
}
return '';
};
// Serves a custom error message.
const serveMessage = (msg, response) => {
if (response.writableEnded) {
console.log(msg);
}
else {
response.statusCode = 400;
response.write(customErrorPage.join('\n').replace('__msg__', msg));
response.end();
}
return '';
};
// Serves a page.
const servePage = (content, newURL, mimeType, response) => {
response.setHeader('Content-Type', `${mimeType}; charset=UTF-8`);
if (newURL) {
response.setHeader('Content-Location', newURL);
}
response.end(content);
};
// Serves or returns part or all of an HTML or plain-text page.
const render = (path, stage, which, query, response) => {
if (! response.writableEnded) {
// If an HTML page is to be rendered:
if (['all', 'raw'].includes(stage)) {
// Get the page.
return fs.readFile(`./${path}/${which}.html`, 'utf8')
.then(
// When it arrives:
page => {
// Replace its placeholders with eponymous query parameters.
const renderedPage = page.replace(/__([a-zA-Z]+)__/g, (ph, qp) => query[qp]);
// If the page is ready to serve in its entirety:
if (stage === 'all') {
// Serve it.
servePage(renderedPage, `/${path}-out.html`, 'text/html', response);
return '';
}
// Otherwise, i.e. if the page needs modification before it is served:
else {
return renderedPage;
}
},
error => serveError(new Error(error), response)
);
}
// Otherwise, if a plain-text page is ready to start:
else if (stage === 'start') {
// Serve its start.
response.setHeader('Content-Type', 'text/plain; charset=UTF-8');
// Set headers to tell the browser to render content chunks as they arrive.
response.setHeader('Transfer-Encoding', 'chunked');
response.setHeader('X-Content-Type-Options', 'nosniff');
if (path) {
response.setHeader('Content-Location', `/${path}-out.txt`);
}
response.write(`Report timestamp: ${query.timeStamp}\n\nProcessed URL 0\n`);
return '';
}
// Otherwise, if a plain-text page is ready to continue:
else if (stage === 'more') {
// Serve its continuation.
response.write(`Processed URL ${query.hostIndex}\n`);
return '';
}
// Otherwise, if a plain-text page is ready to end:
else if (stage === 'end') {
// Serve its end.
response.end(`Processed URL ${query.hostIndex}\n`);
return '';
}
else {
serveError('ERROR: Invalid stage', response);
}
}
};
// Normalizes spacing characters and cases in a string.
const debloat = string => string.replace(/\s/g, ' ').trim().replace(/ {2,}/g, ' ').toLowerCase();
// Returns the text of an element, lower-cased.
const textOf = async (page, element) => {
if (element) {
const tagNameJSHandle = await element.getProperty('tagName');
const tagName = await tagNameJSHandle.jsonValue();
let totalText = '';
// If the element is a link, button, input, or select list:
if (['A', 'BUTTON', 'INPUT', 'SELECT'].includes(tagName)) {
// Return its visible labels, descriptions, and legend if the first input in a fieldset.
totalText = await page.evaluate(element => {
const {tagName} = element;
const ownText = ['A', 'BUTTON'].includes(tagName) ? element.textContent : '';
// HTML link elements have no labels property.
const labels = tagName !== 'A' ? Array.from(element.labels) : [];
const labelTexts = labels.map(label => label.textContent);
const refIDs = new Set([
element.getAttribute('aria-labelledby') || '',
element.getAttribute('aria-describedby') || ''
].join(' ').split(/\s+/));
if (refIDs.size) {
refIDs.forEach(id => {
const labeler = document.getElementById(id);
if (labeler) {
const labelerText = labeler.textContent.trim();
if (labelerText.length) {
labelTexts.push(labelerText);
}
}
});
}
let legendText = '';
if (tagName === 'INPUT') {
const fieldsets = Array.from(document.body.querySelectorAll('fieldset'));
const inputFieldsets = fieldsets.filter(fieldset => {
const inputs = Array.from(fieldset.querySelectorAll('input'));
return inputs.length && inputs[0] === element;
});
const inputFieldset = inputFieldsets[0] || null;
if (inputFieldset) {
const legend = inputFieldset.querySelector('legend');
if (legend) {
legendText = legend.textContent;
}
}
}
return [legendText].concat(labelTexts, ownText).join(' ');
}, element);
}
// Otherwise, if it is an option:
else if (tagName === 'OPTION') {
// Return its text content, prefixed with the text of its select parent if the first option.
const ownText = await element.textContent();
const indexJSHandle = await element.getProperty('index');
const index = await indexJSHandle.jsonValue();
if (index) {
totalText = ownText;
}
else {
const selectJSHandle = await page.evaluateHandle(
element => element.parentElement, element
);
const select = await selectJSHandle.asElement();
if (select) {
const selectText = await textOf(page, select);
totalText = [ownText, selectText].join(' ');
}
else {
totalText = ownText;
}
}
}
// Otherwise, i.e. if it is not an input, select, or option:
else {
// Get its text content.
totalText = await element.textContent();
}
return debloat(totalText);
}
else {
return null;
}
};
// Returns an element case-insensitively matching a text.
const matchElement = async (page, selector, matchText, index = 0) => {
// If the page still exists:
if (page) {
// Wait 3 seconds until the body contains any text to be matched.
const slimText = debloat(matchText);
const bodyText = await page.textContent('body');
const slimBody = debloat(bodyText);
const textInBodyJSHandle = await page.waitForFunction(
args => {
const matchText = args[0];
const bodyText = args[1];
return ! matchText || bodyText.includes(matchText);
},
[slimText, slimBody],
{timeout: 2000}
)
.catch(async error => {
console.log(`ERROR: text to match not in body (${error.message})`);
});
// If there is no text to be matched or the body contained it:
if (textInBodyJSHandle) {
const lcText = matchText ? matchText.toLowerCase() : '';
// Identify the selected elements.
const selections = await page.$$(`body ${selector}`);
// If there are any:
if (selections.length) {
// If there are enough to make a match possible:
if (index < selections.length) {
// Return the nth one including any specified text, or the count of candidates if none.
const elementTexts = [];
let nth = 0;
for (const element of selections) {
const elementText = await textOf(page, element);
elementTexts.push(elementText);
if ((! lcText || elementText.includes(lcText)) && nth++ === index) {
return element;
}
}
return elementTexts;
}
// Otherwise, i.e. if there are too few to make a match possible:
else {
// Return the count of candidates.
return selections.length;
}
}
// Otherwise, i.e. if there are no selected elements, return 0.
else {
return 0;
}
}
// Otherwise, i.e. if the body did not contain it:
else {
// Return the failure.
return -1;
}
}
// Otherwise, i.e. if the page no longer exists:
else {
// Return null.
console.log('ERROR: Page gone');
return null;
}
};
// Validates a browser type.
const isBrowserType = type => ['chromium', 'firefox', 'webkit'].includes(type);
// Validates a load state.
const isState = string => ['loaded', 'idle'].includes(string);
// Validates a URL.
const isURL = string => /^(?:https?|file):\/\/[^\s]+$/.test(string);
// Validates a focusable tag name.
const isFocusable = string => ['a', 'button', 'input', 'select'].includes(string);
// Returns whether all elements of an array are strings.
const areStrings = array => array.every(element => typeof element === 'string');
// Returns whether a variable has a specified type.
const hasType = (variable, type) => {
if (type === 'string') {
return typeof variable === 'string';
}
else if (type === 'array') {
return Array.isArray(variable);
}
else if (type === 'boolean') {
return typeof variable === 'boolean';
}
else if (type === 'number') {
return typeof variable === 'number';
}
else {
return false;
}
};
// Returns whether a variable has a specified subtype.
const hasSubtype = (variable, subtype) => {
if (subtype) {
if (subtype === 'hasLength') {
return variable.length > 0;
}
else if (subtype === 'isURL') {
return isURL(variable);
}
else if (subtype === 'isBrowserType') {
return isBrowserType(variable);
}
else if (subtype === 'isFocusable') {
return isFocusable(variable);
}
else if (subtype === 'isTest') {
return tests[variable];
}
else if (subtype === 'isWaitable') {
return waitables.includes(variable);
}
else if (subtype === 'areStrings') {
return areStrings(variable);
}
else if (subtype === 'isState') {
return isState(variable);
}
else {
return false;
}
}
else {
return true;
}
};
// Validates a command.
const isValid = command => {
// Identify the type of the command.
const type = command.type;
// If the type exists and is known:
if (type && commands.etc[type]) {
// Copy the validator of the type for possible expansion.
const validator = Object.assign({}, commands.etc[type][1]);
// If the type is test:
if (type === 'test') {
// Identify the test.
const testName = command.which;
// If one was specified and is known:
if (testName && tests[testName]) {
// If it has special properties:
if (commands.tests[testName]) {
// Expand the validator by adding them.
Object.assign(validator, commands.tests[testName][1]);
}
}
// Otherwise, i.e. if no or an unknown test was specified:
else {
// Return invalidity.
return false;
}
}
// Return whether the command is valid.
return Object.keys(validator).every(property => {
if (property === 'name') {
return true;
}
else {
const vP = validator[property];
const cP = command[property];
// If it is optional and omitted or present and valid:
const optAndNone = ! vP[0] && ! cP;
const isValid = cP !== undefined && hasType(cP, vP[1]) && hasSubtype(cP, vP[2]);
return optAndNone || isValid;
}
});
}
// Otherwise, i.e. if the command has an unknown or no type:
else {
// Return invalidity.
return false;
}
};
// Returns a string with any final slash removed.
const deSlash = string => string.endsWith('/') ? string.slice(0, -1) : string;
// Tries to visit a URL.
const goto = async (page, url, timeout, waitUntil, isStrict) => {
const response = await page.goto(url, {
timeout,
waitUntil
})
.catch(error => {
console.log(`ERROR: Visit to ${url} timed out before ${waitUntil} (${error.message})`);
visitTimeoutCount++;
return 'error';
});
if (typeof response !== 'string') {
const httpStatus = response.status();
if ([200, 304].includes(httpStatus) || url.startsWith('file:')) {
const actualURL = page.url();
if (isStrict && deSlash(actualURL) !== deSlash(url)) {
console.log(`ERROR: Visit to ${url} redirected to ${actualURL}`);
return 'redirection';
}
else {
return response;
}
}
else {
console.log(`ERROR: Visit to ${url} got status ${httpStatus}`);
visitRejectionCount++;
return 'error';
}
}
else {
return 'error';
}
};
// Visits the URL that is the value of the “which” property of an act.
const visit = async (act, page, isStrict) => {
// Identify the URL.
const resolved = act.which.replace('__dirname', __dirname);
requestedURL = resolved;
// Visit it and wait 15 seconds or until the network is idle.
let response = await goto(page, requestedURL, 15000, 'networkidle', isStrict);
// If the visit fails:
if (response === 'error') {
// Try again, but waiting 10 seconds or until the DOM is loaded.
response = await goto(page, requestedURL, 10000, 'domcontentloaded', isStrict);
// If the visit fails:
if (response === 'error') {
// Launch another browser type.
const newBrowserName = Object.keys(browserTypeNames)
.find(name => name !== browserTypeName);
console.log(`>> Launching ${newBrowserName} instead`);
await launch(newBrowserName);
// Identify its only page as current.
page = browserContext.pages()[0];
// Try again, waiting 10 seconds or until the network is idle.
response = await goto(page, requestedURL, 10000, 'networkidle', isStrict);
// If the visit fails:
if (response === 'error') {
// Try again, but waiting 5 seconds or until the DOM is loaded.
response = await goto(page, requestedURL, 5000, 'domcontentloaded', isStrict);
// If the visit fails:
if (response === 'error') {
// Try again, waiting 5 seconds or until a load.
response = await goto(page, requestedURL, 5000, 'load', isStrict);
// If the visit fails:
if (response === 'error') {
// Give up.
console.log(`ERROR: Visits to ${requestedURL} failed`);
act.result = `ERROR: Visit to ${requestedURL} failed`;
await page.goto('about:blank')
.catch(error => {
console.log(`ERROR: Navigation to blank page failed (${error.message})`);
});
return null;
}
}
}
}
}
// If one of the visits succeeded:
if (response) {
// Add the resulting URL to the act.
if (isStrict && response === 'redirection') {
act.error = 'ERROR: Navigation redirected';
}
act.result = page.url();
// Return the page.
return page;
}
};
// Updates a report file.
const reportFileUpdate = async (reportDir, nameSuffix, report, isJSON) => {
const fileReport = isJSON ? report : JSON.stringify(report, null, 2);
await fs.writeFile(`${reportDir}/report-${nameSuffix}.json`, fileReport);
};
// Returns a property value and whether it satisfies a condition.
const isTrue = (object, specs) => {
let satisfied;
const property = specs[0];
const propertyTree = property.split('.');
const relation = specs[1];
const criterion = specs[2];
let actual = property.length ? object[propertyTree[0]] : object;
// Identify the actual value of the specified property.
while (propertyTree.length > 1 && actual !== undefined) {
propertyTree.shift();
actual = actual[propertyTree[0]];
}
// Determine whether the expectation was fulfilled.
if (relation === '=') {
satisfied = actual === criterion;
}
else if (relation === '<') {
satisfied = actual < criterion;
}
else if (relation === '>') {
satisfied = actual > criterion;
}
else if (relation === '!') {
satisfied = actual !== criterion;
}
else if (! relation) {
satisfied = actual === undefined;
}
return [actual, satisfied];
};
// Recursively performs the commands in a report.
const doActs = async (acts, report, actIndex, page, reportSuffix, reportDir) => {
// If any more commands are to be performed:
if (actIndex > -1 && actIndex < acts.length) {
// Identify the command to be performed.
const scriptAct = acts[actIndex];
const act = JSON.parse(JSON.stringify(scriptAct));
// If it is valid:
if (isValid(act)) {
const whichSuffix = act.which ? ` (${act.which})` : '';
console.log(`>>>> ${act.type}${whichSuffix}`);
// Copy it into the report.
report.acts.push(act);
// Increment the count of commands performed.
actCount++;
// If the command is an index changer:
if (act.type === 'next') {
const condition = act.if;
const logSuffix = condition.length === 3 ? ` ${condition[1]} ${condition[2]}` : '';
console.log(`>> ${condition[0]}${logSuffix}`);
// Identify the act to be checked.
const ifActIndex = report.acts.map(act => act.type !== 'next').lastIndexOf(true);
// Determine whether its jump condition is true.
const truth = isTrue(report.acts[ifActIndex].result, condition);
// Add the result to the act.
act.result = {
property: condition[0],
relation: condition[1],
criterion: condition[2],
value: truth[0],
jumpRequired: truth[1]
};
// If the condition is true:
if (truth[1]) {
// If the performance of commands is to stop:
if (act.jump === 0) {
// Set the command index to cause a stop.
actIndex = -2;
}
// Otherwise, if there is a numerical jump:
else if (act.jump) {
// Set the command index accordingly.
actIndex += act.jump - 1;
}
// Otherwise, if there is a named next command:
else if (act.next) {
// Set the new index accordingly, or stop if it does not exist.
actIndex = acts.map(act => act.name).indexOf(act.next) - 1;
}
}
}
// Otherwise, if the command is a launch:
else if (act.type === 'launch') {
// Launch the specified browser, creating a browser context and a page in it.
await launch(act.which);
// Identify its only page as current.
page = browserContext.pages()[0];
}
// Otherwise, if it is a score:
else if (act.type === 'score') {
// Compute and report the score.
try {
const {scorer} = require(`./procs/score/${act.which}`);
act.result = scorer(report.acts);
}
catch (error) {
act.error = `ERROR: ${error.message}\n${error.stack}`;
}
}
// Otherwise, if a current page exists:
else if (page) {
// If the command is a url:
if (act.type === 'url') {
// Visit it and wait until it is stable.
page = await visit(act, page, report.strict);
}
// Otherwise, if the act is a wait for text:
else if (act.type === 'wait') {
const {what, which} = act;
console.log(`>> for ${what} to include “${which}”`);
const waitError = (error, what) => {
console.log(`ERROR waiting for ${what} (${error.message})`);
act.result = {url: page.url()};
act.result.error = `ERROR waiting for ${what}`;
return false;
};
// Wait 5 seconds for the specified text to appear in the specified place.
let successJSHandle;
if (act.what === 'url') {
successJSHandle = await page.waitForFunction(
text => document.URL.includes(text), act.which, {timeout: 5000}
)
.catch(error => waitError(error, 'URL'));
}
else if (act.what === 'title') {
successJSHandle = await page.waitForFunction(
text => document.title.includes(text), act.which, {timeout: 5000}
)
.catch(error => waitError(error, 'title'));
}
else if (act.what === 'body') {
successJSHandle = await page.waitForFunction(
matchText => {
const innerText = document.body.innerText;
return innerText.includes(matchText);
}, which, {timeout: 5000}
)
.catch(error => waitError(error, 'body'));
}
if (successJSHandle) {
act.result = {url: page.url()};
if (act.what === 'title') {
act.result.title = await page.title();
}
await page.waitForLoadState('networkidle', {timeout: 10000})
.catch(error => {
console.log(`ERROR waiting for stability after ${act.what} (${error.message})`);
act.result.error = `ERROR waiting for stability after ${act.what}`;
});
}
}
// Otherwise, if the act is a wait for a state:
else if (act.type === 'state') {
// If the state is valid:
const stateIndex = ['loaded', 'idle'].indexOf(act.which);
if (stateIndex !== -1) {
// Wait for it.
await page.waitForLoadState(
['domcontentloaded', 'networkidle'][stateIndex], {timeout: [10000, 5000][stateIndex]}
)
.catch(error => {
console.log(`ERROR waiting for page to be ${act.which} (${error.message})`);
act.result = `ERROR waiting for page to be ${act.which}`;
});
}
else {
console.log('ERROR: invalid state');
act.result = 'ERROR: invalid state';
}
}
// Otherwise, if the act is a page switch:
else if (act.type === 'page') {
// Wait for a page to be created and identify it as current.
page = await browserContext.waitForEvent('page');
// Wait until it is stable and thus ready for the next act.
await page.waitForLoadState('networkidle', {timeout: 20000});
// Add the resulting URL and any description of it to the act.
const result = {
url: page.url()
};
act.result = result;
}
// Otherwise, if the page has a URL:
else if (page.url() && page.url() !== 'about:blank') {
const url = page.url();
// If redirection is permitted or did not occur:
if (! report.strict || deSlash(url) === deSlash(requestedURL)) {
// Add the URL to the act.
act.url = url;
// If the act is a revelation:
if (act.type === 'reveal') {
// Make all elements in the page visible.
await require('./procs/test/allVis').allVis(page);
act.result = 'All elements visible.';
}
// Otherwise, if it is a repetitive keyboard navigation:
else if (act.type === 'presses') {
const {navKey, what, which, withItems} = act;
const matchTexts = which ? which.map(text => debloat(text)) : [];
// Initialize the loop variables.
let status = 'more';
let presses = 0;
let amountRead = 0;
let items = [];
let matchedText;
// As long as a matching element has not been reached:
while (status === 'more') {
// Press the Escape key to dismiss any modal dialog.
await page.keyboard.press('Escape');
// Press the specified navigation key.
await page.keyboard.press(navKey);
presses++;
// Identify the newly current element or a failure.
const currentJSHandle = await page.evaluateHandle(actCount => {
// Initialize it as the focused element.
let currentElement = document.activeElement;
// If it exists in the page:
if (currentElement && currentElement.tagName !== 'BODY') {
// Change it, if necessary, to its active descendant.
if (currentElement.hasAttribute('aria-activedescendant')) {
currentElement = document.getElementById(
currentElement.getAttribute('aria-activedescendant')
);
}
// Or change it, if necessary, to its selected option.
else if (currentElement.tagName === 'SELECT') {
const currentIndex = Math.max(0, currentElement.selectedIndex);
const options = currentElement.querySelectorAll('option');
currentElement = options[currentIndex];
}
// Or change it, if necessary, to its active shadow-DOM element.
else if (currentElement.shadowRoot) {
currentElement = currentElement.shadowRoot.activeElement;
}
// If there is a current element:
if (currentElement) {
// If it was already reached within this command performance:
if (currentElement.dataset.pressesReached === actCount.toString(10)) {
// Report the error.
console.log(`ERROR: ${currentElement.tagName} element reached again`);
status = 'ERROR';
return 'ERROR: locallyExhausted';
}
// Otherwise, i.e. if it is newly reached within this act:
else {
// Mark and return it.
currentElement.dataset.pressesReached = actCount;
return currentElement;
}
}
// Otherwise, i.e. if there is no current element:
else {
// Report the error.
status = 'ERROR';
return 'noActiveElement';
}
}
// Otherwise, i.e. if there is no focus in the page:
else {
// Report the error.
status = 'ERROR';
return 'ERROR: globallyExhausted';
}
}, actCount);
// If the current element exists:
const currentElement = currentJSHandle.asElement();
if (currentElement) {
// Update the data.
const tagNameJSHandle = await currentElement.getProperty('tagName');
const tagName = await tagNameJSHandle.jsonValue();
const text = await textOf(page, currentElement);
// If the text of the current element was found:
if (text !== null) {
const textLength = text.length;
// If it is non-empty and there are texts to match:
if (matchTexts.length && textLength) {
// Identify the matching text.
matchedText = matchTexts.find(matchText => text.includes(matchText));
}
// Update the item data if required.
if (withItems) {
const itemData = {
tagName,
text,
textLength
};
if (matchedText) {
itemData.matchedText = matchedText;
}
items.push(itemData);
}
amountRead += textLength;
// If there is no text-match failure:
if (matchedText || ! matchTexts.length) {
// If the element has any specified tag name:
if (! what || tagName === what) {
// Change the status.
status = 'done';
// Perform the action.
const inputText = act.text;
if (inputText) {
await page.keyboard.type(inputText);
presses += inputText.length;
}
if (act.action) {
presses++;
await page.keyboard.press(act.action);
await page.waitForLoadState();
}
}
}
}
else {
status = 'ERROR';
}
}
// Otherwise, i.e. if there was a failure:
else {
// Update the status.
status = await currentJSHandle.jsonValue();
}
}
// Add the result to the act.
act.result = {
status,
totals: {
presses,
amountRead
}
};
if (status === 'done' && matchedText) {
act.result.matchedText = matchedText;
}
if (withItems) {
act.result.items = items;
}
// Add the totals to the report.
report.presses += presses;
report.amountRead += amountRead;
}
// Otherwise, if the act is a test:
else if (act.type === 'test') {
// Add a description of the test to the act.
act.what = tests[act.which];
// Initialize the arguments.
const args = [page];
// Identify the additional validator of the test.
const testValidator = commands.tests[act.which];
// If it exists:
if (testValidator) {
// Identify its argument properties.
const argProperties = Object.keys(testValidator[1]);
// Add their values to the arguments.
args.push(...argProperties.map(propName => act[propName]));
}
// Conduct, report, and time the test.
const startTime = Date.now();
const testReport = await require(`./tests/${act.which}`).reporter(...args);
const expectations = act.expect;
// If the test has expectations:
if (expectations) {
// Initialize whether they were fulfilled.