@elastic/synthetics 1.0.0-beta.8 → 1.0.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.
Files changed (220) hide show
  1. package/README.md +5 -4
  2. package/dist/cli.js +139 -165
  3. package/dist/cli.js.map +1 -1
  4. package/dist/common_types.d.ts +158 -34
  5. package/dist/common_types.d.ts.map +1 -1
  6. package/dist/config.d.ts +1 -0
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +7 -6
  9. package/dist/config.js.map +1 -1
  10. package/dist/core/browser-service.d.ts +1 -1
  11. package/dist/core/browser-service.d.ts.map +1 -1
  12. package/dist/core/browser-service.js +7 -6
  13. package/dist/core/browser-service.js.map +1 -1
  14. package/dist/core/expect.d.ts +25 -25
  15. package/dist/core/expect.d.ts.map +1 -1
  16. package/dist/core/expect.js.map +1 -1
  17. package/dist/core/gatherer.d.ts +5 -8
  18. package/dist/core/gatherer.d.ts.map +1 -1
  19. package/dist/core/gatherer.js +75 -17
  20. package/dist/core/gatherer.js.map +1 -1
  21. package/dist/core/index.d.ts +5 -1
  22. package/dist/core/index.d.ts.map +1 -1
  23. package/dist/core/index.js +23 -11
  24. package/dist/core/index.js.map +1 -1
  25. package/dist/core/logger.d.ts +0 -1
  26. package/dist/core/logger.d.ts.map +1 -1
  27. package/dist/core/logger.js +10 -17
  28. package/dist/core/logger.js.map +1 -1
  29. package/dist/core/runner.d.ts +12 -63
  30. package/dist/core/runner.d.ts.map +1 -1
  31. package/dist/core/runner.js +159 -92
  32. package/dist/core/runner.js.map +1 -1
  33. package/dist/core/transform.d.ts +37 -0
  34. package/dist/core/transform.d.ts.map +1 -0
  35. package/dist/core/transform.js +148 -0
  36. package/dist/core/transform.js.map +1 -0
  37. package/dist/dsl/index.js +5 -1
  38. package/dist/dsl/index.js.map +1 -1
  39. package/dist/dsl/journey.d.ts +9 -7
  40. package/dist/dsl/journey.d.ts.map +1 -1
  41. package/dist/dsl/journey.js +32 -39
  42. package/dist/dsl/journey.js.map +1 -1
  43. package/dist/dsl/monitor.d.ts +93 -0
  44. package/dist/dsl/monitor.d.ts.map +1 -0
  45. package/dist/dsl/monitor.js +110 -0
  46. package/dist/dsl/monitor.js.map +1 -0
  47. package/dist/dsl/step.d.ts +3 -2
  48. package/dist/dsl/step.d.ts.map +1 -1
  49. package/dist/dsl/step.js +6 -1
  50. package/dist/dsl/step.js.map +1 -1
  51. package/dist/formatter/javascript.d.ts +115 -0
  52. package/dist/formatter/javascript.d.ts.map +1 -0
  53. package/dist/formatter/javascript.js +331 -0
  54. package/dist/formatter/javascript.js.map +1 -0
  55. package/dist/generator/index.d.ts +24 -0
  56. package/dist/generator/index.d.ts.map +1 -0
  57. package/dist/generator/index.js +241 -0
  58. package/dist/generator/index.js.map +1 -0
  59. package/dist/{reporters/reporter.js → generator/utils.d.ts} +5 -3
  60. package/dist/generator/utils.d.ts.map +1 -0
  61. package/dist/generator/utils.js +84 -0
  62. package/dist/generator/utils.js.map +1 -0
  63. package/dist/helpers.d.ts +36 -9
  64. package/dist/helpers.d.ts.map +1 -1
  65. package/dist/helpers.js +170 -24
  66. package/dist/helpers.js.map +1 -1
  67. package/dist/index.d.ts +5 -7
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +5 -26
  70. package/dist/index.js.map +1 -1
  71. package/dist/loader.d.ts +34 -0
  72. package/dist/loader.d.ts.map +1 -0
  73. package/dist/loader.js +153 -0
  74. package/dist/loader.js.map +1 -0
  75. package/dist/locations/index.d.ts +45 -0
  76. package/dist/locations/index.d.ts.map +1 -0
  77. package/dist/locations/index.js +83 -0
  78. package/dist/locations/index.js.map +1 -0
  79. package/dist/{reporters/reporter.d.ts → locations/public-locations.d.ts} +12 -8
  80. package/dist/locations/public-locations.d.ts.map +1 -0
  81. package/dist/locations/public-locations.js +41 -0
  82. package/dist/locations/public-locations.js.map +1 -0
  83. package/dist/options.d.ts +42 -0
  84. package/dist/options.d.ts.map +1 -0
  85. package/dist/options.js +146 -0
  86. package/dist/options.js.map +1 -0
  87. package/dist/plugins/browser-console.d.ts +5 -4
  88. package/dist/plugins/browser-console.d.ts.map +1 -1
  89. package/dist/plugins/browser-console.js +47 -24
  90. package/dist/plugins/browser-console.js.map +1 -1
  91. package/dist/plugins/index.js +5 -1
  92. package/dist/plugins/index.js.map +1 -1
  93. package/dist/plugins/network.d.ts +24 -31
  94. package/dist/plugins/network.d.ts.map +1 -1
  95. package/dist/plugins/network.js +226 -229
  96. package/dist/plugins/network.js.map +1 -1
  97. package/dist/plugins/performance.d.ts +4 -19
  98. package/dist/plugins/performance.d.ts.map +1 -1
  99. package/dist/plugins/performance.js +6 -5
  100. package/dist/plugins/performance.js.map +1 -1
  101. package/dist/plugins/plugin-manager.d.ts +9 -5
  102. package/dist/plugins/plugin-manager.d.ts.map +1 -1
  103. package/dist/plugins/plugin-manager.js +46 -30
  104. package/dist/plugins/plugin-manager.js.map +1 -1
  105. package/dist/plugins/tracing.d.ts +6 -6
  106. package/dist/plugins/tracing.d.ts.map +1 -1
  107. package/dist/plugins/tracing.js +13 -7
  108. package/dist/plugins/tracing.js.map +1 -1
  109. package/dist/push/bundler.d.ts +35 -0
  110. package/dist/push/bundler.d.ts.map +1 -0
  111. package/dist/push/bundler.js +131 -0
  112. package/dist/push/bundler.js.map +1 -0
  113. package/dist/push/index.d.ts +10 -0
  114. package/dist/push/index.d.ts.map +1 -0
  115. package/dist/push/index.js +235 -0
  116. package/dist/push/index.js.map +1 -0
  117. package/dist/push/kibana_api.d.ts +56 -0
  118. package/dist/push/kibana_api.d.ts.map +1 -0
  119. package/dist/push/kibana_api.js +135 -0
  120. package/dist/push/kibana_api.js.map +1 -0
  121. package/dist/push/monitor.d.ts +55 -0
  122. package/dist/push/monitor.d.ts.map +1 -0
  123. package/dist/push/monitor.js +268 -0
  124. package/dist/push/monitor.js.map +1 -0
  125. package/dist/{parse_args.d.ts → push/plugin.d.ts} +9 -6
  126. package/dist/push/plugin.d.ts.map +1 -0
  127. package/dist/push/plugin.js +66 -0
  128. package/dist/push/plugin.js.map +1 -0
  129. package/dist/push/request.d.ts +45 -0
  130. package/dist/push/request.d.ts.map +1 -0
  131. package/dist/push/request.js +109 -0
  132. package/dist/push/request.js.map +1 -0
  133. package/dist/push/utils.d.ts +31 -0
  134. package/dist/push/utils.d.ts.map +1 -0
  135. package/dist/push/utils.js +64 -0
  136. package/dist/push/utils.js.map +1 -0
  137. package/dist/reporters/base.d.ts +14 -6
  138. package/dist/reporters/base.d.ts.map +1 -1
  139. package/dist/reporters/base.js +58 -50
  140. package/dist/reporters/base.js.map +1 -1
  141. package/dist/reporters/index.d.ts +18 -8
  142. package/dist/reporters/index.d.ts.map +1 -1
  143. package/dist/reporters/index.js.map +1 -1
  144. package/dist/reporters/json.d.ts +17 -62
  145. package/dist/reporters/json.d.ts.map +1 -1
  146. package/dist/reporters/json.js +147 -177
  147. package/dist/reporters/json.js.map +1 -1
  148. package/dist/reporters/junit.d.ts +7 -1
  149. package/dist/reporters/junit.d.ts.map +1 -1
  150. package/dist/reporters/junit.js +90 -95
  151. package/dist/reporters/junit.js.map +1 -1
  152. package/dist/sdk/lh-trace-processor.d.ts +35 -9
  153. package/dist/sdk/lh-trace-processor.d.ts.map +1 -1
  154. package/dist/sdk/lh-trace-processor.js +114 -53
  155. package/dist/sdk/lh-trace-processor.js.map +1 -1
  156. package/dist/sdk/trace-metrics.d.ts +4 -4
  157. package/dist/sdk/trace-metrics.d.ts.map +1 -1
  158. package/dist/sdk/trace-metrics.js +3 -4
  159. package/dist/sdk/trace-metrics.js.map +1 -1
  160. package/dist/sdk/trace-processor.d.ts +11 -3
  161. package/dist/sdk/trace-processor.d.ts.map +1 -1
  162. package/dist/sdk/trace-processor.js +17 -9
  163. package/dist/sdk/trace-processor.js.map +1 -1
  164. package/package.json +38 -30
  165. package/src/cli.ts +223 -158
  166. package/src/common_types.ts +191 -34
  167. package/src/config.ts +1 -1
  168. package/src/core/expect.ts +58 -24
  169. package/src/core/gatherer.ts +92 -25
  170. package/src/core/index.ts +36 -15
  171. package/src/core/logger.ts +8 -12
  172. package/src/core/runner.ts +158 -148
  173. package/src/core/transform.ts +160 -0
  174. package/src/dsl/journey.ts +41 -21
  175. package/src/dsl/monitor.ts +152 -0
  176. package/src/dsl/step.ts +9 -2
  177. package/src/formatter/javascript.ts +414 -0
  178. package/src/generator/index.ts +308 -0
  179. package/src/generator/utils.ts +84 -0
  180. package/src/helpers.ts +182 -16
  181. package/src/index.ts +21 -22
  182. package/src/loader.ts +171 -0
  183. package/src/locations/index.ts +95 -0
  184. package/src/{reporters/reporter.ts → locations/public-locations.ts} +12 -9
  185. package/src/options.ts +175 -0
  186. package/src/plugins/browser-console.ts +33 -8
  187. package/src/plugins/network.ts +266 -284
  188. package/src/plugins/performance.ts +6 -22
  189. package/src/plugins/plugin-manager.ts +49 -31
  190. package/src/plugins/tracing.ts +11 -9
  191. package/src/push/bundler.ts +112 -0
  192. package/src/push/index.ts +291 -0
  193. package/src/push/kibana_api.ts +191 -0
  194. package/src/push/monitor.ts +307 -0
  195. package/src/push/plugin.ts +66 -0
  196. package/src/push/request.ts +141 -0
  197. package/src/push/utils.ts +77 -0
  198. package/src/reporters/base.ts +63 -52
  199. package/src/reporters/index.ts +26 -3
  200. package/src/reporters/json.ts +181 -201
  201. package/src/reporters/junit.ts +98 -93
  202. package/src/sdk/lh-trace-processor.ts +132 -68
  203. package/src/sdk/trace-metrics.ts +8 -4
  204. package/src/sdk/trace-processor.ts +28 -13
  205. package/templates/.github/workflows/run-synthetics.yml +27 -0
  206. package/templates/README.md +21 -0
  207. package/templates/journeys/advanced-example-helpers.ts +54 -0
  208. package/templates/journeys/advanced-example.journey.ts +43 -0
  209. package/templates/journeys/example.journey.ts +18 -0
  210. package/templates/lightweight/heartbeat.yml +9 -0
  211. package/templates/synthetics.config.ts +35 -0
  212. package/CHANGELOG.md +0 -181
  213. package/NOTICE.txt +0 -221
  214. package/dist/parse_args.d.ts.map +0 -1
  215. package/dist/parse_args.js +0 -98
  216. package/dist/parse_args.js.map +0 -1
  217. package/dist/reporters/reporter.d.ts.map +0 -1
  218. package/dist/reporters/reporter.js.map +0 -1
  219. package/dist/tsconfig.tsbuildinfo +0 -1895
  220. package/src/parse_args.ts +0 -146
@@ -0,0 +1,308 @@
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
+ // @ts-ignore-next-line: has no exported member 'Input'
31
+ import { prompt, Input } from 'enquirer';
32
+ import {
33
+ getMonitorManagementURL,
34
+ progress,
35
+ write as stdWrite,
36
+ } from '../helpers';
37
+ import {
38
+ getPackageManager,
39
+ replaceTemplates,
40
+ runCommand,
41
+ cloudIDToKibanaURL,
42
+ } from './utils';
43
+ import { formatLocations, getLocations, groupLocations } from '../locations';
44
+ import { ALLOWED_SCHEDULES } from '../dsl/monitor';
45
+ import type { ProjectSettings } from '../common_types';
46
+
47
+ // Templates that are required for setting up new synthetics project
48
+ const templateDir = join(__dirname, '..', '..', 'templates');
49
+
50
+ type PromptOptions = ProjectSettings & {
51
+ locations: Array<string>;
52
+ privateLocations: Array<string>;
53
+ schedule: number;
54
+ };
55
+
56
+ // exported for testing
57
+ export const REGULAR_FILES_PATH = [
58
+ 'journeys/example.journey.ts',
59
+ 'journeys/advanced-example-helpers.ts',
60
+ 'journeys/advanced-example.journey.ts',
61
+ 'lightweight/heartbeat.yml',
62
+ '.github/workflows/run-synthetics.yml',
63
+ 'README.md',
64
+ ];
65
+ export const CONFIG_PATH = 'synthetics.config.ts';
66
+
67
+ export class Generator {
68
+ pkgManager = 'npm';
69
+ constructor(public projectDir: string) {}
70
+
71
+ async directory() {
72
+ progress(
73
+ `Initializing Synthetics project in '${
74
+ relative(process.cwd(), this.projectDir) || '.'
75
+ }'`
76
+ );
77
+ if (!existsSync(this.projectDir)) {
78
+ await mkdir(this.projectDir);
79
+ }
80
+ }
81
+
82
+ async questions() {
83
+ if (process.env.TEST_QUESTIONS) {
84
+ return JSON.parse(process.env.TEST_QUESTIONS);
85
+ }
86
+
87
+ const { onCloud } = await prompt<{ onCloud: string }>({
88
+ type: 'confirm',
89
+ name: 'onCloud',
90
+ initial: 'y',
91
+ message: 'Do you use Elastic Cloud',
92
+ });
93
+ const url = await new Input({
94
+ header: onCloud
95
+ ? yellow(
96
+ 'Get cloud.id from your deployment https://www.elastic.co/guide/en/cloud/current/ec-cloud-id.html'
97
+ )
98
+ : '',
99
+ message: onCloud
100
+ ? 'What is your cloud.id'
101
+ : 'What is the url of your Kibana instance',
102
+ name: 'url',
103
+ required: true,
104
+ result(value) {
105
+ return onCloud ? cloudIDToKibanaURL(value) : value;
106
+ },
107
+ }).run();
108
+
109
+ const auth = await new Input({
110
+ name: 'auth',
111
+ header: yellow(
112
+ `Generate API key from Kibana ${getMonitorManagementURL(url)}`
113
+ ),
114
+ required: true,
115
+ message: 'What is your API key',
116
+ }).run();
117
+
118
+ const allLocations = await getLocations({ url, auth });
119
+ const locChoices = formatLocations(allLocations);
120
+ if (locChoices.length === 0) {
121
+ throw 'Follow the docs to set up your first private locations - https://www.elastic.co/guide/en/observability/current/uptime-set-up-choose-agent.html#private-locations';
122
+ }
123
+
124
+ const monitorQues = [
125
+ {
126
+ type: 'select',
127
+ name: 'locations',
128
+ hint: '(Use <space> to select, <return> to submit)',
129
+ message: 'Select the locations where you want to run monitors',
130
+ choices: locChoices,
131
+ multiple: true,
132
+ validate(value) {
133
+ return value.length === 0 ? `Select at least one option.` : true;
134
+ },
135
+ },
136
+ {
137
+ type: 'select',
138
+ name: 'schedule',
139
+ message: 'Set default schedule in minutes for all monitors',
140
+ initial: 3, // Index of the third array item which is 10 minutes
141
+ choices: ALLOWED_SCHEDULES.map(String),
142
+ required: true,
143
+ result(value) {
144
+ return Number(value) as any;
145
+ },
146
+ },
147
+ {
148
+ type: 'input',
149
+ name: 'id',
150
+ message: 'Choose project id to logically group monitors',
151
+ initial: basename(this.projectDir),
152
+ },
153
+ {
154
+ type: 'input',
155
+ name: 'space',
156
+ message: 'Choose the target Kibana space',
157
+ initial: 'default',
158
+ },
159
+ ];
160
+
161
+ // Split and group private and public locations from the answered list.
162
+ const answers = await prompt<PromptOptions>(monitorQues);
163
+ const { locations, privateLocations } = groupLocations(answers.locations);
164
+ return { ...answers, url, locations, privateLocations };
165
+ }
166
+
167
+ async files(answers: PromptOptions) {
168
+ const fileMap = new Map<string, string>();
169
+
170
+ // Setup Synthetics config file
171
+ fileMap.set(
172
+ CONFIG_PATH,
173
+ replaceTemplates(
174
+ await readFile(join(templateDir, CONFIG_PATH), 'utf-8'),
175
+ answers
176
+ )
177
+ );
178
+
179
+ // Setup non-templated files
180
+ Promise.all(
181
+ REGULAR_FILES_PATH.map(async file => {
182
+ fileMap.set(file, await readFile(join(templateDir, file), 'utf-8'));
183
+ })
184
+ ).catch(e => {
185
+ throw e;
186
+ });
187
+
188
+ // Create files
189
+ for (const [relativePath, content] of fileMap) {
190
+ await this.createFile(relativePath, content);
191
+ }
192
+ }
193
+
194
+ async createFile(relativePath: string, content: string, override = false) {
195
+ const absolutePath = join(this.projectDir, relativePath);
196
+
197
+ if (!override && existsSync(absolutePath)) {
198
+ const { override } = await prompt<{ override: boolean }>({
199
+ type: 'confirm',
200
+ name: 'override',
201
+ message: `File ${relativePath} already exists. Override it?`,
202
+ initial: false,
203
+ });
204
+ if (!override) return;
205
+ }
206
+
207
+ progress(`Writing ${relative(process.cwd(), absolutePath)}.`);
208
+ await mkdir(dirname(absolutePath), { recursive: true });
209
+ await writeFile(absolutePath, content, 'utf-8');
210
+ }
211
+
212
+ async package() {
213
+ this.pkgManager = await getPackageManager(this.projectDir);
214
+ const commands = new Map<string, string>();
215
+ commands.set(
216
+ `Setting up project using ${this.pkgManager == 'yarn' ? 'Yarn' : 'NPM'}`,
217
+ this.pkgManager == 'yarn' ? 'yarn init -y' : 'npm init -y'
218
+ );
219
+
220
+ const pkgName = '@elastic/synthetics';
221
+ commands.set(
222
+ `Installing @elastic/synthetics library`,
223
+ this.pkgManager == 'yarn'
224
+ ? `yarn add -dev ${pkgName} --silent`
225
+ : `npm i -d ${pkgName} --quiet`
226
+ );
227
+
228
+ // Execute commands
229
+ for (const [name, command] of commands) {
230
+ progress(`${name}...`);
231
+ execSync(command, {
232
+ stdio: 'inherit',
233
+ cwd: this.projectDir,
234
+ });
235
+ }
236
+ }
237
+
238
+ async patchPkgJSON() {
239
+ const filename = 'package.json';
240
+ const pkgJSON = JSON.parse(
241
+ await readFile(join(this.projectDir, filename), 'utf-8')
242
+ );
243
+
244
+ if (!pkgJSON.scripts) {
245
+ pkgJSON.scripts = {};
246
+ }
247
+ // Add test command
248
+ if (!pkgJSON.scripts.test) {
249
+ pkgJSON.scripts.test = 'npx @elastic/synthetics journeys';
250
+ }
251
+ // Add push command
252
+ if (!pkgJSON.scripts.push) {
253
+ pkgJSON.scripts.push = 'npx @elastic/synthetics push';
254
+ }
255
+
256
+ await this.createFile(
257
+ filename,
258
+ JSON.stringify(pkgJSON, null, 2) + '\n',
259
+ true
260
+ );
261
+ }
262
+
263
+ async patchGitIgnore() {
264
+ const gitIgnorePath = join(this.projectDir, '.gitignore');
265
+ let gitIgnore = '';
266
+ if (existsSync(gitIgnorePath)) {
267
+ const contents = await readFile(gitIgnorePath, 'utf-8');
268
+ gitIgnore += contents.trimEnd() + '\n';
269
+ }
270
+ if (!gitIgnore.includes('node_modules')) {
271
+ gitIgnore += 'node_modules/\n';
272
+ }
273
+ if (!gitIgnore.includes('.synthetics')) {
274
+ gitIgnore += '.synthetics/\n';
275
+ }
276
+ await writeFile(gitIgnorePath, gitIgnore, 'utf-8');
277
+ }
278
+
279
+ banner() {
280
+ stdWrite(
281
+ bold(`
282
+ All set, you can run below commands inside: ${this.projectDir}:
283
+
284
+ Run synthetic tests: ${cyan(runCommand(this.pkgManager, 'test'))}
285
+
286
+ Push monitors to Kibana: ${cyan(
287
+ 'SYNTHETICS_API_KEY=<value> ' + runCommand(this.pkgManager, 'push')
288
+ )}
289
+
290
+ ${yellow(
291
+ 'Make sure to configure the SYNTHETICS_API_KEY before pushing monitors to Kibana.'
292
+ )}
293
+
294
+ Visit https://www.elastic.co/guide/en/observability/current/synthetic-run-tests.html to learn more.
295
+ `)
296
+ );
297
+ }
298
+
299
+ async setup() {
300
+ await this.directory();
301
+ const answers = await this.questions();
302
+ await this.package();
303
+ await this.files(answers);
304
+ await this.patchPkgJSON();
305
+ await this.patchGitIgnore();
306
+ this.banner();
307
+ }
308
+ }
@@ -0,0 +1,84 @@
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, values: Record<string, any>) {
44
+ for (const key in values) {
45
+ const finalValue = values[key];
46
+ input = input.replace(new RegExp(`'{{` + key + `}}'`, 'g'), () => {
47
+ if (Array.isArray(finalValue)) {
48
+ return String(finalValue)
49
+ .split(',')
50
+ .filter(Boolean)
51
+ .map(f => `'${f}'`);
52
+ }
53
+ if (typeof finalValue == 'number') {
54
+ return Number(finalValue);
55
+ }
56
+ if (typeof finalValue == 'string') {
57
+ return `'${finalValue}'`;
58
+ }
59
+ return finalValue;
60
+ });
61
+ }
62
+ return input;
63
+ }
64
+
65
+ export function cloudIDToKibanaURL(id: string) {
66
+ const ID_SEPARATOR = ':';
67
+ const VALUE_SEPARATOR = '$';
68
+ // Ignore values before the separator
69
+ const index = id.lastIndexOf(ID_SEPARATOR);
70
+ if (index >= 0) {
71
+ id = id.substring(index + 1);
72
+ }
73
+
74
+ // Decode the base64 string
75
+ const decoded = Buffer.from(id, 'base64').toString();
76
+ const words = decoded.split(VALUE_SEPARATOR);
77
+
78
+ // construct the kibana and ES urls from decoded value
79
+ const [host, port = '443'] = words[0].split(ID_SEPARATOR);
80
+ const [kibanaId, kibanaPort = port] = words[2].split(ID_SEPARATOR);
81
+ const kibanaURL = `https://${kibanaId}.${host}:${kibanaPort}`;
82
+
83
+ return kibanaURL;
84
+ }
package/src/helpers.ts CHANGED
@@ -23,21 +23,21 @@
23
23
  *
24
24
  */
25
25
 
26
- import { red, green, yellow, cyan } from 'kleur/colors';
26
+ import { red, green, yellow, cyan, bold, grey } from 'kleur/colors';
27
27
  import os from 'os';
28
28
  import { resolve, join, dirname } from 'path';
29
29
  import fs from 'fs';
30
- import { promisify } from 'util';
30
+ import { lstat, readdir } from 'fs/promises';
31
31
  import { performance } from 'perf_hooks';
32
- import { HooksArgs, HooksCallback } from './common_types';
33
-
34
- const lstatAsync = promisify(fs.lstat);
35
- const readdirAsync = promisify(fs.readdir);
36
-
37
- export const readFileAsync = promisify(fs.readFile);
38
- export const writeFileAsync = promisify(fs.writeFile);
39
- export const rmdirAsync = promisify(fs.rmdir);
40
- export const mkdirAsync = promisify(fs.mkdir);
32
+ import sourceMapSupport from 'source-map-support';
33
+ import {
34
+ HooksArgs,
35
+ HooksCallback,
36
+ NetworkConditions,
37
+ Location,
38
+ ThrottlingOptions,
39
+ } from './common_types';
40
+ import micromatch from 'micromatch';
41
41
 
42
42
  const SEPARATOR = '\n';
43
43
 
@@ -55,6 +55,7 @@ const NO_UTF8_SUPPORT = process.platform === 'win32';
55
55
  export const symbols = {
56
56
  warning: yellow(NO_UTF8_SUPPORT ? '!' : '⚠'),
57
57
  skipped: cyan('-'),
58
+ progress: cyan('>'),
58
59
  succeeded: green(NO_UTF8_SUPPORT ? 'ok' : '✓'),
59
60
  failed: red(NO_UTF8_SUPPORT ? 'x' : '✖'),
60
61
  };
@@ -170,11 +171,11 @@ export async function totalist(
170
171
  pre = ''
171
172
  ) {
172
173
  dir = resolve('.', dir);
173
- await readdirAsync(dir).then(arr => {
174
+ await readdir(dir).then(arr => {
174
175
  return Promise.all(
175
176
  arr.map(str => {
176
177
  const abs = join(dir, str);
177
- return lstatAsync(abs).then(stats =>
178
+ return lstat(abs).then(stats =>
178
179
  stats.isDirectory()
179
180
  ? totalist(abs, callback, join(pre, str))
180
181
  : callback(join(pre, str), abs)
@@ -233,10 +234,21 @@ export function rewriteErrorStack(stack: string, indexes: [number, number]) {
233
234
  return stack;
234
235
  }
235
236
 
236
- export function formatError(error: Error) {
237
- if (!(error instanceof Error)) {
237
+ // formatError prefers receiving proper Errors, but since at runtime
238
+ // non Error exceptions can be thrown, it tolerates though. The
239
+ // redundant type Error | any expresses that.
240
+ export function formatError(error: Error | any) {
241
+ if (error === undefined || error === null) {
238
242
  return;
239
243
  }
244
+
245
+ if (!(error instanceof Error)) {
246
+ return {
247
+ message: `Error "${error}" received, with type "${typeof error}". (Do not throw exceptions without using \`new Error("my message")\`)`,
248
+ name: '',
249
+ stack: '',
250
+ };
251
+ }
240
252
  const { name, message, stack } = error;
241
253
  const indexes = findPWLogsIndexes(message);
242
254
  return {
@@ -247,13 +259,167 @@ export function formatError(error: Error) {
247
259
  }
248
260
 
249
261
  const cwd = process.cwd();
262
+ /**
263
+ * All the settings that are related to the Synthetics is stored
264
+ * under this directory
265
+ * Examples: Screenshots, Project setup
266
+ */
267
+ export const SYNTHETICS_PATH = join(cwd, '.synthetics');
250
268
  /**
251
269
  * Synthetics cache path that is based on the process id to make sure
252
270
  * each process does not modify the caching layer used by other process
253
271
  * once we move to executing journeys in parallel
254
272
  */
255
- export const CACHE_PATH = join(cwd, '.synthetics', process.pid.toString());
273
+ export const CACHE_PATH = join(SYNTHETICS_PATH, process.pid.toString());
256
274
 
257
275
  export function getDurationInUs(duration: number) {
258
276
  return Math.trunc(duration * 1e6);
259
277
  }
278
+
279
+ export function megabitsToBytes(megabytes: number) {
280
+ return (megabytes * 1024 * 1024) / 8;
281
+ }
282
+
283
+ export const DEFAULT_THROTTLING_OPTIONS: ThrottlingOptions = {
284
+ download: 5,
285
+ upload: 3,
286
+ latency: 20,
287
+ };
288
+
289
+ /**
290
+ * Transforms the CLI throttling arguments in to format
291
+ * expected by Chrome devtools protocol NetworkConditions
292
+ */
293
+ export function getNetworkConditions(
294
+ throttlingOpts: ThrottlingOptions
295
+ ): NetworkConditions {
296
+ return {
297
+ downloadThroughput: megabitsToBytes(throttlingOpts.download),
298
+ uploadThroughput: megabitsToBytes(throttlingOpts.upload), // Devtools CDP expects format to be in bytes/second
299
+ latency: throttlingOpts.latency, // milliseconds,
300
+ offline: false,
301
+ };
302
+ }
303
+
304
+ export const THROTTLING_WARNING_MSG = `Throttling may not be active when the tests run - see
305
+ https://github.com/elastic/synthetics/blob/main/docs/throttling.md for more details`;
306
+
307
+ const dstackTraceLimit = 10;
308
+
309
+ // Uses the V8 Stacktrace API to get the function location
310
+ // information - https://v8.dev/docs/stack-trace-api#customizing-stack-traces
311
+ export function wrapFnWithLocation<A extends unknown[], R>(
312
+ func: (location: Location, ...args: A) => R
313
+ ): (...args: A) => R {
314
+ return (...args) => {
315
+ const _prepareStackTrace = Error.prepareStackTrace;
316
+ Error.prepareStackTrace = (_, stackFrames) => {
317
+ // Deafult CallSite would not map to the original transpiled source
318
+ // correctly, So we use source-map-support to map the CallSite to the
319
+ // original source from our cached source map
320
+ const frame: NodeJS.CallSite = sourceMapSupport.wrapCallSite(
321
+ stackFrames[1]
322
+ );
323
+ return {
324
+ file: frame.getFileName(),
325
+ line: frame.getLineNumber(),
326
+ column: frame.getColumnNumber(),
327
+ };
328
+ };
329
+ Error.stackTraceLimit = 2;
330
+ const obj: { stack: Location } = {} as any;
331
+ Error.captureStackTrace(obj);
332
+ const location = obj.stack;
333
+ Error.stackTraceLimit = dstackTraceLimit;
334
+ Error.prepareStackTrace = _prepareStackTrace;
335
+ return func(location, ...args);
336
+ };
337
+ }
338
+
339
+ // Safely parse ND JSON (Newline delimitted JSON) chunks
340
+ export function safeNDJSONParse(data: string | string[]) {
341
+ // data may not be at proper newline boundaries, so we make sure everything is split
342
+ // on proper newlines
343
+ const chunks = Array.isArray(data) ? data : [data];
344
+ const lines = chunks.join('\n').split(/\r?\n/);
345
+ return lines
346
+ .filter(l => l.match(/\S/)) // remove blank lines
347
+ .map(line => {
348
+ try {
349
+ return JSON.parse(line);
350
+ } catch (e) {
351
+ throw `Error ${e} could not parse data '${line}'`;
352
+ }
353
+ });
354
+ }
355
+
356
+ // Console helpers
357
+ export function write(message: string, live?: boolean) {
358
+ process.stderr.write(message + (live ? '\r' : '\n'));
359
+ }
360
+
361
+ export function progress(message: string) {
362
+ write(cyan(bold(`${symbols.progress} ${message}`)));
363
+ }
364
+
365
+ export async function liveProgress(promise: Promise<any>, message: string) {
366
+ const start = now();
367
+ const interval = setInterval(() => {
368
+ apiProgress(`${message} (${Math.trunc(now() - start)}ms)`, true);
369
+ }, 500);
370
+ promise.finally(() => clearInterval(interval));
371
+ const result = await promise;
372
+ apiProgress(`${message} (${Math.trunc(now() - start)}ms)`);
373
+ return result;
374
+ }
375
+
376
+ export function apiProgress(message: string, live = false) {
377
+ write(grey(`> ${message}`), live);
378
+ }
379
+
380
+ export function error(message: string) {
381
+ write(red(message));
382
+ }
383
+
384
+ export function done(message: string) {
385
+ write(bold(green(`${symbols['succeeded']} ${message}`)));
386
+ }
387
+
388
+ export function warn(message: string) {
389
+ write(bold(yellow(`${symbols['warning']} ${message}`)));
390
+ }
391
+
392
+ export function removeTrailingSlash(url: string) {
393
+ return url.replace(/\/+$/, '');
394
+ }
395
+
396
+ export function getMonitorManagementURL(url) {
397
+ return removeTrailingSlash(url) + '/app/uptime/manage-monitors/all';
398
+ }
399
+
400
+ /**
401
+ * Matches tests based on the provided args. Proitize tags over match
402
+ * - tags pattern that matches only tags
403
+ * - match pattern that matches both name and tags
404
+ */
405
+ export function isMatch(
406
+ tags: Array<string>,
407
+ name: string,
408
+ tagsPattern?: Array<string>,
409
+ matchPattern?: string
410
+ ) {
411
+ if (tagsPattern) {
412
+ return tagsMatch(tags, tagsPattern);
413
+ }
414
+ if (matchPattern) {
415
+ return (
416
+ micromatch.isMatch(name, matchPattern) || tagsMatch(tags, matchPattern)
417
+ );
418
+ }
419
+ return true;
420
+ }
421
+
422
+ export function tagsMatch(tags, pattern) {
423
+ const matchess = micromatch(tags || ['*'], pattern);
424
+ return matchess.length > 0;
425
+ }
package/src/index.ts CHANGED
@@ -24,35 +24,24 @@
24
24
  */
25
25
 
26
26
  import { runner } from './core';
27
- import { RunOptions } from './core/runner';
28
- import { setLogger } from './core/logger';
29
- import sourceMapSupport from 'source-map-support';
27
+ import { RunOptions } from './common_types';
30
28
 
31
29
  export async function run(options: RunOptions) {
32
- /**
33
- * Install source map support
34
- */
35
- sourceMapSupport.install({
36
- environment: 'node',
37
- });
38
- /**
39
- * set up logger with appropriate file descriptor
40
- * to capture all the DEBUG logs when run through heartbeat
41
- */
42
- setLogger(options.outfd);
43
-
44
- try {
45
- return await runner.run(options);
46
- } catch (e) {
47
- console.error('Failed to run the test', e);
48
- process.exit(1);
49
- }
30
+ return runner.run(options);
50
31
  }
51
32
 
52
33
  /**
53
34
  * Export all core module functions
54
35
  */
55
- 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';
56
45
  export { expect } from './core/expect';
57
46
  /**
58
47
  * Export all the driver related types to be consumed
@@ -63,6 +52,7 @@ export type {
63
52
  ChromiumBrowser,
64
53
  ChromiumBrowserContext,
65
54
  CDPSession,
55
+ APIRequestContext,
66
56
  } from 'playwright-chromium';
67
57
 
68
58
  /**
@@ -72,3 +62,12 @@ export type { default as Runner } from './core/runner';
72
62
  export type { Reporter, ReporterOptions } from './reporters';
73
63
 
74
64
  export type { SyntheticsConfig } from './common_types';
65
+
66
+ export type {
67
+ Action,
68
+ ActionInContext,
69
+ Signal,
70
+ Step,
71
+ Steps,
72
+ actionTitle,
73
+ } from './formatter/javascript';