webship-js 2.0.1 → 2.0.3

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 (194) hide show
  1. package/AGENTS.md +109 -0
  2. package/CLAUDE.md +317 -0
  3. package/bin/generate-reports.js +363 -0
  4. package/bin/init-webship.js +343 -0
  5. package/bin/postinstall.js +8 -74
  6. package/cucumber.js +66 -2
  7. package/docs/00-quick-start.md +102 -0
  8. package/docs/01-getting-started.md +102 -0
  9. package/docs/02-bbr-smart-waits.md +77 -0
  10. package/docs/03-selector-registry.md +95 -0
  11. package/docs/04-step-reference.md +728 -0
  12. package/docs/05-web-first-assertions.md +91 -0
  13. package/docs/06-network-and-dialogs.md +83 -0
  14. package/docs/07-auth-state.md +75 -0
  15. package/docs/08-clock-mocking.md +59 -0
  16. package/docs/09-api-testing.md +114 -0
  17. package/docs/10-accessibility.md +167 -0
  18. package/docs/11-debugging.md +129 -0
  19. package/docs/12-ai-agent-guide.md +338 -0
  20. package/docs/13-faq.md +236 -0
  21. package/docs/14-recipes-cookbook.md +255 -0
  22. package/docs/15-tag-conventions.md +76 -0
  23. package/docs/advanced-screenshots/then-i-save-fullscreen-screenshot.md +36 -0
  24. package/docs/advanced-screenshots/then-i-save-width-x-height-screenshot.md +34 -0
  25. package/docs/advanced-screenshots/when-i-save-screenshot-name-filename.md +45 -0
  26. package/docs/advanced-screenshots.md +52 -0
  27. package/docs/advanced-selectors.md +18 -0
  28. package/docs/api-step-definitions.md +45 -0
  29. package/docs/diffy-step-definitions/then-compare-diffy-env1-env2.md +30 -0
  30. package/docs/diffy-step-definitions/then-create-diffy-comparison-name-value.md +21 -0
  31. package/docs/diffy-step-definitions/then-create-diffy-comparison.md +25 -0
  32. package/docs/diffy-step-definitions/then-create-diffy-screenshot-environment-name.md +35 -0
  33. package/docs/diffy-step-definitions/then-i-take-screenshot.md +21 -0
  34. package/docs/diffy-step-definitions/then-i-take-screenshots-all-breakpoints.md +27 -0
  35. package/docs/diffy-step-definitions/then-send-screenshots-diffy-name-value.md +27 -0
  36. package/docs/diffy-step-definitions/then-upload-folder-url-diffy-snapshotname.md +28 -0
  37. package/docs/diffy-step-definitions/then-wait-diffy-comparison-complete.md +21 -0
  38. package/docs/diffy-step-definitions/when-i-resize-window-number.md +29 -0
  39. package/docs/diffy-step-definitions.md +21 -0
  40. package/docs/global-settings.md +244 -0
  41. package/docs/index.md +104 -0
  42. package/docs/install-webship-js/ddev-webship-js.md +52 -0
  43. package/docs/install-webship-js.md +35 -0
  44. package/docs/overview.md +41 -0
  45. package/docs/step-definitions/given-i-am-anonymous-user.md +67 -0
  46. package/docs/step-definitions/given-i-am-homepage.md +68 -0
  47. package/docs/step-definitions/given-i-am-specific-page.md +72 -0
  48. package/docs/step-definitions/then-i-should-be.md +56 -0
  49. package/docs/step-definitions/then-i-should-see.md +62 -0
  50. package/docs/step-definitions/then-item-checkbox.md +54 -0
  51. package/docs/step-definitions/then-item-link-should-contain-url.md +84 -0
  52. package/docs/step-definitions/then-item-should-contain.md +67 -0
  53. package/docs/step-definitions/then-radio-button-value-should-be-selected.md +68 -0
  54. package/docs/step-definitions/then-response-status-code-should-be-number.md +69 -0
  55. package/docs/step-definitions/then-value-radio-button-selected.md +62 -0
  56. package/docs/step-definitions/when-i-attach-file-file-name-element.md +71 -0
  57. package/docs/step-definitions/when-i-check-checkbox.md +60 -0
  58. package/docs/step-definitions/when-i-click-link.md +51 -0
  59. package/docs/step-definitions/when-i-click-operation-text-row.md +71 -0
  60. package/docs/step-definitions/when-i-fill.md +59 -0
  61. package/docs/step-definitions/when-i-go-homepage.md +60 -0
  62. package/docs/step-definitions/when-i-go-specific-page.md +67 -0
  63. package/docs/step-definitions/when-i-move-backward-one-page.md +49 -0
  64. package/docs/step-definitions/when-i-move-forward-one-page.md +58 -0
  65. package/docs/step-definitions/when-i-press-button.md +58 -0
  66. package/docs/step-definitions/when-i-reload-page.md +51 -0
  67. package/docs/step-definitions/when-i-scroll.md +73 -0
  68. package/docs/step-definitions/when-i-select-option-select-list.md +53 -0
  69. package/docs/step-definitions/when-i-select-radio-button-value.md +62 -0
  70. package/docs/step-definitions/when-i-uncheck-checkbox.md +57 -0
  71. package/docs/step-definitions/when-i-wait-ajax-finish.md +64 -0
  72. package/docs/step-definitions/when-i-wait.md +62 -0
  73. package/docs/step-definitions.md +50 -0
  74. package/examples/a11y.html +31 -0
  75. package/examples/cookies.html +10 -0
  76. package/examples/date.html +12 -0
  77. package/examples/diffy/baseline.html +54 -0
  78. package/examples/diffy/changed.html +63 -0
  79. package/examples/diffy/index.html +52 -0
  80. package/examples/element.html +11 -0
  81. package/examples/field.html +24 -0
  82. package/examples/index.html +6 -0
  83. package/examples/keyboard.html +11 -0
  84. package/examples/links.html +9 -0
  85. package/examples/modal.html +14 -0
  86. package/examples/path.html +3 -0
  87. package/examples/table.html +13 -0
  88. package/examples/test--when--i-additionally-select.html +27 -0
  89. package/package.json +19 -6
  90. package/playwright.config.ts +3 -2
  91. package/tests/features/a11y.feature +39 -0
  92. package/tests/features/cookie.feature +13 -0
  93. package/tests/features/date.feature +11 -0
  94. package/tests/features/diffy/test--diffy-01-example-demo.feature +22 -0
  95. package/tests/features/diffy/test--diffy-02-all-steps.feature +52 -0
  96. package/tests/features/diffy/test--diffy-03-real-api.feature +21 -0
  97. package/tests/features/element.feature +16 -0
  98. package/tests/features/field.feature +25 -0
  99. package/tests/features/keyboard.feature +10 -0
  100. package/tests/features/link.feature +11 -0
  101. package/tests/features/modal-advanced-example.feature +1 -1
  102. package/tests/features/modal.feature +11 -0
  103. package/tests/features/path.feature +16 -0
  104. package/tests/features/response.feature +8 -0
  105. package/tests/features/responsive.feature +10 -0
  106. package/tests/features/table.feature +18 -0
  107. package/tests/features/test--then--i-save-screenshot.feature +33 -0
  108. package/tests/features/test--then--i-see-locator.feature +320 -0
  109. package/tests/features/test--then--i-should-see-n-elements.feature +24 -0
  110. package/tests/features/test--then--print-current-url-and-response.feature +21 -0
  111. package/tests/features/test--when--i-additionally-select.feature +30 -0
  112. package/tests/features/test--when--i-follow.feature +22 -0
  113. package/tests/features/wait.feature +7 -0
  114. package/tests/features/yaml.feature +102 -0
  115. package/tests/reports/README.md +55 -0
  116. package/tests/selectors/_canonical-keys.json +113 -0
  117. package/tests/selectors/back-end-selectors.json +19 -0
  118. package/tests/selectors/cms-contentful-admin.json +35 -0
  119. package/tests/selectors/cms-craft-admin.json +39 -0
  120. package/tests/selectors/cms-drupal-cms-gin.json +56 -0
  121. package/tests/selectors/cms-drupal-core-claro.json +50 -0
  122. package/tests/selectors/cms-generic-admin.json +34 -0
  123. package/tests/selectors/cms-ghost-admin.json +34 -0
  124. package/tests/selectors/cms-joomla-admin.json +41 -0
  125. package/tests/selectors/cms-magento2-admin.json +32 -0
  126. package/tests/selectors/cms-prestashop-admin.json +38 -0
  127. package/tests/selectors/cms-shopify-admin.json +25 -0
  128. package/tests/selectors/cms-strapi-admin.json +42 -0
  129. package/tests/selectors/cms-typo3-admin.json +41 -0
  130. package/tests/selectors/cms-woocommerce-front.json +50 -0
  131. package/tests/selectors/cms-wordpress-admin.json +31 -0
  132. package/tests/selectors/framework-ant-design.json +80 -0
  133. package/tests/selectors/framework-bootstrap.json +86 -0
  134. package/tests/selectors/framework-bulma.json +74 -0
  135. package/tests/selectors/framework-chakra.json +58 -0
  136. package/tests/selectors/framework-foundation.json +51 -0
  137. package/tests/selectors/framework-material-ui.json +72 -0
  138. package/tests/selectors/framework-shadcn.json +51 -0
  139. package/tests/selectors/framework-tailwind.json +40 -0
  140. package/tests/selectors/framework-vuetify.json +61 -0
  141. package/tests/selectors/front-end-selectors.json +16 -0
  142. package/tests/selectors/homepage-selectors.json +13 -0
  143. package/tests/step-definitions/a11y.steps.js +798 -0
  144. package/tests/step-definitions/action.steps.js +167 -0
  145. package/tests/step-definitions/{webship-api.js → api.steps.js} +254 -44
  146. package/tests/step-definitions/assertion.steps.js +352 -0
  147. package/tests/step-definitions/auth.steps.js +124 -0
  148. package/tests/step-definitions/clock.steps.js +128 -0
  149. package/tests/step-definitions/cookie.steps.js +216 -0
  150. package/tests/step-definitions/debug.steps.js +31 -0
  151. package/tests/step-definitions/dialog.steps.js +193 -0
  152. package/tests/step-definitions/element.steps.js +314 -0
  153. package/tests/step-definitions/field.steps.js +653 -0
  154. package/tests/step-definitions/file-download.steps.js +193 -0
  155. package/tests/step-definitions/form.steps.js +333 -0
  156. package/tests/step-definitions/iframe.steps.js +178 -0
  157. package/tests/step-definitions/input.steps.js +163 -0
  158. package/tests/step-definitions/javascript.steps.js +71 -0
  159. package/tests/step-definitions/keyboard.steps.js +78 -0
  160. package/tests/step-definitions/link.steps.js +142 -0
  161. package/tests/step-definitions/metatag.steps.js +91 -0
  162. package/tests/step-definitions/modal.steps.js +219 -0
  163. package/tests/step-definitions/navigation.steps.js +218 -0
  164. package/tests/step-definitions/network.steps.js +238 -0
  165. package/tests/step-definitions/path.steps.js +141 -0
  166. package/tests/step-definitions/response.steps.js +98 -0
  167. package/tests/step-definitions/responsive.steps.js +123 -0
  168. package/tests/step-definitions/rest.steps.js +111 -0
  169. package/tests/step-definitions/screenshot.steps.js +423 -0
  170. package/tests/step-definitions/scroll.steps.js +189 -0
  171. package/tests/step-definitions/selectors.steps.js +996 -0
  172. package/tests/step-definitions/storage.steps.js +194 -0
  173. package/tests/step-definitions/table.steps.js +181 -0
  174. package/tests/step-definitions/wait.steps.js +400 -0
  175. package/tests/step-definitions/web-first.steps.js +296 -0
  176. package/tests/step-definitions/webship.js +567 -923
  177. package/tests/step-definitions/xml.steps.js +409 -0
  178. package/tests/step-definitions/yaml.steps.js +911 -0
  179. package/tests/step-definitions-diffy/README.md +329 -0
  180. package/tests/step-definitions-diffy/mock-diffy-api/server.js +84 -0
  181. package/tests/step-definitions-diffy/webship-diffy-mock.js +31 -0
  182. package/tests/step-definitions-diffy/webship-diffy.js +459 -0
  183. package/tsconfig.json +19 -3
  184. package/generate-reports.js +0 -22
  185. package/required/cucumber.js +0 -37
  186. package/required/generate-reports.js +0 -22
  187. package/required/package.json +0 -18
  188. package/required/playwright.config.ts +0 -37
  189. package/required/tests/features/README.md +0 -1
  190. package/required/tests/features/check-homepage.feature +0 -8
  191. package/required/tests/reports/README.md +0 -1
  192. package/required/tests/step-definitions/README.md +0 -1
  193. package/required/tests/step-definitions/custom.js +0 -4
  194. package/required/tsconfig.json +0 -12
@@ -0,0 +1,111 @@
1
+ 'use strict';
2
+
3
+ // Lightweight REST testing — distinct from the existing api.steps.js steps
4
+ // Preserves exact step phrasing for compatibility.
5
+
6
+ const { Given, When, Then } = require('@cucumber/cucumber');
7
+ const assert = require('assert');
8
+ const axios = require('axios');
9
+
10
+ function ensureState(world) {
11
+ if (!world._rest) world._rest = { headers: {}, response: null };
12
+ return world._rest;
13
+ }
14
+
15
+ /**
16
+ * Add an HTTP header to subsequent REST requests.
17
+ *
18
+ * Example #1: Given a REST header "Authorization" with value "Bearer abc123"
19
+ * Example #2: Given a REST header "Accept" with value "application/json"
20
+ * Example #3: And a REST header "X-Request-ID" with value "req-001"
21
+ * Example #4: Given a REST header "Content-Type" with value "application/json"
22
+ * Example #5: Given a REST header "X-API-Key" with value "key-xyz"
23
+ *
24
+ */
25
+ Given('a REST header {string} with value {string}', async function (name, value) {
26
+ ensureState(this).headers[name] = value;
27
+ });
28
+
29
+ /**
30
+ * Send an HTTP request without a body.
31
+ *
32
+ * Example #1: When I send a REST "GET" request to "/api/users"
33
+ * Example #2: When I send a REST "DELETE" request to "/api/orders/1"
34
+ * Example #3: And we send a REST "GET" request to "https://example.com/api/health"
35
+ * Example #4: When I send a REST "GET" request to "/api/me"
36
+ * Example #5: When I send a REST "DELETE" request to "/api/cart/items/42"
37
+ *
38
+ */
39
+ When(/^(I |we )*send a REST "([^"]*)" request to "([^"]*)"$/, async function (pronoun, method, url) {
40
+ const s = ensureState(this);
41
+ const target = url.startsWith('http') ? url : (this.launchUrl || '') + url;
42
+ s.response = await axios.request({
43
+ method, url: target, headers: s.headers, validateStatus: () => true,
44
+ });
45
+ });
46
+
47
+ /**
48
+ * Send an HTTP request with a doc-string body (raw text, JSON, or form-encoded).
49
+ *
50
+ * Example #1: When I send a REST "POST" request to "/api/users" with body:
51
+ * """
52
+ * {"name": "Alice"}
53
+ * """
54
+ * Example #2: When I send a REST "PUT" request to "/api/users/1" with body:
55
+ * """
56
+ * {"role": "admin"}
57
+ * """
58
+ * Example #3: And we send a REST "PATCH" request to "/api/orders/1" with body:
59
+ * """
60
+ * {"status": "shipped"}
61
+ * """
62
+ * Example #4: When I send a REST "POST" request to "/api/login" with body:
63
+ * """
64
+ * username=alice&password=s3cret
65
+ * """
66
+ * Example #5: When I send a REST "POST" request to "/webhooks/event" with body:
67
+ * """
68
+ * {"event": "ping"}
69
+ * """
70
+ *
71
+ */
72
+ When(/^(I |we )*send a REST "([^"]*)" request to "([^"]*)" with body:$/, async function (pronoun, method, url, body) {
73
+ const s = ensureState(this);
74
+ const target = url.startsWith('http') ? url : (this.launchUrl || '') + url;
75
+ s.response = await axios.request({
76
+ method, url: target, headers: s.headers, data: body, validateStatus: () => true,
77
+ });
78
+ });
79
+
80
+ /**
81
+ * Assert the most recent REST response carried an expected status code.
82
+ *
83
+ * Example #1: Then the REST response status code should be 200
84
+ * Example #2: Then the REST response status code should be 201
85
+ * Example #3: And the REST response status code should be 401
86
+ * Example #4: Then the REST response status code should be 404
87
+ * Example #5: Then the REST response status code should be 500
88
+ *
89
+ */
90
+ Then('the REST response status code should be {int}', async function (code) {
91
+ const s = ensureState(this);
92
+ assert.ok(s.response, 'No REST response captured.');
93
+ assert.strictEqual(s.response.status, code);
94
+ });
95
+
96
+ /**
97
+ * Assert the most recent REST response body contains a substring.
98
+ *
99
+ * Example #1: Then the REST response should contain "Alice"
100
+ * Example #2: Then the REST response should contain "id"
101
+ * Example #3: And the REST response should contain "shipped"
102
+ * Example #4: Then the REST response should contain "ok"
103
+ * Example #5: Then the REST response should contain "Welcome"
104
+ *
105
+ */
106
+ Then('the REST response should contain {string}', async function (text) {
107
+ const s = ensureState(this);
108
+ assert.ok(s.response, 'No REST response captured.');
109
+ const body = typeof s.response.data === 'string' ? s.response.data : JSON.stringify(s.response.data);
110
+ assert.ok(body.indexOf(text) !== -1, `REST response does not contain "${text}".`);
111
+ });
@@ -0,0 +1,423 @@
1
+ 'use strict';
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Webship-JS — Screenshot step definitions
5
+ //
6
+ // Saves PNG (and matching .html) screenshots to a configurable directory.
7
+ // Supports manual steps, automatic capture on failed step, and per-step
8
+ // capture for scenarios tagged @screenshots.
9
+ //
10
+ // Configuration: resolved per-scenario with this priority:
11
+ // 1. process.env.WEBSHIP_SCREENSHOT_* (CI / shell — highest)
12
+ // 2. cucumber.js worldParameters.screenshot.* (project-level defaults)
13
+ // 3. built-in defaults
14
+ //
15
+ // Supported env vars / worldParameters keys:
16
+ // WEBSHIP_SCREENSHOT_DIR dir default "./screenshots"
17
+ // WEBSHIP_SCREENSHOT_PURGE purge "true"/"false" — default false
18
+ // WEBSHIP_SCREENSHOT_ON_FAILED onFailed default true
19
+ // WEBSHIP_SCREENSHOT_ON_EVERY_STEP onEveryStep default false
20
+ // WEBSHIP_SCREENSHOT_FULLSCREEN alwaysFullscreen default false
21
+ // WEBSHIP_SCREENSHOT_FAILED_PREFIX failedPrefix default "failed_"
22
+ // WEBSHIP_SCREENSHOT_PATTERN filenamePattern default "{datetime}.{feature_file}.feature_{step_line}.{ext}"
23
+ // WEBSHIP_SCREENSHOT_PATTERN_FAIL filenamePatternFailed default "{failed_prefix}{datetime}.{feature_file}.feature_{step_line}.{ext}"
24
+ // WEBSHIP_SCREENSHOT_INFO_TYPES infoTypes comma list: url,feature,step,datetime
25
+ // ---------------------------------------------------------------------------
26
+
27
+ const { When, Then, Before, After, AfterStep, BeforeAll } = require('@cucumber/cucumber');
28
+ const fs = require('fs');
29
+ const path = require('path');
30
+ const { pad } = require('./webship');
31
+
32
+ function pick(envVal, paramVal, fallback) {
33
+ if (envVal !== undefined && envVal !== '') return envVal;
34
+ if (paramVal !== undefined && paramVal !== '' && paramVal !== null) return paramVal;
35
+ return fallback;
36
+ }
37
+
38
+ function asBool(v, fallback) {
39
+ if (v === undefined || v === null || v === '') return fallback;
40
+ if (typeof v === 'boolean') return v;
41
+ const s = String(v).toLowerCase();
42
+ return s === '1' || s === 'true' || s === 'yes';
43
+ }
44
+
45
+ function resolveConfig(parameters) {
46
+ const p = (parameters && parameters.screenshot) || {};
47
+ return {
48
+ dir: pick(process.env.WEBSHIP_SCREENSHOT_DIR, p.dir, './screenshots'),
49
+ purge: asBool(pick(process.env.WEBSHIP_SCREENSHOT_PURGE, p.purge, undefined), false),
50
+ onFailed: asBool(pick(process.env.WEBSHIP_SCREENSHOT_ON_FAILED, p.onFailed, undefined), true),
51
+ onEveryStep: asBool(pick(process.env.WEBSHIP_SCREENSHOT_ON_EVERY_STEP, p.onEveryStep, undefined), false),
52
+ alwaysFullscreen: asBool(pick(process.env.WEBSHIP_SCREENSHOT_FULLSCREEN, p.alwaysFullscreen, undefined), false),
53
+ failedPrefix: pick(process.env.WEBSHIP_SCREENSHOT_FAILED_PREFIX, p.failedPrefix, 'failed_'),
54
+ filenamePattern: pick(
55
+ process.env.WEBSHIP_SCREENSHOT_PATTERN,
56
+ p.filenamePattern,
57
+ '{datetime}.{feature_file}.feature_{step_line}.{ext}'
58
+ ),
59
+ filenamePatternFailed: pick(
60
+ process.env.WEBSHIP_SCREENSHOT_PATTERN_FAIL,
61
+ p.filenamePatternFailed,
62
+ '{failed_prefix}{datetime}.{feature_file}.feature_{step_line}.{ext}'
63
+ ),
64
+ infoTypes: String(pick(process.env.WEBSHIP_SCREENSHOT_INFO_TYPES, p.infoTypes, ''))
65
+ .split(',')
66
+ .map(s => s.trim())
67
+ .filter(Boolean),
68
+ };
69
+ }
70
+
71
+ // ---------------------------------------------------------------------------
72
+ // Filename tokenizer
73
+ // ---------------------------------------------------------------------------
74
+ function formatDate(d, format) {
75
+ const yyyy = d.getFullYear();
76
+ const MM = pad(d.getMonth() + 1, 2);
77
+ const dd = pad(d.getDate(), 2);
78
+ const HH = pad(d.getHours(), 2);
79
+ const mm = pad(d.getMinutes(), 2);
80
+ const ss = pad(d.getSeconds(), 2);
81
+ if (!format || format === 'Ymd_His') return `${yyyy}${MM}${dd}_${HH}${mm}${ss}`;
82
+ return format
83
+ .replace(/YYYY/g, yyyy)
84
+ .replace(/MM/g, MM)
85
+ .replace(/DD/g, dd)
86
+ .replace(/HH/g, HH)
87
+ .replace(/mm/g, mm)
88
+ .replace(/ss/g, ss);
89
+ }
90
+
91
+ function urlToken(url, qualifier) {
92
+ if (!url) return '';
93
+ let parsed;
94
+ try { parsed = new URL(url); } catch { return url; }
95
+ let out;
96
+ switch (qualifier) {
97
+ case 'origin': out = `${parsed.protocol}//${parsed.host}`; break;
98
+ case 'domain': out = parsed.host; break;
99
+ case 'path': out = parsed.pathname.replace(/^\/+|\/+$/g, ''); break;
100
+ case 'query': out = parsed.search.replace(/^\?/, ''); break;
101
+ case 'fragment': out = parsed.hash.replace(/^#/, ''); break;
102
+ case 'relative':
103
+ out = parsed.pathname.replace(/^\/+|\/+$/g, '') + parsed.search + parsed.hash;
104
+ break;
105
+ default: out = url;
106
+ }
107
+ return out.replace(/[^\w\-]+/g, '_');
108
+ }
109
+
110
+ function replaceTokens(pattern, data) {
111
+ return pattern.replace(/\{([^}]+)\}/g, (match, raw) => {
112
+ const [head, format] = raw.split(':');
113
+ const parts = head.split('_');
114
+ const name = parts.shift();
115
+ const qualifier = parts.join('_') || null;
116
+
117
+ if (name === 'ext') return data.ext || 'html';
118
+ if (name === 'failed' && qualifier === 'prefix') return data.failed_prefix || match;
119
+ if (name === 'feature' && qualifier === 'file') {
120
+ return data.feature_file ? path.basename(data.feature_file, '.feature') : match;
121
+ }
122
+ if (name === 'step') {
123
+ if (qualifier === 'line') {
124
+ const n = Number(data.step_line);
125
+ if (Number.isNaN(n)) return match;
126
+ // sprintf-like: {step_line:%03d}
127
+ if (format && /^%\d*d$/.test(format)) {
128
+ const w = parseInt(format.match(/\d+/)?.[0] || '0', 10);
129
+ return pad(n, w);
130
+ }
131
+ return String(n);
132
+ }
133
+ if (qualifier === 'name' && data.step_name) {
134
+ return String(data.step_name).replace(/[ "]+/g, c => (c === '"' ? '' : '_'));
135
+ }
136
+ return match;
137
+ }
138
+ if (name === 'url') return urlToken(data.url, qualifier);
139
+ if (name === 'datetime') return data.timestamp ? formatDate(new Date(data.timestamp), format) : match;
140
+ return match;
141
+ });
142
+ }
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // State tracked per-scenario
146
+ // ---------------------------------------------------------------------------
147
+ let purgedOnce = false;
148
+
149
+ function ensureDir(dir) {
150
+ fs.mkdirSync(dir, { recursive: true });
151
+ }
152
+
153
+ function purgeDir(dir) {
154
+ if (!fs.existsSync(dir)) return;
155
+ for (const entry of fs.readdirSync(dir)) {
156
+ const full = path.join(dir, entry);
157
+ const stat = fs.lstatSync(full);
158
+ if (stat.isDirectory()) fs.rmSync(full, { recursive: true, force: true });
159
+ else fs.unlinkSync(full);
160
+ }
161
+ }
162
+
163
+ function buildInfo(cfg, ctx) {
164
+ const lines = [];
165
+ for (const type of cfg.infoTypes) {
166
+ if (type === 'url' && ctx.url) lines.push(`Current URL: ${ctx.url}`);
167
+ if (type === 'feature' && ctx.featureTitle) lines.push(`Feature: ${ctx.featureTitle}`);
168
+ if (type === 'step' && ctx.stepText) lines.push(`Step: ${ctx.stepText} (line ${ctx.stepLine || '?'})`);
169
+ if (type === 'datetime') lines.push(`Datetime: ${formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')}`);
170
+ }
171
+ return lines.join('\n');
172
+ }
173
+
174
+ function makeFileName(cfg, ctx, ext, explicitName, isFailed) {
175
+ let pattern;
176
+ if (isFailed) pattern = cfg.filenamePatternFailed;
177
+ else if (explicitName) pattern = explicitName;
178
+ else pattern = cfg.filenamePattern;
179
+
180
+ if (!pattern.endsWith('.{ext}')) pattern += '.{ext}';
181
+
182
+ return replaceTokens(pattern, {
183
+ ext,
184
+ failed_prefix: cfg.failedPrefix,
185
+ feature_file: ctx.featureFile,
186
+ step_line: ctx.stepLine,
187
+ step_name: ctx.stepText,
188
+ timestamp: Date.now(),
189
+ url: ctx.url,
190
+ });
191
+ }
192
+
193
+ async function captureScreenshot(world, options = {}) {
194
+ const cfg = resolveConfig(world.parameters);
195
+ if (!world.page) return;
196
+
197
+ const fullscreen = Boolean(options.fullscreen || cfg.alwaysFullscreen);
198
+ const ctx = world.__screenshotCtx || {};
199
+
200
+ let url = '';
201
+ try { url = world.page.url(); } catch { /* page closed */ }
202
+ ctx.url = url;
203
+
204
+ ensureDir(cfg.dir);
205
+
206
+ // HTML capture (works for all drivers, Playwright content()).
207
+ try {
208
+ let html = await world.page.content();
209
+ const info = buildInfo(cfg, ctx);
210
+ if (info) html = info.replace(/\n/g, '<br/>\n') + '<hr/>\n' + html;
211
+ const htmlName = makeFileName(cfg, ctx, 'html', options.filename, options.isFailed);
212
+ fs.writeFileSync(path.join(cfg.dir, htmlName), html);
213
+ } catch { /* no content yet */ }
214
+
215
+ // PNG capture.
216
+ try {
217
+ const pngName = makeFileName(cfg, ctx, 'png', options.filename, options.isFailed);
218
+ await world.page.screenshot({
219
+ path: path.join(cfg.dir, pngName),
220
+ fullPage: fullscreen,
221
+ });
222
+ } catch { /* driver without screenshot support */ }
223
+ }
224
+
225
+ // ---------------------------------------------------------------------------
226
+ // Hooks
227
+ // ---------------------------------------------------------------------------
228
+ BeforeAll(function () {
229
+ const cfg = resolveConfig(this && this.parameters);
230
+ if (cfg.purge && !purgedOnce) {
231
+ purgeDir(cfg.dir);
232
+ purgedOnce = true;
233
+ }
234
+ });
235
+
236
+ Before(function (scenario) {
237
+ const pickledTags = (scenario.pickle && scenario.pickle.tags) || [];
238
+ this.__screenshotCtx = {
239
+ hasScreenshotsTag: pickledTags.some(t => t.name === '@screenshots'),
240
+ featureFile: (scenario.gherkinDocument && scenario.gherkinDocument.uri) || '',
241
+ featureTitle: (scenario.gherkinDocument && scenario.gherkinDocument.feature && scenario.gherkinDocument.feature.name) || '',
242
+ stepText: '',
243
+ stepLine: 0,
244
+ url: '',
245
+ };
246
+ });
247
+
248
+ AfterStep(async function (step) {
249
+ if (!this.__screenshotCtx) return;
250
+ this.__screenshotCtx.stepText = (step.pickleStep && step.pickleStep.text) || '';
251
+ this.__screenshotCtx.stepLine = step.pickleStep && step.pickleStep.astNodeIds ? 0 : 0;
252
+
253
+ if (step.gherkinDocument && step.pickleStep) {
254
+ const astIds = step.pickleStep.astNodeIds || [];
255
+ const steps = [];
256
+ (step.gherkinDocument.feature.children || []).forEach(child => {
257
+ const container = child.scenario || child.background;
258
+ if (container && container.steps) steps.push(...container.steps);
259
+ });
260
+ const match = steps.find(s => astIds.includes(s.id));
261
+ if (match && match.location) this.__screenshotCtx.stepLine = match.location.line;
262
+ }
263
+
264
+ const cfg = resolveConfig(this.parameters);
265
+ const passed = step.result && step.result.status === 'PASSED';
266
+
267
+ if (!passed && cfg.onFailed) {
268
+ await captureScreenshot(this, { isFailed: true, fullscreen: cfg.alwaysFullscreen });
269
+ return;
270
+ }
271
+ if (passed && (cfg.onEveryStep || this.__screenshotCtx.hasScreenshotsTag)) {
272
+ await captureScreenshot(this, { fullscreen: cfg.alwaysFullscreen });
273
+ }
274
+ });
275
+
276
+ // ---------------------------------------------------------------------------
277
+ // Step definitions
278
+ // ---------------------------------------------------------------------------
279
+
280
+ /**
281
+ * Save a screenshot at the current viewport size.
282
+ *
283
+ * Example #1: Then I save screenshot
284
+ * Example #2: When I save screenshot
285
+ * Example #3: Then save screenshot
286
+ * Example #4: Given I am on "/about-us"
287
+ * Then I save screenshot
288
+ * Example #5: When I go to homepage
289
+ * Then I save screenshot
290
+ * Example #6: Given I am on "/news"
291
+ * When I scroll to "#latest"
292
+ * Then I save screenshot
293
+ * Example #7: Given I am on "/contact"
294
+ * When I fill in "email" with "info@webship.co"
295
+ * Then I save screenshot
296
+ * Example #8: Given I am on "/search?q=UN"
297
+ * Then I save screenshot
298
+ * Example #9: Then I reload page
299
+ * Then I save screenshot
300
+ * Example #10: Given I am on "/partners/un.org"
301
+ * Then I save screenshot
302
+ */
303
+ When(/^(I |we )*save screenshot$/, async function (pronounCase) {
304
+ await captureScreenshot(this, {});
305
+ });
306
+
307
+ /**
308
+ * Save a full-page screenshot (entire scrollable area).
309
+ *
310
+ * Example #1: Then I save fullscreen screenshot
311
+ * Example #2: When I save fullscreen screenshot
312
+ * Example #3: Then save fullscreen screenshot
313
+ * Example #4: Given I am on "/news"
314
+ * Then I save fullscreen screenshot
315
+ * Example #5: Given I am on "/about-us"
316
+ * Then I save fullscreen screenshot
317
+ * Example #6: Given I am on homepage
318
+ * Then I save fullscreen screenshot
319
+ * Example #7: Given I am on "/partners"
320
+ * When I wait 2 seconds
321
+ * Then I save fullscreen screenshot
322
+ * Example #8: Given I am on "/webship"
323
+ * Then I save fullscreen screenshot
324
+ * Example #9: Given I am on "/un.org/reports"
325
+ * Then I save fullscreen screenshot
326
+ * Example #10: Given I am on "/long-article"
327
+ * Then I save fullscreen screenshot
328
+ */
329
+ When(/^(I |we )*save fullscreen screenshot$/, async function (pronounCase) {
330
+ await captureScreenshot(this, { fullscreen: true });
331
+ });
332
+
333
+ /**
334
+ * Resize the viewport to <width> x <height> then save a screenshot.
335
+ *
336
+ * Example #1: Then I save 1440 x 900 screenshot
337
+ * Example #2: Then I save 1200 x 800 screenshot
338
+ * Example #3: Then I save 375 x 667 screenshot
339
+ * Example #4: Then I save 768 x 1024 screenshot
340
+ * Example #5: Then I save 1920 x 1080 screenshot
341
+ * Example #6: Given I am on "/about-us"
342
+ * Then I save 1440 x 900 screenshot
343
+ * Example #7: Given I am on homepage
344
+ * Then I save 375 x 812 screenshot
345
+ * Example #8: Given I am on "/news"
346
+ * Then I save 1024 x 768 screenshot
347
+ * Example #9: Given I am on "/webship.co"
348
+ * Then I save 1366 x 768 screenshot
349
+ * Example #10: Given I am on "/un.org"
350
+ * Then I save 414 x 896 screenshot
351
+ */
352
+ When(/^(I |we )*save (\d+) x (\d+) screenshot$/, async function (pronounCase, width, height) {
353
+ await this.page.setViewportSize({ width: parseInt(width, 10), height: parseInt(height, 10) });
354
+ await captureScreenshot(this, {});
355
+ });
356
+
357
+ /**
358
+ * Resize the viewport to <width> x <height> then save a full-page screenshot.
359
+ *
360
+ * Example #1: Then I save fullscreen 1440 x 900 screenshot
361
+ * Example #2: Then I save fullscreen 1200 x 800 screenshot
362
+ * Example #3: Then I save fullscreen 375 x 667 screenshot
363
+ * Example #4: Then I save fullscreen 768 x 1024 screenshot
364
+ * Example #5: Then I save fullscreen 1920 x 1080 screenshot
365
+ * Example #6: Given I am on "/about-us"
366
+ * Then I save fullscreen 1440 x 900 screenshot
367
+ * Example #7: Given I am on homepage
368
+ * Then I save fullscreen 375 x 812 screenshot
369
+ * Example #8: Given I am on "/webship.co"
370
+ * Then I save fullscreen 1366 x 768 screenshot
371
+ * Example #9: Given I am on "/un.org"
372
+ * Then I save fullscreen 414 x 896 screenshot
373
+ * Example #10: Given I am on "/long-article"
374
+ * Then I save fullscreen 1440 x 900 screenshot
375
+ */
376
+ When(/^(I |we )*save fullscreen (\d+) x (\d+) screenshot$/, async function (pronounCase, width, height) {
377
+ await this.page.setViewportSize({ width: parseInt(width, 10), height: parseInt(height, 10) });
378
+ await captureScreenshot(this, { fullscreen: true });
379
+ });
380
+
381
+ /**
382
+ * Save a screenshot using an explicit filename (tokens supported).
383
+ *
384
+ * Example #1: Then I save screenshot with name "homepage.png"
385
+ * Example #2: Then I save screenshot with name "webship-home"
386
+ * Example #3: Then I save screenshot with name "un-landing-{datetime}.png"
387
+ * Example #4: Then I save screenshot with name "about-us.png"
388
+ * Example #5: Then I save screenshot with name "{feature_file}_{step_line}"
389
+ * Example #6: Then I save screenshot with name "{url_path}.png"
390
+ * Example #7: Given I am on "/news"
391
+ * Then I save screenshot with name "news-latest.png"
392
+ * Example #8: Given I am on "/webship.co"
393
+ * Then I save screenshot with name "webship-index.png"
394
+ * Example #9: Given I am on "/un.org"
395
+ * Then I save screenshot with name "un-home.png"
396
+ * Example #10: Then I save screenshot with name "contact-form-before-submit.png"
397
+ */
398
+ When(/^(I |we )*save screenshot with name "([^"]*)"$/, async function (pronounCase, filename) {
399
+ await captureScreenshot(this, { filename });
400
+ });
401
+
402
+ /**
403
+ * Save a full-page screenshot using an explicit filename (tokens supported).
404
+ *
405
+ * Example #1: Then I save fullscreen screenshot with name "homepage-full.png"
406
+ * Example #2: Then I save fullscreen screenshot with name "webship-home-full"
407
+ * Example #3: Then I save fullscreen screenshot with name "news-{datetime}.png"
408
+ * Example #4: Then I save fullscreen screenshot with name "about-us-full.png"
409
+ * Example #5: Then I save fullscreen screenshot with name "{feature_file}_full.png"
410
+ * Example #6: Then I save fullscreen screenshot with name "{url_path}-full.png"
411
+ * Example #7: Given I am on "/news"
412
+ * Then I save fullscreen screenshot with name "news-full.png"
413
+ * Example #8: Given I am on "/webship.co"
414
+ * Then I save fullscreen screenshot with name "webship-full.png"
415
+ * Example #9: Given I am on "/un.org"
416
+ * Then I save fullscreen screenshot with name "un-home-full.png"
417
+ * Example #10: Then I save fullscreen screenshot with name "long-article-full.png"
418
+ */
419
+ When(/^(I |we )*save fullscreen screenshot with name "([^"]*)"$/, async function (pronounCase, filename) {
420
+ await captureScreenshot(this, { filename, fullscreen: true });
421
+ });
422
+
423
+ module.exports = { resolveConfig, replaceTokens, makeFileName };