forked from cvs-health/testaro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.js
1617 lines (1603 loc) · 59.7 KB
/
run.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
/*
© 2021–2023 CVS Health and/or one of its affiliates. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
run.js
Testaro main utility module.
*/
// ########## IMPORTS
// Module to keep secrets.
require('dotenv').config();
// Requirements for acts.
const {actSpecs} = require('./actSpecs');
// Module to standardize report formats.
const {standardize} = require('./procs/standardize');
// Module to send a notice to an observer.
const {tellServer} = require('./procs/tellServer');
// ########## CONSTANTS
// Set DEBUG environment variable to 'true' to add debugging features.
const debug = process.env.DEBUG === 'true';
// Set WAITS environment variable to a positive number to insert delays (in ms).
const waits = Number.parseInt(process.env.WAITS) || 0;
// CSS selectors for targets of moves.
const moves = {
button: 'button, [role=button], input[type=submit]',
checkbox: 'input[type=checkbox]',
focus: true,
link: 'a, [role=link]',
radio: 'input[type=radio]',
search: 'input[type=search], input[aria-label*=search i], input[placeholder*=search i]',
select: 'select',
text: 'input'
};
// Names and descriptions of tools.
const tools = {
alfa: 'alfa',
aslint: 'ASLint',
axe: 'Axe',
ed11y: 'Editoria11y',
htmlcs: 'HTML CodeSniffer WCAG 2.1 AA ruleset',
ibm: 'IBM Accessibility Checker',
nuVal: 'Nu Html Checker',
qualWeb: 'QualWeb',
testaro: 'Testaro',
wave: 'WAVE',
};
// Strings in log messages indicating errors.
const errorWords = [
'but not used',
'content security policy',
'deprecated',
'error',
'exception',
'expected',
'failed',
'invalid',
'missing',
'non-standard',
'not supported',
'refused',
'requires',
'sorry',
'suspicious',
'unrecognized',
'violates',
'warning'
];
// ########## VARIABLES
// Facts about the current session.
let actCount = 0;
// Facts about the current browser.
let browser;
let browserContext;
let currentPage;
let requestedURL = '';
// ########## VALIDATORS
// 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 numbers.
const areNumbers = array => array.every(element => typeof element === 'number');
// Returns whether all elements of an array are strings.
const areStrings = array => array.every(element => typeof element === 'string');
// Returns whether all properties of an object have array values.
const areArrays = object => Object.values(object).every(value => Array.isArray(value));
// 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 if (type === 'object') {
return typeof variable === 'object' && ! Array.isArray(variable);
}
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 tools[variable];
}
else if (subtype === 'isWaitable') {
return ['url', 'title', 'body'].includes(variable);
}
else if (subtype === 'areNumbers') {
return areNumbers(variable);
}
else if (subtype === 'areStrings') {
return areStrings(variable);
}
else if (subtype === 'areArrays') {
return areArrays(variable);
}
else if (subtype === 'isState') {
return isState(variable);
}
else {
console.log(`ERROR: ${subtype} not a known subtype`);
return false;
}
}
else {
return true;
}
};
// Validates an act.
const isValidAct = act => {
// Identify the type of the act.
const type = act.type;
// If the type exists and is known:
if (type && actSpecs.etc[type]) {
// Copy the validator of the type for possible expansion.
const validator = Object.assign({}, actSpecs.etc[type][1]);
// If the type is test:
if (type === 'test') {
// Identify the test.
const toolName = act.which;
// If one was specified and is known:
if (toolName && tools[toolName]) {
// If it has special properties:
if (actSpecs.tools[toolName]) {
// Expand the validator by adding them.
Object.assign(validator, actSpecs.tools[toolName][1]);
}
}
// Otherwise, i.e. if no or an unknown test was specified:
else {
// Return invalidity.
return false;
}
}
// Return whether the act is valid.
return Object.keys(validator).every(property => {
if (property === 'name') {
return true;
}
else {
const vP = validator[property];
const aP = act[property];
// If it is optional and omitted or is present and valid:
const optAndNone = ! vP[0] && ! aP;
const isValidAct = aP !== undefined && hasType(aP, vP[1]) && hasSubtype(aP, vP[2]);
return optAndNone || isValidAct;
}
});
}
// Otherwise, i.e. if the act has an unknown or no type:
else {
// Return invalidity.
return false;
}
};
// Validates a report object.
const isValidReport = report => {
if (report) {
// Return whether the report is valid.
const {id, what, strict, timeLimit, acts, sources, creationTime, timeStamp} = report;
if (! id || typeof id !== 'string') {
return 'Bad report ID';
}
if (! what || typeof what !== 'string') {
return 'Bad report what';
}
if (typeof strict !== 'boolean') {
return 'Bad report strict';
}
if (typeof timeLimit !== 'number' || timeLimit < 1) {
return 'Bad report time limit';
}
if (! acts || ! Array.isArray(acts) || ! acts.length) {
return 'Bad report acts';
}
if (! acts.every(act => act.type && typeof act.type === 'string')) {
return 'Act with no type';
}
if (acts[0].type !== 'launch') {
return 'First act type not launch';
}
if (! ['chromium', 'webkit', 'firefox'].includes(acts[0].which)) {
return 'Bad first act which';
}
if (acts[0].type !== 'launch' || (
(
! acts[0].url
|| typeof acts[0].url !== 'string'
|| ! isURL(acts[0].url)
)
&& (
acts[1].type !== 'url'
|| ! acts[1].which
|| typeof acts[1].which !== 'string'
|| ! isURL(acts[1].which)
)
)) {
return 'First or second act has no valid URL';
}
const invalidAct = acts.find(act => ! isValidAct(act));
if (invalidAct) {
return `Invalid act:\n${JSON.stringify(invalidAct, null, 2)}`;
}
if (! sources || typeof sources !== 'object') {
return 'Bad report sources';
}
if (typeof sources.script !== 'string') {
return 'Bad source script';
}
if (! (creationTime && typeof creationTime === 'string' && Date.parse(creationTime))) {
return 'bad job creation time';
}
if (! (timeStamp && typeof timeStamp === 'string')) {
return 'bad report timestamp';
}
return '';
}
else {
return 'no report';
}
};
// ########## OTHER FUNCTIONS
// Returns a string with any final slash removed.
const deSlash = string => string.endsWith('/') ? string.slice(0, -1) : string;
// Gets the script nonce from a response.
const getNonce = async response => {
let nonce = '';
// If the response includes a content security policy:
const headers = await response.allHeaders();
const cspWithQuotes = headers && headers['content-security-policy'];
if (cspWithQuotes) {
// If it requires scripts to have a nonce:
const csp = cspWithQuotes.replace(/'/g, '');
const directives = csp.split(/ *; */).map(directive => directive.split(/ +/));
const scriptDirective = directives.find(dir => dir[0] === 'script-src');
if (scriptDirective) {
const nonceSpec = scriptDirective.find(valPart => valPart.startsWith('nonce-'));
if (nonceSpec) {
// Return the nonce.
nonce = nonceSpec.replace(/^nonce-/, '');
}
}
}
// Return the nonce, if any.
return nonce;
};
// Visits a URL and returns the response of the server.
const goTo = async (report, page, url, timeout, waitUntil) => {
// If the URL is a file path:
if (url.startsWith('file://')) {
// Make it absolute.
url = url.replace('file://', `file://${__dirname}/`);
}
// Visit the URL.
const startTime = Date.now();
try {
const response = await page.goto(url, {
timeout,
waitUntil
});
report.jobData.visitLatency += Math.round((Date.now() - startTime) / 1000);
const httpStatus = response.status();
// If the response status was normal:
if ([200, 304].includes(httpStatus) || url.startsWith('file:')) {
// If the browser was redirected in violation of a strictness requirement:
const actualURL = page.url();
if (report.strict && deSlash(actualURL) !== deSlash(url)) {
// Return an error.
console.log(`ERROR: Visit to ${url} redirected to ${actualURL}`);
return {
exception: 'badRedirection'
};
}
// Otherwise, i.e. if no prohibited redirection occurred:
else {
// Press the Escape key to dismiss any modal dialog.
await page.keyboard.press('Escape');
// Return the result of the navigation.
return {
success: true,
response
};
}
}
// Otherwise, i.e. if the response status was abnormal:
else {
// Return an error.
console.log(`ERROR: Visit to ${url} got status ${httpStatus}`);
report.jobData.visitRejectionCount++;
return {
success: false,
error: 'badStatus'
};
}
}
catch(error) {
console.log(`ERROR visiting ${url} (${error.message.slice(0, 200)})`);
return {
success: false,
error: 'noVisit'
};
}
};
// Closes the current browser.
const browserClose = async () => {
if (browser) {
let contexts = browser.contexts();
for (const context of contexts) {
await context.close();
contexts = browser.contexts();
}
await browser.close();
browser = null;
}
};
// Launches a browser, navigates to a URL, and returns browser data.
const launch = async (report, typeName, url, debug, waits, isLowMotion = false) => {
// If the specified browser type exists:
const browserType = require('playwright')[typeName];
if (browserType) {
// Close the current browser, if any.
await browserClose();
// Launch a browser of the specified type.
const browserOptions = {
logger: {
isEnabled: () => false,
log: (name, severity, message) => console.log(message.slice(0, 100))
}
};
if (debug) {
browserOptions.headless = false;
}
if (waits) {
browserOptions.slowMo = waits;
}
browser = await browserType.launch(browserOptions)
// If the launch failed:
.catch(async error => {
console.log(`ERROR launching browser (${error.message.slice(0, 200)})`);
// Return this.
return {
success: false,
error: 'Browser launch failed'
};
});
// Open a context (i.e. browser tab), with reduced motion if specified.
const options = {reduceMotion: isLowMotion ? 'reduce' : 'no-preference'};
const browserContext = await browser.newContext(options);
// Prevent default timeouts.
browserContext.setDefaultTimeout(0);
// When a page (i.e. browser tab) is added to the browser context (i.e. browser window):
browserContext.on('page', async page => {
// Ensure the report has a jobData property.
report.jobData ??= {};
report.jobData.logCount ??= 0;
report.jobData.logSize ??= 0;
report.jobData.errorLogCount ??= 0;
// Add any error events to the count of logging errors.
page.on('crash', () => {
report.jobData.errorLogCount++;
console.log('Page crashed');
});
page.on('pageerror', () => {
report.jobData.errorLogCount++;
});
page.on('requestfailed', () => {
report.jobData.errorLogCount++;
});
// If the page emits a message:
page.on('console', msg => {
const msgText = msg.text();
let indentedMsg = '';
// If debugging is on:
if (debug) {
// Log a summary of the message on the console.
const parts = [msgText.slice(0, 75)];
if (msgText.length > 75) {
parts.push(msgText.slice(75, 150));
if (msgText.length > 150) {
const tail = msgText.slice(150).slice(-150);
if (msgText.length > 300) {
parts.push('...');
}
parts.push(tail.slice(0, 75));
if (tail.length > 75) {
parts.push(tail.slice(75));
}
}
}
indentedMsg = parts.map(part => ` | ${part}`).join('\n');
console.log(`\n${indentedMsg}`);
}
// Add statistics on the message to the report.
const msgTextLC = msgText.toLowerCase();
const msgLength = msgText.length;
report.jobData.logCount++;
report.jobData.logSize += msgLength;
if (errorWords.some(word => msgTextLC.includes(word))) {
report.jobData.errorLogCount++;
report.jobData.errorLogSize += msgLength;
}
const msgLC = msgText.toLowerCase();
if (
msgText.includes('403') && (msgLC.includes('status')
|| msgLC.includes('prohibited'))
) {
report.jobData.prohibitedCount++;
}
});
});
// Open the first page of the context.
const page = await browserContext.newPage();
try {
// Wait until it is stable.
await page.waitForLoadState('domcontentloaded', {timeout: 5000});
// Navigate to the specified URL.
const navResult = await goTo(report, page, url, 15000, 'domcontentloaded');
// If the navigation succeeded:
if (navResult.success) {
// Update the name of the current browser type and store it in the page.
page.browserTypeName = typeName;
// Return the response of the target server, the browser context, and the page.
return {
success: true,
response: navResult.response,
browserContext,
page
};
}
// Otherwise, if the navigation failed:
else if (navResult.error) {
// Return this.
return {
success: false,
error: 'Navigation failed'
};
}
}
// If it fails to become stable after load:
catch(error) {
// Return this.
console.log(`ERROR: Blank page load in new tab timed out (${error.message})`);
return {
success: false,
error: 'Blank page load in new tab timed out'
};
}
}
// Otherwise, i.e. if it does not exist:
else {
// Return this.
console.log(`ERROR: Browser of type ${typeName} could not be launched`);
return {
success: false,
error: `${typeName} browser launch failed`
};
}
};
// Returns a string representing the date and time.
const nowString = () => (new Date()).toISOString().slice(0, 19);
// Returns the first line of an error message.
const errorStart = error => error.message.replace(/\n.+/s, '');
// 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, ariaLabel} = element;
let ownText = '';
if (['A', 'BUTTON'].includes(tagName)) {
ownText = element.textContent;
}
else if (tagName === 'INPUT' && element.type === 'submit') {
ownText = element.value;
}
// HTML link elements have no labels property.
const labels = tagName !== 'A' ? Array.from(element.labels) : [];
const labelTexts = labels.map(label => label.textContent);
if (ariaLabel) {
labelTexts.push(ariaLabel);
}
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 a property value and whether it satisfies an expectation.
const isTrue = (object, specs) => {
const property = specs[0];
const propertyTree = property.split('.');
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]];
}
// If the expectation is that the property does not exist:
if (specs.length === 1) {
// Return whether the expectation is satisfied.
return [actual, actual === undefined];
}
// Otherwise, i.e. if the expectation is of a property value:
else if (specs.length === 3) {
// Return whether the expectation was fulfilled.
const relation = specs[1];
const criterion = specs[2];
let satisfied;
if (actual === undefined) {
return [null, false];
}
else 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 === 'i') {
satisfied = typeof actual === 'string' && actual.includes(criterion);
}
else if (relation === '!i') {
satisfied = typeof actual === 'string' && ! actual.includes(criterion);
}
else if (relation === 'e') {
satisfied = typeof actual === 'object'
&& JSON.stringify(actual) === JSON.stringify(criterion);
}
return [actual, satisfied];
}
// Otherwise, i.e. if the specifications are invalid:
else {
// Return this.
return [null, false];
}
};
// Adds a wait error result to an act.
const waitError = (page, act, error, what) => {
console.log(`ERROR waiting for ${what} (${error.message})`);
act.result.found = false;
act.result.url = page.url();
act.result.error = `ERROR waiting for ${what}`;
return false;
};
// Waits.
const wait = ms => {
return new Promise(resolve => {
setTimeout(() => {
resolve('');
}, ms);
});
};
// Reports a job being aborted and returns an abortive act index.
const abortActs = async (report, actIndex) => {
// Add data on the aborted act to the report.
report.jobData.abortTime = nowString();
report.jobData.abortedAct = actIndex;
report.jobData.aborted = true;
// Report the job being aborted.
console.log('ERROR: Job aborted');
// Return an abortive act index.
return -2;
};
// Adds an error result to an act.
const addError = async(alsoLog, alsoAbort, report, actIndex, message) => {
// If the error is to be logged:
if (alsoLog) {
// Log it.
console.log(message);
}
// Add error data to the result.
const act = report.acts[actIndex];
act.result ??= {};
act.result.success ??= false;
act.result.error ??= message;
if (act.type === 'test') {
act.data.success = false;
act.data.prevented = true;
act.data.error = message;
// Add prevention data to the job data.
report.jobData.preventions[act.which] = message;
}
// If the job is to be aborted:
if (alsoAbort) {
console.log(`report:\n${JSON.stringify(report, null, 2)}`);
// Return an abortive act index.
return await abortActs(report, actIndex);
}
// Otherwise, i.e. if the job is not to be aborted:
else {
// Return the current act index.
return actIndex;
}
};
// Recursively performs the acts in a report.
const doActs = async (report, actIndex, page) => {
// FUNCTION DEFINITION START
// Quits and reports the job being aborted.
const abortActs = async () => {
// Add data on the aborted act to the report.
report.jobData.abortTime = nowString();
report.jobData.abortedAct = actIndex;
report.jobData.aborted = true;
// Prevent performance of additional acts.
actIndex = -2;
// Report this.
console.log('ERROR: Job aborted');
};
// FUNCTION DEFINITION END
const {acts} = report;
// If any more acts are to be performed:
if (actIndex > -1 && actIndex < acts.length) {
// Identify the act to be performed.
const act = acts[actIndex];
// If it is valid:
if (isValidAct(act)) {
let actInfo = '';
if (act.which) {
if (act.type === 'launch' && act.url) {
actInfo = `${act.which} to ${act.url}`;
}
else {
actInfo = act.which;
}
}
const message = `>>>> ${act.type}: ${actInfo}`;
// If granular reporting has been specified:
if (report.observe) {
// Notify the observer of the act and log it.
const whichParam = act.which ? `&which=${act.which}` : '';
const messageParams = `act=${act.type}${whichParam}`;
tellServer(report, messageParams, message);
}
// Otherwise, i.e. if granular reporting has not been specified:
else {
// Log the act.
console.log(message);
}
// Increment the count of acts performed.
actCount++;
act.startTime = Date.now();
// If the act 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 acts is to stop:
if (act.jump === 0) {
// Quit.
actIndex = -2;
}
// Otherwise, if there is a numerical jump:
else if (act.jump) {
// Set the act index accordingly.
actIndex += act.jump - 1;
}
// Otherwise, if there is a named next act:
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 act is a launch:
else if (act.type === 'launch') {
// Launch the specified browser and navigate to the specified URL.
const launchResult = await launch(
report, act.which, act.url, debug, waits, act.lowMotion ? 'reduce' : 'no-preference'
);
// If the launch and navigation succeeded:
if (launchResult && launchResult.success) {
// Get the response of the target server.
const {response} = launchResult;
// Get the target page.
page = launchResult.page;
// Add the actual URL to the act.
act.actualURL = page.url();
// Add the script nonce, if any, to the act.
const scriptNonce = await getNonce(response);
if (scriptNonce) {
report.jobData.lastScriptNonce = scriptNonce;
}
}
// Otherwise, i.e. if the launch or navigation failed:
else {
// Add an error result to the act and abort the job.
actIndex = await addError(
true, true, report, actIndex, `ERROR: Launch failed (${launchResult.error})`
);
}
}
// Otherwise, if a current page exists:
else if (page) {
// If the act is navigation to a url:
if (act.type === 'url') {
// Identify the URL.
const resolved = act.which.replace('__dirname', __dirname);
requestedURL = resolved;
// Visit it and wait until the DOM is loaded.
const navResult = await goTo(report, page, requestedURL, 15000, 'domcontentloaded');
// If the visit succeeded:
if (navResult.success) {
// Add the script nonce, if any, to the act.
const {response} = navResult;
const scriptNonce = getNonce(response);
if (scriptNonce) {
report.jobData.lastScriptNonce = scriptNonce;
}
// Add the resulting URL to the act.
if (! act.result) {
act.result = {};
}
act.result.url = page.url();
// If a prohibited redirection occurred:
if (response.exception === 'badRedirection') {
// Report this and abort the job.
actIndex = await addError(
true, true, report, actIndex, 'ERROR: Navigation illicitly redirected'
);
}
}
// Otherwise, i.e. if the visit failed:
else {
// Report this and abort the job.
actIndex = await addError(true, true, report, actIndex, 'ERROR: Visit failed');
}
}
// Otherwise, if the act is a wait for text:
else if (act.type === 'wait') {
const {what, which} = act;
console.log(`>> ${what}`);
const result = act.result = {};
// If the text is to be the URL:
if (what === 'url') {
// Wait for the URL to be the exact text.
try {
await page.waitForURL(which, {timeout: 15000});
result.found = true;
result.url = page.url();
}
// If the wait times out:
catch(error) {
// Quit.
await abortActs();
waitError(page, act, error, 'text in the URL');
}
}
// Otherwise, if the text is to be a substring of the page title:
else if (what === 'title') {
// Wait for the page title to include the text, case-insensitively.
try {
await page.waitForFunction(
text => document
&& document.title
&& document.title.toLowerCase().includes(text.toLowerCase()),
which,
{
polling: 1000,
timeout: 5000
}
);
result.found = true;
result.title = await page.title();
}
// If the wait times out:
catch(error) {
// Quit.
await abortActs();
waitError(page, act, error, 'text in the title');
}
}
// Otherwise, if the text is to be a substring of the text of the page body:
else if (what === 'body') {
// Wait for the body to include the text, case-insensitively.
try {
await page.waitForFunction(
text => document
&& document.body
&& document.body.innerText.toLowerCase().includes(text.toLowerCase()),
which,
{
polling: 2000,
timeout: 15000
}
);
result.found = true;
}
// If the wait times out:
catch(error) {
// Quit.
await abortActs();
waitError(page, act, error, 'text in the body');
}
}
}
// Otherwise, if the act is a wait for a state:
else if (act.type === 'state') {
// Wait for it.
const stateIndex = ['loaded', 'idle'].indexOf(act.which);
await page.waitForLoadState(
['domcontentloaded', 'networkidle'][stateIndex], {timeout: [10000, 15000][stateIndex]}
)
// If the wait times out:
.catch(async error => {
// Report this and abort the job.
console.log(`ERROR waiting for page to be ${act.which} (${error.message})`);
actIndex = await addError(
true, true, report, actIndex, `ERROR waiting for page to be ${act.which}`
);
});
// If the wait succeeded:
if (actIndex > -2) {
// Add state data to the report.
act.result = {
success: true,
state: act.which
};
}
}
// 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 idle.
await page.waitForLoadState('networkidle', {timeout: 15000});
// Add the resulting URL 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();
// Add the URL to the act.
act.actualURL = url;
// If the act is a revelation:
if (act.type === 'reveal') {
// Make all elements in the page visible.
await page.$$eval('body *', elements => {