webship-js 2.0.10 → 2.0.12

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 (248) hide show
  1. package/.circleci/config.yml +10 -1
  2. package/.drone.yml +7 -7
  3. package/.github/ISSUE_TEMPLATE/issue.md +37 -0
  4. package/.github/PULL_REQUEST_TEMPLATE.md +24 -0
  5. package/.github/workflows/github-actions.yml +101 -4
  6. package/.gitlab-ci.yml +9 -4
  7. package/.harness/webship-js-pipeline.yml +5 -6
  8. package/.semaphore/semaphore.yml +6 -9
  9. package/.teamcity/settings.kts +7 -6
  10. package/.travis.yml +6 -1
  11. package/AGENTS.md +1 -1
  12. package/CLAUDE.md +69 -24
  13. package/Jenkinsfile +5 -3
  14. package/README.md +13 -1
  15. package/azure-pipelines.yml +17 -8
  16. package/bamboo-specs/bamboo.yml +9 -15
  17. package/bin/generate-reports.js +51 -7
  18. package/bin/init-webship.js +127 -23
  19. package/bitbucket-pipelines.yml +5 -1
  20. package/buildspec.yml +6 -7
  21. package/cloudbuild.yaml +28 -12
  22. package/codefresh.yml +6 -6
  23. package/cucumber.js +46 -11
  24. package/docs/00-quick-start.md +38 -7
  25. package/docs/02-bbr-smart-waits.md +21 -10
  26. package/docs/03-selector-registry.md +24 -0
  27. package/docs/04-step-reference.md +53 -27
  28. package/docs/05-web-first-assertions.md +6 -0
  29. package/docs/07-auth-state.md +1 -1
  30. package/docs/08-clock-mocking.md +21 -2
  31. package/docs/09-api-testing.md +40 -2
  32. package/docs/10-accessibility.md +2 -0
  33. package/docs/11-debugging.md +24 -1
  34. package/docs/12-ai-agent-guide.md +8 -1
  35. package/docs/13-faq.md +75 -1
  36. package/docs/14-recipes-cookbook.md +2 -0
  37. package/docs/15-tag-conventions.md +5 -1
  38. package/docs/16-ci-cd.md +161 -124
  39. package/docs/README.md +5 -5
  40. package/docs/advanced-screenshots.md +3 -1
  41. package/docs/api-step-definitions.md +16 -2
  42. package/docs/global-settings.md +70 -18
  43. package/docs/install-webship-js/ddev-webship-js.md +3 -0
  44. package/docs/install-webship-js.md +16 -2
  45. package/docs/step-definitions/then-i-should-see.md +14 -1
  46. package/docs/step-definitions/then-item-checkbox.md +2 -0
  47. package/docs/step-definitions/when-i-fill.md +4 -0
  48. package/docs/step-definitions/when-i-select-option-select-list.md +2 -0
  49. package/examples/a11y-legacy-widget.html +34 -0
  50. package/examples/auth-state.html +42 -0
  51. package/examples/choice-controls.html +29 -0
  52. package/examples/clock.html +33 -0
  53. package/examples/datetime-fields.html +52 -0
  54. package/examples/downloads/webship-archive.zip +0 -0
  55. package/examples/downloads/webship-notes.txt +4 -0
  56. package/examples/downloads/webship-report.csv +4 -0
  57. package/examples/downloads.html +16 -0
  58. package/examples/element-selector-hint.html +16 -0
  59. package/examples/element-viewport.html +42 -0
  60. package/examples/field-states.html +27 -0
  61. package/examples/field-types.html +98 -0
  62. package/examples/fill-in-empty.html +26 -0
  63. package/examples/fill-unreachable.html +27 -0
  64. package/examples/iframe-inner.html +20 -0
  65. package/examples/iframe-nested.html +16 -0
  66. package/examples/iframe-newsletter.html +29 -0
  67. package/examples/iframe-order.html +26 -0
  68. package/examples/iframe-outer.html +15 -0
  69. package/examples/iframe.html +21 -0
  70. package/examples/javascript-errors.html +35 -0
  71. package/examples/links.html +1 -0
  72. package/examples/metatags.html +18 -0
  73. package/examples/mouse-and-pointer.html +83 -0
  74. package/examples/multi-value-fields.html +54 -0
  75. package/examples/native-dialogs.html +8 -0
  76. package/examples/network.html +83 -0
  77. package/examples/registered-names.html +15 -0
  78. package/examples/scroll-horizontal.html +50 -0
  79. package/examples/select-by-label.html +33 -0
  80. package/examples/selectors-position.html +29 -0
  81. package/examples/settle-budget.html +21 -0
  82. package/examples/sorted-tables.html +38 -0
  83. package/examples/storage.html +57 -0
  84. package/examples/text-matching.html +48 -0
  85. package/examples/text-order.html +25 -0
  86. package/examples/touch.html +22 -0
  87. package/examples/viewport-size.html +24 -0
  88. package/examples/viewport-top.html +36 -0
  89. package/examples/wait-conditions.html +69 -0
  90. package/examples/web-first.html +99 -0
  91. package/package.json +24 -2
  92. package/playwright.config.ts +3 -1
  93. package/tests/assets/catalog.xml +19 -0
  94. package/tests/assets/feed-namespaced.xml +13 -0
  95. package/tests/assets/sitemap.xml +14 -0
  96. package/tests/assets/webship-site-expected.yaml +21 -0
  97. package/tests/assets/webship-site.schema.json +46 -0
  98. package/tests/assets/webship-site.yaml +21 -0
  99. package/tests/check-api-launch-url.js +106 -0
  100. package/tests/check-assets.js +103 -0
  101. package/tests/check-attachments.js +105 -0
  102. package/tests/check-breakpoints.js +117 -0
  103. package/tests/check-clock.js +143 -0
  104. package/tests/check-config.js +90 -0
  105. package/tests/check-context.js +215 -0
  106. package/tests/check-dry-run.js +104 -0
  107. package/tests/check-examples.js +241 -0
  108. package/tests/check-exit-report.js +141 -0
  109. package/tests/check-javascript-errors.js +105 -0
  110. package/tests/check-must-fail.js +85 -0
  111. package/tests/check-paths.js +82 -0
  112. package/tests/check-report.js +119 -0
  113. package/tests/check-scaffold.js +246 -0
  114. package/tests/check-screenshots.js +117 -0
  115. package/tests/check-settle-verbs.js +137 -0
  116. package/tests/check-time-limit.js +104 -0
  117. package/tests/check-video.js +156 -0
  118. package/tests/check-world.js +167 -0
  119. package/tests/features/a11y.feature +18 -0
  120. package/tests/features/api-base-url.feature +25 -0
  121. package/tests/features/api-form-data.feature +18 -0
  122. package/tests/features/api-json-paths.feature +24 -0
  123. package/tests/features/api-response-contains.feature +21 -0
  124. package/tests/features/api-response-header-presence.feature +17 -0
  125. package/tests/features/api-response-header.feature +17 -0
  126. package/tests/features/api-saved-placeholders.feature +37 -0
  127. package/tests/features/api-step-definitions-individual.feature +1 -1
  128. package/tests/features/api-tables.feature +40 -0
  129. package/tests/features/auth-state.feature +32 -0
  130. package/tests/features/breakpoints.feature +25 -0
  131. package/tests/features/choice-controls.feature +35 -0
  132. package/tests/features/clock.feature +27 -0
  133. package/tests/features/complete-api-testing-examples.feature +1 -1
  134. package/tests/features/cookie.feature +9 -0
  135. package/tests/features/datetime-field-lookup.feature +29 -0
  136. package/tests/features/dialog.feature +27 -0
  137. package/tests/features/element-selector-hint.feature +14 -0
  138. package/tests/features/element.feature +47 -0
  139. package/tests/features/field-state.feature +21 -0
  140. package/tests/features/field.feature +104 -0
  141. package/tests/features/file-download.feature +64 -0
  142. package/tests/features/fill-in-empty-value.feature +41 -0
  143. package/tests/features/fill-reachable.feature +13 -0
  144. package/tests/features/iframe-nested.feature +43 -0
  145. package/tests/features/iframe.feature +83 -0
  146. package/tests/features/javascript-tolerated-errors.feature +20 -0
  147. package/tests/features/javascript.feature +47 -0
  148. package/tests/features/link.feature +11 -0
  149. package/tests/features/metatag.feature +38 -0
  150. package/tests/features/modal-open.feature +13 -0
  151. package/tests/features/mouse-and-pointer.feature +86 -0
  152. package/tests/features/multi-value-field-lookup.feature +30 -0
  153. package/tests/features/network-mocking.feature +80 -0
  154. package/tests/features/registered-names.feature +14 -0
  155. package/tests/features/responsive.feature +27 -0
  156. package/tests/features/scroll-horizontal.feature +55 -0
  157. package/tests/features/select-by-label.feature +31 -0
  158. package/tests/features/selector-files.feature +14 -0
  159. package/tests/features/selectors-position.feature +41 -0
  160. package/tests/features/selectors-table-header.feature +35 -0
  161. package/tests/features/settle-budget.feature +11 -0
  162. package/tests/features/sorted-tables.feature +19 -0
  163. package/tests/features/storage-quoted-values.feature +26 -0
  164. package/tests/features/storage.feature +98 -0
  165. package/tests/features/test--then--i-see-locator.feature +13 -0
  166. package/tests/features/test--then--i-should--see-text-in-element.feature +9 -1
  167. package/tests/features/test--then--the-field-should-contain-value.feature +8 -0
  168. package/tests/features/text-matching.feature +38 -0
  169. package/tests/features/text-order.feature +14 -0
  170. package/tests/features/touch.feature +21 -0
  171. package/tests/features/video.feature +1 -0
  172. package/tests/features/viewport-top.feature +13 -0
  173. package/tests/features/wait.feature +89 -0
  174. package/tests/features/web-first.feature +100 -0
  175. package/tests/features/xml-namespaces.feature +34 -0
  176. package/tests/features/xml.feature +96 -0
  177. package/tests/features/yaml.feature +75 -0
  178. package/tests/must-fail/api-json-paths.feature +21 -0
  179. package/tests/must-fail/api-response-contains.feature +23 -0
  180. package/tests/must-fail/api-response-header-presence.feature +17 -0
  181. package/tests/must-fail/api-response-header.feature +21 -0
  182. package/tests/must-fail/api-without-base-url.feature +11 -0
  183. package/tests/must-fail/assertions.feature +96 -0
  184. package/tests/must-fail/breakpoints.feature +15 -0
  185. package/tests/must-fail/choice-controls.feature +25 -0
  186. package/tests/must-fail/clock.feature +11 -0
  187. package/tests/must-fail/datetime-field.feature +10 -0
  188. package/tests/must-fail/element-selector-hint.feature +17 -0
  189. package/tests/must-fail/field-state.feature +20 -0
  190. package/tests/must-fail/fill-field.feature +30 -0
  191. package/tests/must-fail/iframe-text.feature +17 -0
  192. package/tests/must-fail/modal-open.feature +26 -0
  193. package/tests/must-fail/multi-value-field.feature +18 -0
  194. package/tests/must-fail/registered-names.feature +25 -0
  195. package/tests/must-fail/select-list.feature +15 -0
  196. package/tests/must-fail/selector-files.feature +10 -0
  197. package/tests/must-fail/sorted-tables.feature +20 -0
  198. package/tests/must-fail/storage-before-a-page.feature +13 -0
  199. package/tests/must-fail/text-matching.feature +16 -0
  200. package/tests/must-fail/text-order.feature +15 -0
  201. package/tests/must-fail/viewport-top.feature +20 -0
  202. package/tests/must-fail/waits.feature +51 -0
  203. package/tests/must-fail/yaml-numbers.feature +48 -0
  204. package/tests/reports/README.md +2 -2
  205. package/tests/step-definitions/a11y.steps.js +36 -23
  206. package/tests/step-definitions/action.steps.js +22 -8
  207. package/tests/step-definitions/api.steps.js +349 -67
  208. package/tests/step-definitions/assertion.steps.js +327 -63
  209. package/tests/step-definitions/auth.steps.js +15 -18
  210. package/tests/step-definitions/clock.steps.js +22 -0
  211. package/tests/step-definitions/debug.steps.js +8 -0
  212. package/tests/step-definitions/dialog.steps.js +9 -2
  213. package/tests/step-definitions/element.steps.js +135 -18
  214. package/tests/step-definitions/field.steps.js +523 -80
  215. package/tests/step-definitions/file-download.steps.js +74 -10
  216. package/tests/step-definitions/form.steps.js +76 -29
  217. package/tests/step-definitions/iframe.steps.js +89 -29
  218. package/tests/step-definitions/input.steps.js +26 -7
  219. package/tests/step-definitions/javascript.steps.js +64 -22
  220. package/tests/step-definitions/modal.steps.js +79 -13
  221. package/tests/step-definitions/navigation.steps.js +14 -0
  222. package/tests/step-definitions/network.steps.js +15 -5
  223. package/tests/step-definitions/response.steps.js +6 -4
  224. package/tests/step-definitions/responsive.steps.js +26 -33
  225. package/tests/step-definitions/screenshot.steps.js +26 -9
  226. package/tests/step-definitions/scroll.steps.js +20 -0
  227. package/tests/step-definitions/selectors.steps.js +104 -51
  228. package/tests/step-definitions/storage.steps.js +41 -16
  229. package/tests/step-definitions/table.steps.js +81 -6
  230. package/tests/step-definitions/video.steps.js +52 -55
  231. package/tests/step-definitions/wait.steps.js +209 -54
  232. package/tests/step-definitions/web-first.steps.js +69 -35
  233. package/tests/step-definitions/webship.js +807 -128
  234. package/tests/step-definitions/xml.steps.js +124 -28
  235. package/tests/step-definitions/yaml.steps.js +90 -46
  236. package/.scratch/commit.txt +0 -14
  237. package/.scratch/docs.py +0 -42
  238. package/.scratch/echo-server.js +0 -8
  239. package/.scratch/echo.js +0 -35
  240. package/.scratch/echo.pid +0 -1
  241. package/.scratch/features/cookies.feature +0 -22
  242. package/.scratch/http.pid +0 -1
  243. package/.scratch/https.pid +0 -1
  244. package/.scratch/issue.md +0 -49
  245. package/.scratch/one.js +0 -2
  246. package/.scratch/one.json +0 -280
  247. package/.scratch/patch.py +0 -163
  248. package/.scratch/pr.md +0 -30
@@ -4,22 +4,42 @@ const { setWorldConstructor, World, Before, After, BeforeStep, AfterStep, setDef
4
4
  const playwright = require('playwright');
5
5
  const playwrightConfig = require(require('path').join(process.cwd(), 'playwright.config'));
6
6
  const path = require('path');
7
+ const fs = require('fs');
7
8
 
8
9
  // ---------------------------------------------------------------------------
9
10
  // Output filter — strip noisy `✔ Before # ...` / `✔ After # ...` hook lines
10
11
  // 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
+ // the failing step + hint. In a dry run (--dry-run or -d), also strip the
13
+ // pretty formatter's "- skipped" lines: every hook and every step of a dry
14
+ // run is skipped, and a line for each buries the "? undefined" and
15
+ // "✖ ambiguous" lines the dry run is for. Disable with
16
+ // WEBSHIP_FILTER_HOOK_LINES=off.
12
17
  // ---------------------------------------------------------------------------
13
18
  if (process.env.WEBSHIP_FILTER_HOOK_LINES !== 'off') {
14
19
  const HOOK_LINE = /^\s*[✔✖✗⚠?-]\s+(?:Before|After|BeforeStep|AfterStep)\b.*$/;
20
+ const DRY_RUN = process.argv.slice(2).some((arg) => arg === '--dry-run' || arg === '-d');
21
+ const SKIPPED_LINE = /^\s*-\s+skipped\s*$/;
22
+ const plain = (line) => line.replace(/\x1b\[[0-9;]*m/g, '');
23
+ const dropped = (line) => HOOK_LINE.test(plain(line)) || (DRY_RUN && SKIPPED_LINE.test(plain(line)));
15
24
  const wrap = (stream) => {
16
25
  const orig = stream.write.bind(stream);
26
+ // The pretty formatter writes a line and its line break in two writes:
27
+ // when a line is dropped, so is the line break that follows it.
28
+ let dropLineBreak = false;
17
29
  stream.write = (chunk, encoding, cb) => {
18
30
  if (typeof chunk === 'string' || Buffer.isBuffer(chunk)) {
19
31
  const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8');
32
+ const skipBreak = dropLineBreak && /^\r?\n$/.test(text);
33
+ dropLineBreak = false;
34
+ if (skipBreak || (!text.includes('\n') && text.trim() && dropped(text))) {
35
+ dropLineBreak = !skipBreak;
36
+ const done = typeof encoding === 'function' ? encoding : cb;
37
+ if (typeof done === 'function') process.nextTick(done);
38
+ return true;
39
+ }
20
40
  const filtered = text
21
41
  .split('\n')
22
- .filter((line) => !HOOK_LINE.test(line.replace(/\x1b\[[0-9;]*m/g, '')))
42
+ .filter((line) => !dropped(line))
23
43
  .join('\n');
24
44
  return orig(filtered, encoding, cb);
25
45
  }
@@ -65,8 +85,11 @@ if (process.env.WEBSHIP_FILTER_HOOK_LINES !== 'off') {
65
85
  // 5. window.__webshipPendingTimers === 0 (custom setTimeout counter)
66
86
  // 6. Date.now() - window.__webshipLastMutation >= quietMs (DOM-quiet)
67
87
  //
68
- // Steps 4/5/6 are evaluated atomically via a single waitForFunction, so a
88
+ // Steps 4/5/6 are evaluated atomically in one page-side probe, so a
69
89
  // late-firing setTimeout that mutates the DOM re-arms the wait correctly.
90
+ // The probe is polled from Node (see pollPage), never from a timer inside the
91
+ // page: a poll that runs on the page's own setTimeout is counted by step 5 as
92
+ // a pending timer, so the probe would see itself and never pass.
70
93
  // ---------------------------------------------------------------------------
71
94
 
72
95
  /**
@@ -78,15 +101,50 @@ if (process.env.WEBSHIP_FILTER_HOOK_LINES !== 'off') {
78
101
  */
79
102
  const SETTLE_MIN_MS = 25;
80
103
 
104
+ /**
105
+ * Poll a page-side probe from Node until it returns a truthy value or the
106
+ * budget is spent.
107
+ *
108
+ * Use this instead of `page.waitForFunction(..., { polling: <ms> })` for any
109
+ * probe that reads `window.__webshipPendingTimers`. Interval polling inside
110
+ * the page runs on the page's `setTimeout`, which the init script wraps to
111
+ * count pending timers, so such a probe counts its own next poll: it can only
112
+ * pass on its very first look, and waits out its whole timeout otherwise.
113
+ *
114
+ * A probe that throws (the page is navigating, the context was replaced) is
115
+ * read as "not yet" and looked at again.
116
+ *
117
+ * @param {import('playwright').Page} page - Page being probed.
118
+ * @param {Function} probe - Runs in the page; truthy means done.
119
+ * @param {*} arg - Single argument handed to the probe.
120
+ * @param {number} timeout - Budget in ms.
121
+ * @param {number} [interval=50] - Pause between two looks, in ms.
122
+ * @returns {Promise<boolean>} true when the probe passed inside the budget.
123
+ */
124
+ async function pollPage(page, probe, arg, timeout, interval) {
125
+ const pause = typeof interval === 'number' && interval > 0 ? interval : 50;
126
+ const deadline = Date.now() + (typeof timeout === 'number' && timeout > 0 ? timeout : 0);
127
+ for (;;) {
128
+ let done = false;
129
+ try { done = await page.evaluate(probe, arg); } catch { /* not ready yet */ }
130
+ if (done) return true;
131
+ if (Date.now() + pause >= deadline) return false;
132
+ await new Promise((resolve) => setTimeout(resolve, pause));
133
+ }
134
+ }
135
+
81
136
  /**
82
137
  * Wait for the page to reach an "edge" of activity — DOM ready, network
83
138
  * idle, no pending AJAX or timers, and no DOM mutations for ≥250 ms.
84
139
  *
85
- * Each stage gets a share of the budget rather than "whatever is left", so a
86
- * stage that can never resolve cannot starve the ones after it. On a page with
87
- * analytics, a chat widget or a self-rescheduling timer, `networkidle` never
88
- * arrives; capping it at half the budget keeps the AJAX / pending-timer /
89
- * DOM-quiet probe — the useful one — running.
140
+ * Each stage but the last gets a share of the budget rather than "whatever
141
+ * is left", so a stage that can never resolve cannot starve the ones after
142
+ * it. On a page with analytics, a chat widget or a self-rescheduling timer,
143
+ * `networkidle` never arrives; capping it at half the budget keeps the AJAX /
144
+ * pending-timer / DOM-quiet probe — the useful one — running. That probe is
145
+ * the last stage, with nothing after it to starve: it gets everything the
146
+ * earlier stages left, so a request or a timer of more than half the budget
147
+ * is still waited for.
90
148
  *
91
149
  * Returns within `timeout` ms even when nothing on the page ever settles.
92
150
  *
@@ -116,18 +174,23 @@ async function smartSettle(page, timeout) {
116
174
  if (!await stage(0.25, (t) => page.waitForSelector('body', { state: 'attached', timeout: t }))) return;
117
175
  if (!await stage(0.25, (t) => page.waitForLoadState('domcontentloaded', { timeout: t }))) return;
118
176
  if (!await stage(0.5, (t) => page.waitForLoadState('networkidle', { timeout: t }))) return;
119
- await stage(0.5, (t) => page.waitForFunction(
177
+ await stage(1, (t) => pollPage(
178
+ page,
120
179
  (quietMs) => {
121
180
  const ajax = window.__webshipAjaxCount;
122
181
  const timers = window.__webshipPendingTimers;
123
182
  const last = window.__webshipLastMutation;
183
+ const now = typeof window.__webshipNow === 'function' ? window.__webshipNow() : Date.now();
184
+ // Under a fake clock the page's timers are the clock's and run only
185
+ // when it moves; the ones the probes count are the clock's own.
186
+ const fakeClock = !!(window.Date && window.Date.isFake);
124
187
  if (typeof ajax === 'number' && ajax > 0) return false;
125
- if (typeof timers === 'number' && timers > 0) return false;
126
- if (typeof last === 'number' && Date.now() - last < quietMs) return false;
188
+ if (!fakeClock && typeof timers === 'number' && timers > 0) return false;
189
+ if (typeof last === 'number' && now - last < quietMs) return false;
127
190
  return true;
128
191
  },
129
192
  250,
130
- { timeout: t, polling: 50 }
193
+ t
131
194
  ));
132
195
  }
133
196
 
@@ -418,31 +481,75 @@ async function gotoUrl(page, url) {
418
481
  *
419
482
  * @param {import('playwright').Page} page
420
483
  * @param {string} field - Label / placeholder / name.
421
- * @param {string} value - Value to type.
484
+ * @param {string} value - Value to type; null or undefined fills an empty value.
485
+ * @param {WebshipWorld} [world] - The World of the step, to tell a name of the selector registry.
422
486
  * @returns {Promise<void>}
423
487
  */
424
- async function fillField(page, field, value) {
488
+ async function fillField(page, field, value, world) {
489
+ // An empty value in a step ("") reaches the definition as null: it means "".
490
+ value = value === undefined || value === null ? '' : String(value);
425
491
  const byLabel = page.getByLabel(field, { exact: true });
426
492
  if (await byLabel.count() > 0) {
427
- await byLabel.fill(value);
493
+ await fillLocator(page, byLabel, value, field);
428
494
  return;
429
495
  }
430
496
  const byPlaceholder = page.getByPlaceholder(field, { exact: true });
431
497
  if (await byPlaceholder.count() > 0) {
432
- await byPlaceholder.fill(value);
498
+ await fillLocator(page, byPlaceholder, value, field);
433
499
  return;
434
500
  }
435
501
  const byName = page.locator(`[name="${field}"]`).first();
436
502
  if (await byName.count() > 0) {
437
- await byName.fill(value);
503
+ await fillLocator(page, byName, value, field);
438
504
  return;
439
505
  }
440
- throw friendly(
441
- `Could not find a field for "${field}".\n` +
442
- ` Tried: getByLabel(exact), getByPlaceholder(exact), [name="${field}"].\n` +
443
- ` Hints: check the label/placeholder text matches exactly (case-sensitive),\n` +
444
- ` or use the attribute variant: 'I fill in "${field}" with "${value}" by attr'.`
445
- );
506
+ throw failure(page, `Could not find a field for "${field}".`, {
507
+ hint: registeredNameHint(world, field, { withSelector: (selector) => `I fill in the field "${selector}" with "${value}"` }) ||
508
+ `the step looks for a field whose label, placeholder or name is exactly "${field}", letter case included. For an id, a class or another attribute, use: I fill in "${field}" with "${value}" by attr`,
509
+ });
510
+ }
511
+
512
+ /**
513
+ * Fill the field a step found. A field that is hidden, disabled or read-only,
514
+ * or that is not on the page, fails the step within 5 seconds with what is
515
+ * wrong with it, the page and a hint, instead of Playwright's raw timeout.
516
+ *
517
+ * @param {import('playwright').Page} page
518
+ * @param {import('playwright').Locator} loc - The field.
519
+ * @param {string} value - Value to type; null or undefined fills an empty value.
520
+ * @param {string} name - How the step named the field, for the message.
521
+ * @returns {Promise<void>}
522
+ */
523
+ async function fillLocator(page, loc, value, name) {
524
+ const text = value === undefined || value === null ? '' : String(value);
525
+ try {
526
+ await loc.fill(text, { timeout: 5000 });
527
+ return;
528
+ } catch (e) {
529
+ let state = '';
530
+ try {
531
+ if (await loc.count() === 0) state = 'missing';
532
+ else if (!(await loc.first().isVisible())) state = 'hidden';
533
+ else if (await loc.first().isDisabled({ timeout: 1000 })) state = 'disabled';
534
+ else if (!(await loc.first().isEditable({ timeout: 1000 }))) state = 'read-only';
535
+ } catch { /* the page changed while it was looked at */ }
536
+ if (state === 'missing') {
537
+ throw failure(page, `No field with "${name}" was found after 5 seconds.`, {
538
+ hint: 'by attribute the step reads the text as the attribute it names, else as an id, a class, a name, a test id, an aria-label, a value, a placeholder or a title; a text that starts with #, . or [ is a CSS selector.',
539
+ });
540
+ }
541
+ if (state === 'hidden') {
542
+ throw failure(page, `The field "${name}" is on the page but hidden, so it cannot be filled.`, {
543
+ hint: 'a field that shows after an action can be filled once it is visible: wait for it first. A field hidden behind a rich-text editor is filled with: I fill in the WYSIWYG field "<name>" with the "<text>"',
544
+ });
545
+ }
546
+ if (state === 'disabled' || state === 'read-only') {
547
+ throw failure(page, `The field "${name}" is ${state}, so it cannot be filled.`, {
548
+ hint: `a ${state} field keeps its value; to check it, use: the field "${name}" should have "${state}" state`,
549
+ });
550
+ }
551
+ throw failure(page, `Could not fill the field "${name}".`, { hint: `${humanize(e)}.` });
552
+ }
446
553
  }
447
554
 
448
555
  /**
@@ -460,6 +567,67 @@ async function getLocatorText(locator) {
460
567
  }
461
568
  }
462
569
 
570
+ /**
571
+ * Find the element a step names either by the text of its label or by a CSS
572
+ * selector: the field of the label with that exact text and a `for`
573
+ * attribute when the page has one, else the first element the selector
574
+ * matches. Both are looked for together, so a selector does not wait for a
575
+ * label that will never come.
576
+ *
577
+ * @param {import('playwright').Page} page - Page being probed.
578
+ * @param {string} name - Label text or CSS selector.
579
+ * @param {number} [timeout=5000] - How long to look, in ms.
580
+ * @returns {Promise<import('playwright').Locator|null>} The element, or null when neither was found in time.
581
+ */
582
+ async function locateByLabelOrSelector(page, name, timeout) {
583
+ const deadline = Date.now() + (typeof timeout === 'number' && timeout > 0 ? timeout : 5000);
584
+ const labels = page.getByText(name, { exact: true });
585
+ for (;;) {
586
+ const forIds = await labels.evaluateAll((nodes) => nodes.map((node) => node.getAttribute('for'))).catch(() => []);
587
+ const forId = forIds.find((id) => id);
588
+ if (forId) return page.locator(`[id="${forId.replace(/["\\]/g, '\\$&')}"]`).first();
589
+ // A label text is rarely a valid selector: an invalid one matches nothing.
590
+ const bySelector = await page.locator(name).count().catch(() => 0);
591
+ if (bySelector > 0) return page.locator(name).first();
592
+ if (Date.now() >= deadline) return null;
593
+ await page.waitForTimeout(100);
594
+ }
595
+ }
596
+
597
+ // The package's own tests/assets/: read last, so that a file only the package
598
+ // ships keeps working.
599
+ const PACKAGE_ASSETS = path.join(__dirname, '..', 'assets');
600
+
601
+ /**
602
+ * Find a file a step names by its name: an absolute path as written; a
603
+ * relative one in the World's `assetsFolder` (the project's tests/assets/),
604
+ * then as written from the project root, then in the package's own
605
+ * tests/assets/. Fails plainly, with the paths tried, when none holds it.
606
+ *
607
+ * @param {WebshipWorld} world
608
+ * @param {string} name - The file as the step gives it.
609
+ * @returns {string} The absolute path of the file.
610
+ */
611
+ function resolveAssetFile(world, name) {
612
+ const fs = require('fs');
613
+ const file = String(name === undefined || name === null ? '' : name).trim();
614
+ const tried = path.isAbsolute(file)
615
+ ? [file]
616
+ : [...new Set([
617
+ path.resolve((world && world.assetsFolder) || path.join(process.cwd(), 'tests', 'assets'), file),
618
+ path.resolve(process.cwd(), file),
619
+ path.resolve(PACKAGE_ASSETS, file),
620
+ ])];
621
+ const found = tried.find((candidate) => {
622
+ try { return fs.statSync(candidate).isFile(); } catch { return false; }
623
+ });
624
+ if (found) return found;
625
+ throw failure(world && world.page, `The file "${file}" was not found.`, {
626
+ found: `nothing at ${tried.map((candidate) => path.relative(process.cwd(), candidate) || candidate).join(', ')}`,
627
+ hint: 'put the file in the tests/assets/ folder of the project, or name it by its path from the project root.',
628
+ });
629
+ }
630
+
463
631
  /**
464
632
  * Left-pad a number with zeros to the requested width.
465
633
  *
@@ -684,8 +852,105 @@ function friendly(input, cause) {
684
852
  return e;
685
853
  }
686
854
 
855
+ /**
856
+ * Shorten a text for a failure message: white space collapsed, cut at
857
+ * `max` characters.
858
+ *
859
+ * @param {string} text
860
+ * @param {number} [max=200]
861
+ * @returns {string}
862
+ */
863
+ function excerpt(text, max) {
864
+ const limit = typeof max === 'number' && max > 0 ? max : 200;
865
+ const clean = String(text === null || text === undefined ? '' : text).replace(/\s+/g, ' ').trim();
866
+ return clean.length > limit ? clean.slice(0, limit) + '…' : clean;
867
+ }
868
+
869
+ /**
870
+ * Locator for the page when its text contains `text`, read the way the page
871
+ * text steps (`I should see`, `I should not see`, `eventually I should see`)
872
+ * read it: Playwright's text matching on `<body>`, letter case ignored, white
873
+ * space collapsed, the text of hidden elements included, the text of
874
+ * `<script>`, `<noscript>` and `<style>` left out. It matches nothing while
875
+ * the text is not on the page, so `waitFor({ state: 'attached' })` waits for
876
+ * the text to come and `waitFor({ state: 'detached' })` for it to go.
877
+ *
878
+ * @param {import('playwright').Page} page
879
+ * @param {string} text
880
+ * @returns {import('playwright').Locator}
881
+ */
882
+ function pageTextLocator(page, text) {
883
+ return page.locator('body').filter({ hasText: text === undefined || text === null ? '' : String(text) });
884
+ }
885
+
886
+ /**
887
+ * The hint for a step that was given a name of the named-selector registry
888
+ * where it reads a text, a label or a CSS selector: it does not read the
889
+ * registry, so the name matched nothing. Names the bare-name step that reads
890
+ * it, when there is one and the name fits it, and the same step with the
891
+ * selector the name stands for. An empty string when `name` is not a
892
+ * registered name, so a failure that has nothing to do with the registry
893
+ * reads as before.
894
+ *
895
+ * @param {WebshipWorld} world
896
+ * @param {string} name - The argument the step was given.
897
+ * @param {Object} [forms]
898
+ * @param {string} [forms.bare] - The bare-name step, "{name}" for the name.
899
+ * @param {function(string): string} [forms.withSelector] - The step to use with the selector.
900
+ * @returns {string}
901
+ */
902
+ function registeredNameHint(world, name, forms) {
903
+ const key = String(name === undefined || name === null ? '' : name).trim();
904
+ if (!key || !world) return '';
905
+ const css = world.__selectorsCss || {};
906
+ const xpath = world.__selectorsXpath || {};
907
+ let selector = null;
908
+ if (Object.prototype.hasOwnProperty.call(css, key)) selector = css[key];
909
+ else if (Object.prototype.hasOwnProperty.call(xpath, key)) selector = xpath[key].startsWith('xpath=') ? xpath[key] : `xpath=${xpath[key]}`;
910
+ if (!selector) return '';
911
+ const uses = [];
912
+ if (forms && forms.bare && /^[a-zA-Z0-9 ,-]+$/.test(key)) uses.push(forms.bare.replace('{name}', key));
913
+ if (forms && typeof forms.withSelector === 'function') uses.push(forms.withSelector(selector));
914
+ return `"${key}" is a name of the selector registry (${selector}), but this step does not read the registry.` +
915
+ (uses.length ? ` Use: ${uses.join(', or: ')}` : '');
916
+ }
917
+
918
+ /**
919
+ * True when an error is Playwright giving up after its timeout, which in an
920
+ * assertion means "what was looked for is not there".
921
+ *
922
+ * @param {Error} error
923
+ * @returns {boolean}
924
+ */
925
+ function isTimeout(error) {
926
+ return !!error && (error.name === 'TimeoutError' || /Timeout \d+ms exceeded/.test(String(error.message || '')));
927
+ }
928
+
929
+ /**
930
+ * Build the failure of an assertion for a tester: what was looked for, what
931
+ * was found, the address of the page and a hint. No call log, no stack.
932
+ *
933
+ * @param {import('playwright').Page} page - Page the assertion ran on.
934
+ * @param {string} message - What was expected and did not hold.
935
+ * @param {Object} [details]
936
+ * @param {string} [details.found] - What was there instead.
937
+ * @param {string} [details.hint] - What to check or try next.
938
+ * @returns {Error}
939
+ */
940
+ function failure(page, message, details) {
941
+ const lines = [message];
942
+ const info = details || {};
943
+ if (info.found !== undefined && info.found !== null) lines.push(` Found: ${info.found}`);
944
+ let url = '';
945
+ try { url = page.url(); } catch { /* the page is gone */ }
946
+ if (url) lines.push(` Page: ${url}`);
947
+ if (info.hint) lines.push(` Hint: ${info.hint}`);
948
+ return friendly(lines.join('\n'));
949
+ }
950
+
687
951
  module.exports = {
688
952
  smartSettle,
953
+ pollPage,
689
954
  waitForPageLoad,
690
955
  getModalSelector,
691
956
  getModalLocator,
@@ -697,28 +962,145 @@ module.exports = {
697
962
  resolveUrl,
698
963
  sendRequest,
699
964
  fillField,
965
+ fillLocator,
700
966
  getLocatorText,
967
+ locateByLabelOrSelector,
968
+ resolveAssetFile,
701
969
  pad,
702
970
  resolveRelativeDate,
703
971
  parseRelativeOffset,
704
972
  formatRelativeDate,
705
973
  friendly,
706
974
  humanize,
975
+ failure,
976
+ excerpt,
977
+ isTimeout,
978
+ registeredNameHint,
979
+ pageTextLocator,
980
+ breakpoints,
981
+ breakpoint,
982
+ onNewPage,
983
+ videoFileName,
707
984
  };
708
985
 
709
986
  // ---------------------------------------------------------------------------
710
987
  // Auto HTML report on cucumber-js process exit.
711
988
  // Disable: WEBSHIP_REPORT_DISABLE=1. Extra flags: WEBSHIP_REPORT_ARGS="--theme hierarchy --layout 2".
712
- // Registered once per process.
989
+ // Registered once per process, and run only in the process that runs
990
+ // cucumber-js: the workers of a --parallel run load these files too, but exit
991
+ // before the JSON report is complete.
713
992
  // ---------------------------------------------------------------------------
993
+
994
+ /**
995
+ * The values given to an option on a command line, in order: `--name value`,
996
+ * `--name=value` and the short form `-n value`.
997
+ *
998
+ * @param {string[]} args
999
+ * @param {string} name - Long name, with its dashes (`--format`).
1000
+ * @param {string} [short] - Short name, with its dash (`-f`).
1001
+ * @returns {string[]}
1002
+ */
1003
+ function optionValues(args, name, short) {
1004
+ const values = [];
1005
+ for (let i = 0; i < args.length; i += 1) {
1006
+ if (args[i] === name || (short && args[i] === short)) {
1007
+ if (i + 1 < args.length) values.push(args[i + 1]);
1008
+ i += 1;
1009
+ } else if (args[i].startsWith(name + '=')) {
1010
+ values.push(args[i].slice(name.length + 1));
1011
+ }
1012
+ }
1013
+ return values;
1014
+ }
1015
+
1016
+ /**
1017
+ * The file of the last `json` formatter in a list of cucumber-js formats
1018
+ * (`json:path`, `"json":"path"` or `['json', 'path']`), or '' when there is
1019
+ * none that writes to a file.
1020
+ *
1021
+ * @param {Array<string|string[]>} formats
1022
+ * @returns {string}
1023
+ */
1024
+ function jsonFormatterFile(formats) {
1025
+ let file = '';
1026
+ for (const format of formats || []) {
1027
+ if (Array.isArray(format)) {
1028
+ if (format[0] === 'json' && format[1]) file = String(format[1]);
1029
+ continue;
1030
+ }
1031
+ const match = /^"?json"?:(.+)$/.exec(String(format));
1032
+ if (match) file = match[1].replace(/^"(.*)"$/, '$1');
1033
+ }
1034
+ return file;
1035
+ }
1036
+
1037
+ /**
1038
+ * The formats of the cucumber-js config file of this run, for the profiles
1039
+ * the command line names, else the default one. A config file that cannot be
1040
+ * read here (an ES module, a YAML file) gives none.
1041
+ *
1042
+ * @param {string[]} args - The command line of cucumber-js.
1043
+ * @returns {Array<string|string[]>}
1044
+ */
1045
+ function configFormats(args) {
1046
+ const named = optionValues(args, '--config', '-c');
1047
+ const candidates = named.length
1048
+ ? [named[named.length - 1]]
1049
+ : ['cucumber.js', 'cucumber.cjs', 'cucumber.json'];
1050
+ for (const candidate of candidates) {
1051
+ const file = path.resolve(process.cwd(), candidate);
1052
+ if (!/\.(c?js|json)$/.test(file) || !require('fs').existsSync(file)) continue;
1053
+ try {
1054
+ const loaded = require(file);
1055
+ const profiles = optionValues(args, '--profile', '-p');
1056
+ const formats = [];
1057
+ for (const profile of profiles.length ? profiles : ['default']) {
1058
+ const config = (loaded && loaded[profile]) || (profile === 'default' && loaded && !loaded.default ? loaded : null);
1059
+ if (config && Array.isArray(config.format)) formats.push(...config.format);
1060
+ }
1061
+ return formats;
1062
+ } catch {
1063
+ return [];
1064
+ }
1065
+ }
1066
+ return [];
1067
+ }
1068
+
1069
+ /**
1070
+ * Where this run wrote its JSON report: WEBSHIP_REPORT_JSON, else the file of
1071
+ * the `json` formatter of the command line, else the one of the config file,
1072
+ * else the scaffold's `tests/reports/cucumber_report.json`.
1073
+ *
1074
+ * @returns {string}
1075
+ */
1076
+ function reportJsonFile() {
1077
+ if (process.env.WEBSHIP_REPORT_JSON) return process.env.WEBSHIP_REPORT_JSON;
1078
+ const args = process.argv.slice(2);
1079
+ return jsonFormatterFile(optionValues(args, '--format', '-f'))
1080
+ || jsonFormatterFile(configFormats(args))
1081
+ || 'tests/reports/cucumber_report.json';
1082
+ }
1083
+
714
1084
  if (!global.__WEBSHIP_AUTO_REPORT__) {
715
1085
  global.__WEBSHIP_AUTO_REPORT__ = true;
716
1086
  process.on('exit', () => {
717
1087
  if (process.env.WEBSHIP_REPORT_DISABLE) return;
1088
+ // A worker of a --parallel run: the process that runs cucumber-js builds
1089
+ // the report once the whole JSON report is written.
1090
+ if (process.env.CUCUMBER_WORKER_ID) return;
718
1091
  try {
1092
+ const json = reportJsonFile();
1093
+ let size = 0;
1094
+ try { size = require('fs').statSync(path.resolve(process.cwd(), json)).size; } catch { /* not written */ }
1095
+ if (!size) {
1096
+ console.error(`[webship-js] No HTML report: this run wrote no JSON report at "${json}". Set WEBSHIP_REPORT_JSON to the file of your json formatter, or WEBSHIP_REPORT_DISABLE=1 to build no report.`);
1097
+ return;
1098
+ }
719
1099
  const { run } = require(path.join(__dirname, '..', '..', 'bin', 'generate-reports'));
720
1100
  const extra = (process.env.WEBSHIP_REPORT_ARGS || '').split(/\s+/).filter(Boolean);
721
- run(extra);
1101
+ Promise.resolve(run(['--json', json].concat(extra))).catch((err) => {
1102
+ console.error('[webship-js] Report generation failed:', err.message);
1103
+ });
722
1104
  } catch (err) {
723
1105
  console.error('[webship-js] Report generation failed:', err.message);
724
1106
  }
@@ -742,101 +1124,205 @@ const STEP_TIMEOUT = (() => {
742
1124
  })();
743
1125
  setDefaultTimeout(STEP_TIMEOUT);
744
1126
 
1127
+ // The pacing of worldParameters.minWaitTime, in ms. A project may leave the
1128
+ // block out or set only some of its keys: the others keep these values.
1129
+ const MIN_WAIT_TIME = Object.freeze({
1130
+ page: 3000,
1131
+ before_scenario: 0,
1132
+ after_scenario: 0,
1133
+ before_step: 0,
1134
+ after_step: 0,
1135
+ });
1136
+
1137
+ // BBR: the init script installed on every browser context the World opens.
1138
+ // It runs before any document script and counts in-flight fetch / XHR
1139
+ // requests and pending timers and stamps the last DOM mutation, so
1140
+ // smartSettle() detects the edge of background activity rather than guessing
1141
+ // a fixed delay.
1142
+ function smartWaitProbes() {
1143
+ if (window.__webshipAjaxInstalled) return;
1144
+ window.__webshipAjaxInstalled = true;
1145
+ // The time of the probes is real time: a fake clock (Playwright's
1146
+ // page.clock) replaces Date later, and its Date.now() may stand still or
1147
+ // lie in the past.
1148
+ const realNow = Date.now.bind(Date);
1149
+ window.__webshipNow = realNow;
1150
+ window.__webshipAjaxCount = 0;
1151
+ window.__webshipPendingTimers = 0;
1152
+ window.__webshipLastMutation = realNow();
1153
+
1154
+ // Track in-flight fetch requests.
1155
+ const origFetch = window.fetch;
1156
+ if (typeof origFetch === 'function') {
1157
+ window.fetch = function (...args) {
1158
+ window.__webshipAjaxCount++;
1159
+ const p = origFetch.apply(this, args);
1160
+ const settle = () => { window.__webshipAjaxCount--; };
1161
+ p.then(settle, settle);
1162
+ return p;
1163
+ };
1164
+ }
1165
+
1166
+ // Track in-flight XMLHttpRequests.
1167
+ const XHR = window.XMLHttpRequest;
1168
+ if (XHR && XHR.prototype) {
1169
+ const origSend = XHR.prototype.send;
1170
+ XHR.prototype.send = function (...args) {
1171
+ window.__webshipAjaxCount++;
1172
+ const settle = () => { window.__webshipAjaxCount--; };
1173
+ this.addEventListener('loadend', settle, { once: true });
1174
+ return origSend.apply(this, args);
1175
+ };
1176
+ }
1177
+
1178
+ // Track pending setTimeout callbacks. Many client-side frameworks use
1179
+ // setTimeout to schedule UI updates (animation frames, throttled
1180
+ // re-renders, fade-out → display:none). BBR demands we wait for those
1181
+ // timers to drain rather than guess a fixed delay.
1182
+ const origSetTimeout = window.setTimeout;
1183
+ const origClearTimeout = window.clearTimeout;
1184
+ const liveTimers = new Set();
1185
+ if (typeof origSetTimeout === 'function') {
1186
+ window.setTimeout = function (cb, delay, ...args) {
1187
+ window.__webshipPendingTimers++;
1188
+ let id;
1189
+ const wrapped = function () {
1190
+ try {
1191
+ if (typeof cb === 'function') return cb.apply(this, args);
1192
+ } finally {
1193
+ if (liveTimers.delete(id)) window.__webshipPendingTimers--;
1194
+ }
1195
+ };
1196
+ id = origSetTimeout(wrapped, delay);
1197
+ liveTimers.add(id);
1198
+ return id;
1199
+ };
1200
+ if (typeof origClearTimeout === 'function') {
1201
+ window.clearTimeout = function (id) {
1202
+ if (liveTimers.delete(id)) window.__webshipPendingTimers--;
1203
+ return origClearTimeout(id);
1204
+ };
1205
+ }
1206
+ }
1207
+
1208
+ // Track last DOM mutation so smartSettle can wait for the *edge* of
1209
+ // client-side rendering (animations, async hydration, transitions).
1210
+ const startObserver = () => {
1211
+ if (!document || !document.documentElement) return false;
1212
+ try {
1213
+ new MutationObserver(() => { window.__webshipLastMutation = realNow(); })
1214
+ .observe(document.documentElement, { childList: true, subtree: true, attributes: true, characterData: true });
1215
+ return true;
1216
+ } catch (e) { return false; }
1217
+ };
1218
+ if (!startObserver()) {
1219
+ document.addEventListener('DOMContentLoaded', startObserver, { once: true });
1220
+ }
1221
+ }
1222
+
1223
+ // Functions that set up every page the World opens: the first page of a
1224
+ // scenario and each page a step opens in a new browser context (restoring an
1225
+ // auth state, starting or stopping a video recording). Step files add theirs
1226
+ // with onNewPage().
1227
+ const NEW_PAGE_SETUPS = [];
1228
+
1229
+ /**
1230
+ * Run `setup(world, page)` on every page the World opens from now on, before
1231
+ * any step uses it: the first page of each scenario and every page of a
1232
+ * browser context that a step replaces.
1233
+ *
1234
+ * @param {function(WebshipWorld, import('playwright').Page): (void|Promise<void>)} setup
1235
+ * @returns {void}
1236
+ */
1237
+ function onNewPage(setup) {
1238
+ if (typeof setup === 'function') NEW_PAGE_SETUPS.push(setup);
1239
+ }
1240
+
745
1241
  class PlaywrightWorld extends World {
746
1242
  constructor(options) {
747
1243
  super(options);
748
1244
  this.launchUrl = this.parameters.launchUrl;
749
- this.minWaitTime = this.parameters.minWaitTime;
1245
+ this.minWaitTime = Object.assign({}, MIN_WAIT_TIME, this.parameters.minWaitTime || {});
750
1246
  this.playwrightBrowser = null;
751
1247
  this.context = null;
752
1248
  this.page = null;
753
- this.assetsFolder = path.join(__dirname, '../assets/');
1249
+ this.assetsFolder = path.join(process.cwd(), 'tests', 'assets');
754
1250
  }
755
1251
 
756
1252
  async openBrowser(extraContextOptions) {
757
- const { browser: browserName, launchOptions, contextOptions } = playwrightConfig;
1253
+ const { browser: browserName, launchOptions } = playwrightConfig;
758
1254
  this.playwrightBrowser = await playwright[browserName].launch(launchOptions);
759
- const merged = Object.assign({}, contextOptions, extraContextOptions || {});
760
- this.context = await this.playwrightBrowser.newContext(merged);
761
- // BBR: install in-flight fetch/XHR counter on every page (init script runs
762
- // before any document script). The counter lets smartSettle() detect the
763
- // edge of background activity rather than guessing a fixed delay.
764
- await this.context.addInitScript(() => {
765
- if (window.__webshipAjaxInstalled) return;
766
- window.__webshipAjaxInstalled = true;
767
- window.__webshipAjaxCount = 0;
768
- window.__webshipPendingTimers = 0;
769
- window.__webshipLastMutation = Date.now();
770
-
771
- // Track in-flight fetch requests.
772
- const origFetch = window.fetch;
773
- if (typeof origFetch === 'function') {
774
- window.fetch = function (...args) {
775
- window.__webshipAjaxCount++;
776
- const p = origFetch.apply(this, args);
777
- const settle = () => { window.__webshipAjaxCount--; };
778
- p.then(settle, settle);
779
- return p;
780
- };
781
- }
1255
+ await this.openContext(extraContextOptions);
1256
+ }
782
1257
 
783
- // Track in-flight XMLHttpRequests.
784
- const XHR = window.XMLHttpRequest;
785
- if (XHR && XHR.prototype) {
786
- const origSend = XHR.prototype.send;
787
- XHR.prototype.send = function (...args) {
788
- window.__webshipAjaxCount++;
789
- const settle = () => { window.__webshipAjaxCount--; };
790
- this.addEventListener('loadend', settle, { once: true });
791
- return origSend.apply(this, args);
792
- };
793
- }
1258
+ /**
1259
+ * Open a browser context and its page with everything a scenario relies
1260
+ * on: the context options of playwright.config.ts, the scenario's own (the
1261
+ * viewport of an @mobile / @desktop tag, video recording while it is on),
1262
+ * then `extraContextOptions`; the smart-wait init script; and the page
1263
+ * setups registered with onNewPage() (JavaScript-error capture, the
1264
+ * response tracker, the request log, a pending dialog handler).
1265
+ *
1266
+ * @param {import('playwright').BrowserContextOptions} [extraContextOptions]
1267
+ * @returns {Promise<void>}
1268
+ */
1269
+ async openContext(extraContextOptions) {
1270
+ const options = Object.assign({}, playwrightConfig.contextOptions, this._scenarioContextOptions || {});
1271
+ if (this._videoRequested && this._videoSettings) {
1272
+ fs.mkdirSync(this._videoSettings.dir, { recursive: true });
1273
+ options.recordVideo = { dir: this._videoSettings.dir, size: this._videoSettings.size };
1274
+ }
1275
+ Object.assign(options, extraContextOptions || {});
1276
+ this.context = await this.playwrightBrowser.newContext(options);
1277
+ await this.context.addInitScript(smartWaitProbes);
1278
+ this.page = await this.context.newPage();
1279
+ this.frame = null;
1280
+ for (const setup of NEW_PAGE_SETUPS) await setup(this, this.page);
1281
+ }
794
1282
 
795
- // Track pending setTimeout callbacks. Many client-side frameworks use
796
- // setTimeout to schedule UI updates (animation frames, throttled
797
- // re-renders, fade-out → display:none). BBR demands we wait for those
798
- // timers to drain rather than guess a fixed delay.
799
- const origSetTimeout = window.setTimeout;
800
- const origClearTimeout = window.clearTimeout;
801
- const liveTimers = new Set();
802
- if (typeof origSetTimeout === 'function') {
803
- window.setTimeout = function (cb, delay, ...args) {
804
- window.__webshipPendingTimers++;
805
- let id;
806
- const wrapped = function () {
807
- try {
808
- if (typeof cb === 'function') return cb.apply(this, args);
809
- } finally {
810
- if (liveTimers.delete(id)) window.__webshipPendingTimers--;
811
- }
812
- };
813
- id = origSetTimeout(wrapped, delay);
814
- liveTimers.add(id);
815
- return id;
816
- };
817
- if (typeof origClearTimeout === 'function') {
818
- window.clearTimeout = function (id) {
819
- if (liveTimers.delete(id)) window.__webshipPendingTimers--;
820
- return origClearTimeout(id);
821
- };
822
- }
823
- }
1283
+ /**
1284
+ * Replace the browser context in the middle of a scenario (restoring an
1285
+ * auth state, starting a video recording) with one opened by
1286
+ * openContext(), so the new page keeps the smart waits, the viewport of the
1287
+ * scenario, video recording and every page setup. The cookies and the
1288
+ * local storage of the context go over to the new one, unless
1289
+ * `extraContextOptions.storageState` gives others. The new page is blank,
1290
+ * and a video of the context being replaced is not kept.
1291
+ *
1292
+ * @param {import('playwright').BrowserContextOptions} [extraContextOptions]
1293
+ * @returns {Promise<void>}
1294
+ */
1295
+ async replaceContext(extraContextOptions) {
1296
+ const extra = Object.assign({}, extraContextOptions || {});
1297
+ const outgoing = this.context;
1298
+ const video = this.page && typeof this.page.video === 'function' ? this.page.video() : null;
1299
+ if (outgoing && !('storageState' in extra)) {
1300
+ try { extra.storageState = await outgoing.storageState(); } catch { /* a closed context has nothing to carry */ }
1301
+ }
1302
+ if (outgoing) {
1303
+ try { await outgoing.close(); } catch { /* already closed */ }
1304
+ }
1305
+ if (video) await video.delete().catch(() => {});
1306
+ await this.openContext(extra);
1307
+ }
824
1308
 
825
- // Track last DOM mutation so smartSettle can wait for the *edge* of
826
- // client-side rendering (animations, async hydration, transitions).
827
- const startObserver = () => {
828
- if (!document || !document.documentElement) return false;
829
- try {
830
- new MutationObserver(() => { window.__webshipLastMutation = Date.now(); })
831
- .observe(document.documentElement, { childList: true, subtree: true, attributes: true, characterData: true });
832
- return true;
833
- } catch (e) { return false; }
834
- };
835
- if (!startObserver()) {
836
- document.addEventListener('DOMContentLoaded', startObserver, { once: true });
837
- }
838
- });
839
- this.page = await this.context.newPage();
1309
+ /**
1310
+ * Wait for the page to settle the way the built-in action steps do: no
1311
+ * request in flight, no pending timer and a DOM quiet for 250 ms, bounded
1312
+ * by `budget` ms (by default 1500, the budget after a step). For a
1313
+ * project's own step that changes the page:
1314
+ *
1315
+ * When('I add {string} to the cart', async function (item) {
1316
+ * await this.page.click(`[data-add="${item}"]`);
1317
+ * await this.smartSettle();
1318
+ * });
1319
+ *
1320
+ * @param {number} [budget=1500]
1321
+ * @returns {Promise<void>}
1322
+ */
1323
+ async smartSettle(budget) {
1324
+ if (!this.page) return;
1325
+ await smartSettle(this.page, typeof budget === 'number' && budget > 0 ? budget : 1500);
840
1326
  }
841
1327
 
842
1328
  async closeBrowser() {
@@ -851,6 +1337,35 @@ class PlaywrightWorld extends World {
851
1337
 
852
1338
  setWorldConstructor(PlaywrightWorld);
853
1339
 
1340
+ // A project extends the World instead of replacing it, so the smart waits,
1341
+ // the viewport tags, video recording and the page setups stay:
1342
+ // const { PlaywrightWorld } = require('webship-js/tests/step-definitions/webship');
1343
+ // setWorldConstructor(class extends PlaywrightWorld { … });
1344
+ module.exports.PlaywrightWorld = PlaywrightWorld;
1345
+
1346
+ let foreignWorldReported = false;
1347
+
1348
+ // A World set with setWorldConstructor that does not extend PlaywrightWorld
1349
+ // has none of what webship-js puts on a page: say so once, plainly.
1350
+ function checkWorld(world) {
1351
+ if (world instanceof PlaywrightWorld) return;
1352
+ // The hooks below read the pacing of the World: give a World of its own
1353
+ // the defaults, so it can still run.
1354
+ if (!world.minWaitTime) world.minWaitTime = Object.assign({}, MIN_WAIT_TIME);
1355
+ if (typeof world.openBrowser !== 'function') {
1356
+ throw friendly(
1357
+ 'The World of this run is not a PlaywrightWorld of webship-js, and it has no openBrowser().\n' +
1358
+ " Hint: extend it instead of replacing it: const { PlaywrightWorld } = require('webship-js/tests/step-definitions/webship'); setWorldConstructor(class extends PlaywrightWorld { … });"
1359
+ );
1360
+ }
1361
+ if (foreignWorldReported) return;
1362
+ foreignWorldReported = true;
1363
+ process.stderr.write(
1364
+ '\n[webship-js] The World of this run does not extend PlaywrightWorld: the smart waits, the @mobile / @desktop viewport, video recording and the page setups depend on it. ' +
1365
+ "Extend it instead: const { PlaywrightWorld } = require('webship-js/tests/step-definitions/webship').\n"
1366
+ );
1367
+ }
1368
+
854
1369
  // ---------------------------------------------------------------------------
855
1370
  // Video recording — Playwright records at browser-context creation. The
856
1371
  // helpers below resolve config + tags into either an empty {} (no
@@ -860,6 +1375,14 @@ setWorldConstructor(PlaywrightWorld);
860
1375
 
861
1376
  const VIDEO_MODES = new Set(['off', 'on', 'on-failure', 'tag']);
862
1377
 
1378
+ // WEBSHIP_VIDEO_SIZE: "<width>x<height>", such as "1280x720".
1379
+ function videoSizeFromEnv() {
1380
+ const m = String(process.env.WEBSHIP_VIDEO_SIZE || '').trim().match(/^(\d+)\s*[x×]\s*(\d+)$/i);
1381
+ return m && parseInt(m[1], 10) > 0 && parseInt(m[2], 10) > 0
1382
+ ? { width: parseInt(m[1], 10), height: parseInt(m[2], 10) }
1383
+ : null;
1384
+ }
1385
+
863
1386
  function videoSettings(world, scope) {
864
1387
  const cfg = (world.parameters && world.parameters.video) || {};
865
1388
  let mode = process.env.WEBSHIP_VIDEO || cfg.mode || 'off';
@@ -867,7 +1390,7 @@ function videoSettings(world, scope) {
867
1390
  return {
868
1391
  mode,
869
1392
  dir: process.env.WEBSHIP_VIDEO_DIR || cfg.dir || './videos',
870
- size: cfg.size || { width: 1280, height: 720 },
1393
+ size: videoSizeFromEnv() || cfg.size || { width: 1280, height: 720 },
871
1394
  filenamePattern: cfg.filenamePattern || '{datetime}.{feature_file}.{scenario}.{status}.{ext}',
872
1395
  };
873
1396
  }
@@ -887,42 +1410,185 @@ function sanitisePart(s) {
887
1410
  return String(s || '').replace(/[^a-zA-Z0-9._-]+/g, '_').slice(0, 80);
888
1411
  }
889
1412
 
890
- function buildVideoFilename(template, scope, status) {
1413
+ // The file name of a scenario's video: {datetime} is when the recording
1414
+ // started, {status} the scenario's result in lower case (passed, failed, …),
1415
+ // or the word given for a recording a step stopped. A null status leaves
1416
+ // "<status>" in the name, for a name printed before the scenario ends.
1417
+ function buildVideoFilename(template, scope, status, startedAt) {
891
1418
  const featurePath = (scope && scope.gherkinDocument && scope.gherkinDocument.uri) || 'unknown';
892
1419
  const feature = (scope && scope.gherkinDocument && scope.gherkinDocument.feature && scope.gherkinDocument.feature.name) || 'feature';
893
1420
  const scenario = (scope && scope.pickle && scope.pickle.name) || 'scenario';
894
1421
  const featureFile = featurePath.split('/').pop().replace(/\.feature$/, '');
895
- const dt = new Date().toISOString().replace(/[:.]/g, '-');
1422
+ const dt = (startedAt instanceof Date ? startedAt : new Date()).toISOString().replace(/[:.]/g, '-');
896
1423
  return template
897
1424
  .replace('{datetime}', dt)
898
1425
  .replace('{feature_file}', sanitisePart(featureFile))
899
1426
  .replace('{feature}', sanitisePart(feature))
900
1427
  .replace('{scenario}', sanitisePart(scenario))
901
- .replace('{status}', sanitisePart(status))
1428
+ .replace('{status}', status === null ? '<status>' : sanitisePart(String(status).toLowerCase()))
902
1429
  .replace('{ext}', 'webm');
903
1430
  }
904
1431
 
905
- Before({ order: 5 }, async function (scope) {
1432
+ /**
1433
+ * The file name the current video of the scenario is saved under: the name a
1434
+ * step reserved ("I save the current video as"), else the filenamePattern of
1435
+ * worldParameters.video with the given status (null: "<status>").
1436
+ *
1437
+ * @param {WebshipWorld} world
1438
+ * @param {?string} status
1439
+ * @returns {string}
1440
+ */
1441
+ function videoFileName(world, status) {
1442
+ if (world._videoSaveAsName) return world._videoSaveAsName;
1443
+ const settings = world._videoSettings || videoSettings(world);
1444
+ return buildVideoFilename(settings.filenamePattern, world._scenarioScope, status, world._videoStartedAt);
1445
+ }
1446
+
1447
+ // ---------------------------------------------------------------------------
1448
+ // Breakpoints: one registry of named viewport sizes for every step and tag
1449
+ // that names a size — the @mobile and @desktop tags, "I set the viewport to
1450
+ // the "…" breakpoint" and "I am viewing the site on a … screen".
1451
+ //
1452
+ // The built-in names come first, then worldParameters.selectors.breakpoints,
1453
+ // then the JSON object of WEBSHIP_SELECTORS_BREAKPOINTS, then the names a
1454
+ // scenario adds with "the following responsive breakpoints:"; each replaces
1455
+ // the sizes of the names it gives and keeps the others. `desktop` stands for
1456
+ // the breakpoint marked `default: true` when the project gives no `desktop`
1457
+ // of its own.
1458
+ // ---------------------------------------------------------------------------
1459
+
1460
+ const BUILT_IN_BREAKPOINTS = Object.freeze({
1461
+ xs: { width: 375, height: 667 },
1462
+ sm: { width: 576, height: 800 },
1463
+ md: { width: 768, height: 1024 },
1464
+ lg: { width: 992, height: 768 },
1465
+ xl: { width: 1200, height: 900 },
1466
+ xxl: { width: 1400, height: 900 },
1467
+ xxxl: { width: 1920, height: 1080 },
1468
+ mobile: { width: 375, height: 667 },
1469
+ tablet: { width: 768, height: 1024 },
1470
+ desktop: { width: 1200, height: 900 },
1471
+ });
1472
+
1473
+ let badBreakpointsReported = false;
1474
+
1475
+ /**
1476
+ * The named sizes of WEBSHIP_SELECTORS_BREAKPOINTS, or an empty object when
1477
+ * it is not set. A value that is not a JSON object of sizes is reported once
1478
+ * and ignored.
1479
+ *
1480
+ * @returns {Object<string, {width: number, height: number}>}
1481
+ */
1482
+ function breakpointsFromEnv() {
1483
+ const raw = process.env.WEBSHIP_SELECTORS_BREAKPOINTS;
1484
+ if (!raw) return {};
1485
+ try {
1486
+ const parsed = JSON.parse(raw);
1487
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
1488
+ } catch { /* reported below */ }
1489
+ if (!badBreakpointsReported) {
1490
+ badBreakpointsReported = true;
1491
+ process.stderr.write('\n[webship-js] WEBSHIP_SELECTORS_BREAKPOINTS is not a JSON object of named sizes, such as {"tablet":{"width":800,"height":1280}}; it is ignored.\n');
1492
+ }
1493
+ return {};
1494
+ }
1495
+
1496
+ /**
1497
+ * A `{ width, height }` of whole positive pixels, or null.
1498
+ *
1499
+ * @param {*} size
1500
+ * @returns {{width: number, height: number}|null}
1501
+ */
1502
+ function breakpointSize(size) {
1503
+ const width = parseInt(size && size.width, 10);
1504
+ const height = parseInt(size && size.height, 10);
1505
+ return width > 0 && height > 0 ? { width, height } : null;
1506
+ }
1507
+
1508
+ /**
1509
+ * Every named viewport size the scenario can use, in the order of precedence
1510
+ * described above.
1511
+ *
1512
+ * @param {WebshipWorld} world
1513
+ * @returns {Object<string, {width: number, height: number}>}
1514
+ */
1515
+ function breakpoints(world) {
1516
+ const configured = (world && world.parameters && world.parameters.selectors && world.parameters.selectors.breakpoints) || {};
1517
+ const fromEnv = breakpointsFromEnv();
1518
+ const named = Object.assign({}, BUILT_IN_BREAKPOINTS);
1519
+ for (const source of [configured, fromEnv]) {
1520
+ for (const [name, value] of Object.entries(source)) {
1521
+ const size = breakpointSize(value);
1522
+ if (size) named[name] = size;
1523
+ }
1524
+ }
1525
+ if (!('desktop' in configured) && !('desktop' in fromEnv)) {
1526
+ const marked = Object.values(Object.assign({}, configured, fromEnv)).find((value) => value && value.default === true);
1527
+ const size = breakpointSize(marked);
1528
+ if (size) named.desktop = size;
1529
+ }
1530
+ return Object.assign(named, (world && world.__scenarioBreakpoints) || {});
1531
+ }
1532
+
1533
+ /**
1534
+ * The size of a named breakpoint. Throws a tester-facing error that lists the
1535
+ * known names when there is no such breakpoint.
1536
+ *
1537
+ * @param {WebshipWorld} world
1538
+ * @param {string} name
1539
+ * @returns {{width: number, height: number}}
1540
+ */
1541
+ function breakpoint(world, name) {
1542
+ const named = breakpoints(world);
1543
+ const key = String(name === undefined || name === null ? '' : name).trim();
1544
+ if (Object.prototype.hasOwnProperty.call(named, key)) return Object.assign({}, named[key]);
1545
+ throw failure(world && world.page, `There is no breakpoint named "${key}".`, {
1546
+ found: `the breakpoints ${Object.keys(named).join(', ')}`,
1547
+ hint: 'name a size in worldParameters.selectors.breakpoints of cucumber.js, in WEBSHIP_SELECTORS_BREAKPOINTS (a JSON object), or for one scenario with "Given the following responsive breakpoints:".',
1548
+ });
1549
+ }
1550
+
1551
+ // A scenario tagged @mobile or @desktop opens at the size of the `mobile` or
1552
+ // the `desktop` breakpoint. Without either tag the viewport stays fluid
1553
+ // (contextOptions.viewport). A step can still change the viewport inside the
1554
+ // scenario.
1555
+ const TAG_BREAKPOINTS = [['@mobile', 'mobile'], ['@desktop', 'desktop']];
1556
+
1557
+ function tagViewport(world, scope) {
1558
+ const tags = new Set(((scope && scope.pickle && scope.pickle.tags) || []).map((t) => t.name));
1559
+ const entry = TAG_BREAKPOINTS.find(([tag]) => tags.has(tag));
1560
+ return entry ? breakpoint(world, entry[1]) : null;
1561
+ }
1562
+
1563
+ // The order of the hooks is the order they are registered in: cucumber-js
1564
+ // runs the Before hooks in that order and the After hooks in the reverse one
1565
+ // (it has no `order` option). This file is loaded before any other hook is
1566
+ // registered — the first step file of the glob and every step file with
1567
+ // hooks of its own require it at their top — so the Before hook below opens
1568
+ // the browser before any other Before hook runs, and the After hook below
1569
+ // closes it after every other After hook ran.
1570
+ Before(async function (scope) {
1571
+ checkWorld(this);
1572
+ this._scenarioScope = scope;
906
1573
  this._videoSettings = videoSettings(this, scope);
907
1574
  this._videoRequested = shouldRecordAtStart(this._videoSettings, scope);
908
1575
  this._videoForcedByTag = videoHasTag(scope, '@video');
1576
+ this._videoStartedAt = this._videoRequested ? new Date() : null;
909
1577
 
910
- const extra = {};
911
- if (this._videoRequested) {
912
- require('fs').mkdirSync(this._videoSettings.dir, { recursive: true });
913
- extra.recordVideo = {
914
- dir: this._videoSettings.dir,
915
- size: this._videoSettings.size,
916
- };
917
- }
1578
+ // Kept for the whole scenario: a step that replaces the browser context
1579
+ // opens the new one with the same viewport and touch (see openContext).
1580
+ // @touch opens the context with touch on, so "I tap on" fires touch events.
1581
+ const viewport = tagViewport(this, scope);
1582
+ this._scenarioContextOptions = viewport ? { viewport } : {};
1583
+ if (videoHasTag(scope, '@touch')) this._scenarioContextOptions.hasTouch = true;
918
1584
 
919
- await this.openBrowser(extra);
1585
+ await this.openBrowser();
920
1586
  if (this.minWaitTime.before_scenario > 0) {
921
1587
  await this.page.waitForTimeout(this.minWaitTime.before_scenario);
922
1588
  }
923
1589
  });
924
1590
 
925
- After({ order: 5 }, async function (scope) {
1591
+ After(async function (scope) {
926
1592
  if (this.minWaitTime.after_scenario > 0) {
927
1593
  try { await this.page.waitForTimeout(this.minWaitTime.after_scenario); } catch { /* page already closed */ }
928
1594
  }
@@ -944,11 +1610,13 @@ After({ order: 5 }, async function (scope) {
944
1610
 
945
1611
  if (videoRef) {
946
1612
  const settings = this._videoSettings;
947
- const filename = this._videoSaveAsName || buildVideoFilename(settings.filenamePattern, scope, status);
1613
+ const filename = videoFileName(this, status);
948
1614
  const dest = require('path').join(settings.dir, filename);
949
1615
  try {
950
1616
  const passed = status === 'PASSED' || status === 'passed';
951
- if (settings.mode === 'on-failure' && passed && !this._videoForcedByTag) {
1617
+ // on-failure keeps a passing scenario's video only when the @video tag
1618
+ // or "I save the current video as" asked for it.
1619
+ if (settings.mode === 'on-failure' && passed && !this._videoForcedByTag && !this._videoSaveAsName) {
952
1620
  await videoRef.delete().catch(() => {});
953
1621
  } else {
954
1622
  await videoRef.saveAs(dest);
@@ -979,10 +1647,21 @@ BeforeStep(async function () {
979
1647
  }
980
1648
  });
981
1649
 
982
- // BBR: regex matches steps that mutate page state (click/press/fill/check/etc.).
983
- // After such a step, run a short smartSettle so assertions in the next step
984
- // observe the post-action edge instead of mid-transition state.
985
- const STATE_MUTATING_STEP = /\b(click|press|fill|submit|select|check|uncheck|choose|attach|reload|move (?:back|forward)|go to|navigate|on (?:the )?(?:home|front)page)\b/i;
1650
+ // BBR: the verbs of a step that changes the page — the built-in ones (click,
1651
+ // press, fill, …) and the ones a project's own steps use (add, open, delete,
1652
+ // save, log in, …). After such a step, run a short smartSettle so the next
1653
+ // step observes the post-action edge instead of a mid-transition state. The
1654
+ // verbs are read in the step's own words, not in its quoted arguments: "Then
1655
+ // I should see "Delete"" is no action. "scroll" is left out on purpose: a
1656
+ // scroll often starts a loader that the next step checks while it shows. A
1657
+ // project step whose words carry none of them can settle itself with
1658
+ // `await this.smartSettle()`.
1659
+ const STATE_MUTATING_STEP = /\b(click|press|fill|submit|select|check|uncheck|choose|attach|upload|reload|move (?:back|forward)|go to|navigate|on (?:the )?(?:home|front)page|open|close|add|remove|insert|delete|save|publish|edit|update|create|enter|type|clear|reset|drag|drop|hover|tap|toggle|expand|collapse|search|send|request|flush|confirm|cancel|accept|dismiss|log ?in|log ?out|sign ?in|sign ?out)\b/i;
1660
+
1661
+ // The words of a step without its quoted arguments.
1662
+ function stepWords(text) {
1663
+ return String(text).replace(/"(?:[^"\\]|\\.)*"/g, '""');
1664
+ }
986
1665
 
987
1666
  AfterStep(async function (scope) {
988
1667
  if (!this.page) return;
@@ -993,7 +1672,7 @@ AfterStep(async function (scope) {
993
1672
  if (process.env.WEBSHIP_AUTO_SETTLE === 'off') return;
994
1673
  const text = scope && scope.pickleStep && scope.pickleStep.text;
995
1674
  if (typeof text !== 'string') return;
996
- if (!STATE_MUTATING_STEP.test(text)) return;
1675
+ if (!STATE_MUTATING_STEP.test(stepWords(text))) return;
997
1676
  try { await smartSettle(this.page, 1500); } catch { /* best effort */ }
998
1677
  });
999
1678