@elastic/synthetics 1.0.0-beta.25 → 1.0.0-beta.28

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 (126) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +56 -8
  3. package/dist/cli.js.map +1 -1
  4. package/dist/common_types.d.ts +59 -5
  5. package/dist/common_types.d.ts.map +1 -1
  6. package/dist/core/gatherer.d.ts +2 -2
  7. package/dist/core/gatherer.d.ts.map +1 -1
  8. package/dist/core/gatherer.js +2 -2
  9. package/dist/core/gatherer.js.map +1 -1
  10. package/dist/core/index.d.ts +4 -0
  11. package/dist/core/index.d.ts.map +1 -1
  12. package/dist/core/index.js +15 -1
  13. package/dist/core/index.js.map +1 -1
  14. package/dist/core/runner.d.ts +10 -58
  15. package/dist/core/runner.d.ts.map +1 -1
  16. package/dist/core/runner.js +92 -49
  17. package/dist/core/runner.js.map +1 -1
  18. package/dist/dsl/journey.d.ts +3 -0
  19. package/dist/dsl/journey.d.ts.map +1 -1
  20. package/dist/dsl/journey.js +15 -0
  21. package/dist/dsl/journey.js.map +1 -1
  22. package/dist/{reporters/reporter.d.ts → dsl/locations.d.ts} +12 -8
  23. package/dist/dsl/locations.d.ts.map +1 -0
  24. package/dist/dsl/locations.js +41 -0
  25. package/dist/dsl/locations.js.map +1 -0
  26. package/dist/dsl/monitor.d.ts +65 -0
  27. package/dist/dsl/monitor.d.ts.map +1 -0
  28. package/dist/dsl/monitor.js +63 -0
  29. package/dist/dsl/monitor.js.map +1 -0
  30. package/dist/generator/index.d.ts +21 -0
  31. package/dist/generator/index.d.ts.map +1 -0
  32. package/dist/generator/index.js +169 -0
  33. package/dist/generator/index.js.map +1 -0
  34. package/{src/reporters/reporter.ts → dist/generator/utils.d.ts} +4 -11
  35. package/dist/generator/utils.d.ts.map +1 -0
  36. package/dist/generator/utils.js +57 -0
  37. package/dist/generator/utils.js.map +1 -0
  38. package/dist/helpers.d.ts +12 -6
  39. package/dist/helpers.d.ts.map +1 -1
  40. package/dist/helpers.js +33 -43
  41. package/dist/helpers.js.map +1 -1
  42. package/dist/index.d.ts +2 -7
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +4 -3
  45. package/dist/index.js.map +1 -1
  46. package/dist/loader.js +4 -4
  47. package/dist/loader.js.map +1 -1
  48. package/dist/options.d.ts +7 -0
  49. package/dist/options.d.ts.map +1 -1
  50. package/dist/options.js +66 -12
  51. package/dist/options.js.map +1 -1
  52. package/dist/plugins/performance.d.ts +1 -16
  53. package/dist/plugins/performance.d.ts.map +1 -1
  54. package/dist/plugins/performance.js.map +1 -1
  55. package/dist/plugins/plugin-manager.d.ts +1 -1
  56. package/dist/push/bundler.d.ts +34 -0
  57. package/dist/push/bundler.d.ts.map +1 -0
  58. package/dist/push/bundler.js +119 -0
  59. package/dist/push/bundler.js.map +1 -0
  60. package/dist/{reporters/reporter.js → push/index.d.ts} +4 -3
  61. package/dist/push/index.d.ts.map +1 -0
  62. package/dist/push/index.js +58 -0
  63. package/dist/push/index.js.map +1 -0
  64. package/dist/push/monitor.d.ts +32 -0
  65. package/dist/push/monitor.d.ts.map +1 -0
  66. package/dist/push/monitor.js +62 -0
  67. package/dist/push/monitor.js.map +1 -0
  68. package/dist/push/plugin.d.ts +33 -0
  69. package/dist/push/plugin.d.ts.map +1 -0
  70. package/dist/push/plugin.js +123 -0
  71. package/dist/push/plugin.js.map +1 -0
  72. package/dist/push/request.d.ts +43 -0
  73. package/dist/push/request.d.ts.map +1 -0
  74. package/dist/push/request.js +89 -0
  75. package/dist/push/request.js.map +1 -0
  76. package/dist/reporters/base.d.ts +14 -6
  77. package/dist/reporters/base.d.ts.map +1 -1
  78. package/dist/reporters/base.js +45 -47
  79. package/dist/reporters/base.js.map +1 -1
  80. package/dist/reporters/index.d.ts +18 -8
  81. package/dist/reporters/index.d.ts.map +1 -1
  82. package/dist/reporters/index.js.map +1 -1
  83. package/dist/reporters/json.d.ts +7 -3
  84. package/dist/reporters/json.d.ts.map +1 -1
  85. package/dist/reporters/json.js +118 -118
  86. package/dist/reporters/json.js.map +1 -1
  87. package/dist/reporters/junit.d.ts +7 -1
  88. package/dist/reporters/junit.d.ts.map +1 -1
  89. package/dist/reporters/junit.js +91 -86
  90. package/dist/reporters/junit.js.map +1 -1
  91. package/dist/tsconfig.tsbuildinfo +1 -1
  92. package/package.json +17 -11
  93. package/src/cli.ts +91 -14
  94. package/src/common_types.ts +69 -5
  95. package/src/core/gatherer.ts +4 -4
  96. package/src/core/index.ts +15 -0
  97. package/src/core/runner.ts +93 -113
  98. package/src/dsl/journey.ts +18 -0
  99. package/src/dsl/locations.ts +38 -0
  100. package/src/dsl/monitor.ts +87 -0
  101. package/src/generator/index.ts +212 -0
  102. package/src/generator/utils.ts +54 -0
  103. package/src/helpers.ts +36 -52
  104. package/src/index.ts +9 -1
  105. package/src/loader.ts +4 -4
  106. package/src/options.ts +72 -15
  107. package/src/plugins/performance.ts +1 -17
  108. package/src/push/bundler.ts +99 -0
  109. package/src/push/index.ts +63 -0
  110. package/src/push/monitor.ts +68 -0
  111. package/src/push/plugin.ts +113 -0
  112. package/src/push/request.ts +116 -0
  113. package/src/reporters/base.ts +57 -56
  114. package/src/reporters/index.ts +26 -3
  115. package/src/reporters/json.ts +153 -145
  116. package/src/reporters/junit.ts +98 -93
  117. package/templates/.github/workflows/run-synthetics.yml +28 -0
  118. package/templates/README.md +21 -0
  119. package/templates/journeys/advanced-example-helpers.ts +54 -0
  120. package/templates/journeys/advanced-example.journey.ts +43 -0
  121. package/templates/journeys/example.journey.ts +18 -0
  122. package/templates/synthetics.config.ts +26 -0
  123. package/CHANGELOG.md +0 -348
  124. package/NOTICE.txt +0 -221
  125. package/dist/reporters/reporter.d.ts.map +0 -1
  126. package/dist/reporters/reporter.js.map +0 -1
@@ -0,0 +1,212 @@
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
+ import { execSync } from 'child_process';
26
+ import { existsSync } from 'fs';
27
+ import { mkdir, readFile, writeFile } from 'fs/promises';
28
+ import { bold, cyan, yellow } from 'kleur/colors';
29
+ import { join, relative, dirname, basename } from 'path';
30
+ import { prompt } from 'enquirer';
31
+ import { SyntheticsLocations } from '../dsl/monitor';
32
+ import { progress, write as stdWrite } from '../helpers';
33
+ import { getPackageManager, replaceTemplates, runCommand } from './utils';
34
+
35
+ // Templates that are required for setting up new
36
+ // synthetics project
37
+ const templateDir = join(__dirname, '..', '..', 'templates');
38
+
39
+ type PromptOptions = {
40
+ locations: string;
41
+ schedule: number;
42
+ };
43
+
44
+ // exported for testing
45
+ export const regularFiles = [
46
+ '.github/workflows/run-synthetics.yml',
47
+ 'README.md',
48
+ 'journeys/example.journey.ts',
49
+ 'journeys/advanced-example.journey.ts',
50
+ 'journeys/advanced-example-helpers.ts',
51
+ ];
52
+
53
+ export class Generator {
54
+ pkgManager = 'npm';
55
+ constructor(public projectDir: string) {}
56
+
57
+ async directory() {
58
+ if (!existsSync(this.projectDir)) {
59
+ await mkdir(this.projectDir);
60
+ }
61
+ }
62
+
63
+ async questions() {
64
+ if (process.env.TEST_QUESTIONS) {
65
+ return JSON.parse(process.env.TEST_QUESTIONS);
66
+ }
67
+ const question = [
68
+ {
69
+ type: 'select',
70
+ name: 'locations',
71
+ message: 'Select the default location where you want to run monitors.',
72
+ choices: SyntheticsLocations,
73
+ },
74
+ {
75
+ type: 'numeral',
76
+ name: 'schedule',
77
+ message: 'Set default schedule in minutes for all monitors',
78
+ initial: 10,
79
+ },
80
+ ];
81
+ return await prompt<PromptOptions>(question);
82
+ }
83
+
84
+ async files(answers: PromptOptions) {
85
+ const fileMap = new Map<string, string>();
86
+ // Setup Synthetics config file
87
+ const configFile = 'synthetics.config.ts';
88
+ fileMap.set(
89
+ configFile,
90
+ replaceTemplates(
91
+ await readFile(join(templateDir, configFile), 'utf-8'),
92
+ answers
93
+ )
94
+ );
95
+
96
+ // Setup non-templated files
97
+ Promise.all(
98
+ regularFiles.map(async fn => {
99
+ fileMap.set(fn, await readFile(join(templateDir, fn), 'utf-8'));
100
+ })
101
+ ).catch(e => {
102
+ throw e;
103
+ });
104
+
105
+ // Create files
106
+ for (const [relativePath, content] of fileMap) {
107
+ await this.createFile(relativePath, content);
108
+ }
109
+ }
110
+
111
+ async createFile(relativePath: string, content: string, override = false) {
112
+ const absolutePath = join(this.projectDir, relativePath);
113
+ if (override || !existsSync(absolutePath)) {
114
+ progress(`Writing ${relative(process.cwd(), absolutePath)}.`);
115
+ await mkdir(dirname(absolutePath), { recursive: true });
116
+ await writeFile(absolutePath, content, 'utf-8');
117
+ }
118
+ }
119
+
120
+ async package() {
121
+ this.pkgManager = await getPackageManager(this.projectDir);
122
+ const commands = new Map<string, string>();
123
+ commands.set(
124
+ `Initializing Synthetics project using ${
125
+ this.pkgManager == 'yarn' ? 'Yarn' : 'NPM'
126
+ }`,
127
+ this.pkgManager == 'yarn' ? 'yarn init -y' : 'npm init -y'
128
+ );
129
+
130
+ const pkgName = '@elastic/synthetics';
131
+ commands.set(
132
+ `Installing @elastic/synthetics library`,
133
+ this.pkgManager == 'yarn'
134
+ ? `yarn add -dev ${pkgName}`
135
+ : `npm i -d ${pkgName}`
136
+ );
137
+
138
+ // Execute commands
139
+ for (const [name, command] of commands) {
140
+ progress(`${name}...`);
141
+ execSync(command, {
142
+ stdio: 'inherit',
143
+ cwd: this.projectDir,
144
+ });
145
+ }
146
+ }
147
+
148
+ async patchPkgJSON() {
149
+ const filename = 'package.json';
150
+ const pkgJSON = JSON.parse(
151
+ await readFile(join(this.projectDir, filename), 'utf-8')
152
+ );
153
+
154
+ if (!pkgJSON.scripts) {
155
+ pkgJSON.scripts = {};
156
+ }
157
+ // Add test command
158
+ pkgJSON.scripts.test = 'npx @elastic/synthetics journeys';
159
+
160
+ // Add push command
161
+ const project = basename(this.projectDir);
162
+ pkgJSON.scripts.push = `npx @elastic/synthetics push journeys --project ${project} --url http://localhost:5601 --auth apiKey`;
163
+
164
+ await this.createFile(
165
+ filename,
166
+ JSON.stringify(pkgJSON, null, 2) + '\n',
167
+ true
168
+ );
169
+ }
170
+
171
+ async patchGitIgnore() {
172
+ const gitIgnorePath = join(this.projectDir, '.gitignore');
173
+ let gitIgnore = '';
174
+ if (existsSync(gitIgnorePath)) {
175
+ const contents = await readFile(gitIgnorePath, 'utf-8');
176
+ gitIgnore += contents.trimEnd() + '\n';
177
+ }
178
+ if (!gitIgnore.includes('node_modules')) {
179
+ gitIgnore += 'node_modules/\n';
180
+ }
181
+ gitIgnore += '.synthetics/\n';
182
+ await writeFile(gitIgnorePath, gitIgnore, 'utf-8');
183
+ }
184
+
185
+ banner() {
186
+ stdWrite(
187
+ bold(`
188
+ All set, you can run below commands inside: ${this.projectDir}:
189
+
190
+ Run synthetic tests: ${cyan(runCommand(this.pkgManager, 'test'))}
191
+
192
+ Push monitors to Kibana: ${cyan(runCommand(this.pkgManager, 'push'))}
193
+
194
+ ${yellow(
195
+ 'Make sure to update the Kibana url and api keys before pushing monitors to Kibana.'
196
+ )}
197
+
198
+ Visit https://www.elastic.co/guide/en/observability/master/synthetics-journeys.html to learn more.
199
+ `)
200
+ );
201
+ }
202
+
203
+ async setup() {
204
+ await this.directory();
205
+ const answers = await this.questions();
206
+ await this.package();
207
+ await this.files(answers);
208
+ await this.patchPkgJSON();
209
+ await this.patchGitIgnore();
210
+ this.banner();
211
+ }
212
+ }
@@ -0,0 +1,54 @@
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 { existsSync } from 'fs';
27
+ import { join } from 'path';
28
+
29
+ export async function getPackageManager(dir: string) {
30
+ if (existsSync(join(dir, 'yarn.lock'))) {
31
+ return 'yarn';
32
+ }
33
+ return 'npm';
34
+ }
35
+
36
+ export function runCommand(pkgManager: string, command: string) {
37
+ if (pkgManager === 'yarn') {
38
+ return `yarn ${command}`;
39
+ }
40
+ return `npm run ${command}`;
41
+ }
42
+
43
+ export function replaceTemplates(input: string, literals: Record<string, any>) {
44
+ for (const key in literals) {
45
+ const finalValue = literals[key];
46
+ input = input.replace(new RegExp(`'{{` + key + `}}'`, 'g'), () => {
47
+ if (typeof finalValue == 'number') {
48
+ return Number(finalValue);
49
+ }
50
+ return finalValue;
51
+ });
52
+ }
53
+ return input;
54
+ }
package/src/helpers.ts CHANGED
@@ -23,7 +23,7 @@
23
23
  *
24
24
  */
25
25
 
26
- import { red, green, yellow, cyan } from 'kleur/colors';
26
+ import { red, green, yellow, cyan, bold } from 'kleur/colors';
27
27
  import os from 'os';
28
28
  import { resolve, join, dirname } from 'path';
29
29
  import fs from 'fs';
@@ -35,6 +35,7 @@ import {
35
35
  HooksCallback,
36
36
  NetworkConditions,
37
37
  Location,
38
+ ThrottlingOptions,
38
39
  } from './common_types';
39
40
 
40
41
  const lstatAsync = promisify(fs.lstat);
@@ -60,6 +61,7 @@ const NO_UTF8_SUPPORT = process.platform === 'win32';
60
61
  export const symbols = {
61
62
  warning: yellow(NO_UTF8_SUPPORT ? '!' : '⚠'),
62
63
  skipped: cyan('-'),
64
+ progress: cyan('>'),
63
65
  succeeded: green(NO_UTF8_SUPPORT ? 'ok' : '✓'),
64
66
  failed: red(NO_UTF8_SUPPORT ? 'x' : '✖'),
65
67
  };
@@ -267,62 +269,27 @@ export function megabitsToBytes(megabytes: number) {
267
269
  return (megabytes * 1024 * 1024) / 8;
268
270
  }
269
271
 
270
- export function bytesToMegabits(bytes: number) {
271
- return (bytes / 1024 / 1024) * 8;
272
- }
273
-
274
- export const DEFAULT_NETWORK_CONDITIONS: NetworkConditions = {
275
- downloadThroughput: megabitsToBytes(5), // Devtools CDP expects format to be in bytes/second
276
- uploadThroughput: megabitsToBytes(3), // Devtools CDP expects format to be in bytes/second
277
- latency: 20, // milliseconds,
278
- offline: false,
272
+ export const DEFAULT_THROTTLING_OPTIONS: ThrottlingOptions = {
273
+ download: 5,
274
+ upload: 3,
275
+ latency: 20,
279
276
  };
280
277
 
281
- // Tranforms CDP dev tools format back to cli args format
282
- export function formatNetworkConditionsArgs(
283
- networkConditions: NetworkConditions
284
- ) {
285
- const d = bytesToMegabits(networkConditions.downloadThroughput);
286
- const u = bytesToMegabits(networkConditions.uploadThroughput);
287
- const l = networkConditions.latency;
288
- return `${d}d/${u}u/${l}l`;
289
- }
290
-
291
- export const DEFAULT_NETWORK_CONDITIONS_ARG = formatNetworkConditionsArgs(
292
- DEFAULT_NETWORK_CONDITIONS
293
- );
294
-
295
- export function parseNetworkConditions(args: string): NetworkConditions {
296
- const uploadToken = 'u';
297
- const downloadToken = 'd';
298
- const latencyToken = 'l';
299
- const networkConditions = {
300
- ...DEFAULT_NETWORK_CONDITIONS,
278
+ /**
279
+ * Transforms the CLI throttling arguments in to format
280
+ * expected by Chrome devtools protocol NetworkConditions
281
+ */
282
+ export function getNetworkConditions(
283
+ throttlingOpts: ThrottlingOptions
284
+ ): NetworkConditions {
285
+ return {
286
+ downloadThroughput: megabitsToBytes(throttlingOpts.download),
287
+ uploadThroughput: megabitsToBytes(throttlingOpts.upload), // Devtools CDP expects format to be in bytes/second
288
+ latency: throttlingOpts.latency, // milliseconds,
289
+ offline: false,
301
290
  };
302
-
303
- const conditions = args.split('/');
304
-
305
- conditions.forEach(condition => {
306
- const value = condition.slice(0, condition.length - 1);
307
- const token = condition.slice(-1);
308
-
309
- switch (token) {
310
- case uploadToken:
311
- networkConditions.uploadThroughput = megabitsToBytes(Number(value));
312
- break;
313
- case downloadToken:
314
- networkConditions.downloadThroughput = megabitsToBytes(Number(value));
315
- break;
316
- case latencyToken:
317
- networkConditions.latency = Number(value);
318
- break;
319
- }
320
- });
321
-
322
- return networkConditions;
323
291
  }
324
292
 
325
- // default stack trace limit
326
293
  const dstackTraceLimit = 10;
327
294
 
328
295
  // Uses the V8 Stacktrace API to get the function location
@@ -354,3 +321,20 @@ export function wrapFnWithLocation<A extends unknown[], R>(
354
321
  return func(location, ...args);
355
322
  };
356
323
  }
324
+
325
+ // Console helpers
326
+ export function write(message: string) {
327
+ process.stderr.write(message + '\n');
328
+ }
329
+
330
+ export function progress(message: string) {
331
+ write(cyan(bold(`${symbols.progress} ${message}`)));
332
+ }
333
+
334
+ export function error(message: string) {
335
+ write(red(message));
336
+ }
337
+
338
+ export function done(message: string) {
339
+ write(bold(green(`${symbols['succeeded']} ${message}`)));
340
+ }
package/src/index.ts CHANGED
@@ -33,7 +33,15 @@ export async function run(options: RunOptions) {
33
33
  /**
34
34
  * Export all core module functions
35
35
  */
36
- export { beforeAll, afterAll, journey, step, before, after } from './core';
36
+ export {
37
+ journey,
38
+ step,
39
+ monitor,
40
+ beforeAll,
41
+ afterAll,
42
+ before,
43
+ after,
44
+ } from './core';
37
45
  export { expect } from './core/expect';
38
46
  /**
39
47
  * Export all the driver related types to be consumed
package/src/loader.ts CHANGED
@@ -81,7 +81,7 @@ export async function loadTestFiles(options: CliArgs, args: string[]) {
81
81
  */
82
82
  const files =
83
83
  args.length > 0 ? args : (await readStdin()).split('\n').filter(Boolean);
84
- const suites = await prepareSuites(files, options);
84
+ const suites = await prepareSuites(files, options.pattern);
85
85
  requireSuites(suites);
86
86
  }
87
87
 
@@ -123,7 +123,7 @@ function requireSuites(suites: Iterable<string>) {
123
123
  * Handle both directory and files that are passed through TTY
124
124
  * and add them to suites
125
125
  */
126
- async function prepareSuites(inputs: string[], cliArgs: CliArgs) {
126
+ async function prepareSuites(inputs: string[], filePattern?: string) {
127
127
  const suites = new Set<string>();
128
128
  const addSuite = absPath => {
129
129
  log(`Processing file: ${absPath}`);
@@ -133,8 +133,8 @@ async function prepareSuites(inputs: string[], cliArgs: CliArgs) {
133
133
  * Match all files inside the directory with the
134
134
  * .journey.{mjs|cjs|js|ts) extensions
135
135
  */
136
- const pattern = cliArgs.pattern
137
- ? new RegExp(cliArgs.pattern, 'i')
136
+ const pattern = filePattern
137
+ ? new RegExp(filePattern, 'i')
138
138
  : /.+\.journey\.([mc]js|[jt]s?)$/;
139
139
  /**
140
140
  * Ignore node_modules by default when running suites
package/src/options.ts CHANGED
@@ -25,8 +25,8 @@
25
25
 
26
26
  import merge from 'deepmerge';
27
27
  import { readConfig } from './config';
28
- import { parseNetworkConditions } from './helpers';
29
- import type { CliArgs, RunOptions } from './common_types';
28
+ import { getNetworkConditions, DEFAULT_THROTTLING_OPTIONS } from './helpers';
29
+ import type { CliArgs, RunOptions, ThrottlingOptions } from './common_types';
30
30
 
31
31
  /**
32
32
  * Set debug based on DEBUG ENV and -d flags
@@ -91,26 +91,83 @@ export function normalizeOptions(cliArgs: CliArgs): RunOptions {
91
91
  ? readConfig(options.environment, cliArgs.config)
92
92
  : {};
93
93
 
94
+ /**
95
+ * Order of preference for options that are used while running are
96
+ * 1. Local options configured via Runner API
97
+ * 2. CLI flags
98
+ * 3. Configuration file
99
+ */
94
100
  options.params = Object.freeze(merge(config.params, cliArgs.params || {}));
95
101
 
96
102
  /**
97
- * Favor playwright options passed via cli to inline playwright options
103
+ * Merge playwright options from CLI and Synthetics config
104
+ * and prefer individual options over other option
98
105
  */
99
- options.playwrightOptions = merge.all([
100
- config.playwrightOptions || {},
101
- cliArgs.playwrightOptions || {},
102
- {
103
- headless: cliArgs.headless,
104
- chromiumSandbox: cliArgs.sandbox,
105
- ignoreHTTPSErrors: cliArgs.ignoreHttpsErrors,
106
- },
107
- ]);
106
+ const playwrightOpts = merge(
107
+ config.playwrightOptions,
108
+ cliArgs.playwrightOptions || {}
109
+ );
110
+ options.playwrightOptions = {
111
+ ...playwrightOpts,
112
+ headless: cliArgs.headless,
113
+ chromiumSandbox: cliArgs.sandbox ?? playwrightOpts?.chromiumSandbox,
114
+ ignoreHTTPSErrors:
115
+ cliArgs.ignoreHttpsErrors ?? playwrightOpts?.ignoreHTTPSErrors,
116
+ };
108
117
 
118
+ /**
119
+ * Get the default monitor config from synthetics.config.ts file
120
+ */
121
+ const monitor = config.monitor;
109
122
  if (cliArgs.throttling) {
110
- options.networkConditions = parseNetworkConditions(
111
- cliArgs.throttling as string
112
- );
123
+ const throttleConfig = merge.all([
124
+ DEFAULT_THROTTLING_OPTIONS,
125
+ monitor?.throttling || {},
126
+ cliArgs.throttling as ThrottlingOptions,
127
+ ]);
128
+ options.throttling = throttleConfig;
129
+ options.networkConditions = getNetworkConditions(throttleConfig);
130
+ } else {
131
+ /**
132
+ * Do not apply throttling when `--no-throttling` flag is passed
133
+ */
134
+ options.throttling = {};
113
135
  }
114
136
 
137
+ options.schedule = cliArgs.schedule ?? monitor?.schedule;
138
+ options.locations = cliArgs.locations ?? monitor?.locations;
139
+
115
140
  return options;
116
141
  }
142
+
143
+ /**
144
+ * Parses the throttling CLI settings and also
145
+ * adapts to the format to keep the backwards compatability
146
+ * - Accepts old format `<5d/3u/20l>`
147
+ * - Processess new format otherwise `{download: 5, upload: 3, latency: 20}`
148
+ */
149
+ export function parseThrottling(value: string, prev?: string) {
150
+ const THROTTLING_REGEX = /([0-9]{1,}u)|([0-9]{1,}d)|([0-9]{1,}l)/gm;
151
+ if (THROTTLING_REGEX.test(value)) {
152
+ const throttling: ThrottlingOptions = {};
153
+ const conditions = value.split('/');
154
+
155
+ conditions.forEach(condition => {
156
+ const setting = condition.slice(0, condition.length - 1);
157
+ const token = condition.slice(-1);
158
+ switch (token) {
159
+ case 'd':
160
+ throttling.download = Number(setting);
161
+ break;
162
+ case 'u':
163
+ throttling.upload = Number(setting);
164
+ break;
165
+ case 'l':
166
+ throttling.latency = Number(setting);
167
+ break;
168
+ }
169
+ });
170
+ return throttling;
171
+ }
172
+ return JSON.parse(value || prev);
173
+ }
@@ -23,7 +23,7 @@
23
23
  *
24
24
  */
25
25
 
26
- import { Driver } from '../common_types';
26
+ import { Driver, PageMetrics } from '../common_types';
27
27
 
28
28
  const supportedMetrics = new Set<string>([
29
29
  'Timestamp',
@@ -41,22 +41,6 @@ const supportedMetrics = new Set<string>([
41
41
  'JSHeapTotalSize',
42
42
  ]);
43
43
 
44
- export interface PageMetrics {
45
- Timestamp?: number;
46
- Documents?: number;
47
- Frames?: number;
48
- JSEventListeners?: number;
49
- Nodes?: number;
50
- LayoutCount?: number;
51
- RecalcStyleCount?: number;
52
- LayoutDuration?: number;
53
- RecalcStyleDuration?: number;
54
- ScriptDuration?: number;
55
- TaskDuration?: number;
56
- JSHeapUsedSize?: number;
57
- JSHeapTotalSize?: number;
58
- }
59
-
60
44
  export class PerformanceManager {
61
45
  constructor(private driver: Driver) {}
62
46
 
@@ -0,0 +1,99 @@
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 path from 'path';
27
+ import { unlink, readFile } from 'fs/promises';
28
+ import { createWriteStream } from 'fs';
29
+ import * as esbuild from 'esbuild';
30
+ import archiver from 'archiver';
31
+ import { commonOptions, MultiAssetPlugin, PluginData } from './plugin';
32
+
33
+ function relativeToCwd(entry: string) {
34
+ return path.relative(process.cwd(), entry);
35
+ }
36
+
37
+ export class Bundler {
38
+ moduleMap = new Map<string, string>();
39
+ constructor() {}
40
+
41
+ async prepare(absPath: string) {
42
+ const addToMap = (data: PluginData) => {
43
+ this.moduleMap.set(data.path, data.contents);
44
+ };
45
+
46
+ const options: esbuild.BuildOptions = {
47
+ ...commonOptions(),
48
+ ...{
49
+ entryPoints: {
50
+ [absPath]: absPath,
51
+ },
52
+ plugins: [MultiAssetPlugin(addToMap)],
53
+ },
54
+ };
55
+ try {
56
+ const result = await esbuild.build(options);
57
+ if (result.errors.length > 0) {
58
+ throw result.errors;
59
+ }
60
+ this.moduleMap.set(absPath, result.outputFiles[0].text);
61
+ } catch (e) {
62
+ console.error(e);
63
+ }
64
+ }
65
+
66
+ async zip(outputPath: string) {
67
+ return new Promise((fulfill, reject) => {
68
+ const output = createWriteStream(outputPath);
69
+ const archive = archiver('zip', {
70
+ zlib: { level: 9 },
71
+ });
72
+ archive.on('error', err => reject(err));
73
+ output.on('close', fulfill);
74
+ archive.pipe(output);
75
+ for (const [path, content] of this.moduleMap.entries()) {
76
+ const relativePath = relativeToCwd(path);
77
+ archive.append(content, { name: relativePath });
78
+ }
79
+ archive.finalize();
80
+ });
81
+ }
82
+
83
+ async build(entry: string, output: string) {
84
+ await this.prepare(entry);
85
+ await this.zip(output);
86
+ const data = await this.encode(output);
87
+ await this.cleanup(output);
88
+ return data;
89
+ }
90
+
91
+ async encode(outputPath: string) {
92
+ return await readFile(outputPath, 'base64');
93
+ }
94
+
95
+ async cleanup(outputPath: string) {
96
+ this.moduleMap = new Map<string, string>();
97
+ await unlink(outputPath);
98
+ }
99
+ }