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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/README.md +4 -3
  2. package/dist/cli.js +123 -161
  3. package/dist/cli.js.map +1 -1
  4. package/dist/common_types.d.ts +159 -34
  5. package/dist/common_types.d.ts.map +1 -1
  6. package/dist/config.d.ts +2 -5
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +5 -5
  9. package/dist/config.js.map +1 -1
  10. package/dist/core/browser-service.js +5 -5
  11. package/dist/core/browser-service.js.map +1 -1
  12. package/dist/core/expect.d.ts +25 -25
  13. package/dist/core/expect.d.ts.map +1 -1
  14. package/dist/core/expect.js.map +1 -1
  15. package/dist/core/gatherer.d.ts +4 -8
  16. package/dist/core/gatherer.d.ts.map +1 -1
  17. package/dist/core/gatherer.js +49 -15
  18. package/dist/core/gatherer.js.map +1 -1
  19. package/dist/core/index.d.ts +5 -1
  20. package/dist/core/index.d.ts.map +1 -1
  21. package/dist/core/index.js +23 -11
  22. package/dist/core/index.js.map +1 -1
  23. package/dist/core/logger.d.ts +0 -1
  24. package/dist/core/logger.d.ts.map +1 -1
  25. package/dist/core/logger.js +3 -16
  26. package/dist/core/logger.js.map +1 -1
  27. package/dist/core/runner.d.ts +21 -65
  28. package/dist/core/runner.d.ts.map +1 -1
  29. package/dist/core/runner.js +212 -93
  30. package/dist/core/runner.js.map +1 -1
  31. package/dist/dsl/index.js +5 -1
  32. package/dist/dsl/index.js.map +1 -1
  33. package/dist/dsl/journey.d.ts +9 -4
  34. package/dist/dsl/journey.d.ts.map +1 -1
  35. package/dist/dsl/journey.js +27 -7
  36. package/dist/dsl/journey.js.map +1 -1
  37. package/dist/dsl/monitor.d.ts +66 -0
  38. package/dist/dsl/monitor.d.ts.map +1 -0
  39. package/dist/dsl/monitor.js +63 -0
  40. package/dist/dsl/monitor.js.map +1 -0
  41. package/dist/dsl/step.d.ts +3 -2
  42. package/dist/dsl/step.d.ts.map +1 -1
  43. package/dist/dsl/step.js +2 -1
  44. package/dist/dsl/step.js.map +1 -1
  45. package/dist/formatter/javascript.d.ts +98 -0
  46. package/dist/formatter/javascript.d.ts.map +1 -0
  47. package/dist/formatter/javascript.js +295 -0
  48. package/dist/formatter/javascript.js.map +1 -0
  49. package/dist/generator/index.d.ts +29 -0
  50. package/dist/generator/index.d.ts.map +1 -0
  51. package/dist/generator/index.js +240 -0
  52. package/dist/generator/index.js.map +1 -0
  53. package/dist/{reporters/reporter.js → generator/utils.d.ts} +5 -3
  54. package/dist/generator/utils.d.ts.map +1 -0
  55. package/dist/generator/utils.js +80 -0
  56. package/dist/generator/utils.js.map +1 -0
  57. package/dist/helpers.d.ts +24 -1
  58. package/dist/helpers.d.ts.map +1 -1
  59. package/dist/helpers.js +126 -19
  60. package/dist/helpers.js.map +1 -1
  61. package/dist/index.d.ts +6 -7
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +5 -26
  64. package/dist/index.js.map +1 -1
  65. package/dist/{parse_args.d.ts → loader.d.ts} +2 -5
  66. package/dist/loader.d.ts.map +1 -0
  67. package/dist/loader.js +152 -0
  68. package/dist/loader.js.map +1 -0
  69. package/dist/locations/index.d.ts +45 -0
  70. package/dist/locations/index.d.ts.map +1 -0
  71. package/dist/locations/index.js +90 -0
  72. package/dist/locations/index.js.map +1 -0
  73. package/dist/{reporters/reporter.d.ts → locations/public-locations.d.ts} +12 -8
  74. package/dist/locations/public-locations.d.ts.map +1 -0
  75. package/dist/locations/public-locations.js +41 -0
  76. package/dist/locations/public-locations.js.map +1 -0
  77. package/dist/options.d.ts +41 -0
  78. package/dist/options.d.ts.map +1 -0
  79. package/dist/options.js +182 -0
  80. package/dist/options.js.map +1 -0
  81. package/dist/plugins/browser-console.d.ts +5 -4
  82. package/dist/plugins/browser-console.d.ts.map +1 -1
  83. package/dist/plugins/browser-console.js +27 -8
  84. package/dist/plugins/browser-console.js.map +1 -1
  85. package/dist/plugins/index.js +5 -1
  86. package/dist/plugins/index.js.map +1 -1
  87. package/dist/plugins/network.d.ts +20 -33
  88. package/dist/plugins/network.d.ts.map +1 -1
  89. package/dist/plugins/network.js +173 -214
  90. package/dist/plugins/network.js.map +1 -1
  91. package/dist/plugins/performance.d.ts +4 -19
  92. package/dist/plugins/performance.d.ts.map +1 -1
  93. package/dist/plugins/performance.js +5 -5
  94. package/dist/plugins/performance.js.map +1 -1
  95. package/dist/plugins/plugin-manager.d.ts +9 -5
  96. package/dist/plugins/plugin-manager.d.ts.map +1 -1
  97. package/dist/plugins/plugin-manager.js +44 -29
  98. package/dist/plugins/plugin-manager.js.map +1 -1
  99. package/dist/plugins/tracing.d.ts +6 -6
  100. package/dist/plugins/tracing.d.ts.map +1 -1
  101. package/dist/plugins/tracing.js +8 -7
  102. package/dist/plugins/tracing.js.map +1 -1
  103. package/dist/push/bundler.d.ts +34 -0
  104. package/dist/push/bundler.d.ts.map +1 -0
  105. package/dist/push/bundler.js +123 -0
  106. package/dist/push/bundler.js.map +1 -0
  107. package/dist/push/index.d.ts +33 -0
  108. package/dist/push/index.d.ts.map +1 -0
  109. package/dist/push/index.js +174 -0
  110. package/dist/push/index.js.map +1 -0
  111. package/dist/push/monitor.d.ts +34 -0
  112. package/dist/push/monitor.d.ts.map +1 -0
  113. package/dist/push/monitor.js +78 -0
  114. package/dist/push/monitor.js.map +1 -0
  115. package/{src/reporters/reporter.ts → dist/push/plugin.d.ts} +8 -10
  116. package/dist/push/plugin.d.ts.map +1 -0
  117. package/dist/push/plugin.js +133 -0
  118. package/dist/push/plugin.js.map +1 -0
  119. package/dist/push/request.d.ts +43 -0
  120. package/dist/push/request.d.ts.map +1 -0
  121. package/dist/push/request.js +83 -0
  122. package/dist/push/request.js.map +1 -0
  123. package/dist/reporters/base.d.ts +14 -6
  124. package/dist/reporters/base.d.ts.map +1 -1
  125. package/dist/reporters/base.js +54 -48
  126. package/dist/reporters/base.js.map +1 -1
  127. package/dist/reporters/index.d.ts +18 -8
  128. package/dist/reporters/index.d.ts.map +1 -1
  129. package/dist/reporters/index.js.map +1 -1
  130. package/dist/reporters/json.d.ts +18 -67
  131. package/dist/reporters/json.d.ts.map +1 -1
  132. package/dist/reporters/json.js +153 -175
  133. package/dist/reporters/json.js.map +1 -1
  134. package/dist/reporters/junit.d.ts +7 -1
  135. package/dist/reporters/junit.d.ts.map +1 -1
  136. package/dist/reporters/junit.js +94 -89
  137. package/dist/reporters/junit.js.map +1 -1
  138. package/dist/sdk/lh-trace-processor.d.ts +35 -9
  139. package/dist/sdk/lh-trace-processor.d.ts.map +1 -1
  140. package/dist/sdk/lh-trace-processor.js +114 -53
  141. package/dist/sdk/lh-trace-processor.js.map +1 -1
  142. package/dist/sdk/trace-metrics.d.ts +4 -4
  143. package/dist/sdk/trace-metrics.d.ts.map +1 -1
  144. package/dist/sdk/trace-metrics.js +5 -6
  145. package/dist/sdk/trace-metrics.js.map +1 -1
  146. package/dist/sdk/trace-processor.d.ts +11 -3
  147. package/dist/sdk/trace-processor.d.ts.map +1 -1
  148. package/dist/sdk/trace-processor.js +17 -9
  149. package/dist/sdk/trace-processor.js.map +1 -1
  150. package/dist/tsconfig.tsbuildinfo +1 -1888
  151. package/package.json +32 -20
  152. package/src/cli.ts +205 -152
  153. package/src/common_types.ts +192 -34
  154. package/src/config.ts +2 -5
  155. package/src/core/expect.ts +58 -24
  156. package/src/core/gatherer.ts +59 -24
  157. package/src/core/index.ts +36 -15
  158. package/src/core/logger.ts +1 -12
  159. package/src/core/runner.ts +215 -152
  160. package/src/dsl/journey.ts +37 -6
  161. package/src/dsl/monitor.ts +88 -0
  162. package/src/dsl/step.ts +9 -2
  163. package/src/formatter/javascript.ts +367 -0
  164. package/src/generator/index.ts +316 -0
  165. package/src/generator/utils.ts +80 -0
  166. package/src/helpers.ts +132 -12
  167. package/src/index.ts +22 -22
  168. package/src/loader.ts +171 -0
  169. package/src/locations/index.ts +108 -0
  170. package/src/locations/public-locations.ts +38 -0
  171. package/src/options.ts +211 -0
  172. package/src/plugins/browser-console.ts +30 -8
  173. package/src/plugins/network.ts +208 -267
  174. package/src/plugins/performance.ts +6 -22
  175. package/src/plugins/plugin-manager.ts +49 -31
  176. package/src/plugins/tracing.ts +8 -9
  177. package/src/push/bundler.ts +100 -0
  178. package/src/push/index.ts +202 -0
  179. package/src/push/monitor.ts +96 -0
  180. package/src/push/plugin.ts +119 -0
  181. package/src/push/request.ts +103 -0
  182. package/src/reporters/base.ts +63 -52
  183. package/src/reporters/index.ts +26 -3
  184. package/src/reporters/json.ts +203 -206
  185. package/src/reporters/junit.ts +98 -93
  186. package/src/sdk/lh-trace-processor.ts +132 -68
  187. package/src/sdk/trace-metrics.ts +10 -6
  188. package/src/sdk/trace-processor.ts +28 -13
  189. package/templates/.github/workflows/run-synthetics.yml +26 -0
  190. package/templates/README.md +21 -0
  191. package/templates/journeys/advanced-example-helpers.ts +54 -0
  192. package/templates/journeys/advanced-example.journey.ts +43 -0
  193. package/templates/journeys/example.journey.ts +18 -0
  194. package/templates/synthetics.config.ts +27 -0
  195. package/CHANGELOG.md +0 -102
  196. package/NOTICE.txt +0 -221
  197. package/dist/parse_args.d.ts.map +0 -1
  198. package/dist/parse_args.js +0 -89
  199. package/dist/parse_args.js.map +0 -1
  200. package/dist/reporters/reporter.d.ts.map +0 -1
  201. package/dist/reporters/reporter.js.map +0 -1
  202. package/src/parse_args.ts +0 -127
@@ -23,7 +23,7 @@
23
23
  *
24
24
  */
25
25
 
26
- import { PluginOutput } from '../common_types';
26
+ import { PluginOutput, Driver } from '../common_types';
27
27
  import {
28
28
  BrowserConsole,
29
29
  NetworkManager,
@@ -31,7 +31,6 @@ import {
31
31
  Tracing,
32
32
  TraceOptions,
33
33
  } from './';
34
- import { Driver } from '../core/gatherer';
35
34
  import { Step } from '../dsl';
36
35
 
37
36
  type PluginType = 'network' | 'trace' | 'performance' | 'browserconsole';
@@ -39,59 +38,78 @@ type Plugin = NetworkManager | Tracing | PerformanceManager | BrowserConsole;
39
38
  type PluginOptions = TraceOptions;
40
39
 
41
40
  export class PluginManager {
42
- protected plugins = new Map<string, Plugin>();
43
-
41
+ protected plugins = new Map<PluginType, Plugin>();
42
+ public PLUGIN_TYPES: Array<PluginType> = [
43
+ 'network',
44
+ 'trace',
45
+ 'performance',
46
+ 'browserconsole',
47
+ ];
44
48
  constructor(private driver: Driver) {}
45
49
 
46
- async start(type: PluginType, options?: PluginOptions) {
50
+ register(type: PluginType, options: PluginOptions) {
47
51
  let instance: Plugin;
48
52
  switch (type) {
49
53
  case 'network':
50
- instance = new NetworkManager();
51
- await instance.start(this.driver.client);
54
+ instance = new NetworkManager(this.driver);
52
55
  break;
53
56
  case 'trace':
54
- instance = new Tracing(options);
55
- await instance.start(this.driver.client);
57
+ instance = new Tracing(this.driver, options);
56
58
  break;
57
59
  case 'performance':
58
- instance = new PerformanceManager(this.driver.client);
59
- instance.start();
60
+ instance = new PerformanceManager(this.driver);
60
61
  break;
61
62
  case 'browserconsole':
62
- instance = new BrowserConsole(this.driver.page);
63
- instance.start();
63
+ instance = new BrowserConsole(this.driver);
64
64
  break;
65
65
  }
66
+ instance && this.plugins.set(type, instance);
67
+ return instance;
68
+ }
69
+
70
+ registerAll(options: PluginOptions) {
71
+ for (const type of this.PLUGIN_TYPES) {
72
+ this.register(type, options);
73
+ }
74
+ }
75
+
76
+ unregisterAll() {
77
+ for (const type of this.PLUGIN_TYPES) {
78
+ this.plugins.delete(type);
79
+ }
80
+ }
81
+
82
+ async stop(type: PluginType) {
83
+ const instance = this.plugins.get(type);
84
+ if (instance) {
85
+ return await instance.stop();
86
+ }
87
+ return {};
88
+ }
66
89
 
67
- this.plugins.set(instance.constructor.name, instance);
90
+ async start(type: PluginType) {
91
+ const instance = this.plugins.get(type);
92
+ instance && (await instance.start());
68
93
  return instance;
69
94
  }
70
95
 
71
- get<T extends Plugin>(Type: new (...args: any[]) => T): T {
72
- return this.plugins.get(Type.name) as T;
96
+ get(type: PluginType) {
97
+ return this.plugins.get(type);
73
98
  }
74
99
 
75
100
  onStep(step: Step) {
76
- this.get(BrowserConsole) && (this.get(BrowserConsole)._currentStep = step);
77
- this.get(NetworkManager) && (this.get(NetworkManager)._currentStep = step);
101
+ (this.get('browserconsole') as BrowserConsole)._currentStep = step;
102
+ (this.get('network') as NetworkManager)._currentStep = step;
78
103
  }
79
104
 
80
- async output(): Promise<PluginOutput> {
105
+ async output() {
81
106
  const data: PluginOutput = {};
82
- try {
83
- for (const [, plugin] of this.plugins) {
84
- if (plugin instanceof NetworkManager) {
85
- data.networkinfo = plugin.stop();
86
- } else if (plugin instanceof Tracing) {
87
- const result = await plugin.stop(this.driver.client);
88
- Object.assign(data, { ...result });
89
- } else if (plugin instanceof BrowserConsole) {
90
- data.browserconsole = plugin.stop();
91
- }
107
+ for (const [, plugin] of this.plugins) {
108
+ if (plugin instanceof NetworkManager) {
109
+ data.networkinfo = await plugin.stop();
110
+ } else if (plugin instanceof BrowserConsole) {
111
+ data.browserconsole = plugin.stop();
92
112
  }
93
- } catch (e) {
94
- console.error('Error capturing data', e.message);
95
113
  }
96
114
  return data;
97
115
  }
@@ -23,8 +23,7 @@
23
23
  *
24
24
  */
25
25
 
26
- import { CDPSession } from 'playwright-chromium';
27
- import { PluginOutput } from '../common_types';
26
+ import { Driver, PluginOutput } from '../common_types';
28
27
  import { Filmstrips } from '../sdk/trace-metrics';
29
28
  import { TraceEvent, TraceProcessor } from '../sdk/trace-processor';
30
29
 
@@ -38,9 +37,9 @@ export type TraceOptions = {
38
37
  * https://chromedevtools.github.io/devtools-protocol/tot/Tracing/
39
38
  */
40
39
  export class Tracing {
41
- constructor(public options: TraceOptions) {}
40
+ constructor(private driver: Driver, private options: TraceOptions) {}
42
41
 
43
- async start(client: CDPSession) {
42
+ async start() {
44
43
  const includedCategories = [
45
44
  // exclude all default categories
46
45
  '-*',
@@ -63,21 +62,21 @@ export class Tracing {
63
62
  'disabled-by-default-devtools.timeline'
64
63
  );
65
64
  }
66
- await client.send('Tracing.start', {
65
+ await this.driver.client.send('Tracing.start', {
67
66
  /**
68
67
  * Using `ReportEvents` makes gathering trace events
69
68
  * much faster as opposed to using `ReturnAsStream` mode
70
69
  */
71
70
  transferMode: 'ReportEvents',
72
- traceConfig: {
73
- includedCategories,
74
- },
71
+ categories: includedCategories.join(','),
72
+ options: 'sampling-frequency=10000', // 1000 is default
75
73
  });
76
74
  }
77
75
 
78
- async stop(client: CDPSession) {
76
+ async stop() {
79
77
  const events = [];
80
78
  const collectListener = payload => events.push(...payload.value);
79
+ const { client } = this.driver;
81
80
  client.on('Tracing.dataCollected', collectListener);
82
81
 
83
82
  const [traceEvents] = await Promise.all([
@@ -0,0 +1,100 @@
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
+ const result = await esbuild.build(options);
56
+ if (result.errors.length > 0) {
57
+ throw result.errors;
58
+ }
59
+ this.moduleMap.set(absPath, result.outputFiles[0].text);
60
+ }
61
+
62
+ async zip(outputPath: string) {
63
+ return new Promise((fulfill, reject) => {
64
+ const output = createWriteStream(outputPath);
65
+ const archive = archiver('zip', {
66
+ zlib: { level: 9 },
67
+ });
68
+ archive.on('error', reject);
69
+ output.on('close', fulfill);
70
+ archive.pipe(output);
71
+ for (const [path, content] of this.moduleMap.entries()) {
72
+ const relativePath = relativeToCwd(path);
73
+ // Date is fixed to Unix epoch so the file metadata is
74
+ // not modified everytime when files are bundled
75
+ archive.append(content, {
76
+ name: relativePath,
77
+ date: new Date('1970-01-01'),
78
+ });
79
+ }
80
+ archive.finalize();
81
+ });
82
+ }
83
+
84
+ async build(entry: string, output: string) {
85
+ await this.prepare(entry);
86
+ await this.zip(output);
87
+ const data = await this.encode(output);
88
+ await this.cleanup(output);
89
+ return data;
90
+ }
91
+
92
+ async encode(outputPath: string) {
93
+ return await readFile(outputPath, 'base64');
94
+ }
95
+
96
+ async cleanup(outputPath: string) {
97
+ this.moduleMap = new Map<string, string>();
98
+ await unlink(outputPath);
99
+ }
100
+ }
@@ -0,0 +1,202 @@
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 { join } from 'path';
27
+ import { existsSync } from 'fs';
28
+ import { readFile, writeFile } from 'fs/promises';
29
+ import { prompt } from 'enquirer';
30
+ import { bold, yellow } from 'kleur/colors';
31
+ import {
32
+ ok,
33
+ formatAPIError,
34
+ formatFailedMonitors,
35
+ formatNotFoundError,
36
+ formatStaleMonitors,
37
+ } from './request';
38
+ import { buildMonitorSchema, createMonitors } from './monitor';
39
+ import { ProjectSettings } from '../generator';
40
+ import { Monitor } from '../dsl/monitor';
41
+ import {
42
+ progress,
43
+ write,
44
+ error,
45
+ SYNTHETICS_PATH,
46
+ aborted,
47
+ indent,
48
+ safeNDJSONParse,
49
+ done,
50
+ } from '../helpers';
51
+ import type { PushOptions } from '../common_types';
52
+
53
+ export async function push(monitors: Monitor[], options: PushOptions) {
54
+ if (monitors.length === 0) {
55
+ throw 'No Monitors found';
56
+ }
57
+
58
+ const duplicates = trackDuplicates(monitors);
59
+ if (duplicates.size > 0) {
60
+ throw error(formatDuplicateError(duplicates));
61
+ }
62
+
63
+ progress(`preparing all monitors`);
64
+ const schemas = await buildMonitorSchema(monitors);
65
+ try {
66
+ progress(`creating all monitors`);
67
+ const { body, statusCode } = await createMonitors(schemas, options);
68
+ if (statusCode === 404) {
69
+ throw formatNotFoundError(await body.text());
70
+ }
71
+ if (!ok(statusCode)) {
72
+ const { error, message } = await body.json();
73
+ throw formatAPIError(statusCode, error, message);
74
+ }
75
+ body.setEncoding('utf-8');
76
+ for await (const data of body) {
77
+ // Its kind of hacky for now where Kibana streams the response by
78
+ // writing the data as NDJSON events (data can be interleaved), we
79
+ // distinguish the final data by checking if the event was a progress vs complete event
80
+ const chunks = safeNDJSONParse(data);
81
+ for (const chunk of chunks) {
82
+ if (typeof chunk === 'string') {
83
+ progress(chunk);
84
+ continue;
85
+ }
86
+ const { failedMonitors, failedStaleMonitors } = chunk;
87
+ if (failedMonitors && failedMonitors.length > 0) {
88
+ throw formatFailedMonitors(failedMonitors);
89
+ }
90
+ if (failedStaleMonitors.length > 0) {
91
+ write(yellow(formatStaleMonitors(failedStaleMonitors)));
92
+ }
93
+ }
94
+ }
95
+ done('Pushed');
96
+ } catch (e) {
97
+ error(e);
98
+ }
99
+ }
100
+
101
+ function trackDuplicates(monitors: Monitor[]) {
102
+ const monitorMap: Map<string, Monitor> = new Map();
103
+ const duplicates: Set<Monitor> = new Set();
104
+ for (const monitor of monitors) {
105
+ const id = monitor.config.id;
106
+ if (monitorMap.has(id)) {
107
+ duplicates.add(monitorMap.get(id));
108
+ duplicates.add(monitor);
109
+ }
110
+ monitorMap.set(id, monitor);
111
+ }
112
+ return duplicates;
113
+ }
114
+
115
+ export function formatDuplicateError(monitors: Set<Monitor>) {
116
+ let outer = bold(`Aborted: Duplicate monitors found\n`);
117
+
118
+ let inner = '';
119
+ for (const monitor of monitors) {
120
+ const { config, source } = monitor;
121
+ inner += `* ${config.id} - ${source.file}:${source.line}:${source.column}\n`;
122
+ }
123
+ outer += indent(inner);
124
+ return outer;
125
+ }
126
+
127
+ const PROJECT_SETTINGS_PATH = join(SYNTHETICS_PATH, 'project.json');
128
+ const INSTALLATION_HELP = `Run 'npx @elastic/synthetics init' to create project with default settings.`;
129
+
130
+ export async function loadSettings() {
131
+ if (!existsSync(PROJECT_SETTINGS_PATH)) {
132
+ throw error(`Aborted. Synthetics project not set up.
133
+
134
+ ${INSTALLATION_HELP}`);
135
+ }
136
+
137
+ const contents = await readFile(PROJECT_SETTINGS_PATH, 'utf-8');
138
+ return JSON.parse(contents) as ProjectSettings;
139
+ }
140
+
141
+ export function validateSettings(opts: PushOptions) {
142
+ const INVALID = 'Aborted. Invalid synthetics project settings.';
143
+
144
+ let reason = '';
145
+ if (!opts.project) {
146
+ reason = 'Set project id via CLI as `--project <id>`';
147
+ } else if (!opts.locations && !opts.privateLocations) {
148
+ reason = `Set default location for all monitors via
149
+ - CLI as '--locations <values...> or --privateLocations <values...>'
150
+ - Synthetics config file 'monitors.locations' | 'monitors.privateLocations' field`;
151
+ } else if (!opts.schedule) {
152
+ reason = `Set default schedule in minutes for all monitors via
153
+ - CLI as '--schedule <mins>'
154
+ - Synthetics config file 'monitors.schedule' field`;
155
+ }
156
+
157
+ if (!reason) return;
158
+
159
+ throw error(`${INVALID}
160
+
161
+ ${reason}
162
+
163
+ ${INSTALLATION_HELP}`);
164
+ }
165
+
166
+ async function overrideSettings(project: string) {
167
+ const settings = JSON.parse(await readFile(PROJECT_SETTINGS_PATH, 'utf-8'));
168
+ settings.project = project;
169
+
170
+ await writeFile(
171
+ PROJECT_SETTINGS_PATH,
172
+ JSON.stringify(settings, null, 2),
173
+ 'utf-8'
174
+ );
175
+ }
176
+
177
+ export async function catchIncorrectSettings(
178
+ settings: ProjectSettings,
179
+ options: PushOptions
180
+ ) {
181
+ let override = !settings.project;
182
+ if (settings.project && settings.project !== options.project) {
183
+ if (typeof process.env.TEST_OVERRIDE != null) {
184
+ override = Boolean(process.env.TEST_OVERRIDE);
185
+ } else {
186
+ // Add an extra line to make it easier to read the prompt
187
+ write('');
188
+ ({ override } = await prompt<{ override: boolean }>({
189
+ type: 'confirm',
190
+ name: 'override',
191
+ message: `Monitors were pushed under the '${settings.project}' project. Are you sure you want to push them under the new '${options.project}' (note that this will duplicate the monitors, the old ones being orphaned)`,
192
+ initial: false,
193
+ }));
194
+ }
195
+ if (!override) {
196
+ throw aborted('Push command Aborted');
197
+ }
198
+ }
199
+ if (override) {
200
+ await overrideSettings(options.project);
201
+ }
202
+ }
@@ -0,0 +1,96 @@
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 { mkdir, rm } from 'fs/promises';
27
+ import { join } from 'path';
28
+ import { Bundler } from './bundler';
29
+ import { sendRequest } from './request';
30
+ import { removeTrailingSlash, SYNTHETICS_PATH } from '../helpers';
31
+ import { LocationsMap } from '../locations/public-locations';
32
+ import { Monitor, MonitorConfig } from '../dsl/monitor';
33
+ import { PushOptions } from '../common_types';
34
+
35
+ export type MonitorSchema = Omit<MonitorConfig, 'locations'> & {
36
+ content: string;
37
+ locations: string[];
38
+ filter: Monitor['filter'];
39
+ };
40
+
41
+ type APISchema = {
42
+ project: string;
43
+ keep_stale: boolean;
44
+ monitors: MonitorSchema[];
45
+ };
46
+
47
+ function translateLocation(locations?: MonitorConfig['locations']) {
48
+ if (!locations) return [];
49
+ return locations.map(loc => LocationsMap[loc] || loc).filter(Boolean);
50
+ }
51
+
52
+ export async function buildMonitorSchema(monitors: Monitor[]) {
53
+ /**
54
+ * Set up the bundle artifacts path which can be used to
55
+ * create the bundles required for uploading journeys
56
+ */
57
+ const bundlePath = join(SYNTHETICS_PATH, 'bundles');
58
+ await mkdir(bundlePath, { recursive: true });
59
+ const bundler = new Bundler();
60
+ const schemas: MonitorSchema[] = [];
61
+
62
+ for (const monitor of monitors) {
63
+ const { source, config, filter } = monitor;
64
+ const outPath = join(bundlePath, config.name + '.zip');
65
+ const content = await bundler.build(source.file, outPath);
66
+ schemas.push({
67
+ ...config,
68
+ content,
69
+ locations: translateLocation(config.locations),
70
+ filter: filter,
71
+ });
72
+ }
73
+
74
+ await rm(bundlePath, { recursive: true });
75
+ return schemas;
76
+ }
77
+
78
+ export async function createMonitors(
79
+ monitors: MonitorSchema[],
80
+ options: PushOptions
81
+ ) {
82
+ const schema: APISchema = {
83
+ project: options.project,
84
+ keep_stale: false,
85
+ monitors,
86
+ };
87
+
88
+ return await sendRequest({
89
+ url:
90
+ removeTrailingSlash(options.url) +
91
+ `/s/${options.space}/api/synthetics/service/project/monitors`,
92
+ method: 'PUT',
93
+ auth: options.auth,
94
+ body: JSON.stringify(schema),
95
+ });
96
+ }
@@ -0,0 +1,119 @@
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 fs from 'fs/promises';
28
+ import * as esbuild from 'esbuild';
29
+
30
+ export function commonOptions(): esbuild.BuildOptions {
31
+ return {
32
+ bundle: true,
33
+ external: ['node_modules', '@elastic/synthetics'],
34
+ minify: false,
35
+ platform: 'node',
36
+ logLevel: 'silent',
37
+ format: 'esm',
38
+ write: false,
39
+ outExtension: {
40
+ '.js': '.js',
41
+ },
42
+ };
43
+ }
44
+
45
+ export type PluginData = {
46
+ path: string;
47
+ contents: string;
48
+ };
49
+ export type PluginCallback = (data: PluginData) => void;
50
+
51
+ export function MultiAssetPlugin(callback: PluginCallback): esbuild.Plugin {
52
+ // Check that the path isn't in an external package by making sure it's at a standard
53
+ // local filesystem location
54
+ const isBare = (str: string) => {
55
+ // Note that we use `isAbsolute` to handle UNC/windows style paths like C:\path\to\thing
56
+ // This is not necessary for relative directories since `.\file` is not supported as an import
57
+ // nor is `~/path/to/file`.
58
+ if (path.isAbsolute(str) || str.startsWith('./') || str.startsWith('../')) {
59
+ return true;
60
+ }
61
+ return false;
62
+ };
63
+
64
+ return {
65
+ name: 'esbuild-multiasset-plugin',
66
+ setup(build) {
67
+ build.onResolve({ filter: /.*?/ }, async args => {
68
+ // External and other packages need be marked external to
69
+ // be removed from the bundle
70
+ if (
71
+ build.initialOptions.external?.includes(args.path) ||
72
+ !isBare(args.path)
73
+ ) {
74
+ return {
75
+ external: true,
76
+ };
77
+ }
78
+
79
+ if (args.kind === 'entry-point') {
80
+ return {
81
+ path: args.path,
82
+ namespace: 'asset',
83
+ };
84
+ }
85
+
86
+ // If the modules are resolved locally, then
87
+ // use the imported path to get full path
88
+ const entryPath =
89
+ path.join(path.dirname(args.importer), args.path) +
90
+ path.extname(args.importer);
91
+ // Spin off another build to copy over the imported modules without bundling
92
+ const result = await esbuild.build({
93
+ ...commonOptions(),
94
+ entryPoints: {
95
+ [entryPath]: entryPath,
96
+ },
97
+ bundle: false,
98
+ external: [],
99
+ });
100
+
101
+ callback({
102
+ path: entryPath,
103
+ contents: result.outputFiles[0].text,
104
+ });
105
+
106
+ return {
107
+ errors: result.errors,
108
+ external: true,
109
+ };
110
+ });
111
+
112
+ build.onLoad({ filter: /.*?/, namespace: 'asset' }, async args => {
113
+ const contents = await fs.readFile(args.path, 'utf-8');
114
+ callback({ path: args.path, contents });
115
+ return { contents };
116
+ });
117
+ },
118
+ };
119
+ }