@elastic/synthetics 1.0.0-beta.4 → 1.0.0-beta.41

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 +4 -3
  2. package/dist/cli.js +137 -160
  3. package/dist/cli.js.map +1 -1
  4. package/dist/common_types.d.ts +161 -31
  5. package/dist/common_types.d.ts.map +1 -1
  6. package/dist/config.d.ts +3 -5
  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 +4 -8
  18. package/dist/core/gatherer.d.ts.map +1 -1
  19. package/dist/core/gatherer.js +53 -15
  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 +3 -16
  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 +156 -90
  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 -4
  40. package/dist/dsl/journey.d.ts.map +1 -1
  41. package/dist/dsl/journey.js +37 -9
  42. package/dist/dsl/journey.js.map +1 -1
  43. package/dist/dsl/monitor.d.ts +83 -0
  44. package/dist/dsl/monitor.d.ts.map +1 -0
  45. package/dist/dsl/monitor.js +108 -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 +98 -0
  52. package/dist/formatter/javascript.d.ts.map +1 -0
  53. package/dist/formatter/javascript.js +298 -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 +28 -3
  64. package/dist/helpers.d.ts.map +1 -1
  65. package/dist/helpers.js +152 -20
  66. package/dist/helpers.js.map +1 -1
  67. package/dist/index.d.ts +6 -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 +149 -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 +41 -0
  84. package/dist/options.d.ts.map +1 -0
  85. package/dist/options.js +198 -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 +44 -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 +20 -33
  94. package/dist/plugins/network.d.ts.map +1 -1
  95. package/dist/plugins/network.js +177 -216
  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 +10 -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 +9 -0
  114. package/dist/push/index.d.ts.map +1 -0
  115. package/dist/push/index.js +227 -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 +51 -0
  122. package/dist/push/monitor.d.ts.map +1 -0
  123. package/dist/push/monitor.js +244 -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 +149 -179
  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 +39 -24
  165. package/src/cli.ts +219 -151
  166. package/src/common_types.ts +193 -31
  167. package/src/config.ts +3 -6
  168. package/src/core/expect.ts +58 -24
  169. package/src/core/gatherer.ts +64 -24
  170. package/src/core/index.ts +36 -15
  171. package/src/core/logger.ts +1 -12
  172. package/src/core/runner.ts +151 -136
  173. package/src/core/transform.ts +160 -0
  174. package/src/dsl/journey.ts +39 -6
  175. package/src/dsl/monitor.ts +140 -0
  176. package/src/dsl/step.ts +9 -2
  177. package/src/formatter/javascript.ts +367 -0
  178. package/src/generator/index.ts +308 -0
  179. package/src/generator/utils.ts +84 -0
  180. package/src/helpers.ts +159 -13
  181. package/src/index.ts +22 -22
  182. package/src/loader.ts +167 -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 +227 -0
  186. package/src/plugins/browser-console.ts +30 -8
  187. package/src/plugins/network.ts +208 -267
  188. package/src/plugins/performance.ts +6 -22
  189. package/src/plugins/plugin-manager.ts +49 -31
  190. package/src/plugins/tracing.ts +8 -9
  191. package/src/push/bundler.ts +112 -0
  192. package/src/push/index.ts +282 -0
  193. package/src/push/kibana_api.ts +191 -0
  194. package/src/push/monitor.ts +276 -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 +183 -202
  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 +8 -0
  211. package/templates/synthetics.config.ts +35 -0
  212. package/CHANGELOG.md +0 -131
  213. package/NOTICE.txt +0 -221
  214. package/dist/parse_args.d.ts.map +0 -1
  215. package/dist/parse_args.js +0 -95
  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 -1888
  220. package/src/parse_args.ts +0 -135
@@ -23,10 +23,17 @@
23
23
  *
24
24
  */
25
25
 
26
- import { Browser, Page, BrowserContext, CDPSession } from 'playwright-chromium';
26
+ import {
27
+ Browser,
28
+ Page,
29
+ BrowserContext,
30
+ CDPSession,
31
+ APIRequestContext,
32
+ } from 'playwright-chromium';
27
33
  import micromatch, { isMatch } from 'micromatch';
28
34
  import { Step } from './step';
29
- import { VoidCallback, HooksCallback, Params } from '../common_types';
35
+ import { VoidCallback, HooksCallback, Params, Location } from '../common_types';
36
+ import { Monitor, MonitorConfig } from './monitor';
30
37
 
31
38
  export type JourneyOptions = {
32
39
  name: string;
@@ -42,6 +49,7 @@ export type JourneyCallback = (options: {
42
49
  browser: Browser;
43
50
  client: CDPSession;
44
51
  params: Params;
52
+ request: APIRequestContext;
45
53
  }) => void;
46
54
 
47
55
  export class Journey {
@@ -49,18 +57,26 @@ export class Journey {
49
57
  id?: string;
50
58
  tags?: string[];
51
59
  callback: JourneyCallback;
60
+ location?: Location;
52
61
  steps: Step[] = [];
53
62
  hooks: Hooks = { before: [], after: [] };
63
+ monitor: Monitor;
54
64
 
55
- constructor(options: JourneyOptions, callback: JourneyCallback) {
65
+ constructor(
66
+ options: JourneyOptions,
67
+ callback: JourneyCallback,
68
+ location?: Location
69
+ ) {
56
70
  this.name = options.name;
57
- this.id = options.id;
71
+ this.id = options.id || options.name;
58
72
  this.tags = options.tags;
59
73
  this.callback = callback;
74
+ this.location = location;
75
+ this.updateMonitor({});
60
76
  }
61
77
 
62
- addStep(name: string, callback: VoidCallback) {
63
- const step = new Step(name, this.steps.length + 1, callback);
78
+ addStep(name: string, callback: VoidCallback, location?: Location) {
79
+ const step = new Step(name, this.steps.length + 1, callback, location);
64
80
  this.steps.push(step);
65
81
  return step;
66
82
  }
@@ -68,6 +84,23 @@ export class Journey {
68
84
  addHook(type: HookType, callback: HooksCallback) {
69
85
  this.hooks[type].push(callback);
70
86
  }
87
+
88
+ updateMonitor(config: MonitorConfig) {
89
+ /**
90
+ * Use defaults values from journey for monitor object (id, name and tags)
91
+ */
92
+ this.monitor = new Monitor({
93
+ name: this.name,
94
+ id: this.id,
95
+ type: 'browser',
96
+ tags: this.tags ?? [],
97
+ ...config,
98
+ });
99
+ this.monitor.setSource(this.location);
100
+ this.monitor.setContent(this.callback.toString());
101
+ this.monitor.setFilter({ match: this.name });
102
+ }
103
+
71
104
  /**
72
105
  * Matches journeys based on the provided args. Proitize tags over match
73
106
  * - tags pattern that matches only tags
@@ -0,0 +1,140 @@
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 { createHash } from 'crypto';
27
+ import merge from 'deepmerge';
28
+ import { bold, red } from 'kleur/colors';
29
+ import {
30
+ ThrottlingOptions,
31
+ Location,
32
+ ScreenshotOptions,
33
+ Params,
34
+ PlaywrightOptions,
35
+ } from '../common_types';
36
+ import { indent } from '../helpers';
37
+ import { LocationsMap } from '../locations/public-locations';
38
+
39
+ export type SyntheticsLocationsType = keyof typeof LocationsMap;
40
+ export const SyntheticsLocations = Object.keys(
41
+ LocationsMap
42
+ ) as SyntheticsLocationsType[];
43
+ export const ALLOWED_SCHEDULES = [1, 3, 5, 10, 15, 30, 60] as const;
44
+
45
+ export type MonitorConfig = {
46
+ id?: string;
47
+ name?: string;
48
+ type?: string;
49
+ tags?: string[];
50
+ schedule?: typeof ALLOWED_SCHEDULES[number];
51
+ enabled?: boolean;
52
+ locations?: SyntheticsLocationsType[];
53
+ privateLocations?: string[];
54
+ throttling?: boolean | ThrottlingOptions;
55
+ screenshot?: ScreenshotOptions;
56
+ params?: Params;
57
+ playwrightOptions?: PlaywrightOptions;
58
+ };
59
+
60
+ type MonitorFilter = {
61
+ match: string;
62
+ tags?: string[];
63
+ };
64
+
65
+ export class Monitor {
66
+ content?: string;
67
+ source?: Location;
68
+ filter: MonitorFilter;
69
+ constructor(public config: MonitorConfig = {}) {}
70
+ /**
71
+ * Treat the creation time config with `monitor.use` as source of truth by
72
+ * merging the values coming from CLI and Synthetics config file
73
+ */
74
+ update(globalOpts: MonitorConfig = {}) {
75
+ this.config = merge(globalOpts, this.config, {
76
+ arrayMerge(target, source) {
77
+ return [...new Set(source)];
78
+ },
79
+ });
80
+ }
81
+
82
+ get type() {
83
+ return this.config.type;
84
+ }
85
+
86
+ setSource(source: Location) {
87
+ this.source = source;
88
+ }
89
+
90
+ /**
91
+ * The underlying journey code of the monitor
92
+ */
93
+ setContent(content = '') {
94
+ this.content = content;
95
+ }
96
+
97
+ /**
98
+ * If journey files are colocated within the same file during
99
+ * push command, when we invoke synthetics from HB we rely on
100
+ * this filter for running that specific journey alone instead of
101
+ * all journeys on the file
102
+ */
103
+ setFilter(filter: MonitorFilter) {
104
+ this.filter = filter;
105
+ }
106
+
107
+ /**
108
+ * Hash is used to identify if the monitor has changed since the last time
109
+ * it was pushed to Kibana. Change is based on three factors:
110
+ * - Monitor configuration
111
+ * - Code changes
112
+ * - File path changes
113
+ */
114
+ hash(): string {
115
+ const hash = createHash('sha256');
116
+ return hash
117
+ .update(JSON.stringify(this.config))
118
+ .update(this.content || '')
119
+ .update(this.source?.file || '')
120
+ .digest('base64');
121
+ }
122
+
123
+ validate() {
124
+ const schedule = this.config.schedule;
125
+ if (ALLOWED_SCHEDULES.includes(schedule)) {
126
+ return;
127
+ }
128
+ const { config, source } = this;
129
+ let outer = bold(
130
+ `Invalid schedule: ${schedule}, allowed values are ${ALLOWED_SCHEDULES.join(
131
+ ','
132
+ )}\n`
133
+ );
134
+ if (source) {
135
+ const inner = `* ${config.id} - ${source.file}:${source.line}:${source.column}\n`;
136
+ outer += indent(inner);
137
+ }
138
+ throw red(outer);
139
+ }
140
+ }
package/src/dsl/step.ts CHANGED
@@ -23,16 +23,23 @@
23
23
  *
24
24
  */
25
25
 
26
- import { VoidCallback } from '../common_types';
26
+ import { Location, VoidCallback } from '../common_types';
27
27
 
28
28
  export class Step {
29
29
  name: string;
30
30
  index: number;
31
31
  callback: VoidCallback;
32
+ location?: Location;
32
33
 
33
- constructor(name: string, index: number, callback: VoidCallback) {
34
+ constructor(
35
+ name: string,
36
+ index: number,
37
+ callback: VoidCallback,
38
+ location: Location
39
+ ) {
34
40
  this.name = name;
35
41
  this.index = index;
36
42
  this.callback = callback;
43
+ this.location = location;
37
44
  }
38
45
  }
@@ -0,0 +1,367 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2020-present, Elastic NV
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in
14
+ * all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ * THE SOFTWARE.
23
+ *
24
+ */
25
+
26
+ import {
27
+ JavaScriptLanguageGenerator,
28
+ JavaScriptFormatter,
29
+ } from 'playwright-core/lib/server/recorder/javascript';
30
+
31
+ export type Step = {
32
+ actions: ActionInContext[];
33
+ name?: string;
34
+ };
35
+
36
+ export type Steps = Step[];
37
+
38
+ export type ActionInContext = {
39
+ pageAlias: string;
40
+ frameName?: string;
41
+ frameUrl: string;
42
+ isMainFrame: boolean;
43
+ action: Action;
44
+ committed?: boolean;
45
+ modified?: boolean;
46
+ title?: string;
47
+ };
48
+
49
+ export type Action = {
50
+ name: string;
51
+ selector?: string;
52
+ url?: string;
53
+ key?: string;
54
+ signals: Signal[];
55
+ modifiers?: number;
56
+ button?: 'left' | 'middle' | 'right';
57
+ clickCount?: number;
58
+ text?: string;
59
+ value?: string;
60
+ isAssert?: boolean;
61
+ command?: string;
62
+ files?: string[];
63
+ options?: string[];
64
+ };
65
+
66
+ export type Signal = {
67
+ name: string;
68
+ url?: string;
69
+ isAsync?: boolean;
70
+ popupAlias?: string;
71
+ downloadAlias?: string;
72
+ dialogAlias?: string;
73
+ };
74
+
75
+ export class SyntheticsGenerator extends JavaScriptLanguageGenerator {
76
+ private previousContext: ActionInContext;
77
+ private insideStep: boolean;
78
+
79
+ constructor(private isSuite: boolean) {
80
+ super(true);
81
+ this.insideStep = false;
82
+ this.previousContext = undefined;
83
+ }
84
+
85
+ /**
86
+ * Generate code for an action.
87
+ * @param actionInContext The action to create code for.
88
+ * @returns the strings generated for the action.
89
+ */
90
+ generateAction(actionInContext: ActionInContext) {
91
+ const { action, pageAlias } = actionInContext;
92
+ if (action.name === 'openPage') {
93
+ return '';
94
+ }
95
+ // Don't cleanup page object managed by Synthetics
96
+ const isCleanUp = action.name === 'closePage' && pageAlias === 'page';
97
+ if (isCleanUp) {
98
+ return '';
99
+ }
100
+
101
+ const stepIndent = this.insideStep ? 2 : 0;
102
+ const offset = this.isSuite ? 2 + stepIndent : 0 + stepIndent;
103
+ const formatter = new JavaScriptFormatter(offset);
104
+
105
+ const subject = actionInContext.isMainFrame
106
+ ? pageAlias
107
+ : actionInContext.frameName
108
+ ? `${pageAlias}.frame(${formatObject({
109
+ name: actionInContext.frameName,
110
+ })})`
111
+ : `${pageAlias}.frame(${formatObject({
112
+ url: actionInContext.frameUrl,
113
+ })})`;
114
+
115
+ const signals = toSignalMap(action);
116
+
117
+ if (signals.dialog) {
118
+ formatter.add(` ${pageAlias}.once('dialog', dialog => {
119
+ console.log(\`Dialog message: $\{dialog.message()}\`);
120
+ dialog.dismiss().catch(() => {});
121
+ });`);
122
+ }
123
+
124
+ const emitPromiseAll =
125
+ signals.waitForNavigation || signals.popup || signals.download;
126
+ if (emitPromiseAll) {
127
+ // Generate either await Promise.all([]) or
128
+ // const [popup1] = await Promise.all([]).
129
+ let leftHandSide = '';
130
+ if (signals.popup)
131
+ leftHandSide = `const [${signals.popup.popupAlias}] = `;
132
+ else if (signals.download) leftHandSide = `const [download] = `;
133
+ formatter.add(`${leftHandSide}await Promise.all([`);
134
+ }
135
+
136
+ // Popup signals.
137
+ if (signals.popup) formatter.add(`${pageAlias}.waitForEvent('popup'),`);
138
+
139
+ // Navigation signal.
140
+ if (signals.waitForNavigation)
141
+ formatter.add(
142
+ `${pageAlias}.waitForNavigation(/*{ url: ${quote(
143
+ signals.waitForNavigation.url
144
+ )} }*/),`
145
+ );
146
+
147
+ // Download signals.
148
+ if (signals.download)
149
+ formatter.add(`${pageAlias}.waitForEvent('download'),`);
150
+
151
+ const prefix =
152
+ signals.popup || signals.waitForNavigation || signals.download
153
+ ? ''
154
+ : 'await ';
155
+ const actionCall = super._generateActionCall(action);
156
+ // Add assertion from Synthetics.
157
+ const isAssert = action.name === 'assert' && action.isAssert;
158
+
159
+ if (!isAssert) {
160
+ const suffix = signals.waitForNavigation || emitPromiseAll ? '' : ';';
161
+ formatter.add(`${prefix}${subject}.${actionCall}${suffix}`);
162
+
163
+ if (emitPromiseAll) {
164
+ formatter.add(`]);`);
165
+ } else if (signals.assertNavigation) {
166
+ formatter.add(
167
+ ` expect(${pageAlias}.url()).toBe(${quote(
168
+ signals.assertNavigation.url
169
+ )});`
170
+ );
171
+ }
172
+ } else if (action.command) {
173
+ formatter.add(toAssertCall(pageAlias, action));
174
+ }
175
+
176
+ this.previousContext = actionInContext;
177
+ return formatter.format();
178
+ }
179
+
180
+ isNewStep(actioninContext: ActionInContext) {
181
+ const { action, frameUrl } = actioninContext;
182
+ if (action.name === 'navigate') {
183
+ return true;
184
+ } else if (action.name === 'click') {
185
+ return (
186
+ this.previousContext?.frameUrl === frameUrl && action.signals.length > 0
187
+ );
188
+ }
189
+ return false;
190
+ }
191
+
192
+ generateStepStart(name) {
193
+ this.insideStep = true;
194
+ const formatter = new JavaScriptFormatter(this.isSuite ? 2 : 0);
195
+ formatter.add(`step(${quote(name)}, async () => {`);
196
+ return formatter.format();
197
+ }
198
+
199
+ generateStepEnd() {
200
+ if (!this.insideStep) {
201
+ return '';
202
+ }
203
+ this.insideStep = false;
204
+ const formatter = new JavaScriptFormatter(this.isSuite ? 2 : 0);
205
+ formatter.add(`});`);
206
+ return formatter.format();
207
+ }
208
+
209
+ generateHeader() {
210
+ const formatter = new JavaScriptFormatter(0);
211
+ formatter.add(`
212
+ const { journey, step, expect } = require('@elastic/synthetics');
213
+
214
+ journey('Recorded journey', async ({ page, context }) => {`);
215
+ return formatter.format();
216
+ }
217
+
218
+ generateFooter() {
219
+ return `});`;
220
+ }
221
+
222
+ /**
223
+ * Generates JavaScript code from a custom set of steps and nested actions.
224
+ *
225
+ * This function makes no assumptions about where steps should be created,
226
+ * and instead follows the step definitions the caller has defined.
227
+ * @param steps IR to use for code generation
228
+ * @returns a list of the code strings outputted by the generator
229
+ */
230
+ generateFromSteps(steps: Steps): string {
231
+ const text = [];
232
+ if (this.isSuite) {
233
+ text.push(this.generateHeader());
234
+ }
235
+ for (const step of steps) {
236
+ if (step.actions.length === 0)
237
+ throw Error('Cannot process an empty step');
238
+ text.push(
239
+ this.generateStepStart(
240
+ step.name ??
241
+ step.actions[0].title ??
242
+ actionTitle(step.actions[0].action)
243
+ )
244
+ );
245
+
246
+ for (const action of step.actions) {
247
+ const actionText = this.generateAction(action);
248
+ if (actionText.length) text.push(actionText);
249
+ }
250
+
251
+ text.push(this.generateStepEnd());
252
+ }
253
+ if (this.isSuite) {
254
+ text.push(this.generateFooter());
255
+ }
256
+ return text.filter(s => !!s).join('\n');
257
+ }
258
+ }
259
+
260
+ // TODO: Replace once Playwright releases new version
261
+ export function quote(text: string, char = "'") {
262
+ const stringified = JSON.stringify(text);
263
+ const escapedText = stringified
264
+ .substring(1, stringified.length - 1)
265
+ .replace(/\\"/g, '"');
266
+ if (char === "'") return char + escapedText.replace(/[']/g, "\\'") + char;
267
+ if (char === '"') return char + escapedText.replace(/["]/g, '\\"') + char;
268
+ if (char === '`') return char + escapedText.replace(/[`]/g, '`') + char;
269
+ throw new Error('Invalid escape char');
270
+ }
271
+
272
+ function toSignalMap(action) {
273
+ let waitForNavigation;
274
+ let assertNavigation;
275
+ let popup;
276
+ let download;
277
+ let dialog;
278
+ for (const signal of action.signals) {
279
+ if (signal.name === 'navigation' && signal.isAsync)
280
+ waitForNavigation = signal;
281
+ else if (signal.name === 'navigation' && !signal.isAsync)
282
+ assertNavigation = signal;
283
+ else if (signal.name === 'popup') popup = signal;
284
+ else if (signal.name === 'download') download = signal;
285
+ else if (signal.name === 'dialog') dialog = signal;
286
+ }
287
+ return {
288
+ waitForNavigation,
289
+ assertNavigation,
290
+ popup,
291
+ download,
292
+ dialog,
293
+ };
294
+ }
295
+
296
+ function toAssertCall(pageAlias, action) {
297
+ const { command, selector, value } = action;
298
+ switch (command) {
299
+ case 'textContent':
300
+ case 'innerText':
301
+ return `expect(await ${pageAlias}.${command}(${quote(
302
+ selector
303
+ )})).toMatch(${quote(value)});`;
304
+ case 'isVisible':
305
+ case 'isHidden':
306
+ case 'isChecked':
307
+ case 'isEditable':
308
+ case 'isEnabled':
309
+ case 'isDisabled':
310
+ return `expect(await ${pageAlias}.${command}(${quote(
311
+ selector
312
+ )})).toBeTruthy();`;
313
+ }
314
+ }
315
+
316
+ function formatObject(value, indent = ' ') {
317
+ if (typeof value === 'string') return quote(value);
318
+ if (Array.isArray(value))
319
+ return `[${value.map(o => formatObject(o)).join(', ')}]`;
320
+ if (typeof value === 'object') {
321
+ const keys = Object.keys(value);
322
+ if (!keys.length) return '{}';
323
+ const tokens = [];
324
+ for (const key of keys) tokens.push(`${key}: ${formatObject(value[key])}`);
325
+ return `{\n${indent}${tokens.join(`,\n${indent}`)}\n}`;
326
+ }
327
+ return String(value);
328
+ }
329
+
330
+ /**
331
+ * Generates an appropriate title string based on the action type/data.
332
+ * @param action Playwright action IR
333
+ * @returns title string
334
+ */
335
+ export function actionTitle(action: Action) {
336
+ switch (action.name) {
337
+ case 'openPage':
338
+ return `Open new page`;
339
+ case 'closePage':
340
+ return `Close page`;
341
+ case 'check':
342
+ return `Check ${action.selector}`;
343
+ case 'uncheck':
344
+ return `Uncheck ${action.selector}`;
345
+ case 'click': {
346
+ if (action.clickCount === 1) return `Click ${action.selector}`;
347
+ if (action.clickCount === 2) return `Double click ${action.selector}`;
348
+ if (action.clickCount === 3) return `Triple click ${action.selector}`;
349
+ return `${action.clickCount}× click`;
350
+ }
351
+ case 'fill':
352
+ return `Fill ${action.selector}`;
353
+ case 'setInputFiles':
354
+ if (action.files.length === 0) return `Clear selected files`;
355
+ else return `Upload ${action.files.join(', ')}`;
356
+ case 'navigate':
357
+ return `Go to ${action.url}`;
358
+ case 'press':
359
+ return (
360
+ `Press ${action.key}` + (action.modifiers ? ' with modifiers' : '')
361
+ );
362
+ case 'select':
363
+ return `Select ${action.options.join(', ')}`;
364
+ case 'assert':
365
+ return `Assert ${action.selector} ${action.command}`;
366
+ }
367
+ }