pa11y-ci-reporter-runner 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,9 +19,10 @@ Pa11y CI Reporter Runner exports a factory function that creates a reporter runn
19
19
  - `options`: Optional [reporter options](https://github.com/pa11y/pa11y-ci#reporter-options).
20
20
  - `config`: Optional Pa11y CI configuration file that produces the Pa11y CI JSON results.
21
21
 
22
- The reporter runner currently has one function:
22
+ The reporter runner has two functions:
23
23
 
24
- - `runAll`: Simulates Pa11y CI running the complete analysis from the provided JSON results file, calling all associated reporter functions (`beforeAll`, `begin` and `results`/`error` for each URL, `afterAll`).
24
+ - `runAll`: Simulates Pa11y CI running the complete analysis from the provided JSON results file, calling all associated reporter functions (`beforeAll`, `begin` and `results`/`error` for each URL, `afterAll`). Once a run has been completed the runner must be reset before running again.
25
+ - `reset`: Resets the runner to the initial state.
25
26
 
26
27
  A complete example is provided below:
27
28
 
package/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  /**
4
- * Pa11y CI Reporter Runner allows a pa11y-ci reporter to be run
4
+ * Pa11y CI Reporter Runner allows a Pa11y CI reporter to be run
5
5
  * from a JSON results file without using pa11y-ci.
6
6
  *
7
7
  * @module pa11y-ci-reporter-runner
@@ -9,9 +9,17 @@
9
9
 
10
10
  const fs = require('fs');
11
11
  const formatter = require('./lib/formatter');
12
- const reporterBuilder = require('./lib/reporterBuilder');
12
+ const reporterBuilder = require('./lib/reporter-builder');
13
13
  const createConfig = require('./lib/config');
14
+ const { serviceFactory } = require('./lib/pa11yci-service');
14
15
 
16
+ /**
17
+ * Loads the Pa11y CI results from JSON file.
18
+ *
19
+ * @private
20
+ * @param {string} fileName Pa11y CI JSON results file name.
21
+ * @returns {object} Pa11y CI results.
22
+ */
15
23
  const loadPa11yciResults = fileName => {
16
24
  if (typeof fileName !== 'string') {
17
25
  throw new TypeError('fileName must be a string');
@@ -21,20 +29,17 @@ const loadPa11yciResults = fileName => {
21
29
  const results = JSON.parse(fs.readFileSync(fileName, 'utf8'));
22
30
  return formatter.convertJsonToResultsObject(results);
23
31
  }
24
- catch (err) {
25
- throw new Error(`Error loading results file - ${err.message}`);
32
+ catch (error) {
33
+ throw new Error(`Error loading results file - ${error.message}`);
26
34
  }
27
35
  };
28
36
 
29
- const isError = results => results.length === 1 && results[0] instanceof Error;
30
-
31
37
  /**
32
38
  * Pa11y CI configuration allows config.urls entries to be either url strings
33
39
  * or object with url and other configuration, so this return a list of just
34
40
  * the url strings.
35
41
  *
36
42
  * @private
37
- * @static
38
43
  * @param {object[]} values The urls array from configuration.
39
44
  * @returns {string[]} Array of URL strings.
40
45
  */
@@ -55,13 +60,12 @@ const getUrlList = values => {
55
60
  };
56
61
 
57
62
  /**
58
- * Compares URLs in Pa1y CI results and configuration files to ensure
63
+ * Compares URLs in Pa11y CI results and configuration files to ensure
59
64
  * consistency (i.e. The same URLs are in both lists, although they
60
65
  * may not be in the same order). URLs in config are only checked if
61
66
  * provided. If specified and inconsistent, throws error.
62
67
  *
63
68
  * @private
64
- * @static
65
69
  * @param {object} results Pa11y CI JSON results file.
66
70
  * @param {object} config Pa11y CI configuration.
67
71
  */
@@ -78,6 +82,15 @@ const validateUrls = (results, config) => {
78
82
  }
79
83
  };
80
84
 
85
+ /**
86
+ * Check if the given Pa11y results are an execution error.
87
+ *
88
+ * @private
89
+ * @param {object} results Pa11y results for a single URL.
90
+ * @returns {boolean} True if the results are an execution error.
91
+ */
92
+ const isError = results => results.length === 1 && results[0] instanceof Error;
93
+
81
94
  /**
82
95
  * Factory to create a pa11y-ci reporter runner that can execute
83
96
  * a reporter with the specified pa11y-ci JSON results file.
@@ -90,6 +103,7 @@ const validateUrls = (results, config) => {
90
103
  * @param {object} config The Pa11y CI configuration.
91
104
  * @returns {object} A Pa11y CI reporter runner.
92
105
  */
106
+ // eslint-disable-next-line max-lines-per-function
93
107
  const createRunner = (resultsFileName, reporterName, options = {}, config = {}) => {
94
108
  const pa11yciResults = loadPa11yciResults(resultsFileName);
95
109
 
@@ -97,27 +111,85 @@ const createRunner = (resultsFileName, reporterName, options = {}, config = {})
97
111
 
98
112
  const pa11yciConfig = createConfig(config);
99
113
  const reporter = reporterBuilder.buildReporter(reporterName, options, pa11yciConfig.defaults);
114
+ const urls = config.urls || Object.keys(pa11yciResults.results);
115
+
116
+ /**
117
+ * Implements the runner beforeAll event, calling reporter.beforeAll.
118
+ *
119
+ * @private
120
+ */
121
+ const beforeAll = async () => {
122
+ await reporter.beforeAll(urls);
123
+ };
100
124
 
101
- const runAll = async () => {
102
- await reporter.beforeAll(config.urls || Object.keys(pa11yciResults.results));
103
-
104
- for (const url of Object.keys(pa11yciResults.results)) {
105
- await reporter.begin(url);
106
-
107
- const urlResults = pa11yciResults.results[url];
108
- const urlConfig = pa11yciConfig.getConfigForUrl(url);
109
- if (isError(urlResults)) {
110
- await reporter.error(urlResults[0], url, urlConfig);
111
- }
112
- else {
113
- await reporter.results(formatter.getPa11yResultsFromPa11yCiResults(url, pa11yciResults), urlConfig);
114
- }
115
- }
125
+ /**
126
+ * Implements the runner beginUrl event, calling reporter.begin.
127
+ *
128
+ * @private
129
+ * @param {string} url The url being analyzed.
130
+ */
131
+ const beginUrl = async (url) => {
132
+ await reporter.begin(url);
133
+ };
116
134
 
135
+ /**
136
+ * Implements the runner urlResults event, calling reporter.results or
137
+ * reporter.error as appropriate based on the results.
138
+ *
139
+ * @private
140
+ * @param {string} url The url being analyzed.
141
+ */
142
+ const urlResults = async (url) => {
143
+ const results = pa11yciResults.results[url];
144
+ const urlConfig = pa11yciConfig.getConfigForUrl(url);
145
+ await (isError(results)
146
+ ? reporter.error(results[0], url, urlConfig)
147
+ : reporter.results(formatter.getPa11yResultsFromPa11yCiResults(url, pa11yciResults), urlConfig));
148
+ };
149
+
150
+ /**
151
+ * Implements the runner afterAll event, calling reporter.afterAll.
152
+ *
153
+ * @private
154
+ */
155
+ const afterAll = async () => {
117
156
  await reporter.afterAll(pa11yciResults, pa11yciConfig.defaults);
118
157
  };
119
158
 
159
+ // Collection of runner actions to be passed to the state service.
160
+ const actions = {
161
+ beforeAll,
162
+ beginUrl,
163
+ urlResults,
164
+ afterAll
165
+ };
166
+
167
+ // URLs for the service is always the array of result URLs since they
168
+ // are used to retrieve the results.
169
+ const service = serviceFactory(Object.keys(pa11yciResults.results), actions);
170
+
171
+ /**
172
+ * Resets the runner to the initial state.
173
+ *
174
+ * @public
175
+ * @instance
176
+ */
177
+ const reset = async () => {
178
+ await service.reset();
179
+ };
180
+
181
+ /**
182
+ * Executes the entire Pa11y CI sequence, calling all reporter functions.
183
+ *
184
+ * @public
185
+ * @instance
186
+ */
187
+ const runAll = async () => {
188
+ await service.runAll();
189
+ };
190
+
120
191
  return {
192
+ reset,
121
193
  runAll
122
194
  };
123
195
  };
package/lib/config.js CHANGED
@@ -20,7 +20,7 @@ const normalizeConfig = (config) => {
20
20
  };
21
21
 
22
22
  /**
23
- * Factory function that returns a config object for managing PA11y CI
23
+ * Factory function that returns a config object for managing Pa11y CI
24
24
  * configuration including defaults and determining the consolidated
25
25
  * configuration for each URL.
26
26
  *
package/lib/formatter.js CHANGED
@@ -6,6 +6,9 @@
6
6
  * @module formatter
7
7
  */
8
8
 
9
+ const isError = issues => issues.length === 1 && Object.keys(issues[0]).length === 1
10
+ && issues[0].message;
11
+
9
12
  /**
10
13
  * Converts Pa11y CI JSON output to an equivalent Pa11y CI object,
11
14
  * allowing JSON result files to be used for reporter interface
@@ -25,13 +28,7 @@ const convertJsonToResultsObject = jsonResults => {
25
28
 
26
29
  for (const url of Object.keys(jsonResults.results)) {
27
30
  const issues = jsonResults.results[url];
28
- let formattedIssues;
29
- if (issues.length === 1 && Object.keys(issues[0]).length === 1 && issues[0].message) {
30
- formattedIssues = [new Error(issues[0].message)];
31
- }
32
- else {
33
- formattedIssues = issues;
34
- }
31
+ const formattedIssues = isError(issues) ? [new Error(issues[0].message)] : issues;
35
32
  results.results[url] = formattedIssues;
36
33
  }
37
34
 
@@ -63,4 +60,3 @@ const getPa11yResultsFromPa11yCiResults = (url, results) => {
63
60
 
64
61
  module.exports.convertJsonToResultsObject = convertJsonToResultsObject;
65
62
  module.exports.getPa11yResultsFromPa11yCiResults = getPa11yResultsFromPa11yCiResults;
66
-
@@ -0,0 +1,68 @@
1
+ 'use strict';
2
+
3
+ const { createMachine, assign } = require('xstate');
4
+
5
+ const pa11yciMachine = createMachine(
6
+ {
7
+ id: 'pa11yci-runner',
8
+ initial: 'init',
9
+ context: {
10
+ urlIndex: 0,
11
+ urls: []
12
+ },
13
+ states: {
14
+ init: {
15
+ entry: 'setInitialUrlIndex',
16
+ on: {
17
+ NEXT: { target: 'beforeAll' }
18
+ }
19
+ },
20
+ beforeAll: {
21
+ on: {
22
+ NEXT: [
23
+ { target: 'beginUrl', cond: 'hasUrls' },
24
+ { target: 'afterAll' }
25
+ ],
26
+ RESET: { target: 'init' }
27
+ }
28
+ },
29
+ beginUrl: {
30
+ on: {
31
+ NEXT: { target: 'urlResults' },
32
+ RESET: { target: 'init' }
33
+ }
34
+ },
35
+ urlResults: {
36
+ on: {
37
+ NEXT: [
38
+ { target: 'afterAll', cond: 'isLastUrl' },
39
+ { target: 'beginUrl', actions: 'incrementUrl' }
40
+ ],
41
+ RESET: { target: 'init' }
42
+ }
43
+ },
44
+ afterAll: {
45
+ on: {
46
+ RESET: { target: 'init' }
47
+ }
48
+ }
49
+ }
50
+ },
51
+ {
52
+ actions: {
53
+ incrementUrl: assign({
54
+ urlIndex: (context) => context.urlIndex + 1
55
+ }),
56
+ setInitialUrlIndex: assign({
57
+ urlIndex: () => 0
58
+ })
59
+ },
60
+ guards: {
61
+ hasUrls: (context) => context.urls.length > 0,
62
+ isLastUrl: (context) =>
63
+ context.urlIndex === context.urls.length - 1
64
+ }
65
+ }
66
+ );
67
+
68
+ module.exports = pa11yciMachine;
@@ -0,0 +1,139 @@
1
+ 'use strict';
2
+
3
+ const { interpret } = require('xstate');
4
+ const machine = require('./pa11yci-machine');
5
+
6
+ const RunnerStates = Object.freeze({
7
+ beforeAll: 'beforeAll',
8
+ beginUrl: 'beginUrl',
9
+ urlResults: 'urlResults',
10
+ afterAll: 'afterAll'
11
+ });
12
+ const finalState = RunnerStates.afterAll;
13
+
14
+ /**
15
+ * Gets the initial pa11yci-runner state machine context given an array of URLs.
16
+ *
17
+ * @private
18
+ * @param {Array} urls Array of URLs.
19
+ * @returns {object} The initial state machine context.
20
+ */
21
+ const getInitialContext = urls => ({
22
+ urlIndex: 0,
23
+ urls
24
+ });
25
+
26
+ /**
27
+ * Checks the state to determine whether it has an associated URL.
28
+ *
29
+ * @private
30
+ * @param {RunnerStates} state The state to check.
31
+ * @returns {boolean} True if the state has an associated url.
32
+ */
33
+ const hasUrl = state => state === RunnerStates.beginUrl || state === RunnerStates.urlResults;
34
+
35
+ /**
36
+ * Factory function that return a pa11yci-runner service.
37
+ *
38
+ * @public
39
+ * @static
40
+ * @param {Array} urls Array of URLs.
41
+ * @param {object} actions Actions object with functions to execute for each event.
42
+ * @returns {object} A pa11yci-runner service.
43
+ */
44
+ // eslint-disable-next-line max-lines-per-function
45
+ const serviceFactory = (urls, actions) => {
46
+ let pendingCommand;
47
+ const currentContext = {
48
+ state: undefined,
49
+ url: undefined
50
+ };
51
+
52
+ // Create service from pa11yci-machine with context, setup
53
+ // transition event handler, and start service
54
+ const service = interpret(machine.withContext(getInitialContext(urls)));
55
+ service.onTransition(async (state) => {
56
+ // Save the current state and url for use in manual transitions.
57
+ // The state machine only increments the url index, so use that
58
+ // to get the url from the original urls array.
59
+ currentContext.state = state.value;
60
+ currentContext.url = hasUrl(currentContext.state)
61
+ ? urls[state.context.urlIndex] : undefined;
62
+
63
+ if (pendingCommand) {
64
+ // Do not take any action in init state
65
+ if (currentContext.state !== 'init') {
66
+ await actions[currentContext.state](currentContext.url);
67
+ }
68
+ pendingCommand.resolve();
69
+ pendingCommand = undefined;
70
+ }
71
+ });
72
+ service.start();
73
+
74
+ /**
75
+ * Sends the NEXT event to the pa11yci-runner service. Resolves when
76
+ * the next state has been reached and the reporter event raised.
77
+ *
78
+ * @private
79
+ * @returns {Promise<void>} Promise that indicates a pending state change.
80
+ */
81
+ const next = () => {
82
+ return new Promise((resolve, reject) => {
83
+ pendingCommand = { resolve, reject };
84
+ service.send({ type: 'NEXT' });
85
+ });
86
+ };
87
+
88
+ /**
89
+ * Sends the RESET event to the pa11yci-runner service. Resolves when
90
+ * the next state has been reached and the reporter event raised.
91
+ *
92
+ * @private
93
+ * @returns {Promise<void>} Promise that indicates a pending state change.
94
+ */
95
+ const resetInternal = () => {
96
+ return new Promise((resolve, reject) => {
97
+ pendingCommand = { resolve, reject };
98
+ service.send({ type: 'RESET' });
99
+ });
100
+ };
101
+
102
+ /**
103
+ * Resets the service to the init state.
104
+ *
105
+ * @public
106
+ * @instance
107
+ */
108
+ const reset = async () => {
109
+ await resetInternal();
110
+ };
111
+
112
+ /**
113
+ * Executes the entire Pa11y CI sequence, calling all reporter functions.
114
+ *
115
+ * @public
116
+ * @instance
117
+ */
118
+ const runAll = async () => {
119
+ if (currentContext.state === finalState) {
120
+ throw new Error(`runner must be reset before executing any other functions from the ${finalState} state`);
121
+ }
122
+
123
+ // Since this runs the entire sequence, send the NEXT event
124
+ // until the final state is reached.
125
+ while (currentContext.state !== finalState) {
126
+ // eslint-disable-next-line node/callback-return -- not a callback
127
+ await next();
128
+ }
129
+ };
130
+
131
+ return {
132
+ reset,
133
+ runAll
134
+ };
135
+ };
136
+
137
+ module.exports = {
138
+ serviceFactory
139
+ };
@@ -27,6 +27,7 @@ const loadReporter = reporterName => {
27
27
  * @param {object} config The Pa11y CI configuration.
28
28
  * @returns {object} The reporter object.
29
29
  */
30
+ // eslint-disable-next-line sonarjs/cognitive-complexity -- allow < 10
30
31
  const buildReporter = (reporterName, options, config) => {
31
32
  if (typeof reporterName !== 'string') {
32
33
  throw new TypeError('reporterName must be a string');
@@ -37,15 +38,15 @@ const buildReporter = (reporterName, options, config) => {
37
38
  if (typeof reporter === 'function') {
38
39
  reporter = reporter(options, config);
39
40
  }
40
- reporterMethods.forEach(method => {
41
+ for (const method of reporterMethods) {
41
42
  if (typeof reporter[method] !== 'function') {
42
43
  reporter[method] = noop;
43
44
  }
44
- });
45
+ }
45
46
  return reporter;
46
47
  }
47
- catch (err) {
48
- throw new Error(`Error loading reporter: ${err.message}`);
48
+ catch (error) {
49
+ throw new Error(`Error loading reporter: ${error.message}`);
49
50
  }
50
51
  };
51
52
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pa11y-ci-reporter-runner",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Pa11y CI Reporter Runner is designed to facilitate testing of Pa11y CI reporters. Given a Pa11y CI JSON results file and optional configuration it simulates the Pa11y CI calls to the reporter.",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -35,14 +35,15 @@
35
35
  },
36
36
  "homepage": "https://gitlab.com/gitlab-ci-utils/pa11y-ci-reporter-runner#readme",
37
37
  "devDependencies": {
38
- "@aarongoldenthal/eslint-config-standard": "^11.0.0",
39
- "eslint": "^8.8.0",
40
- "jest": "^27.4.7",
38
+ "@aarongoldenthal/eslint-config-standard": "^12.0.2",
39
+ "eslint": "^8.9.0",
40
+ "jest": "^27.5.1",
41
41
  "jest-junit": "^13.0.0",
42
- "markdownlint-cli": "^0.30.0",
42
+ "markdownlint-cli": "^0.31.1",
43
43
  "pa11y-ci-reporter-cli-summary": "^1.0.1"
44
44
  },
45
45
  "dependencies": {
46
- "lodash": "^4.17.21"
46
+ "lodash": "^4.17.21",
47
+ "xstate": "^4.30.2"
47
48
  }
48
49
  }