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

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 (116) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +42 -5
  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.map +1 -1
  9. package/dist/core/index.d.ts +4 -0
  10. package/dist/core/index.d.ts.map +1 -1
  11. package/dist/core/index.js +15 -1
  12. package/dist/core/index.js.map +1 -1
  13. package/dist/core/runner.d.ts +10 -58
  14. package/dist/core/runner.d.ts.map +1 -1
  15. package/dist/core/runner.js +88 -49
  16. package/dist/core/runner.js.map +1 -1
  17. package/dist/dsl/journey.d.ts +3 -0
  18. package/dist/dsl/journey.d.ts.map +1 -1
  19. package/dist/dsl/journey.js +15 -0
  20. package/dist/dsl/journey.js.map +1 -1
  21. package/dist/dsl/monitor.d.ts +64 -0
  22. package/dist/dsl/monitor.d.ts.map +1 -0
  23. package/dist/dsl/monitor.js +62 -0
  24. package/dist/dsl/monitor.js.map +1 -0
  25. package/dist/generator/index.d.ts +13 -0
  26. package/dist/generator/index.d.ts.map +1 -0
  27. package/dist/generator/index.js +123 -0
  28. package/dist/generator/index.js.map +1 -0
  29. package/dist/{reporters/reporter.js → generator/utils.d.ts} +3 -3
  30. package/dist/generator/utils.d.ts.map +1 -0
  31. package/dist/generator/utils.js +44 -0
  32. package/dist/generator/utils.js.map +1 -0
  33. package/dist/helpers.d.ts +12 -6
  34. package/dist/helpers.d.ts.map +1 -1
  35. package/dist/helpers.js +33 -43
  36. package/dist/helpers.js.map +1 -1
  37. package/dist/index.d.ts +2 -7
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +4 -3
  40. package/dist/index.js.map +1 -1
  41. package/dist/loader.js +4 -4
  42. package/dist/loader.js.map +1 -1
  43. package/dist/options.d.ts +12 -0
  44. package/dist/options.d.ts.map +1 -1
  45. package/dist/options.js +66 -4
  46. package/dist/options.js.map +1 -1
  47. package/dist/plugins/performance.d.ts +1 -16
  48. package/dist/plugins/performance.d.ts.map +1 -1
  49. package/dist/plugins/performance.js.map +1 -1
  50. package/dist/plugins/plugin-manager.d.ts +1 -1
  51. package/dist/push/bundler.d.ts +34 -0
  52. package/dist/push/bundler.d.ts.map +1 -0
  53. package/dist/push/bundler.js +119 -0
  54. package/dist/push/bundler.js.map +1 -0
  55. package/{src/reporters/reporter.ts → dist/push/index.d.ts} +4 -11
  56. package/dist/push/index.d.ts.map +1 -0
  57. package/dist/push/index.js +58 -0
  58. package/dist/push/index.js.map +1 -0
  59. package/dist/{reporters/reporter.d.ts → push/monitor.d.ts} +7 -8
  60. package/dist/push/monitor.d.ts.map +1 -0
  61. package/dist/push/monitor.js +67 -0
  62. package/dist/push/monitor.js.map +1 -0
  63. package/dist/push/plugin.d.ts +33 -0
  64. package/dist/push/plugin.d.ts.map +1 -0
  65. package/dist/push/plugin.js +123 -0
  66. package/dist/push/plugin.js.map +1 -0
  67. package/dist/push/request.d.ts +43 -0
  68. package/dist/push/request.d.ts.map +1 -0
  69. package/dist/push/request.js +95 -0
  70. package/dist/push/request.js.map +1 -0
  71. package/dist/reporters/base.d.ts +14 -6
  72. package/dist/reporters/base.d.ts.map +1 -1
  73. package/dist/reporters/base.js +45 -47
  74. package/dist/reporters/base.js.map +1 -1
  75. package/dist/reporters/index.d.ts +18 -8
  76. package/dist/reporters/index.d.ts.map +1 -1
  77. package/dist/reporters/index.js.map +1 -1
  78. package/dist/reporters/json.d.ts +7 -3
  79. package/dist/reporters/json.d.ts.map +1 -1
  80. package/dist/reporters/json.js +118 -118
  81. package/dist/reporters/json.js.map +1 -1
  82. package/dist/reporters/junit.d.ts +7 -1
  83. package/dist/reporters/junit.d.ts.map +1 -1
  84. package/dist/reporters/junit.js +91 -86
  85. package/dist/reporters/junit.js.map +1 -1
  86. package/dist/tsconfig.tsbuildinfo +1 -1
  87. package/package.json +12 -8
  88. package/src/cli.ts +65 -9
  89. package/src/common_types.ts +69 -5
  90. package/src/core/gatherer.ts +2 -2
  91. package/src/core/index.ts +15 -0
  92. package/src/core/runner.ts +86 -113
  93. package/src/dsl/journey.ts +18 -0
  94. package/src/dsl/monitor.ts +83 -0
  95. package/src/generator/index.ts +159 -0
  96. package/src/generator/utils.ts +41 -0
  97. package/src/helpers.ts +36 -52
  98. package/src/index.ts +9 -1
  99. package/src/loader.ts +4 -4
  100. package/src/options.ts +71 -8
  101. package/src/plugins/performance.ts +1 -17
  102. package/src/push/bundler.ts +99 -0
  103. package/src/push/index.ts +63 -0
  104. package/src/push/monitor.ts +77 -0
  105. package/src/push/plugin.ts +113 -0
  106. package/src/push/request.ts +123 -0
  107. package/src/reporters/base.ts +57 -56
  108. package/src/reporters/index.ts +26 -3
  109. package/src/reporters/json.ts +153 -145
  110. package/src/reporters/junit.ts +98 -93
  111. package/templates/journeys/example.journey.ts +18 -0
  112. package/templates/synthetics.config.ts +19 -0
  113. package/CHANGELOG.md +0 -348
  114. package/NOTICE.txt +0 -221
  115. package/dist/reporters/reporter.d.ts.map +0 -1
  116. package/dist/reporters/reporter.js.map +0 -1
@@ -0,0 +1,83 @@
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 {
28
+ ThrottlingOptions,
29
+ Location,
30
+ ScreenshotOptions,
31
+ Params,
32
+ PlaywrightOptions,
33
+ } from '../common_types';
34
+
35
+ export const SyntheticsLocations = ['US East', 'EU West'] as const;
36
+ export type SyntheticsLocationsType = typeof SyntheticsLocations[number];
37
+ export type MonitorConfig = {
38
+ id?: string;
39
+ name?: string;
40
+ tags?: string[];
41
+ schedule?: number;
42
+ enabled?: boolean;
43
+ locations?: SyntheticsLocationsType[];
44
+ throttling?: ThrottlingOptions;
45
+ screenshot?: ScreenshotOptions;
46
+ params?: Params;
47
+ playwrightOptions?: PlaywrightOptions;
48
+ };
49
+
50
+ type MonitorFilter = {
51
+ match: string;
52
+ tags?: string[];
53
+ };
54
+
55
+ export class Monitor {
56
+ source?: Location;
57
+ filter: MonitorFilter;
58
+ constructor(public config: MonitorConfig = {}) {}
59
+ /**
60
+ * Treat the creation time config with `monitor.use` as source of truth by
61
+ * merging the values coming from CLI and Synthetics config file
62
+ */
63
+ update(globalOpts: MonitorConfig = {}) {
64
+ this.config = merge(globalOpts, this.config, {
65
+ arrayMerge(target, source) {
66
+ return [...new Set(source)];
67
+ },
68
+ });
69
+ }
70
+
71
+ setSource(source: Location) {
72
+ this.source = source;
73
+ }
74
+ /**
75
+ * If journey files are colocated within the same file during
76
+ * push command, when we invoke synthetics from HB we rely on
77
+ * this filter for running that specific journey alone instead of
78
+ * all journeys on the file
79
+ */
80
+ setFilter(filter: MonitorFilter) {
81
+ this.filter = filter;
82
+ }
83
+ }
@@ -0,0 +1,159 @@
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 { progress, write as stdWrite } from '../helpers';
31
+ import { getPackageManager, runCommand } from './utils';
32
+
33
+ // Templates that are required for setting up new
34
+ // synthetics project
35
+ const templateDir = join(__dirname, '..', '..', 'templates');
36
+
37
+ export class Generator {
38
+ pkgManager = 'npm';
39
+ constructor(public projectDir: string) {}
40
+
41
+ async directory() {
42
+ if (!existsSync(this.projectDir)) {
43
+ await mkdir(this.projectDir);
44
+ }
45
+ }
46
+
47
+ async files() {
48
+ const fileMap = new Map<string, string>();
49
+ // Setup Synthetics config file
50
+ const configFile = 'synthetics.config.ts';
51
+ fileMap.set(
52
+ configFile,
53
+ await readFile(join(templateDir, configFile), 'utf-8')
54
+ );
55
+
56
+ // Setup example journey file
57
+ const journeyFile = 'journeys/example.journey.ts';
58
+ fileMap.set(
59
+ journeyFile,
60
+ await readFile(join(templateDir, journeyFile), 'utf-8')
61
+ );
62
+ // Setup gitignore
63
+ fileMap.set(
64
+ '.gitignore',
65
+ await readFile(join(templateDir, '.gitignore'), 'utf-8')
66
+ );
67
+
68
+ // Create files
69
+ for (const [relativePath, content] of fileMap) {
70
+ await this.createFile(relativePath, content);
71
+ }
72
+ }
73
+
74
+ async createFile(relativePath: string, content: string, override = false) {
75
+ const absolutePath = join(this.projectDir, relativePath);
76
+ if (override || !existsSync(absolutePath)) {
77
+ progress(`Writing ${relative(process.cwd(), absolutePath)}.`);
78
+ await mkdir(dirname(absolutePath), { recursive: true });
79
+ await writeFile(absolutePath, content, 'utf-8');
80
+ }
81
+ }
82
+
83
+ async package() {
84
+ this.pkgManager = await getPackageManager(this.projectDir);
85
+ const commands = new Map<string, string>();
86
+ commands.set(
87
+ `Initializing Synthetics project using ${
88
+ this.pkgManager == 'yarn' ? 'Yarn' : 'NPM'
89
+ }`,
90
+ this.pkgManager == 'yarn' ? 'yarn init -y' : 'npm init -y'
91
+ );
92
+
93
+ const pkgName = '@elastic/synthetics';
94
+ commands.set(
95
+ `Installing @elastic/synthetics library`,
96
+ this.pkgManager == 'yarn'
97
+ ? `yarn add -dev ${pkgName}`
98
+ : `npm i -d ${pkgName}`
99
+ );
100
+
101
+ // Execute commands
102
+ for (const [name, command] of commands) {
103
+ progress(`${name}...`);
104
+ execSync(command, {
105
+ stdio: 'inherit',
106
+ cwd: this.projectDir,
107
+ });
108
+ }
109
+ }
110
+
111
+ async patchPkgJSON() {
112
+ const filename = 'package.json';
113
+ const pkgJSON = JSON.parse(
114
+ await readFile(join(this.projectDir, filename), 'utf-8')
115
+ );
116
+
117
+ if (!pkgJSON.scripts) {
118
+ pkgJSON.scripts = {};
119
+ }
120
+ // Add test command
121
+ pkgJSON.scripts.test = 'npx @elastic/synthetics journeys';
122
+
123
+ // Add push command
124
+ const project = basename(this.projectDir);
125
+ pkgJSON.scripts.push = `npx @elastic/synthetics push journeys --project ${project} --url http://localhost:5601 --auth basic-auth`;
126
+
127
+ await this.createFile(
128
+ filename,
129
+ JSON.stringify(pkgJSON, null, 2) + '\n',
130
+ true
131
+ );
132
+ }
133
+
134
+ banner() {
135
+ stdWrite(
136
+ bold(`
137
+ All set, you can run below commands inside: ${this.projectDir}:
138
+
139
+ Run synthetic tests: ${cyan(runCommand(this.pkgManager, 'test'))}
140
+
141
+ Push monitors to Kibana: ${cyan(runCommand(this.pkgManager, 'push'))}
142
+
143
+ ${yellow(
144
+ 'Make sure to update the Kibana url and authentication info before pushing monitors to Kibana.'
145
+ )}
146
+
147
+ Visit https://www.elastic.co/guide/en/observability/master/synthetics-journeys.html to learn more.
148
+ `)
149
+ );
150
+ }
151
+
152
+ async setup() {
153
+ await this.directory();
154
+ await this.package();
155
+ await this.files();
156
+ await this.patchPkgJSON();
157
+ this.banner();
158
+ }
159
+ }
@@ -0,0 +1,41 @@
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
+ }
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,9 @@
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
+ import { MonitorConfig } from './dsl/monitor';
30
31
 
31
32
  /**
32
33
  * Set debug based on DEBUG ENV and -d flags
@@ -91,11 +92,14 @@ export function normalizeOptions(cliArgs: CliArgs): RunOptions {
91
92
  ? readConfig(options.environment, cliArgs.config)
92
93
  : {};
93
94
 
94
- options.params = Object.freeze(merge(config.params, cliArgs.params || {}));
95
-
96
95
  /**
97
- * Favor playwright options passed via cli to inline playwright options
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
98
100
  */
101
+ options.params = Object.freeze(merge(config.params, cliArgs.params || {}));
102
+
99
103
  options.playwrightOptions = merge.all([
100
104
  config.playwrightOptions || {},
101
105
  cliArgs.playwrightOptions || {},
@@ -106,11 +110,70 @@ export function normalizeOptions(cliArgs: CliArgs): RunOptions {
106
110
  },
107
111
  ]);
108
112
 
113
+ const defaults = getDefaultMonitorConfig();
109
114
  if (cliArgs.throttling) {
110
- options.networkConditions = parseNetworkConditions(
111
- cliArgs.throttling as string
112
- );
115
+ const throttleConfig = merge.all([
116
+ defaults.throttling,
117
+ config.monitor?.throttling || {},
118
+ cliArgs.throttling as ThrottlingOptions,
119
+ ]);
120
+ options.throttling = throttleConfig;
121
+ options.networkConditions = getNetworkConditions(throttleConfig);
122
+ } else {
123
+ /**
124
+ * Do not apply throttling when `--no-throttling` flag is passed
125
+ */
126
+ options.throttling = {};
113
127
  }
114
128
 
129
+ options.locations =
130
+ cliArgs.locations ?? config.monitor?.locations ?? defaults.locations;
131
+
132
+ options.schedule =
133
+ cliArgs.schedule ?? config.monitor?.schedule ?? defaults.schedule;
134
+
115
135
  return options;
116
136
  }
137
+
138
+ /**
139
+ * Get the default monitor configuration for all journeys
140
+ */
141
+ export function getDefaultMonitorConfig(): MonitorConfig {
142
+ return {
143
+ throttling: DEFAULT_THROTTLING_OPTIONS,
144
+ locations: ['US East'],
145
+ schedule: 10,
146
+ };
147
+ }
148
+
149
+ /**
150
+ * Parses the throttling CLI settings and also
151
+ * adapts to the format to keep the backwards compatability
152
+ * - Accepts old format `<5d/3u/20l>`
153
+ * - Processess new format otherwise `{download: 5, upload: 3, latency: 20}`
154
+ */
155
+ export function parseThrottling(value: string, prev?: string) {
156
+ const THROTTLING_REGEX = /([0-9]{1,}u)|([0-9]{1,}d)|([0-9]{1,}l)/gm;
157
+ if (THROTTLING_REGEX.test(value)) {
158
+ const throttling: ThrottlingOptions = {};
159
+ const conditions = value.split('/');
160
+
161
+ conditions.forEach(condition => {
162
+ const setting = condition.slice(0, condition.length - 1);
163
+ const token = condition.slice(-1);
164
+ switch (token) {
165
+ case 'd':
166
+ throttling.download = Number(setting);
167
+ break;
168
+ case 'u':
169
+ throttling.upload = Number(setting);
170
+ break;
171
+ case 'l':
172
+ throttling.latency = Number(setting);
173
+ break;
174
+ }
175
+ });
176
+ return throttling;
177
+ }
178
+ return JSON.parse(value || prev);
179
+ }
@@ -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
+ }