webship-js 2.0.3 → 2.0.4

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 (49) hide show
  1. package/.circleci/config.yml +7 -31
  2. package/.drone.yml +68 -0
  3. package/.harness/webship-js-pipeline.yml +101 -0
  4. package/.semaphore/semaphore.yml +58 -0
  5. package/.teamcity/pom.xml +52 -0
  6. package/.teamcity/settings.kts +92 -0
  7. package/.travis.yml +24 -3
  8. package/AGENTS.md +2 -2
  9. package/CLAUDE.md +2 -2
  10. package/Jenkinsfile +54 -0
  11. package/azure-pipelines.yml +82 -0
  12. package/bamboo-specs/bamboo.yml +131 -0
  13. package/buildspec.yml +56 -0
  14. package/cloudbuild.yaml +49 -0
  15. package/codefresh.yml +77 -0
  16. package/cucumber.js +40 -3
  17. package/docs/04-step-reference.md +74 -3
  18. package/docs/16-ci-cd.md +879 -0
  19. package/docs/README.md +113 -0
  20. package/docs/global-settings.md +51 -0
  21. package/examples/video-demo.html +43 -0
  22. package/package.json +1 -1
  23. package/tests/features/video.feature +18 -0
  24. package/tests/step-definitions/a11y.steps.js +3 -1
  25. package/tests/step-definitions/action.steps.js +2 -2
  26. package/tests/step-definitions/api.steps.js +17 -16
  27. package/tests/step-definitions/assertion.steps.js +2 -2
  28. package/tests/step-definitions/auth.steps.js +3 -1
  29. package/tests/step-definitions/clock.steps.js +38 -38
  30. package/tests/step-definitions/debug.steps.js +13 -5
  31. package/tests/step-definitions/element.steps.js +47 -5
  32. package/tests/step-definitions/file-download.steps.js +38 -20
  33. package/tests/step-definitions/form.steps.js +6 -6
  34. package/tests/step-definitions/iframe.steps.js +65 -15
  35. package/tests/step-definitions/input.steps.js +47 -8
  36. package/tests/step-definitions/javascript.steps.js +195 -34
  37. package/tests/step-definitions/keyboard.steps.js +38 -4
  38. package/tests/step-definitions/modal.steps.js +39 -14
  39. package/tests/step-definitions/network.steps.js +61 -19
  40. package/tests/step-definitions/responsive.steps.js +3 -1
  41. package/tests/step-definitions/selectors.steps.js +19 -17
  42. package/tests/step-definitions/video.steps.js +178 -0
  43. package/tests/step-definitions/web-first.steps.js +3 -1
  44. package/tests/step-definitions/webship.js +234 -15
  45. package/tests/step-definitions/xml.steps.js +4 -2
  46. package/tests/step-definitions/yaml.steps.js +13 -11
  47. package/videos/README.md +32 -0
  48. package/.travis-ci.yml +0 -16
  49. package/docs/index.md +0 -104
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { friendly } = require('./webship');
4
+
3
5
  // ---------------------------------------------------------------------------
4
6
  // Webship-JS — Selectors step definitions
5
7
  //
@@ -62,7 +64,7 @@ const path = require('path');
62
64
  function parseFile(filePath) {
63
65
  const ext = path.extname(filePath).toLowerCase();
64
66
  if (ext !== '.json') {
65
- throw new Error(`Selector files must be JSON (got "${ext}" for "${filePath}").`);
67
+ throw friendly(`Selector files must be JSON (got "${ext}" for "${filePath}").`);
66
68
  }
67
69
  return JSON.parse(fs.readFileSync(filePath, 'utf8'));
68
70
  }
@@ -120,7 +122,7 @@ Before(function () {
120
122
  if (parsed && parsed.css) Object.assign(this.__selectorsCss, parsed.css);
121
123
  if (parsed && parsed.xpath) Object.assign(this.__selectorsXpath, parsed.xpath);
122
124
  } catch (e) {
123
- throw new Error(`Selectors: failed to load selector file "${filePath}": ${e.message}`);
125
+ throw friendly(`Selectors: failed to load selector file "${filePath}": ${e.message}`);
124
126
  }
125
127
  }
126
128
  });
@@ -173,7 +175,7 @@ function resolveSelector(world, name) {
173
175
  ? `\n Registered names: ${known.slice(0, 8).join(', ')}${known.length > 8 ? ', ...' : ''}`
174
176
  : '\n No selectors registered yet.';
175
177
 
176
- throw new Error(
178
+ throw friendly(
177
179
  `Unknown selector "${trimmed}".${suggestion}${examples}\n` +
178
180
  ` Register one with:\n` +
179
181
  ` Given I define css selectors:\n` +
@@ -219,9 +221,9 @@ async function getGeometry(page, selector) {
219
221
 
220
222
  async function assertPosition(page, position, c1Name, c1Sel, c2Name, c2Sel) {
221
223
  const g1 = await getGeometry(page, c1Sel);
222
- if (!g1) throw new Error(`Cannot get bounding box for "${c1Name}" (${c1Sel}) — element not visible`);
224
+ if (!g1) throw friendly(`Cannot get bounding box for "${c1Name}" (${c1Sel}) — element not visible`);
223
225
  const g2 = await getGeometry(page, c2Sel);
224
- if (!g2) throw new Error(`Cannot get bounding box for "${c2Name}" (${c2Sel}) — element not visible`);
226
+ if (!g2) throw friendly(`Cannot get bounding box for "${c2Name}" (${c2Sel}) — element not visible`);
225
227
 
226
228
  let pass = false;
227
229
  switch (position) {
@@ -262,7 +264,7 @@ async function dispatcher(world, position, subjectText, othersText, negate = fal
262
264
  } catch (e) { errors.push(e.message); }
263
265
  }
264
266
  }
265
- if (errors.length > 0) throw new Error(errors.join('\n'));
267
+ if (errors.length > 0) throw friendly(errors.join('\n'));
266
268
  }
267
269
 
268
270
  // ===========================================================================
@@ -296,7 +298,7 @@ async function dispatcher(world, position, subjectText, othersText, negate = fal
296
298
  * And I add "cta link" selector for "//a[contains(@class,'cta')]" xpath selector
297
299
  */
298
300
  When(/^(I |we )*add "([^"]*)" selector for "([^"]*)" css selector$/, function (pronounCase, selectorName, cssSelector) {
299
- if (!selectorName || !cssSelector) throw new Error('Selectors: selector name and CSS selector must not be empty.');
301
+ if (!selectorName || !cssSelector) throw friendly('Selectors: selector name and CSS selector must not be empty.');
300
302
  this.__selectorsCss[selectorName.trim()] = cssSelector.trim();
301
303
  });
302
304
 
@@ -323,7 +325,7 @@ When(/^(I |we )*add "([^"]*)" selector for "([^"]*)" css selector$/, function (p
323
325
  * When I add "last nav item" selector for "//nav[@role='navigation']//a[last()]" xpath selector
324
326
  */
325
327
  When(/^(I |we )*add "([^"]*)" selector for "([^"]*)" xpath selector$/, function (pronounCase, selectorName, xpathSelector) {
326
- if (!selectorName || !xpathSelector) throw new Error('Selectors: selector name and XPath selector must not be empty.');
328
+ if (!selectorName || !xpathSelector) throw friendly('Selectors: selector name and XPath selector must not be empty.');
327
329
  this.__selectorsXpath[selectorName.trim()] = xpathSelector.trim();
328
330
  });
329
331
 
@@ -357,12 +359,12 @@ When(/^(I |we )*add "([^"]*)" selector for "([^"]*)" xpath selector$/, function
357
359
  */
358
360
  When(/^(I |we )*add selectors from "([^"]*)" file$/, function (pronounCase, fileName) {
359
361
  const cfg = this.__selectorsConfig;
360
- if (!fileName) throw new Error('Selectors: file name must not be empty.');
361
- if (!cfg.filesPath) throw new Error('Selectors: worldParameters.selectors.filesPath must be set to load selector files.');
362
+ if (!fileName) throw friendly('Selectors: file name must not be empty.');
363
+ if (!cfg.filesPath) throw friendly('Selectors: worldParameters.selectors.filesPath must be set to load selector files.');
362
364
  const filePath = path.join(cfg.filesPath, fileName);
363
365
  let parsed;
364
366
  try { parsed = parseFile(filePath); } catch (e) {
365
- throw new Error(`Selectors: failed to load selector file "${filePath}": ${e.message}`);
367
+ throw friendly(`Selectors: failed to load selector file "${filePath}": ${e.message}`);
366
368
  }
367
369
  if (parsed && parsed.css) Object.assign(this.__selectorsCss, parsed.css);
368
370
  if (parsed && parsed.xpath) Object.assign(this.__selectorsXpath, parsed.xpath);
@@ -569,7 +571,7 @@ Given(/^(I |we )*define xpath selectors:$/, function (pronounCase, dataTable) {
569
571
  Given(/^(I am |we are )?viewing the site on a (?:"([^"]+)"|([a-zA-Z0-9 _,]+)) (?:screen|device)$/, async function (pronounCase, quoted, bare) {
570
572
  const name = (quoted || bare || '').trim();
571
573
  const cfg = this.__selectorsConfig;
572
- if (!cfg.breakpoints[name]) throw new Error(`Selectors: breakpoint "${name}" not defined in worldParameters.selectors.breakpoints.`);
574
+ if (!cfg.breakpoints[name]) throw friendly(`Selectors: breakpoint "${name}" not defined in worldParameters.selectors.breakpoints.`);
573
575
  const { width, height } = cfg.breakpoints[name];
574
576
  await this.page.setViewportSize({ width, height });
575
577
  });
@@ -772,7 +774,7 @@ Then(/^(I |we )*see visible ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, s
772
774
  try { await this.page.locator(sel).first().waitFor({ state: 'visible', timeout: 5000 }); }
773
775
  catch { errors.push(`"${name}" (${sel}) is not visible`); }
774
776
  }
775
- if (errors.length > 0) throw new Error(errors.join('\n'));
777
+ if (errors.length > 0) throw friendly(errors.join('\n'));
776
778
  });
777
779
 
778
780
  /**
@@ -798,7 +800,7 @@ Then(/^(I |we )*(don't|do not) see ([a-zA-Z0-9 ,\-]+)$/, async function (pronoun
798
800
  try { await this.page.locator(sel).first().waitFor({ state: 'hidden', timeout: 5000 }); }
799
801
  catch { errors.push(`"${name}" (${sel}) is visible (expected hidden)`); }
800
802
  }
801
- if (errors.length > 0) throw new Error(errors.join('\n'));
803
+ if (errors.length > 0) throw friendly(errors.join('\n'));
802
804
  });
803
805
 
804
806
  /**
@@ -825,7 +827,7 @@ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) has focus$/, async function (pronounCase,
825
827
  const handle = await loc.elementHandle();
826
828
  await this.page.waitForFunction((el) => el === document.activeElement, handle, { timeout: 5000 });
827
829
  } catch {
828
- throw new Error(`"${name}" (${sel}) does not have focus`);
830
+ throw friendly(`"${name}" (${sel}) does not have focus`);
829
831
  }
830
832
  });
831
833
 
@@ -944,7 +946,7 @@ When(/^(I |we )*select "([^"]*)" text in "([^"]*)" field$/, async function (pron
944
946
 
945
947
  const value = await loc.inputValue();
946
948
  const start = value.indexOf(selectedText);
947
- if (start === -1) throw new Error(`Text "${selectedText}" not found in field "${fieldLabel}"`);
949
+ if (start === -1) throw friendly(`Text "${selectedText}" not found in field "${fieldLabel}"`);
948
950
  const end = start + selectedText.length;
949
951
 
950
952
  await loc.focus();
@@ -992,5 +994,5 @@ When(/^(I |we )*click (?:on |a )?([a-zA-Z0-9 ,\-]+)$/, async function (pronounCa
992
994
  try { await this.page.locator(sel).first().click(); }
993
995
  catch (e) { errors.push(`Cannot click "${name}" (${sel}): ${e.message}`); }
994
996
  }
995
- if (errors.length > 0) throw new Error(errors.join('\n'));
997
+ if (errors.length > 0) throw friendly(errors.join('\n'));
996
998
  });
@@ -0,0 +1,178 @@
1
+ 'use strict';
2
+
3
+ const { friendly } = require('./webship');
4
+
5
+ // Video recording steps — start / stop / save mid-scenario.
6
+ //
7
+ // Playwright records video only at browser-context creation. Mid-scenario
8
+ // `start` / `stop` therefore work by tearing down the current page +
9
+ // context and reopening with the new recording flag. Page state is lost
10
+ // across the boundary — call `start` BEFORE any navigation and `stop` only
11
+ // when you no longer need the current page state.
12
+ //
13
+ // Default mode is 'off' (no recording). See cucumber.js → worldParameters.video.
14
+
15
+ const { When, Then } = require('@cucumber/cucumber');
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+
19
+ function settings(world) {
20
+ const cfg = (world.parameters && world.parameters.video) || {};
21
+ return {
22
+ dir: process.env.WEBSHIP_VIDEO_DIR || cfg.dir || './videos',
23
+ size: cfg.size || { width: 1280, height: 720 },
24
+ };
25
+ }
26
+
27
+ async function rebuildContext(world, recordVideo) {
28
+ await world.closeBrowser();
29
+ if (recordVideo) {
30
+ const s = settings(world);
31
+ fs.mkdirSync(s.dir, { recursive: true });
32
+ world._videoRequested = true;
33
+ await world.openBrowser({ recordVideo: { dir: s.dir, size: s.size } });
34
+ } else {
35
+ world._videoRequested = false;
36
+ await world.openBrowser();
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Start recording the browser as a webm video. Closes the current page +
42
+ * context and reopens with `recordVideo` enabled. Place BEFORE any
43
+ * navigation in the scenario.
44
+ *
45
+ * Example #1: When I start video recording
46
+ * Example #2: And I start video recording
47
+ * Example #3: Given I start video recording
48
+ * Example #4: But I start video recording
49
+ * Example #5: Then I start video recording
50
+ *
51
+ */
52
+ When(/^(I |we )*start video recording$/, async function (pronoun) {
53
+ try {
54
+ await rebuildContext(this, true);
55
+ } catch (e) {
56
+ throw friendly({
57
+ action: 'start video recording',
58
+ cause: e,
59
+ hint: `the videos directory (${(this.parameters && this.parameters.video && this.parameters.video.dir) || './videos'}) must be writable.`,
60
+ });
61
+ }
62
+ });
63
+
64
+ /**
65
+ * Stop recording. Closes the current page + context (which flushes the
66
+ * webm to disk) and reopens a fresh, non-recording browser so the rest
67
+ * of the scenario can continue.
68
+ *
69
+ * Example #1: When I stop video recording
70
+ * Example #2: And I stop video recording
71
+ * Example #3: But I stop video recording
72
+ * Example #4: Then I stop video recording
73
+ * Example #5: Then I stop video recording
74
+ *
75
+ */
76
+ When(/^(I |we )*stop video recording$/, async function (pronoun) {
77
+ try {
78
+ if (!this.page || !this._videoRequested) return;
79
+ const video = this.page.video();
80
+ // Close context first — flushes the webm — then saveAs while the
81
+ // browser is still alive, finally close the browser and reopen fresh.
82
+ try { await this.context.close(); } catch { /* ignore */ }
83
+ if (video) {
84
+ try {
85
+ const s = settings(this);
86
+ const name = this._videoSaveAsName || `manual.${Date.now()}.webm`;
87
+ const dest = path.join(s.dir, name);
88
+ await video.saveAs(dest);
89
+ await video.delete().catch(() => {});
90
+ process.stderr.write(`\n[webship-js] video saved → ${dest}\n`);
91
+ // Reset so the After hook does not try to re-save.
92
+ this._videoSaveAsName = null;
93
+ } catch (e) {
94
+ process.stderr.write(`\n[webship-js] video save failed: ${e.message}\n`);
95
+ }
96
+ }
97
+ if (this.playwrightBrowser) {
98
+ try { await this.playwrightBrowser.close(); } catch { /* ignore */ }
99
+ this.playwrightBrowser = null;
100
+ }
101
+ this.context = null;
102
+ this.page = null;
103
+ this._videoRequested = false;
104
+ await this.openBrowser();
105
+ } catch (e) {
106
+ throw friendly({
107
+ action: 'stop video recording',
108
+ cause: e,
109
+ hint: 'the scenario will continue with a fresh, non-recording browser.',
110
+ });
111
+ }
112
+ });
113
+
114
+ /**
115
+ * Reserve a custom filename for the current scenario's video. The actual
116
+ * save happens at scenario end (Playwright's `video.saveAs()` blocks
117
+ * until recording finishes, so we cannot copy bytes mid-flight). If the
118
+ * scenario calls `stop video recording` before scenario end, the manual
119
+ * webm uses this name instead of the automatic timestamped one.
120
+ *
121
+ * Example #1: When I save the current video as "checkout-flow.webm"
122
+ * Example #2: When I save the current video as "regression-21.webm"
123
+ * Example #3: And I save the current video as "smoke.webm"
124
+ * Example #4: Then I save the current video as "demo.webm"
125
+ * Example #5: But I save the current video as "rerun.webm"
126
+ *
127
+ */
128
+ When(/^(I |we )*save the current video as "([^"]*)"$/, function (pronoun, name) {
129
+ try {
130
+ if (!this._videoRequested) {
131
+ throw new Error('recording is not active');
132
+ }
133
+ if (!name || !name.trim()) {
134
+ throw new Error('filename is empty');
135
+ }
136
+ this._videoSaveAsName = name;
137
+ } catch (e) {
138
+ throw friendly({
139
+ action: `save the current video as "${name}"`,
140
+ cause: e,
141
+ hint: 'call "When I start video recording" first, or set worldParameters.video.mode to "on".',
142
+ });
143
+ }
144
+ });
145
+
146
+ /**
147
+ * Print the path that the current video will be written to. Diagnostic
148
+ * only — never asserts, never fails.
149
+ *
150
+ * Example #1: Then print video path
151
+ * Example #2: And print video path
152
+ * Example #3: But print video path
153
+ * Example #4: Then print video path
154
+ * Example #5: Then print video path
155
+ *
156
+ */
157
+ Then(/^print video path$/, async function () {
158
+ // Diagnostic only — swallow every error and report inline.
159
+ try {
160
+ if (!this.page || !this._videoRequested) {
161
+ console.log('\n--- Video path: recording is OFF ---');
162
+ return;
163
+ }
164
+ const video = this.page.video();
165
+ if (!video) {
166
+ console.log('\n--- Video path: no video object on this page ---');
167
+ return;
168
+ }
169
+ try {
170
+ const p = await video.path();
171
+ console.log(`\n--- Video path: ${p} ---`);
172
+ } catch (e) {
173
+ console.log(`\n--- Video path unavailable: ${e.message} ---`);
174
+ }
175
+ } catch (e) {
176
+ console.log(`\n--- Video path error: ${e.message} ---`);
177
+ }
178
+ });
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { friendly } = require('./webship');
4
+
3
5
  // Web-first assertion steps — each matcher polls the live page until the
4
6
  // condition holds or the per-step timeout elapses. The assertion IS the
5
7
  // wait, so no `wait for AJAX` is required between an action and its check.
@@ -29,7 +31,7 @@ async function poll(fn, predicate, timeout, message) {
29
31
  }
30
32
  await new Promise((r) => setTimeout(r, 100));
31
33
  }
32
- throw new Error(`${message} (last seen: ${typeof last === 'object' ? JSON.stringify(last) : String(last)})`);
34
+ throw friendly(`${message} (last seen: ${typeof last === 'object' ? JSON.stringify(last) : String(last)})`);
33
35
  }
34
36
 
35
37
  async function checkState(locator, state) {
@@ -5,6 +5,31 @@ const playwright = require('playwright');
5
5
  const playwrightConfig = require(require('path').join(process.cwd(), 'playwright.config'));
6
6
  const path = require('path');
7
7
 
8
+ // ---------------------------------------------------------------------------
9
+ // Output filter — strip noisy `✔ Before # ...` / `✔ After # ...` hook lines
10
+ // from cucumber-js's failure dump so tester-facing output stays focused on
11
+ // the failing step + hint. Disable with WEBSHIP_FILTER_HOOK_LINES=off.
12
+ // ---------------------------------------------------------------------------
13
+ if (process.env.WEBSHIP_FILTER_HOOK_LINES !== 'off') {
14
+ const HOOK_LINE = /^\s*[✔✖✗⚠?-]\s+(?:Before|After|BeforeStep|AfterStep)\b.*$/;
15
+ const wrap = (stream) => {
16
+ const orig = stream.write.bind(stream);
17
+ stream.write = (chunk, encoding, cb) => {
18
+ if (typeof chunk === 'string' || Buffer.isBuffer(chunk)) {
19
+ const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8');
20
+ const filtered = text
21
+ .split('\n')
22
+ .filter((line) => !HOOK_LINE.test(line.replace(/\x1b\[[0-9;]*m/g, '')))
23
+ .join('\n');
24
+ return orig(filtered, encoding, cb);
25
+ }
26
+ return orig(chunk, encoding, cb);
27
+ };
28
+ };
29
+ wrap(process.stdout);
30
+ wrap(process.stderr);
31
+ }
32
+
8
33
  // ===========================================================================
9
34
  // Internal helpers (BBR smart settle, modal probes, selector + text utilities).
10
35
  // Imported by every *.steps.js file via require('./webship'). Defined here
@@ -166,7 +191,7 @@ async function findVisibleModal(page, world) {
166
191
  if (await all.nth(i).isVisible()) return all.nth(i);
167
192
  }
168
193
  const sel = getModalSelector(world);
169
- throw new Error(
194
+ throw friendly(
170
195
  `No visible modal found.\n` +
171
196
  ` Selector tried: ${sel}\n` +
172
197
  ` Hint: did you "wait for the modal to appear" first?\n` +
@@ -257,7 +282,7 @@ async function gotoUrl(page, url) {
257
282
  if (/NS_ERROR_NET_EMPTY_RESPONSE|net::ERR_EMPTY_RESPONSE/.test(msg)) return;
258
283
  // Connection refused: server probably not running.
259
284
  if (/ECONNREFUSED|net::ERR_CONNECTION_REFUSED/.test(msg)) {
260
- throw new Error(
285
+ throw friendly(
261
286
  `Could not reach "${url}".\n` +
262
287
  ` ${msg.split('\n')[0]}\n` +
263
288
  ` Hint: is your dev server running? Check LAUNCH_URL env var.`
@@ -265,15 +290,14 @@ async function gotoUrl(page, url) {
265
290
  }
266
291
  // DNS failure.
267
292
  if (/ERR_NAME_NOT_RESOLVED|NS_ERROR_UNKNOWN_HOST/.test(msg)) {
268
- throw new Error(
293
+ throw friendly(
269
294
  `Could not resolve host for "${url}".\n` +
270
295
  ` ${msg.split('\n')[0]}\n` +
271
296
  ` Hint: double-check the hostname in LAUNCH_URL or your "Given I am on" path.`
272
297
  );
273
298
  }
274
- // Anything else — preserve original stack but prepend context.
275
- e.message = `Failed to navigate to "${url}":\n ${e.message}`;
276
- throw e;
299
+ // Anything else — strip the stack trace too.
300
+ throw friendly(`Failed to navigate to "${url}":\n ${e.message}`);
277
301
  }
278
302
  }
279
303
 
@@ -303,7 +327,7 @@ async function fillField(page, field, value) {
303
327
  await byName.fill(value);
304
328
  return;
305
329
  }
306
- throw new Error(
330
+ throw friendly(
307
331
  `Could not find a field for "${field}".\n` +
308
332
  ` Tried: getByLabel(exact), getByPlaceholder(exact), [name="${field}"].\n` +
309
333
  ` Hints: check the label/placeholder text matches exactly (case-sensitive),\n` +
@@ -470,6 +494,86 @@ BeforeStep(function (scope) {
470
494
  }
471
495
  });
472
496
 
497
+ /**
498
+ * Translate a raw Playwright / Node / HTTP error message into one short,
499
+ * plain-English sentence aimed at non-coder testers. Falls back to a
500
+ * cleaned-up first line of the original when no pattern matches.
501
+ *
502
+ * @param {Error|string} err
503
+ * @returns {string}
504
+ */
505
+ function humanize(err) {
506
+ const msg = typeof err === 'string' ? err : (err && err.message) || '';
507
+ const first = msg.split('\n')[0].trim();
508
+ // Common Playwright / Node patterns → plain English.
509
+ const map = [
510
+ [/Timeout\s+\d+ms\s+exceeded/i, 'the page took too long to respond'],
511
+ [/locator\.(click|press|fill|hover|dblclick|tap|focus|dispatchEvent|scrollIntoViewIfNeeded)/i,
512
+ 'the element could not be reached'],
513
+ [/strict mode violation/i, 'the locator matched more than one element'],
514
+ [/element is not visible/i, 'the element is hidden or off-screen'],
515
+ [/element is not attached/i, 'the element was removed from the page'],
516
+ [/element is not enabled/i, 'the element is disabled'],
517
+ [/element is outside of the viewport/i, 'the element is outside the visible area'],
518
+ [/intercepts pointer events/i, 'another element is on top of the target'],
519
+ [/ECONNREFUSED|net::ERR_CONNECTION_REFUSED/i, 'the server is not running or refused the connection'],
520
+ [/ERR_NAME_NOT_RESOLVED|NS_ERROR_UNKNOWN_HOST/i, 'the hostname could not be resolved'],
521
+ [/ERR_HTTP_RESPONSE_CODE_FAILURE/i, 'the page returned an HTTP error status'],
522
+ [/ENOENT/i, 'the file could not be found'],
523
+ [/EACCES|EPERM/i, 'the file is not readable or writable'],
524
+ [/Invalid (regular expression|regex)/i, 'the regular expression is invalid'],
525
+ [/Unexpected token|Unexpected end of JSON input/i, 'the JSON could not be parsed'],
526
+ [/Target page, context or browser has been closed/i, 'the browser closed before the step finished'],
527
+ [/page\.goto:/i, 'the page could not be opened'],
528
+ [/frameLocator|content frame/i, 'the iframe content was not ready'],
529
+ [/Cookies? not found|Cookie .* not (set|found)/i, 'the cookie does not exist on this page'],
530
+ [/setViewportSize/i, 'the viewport cannot be resized for this browser context'],
531
+ ];
532
+ for (const [re, plain] of map) {
533
+ if (re.test(msg)) return plain;
534
+ }
535
+ // Strip noisy "Call log:" suffix common in Playwright errors.
536
+ return first.replace(/^\w+\.\w+:\s*/, '').replace(/\s+Call log:.*$/i, '');
537
+ }
538
+
539
+ /**
540
+ * Build a tester-friendly error.
541
+ *
542
+ * Three forms:
543
+ * 1. `friendly(message)` — message becomes the stack.
544
+ * 2. `friendly(message, err)` — appends "Why: <humanized>" + cleaned cause.
545
+ * 3. `friendly({ action, target, hint, cause })` — builds a structured message.
546
+ *
547
+ * The Error's `.stack` is set to the rendered message, so cucumber-js does
548
+ * not print a JS stack trace — only the lines we authored.
549
+ *
550
+ * @param {string|Object} input
551
+ * @param {Error} [cause]
552
+ * @returns {Error}
553
+ */
554
+ function friendly(input, cause) {
555
+ let body;
556
+ if (typeof input === 'string') {
557
+ body = input;
558
+ if (cause) {
559
+ body += `\n Why: ${humanize(cause)}`;
560
+ }
561
+ } else if (input && typeof input === 'object') {
562
+ const lines = [];
563
+ if (input.action && input.target) lines.push(`Could not ${input.action} "${input.target}".`);
564
+ else if (input.action) lines.push(`Could not ${input.action}.`);
565
+ else if (input.message) lines.push(input.message);
566
+ if (input.cause) lines.push(` Why: ${humanize(input.cause)}`);
567
+ if (input.hint) lines.push(` Hint: ${input.hint}`);
568
+ body = lines.join('\n');
569
+ } else {
570
+ body = String(input);
571
+ }
572
+ const e = new Error(body);
573
+ e.stack = body;
574
+ return e;
575
+ }
576
+
473
577
  module.exports = {
474
578
  smartSettle,
475
579
  waitForPageLoad,
@@ -486,6 +590,8 @@ module.exports = {
486
590
  resolveRelativeDate,
487
591
  parseRelativeOffset,
488
592
  formatRelativeDate,
593
+ friendly,
594
+ humanize,
489
595
  };
490
596
 
491
597
  // ---------------------------------------------------------------------------
@@ -510,7 +616,11 @@ if (!global.__WEBSHIP_AUTO_REPORT__) {
510
616
  // ---------------------------------------------------------------------------
511
617
  // World
512
618
  // ---------------------------------------------------------------------------
513
- setDefaultTimeout(30 * 1000);
619
+ // Step timeout must exceed Playwright's 30s default so that locator timeouts
620
+ // (e.g. click() with no match) reach our try/catch wrappers BEFORE cucumber
621
+ // trips its own timeout — otherwise testers see "function timed out" instead
622
+ // of the friendly Why/Hint message.
623
+ setDefaultTimeout(45 * 1000);
514
624
 
515
625
  class PlaywrightWorld extends World {
516
626
  constructor(options) {
@@ -523,10 +633,11 @@ class PlaywrightWorld extends World {
523
633
  this.assetsFolder = path.join(__dirname, '../assets/');
524
634
  }
525
635
 
526
- async openBrowser() {
636
+ async openBrowser(extraContextOptions) {
527
637
  const { browser: browserName, launchOptions, contextOptions } = playwrightConfig;
528
638
  this.playwrightBrowser = await playwright[browserName].launch(launchOptions);
529
- this.context = await this.playwrightBrowser.newContext(contextOptions);
639
+ const merged = Object.assign({}, contextOptions, extraContextOptions || {});
640
+ this.context = await this.playwrightBrowser.newContext(merged);
530
641
  // BBR: install in-flight fetch/XHR counter on every page (init script runs
531
642
  // before any document script). The counter lets smartSettle() detect the
532
643
  // edge of background activity rather than guessing a fixed delay.
@@ -620,18 +731,126 @@ class PlaywrightWorld extends World {
620
731
 
621
732
  setWorldConstructor(PlaywrightWorld);
622
733
 
623
- Before(async function () {
624
- await this.openBrowser();
734
+ // ---------------------------------------------------------------------------
735
+ // Video recording — Playwright records at browser-context creation. The
736
+ // helpers below resolve config + tags into either an empty {} (no
737
+ // recording) or { recordVideo: { dir, size } } that gets merged into the
738
+ // context options.
739
+ // ---------------------------------------------------------------------------
740
+
741
+ const VIDEO_MODES = new Set(['off', 'on', 'on-failure', 'tag']);
742
+
743
+ function videoSettings(world, scope) {
744
+ const cfg = (world.parameters && world.parameters.video) || {};
745
+ let mode = process.env.WEBSHIP_VIDEO || cfg.mode || 'off';
746
+ if (!VIDEO_MODES.has(mode)) mode = 'off';
747
+ return {
748
+ mode,
749
+ dir: process.env.WEBSHIP_VIDEO_DIR || cfg.dir || './videos',
750
+ size: cfg.size || { width: 1280, height: 720 },
751
+ filenamePattern: cfg.filenamePattern || '{datetime}.{feature_file}.{scenario}.{status}.{ext}',
752
+ };
753
+ }
754
+
755
+ function videoHasTag(scope, name) {
756
+ return !!(scope && scope.pickle && Array.isArray(scope.pickle.tags) &&
757
+ scope.pickle.tags.some((t) => t.name === name));
758
+ }
759
+
760
+ function shouldRecordAtStart(s, scope) {
761
+ if (videoHasTag(scope, '@no-video')) return false;
762
+ if (videoHasTag(scope, '@video')) return true;
763
+ return s.mode === 'on' || s.mode === 'on-failure';
764
+ }
765
+
766
+ function sanitisePart(s) {
767
+ return String(s || '').replace(/[^a-zA-Z0-9._-]+/g, '_').slice(0, 80);
768
+ }
769
+
770
+ function buildVideoFilename(template, scope, status) {
771
+ const featurePath = (scope && scope.gherkinDocument && scope.gherkinDocument.uri) || 'unknown';
772
+ const feature = (scope && scope.gherkinDocument && scope.gherkinDocument.feature && scope.gherkinDocument.feature.name) || 'feature';
773
+ const scenario = (scope && scope.pickle && scope.pickle.name) || 'scenario';
774
+ const featureFile = featurePath.split('/').pop().replace(/\.feature$/, '');
775
+ const dt = new Date().toISOString().replace(/[:.]/g, '-');
776
+ return template
777
+ .replace('{datetime}', dt)
778
+ .replace('{feature_file}', sanitisePart(featureFile))
779
+ .replace('{feature}', sanitisePart(feature))
780
+ .replace('{scenario}', sanitisePart(scenario))
781
+ .replace('{status}', sanitisePart(status))
782
+ .replace('{ext}', 'webm');
783
+ }
784
+
785
+ Before({ order: 5 }, async function (scope) {
786
+ this._videoSettings = videoSettings(this, scope);
787
+ this._videoRequested = shouldRecordAtStart(this._videoSettings, scope);
788
+ this._videoForcedByTag = videoHasTag(scope, '@video');
789
+
790
+ const extra = {};
791
+ if (this._videoRequested) {
792
+ require('fs').mkdirSync(this._videoSettings.dir, { recursive: true });
793
+ extra.recordVideo = {
794
+ dir: this._videoSettings.dir,
795
+ size: this._videoSettings.size,
796
+ };
797
+ }
798
+
799
+ await this.openBrowser(extra);
625
800
  if (this.minWaitTime.before_scenario > 0) {
626
801
  await this.page.waitForTimeout(this.minWaitTime.before_scenario);
627
802
  }
628
803
  });
629
804
 
630
- After(async function () {
805
+ After({ order: 5 }, async function (scope) {
631
806
  if (this.minWaitTime.after_scenario > 0) {
632
- await this.page.waitForTimeout(this.minWaitTime.after_scenario);
807
+ try { await this.page.waitForTimeout(this.minWaitTime.after_scenario); } catch { /* page already closed */ }
808
+ }
809
+
810
+ const status = (scope && scope.result && scope.result.status) || 'unknown';
811
+ const videoRef = (this._videoRequested && this.page) ? this.page.video() : null;
812
+ // Capture the raw Playwright path BEFORE closing the context — after
813
+ // close, the remote handle is gone and video.path() throws.
814
+ let rawPath = null;
815
+ if (videoRef) {
816
+ try { rawPath = await videoRef.path(); } catch { /* may throw on remote */ }
817
+ }
818
+
819
+ // Close the *context* (flushes the webm to disk). Browser stays up so
820
+ // saveAs() / delete() can still talk to it.
821
+ if (this.context) {
822
+ try { await this.context.close(); } catch { /* ignore */ }
823
+ }
824
+
825
+ if (videoRef) {
826
+ const settings = this._videoSettings;
827
+ const filename = this._videoSaveAsName || buildVideoFilename(settings.filenamePattern, scope, status);
828
+ const dest = require('path').join(settings.dir, filename);
829
+ try {
830
+ const passed = status === 'PASSED' || status === 'passed';
831
+ if (settings.mode === 'on-failure' && passed && !this._videoForcedByTag) {
832
+ await videoRef.delete().catch(() => {});
833
+ } else {
834
+ await videoRef.saveAs(dest);
835
+ await videoRef.delete().catch(() => {});
836
+ process.stderr.write(`\n[webship-js] video saved → ${dest}\n`);
837
+ }
838
+ } catch (e) {
839
+ process.stderr.write(`\n[webship-js] video save failed: ${e.message}\n`);
840
+ }
841
+ // Fallback: remove the Playwright scratch file via fs if it still exists.
842
+ if (rawPath) {
843
+ try { require('fs').unlinkSync(rawPath); } catch { /* already gone */ }
844
+ }
845
+ }
846
+
847
+ // Finally close the browser.
848
+ if (this.playwrightBrowser) {
849
+ try { await this.playwrightBrowser.close(); } catch { /* ignore */ }
850
+ this.playwrightBrowser = null;
633
851
  }
634
- await this.closeBrowser();
852
+ this.context = null;
853
+ this.page = null;
635
854
  });
636
855
 
637
856
  BeforeStep(async function () {