@elastic/synthetics 1.0.0-beta.3 → 1.0.0-beta.32

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.
Files changed (202) hide show
  1. package/README.md +4 -3
  2. package/dist/cli.js +123 -161
  3. package/dist/cli.js.map +1 -1
  4. package/dist/common_types.d.ts +159 -34
  5. package/dist/common_types.d.ts.map +1 -1
  6. package/dist/config.d.ts +2 -5
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +5 -5
  9. package/dist/config.js.map +1 -1
  10. package/dist/core/browser-service.js +5 -5
  11. package/dist/core/browser-service.js.map +1 -1
  12. package/dist/core/expect.d.ts +25 -25
  13. package/dist/core/expect.d.ts.map +1 -1
  14. package/dist/core/expect.js.map +1 -1
  15. package/dist/core/gatherer.d.ts +4 -8
  16. package/dist/core/gatherer.d.ts.map +1 -1
  17. package/dist/core/gatherer.js +49 -15
  18. package/dist/core/gatherer.js.map +1 -1
  19. package/dist/core/index.d.ts +5 -1
  20. package/dist/core/index.d.ts.map +1 -1
  21. package/dist/core/index.js +23 -11
  22. package/dist/core/index.js.map +1 -1
  23. package/dist/core/logger.d.ts +0 -1
  24. package/dist/core/logger.d.ts.map +1 -1
  25. package/dist/core/logger.js +3 -16
  26. package/dist/core/logger.js.map +1 -1
  27. package/dist/core/runner.d.ts +21 -65
  28. package/dist/core/runner.d.ts.map +1 -1
  29. package/dist/core/runner.js +212 -93
  30. package/dist/core/runner.js.map +1 -1
  31. package/dist/dsl/index.js +5 -1
  32. package/dist/dsl/index.js.map +1 -1
  33. package/dist/dsl/journey.d.ts +9 -4
  34. package/dist/dsl/journey.d.ts.map +1 -1
  35. package/dist/dsl/journey.js +27 -7
  36. package/dist/dsl/journey.js.map +1 -1
  37. package/dist/dsl/monitor.d.ts +66 -0
  38. package/dist/dsl/monitor.d.ts.map +1 -0
  39. package/dist/dsl/monitor.js +63 -0
  40. package/dist/dsl/monitor.js.map +1 -0
  41. package/dist/dsl/step.d.ts +3 -2
  42. package/dist/dsl/step.d.ts.map +1 -1
  43. package/dist/dsl/step.js +2 -1
  44. package/dist/dsl/step.js.map +1 -1
  45. package/dist/formatter/javascript.d.ts +98 -0
  46. package/dist/formatter/javascript.d.ts.map +1 -0
  47. package/dist/formatter/javascript.js +295 -0
  48. package/dist/formatter/javascript.js.map +1 -0
  49. package/dist/generator/index.d.ts +29 -0
  50. package/dist/generator/index.d.ts.map +1 -0
  51. package/dist/generator/index.js +240 -0
  52. package/dist/generator/index.js.map +1 -0
  53. package/dist/{reporters/reporter.js → generator/utils.d.ts} +5 -3
  54. package/dist/generator/utils.d.ts.map +1 -0
  55. package/dist/generator/utils.js +80 -0
  56. package/dist/generator/utils.js.map +1 -0
  57. package/dist/helpers.d.ts +24 -1
  58. package/dist/helpers.d.ts.map +1 -1
  59. package/dist/helpers.js +126 -19
  60. package/dist/helpers.js.map +1 -1
  61. package/dist/index.d.ts +6 -7
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +5 -26
  64. package/dist/index.js.map +1 -1
  65. package/dist/{parse_args.d.ts → loader.d.ts} +2 -5
  66. package/dist/loader.d.ts.map +1 -0
  67. package/dist/loader.js +152 -0
  68. package/dist/loader.js.map +1 -0
  69. package/dist/locations/index.d.ts +45 -0
  70. package/dist/locations/index.d.ts.map +1 -0
  71. package/dist/locations/index.js +90 -0
  72. package/dist/locations/index.js.map +1 -0
  73. package/dist/{reporters/reporter.d.ts → locations/public-locations.d.ts} +12 -8
  74. package/dist/locations/public-locations.d.ts.map +1 -0
  75. package/dist/locations/public-locations.js +41 -0
  76. package/dist/locations/public-locations.js.map +1 -0
  77. package/dist/options.d.ts +41 -0
  78. package/dist/options.d.ts.map +1 -0
  79. package/dist/options.js +182 -0
  80. package/dist/options.js.map +1 -0
  81. package/dist/plugins/browser-console.d.ts +5 -4
  82. package/dist/plugins/browser-console.d.ts.map +1 -1
  83. package/dist/plugins/browser-console.js +27 -8
  84. package/dist/plugins/browser-console.js.map +1 -1
  85. package/dist/plugins/index.js +5 -1
  86. package/dist/plugins/index.js.map +1 -1
  87. package/dist/plugins/network.d.ts +20 -33
  88. package/dist/plugins/network.d.ts.map +1 -1
  89. package/dist/plugins/network.js +173 -214
  90. package/dist/plugins/network.js.map +1 -1
  91. package/dist/plugins/performance.d.ts +4 -19
  92. package/dist/plugins/performance.d.ts.map +1 -1
  93. package/dist/plugins/performance.js +5 -5
  94. package/dist/plugins/performance.js.map +1 -1
  95. package/dist/plugins/plugin-manager.d.ts +9 -5
  96. package/dist/plugins/plugin-manager.d.ts.map +1 -1
  97. package/dist/plugins/plugin-manager.js +44 -29
  98. package/dist/plugins/plugin-manager.js.map +1 -1
  99. package/dist/plugins/tracing.d.ts +6 -6
  100. package/dist/plugins/tracing.d.ts.map +1 -1
  101. package/dist/plugins/tracing.js +8 -7
  102. package/dist/plugins/tracing.js.map +1 -1
  103. package/dist/push/bundler.d.ts +34 -0
  104. package/dist/push/bundler.d.ts.map +1 -0
  105. package/dist/push/bundler.js +123 -0
  106. package/dist/push/bundler.js.map +1 -0
  107. package/dist/push/index.d.ts +33 -0
  108. package/dist/push/index.d.ts.map +1 -0
  109. package/dist/push/index.js +174 -0
  110. package/dist/push/index.js.map +1 -0
  111. package/dist/push/monitor.d.ts +34 -0
  112. package/dist/push/monitor.d.ts.map +1 -0
  113. package/dist/push/monitor.js +78 -0
  114. package/dist/push/monitor.js.map +1 -0
  115. package/{src/reporters/reporter.ts → dist/push/plugin.d.ts} +8 -10
  116. package/dist/push/plugin.d.ts.map +1 -0
  117. package/dist/push/plugin.js +133 -0
  118. package/dist/push/plugin.js.map +1 -0
  119. package/dist/push/request.d.ts +43 -0
  120. package/dist/push/request.d.ts.map +1 -0
  121. package/dist/push/request.js +83 -0
  122. package/dist/push/request.js.map +1 -0
  123. package/dist/reporters/base.d.ts +14 -6
  124. package/dist/reporters/base.d.ts.map +1 -1
  125. package/dist/reporters/base.js +54 -48
  126. package/dist/reporters/base.js.map +1 -1
  127. package/dist/reporters/index.d.ts +18 -8
  128. package/dist/reporters/index.d.ts.map +1 -1
  129. package/dist/reporters/index.js.map +1 -1
  130. package/dist/reporters/json.d.ts +18 -67
  131. package/dist/reporters/json.d.ts.map +1 -1
  132. package/dist/reporters/json.js +153 -175
  133. package/dist/reporters/json.js.map +1 -1
  134. package/dist/reporters/junit.d.ts +7 -1
  135. package/dist/reporters/junit.d.ts.map +1 -1
  136. package/dist/reporters/junit.js +94 -89
  137. package/dist/reporters/junit.js.map +1 -1
  138. package/dist/sdk/lh-trace-processor.d.ts +35 -9
  139. package/dist/sdk/lh-trace-processor.d.ts.map +1 -1
  140. package/dist/sdk/lh-trace-processor.js +114 -53
  141. package/dist/sdk/lh-trace-processor.js.map +1 -1
  142. package/dist/sdk/trace-metrics.d.ts +4 -4
  143. package/dist/sdk/trace-metrics.d.ts.map +1 -1
  144. package/dist/sdk/trace-metrics.js +5 -6
  145. package/dist/sdk/trace-metrics.js.map +1 -1
  146. package/dist/sdk/trace-processor.d.ts +11 -3
  147. package/dist/sdk/trace-processor.d.ts.map +1 -1
  148. package/dist/sdk/trace-processor.js +17 -9
  149. package/dist/sdk/trace-processor.js.map +1 -1
  150. package/dist/tsconfig.tsbuildinfo +1 -1888
  151. package/package.json +32 -20
  152. package/src/cli.ts +205 -152
  153. package/src/common_types.ts +192 -34
  154. package/src/config.ts +2 -5
  155. package/src/core/expect.ts +58 -24
  156. package/src/core/gatherer.ts +59 -24
  157. package/src/core/index.ts +36 -15
  158. package/src/core/logger.ts +1 -12
  159. package/src/core/runner.ts +215 -152
  160. package/src/dsl/journey.ts +37 -6
  161. package/src/dsl/monitor.ts +88 -0
  162. package/src/dsl/step.ts +9 -2
  163. package/src/formatter/javascript.ts +367 -0
  164. package/src/generator/index.ts +316 -0
  165. package/src/generator/utils.ts +80 -0
  166. package/src/helpers.ts +132 -12
  167. package/src/index.ts +22 -22
  168. package/src/loader.ts +171 -0
  169. package/src/locations/index.ts +108 -0
  170. package/src/locations/public-locations.ts +38 -0
  171. package/src/options.ts +211 -0
  172. package/src/plugins/browser-console.ts +30 -8
  173. package/src/plugins/network.ts +208 -267
  174. package/src/plugins/performance.ts +6 -22
  175. package/src/plugins/plugin-manager.ts +49 -31
  176. package/src/plugins/tracing.ts +8 -9
  177. package/src/push/bundler.ts +100 -0
  178. package/src/push/index.ts +202 -0
  179. package/src/push/monitor.ts +96 -0
  180. package/src/push/plugin.ts +119 -0
  181. package/src/push/request.ts +103 -0
  182. package/src/reporters/base.ts +63 -52
  183. package/src/reporters/index.ts +26 -3
  184. package/src/reporters/json.ts +203 -206
  185. package/src/reporters/junit.ts +98 -93
  186. package/src/sdk/lh-trace-processor.ts +132 -68
  187. package/src/sdk/trace-metrics.ts +10 -6
  188. package/src/sdk/trace-processor.ts +28 -13
  189. package/templates/.github/workflows/run-synthetics.yml +26 -0
  190. package/templates/README.md +21 -0
  191. package/templates/journeys/advanced-example-helpers.ts +54 -0
  192. package/templates/journeys/advanced-example.journey.ts +43 -0
  193. package/templates/journeys/example.journey.ts +18 -0
  194. package/templates/synthetics.config.ts +27 -0
  195. package/CHANGELOG.md +0 -102
  196. package/NOTICE.txt +0 -221
  197. package/dist/parse_args.d.ts.map +0 -1
  198. package/dist/parse_args.js +0 -89
  199. package/dist/parse_args.js.map +0 -1
  200. package/dist/reporters/reporter.d.ts.map +0 -1
  201. package/dist/reporters/reporter.js.map +0 -1
  202. package/src/parse_args.ts +0 -127
package/src/loader.ts ADDED
@@ -0,0 +1,171 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2020-present, Elastic NV
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in
14
+ * all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ * THE SOFTWARE.
23
+ *
24
+ */
25
+
26
+ import { stdin, cwd } from 'process';
27
+ import { resolve } from 'path';
28
+ import { CliArgs } from './common_types';
29
+ import { step, journey } from './core';
30
+ import { log } from './core/logger';
31
+ import { expect } from './core/expect';
32
+ import {
33
+ isDepInstalled,
34
+ isDirectory,
35
+ totalist,
36
+ findPkgJsonByTraversing,
37
+ } from './helpers';
38
+
39
+ const resolvedCwd = cwd();
40
+
41
+ export async function loadTestFiles(options: CliArgs, args: string[]) {
42
+ /**
43
+ * Transform `.ts` files out of the box by invoking
44
+ * the `ts-node` via `transpile-only` mode that compiles
45
+ * TS files without doing any extensive type checks.
46
+ *
47
+ * We must register `ts-node` _before_ loading inline
48
+ * scripts too because otherwise we will not be able to
49
+ * require `.ts` configuration files.
50
+ */
51
+ /* eslint-disable-next-line @typescript-eslint/no-var-requires */
52
+ require('ts-node').register({
53
+ transpileOnly: true,
54
+ compilerOptions: {
55
+ esModuleInterop: true,
56
+ allowJs: true,
57
+ target: 'es2020',
58
+ },
59
+ });
60
+
61
+ /**
62
+ * Preload modules before running the tests
63
+ */
64
+ const modules = [].concat(options.require || []).filter(Boolean);
65
+ for (const name of modules) {
66
+ if (isDepInstalled(name)) {
67
+ require(name);
68
+ } else {
69
+ throw new Error(`cannot find module '${name}'`);
70
+ }
71
+ }
72
+
73
+ if (options.inline) {
74
+ const source = await readStdin();
75
+ loadInlineScript(source);
76
+ return;
77
+ }
78
+ /**
79
+ * Handle piped files by reading the STDIN
80
+ * ex: ls example/suites/*.js | npx @elastic/synthetics
81
+ */
82
+ const files =
83
+ args.length > 0 ? args : (await readStdin()).split('\n').filter(Boolean);
84
+ const suites = await prepareSuites(files, options.pattern);
85
+ requireSuites(suites);
86
+ }
87
+
88
+ const loadInlineScript = source => {
89
+ const scriptFn = new Function(
90
+ 'step',
91
+ 'page',
92
+ 'context',
93
+ 'browser',
94
+ 'params',
95
+ 'expect',
96
+ 'request',
97
+ source
98
+ );
99
+ journey('inline', ({ page, context, browser, params, request }) => {
100
+ scriptFn.apply(null, [
101
+ step,
102
+ page,
103
+ context,
104
+ browser,
105
+ params,
106
+ expect,
107
+ request,
108
+ ]);
109
+ });
110
+ };
111
+
112
+ /**
113
+ * Read the input from STDIN and run it as inline journey
114
+ */
115
+ async function readStdin() {
116
+ const chunks = [];
117
+ stdin.resume();
118
+ stdin.setEncoding('utf-8');
119
+ for await (const chunk of stdin) {
120
+ chunks.push(chunk);
121
+ }
122
+ return chunks.join();
123
+ }
124
+
125
+ function requireSuites(suites: Iterable<string>) {
126
+ for (const suite of suites) {
127
+ require(suite);
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Handle both directory and files that are passed through TTY
133
+ * and add them to suites
134
+ */
135
+ async function prepareSuites(inputs: string[], filePattern?: string) {
136
+ const suites = new Set<string>();
137
+ const addSuite = absPath => {
138
+ log(`Processing file: ${absPath}`);
139
+ suites.add(require.resolve(absPath));
140
+ };
141
+ /**
142
+ * Match all files inside the directory with the
143
+ * .journey.{mjs|cjs|js|ts) extensions
144
+ */
145
+ const pattern = filePattern
146
+ ? new RegExp(filePattern, 'i')
147
+ : /.+\.journey\.([mc]js|[jt]s?)$/;
148
+ /**
149
+ * Ignore node_modules by default when running suites
150
+ */
151
+ const ignored = /node_modules/i;
152
+
153
+ for (const input of inputs) {
154
+ const absPath = resolve(resolvedCwd, input);
155
+ /**
156
+ * Validate for package.json file before running
157
+ * the suites
158
+ */
159
+ findPkgJsonByTraversing(absPath, resolvedCwd);
160
+ if (isDirectory(absPath)) {
161
+ await totalist(absPath, (rel, abs) => {
162
+ if (pattern.test(rel) && !ignored.test(rel)) {
163
+ addSuite(abs);
164
+ }
165
+ });
166
+ } else {
167
+ addSuite(absPath);
168
+ }
169
+ }
170
+ return suites.values();
171
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2020-present, Elastic NV
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in
14
+ * all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ * THE SOFTWARE.
23
+ *
24
+ */
25
+
26
+ import {
27
+ formatAPIError,
28
+ formatNotFoundError,
29
+ sendRequest,
30
+ ok,
31
+ } from '../push/request';
32
+ import { indent, removeTrailingSlash, write } from '../helpers';
33
+
34
+ export type LocationCmdOptions = {
35
+ auth: string;
36
+ url: string;
37
+ };
38
+
39
+ type LocationMetadata = {
40
+ id: string;
41
+ label: string;
42
+ isServiceManaged: boolean;
43
+ };
44
+
45
+ export type LocationAPIResponse = {
46
+ locations: Array<LocationMetadata>;
47
+ };
48
+
49
+ const PRIVATE_KEYWORD = '(private)';
50
+
51
+ export async function getLocations(options: LocationCmdOptions) {
52
+ const url =
53
+ removeTrailingSlash(options.url) + '/internal/uptime/service/locations';
54
+ const { body, statusCode } = await sendRequest({
55
+ url,
56
+ method: 'GET',
57
+ auth: options.auth,
58
+ });
59
+ if (statusCode === 404) {
60
+ throw formatNotFoundError(await body.text());
61
+ }
62
+ if (!ok(statusCode)) {
63
+ const { error, message } = await body.json();
64
+ throw formatAPIError(statusCode, error, message);
65
+ }
66
+ return ((await body.json()) as LocationAPIResponse).locations;
67
+ }
68
+
69
+ export function formatLocations(locations: Array<LocationMetadata>) {
70
+ const formatted: Array<string> = [];
71
+ for (const location of locations) {
72
+ let name = location.label;
73
+ if (location.isServiceManaged) {
74
+ [, name] = name.includes('-') ? name.split('-') : [, name];
75
+ name = name.toLowerCase().trim().split(' ').join('_');
76
+ } else {
77
+ name = `${name}${PRIVATE_KEYWORD}`;
78
+ }
79
+ formatted.push(name);
80
+ }
81
+ return formatted;
82
+ }
83
+
84
+ export function groupLocations(locations: Array<string>) {
85
+ const grouped = { locations: [], privateLocations: [] };
86
+ for (const loc of locations) {
87
+ if (loc.includes(PRIVATE_KEYWORD)) {
88
+ grouped.privateLocations.push(loc.replace(PRIVATE_KEYWORD, ''));
89
+ } else {
90
+ grouped.locations.push(loc);
91
+ }
92
+ }
93
+ return grouped;
94
+ }
95
+
96
+ export function renderLocations(locations: Array<string>) {
97
+ let outer = 'Available locations: \n';
98
+ let inner = '';
99
+ for (const location of locations) {
100
+ inner += `* ${location}\n`;
101
+ }
102
+ outer += indent(inner);
103
+ outer += `\nSet default location for monitors via
104
+ - Synthetics config file 'monitors.locations' | 'monitors.privateLocations' field
105
+ - Monitor API 'monitor.use({ locations: ["japan"], privateLocations: ["custom-location"] }')`;
106
+
107
+ write(outer);
108
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2020-present, Elastic NV
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in
14
+ * all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ * THE SOFTWARE.
23
+ *
24
+ */
25
+
26
+ // DO NOT EDIT - UPDATE WITH `npm run build:locations`
27
+ export const LocationsMap = {
28
+ japan: 'asia-northeast1-a',
29
+ india: 'asia-south1-a',
30
+ singapore: 'asia-southeast1-a',
31
+ australia_east: 'australia-southeast1-a',
32
+ united_kingdom: 'europe-west2-a',
33
+ germany: 'europe-west3-a',
34
+ canada_east: 'northamerica-northeast1-a',
35
+ brazil: 'southamerica-east1-a',
36
+ us_east: 'us-east4-a',
37
+ us_west: 'us-west1-a',
38
+ };
package/src/options.ts ADDED
@@ -0,0 +1,211 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2020-present, Elastic NV
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in
14
+ * all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ * THE SOFTWARE.
23
+ *
24
+ */
25
+
26
+ import merge from 'deepmerge';
27
+ import { createOption } from 'commander';
28
+ import { readConfig } from './config';
29
+ import { getNetworkConditions, DEFAULT_THROTTLING_OPTIONS } from './helpers';
30
+ import type { CliArgs, RunOptions, ThrottlingOptions } from './common_types';
31
+
32
+ /**
33
+ * Set debug based on DEBUG ENV and -d flags
34
+ * namespace - synthetics
35
+ */
36
+ const namespace = 'synthetics';
37
+ if (process.env.DEBUG && process.env.DEBUG.includes(namespace)) {
38
+ process.env.DEBUG = '1';
39
+ }
40
+
41
+ export function normalizeOptions(cliArgs: CliArgs): RunOptions {
42
+ const options: RunOptions = {
43
+ ...cliArgs,
44
+ environment: process.env['NODE_ENV'] || 'development',
45
+ };
46
+ /**
47
+ * Group all events that can be consumed by heartbeat and
48
+ * eventually by the Synthetics UI.
49
+ */
50
+ if (cliArgs.richEvents) {
51
+ options.reporter = cliArgs.reporter ?? 'json';
52
+ options.ssblocks = true;
53
+ options.network = true;
54
+ options.trace = true;
55
+ options.quietExitCode = true;
56
+ }
57
+
58
+ if (cliArgs.capability) {
59
+ const supportedCapabilities = [
60
+ 'trace',
61
+ 'network',
62
+ 'filmstrips',
63
+ 'metrics',
64
+ 'ssblocks',
65
+ ];
66
+ /**
67
+ * trace - record chrome trace events(LCP, FCP, CLS, etc.) for all journeys
68
+ * network - capture network information for all journeys
69
+ * filmstrips - record detailed filmstrips for all journeys
70
+ * metrics - capture performance metrics (DOM Nodes, Heap size, etc.) for each step
71
+ * ssblocks - Dedupes the screenshots in to blocks to save storage space
72
+ */
73
+ for (const flag of cliArgs.capability) {
74
+ if (supportedCapabilities.includes(flag)) {
75
+ options[flag] = true;
76
+ } else {
77
+ console.warn(
78
+ `Missing capability "${flag}", current supported capabilities are ${supportedCapabilities.join(
79
+ ', '
80
+ )}`
81
+ );
82
+ }
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Validate and read synthetics config file
88
+ * based on the environment
89
+ */
90
+ const config =
91
+ cliArgs.config || !cliArgs.inline
92
+ ? readConfig(options.environment, cliArgs.config)
93
+ : {};
94
+
95
+ /**
96
+ * Order of preference for options that are used while running are
97
+ * 1. Local options configured via Runner API
98
+ * 2. CLI flags
99
+ * 3. Configuration file
100
+ */
101
+ options.params = Object.freeze(merge(config.params, cliArgs.params || {}));
102
+
103
+ /**
104
+ * Merge playwright options from CLI and Synthetics config
105
+ * and prefer individual options over other option
106
+ */
107
+ const playwrightOpts = merge(
108
+ config.playwrightOptions,
109
+ cliArgs.playwrightOptions || {}
110
+ );
111
+ options.playwrightOptions = {
112
+ ...playwrightOpts,
113
+ headless: cliArgs.headless,
114
+ chromiumSandbox: cliArgs.sandbox ?? playwrightOpts?.chromiumSandbox,
115
+ ignoreHTTPSErrors:
116
+ cliArgs.ignoreHttpsErrors ?? playwrightOpts?.ignoreHTTPSErrors,
117
+ };
118
+
119
+ /**
120
+ * Get the default monitor config from synthetics.config.ts file
121
+ */
122
+ const monitor = config.monitor;
123
+ if (cliArgs.throttling) {
124
+ const throttleConfig = merge.all([
125
+ DEFAULT_THROTTLING_OPTIONS,
126
+ monitor?.throttling || {},
127
+ cliArgs.throttling as ThrottlingOptions,
128
+ ]);
129
+ options.throttling = throttleConfig;
130
+ options.networkConditions = getNetworkConditions(throttleConfig);
131
+ } else {
132
+ /**
133
+ * Do not apply throttling when `--no-throttling` flag is passed
134
+ */
135
+ options.throttling = {};
136
+ }
137
+
138
+ options.schedule = cliArgs.schedule ?? monitor?.schedule;
139
+ options.locations = cliArgs.locations ?? monitor?.locations;
140
+ options.privateLocations =
141
+ cliArgs.privateLocations ?? monitor?.privateLocations;
142
+
143
+ return options;
144
+ }
145
+
146
+ /**
147
+ * Parses the throttling CLI settings and also
148
+ * adapts to the format to keep the backwards compatability
149
+ * - Accepts old format `<5d/3u/20l>`
150
+ * - Processess new format otherwise `{download: 5, upload: 3, latency: 20}`
151
+ */
152
+ export function parseThrottling(value: string, prev?: string) {
153
+ const THROTTLING_REGEX = /([0-9]{1,}u)|([0-9]{1,}d)|([0-9]{1,}l)/gm;
154
+ if (THROTTLING_REGEX.test(value)) {
155
+ const throttling: ThrottlingOptions = {};
156
+ const conditions = value.split('/');
157
+
158
+ conditions.forEach(condition => {
159
+ const setting = condition.slice(0, condition.length - 1);
160
+ const token = condition.slice(-1);
161
+ switch (token) {
162
+ case 'd':
163
+ throttling.download = Number(setting);
164
+ break;
165
+ case 'u':
166
+ throttling.upload = Number(setting);
167
+ break;
168
+ case 'l':
169
+ throttling.latency = Number(setting);
170
+ break;
171
+ }
172
+ });
173
+ return throttling;
174
+ }
175
+ return JSON.parse(value || prev);
176
+ }
177
+
178
+ export function getCommonCommandOpts() {
179
+ const params = createOption(
180
+ '-p, --params <jsonstring>',
181
+ 'JSON object that gets injected to all journeys'
182
+ );
183
+ params.argParser(JSON.parse);
184
+
185
+ const playwrightOpts = createOption(
186
+ '--playwright-options <jsonstring>',
187
+ 'JSON object to pass in custom Playwright options for the agent. Options passed will be merged with Playwright options defined in your synthetics.config.js file.'
188
+ );
189
+ playwrightOpts.argParser(JSON.parse);
190
+
191
+ const pattern = createOption(
192
+ '--pattern <pattern>',
193
+ 'RegExp file patterns to search inside directory'
194
+ );
195
+ const tags = createOption(
196
+ '--tags <name...>',
197
+ 'run only journeys with a tag that matches the glob'
198
+ );
199
+ const match = createOption(
200
+ '--match <name>',
201
+ 'run only journeys with a name or tag that matches the glob'
202
+ );
203
+
204
+ return {
205
+ params,
206
+ playwrightOpts,
207
+ pattern,
208
+ tags,
209
+ match,
210
+ };
211
+ }
@@ -23,8 +23,7 @@
23
23
  *
24
24
  */
25
25
 
26
- import { Page } from 'playwright-chromium';
27
- import { BrowserMessage } from '../common_types';
26
+ import { BrowserMessage, Driver } from '../common_types';
28
27
  import { Step } from '../dsl';
29
28
  import { getTimestamp } from '../helpers';
30
29
 
@@ -34,6 +33,8 @@ export class BrowserConsole {
34
33
  private messages: BrowserMessage[] = [];
35
34
  _currentStep: Partial<Step> = null;
36
35
 
36
+ constructor(private driver: Driver) {}
37
+
37
38
  private consoleEventListener = msg => {
38
39
  if (!this._currentStep) {
39
40
  return;
@@ -47,20 +48,41 @@ export class BrowserConsole {
47
48
  type,
48
49
  step: { name, index },
49
50
  });
50
- if (this.messages.length > defaultMessageLimit) {
51
- this.messages.splice(0, 1);
52
- }
51
+
52
+ this.enforceMessagesLimit();
53
+ }
54
+ };
55
+
56
+ private pageErrorEventListener = (error: Error) => {
57
+ if (!this._currentStep) {
58
+ return;
53
59
  }
60
+ const { name, index } = this._currentStep;
61
+ this.messages.push({
62
+ timestamp: getTimestamp(),
63
+ text: error.message,
64
+ type: 'error',
65
+ step: { name, index },
66
+ error,
67
+ });
68
+
69
+ this.enforceMessagesLimit();
54
70
  };
55
71
 
56
- constructor(private page: Page) {}
72
+ private enforceMessagesLimit() {
73
+ if (this.messages.length > defaultMessageLimit) {
74
+ this.messages.splice(0, 1);
75
+ }
76
+ }
57
77
 
58
78
  start() {
59
- this.page.on('console', this.consoleEventListener);
79
+ this.driver.page.on('console', this.consoleEventListener);
80
+ this.driver.page.on('pageerror', this.pageErrorEventListener);
60
81
  }
61
82
 
62
83
  stop() {
63
- this.page.off('console', this.consoleEventListener);
84
+ this.driver.page.off('console', this.consoleEventListener);
85
+ this.driver.page.off('pageerror', this.pageErrorEventListener);
64
86
  return this.messages;
65
87
  }
66
88
  }