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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +42 -5
  3. package/dist/cli.js.map +1 -1
  4. package/dist/common_types.d.ts +62 -14
  5. package/dist/common_types.d.ts.map +1 -1
  6. package/dist/core/gatherer.d.ts +2 -2
  7. package/dist/core/gatherer.d.ts.map +1 -1
  8. package/dist/core/gatherer.js +14 -5
  9. package/dist/core/gatherer.js.map +1 -1
  10. package/dist/core/index.d.ts +4 -0
  11. package/dist/core/index.d.ts.map +1 -1
  12. package/dist/core/index.js +15 -1
  13. package/dist/core/index.js.map +1 -1
  14. package/dist/core/runner.d.ts +10 -58
  15. package/dist/core/runner.d.ts.map +1 -1
  16. package/dist/core/runner.js +89 -50
  17. package/dist/core/runner.js.map +1 -1
  18. package/dist/dsl/journey.d.ts +3 -0
  19. package/dist/dsl/journey.d.ts.map +1 -1
  20. package/dist/dsl/journey.js +15 -0
  21. package/dist/dsl/journey.js.map +1 -1
  22. package/dist/dsl/monitor.d.ts +64 -0
  23. package/dist/dsl/monitor.d.ts.map +1 -0
  24. package/dist/dsl/monitor.js +62 -0
  25. package/dist/dsl/monitor.js.map +1 -0
  26. package/dist/formatter/javascript.d.ts +1 -1
  27. package/dist/formatter/javascript.d.ts.map +1 -1
  28. package/dist/formatter/javascript.js +1 -1
  29. package/dist/formatter/javascript.js.map +1 -1
  30. package/dist/generator/index.d.ts +13 -0
  31. package/dist/generator/index.d.ts.map +1 -0
  32. package/dist/generator/index.js +123 -0
  33. package/dist/generator/index.js.map +1 -0
  34. package/dist/{reporters/reporter.js → generator/utils.d.ts} +3 -3
  35. package/dist/generator/utils.d.ts.map +1 -0
  36. package/dist/generator/utils.js +44 -0
  37. package/dist/generator/utils.js.map +1 -0
  38. package/dist/helpers.d.ts +12 -6
  39. package/dist/helpers.d.ts.map +1 -1
  40. package/dist/helpers.js +33 -43
  41. package/dist/helpers.js.map +1 -1
  42. package/dist/index.d.ts +3 -9
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +4 -5
  45. package/dist/index.js.map +1 -1
  46. package/dist/loader.js +4 -4
  47. package/dist/loader.js.map +1 -1
  48. package/dist/options.d.ts +12 -0
  49. package/dist/options.d.ts.map +1 -1
  50. package/dist/options.js +66 -4
  51. package/dist/options.js.map +1 -1
  52. package/dist/plugins/network.d.ts +17 -30
  53. package/dist/plugins/network.d.ts.map +1 -1
  54. package/dist/plugins/network.js +179 -244
  55. package/dist/plugins/network.js.map +1 -1
  56. package/dist/plugins/performance.d.ts +1 -16
  57. package/dist/plugins/performance.d.ts.map +1 -1
  58. package/dist/plugins/performance.js.map +1 -1
  59. package/dist/plugins/plugin-manager.d.ts +2 -2
  60. package/dist/plugins/plugin-manager.d.ts.map +1 -1
  61. package/dist/plugins/plugin-manager.js +2 -2
  62. package/dist/plugins/plugin-manager.js.map +1 -1
  63. package/dist/push/bundler.d.ts +34 -0
  64. package/dist/push/bundler.d.ts.map +1 -0
  65. package/dist/push/bundler.js +119 -0
  66. package/dist/push/bundler.js.map +1 -0
  67. package/{src/reporters/reporter.ts → dist/push/index.d.ts} +4 -11
  68. package/dist/push/index.d.ts.map +1 -0
  69. package/dist/push/index.js +58 -0
  70. package/dist/push/index.js.map +1 -0
  71. package/dist/{reporters/reporter.d.ts → push/monitor.d.ts} +7 -8
  72. package/dist/push/monitor.d.ts.map +1 -0
  73. package/dist/push/monitor.js +67 -0
  74. package/dist/push/monitor.js.map +1 -0
  75. package/dist/push/plugin.d.ts +33 -0
  76. package/dist/push/plugin.d.ts.map +1 -0
  77. package/dist/push/plugin.js +123 -0
  78. package/dist/push/plugin.js.map +1 -0
  79. package/dist/push/request.d.ts +43 -0
  80. package/dist/push/request.d.ts.map +1 -0
  81. package/dist/push/request.js +95 -0
  82. package/dist/push/request.js.map +1 -0
  83. package/dist/reporters/base.d.ts +14 -6
  84. package/dist/reporters/base.d.ts.map +1 -1
  85. package/dist/reporters/base.js +45 -47
  86. package/dist/reporters/base.js.map +1 -1
  87. package/dist/reporters/index.d.ts +18 -8
  88. package/dist/reporters/index.d.ts.map +1 -1
  89. package/dist/reporters/index.js.map +1 -1
  90. package/dist/reporters/json.d.ts +7 -4
  91. package/dist/reporters/json.d.ts.map +1 -1
  92. package/dist/reporters/json.js +119 -137
  93. package/dist/reporters/json.js.map +1 -1
  94. package/dist/reporters/junit.d.ts +7 -1
  95. package/dist/reporters/junit.d.ts.map +1 -1
  96. package/dist/reporters/junit.js +91 -86
  97. package/dist/reporters/junit.js.map +1 -1
  98. package/dist/tsconfig.tsbuildinfo +1 -1
  99. package/package.json +14 -9
  100. package/src/cli.ts +65 -9
  101. package/src/common_types.ts +72 -14
  102. package/src/core/gatherer.ts +18 -10
  103. package/src/core/index.ts +15 -0
  104. package/src/core/runner.ts +87 -114
  105. package/src/dsl/journey.ts +18 -0
  106. package/src/dsl/monitor.ts +83 -0
  107. package/src/formatter/javascript.ts +1 -1
  108. package/src/generator/index.ts +159 -0
  109. package/src/generator/utils.ts +41 -0
  110. package/src/helpers.ts +36 -52
  111. package/src/index.ts +10 -2
  112. package/src/loader.ts +4 -4
  113. package/src/options.ts +71 -8
  114. package/src/plugins/network.ts +218 -293
  115. package/src/plugins/performance.ts +1 -17
  116. package/src/plugins/plugin-manager.ts +2 -2
  117. package/src/push/bundler.ts +99 -0
  118. package/src/push/index.ts +63 -0
  119. package/src/push/monitor.ts +77 -0
  120. package/src/push/plugin.ts +113 -0
  121. package/src/push/request.ts +123 -0
  122. package/src/reporters/base.ts +57 -56
  123. package/src/reporters/index.ts +26 -3
  124. package/src/reporters/json.ts +154 -162
  125. package/src/reporters/junit.ts +98 -93
  126. package/templates/journeys/example.journey.ts +18 -0
  127. package/templates/synthetics.config.ts +19 -0
  128. package/CHANGELOG.md +0 -339
  129. package/NOTICE.txt +0 -250
  130. package/dist/reporters/reporter.d.ts.map +0 -1
  131. package/dist/reporters/reporter.js.map +0 -1
@@ -23,12 +23,11 @@
23
23
  *
24
24
  */
25
25
 
26
- import { once, EventEmitter } from 'events';
27
26
  import { join } from 'path';
28
27
  import { rm } from 'fs/promises';
29
28
  import { Journey } from '../dsl/journey';
30
29
  import { Step } from '../dsl/step';
31
- import { reporters } from '../reporters';
30
+ import { reporters, Reporter } from '../reporters';
32
31
  import {
33
32
  CACHE_PATH,
34
33
  monotonicTimeInSeconds,
@@ -39,20 +38,20 @@ import {
39
38
  writeFileAsync,
40
39
  } from '../helpers';
41
40
  import {
42
- StatusValue,
43
41
  HooksCallback,
44
42
  Params,
45
- NetworkConditions,
46
- PluginOutput,
47
43
  HooksArgs,
48
44
  Driver,
49
45
  Screenshot,
50
46
  RunOptions,
47
+ JourneyResult,
48
+ StepResult,
51
49
  } from '../common_types';
52
- import { PageMetrics, PluginManager } from '../plugins';
50
+ import { PluginManager } from '../plugins';
53
51
  import { PerformanceManager } from '../plugins';
54
52
  import { Gatherer } from './gatherer';
55
53
  import { log } from './logger';
54
+ import { Monitor, MonitorConfig } from '../dsl/monitor';
56
55
 
57
56
  type HookType = 'beforeAll' | 'afterAll';
58
57
  export type SuiteHooks = Record<HookType, Array<HooksCallback>>;
@@ -64,73 +63,16 @@ type JourneyContext = {
64
63
  pluginManager: PluginManager;
65
64
  };
66
65
 
67
- type StepResult = {
68
- status: StatusValue;
69
- url?: string;
70
- error?: Error;
71
- pagemetrics?: PageMetrics;
72
- filmstrips?: PluginOutput['filmstrips'];
73
- metrics?: PluginOutput['metrics'];
74
- traces?: PluginOutput['traces'];
75
- };
76
-
77
- type JourneyResult = {
78
- status: StatusValue;
79
- error?: Error;
80
- networkinfo?: PluginOutput['networkinfo'];
81
- browserconsole?: PluginOutput['browserconsole'];
82
- };
83
-
84
66
  type RunResult = Record<string, JourneyResult>;
85
67
 
86
- interface StepEvent {
87
- step: Step;
88
- journey: Journey;
89
- }
90
-
91
- interface JourneyEvent {
92
- journey: Journey;
93
- timestamp: number;
94
- params?: Params;
95
- }
96
-
97
- interface Events {
98
- start: {
99
- numJourneys: number;
100
- networkConditions?: NetworkConditions;
101
- };
102
- 'journey:register': {
103
- journey: Journey;
104
- };
105
- 'journey:start': JourneyEvent;
106
- 'journey:end': JourneyEvent &
107
- JourneyResult & {
108
- start: number;
109
- end: number;
110
- options: RunOptions;
111
- timestamp: number;
112
- };
113
- 'journey:end:reported': unknown;
114
- 'step:start': StepEvent;
115
- 'step:end': StepEvent &
116
- StepResult & {
117
- start: number;
118
- end: number;
119
- };
120
- end: unknown;
121
- }
122
-
123
- export default interface Runner {
124
- on<K extends keyof Events>(name: K, listener: (v: Events[K]) => void): this;
125
- emit<K extends keyof Events>(event: K, args: Events[K]): boolean;
126
- }
127
-
128
- export default class Runner extends EventEmitter {
129
- active = false;
130
- currentJourney?: Journey = null;
68
+ export default class Runner {
69
+ #active = false;
70
+ #reporter: Reporter;
71
+ #currentJourney?: Journey = null;
131
72
  journeys: Journey[] = [];
132
73
  hooks: SuiteHooks = { beforeAll: [], afterAll: [] };
133
74
  hookError: Error | undefined;
75
+ monitor?: Monitor;
134
76
  static screenshotPath = join(CACHE_PATH, 'screenshots');
135
77
 
136
78
  static async createContext(options: RunOptions): Promise<JourneyContext> {
@@ -181,13 +123,38 @@ export default class Runner extends EventEmitter {
181
123
  }
182
124
  }
183
125
 
126
+ get currentJourney() {
127
+ return this.#currentJourney;
128
+ }
129
+
184
130
  addHook(type: HookType, callback: HooksCallback) {
185
131
  this.hooks[type].push(callback);
186
132
  }
187
133
 
134
+ updateMonitor(config: MonitorConfig) {
135
+ if (!this.monitor) {
136
+ this.monitor = new Monitor(config);
137
+ return;
138
+ }
139
+ this.monitor.update(config);
140
+ }
141
+
188
142
  addJourney(journey: Journey) {
189
143
  this.journeys.push(journey);
190
- this.currentJourney = journey;
144
+ this.#currentJourney = journey;
145
+ }
146
+
147
+ setReporter(options: RunOptions) {
148
+ /**
149
+ * Set up the corresponding reporter and fallback
150
+ * to default reporter if not provided
151
+ */
152
+ const { reporter, outfd } = options;
153
+ const Reporter =
154
+ typeof reporter === 'function'
155
+ ? reporter
156
+ : reporters[reporter] || reporters['default'];
157
+ this.#reporter = new Reporter({ fd: outfd });
191
158
  }
192
159
 
193
160
  async runBeforeAllHook(args: HooksArgs) {
@@ -288,7 +255,7 @@ export default class Runner extends EventEmitter {
288
255
  let skipStep = false;
289
256
  for (const step of journey.steps) {
290
257
  const start = monotonicTimeInSeconds();
291
- this.emit('step:start', { journey, step });
258
+ this.#reporter?.onStepStart?.(journey, step);
292
259
  let data: StepResult = { status: 'succeeded' };
293
260
  if (skipStep) {
294
261
  data.status = 'skipped';
@@ -299,9 +266,7 @@ export default class Runner extends EventEmitter {
299
266
  */
300
267
  if (data.error) skipStep = true;
301
268
  }
302
- this.emit('step:end', {
303
- journey,
304
- step,
269
+ this.#reporter?.onStepEnd?.(journey, step, {
305
270
  start,
306
271
  end: monotonicTimeInSeconds(),
307
272
  ...data,
@@ -315,12 +280,16 @@ export default class Runner extends EventEmitter {
315
280
  }
316
281
 
317
282
  registerJourney(journey: Journey, context: JourneyContext) {
318
- this.currentJourney = journey;
283
+ this.#currentJourney = journey;
319
284
  const timestamp = getTimestamp();
320
285
  const { params } = context;
321
- this.emit('journey:start', { journey, timestamp, params });
286
+ this.#reporter?.onJourneyStart?.(journey, {
287
+ timestamp,
288
+ params,
289
+ });
322
290
  /**
323
- * Load and register the steps for the current journey
291
+ * Exeucute the journey callback which would
292
+ * register the steps for the current journey
324
293
  */
325
294
  journey.callback({ ...context.driver, params });
326
295
  }
@@ -332,9 +301,8 @@ export default class Runner extends EventEmitter {
332
301
  ) {
333
302
  const end = monotonicTimeInSeconds();
334
303
  const { pluginManager, start, status, error } = result;
335
- const pluginOutput = pluginManager.output();
336
- this.emit('journey:end', {
337
- journey,
304
+ const pluginOutput = await pluginManager.output();
305
+ await this.#reporter?.onJourneyEnd?.(journey, {
338
306
  status,
339
307
  error,
340
308
  start,
@@ -344,13 +312,6 @@ export default class Runner extends EventEmitter {
344
312
  ...pluginOutput,
345
313
  browserconsole: status == 'failed' ? pluginOutput.browserconsole : [],
346
314
  });
347
- /**
348
- * Wait for the all the reported events to be consumed aschronously
349
- * by reporter.
350
- */
351
- if (options.reporter === 'json') {
352
- await once(this, 'journey:end:reported');
353
- }
354
315
  // clear screenshots cache after each journey
355
316
  await rm(Runner.screenshotPath, { recursive: true, force: true });
356
317
  }
@@ -360,8 +321,7 @@ export default class Runner extends EventEmitter {
360
321
  */
361
322
  async runFakeJourney(journey: Journey, options: RunOptions) {
362
323
  const start = monotonicTimeInSeconds();
363
- this.emit('journey:start', {
364
- journey,
324
+ this.#reporter.onJourneyStart?.(journey, {
365
325
  timestamp: getTimestamp(),
366
326
  params: options.params,
367
327
  });
@@ -369,24 +329,18 @@ export default class Runner extends EventEmitter {
369
329
  status: 'failed',
370
330
  error: this.hookError,
371
331
  };
372
- this.emit('journey:end', {
373
- journey,
332
+ await this.#reporter.onJourneyEnd?.(journey, {
374
333
  timestamp: getTimestamp(),
375
334
  start,
376
335
  options,
377
336
  end: monotonicTimeInSeconds(),
378
337
  ...result,
379
338
  });
380
- if (options.reporter === 'json') {
381
- await once(this, 'journey:end:reported');
382
- }
383
339
  return result;
384
340
  }
385
341
 
386
342
  async runJourney(journey: Journey, options: RunOptions) {
387
- const result: JourneyResult = {
388
- status: 'succeeded',
389
- };
343
+ const result: JourneyResult = { status: 'succeeded' };
390
344
  const context = await Runner.createContext(options);
391
345
  log(`Runner: start journey (${journey.name})`);
392
346
  try {
@@ -419,18 +373,10 @@ export default class Runner extends EventEmitter {
419
373
  }
420
374
 
421
375
  async init(options: RunOptions) {
422
- const { reporter, outfd, networkConditions } = options;
423
- /**
424
- * Set up the corresponding reporter and fallback
425
- */
426
- const Reporter =
427
- typeof reporter === 'function'
428
- ? reporter
429
- : reporters[reporter] || reporters['default'];
430
- new Reporter(this, { fd: outfd });
431
- this.emit('start', {
376
+ this.setReporter(options);
377
+ this.#reporter.onStart?.({
432
378
  numJourneys: this.journeys.length,
433
- networkConditions,
379
+ networkConditions: options.networkConditions,
434
380
  });
435
381
  /**
436
382
  * Set up the directory for caching screenshots
@@ -438,12 +384,39 @@ export default class Runner extends EventEmitter {
438
384
  await mkdirAsync(CACHE_PATH, { recursive: true });
439
385
  }
440
386
 
387
+ buildMonitors(options: RunOptions) {
388
+ /**
389
+ * Update the global monitor configuration required for
390
+ * setting defaults
391
+ */
392
+ this.updateMonitor({
393
+ throttling: options.throttling,
394
+ schedule: options.schedule,
395
+ locations: options.locations,
396
+ params: options.params,
397
+ playwrightOptions: options.playwrightOptions,
398
+ });
399
+
400
+ const monitors: Monitor[] = [];
401
+ for (const journey of this.journeys) {
402
+ this.#currentJourney = journey;
403
+ /**
404
+ * Execute dummy callback to get all monitor specific
405
+ * configurations for the current journey
406
+ */
407
+ journey.callback({ params: options.params } as any);
408
+ journey.monitor.update(this.monitor?.config);
409
+ monitors.push(journey.monitor);
410
+ }
411
+ return monitors;
412
+ }
413
+
441
414
  async run(options: RunOptions) {
442
415
  const result: RunResult = {};
443
- if (this.active) {
416
+ if (this.#active) {
444
417
  return result;
445
418
  }
446
- this.active = true;
419
+ this.#active = true;
447
420
  log(`Runner: run ${this.journeys.length} journeys`);
448
421
  this.init(options);
449
422
  await this.runBeforeAllHook({
@@ -457,7 +430,7 @@ export default class Runner extends EventEmitter {
457
430
  * Used by heartbeat to gather all registered journeys
458
431
  */
459
432
  if (dryRun) {
460
- this.emit('journey:register', { journey });
433
+ this.#reporter.onJourneyRegister?.(journey);
461
434
  continue;
462
435
  }
463
436
  if (!journey.isMatch(match, tags)) {
@@ -478,14 +451,14 @@ export default class Runner extends EventEmitter {
478
451
  }
479
452
 
480
453
  async reset() {
454
+ this.#currentJourney = null;
455
+ this.journeys = [];
456
+ this.#active = false;
481
457
  /**
482
458
  * Clear all cache data stored for post processing by
483
459
  * the current synthetic agent run
484
460
  */
485
461
  await rm(CACHE_PATH, { recursive: true, force: true });
486
- this.currentJourney = null;
487
- this.journeys = [];
488
- this.active = false;
489
- this.emit('end', {});
462
+ await this.#reporter?.onEnd?.();
490
463
  }
491
464
  }
@@ -27,6 +27,7 @@ import { Browser, Page, BrowserContext, CDPSession } from 'playwright-chromium';
27
27
  import micromatch, { isMatch } from 'micromatch';
28
28
  import { Step } from './step';
29
29
  import { VoidCallback, HooksCallback, Params, Location } from '../common_types';
30
+ import { Monitor, MonitorConfig } from './monitor';
30
31
 
31
32
  export type JourneyOptions = {
32
33
  name: string;
@@ -52,6 +53,7 @@ export class Journey {
52
53
  location?: Location;
53
54
  steps: Step[] = [];
54
55
  hooks: Hooks = { before: [], after: [] };
56
+ monitor: Monitor;
55
57
 
56
58
  constructor(
57
59
  options: JourneyOptions,
@@ -63,6 +65,7 @@ export class Journey {
63
65
  this.tags = options.tags;
64
66
  this.callback = callback;
65
67
  this.location = location;
68
+ this.updateMonitor({});
66
69
  }
67
70
 
68
71
  addStep(name: string, callback: VoidCallback, location?: Location) {
@@ -74,6 +77,21 @@ export class Journey {
74
77
  addHook(type: HookType, callback: HooksCallback) {
75
78
  this.hooks[type].push(callback);
76
79
  }
80
+
81
+ updateMonitor(config: MonitorConfig) {
82
+ /**
83
+ * Use defaults values from journey for monitor object (id, name and tags)
84
+ */
85
+ this.monitor = new Monitor({
86
+ name: this.name,
87
+ id: this.id,
88
+ tags: this.tags ?? [],
89
+ ...config,
90
+ });
91
+ this.monitor.setSource(this.location);
92
+ this.monitor.setFilter({ match: this.name });
93
+ }
94
+
77
95
  /**
78
96
  * Matches journeys based on the provided args. Proitize tags over match
79
97
  * - tags pattern that matches only tags
@@ -0,0 +1,83 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2020-present, Elastic NV
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in
14
+ * all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ * THE SOFTWARE.
23
+ *
24
+ */
25
+
26
+ import merge from 'deepmerge';
27
+ import {
28
+ ThrottlingOptions,
29
+ Location,
30
+ ScreenshotOptions,
31
+ Params,
32
+ PlaywrightOptions,
33
+ } from '../common_types';
34
+
35
+ export const SyntheticsLocations = ['US East', 'EU West'] as const;
36
+ export type SyntheticsLocationsType = typeof SyntheticsLocations[number];
37
+ export type MonitorConfig = {
38
+ id?: string;
39
+ name?: string;
40
+ tags?: string[];
41
+ schedule?: number;
42
+ enabled?: boolean;
43
+ locations?: SyntheticsLocationsType[];
44
+ throttling?: ThrottlingOptions;
45
+ screenshot?: ScreenshotOptions;
46
+ params?: Params;
47
+ playwrightOptions?: PlaywrightOptions;
48
+ };
49
+
50
+ type MonitorFilter = {
51
+ match: string;
52
+ tags?: string[];
53
+ };
54
+
55
+ export class Monitor {
56
+ source?: Location;
57
+ filter: MonitorFilter;
58
+ constructor(public config: MonitorConfig = {}) {}
59
+ /**
60
+ * Treat the creation time config with `monitor.use` as source of truth by
61
+ * merging the values coming from CLI and Synthetics config file
62
+ */
63
+ update(globalOpts: MonitorConfig = {}) {
64
+ this.config = merge(globalOpts, this.config, {
65
+ arrayMerge(target, source) {
66
+ return [...new Set(source)];
67
+ },
68
+ });
69
+ }
70
+
71
+ setSource(source: Location) {
72
+ this.source = source;
73
+ }
74
+ /**
75
+ * If journey files are colocated within the same file during
76
+ * push command, when we invoke synthetics from HB we rely on
77
+ * this filter for running that specific journey alone instead of
78
+ * all journeys on the file
79
+ */
80
+ setFilter(filter: MonitorFilter) {
81
+ this.filter = filter;
82
+ }
83
+ }
@@ -26,7 +26,7 @@
26
26
  import {
27
27
  JavaScriptLanguageGenerator,
28
28
  JavaScriptFormatter,
29
- } from 'playwright-chromium/lib/server/supplements/recorder/javascript';
29
+ } from 'playwright-core/lib/server/supplements/recorder/javascript';
30
30
 
31
31
  export type Step = {
32
32
  actions: ActionInContext[];
@@ -0,0 +1,159 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2020-present, Elastic NV
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in
14
+ * all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ * THE SOFTWARE.
23
+ *
24
+ */
25
+ import { execSync } from 'child_process';
26
+ import { existsSync } from 'fs';
27
+ import { mkdir, readFile, writeFile } from 'fs/promises';
28
+ import { bold, cyan, yellow } from 'kleur/colors';
29
+ import { join, relative, dirname, basename } from 'path';
30
+ import { progress, write as stdWrite } from '../helpers';
31
+ import { getPackageManager, runCommand } from './utils';
32
+
33
+ // Templates that are required for setting up new
34
+ // synthetics project
35
+ const templateDir = join(__dirname, '..', '..', 'templates');
36
+
37
+ export class Generator {
38
+ pkgManager = 'npm';
39
+ constructor(public projectDir: string) {}
40
+
41
+ async directory() {
42
+ if (!existsSync(this.projectDir)) {
43
+ await mkdir(this.projectDir);
44
+ }
45
+ }
46
+
47
+ async files() {
48
+ const fileMap = new Map<string, string>();
49
+ // Setup Synthetics config file
50
+ const configFile = 'synthetics.config.ts';
51
+ fileMap.set(
52
+ configFile,
53
+ await readFile(join(templateDir, configFile), 'utf-8')
54
+ );
55
+
56
+ // Setup example journey file
57
+ const journeyFile = 'journeys/example.journey.ts';
58
+ fileMap.set(
59
+ journeyFile,
60
+ await readFile(join(templateDir, journeyFile), 'utf-8')
61
+ );
62
+ // Setup gitignore
63
+ fileMap.set(
64
+ '.gitignore',
65
+ await readFile(join(templateDir, '.gitignore'), 'utf-8')
66
+ );
67
+
68
+ // Create files
69
+ for (const [relativePath, content] of fileMap) {
70
+ await this.createFile(relativePath, content);
71
+ }
72
+ }
73
+
74
+ async createFile(relativePath: string, content: string, override = false) {
75
+ const absolutePath = join(this.projectDir, relativePath);
76
+ if (override || !existsSync(absolutePath)) {
77
+ progress(`Writing ${relative(process.cwd(), absolutePath)}.`);
78
+ await mkdir(dirname(absolutePath), { recursive: true });
79
+ await writeFile(absolutePath, content, 'utf-8');
80
+ }
81
+ }
82
+
83
+ async package() {
84
+ this.pkgManager = await getPackageManager(this.projectDir);
85
+ const commands = new Map<string, string>();
86
+ commands.set(
87
+ `Initializing Synthetics project using ${
88
+ this.pkgManager == 'yarn' ? 'Yarn' : 'NPM'
89
+ }`,
90
+ this.pkgManager == 'yarn' ? 'yarn init -y' : 'npm init -y'
91
+ );
92
+
93
+ const pkgName = '@elastic/synthetics';
94
+ commands.set(
95
+ `Installing @elastic/synthetics library`,
96
+ this.pkgManager == 'yarn'
97
+ ? `yarn add -dev ${pkgName}`
98
+ : `npm i -d ${pkgName}`
99
+ );
100
+
101
+ // Execute commands
102
+ for (const [name, command] of commands) {
103
+ progress(`${name}...`);
104
+ execSync(command, {
105
+ stdio: 'inherit',
106
+ cwd: this.projectDir,
107
+ });
108
+ }
109
+ }
110
+
111
+ async patchPkgJSON() {
112
+ const filename = 'package.json';
113
+ const pkgJSON = JSON.parse(
114
+ await readFile(join(this.projectDir, filename), 'utf-8')
115
+ );
116
+
117
+ if (!pkgJSON.scripts) {
118
+ pkgJSON.scripts = {};
119
+ }
120
+ // Add test command
121
+ pkgJSON.scripts.test = 'npx @elastic/synthetics journeys';
122
+
123
+ // Add push command
124
+ const project = basename(this.projectDir);
125
+ pkgJSON.scripts.push = `npx @elastic/synthetics push journeys --project ${project} --url http://localhost:5601 --auth basic-auth`;
126
+
127
+ await this.createFile(
128
+ filename,
129
+ JSON.stringify(pkgJSON, null, 2) + '\n',
130
+ true
131
+ );
132
+ }
133
+
134
+ banner() {
135
+ stdWrite(
136
+ bold(`
137
+ All set, you can run below commands inside: ${this.projectDir}:
138
+
139
+ Run synthetic tests: ${cyan(runCommand(this.pkgManager, 'test'))}
140
+
141
+ Push monitors to Kibana: ${cyan(runCommand(this.pkgManager, 'push'))}
142
+
143
+ ${yellow(
144
+ 'Make sure to update the Kibana url and authentication info before pushing monitors to Kibana.'
145
+ )}
146
+
147
+ Visit https://www.elastic.co/guide/en/observability/master/synthetics-journeys.html to learn more.
148
+ `)
149
+ );
150
+ }
151
+
152
+ async setup() {
153
+ await this.directory();
154
+ await this.package();
155
+ await this.files();
156
+ await this.patchPkgJSON();
157
+ this.banner();
158
+ }
159
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2020-present, Elastic NV
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in
14
+ * all copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ * THE SOFTWARE.
23
+ *
24
+ */
25
+
26
+ import { existsSync } from 'fs';
27
+ import { join } from 'path';
28
+
29
+ export async function getPackageManager(dir: string) {
30
+ if (existsSync(join(dir, 'yarn.lock'))) {
31
+ return 'yarn';
32
+ }
33
+ return 'npm';
34
+ }
35
+
36
+ export function runCommand(pkgManager: string, command: string) {
37
+ if (pkgManager === 'yarn') {
38
+ return `yarn ${command}`;
39
+ }
40
+ return `npm run ${command}`;
41
+ }