@dev-blinq/cucumber_client 1.0.1475-dev → 1.0.1475-stage

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 (47) hide show
  1. package/bin/assets/bundled_scripts/recorder.js +49 -49
  2. package/bin/assets/scripts/recorder.js +87 -34
  3. package/bin/assets/scripts/snapshot_capturer.js +10 -17
  4. package/bin/assets/scripts/unique_locators.js +78 -28
  5. package/bin/assets/templates/_hooks_template.txt +6 -2
  6. package/bin/assets/templates/utils_template.txt +16 -16
  7. package/bin/client/code_cleanup/codemod/find_harcoded_locators.js +173 -0
  8. package/bin/client/code_cleanup/codemod/fix_hardcoded_locators.js +247 -0
  9. package/bin/client/code_cleanup/utils.js +16 -7
  10. package/bin/client/code_gen/code_inversion.js +125 -1
  11. package/bin/client/code_gen/duplication_analysis.js +2 -1
  12. package/bin/client/code_gen/function_signature.js +8 -0
  13. package/bin/client/code_gen/index.js +4 -0
  14. package/bin/client/code_gen/page_reflection.js +90 -9
  15. package/bin/client/code_gen/playwright_codeget.js +173 -77
  16. package/bin/client/codemod/find_harcoded_locators.js +173 -0
  17. package/bin/client/codemod/fix_hardcoded_locators.js +247 -0
  18. package/bin/client/codemod/index.js +8 -0
  19. package/bin/client/codemod/locators_array/find_misstructured_elements.js +148 -0
  20. package/bin/client/codemod/locators_array/fix_misstructured_elements.js +144 -0
  21. package/bin/client/codemod/locators_array/index.js +114 -0
  22. package/bin/client/codemod/types.js +1 -0
  23. package/bin/client/cucumber/feature.js +4 -17
  24. package/bin/client/cucumber/steps_definitions.js +17 -12
  25. package/bin/client/recorderv3/bvt_init.js +310 -0
  26. package/bin/client/recorderv3/bvt_recorder.js +1560 -1183
  27. package/bin/client/recorderv3/constants.js +45 -0
  28. package/bin/client/recorderv3/implemented_steps.js +2 -0
  29. package/bin/client/recorderv3/index.js +3 -293
  30. package/bin/client/recorderv3/mixpanel.js +39 -0
  31. package/bin/client/recorderv3/services.js +839 -142
  32. package/bin/client/recorderv3/step_runner.js +36 -7
  33. package/bin/client/recorderv3/step_utils.js +316 -98
  34. package/bin/client/recorderv3/update_feature.js +85 -37
  35. package/bin/client/recorderv3/utils.js +80 -0
  36. package/bin/client/recorderv3/wbr_entry.js +61 -0
  37. package/bin/client/recording.js +1 -0
  38. package/bin/client/types/locators.js +2 -0
  39. package/bin/client/upload-service.js +2 -0
  40. package/bin/client/utils/app_dir.js +21 -0
  41. package/bin/client/utils/socket_logger.js +100 -125
  42. package/bin/index.js +5 -0
  43. package/package.json +21 -6
  44. package/bin/client/recorderv3/app_dir.js +0 -23
  45. package/bin/client/recorderv3/network.js +0 -299
  46. package/bin/client/recorderv3/scriptTest.js +0 -5
  47. package/bin/client/recorderv3/ws_server.js +0 -72
@@ -0,0 +1,173 @@
1
+ #!/usr/bin/env node
2
+ import { promises as fs } from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { parse } from "@babel/parser";
6
+ import traverseImport from "@babel/traverse";
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = path.dirname(__filename);
10
+
11
+ const ROOT = process.cwd();
12
+ const ALLOWED_HARDCODE_RATIO = 0.2;
13
+ const IGNORED_RATIO = 1.0;
14
+ const PLACEHOLDER_REGEX = /{[^}]+}/;
15
+ const IGNORE_DIRS = new Set(["node_modules", ".git", ".idea"]);
16
+
17
+ const results = [];
18
+
19
+ function hasPlaceholder(str) {
20
+ return PLACEHOLDER_REGEX.test(str);
21
+ }
22
+
23
+ function stringFromNode(node) {
24
+ if (!node) return undefined;
25
+ if (node.type === "StringLiteral") return node.value;
26
+ if (node.type === "TemplateLiteral") {
27
+ const raw = node.quasis.map((q) => q.value.cooked ?? q.value.raw).join("${}");
28
+ return raw;
29
+ }
30
+ return undefined;
31
+ }
32
+
33
+ function locatorIsParameterized(objNode) {
34
+ if (objNode.type !== "ObjectExpression") return false;
35
+ return objNode.properties.some((prop) => {
36
+ if (prop.type !== "ObjectProperty") return false;
37
+ const valueString = stringFromNode(prop.value);
38
+ return typeof valueString === "string" && hasPlaceholder(valueString);
39
+ });
40
+ }
41
+
42
+ function analyzeMjsFile(filePath, code) {
43
+ const ast = parse(code, {
44
+ sourceType: "module",
45
+ plugins: ["jsx", "typescript", "classProperties", "optionalChaining", "nullishCoalescingOperator", "topLevelAwait"],
46
+ });
47
+
48
+ const traverse = typeof traverseImport === "function" ? traverseImport : traverseImport.default;
49
+
50
+ traverse(ast, {
51
+ ObjectExpression(pathObj) {
52
+ const props = pathObj.node.properties;
53
+ const locatorProp = props.find(
54
+ (p) =>
55
+ p.type === "ObjectProperty" &&
56
+ ((p.key.type === "Identifier" && p.key.name === "locators") ||
57
+ (p.key.type === "StringLiteral" && p.key.value === "locators"))
58
+ );
59
+ if (!locatorProp || locatorProp.value.type !== "ArrayExpression") return;
60
+
61
+ const locators = locatorProp.value.elements.filter(Boolean);
62
+ if (locators.length === 0) return;
63
+
64
+ const total = locators.length;
65
+ const hardcoded = locators.filter((loc) => !locatorIsParameterized(loc)).length;
66
+ if (hardcoded / total === IGNORED_RATIO) return; // Skip if all locators are hardcoded (likely a non-locator object)
67
+ if (hardcoded / total <= ALLOWED_HARDCODE_RATIO) return;
68
+
69
+ const nameProp = props.find(
70
+ (p) =>
71
+ p.type === "ObjectProperty" &&
72
+ ((p.key.type === "Identifier" && (p.key.name === "element_name" || p.key.name === "element_key")) ||
73
+ (p.key.type === "StringLiteral" && (p.key.value === "element_name" || p.key.value === "element_key")))
74
+ );
75
+ const elementNameValue = nameProp ? stringFromNode(nameProp.value) : undefined;
76
+ const loc = pathObj.node.loc?.start;
77
+ results.push({
78
+ file: filePath,
79
+ line: loc?.line ?? 0,
80
+ element: elementNameValue ?? "<unknown>",
81
+ hardcoded,
82
+ total,
83
+ });
84
+ },
85
+ });
86
+ }
87
+
88
+ function locatorIsParameterizedJson(locator) {
89
+ if (locator && typeof locator === "object") {
90
+ return Object.values(locator).some((val) => typeof val === "string" && hasPlaceholder(val));
91
+ }
92
+ return false;
93
+ }
94
+
95
+ function findLineNumber(content, searchValue) {
96
+ const idx = content.indexOf(searchValue);
97
+ if (idx === -1) return 0;
98
+ return content.slice(0, idx).split("\n").length;
99
+ }
100
+
101
+ function analyzeJsonFile(filePath, content) {
102
+ let data;
103
+ try {
104
+ data = JSON.parse(content);
105
+ } catch (err) {
106
+ console.warn(`Skipping ${filePath}: invalid JSON`);
107
+ return;
108
+ }
109
+
110
+ const visit = (node) => {
111
+ if (!node || typeof node !== "object") return;
112
+ if (Array.isArray(node)) {
113
+ node.forEach(visit);
114
+ return;
115
+ }
116
+
117
+ if (Array.isArray(node.locators) && node.locators.length > 0) {
118
+ const total = node.locators.length;
119
+ const hardcoded = node.locators.filter((loc) => !locatorIsParameterizedJson(loc)).length;
120
+
121
+ if (hardcoded / total > ALLOWED_HARDCODE_RATIO) {
122
+ if (hardcoded / total === IGNORED_RATIO) return; // Skip if all locators are hardcoded (likely a non-locator object)
123
+ const name = node.element_name || node.element_key || "<unknown>";
124
+ const line = findLineNumber(content, name);
125
+ results.push({ file: filePath, line, element: name, hardcoded, total });
126
+ }
127
+ }
128
+
129
+ Object.values(node).forEach(visit);
130
+ };
131
+
132
+ visit(data);
133
+ }
134
+
135
+ async function walk(dir) {
136
+ const entries = await fs.readdir(dir, { withFileTypes: true });
137
+ for (const entry of entries) {
138
+ if (IGNORE_DIRS.has(entry.name)) continue;
139
+ const resolved = path.join(dir, entry.name);
140
+ if (entry.isDirectory()) {
141
+ await walk(resolved);
142
+ } else if (entry.isFile() && (entry.name.endsWith(".mjs") || entry.name.endsWith(".json"))) {
143
+ const content = await fs.readFile(resolved, "utf8");
144
+ try {
145
+ if (entry.name.endsWith(".mjs")) {
146
+ analyzeMjsFile(resolved, content);
147
+ } else {
148
+ analyzeJsonFile(resolved, content);
149
+ }
150
+ } catch (err) {
151
+ console.error(`Failed to analyze ${resolved}:`, err.message);
152
+ }
153
+ }
154
+ }
155
+ }
156
+
157
+ async function main() {
158
+ await walk(ROOT);
159
+ if (results.length === 0) {
160
+ console.log("No elements exceeded 20% hardcoded locator threshold.");
161
+ return;
162
+ }
163
+
164
+ for (const r of results) {
165
+ console.log(`${r.file}:${r.line} — ${r.element} (${r.hardcoded}/${r.total} hardcoded)`);
166
+ }
167
+ process.exitCode = 1;
168
+ }
169
+
170
+ main().catch((err) => {
171
+ console.error(err);
172
+ process.exit(1);
173
+ });
@@ -0,0 +1,247 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Codemod to drop hardcoded locators flagged by find_harcoded_locators.mjs.
4
+ * - Default: clones workspace to a temp dir, git init + baseline commit, applies fixes, prints diffs.
5
+ * - --inplace: modifies files in the current workspace.
6
+ *
7
+ * Behavior:
8
+ * For each reported file, in every object with a `locators` array,
9
+ * remove locator entries that contain no placeholders ({...}).
10
+ * If all locators are hardcoded, the array is left unchanged to avoid emptying it.
11
+ * JSON files are handled similarly.
12
+ *
13
+ * Usage:
14
+ * node find_harcoded_locators.mjs | node fix-hardcoded-locators.mjs
15
+ * node find_harcoded_locators.mjs | node fix-hardcoded-locators.mjs --inplace
16
+ */
17
+
18
+ import fs from "node:fs";
19
+ import { promises as fsPromises } from "node:fs";
20
+ import path from "node:path";
21
+ import os from "node:os";
22
+ import { parse } from "@babel/parser";
23
+ import traverseImport from "@babel/traverse";
24
+ import { spawnSync } from "node:child_process";
25
+
26
+ const traverse = typeof traverseImport === "function" ? traverseImport : traverseImport.default;
27
+ const PLACEHOLDER_REGEX = /{[^}]+}/;
28
+ const ROOT = process.cwd();
29
+
30
+ const INPUT = await readStdin();
31
+ if (!INPUT.trim()) {
32
+ console.error("No input provided. Pipe find_harcoded_locators.mjs into this script.");
33
+ process.exit(1);
34
+ }
35
+
36
+ const filesToFix = parseInputLines(INPUT);
37
+ if (filesToFix.size === 0) {
38
+ console.log("No actionable lines detected.");
39
+ process.exit(0);
40
+ }
41
+
42
+ const INPLACE = process.argv.includes("--inplace");
43
+ const { cloneRoot, mapper } = INPLACE ? { cloneRoot: ROOT, mapper: (p) => p } : await cloneWorkspace(ROOT);
44
+ if (!INPLACE) {
45
+ console.log(`Cloned workspace to: ${cloneRoot}`);
46
+ await initGitRepo(cloneRoot);
47
+ } else {
48
+ console.log("Running in-place (original files will be modified).");
49
+ }
50
+
51
+ const changes = [];
52
+
53
+ for (const originalPath of filesToFix) {
54
+ const clonedPath = mapper(originalPath);
55
+ const ext = path.extname(clonedPath).toLowerCase();
56
+ const original = await fsPromises.readFile(clonedPath, "utf8");
57
+ let fixed = original;
58
+
59
+ if (ext === ".json") {
60
+ fixed = fixJson(original);
61
+ } else if (ext === ".mjs" || ext === ".js") {
62
+ fixed = fixJs(original);
63
+ }
64
+
65
+ if (fixed === original) continue;
66
+
67
+ const diff = makeDiff(originalPath, clonedPath, fixed);
68
+ await fsPromises.writeFile(clonedPath, fixed, "utf8");
69
+ changes.push({ filePath: originalPath, diff });
70
+ }
71
+
72
+ if (changes.length === 0) {
73
+ console.log("No changes needed.");
74
+ process.exit(0);
75
+ }
76
+
77
+ for (const { filePath, diff } of changes) {
78
+ console.log(`\n=== ${filePath} (cloned) ===`);
79
+ console.log(diff.trimEnd());
80
+ }
81
+
82
+ process.exit(1);
83
+
84
+ // ---------- helpers ----------
85
+
86
+ function parseInputLines(text) {
87
+ const set = new Set();
88
+ for (const line of text.split(/\r?\n/)) {
89
+ const m = line.match(/^(.*?):\d+ — /);
90
+ if (m) set.add(m[1]);
91
+ }
92
+ return set;
93
+ }
94
+
95
+ function hasPlaceholder(str) {
96
+ return PLACEHOLDER_REGEX.test(str);
97
+ }
98
+
99
+ function locatorHasPlaceholderNode(node) {
100
+ if (!node || node.type !== "ObjectExpression") return false;
101
+ return node.properties.some((prop) => {
102
+ if (prop.type !== "ObjectProperty") return false;
103
+ const val = prop.value;
104
+ if (val.type === "StringLiteral") return hasPlaceholder(val.value);
105
+ if (val.type === "TemplateLiteral") {
106
+ const raw = val.quasis.map((q) => q.value.cooked ?? q.value.raw).join("${}");
107
+ return hasPlaceholder(raw);
108
+ }
109
+ return false;
110
+ });
111
+ }
112
+
113
+ function propName(prop) {
114
+ if (prop.type !== "ObjectProperty") return undefined;
115
+ const k = prop.key;
116
+ if (k.type === "Identifier") return k.name;
117
+ if (k.type === "StringLiteral") return k.value;
118
+ return undefined;
119
+ }
120
+
121
+ function leadingWhitespace(text, index) {
122
+ const lineStart = text.lastIndexOf("\n", index - 1) + 1;
123
+ const m = text.slice(lineStart, index).match(/^[ \t]*/);
124
+ return m ? m[0] : "";
125
+ }
126
+
127
+ function fixJs(code) {
128
+ let touched = false;
129
+ const replacements = [];
130
+
131
+ const ast = parse(code, {
132
+ sourceType: "module",
133
+ plugins: ["jsx", "typescript", "classProperties", "optionalChaining", "nullishCoalescingOperator", "topLevelAwait"],
134
+ ranges: true,
135
+ });
136
+
137
+ traverse(ast, {
138
+ ObjectExpression(pathObj) {
139
+ const props = pathObj.node.properties.filter((p) => p.type === "ObjectProperty");
140
+ if (!props.length) return;
141
+ const locProp = props.find((p) => propName(p) === "locators" && p.value.type === "ArrayExpression");
142
+ if (!locProp) return;
143
+ const elements = locProp.value.elements.filter(Boolean);
144
+ if (elements.length === 0) return;
145
+
146
+ const keep = elements.filter(locatorHasPlaceholderNode);
147
+ if (keep.length === elements.length) return;
148
+ if (keep.length === 0) return; // avoid emptying; leave as-is
149
+
150
+ if (typeof locProp.value.start !== "number" || typeof locProp.value.end !== "number") return;
151
+
152
+ const valueStart = locProp.value.start;
153
+ const valueEnd = locProp.value.end;
154
+ const indent = leadingWhitespace(code, valueStart) + " ";
155
+ const keepTexts = keep.map((el) => code.slice(el.start, el.end));
156
+ const newArray =
157
+ "[\n" + keepTexts.map((t) => indent + t.trim()).join(",\n") + "\n" + leadingWhitespace(code, valueStart) + "]";
158
+
159
+ replacements.push({ start: valueStart, end: valueEnd, text: newArray });
160
+ touched = true;
161
+ },
162
+ });
163
+
164
+ if (!touched) return code;
165
+
166
+ let out = code;
167
+ replacements
168
+ .sort((a, b) => b.start - a.start)
169
+ .forEach(({ start, end, text }) => {
170
+ out = out.slice(0, start) + text + out.slice(end);
171
+ });
172
+ return out;
173
+ }
174
+
175
+ function locatorHasPlaceholderJson(locator) {
176
+ if (locator && typeof locator === "object") {
177
+ return Object.values(locator).some((val) => typeof val === "string" && hasPlaceholder(val));
178
+ }
179
+ return false;
180
+ }
181
+
182
+ function fixJson(content) {
183
+ let data;
184
+ try {
185
+ data = JSON.parse(content);
186
+ } catch {
187
+ return content;
188
+ }
189
+ let touched = false;
190
+
191
+ const visit = (node) => {
192
+ if (!node || typeof node !== "object") return;
193
+ if (Array.isArray(node)) return node.forEach(visit);
194
+
195
+ if (Array.isArray(node.locators) && node.locators.length > 0) {
196
+ const keep = node.locators.filter(locatorHasPlaceholderJson);
197
+ if (keep.length > 0 && keep.length < node.locators.length) {
198
+ node.locators = keep;
199
+ touched = true;
200
+ }
201
+ }
202
+ Object.values(node).forEach(visit);
203
+ };
204
+
205
+ visit(data);
206
+ return touched ? JSON.stringify(data, null, 2) + "\n" : content;
207
+ }
208
+
209
+ async function cloneWorkspace(root) {
210
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "codemod-clone-"));
211
+ const cloneRoot = path.join(tmpDir, path.basename(root));
212
+
213
+ if (fsPromises.cp) {
214
+ await fsPromises.cp(root, cloneRoot, { recursive: true, force: true });
215
+ } else {
216
+ const res = spawnSync("cp", ["-R", ".", cloneRoot], { cwd: root, stdio: "inherit" });
217
+ if (res.status !== 0) throw new Error("Failed to clone workspace");
218
+ }
219
+
220
+ const mapper = (orig) => path.join(cloneRoot, path.relative(root, orig));
221
+ return { cloneRoot, mapper };
222
+ }
223
+
224
+ async function initGitRepo(cloneRoot) {
225
+ if (fs.existsSync(path.join(cloneRoot, ".git"))) return;
226
+ const run = (args) => spawnSync("git", args, { cwd: cloneRoot, stdio: "inherit" });
227
+ run(["init"]);
228
+ run(["add", "."]);
229
+ run(["commit", "-m", "chore: baseline before codemod"]);
230
+ }
231
+
232
+ function makeDiff(originalPath, clonedPath, fixed) {
233
+ const tmpOutDir = fs.mkdtempSync(path.join(os.tmpdir(), "codemod-out-"));
234
+ const fixedPath = path.join(tmpOutDir, path.basename(clonedPath));
235
+ fs.writeFileSync(fixedPath, fixed, "utf8");
236
+ const diff = spawnSync("diff", ["-u", originalPath, fixedPath], { encoding: "utf8" });
237
+ return diff.stdout || diff.stderr || "";
238
+ }
239
+
240
+ async function readStdin() {
241
+ return await new Promise((resolve) => {
242
+ let d = "";
243
+ process.stdin.setEncoding("utf8");
244
+ process.stdin.on("data", (c) => (d += c));
245
+ process.stdin.on("end", () => resolve(d));
246
+ });
247
+ }
@@ -10,7 +10,7 @@ import * as t from "@babel/types";
10
10
  import { CucumberExpression, ParameterTypeRegistry } from "@cucumber/cucumber-expressions";
11
11
  import { existsSync, readFileSync, writeFileSync } from "fs";
12
12
  import { getAiConfig } from "../code_gen/page_reflection.js";
13
- import socketLogger from "../utils/socket_logger.js";
13
+ import socketLogger, { getErrorMessage } from "../utils/socket_logger.js";
14
14
 
15
15
  const STEP_KEYWORDS = new Set(["Given", "When", "Then"]);
16
16
 
@@ -308,18 +308,27 @@ export function getDefaultPrettierConfig() {
308
308
  const configContent = readFileSync(prettierConfigPath, "utf-8");
309
309
  prettierConfig = JSON.parse(configContent);
310
310
  } catch (error) {
311
- socketLogger.error("Error parsing Prettier config file", error);
312
- console.error(`Error parsing Prettier config file: ${error}`);
311
+ socketLogger.error(
312
+ `Error parsing Prettier config file: ${getErrorMessage(error)}`,
313
+ undefined,
314
+ "getDefaultPrettierConfig"
315
+ );
313
316
  }
314
317
  } else {
315
318
  // save the default config to .prettierrc
316
319
  try {
317
320
  writeFileSync(prettierConfigPath, JSON.stringify(prettierConfig, null, 2), "utf-8");
318
- socketLogger.info(`Created default Prettier config at ${prettierConfigPath}`);
319
- console.log(`Created default Prettier config at ${prettierConfigPath}`);
321
+ socketLogger.info(
322
+ `Created default Prettier config at ${prettierConfigPath}`,
323
+ undefined,
324
+ "getDefaultPrettierConfig"
325
+ );
320
326
  } catch (error) {
321
- socketLogger.error(`Error writing Prettier config file: ${error}`);
322
- console.error(`Error writing Prettier config file: ${error}`);
327
+ socketLogger.error(
328
+ `Error writing Prettier config file: ${getErrorMessage(error)}`,
329
+ undefined,
330
+ "getDefaultPrettierConfig"
331
+ );
323
332
  }
324
333
  }
325
334
  return prettierConfig;