ff-dom 1.0.17 → 1.0.18-beta.1

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.
@@ -0,0 +1,2773 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const reWhiteSpace$1 = /^[\S]+( [\S]+)*$/gi;
6
+ const xpathCache$1 = {};
7
+ let multiElementReferenceMode = false;
8
+ let relativeXPathCache = new Map();
9
+ let modifiedElementAttributes$1 = [];
10
+ let mutationObserver;
11
+ const createObserver = (addedNodeCallBack) => {
12
+ mutationObserver = new MutationObserver((mutations) => {
13
+ mutations.forEach((mutation) => {
14
+ if (mutation?.addedNodes?.length) {
15
+ addedNodeCallBack(mutation?.addedNodes);
16
+ }
17
+ if (mutation.target instanceof HTMLElement) {
18
+ if (mutation?.type === "attributes" &&
19
+ mutation.attributeName === "class" &&
20
+ ((isSvg(mutation.target) &&
21
+ mutation.oldValue?.trim() ===
22
+ mutation.target.classList.value?.trim()) ||
23
+ mutation.target.classList?.value
24
+ ?.replace(mutation.oldValue, "")
25
+ .trim() === "marked-element-temp" ||
26
+ mutation?.oldValue
27
+ ?.replace(mutation.target.classList?.value, "")
28
+ .trim() === "marked-element-temp")) ;
29
+ else if (mutation?.type === "attributes" &&
30
+ !["flndisabled"].includes(mutation.attributeName)) {
31
+ modifiedElementAttributes$1.push({
32
+ url: mutation.target.baseURI,
33
+ attributeName: mutation.attributeName,
34
+ element: mutation.target,
35
+ doc: mutation.target.ownerDocument,
36
+ });
37
+ }
38
+ }
39
+ });
40
+ });
41
+ };
42
+ const startObserver = (target, options) => {
43
+ mutationObserver?.observe(target, options);
44
+ };
45
+ const stopObserver = () => {
46
+ mutationObserver?.disconnect();
47
+ };
48
+ const isNumberExist = (str) => {
49
+ const hasNumber = /\d/;
50
+ return hasNumber.test(str);
51
+ };
52
+ const buildPattern = (pattern, isSvg, tagName) => {
53
+ return isSvg
54
+ ? `//*[local-name()='${tagName}' and ${pattern}]`
55
+ : `//${tagName}[${pattern}]`;
56
+ };
57
+ const getTextContent = (targetElement) => {
58
+ const textContent = targetElement?.textContent;
59
+ {
60
+ return textContent;
61
+ }
62
+ };
63
+ const getFilteredText = (element) => {
64
+ return element?.childNodes[0]?.nodeValue || "";
65
+ };
66
+ const getCountOfXPath = (xpath, element, docmt) => {
67
+ try {
68
+ let count;
69
+ // Check if result is cached
70
+ if (xpathCache$1[xpath] !== undefined) {
71
+ count = xpathCache$1[xpath];
72
+ }
73
+ else {
74
+ const owner = docmt.nodeType === 9 // DOCUMENT_NODE
75
+ ? docmt
76
+ : docmt.ownerDocument;
77
+ count = owner.evaluate(`count(${xpath})`, docmt, null, XPathResult.NUMBER_TYPE, null).numberValue;
78
+ xpathCache$1[xpath] = count;
79
+ }
80
+ if (multiElementReferenceMode && Array.isArray(element)) ;
81
+ else {
82
+ // Short-circuit if we only need to match one element
83
+ if (count === 1) {
84
+ const elementFromXpath = getElementFromXpath(xpath, docmt);
85
+ return elementFromXpath === element ? count : 0; // Return 0 if no match
86
+ }
87
+ }
88
+ return count; // Return the count
89
+ }
90
+ catch (error) {
91
+ console.error(`Error evaluating XPath: ${xpath}`, error);
92
+ return 0; // Return 0 on error to avoid re-processing
93
+ }
94
+ };
95
+ const escapeCharacters = (text) => {
96
+ if (text) {
97
+ if (!(text.indexOf('"') === -1)) {
98
+ return `'${text}'`;
99
+ }
100
+ if (!(text.indexOf("'") === -1)) {
101
+ return `"${text}"`;
102
+ }
103
+ }
104
+ return `'${text}'`;
105
+ };
106
+ const removeParenthesis = (xpath) => {
107
+ const charArr = xpath.split("");
108
+ let count = charArr.length;
109
+ const indexArray = [];
110
+ while (charArr[count - 2] !== "[") {
111
+ indexArray.push(charArr[count - 2]);
112
+ count--;
113
+ }
114
+ indexArray.reverse();
115
+ let finalStr = "";
116
+ for (let i = 0; i < indexArray.length; i++) {
117
+ finalStr += indexArray[i];
118
+ }
119
+ const endBracketLength = finalStr.length + 2;
120
+ let firstpart = xpath.slice(0, xpath.length - endBracketLength);
121
+ if (firstpart.startsWith("(") && firstpart.endsWith(")")) {
122
+ firstpart = firstpart.slice(1, -1);
123
+ }
124
+ else {
125
+ firstpart = xpath;
126
+ }
127
+ return firstpart;
128
+ };
129
+ const findXpathWithIndex = (val, node, docmt, count) => {
130
+ try {
131
+ const owner = docmt.nodeType === 9 // DOCUMENT_NODE
132
+ ? docmt
133
+ : docmt.ownerDocument;
134
+ let index = 0;
135
+ if (count) {
136
+ if (getCountOfXPath(`${val}[${count}]`, node, docmt) === 1) {
137
+ return `${val}[${count}]`;
138
+ }
139
+ if (getCountOfXPath(`(${val})[${count}]`, node, docmt) === 1) {
140
+ return `(${val})[${count}]`;
141
+ }
142
+ }
143
+ const nodes = owner.evaluate(val, docmt, null, XPathResult.ANY_TYPE, null);
144
+ let nodex;
145
+ while ((nodex = nodes.iterateNext())) {
146
+ index++;
147
+ if (nodex.isSameNode(node)) {
148
+ if (getCountOfXPath(`${val}[${index}]`, node, docmt) === 1) {
149
+ return `${val}[${index}]`;
150
+ }
151
+ if (getCountOfXPath(`(${val})[${index}]`, node, docmt) === 1) {
152
+ return `(${val})[${index}]`;
153
+ }
154
+ return;
155
+ }
156
+ }
157
+ }
158
+ catch (error) {
159
+ console.log(error);
160
+ }
161
+ };
162
+ const deleteLineGap = (a) => {
163
+ a &&= a.split("\n")[0].length > 0 ? a.split("\n")[0] : a.split("\n")[1];
164
+ return a;
165
+ };
166
+ const deleteGarbageFromInnerText = (a) => {
167
+ a = deleteLineGap(a);
168
+ a = a
169
+ .split(/[^\u0000-\u00ff]/)
170
+ .reduce((b, c) => {
171
+ return b.length > c.length ? b : c;
172
+ }, "")
173
+ .trim();
174
+ return (a = a.split("/")[0].trim());
175
+ };
176
+ const replaceWhiteSpaces = (str) => {
177
+ if (str) {
178
+ return str.replace(/\s\s+/g, " ").trim();
179
+ }
180
+ return str;
181
+ };
182
+ const getShadowRoot = (a) => {
183
+ for (a = a && a.parentElement; a;) {
184
+ if (a.toString() === "[object ShadowRoot]")
185
+ return a;
186
+ a = a.parentElement;
187
+ }
188
+ return null;
189
+ };
190
+ const checkBlockedAttributes = (attribute, targetElement, isTarget) => {
191
+ if (!attribute?.value ||
192
+ typeof attribute?.value === "boolean" ||
193
+ ["true", "false", "on", "off", "flntooltip"].some((x) => x === attribute.value) ||
194
+ ["type", "style", "locator-data-tooltip", "value"].some((x) => x === attribute.name) ||
195
+ modifiedElementAttributes$1?.find((x) => x.doc === targetElement.ownerDocument &&
196
+ x.element === targetElement &&
197
+ x.attributeName === attribute.name) ||
198
+ (attribute?.name?.indexOf("on") === 0 && attribute?.name?.length > 3) ||
199
+ typeof attribute.value === "function" ||
200
+ (isTarget && isNumberExist(attribute.value))) {
201
+ return false;
202
+ }
203
+ return true;
204
+ };
205
+ const getRelationship = (a, b) => {
206
+ let pos = a.compareDocumentPosition(b);
207
+ return pos === 2
208
+ ? "preceding"
209
+ : pos === 4
210
+ ? "following"
211
+ : pos === 8
212
+ ? "ancestor"
213
+ : pos === 16
214
+ ? "descendant"
215
+ : pos === 32
216
+ ? "self"
217
+ : "";
218
+ };
219
+ const findRoot = (node) => {
220
+ while (node && node.parentNode) {
221
+ node = node.parentNode;
222
+ }
223
+ return node;
224
+ };
225
+ const isSvg = (element) => {
226
+ return element instanceof SVGElement;
227
+ };
228
+ const replaceTempAttributes = (str) => {
229
+ if (!str)
230
+ return str;
231
+ return str.replace(/\b[a-zA-Z_]*disabled\b/gi, "disabled");
232
+ };
233
+ const getElementFromXpath = (xpath, docmt, multi = false) => {
234
+ const owner = docmt.nodeType === 9 // DOCUMENT_NODE
235
+ ? docmt
236
+ : docmt.ownerDocument;
237
+ if (multi) {
238
+ return owner.evaluate(xpath, docmt, null, XPathResult.ANY_TYPE, null);
239
+ }
240
+ else {
241
+ return owner.evaluate(xpath, docmt, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
242
+ }
243
+ };
244
+ const getPropertyXPath = (element, docmt, prop, value, isIndex, isTarget) => {
245
+ if (value) {
246
+ const { tagName } = element;
247
+ let count;
248
+ let combinePattern = "";
249
+ const mergePattern = [];
250
+ let pattern;
251
+ if (value && (!isTarget || !isNumberExist(value))) {
252
+ if (!reWhiteSpace$1.test(value)) {
253
+ pattern = buildPattern(`normalize-space(${prop})=${escapeCharacters(replaceWhiteSpaces(value)).trim()}`, isSvg(element), element.tagName.toLowerCase());
254
+ }
255
+ else {
256
+ pattern = `//${tagName}[${prop}=${escapeCharacters(value)}]`;
257
+ }
258
+ count = getCountOfXPath(pattern, element, docmt);
259
+ if (count === 1 && !isIndex) {
260
+ return pattern;
261
+ }
262
+ }
263
+ if (value && isTarget) {
264
+ const splitText = value.split(" ");
265
+ if (splitText?.length) {
266
+ if (splitText.length === 1) {
267
+ const contentRes = [...new Set(splitText[0].match(/([^0-9]+)/g))];
268
+ if (contentRes?.length >= 1) {
269
+ if (contentRes[0] &&
270
+ replaceWhiteSpaces(contentRes[0].trim())?.length > 1) {
271
+ if (value.startsWith(contentRes[0])) {
272
+ if (!reWhiteSpace$1.test(contentRes[0])) {
273
+ combinePattern = `starts-with(${prop},${escapeCharacters(replaceWhiteSpaces(contentRes[0])).trim()})`;
274
+ }
275
+ else {
276
+ combinePattern = `starts-with(${prop},${escapeCharacters(contentRes[0]).trim()})`;
277
+ }
278
+ }
279
+ }
280
+ }
281
+ if (contentRes?.length > 1) {
282
+ if (contentRes[contentRes.length - 1] &&
283
+ replaceWhiteSpaces(contentRes[contentRes.length - 1].trim())
284
+ ?.length > 1) {
285
+ if (value.endsWith(contentRes[contentRes.length - 1])) {
286
+ if (!reWhiteSpace$1.test(contentRes[contentRes.length - 1])) {
287
+ combinePattern = `ends-with(${prop},${escapeCharacters(replaceWhiteSpaces(contentRes[contentRes.length - 1])).trim()})`;
288
+ }
289
+ else {
290
+ combinePattern = `ends-with(${prop},${escapeCharacters(contentRes[contentRes.length - 1]).trim()})`;
291
+ }
292
+ }
293
+ }
294
+ }
295
+ if (combinePattern?.length) {
296
+ if (isSvg(element)) {
297
+ pattern = `//*[local-name()='${tagName}' and ${combinePattern}]`;
298
+ }
299
+ else {
300
+ pattern = `//${tagName}[${combinePattern}]`;
301
+ }
302
+ count = getCountOfXPath(pattern, element, docmt);
303
+ if (count === 1 && !isIndex) {
304
+ return pattern;
305
+ }
306
+ }
307
+ }
308
+ else {
309
+ const endIndex = splitText.length % 2 === 0
310
+ ? splitText.length / 2
311
+ : splitText.length % 2;
312
+ const startIndexString = splitText.slice(0, endIndex).join(" ");
313
+ let contentRes = [...new Set(startIndexString.match(/([^0-9]+)/g))];
314
+ if (contentRes?.length) {
315
+ if (contentRes[0] &&
316
+ replaceWhiteSpaces(contentRes[0].trim())?.length) {
317
+ if (value.startsWith(contentRes[0])) {
318
+ if (!reWhiteSpace$1.test(contentRes[0])) {
319
+ combinePattern = `starts-with(${prop},${escapeCharacters(replaceWhiteSpaces(contentRes[0])).trim()})`;
320
+ }
321
+ else {
322
+ combinePattern = `starts-with(${prop},${escapeCharacters(contentRes[0]).trim()})`;
323
+ }
324
+ }
325
+ }
326
+ }
327
+ if (combinePattern?.length) {
328
+ if (isSvg(element)) {
329
+ pattern = `//*[local-name()='${tagName}' and ${combinePattern}]`;
330
+ }
331
+ else {
332
+ pattern = `//${tagName}[${combinePattern}]`;
333
+ }
334
+ count = getCountOfXPath(pattern, element, docmt);
335
+ if (count === 1 && !isIndex) {
336
+ return pattern;
337
+ }
338
+ }
339
+ const endIndexString = splitText
340
+ .slice(endIndex, splitText.length - 1)
341
+ .join(" ");
342
+ contentRes = [...new Set(endIndexString.match(/([^0-9]+)/g))];
343
+ if (contentRes?.length) {
344
+ if (contentRes[0] &&
345
+ replaceWhiteSpaces(contentRes[0].trim())?.length > 3) {
346
+ if (value.endsWith(contentRes[0])) {
347
+ if (!reWhiteSpace$1.test(contentRes[0])) {
348
+ combinePattern = `ends-with(${prop},${escapeCharacters(replaceWhiteSpaces(contentRes[0])).trim()})`;
349
+ }
350
+ else {
351
+ combinePattern = `ends-with(${prop},${escapeCharacters(contentRes[0]).trim()})`;
352
+ }
353
+ }
354
+ }
355
+ }
356
+ if (combinePattern?.length) {
357
+ if (isSvg(element)) {
358
+ pattern = `//*[local-name()='${tagName}' and ${combinePattern}]`;
359
+ }
360
+ else {
361
+ pattern = `//${tagName}[${combinePattern}]`;
362
+ }
363
+ count = getCountOfXPath(pattern, element, docmt);
364
+ if (count === 1 && !isIndex) {
365
+ return pattern;
366
+ }
367
+ }
368
+ }
369
+ }
370
+ }
371
+ if (value && isTarget && isNumberExist(value)) {
372
+ const contentRes = [...new Set(value.match(/([^0-9]+)/g))];
373
+ if (contentRes?.length) {
374
+ for (let i = 0; i < contentRes?.length; i++) {
375
+ if (contentRes[i] &&
376
+ replaceWhiteSpaces(contentRes[i].trim())?.length > 1) {
377
+ if (!reWhiteSpace$1.test(contentRes[i])) {
378
+ mergePattern.push(`contains(${prop},${escapeCharacters(replaceWhiteSpaces(contentRes[i])).trim()})`);
379
+ }
380
+ else {
381
+ mergePattern.push(`contains(${prop},${escapeCharacters(contentRes[i].trim()).trim()})`);
382
+ }
383
+ }
384
+ }
385
+ }
386
+ if (mergePattern?.length) {
387
+ if (isSvg(element)) {
388
+ pattern = `//*[local-name()='${tagName}' and ${mergePattern.join(" and ")}]`;
389
+ }
390
+ else {
391
+ pattern = `//${tagName}[${mergePattern.join(" and ")}]`;
392
+ }
393
+ count = getCountOfXPath(pattern, element, docmt);
394
+ if (count === 1 && !isIndex) {
395
+ return pattern;
396
+ }
397
+ }
398
+ }
399
+ if (isSvg(element)) {
400
+ pattern = `//*[local-name()='${tagName}' and text()]`;
401
+ }
402
+ else {
403
+ pattern = `//${tagName}[text()]`;
404
+ }
405
+ count = getCountOfXPath(pattern, element, docmt);
406
+ if (count === 1 && !isIndex) {
407
+ return pattern;
408
+ }
409
+ }
410
+ };
411
+ const getAbsoluteXPath = (domNode, docmt) => {
412
+ try {
413
+ if (!domNode) {
414
+ return "";
415
+ }
416
+ let xpathe = isSvg(domNode)
417
+ ? `/*[local-name()='${domNode.tagName}']`
418
+ : `/${domNode.tagName}`;
419
+ // // If this node has siblings of the same tagName, get the index of this node
420
+ if (domNode.parentElement) {
421
+ // Get the siblings
422
+ const childNodes = Array.prototype.slice
423
+ .call(domNode.parentElement.children, 0)
424
+ .filter((childNode) => childNode.tagName === domNode.tagName);
425
+ // // If there's more than one sibling, append the index
426
+ if (childNodes.length > 1) {
427
+ const index = childNodes.indexOf(domNode);
428
+ xpathe += `[${index + 1}]`;
429
+ }
430
+ }
431
+ else if (domNode instanceof HTMLElement) {
432
+ if (domNode.offsetParent) {
433
+ const childNodes = Array.prototype.slice
434
+ .call(domNode.offsetParent.children, 0)
435
+ .filter((childNode) => childNode.tagName === domNode.tagName);
436
+ // // If there's more than one sibling, append the index
437
+ if (childNodes.length > 1) {
438
+ const index = childNodes.indexOf(domNode);
439
+ xpathe += `[${index + 1}]`;
440
+ }
441
+ }
442
+ }
443
+ // // Make a recursive call to this nodes parents and prepend it to this xpath
444
+ return getAbsoluteXPath(domNode?.parentElement, docmt) + xpathe;
445
+ }
446
+ catch (error) {
447
+ // If there's an unexpected exception, abort and don't get an XPath
448
+ console.log("xpath", error);
449
+ return "";
450
+ }
451
+ };
452
+ const getRelativeXPath = (domNode, docmt, isIndex, isTarget = false, attributesArray) => {
453
+ try {
454
+ // Generate a cache key based on the node's identifier, index, and target flag
455
+ // Check if the result for this node is already cached
456
+ if (relativeXPathCache.has(domNode)) {
457
+ return relativeXPathCache.get(domNode);
458
+ }
459
+ // Initialize an array to hold parts of the XPath
460
+ const xpathParts = [];
461
+ let currentNode = domNode;
462
+ // Traverse up the DOM tree iteratively instead of using recursion
463
+ while (currentNode) {
464
+ let xpathe = "";
465
+ let hasUniqueAttr = false;
466
+ let attributes = domNode === currentNode ? attributesArray : currentNode.attributes;
467
+ // Loop through attributes to check for unique identifiers
468
+ for (const attrName of attributes) {
469
+ if (checkBlockedAttributes(attrName, currentNode, isTarget)) {
470
+ let attrValue = attrName.nodeValue;
471
+ // Clean up attribute value
472
+ attrValue = attrValue?.replace("removePointers", "") ?? "";
473
+ const elementName = attrName.name;
474
+ // Construct an XPath based on attribute
475
+ xpathe = getXpathString(currentNode, elementName, attrValue);
476
+ let othersWithAttr = 0;
477
+ if (xpathe) {
478
+ othersWithAttr = getCountOfXPath(xpathe, currentNode, docmt);
479
+ if (othersWithAttr === 1) {
480
+ xpathParts.unshift(replaceTempAttributes(xpathe));
481
+ hasUniqueAttr = true;
482
+ break;
483
+ }
484
+ }
485
+ if (othersWithAttr > 1 && isIndex) {
486
+ xpathe = findXpathWithIndex(xpathe, currentNode, docmt, othersWithAttr);
487
+ if (xpathe) {
488
+ xpathParts.unshift(replaceTempAttributes(xpathe));
489
+ hasUniqueAttr = true;
490
+ break;
491
+ }
492
+ // return replaceTempAttributes(xpathe);
493
+ }
494
+ }
495
+ }
496
+ if (currentNode.textContent) {
497
+ if (!isTarget || (isTarget && !isNumberExist(currentNode.textContent))) {
498
+ let reWhiteSpace = new RegExp(/^[\S]+( [\S]+)*$/gi);
499
+ if (!reWhiteSpace.test(currentNode.textContent)) {
500
+ xpathe =
501
+ isSvg(currentNode)
502
+ ? `//*[local-name()='${currentNode.tagName}' and normalize-space(.)=${escapeCharacters(getFilteredText(currentNode))}]`
503
+ : `//${currentNode.tagName || "*"}[normalize-space(.)=${escapeCharacters(getFilteredText(currentNode))}]`;
504
+ }
505
+ else {
506
+ xpathe =
507
+ isSvg(currentNode)
508
+ ? `//*[local-name()='${currentNode.tagName}' and .=${escapeCharacters(getFilteredText(currentNode))}]`
509
+ : `//${currentNode.tagName || "*"}[.=${escapeCharacters(getFilteredText(currentNode))}]`;
510
+ }
511
+ let othersWithAttr = getCountOfXPath(xpathe, currentNode, docmt);
512
+ if (othersWithAttr === 1) {
513
+ return xpathe;
514
+ }
515
+ if (othersWithAttr > 1 && isIndex) {
516
+ xpathe = findXpathWithIndex(xpathe, currentNode, docmt, othersWithAttr);
517
+ return xpathe;
518
+ }
519
+ }
520
+ else {
521
+ let combinePattern = [];
522
+ const contentRes = [
523
+ ...new Set(getFilteredText(currentNode).match(/([^0-9]+)/g)),
524
+ ];
525
+ let reWhiteSpace = new RegExp(/^[\S]+( [\S]+)*$/gi);
526
+ if (contentRes?.length) {
527
+ for (let i = 0; i < contentRes?.length; i++) {
528
+ if (contentRes[i] &&
529
+ replaceWhiteSpaces(contentRes[i].trim())) {
530
+ if (!reWhiteSpace.test(contentRes[i])) {
531
+ combinePattern.push(`contains(.,${escapeCharacters(replaceWhiteSpaces(contentRes[i])).trim()})`);
532
+ }
533
+ else {
534
+ combinePattern.push(`contains(.,${escapeCharacters(contentRes[i].trim()).trim()})`);
535
+ }
536
+ }
537
+ }
538
+ }
539
+ if (combinePattern?.length) {
540
+ xpathe =
541
+ isSvg(currentNode)
542
+ ? `//*[local-name()='${currentNode.tagName}' and ${combinePattern.join(" and ")}]`
543
+ : `//${currentNode.tagName || "*"}[${combinePattern.join(" and ")}]`;
544
+ let othersWithAttr = getCountOfXPath(xpathe, currentNode, docmt);
545
+ if (othersWithAttr === 1) {
546
+ return xpathe;
547
+ }
548
+ if (othersWithAttr > 1 && isIndex) {
549
+ xpathe = findXpathWithIndex(xpathe, currentNode, docmt, othersWithAttr);
550
+ return xpathe;
551
+ }
552
+ }
553
+ }
554
+ }
555
+ // If no unique attribute was found, construct XPath by tag name
556
+ if (!hasUniqueAttr) {
557
+ let tagBasedXPath = isSvg(currentNode)
558
+ ? `/*[local-name()='${currentNode.tagName}']`
559
+ : `/${currentNode.tagName}`;
560
+ // Handle sibling nodes
561
+ if (currentNode.parentElement) {
562
+ const siblings = Array.from(currentNode.parentElement.children).filter((childNode) => childNode.tagName === currentNode.tagName);
563
+ // Append index to distinguish between siblings
564
+ if (siblings.length > 1) {
565
+ const index = siblings.indexOf(currentNode);
566
+ tagBasedXPath += `[${index + 1}]`;
567
+ }
568
+ }
569
+ // Add the constructed tag-based XPath to the parts array
570
+ xpathParts.unshift(tagBasedXPath);
571
+ }
572
+ else {
573
+ break;
574
+ }
575
+ // Move up to the parent node for the next iteration
576
+ currentNode = currentNode.parentElement;
577
+ }
578
+ // Combine all parts into the final XPath
579
+ const finalXPath = `${xpathParts.join("")}`;
580
+ // Cache the final XPath for this node
581
+ relativeXPathCache.set(domNode, finalXPath);
582
+ return finalXPath;
583
+ }
584
+ catch (error) {
585
+ console.log(error);
586
+ return null;
587
+ }
588
+ };
589
+ const getCombinationXpath = (attribute, domNode) => {
590
+ const combinePattern = [];
591
+ let pattern = "";
592
+ if (attribute &&
593
+ !isNumberExist(attribute.value) &&
594
+ typeof attribute.nodeValue !== "function" // &&
595
+ // !modifiedElementAttributes?.find(
596
+ // (x) => x.element === domNode && x.attributeName === attribute.name
597
+ // )
598
+ ) {
599
+ const contentRes = [...new Set(attribute.value.match(/([^0-9]+)/g))];
600
+ if (contentRes?.length) {
601
+ for (let i = 0; i < contentRes?.length; i++) {
602
+ if (contentRes[i] &&
603
+ replaceWhiteSpaces(contentRes[i].trim())?.length > 2) {
604
+ if (!reWhiteSpace$1.test(contentRes[i])) {
605
+ combinePattern.push(`contains(@${attribute.name},${escapeCharacters(replaceWhiteSpaces(contentRes[i])).trim()})`);
606
+ }
607
+ else {
608
+ combinePattern.push(`contains(@${attribute.name},${escapeCharacters(contentRes[i].trim())})`);
609
+ }
610
+ }
611
+ }
612
+ }
613
+ if (combinePattern?.length) {
614
+ pattern = isSvg(domNode)
615
+ ? `//*[local-name()='${domNode.tagName}' and ${combinePattern.join(" and ")}]`
616
+ : `//${domNode.tagName}[${combinePattern.join(" and ")}]`;
617
+ return pattern;
618
+ }
619
+ }
620
+ };
621
+ const getAttributeCombinationXpath = (domNode, docmt, uniqueAttributes, isTarget) => {
622
+ try {
623
+ const xpathAttributes = [];
624
+ if (uniqueAttributes.length > 1) {
625
+ for (const attrName of uniqueAttributes) {
626
+ if (checkBlockedAttributes(attrName, domNode, isTarget)) {
627
+ const attrValue = attrName.nodeValue;
628
+ if (!reWhiteSpace$1.test(attrValue)) {
629
+ xpathAttributes.push(`normalize-space(@${attrName.nodeName})="${attrValue}"`);
630
+ }
631
+ else if (attrName.nodeName === "class") {
632
+ xpathAttributes.push(`contains(@${attrName.nodeName},"${attrValue}")`);
633
+ }
634
+ else {
635
+ xpathAttributes.push(`@${attrName.nodeName}="${attrValue}"`);
636
+ }
637
+ const xpathe = isSvg(domNode)
638
+ ? `//*[local-name()='${domNode.tagName}' and ${xpathAttributes.join(" and ")}]`
639
+ : `//${domNode.tagName}[${xpathAttributes.join(" and ")}]`;
640
+ let othersWithAttr;
641
+ // If the XPath does not parse, move to the next unique attribute
642
+ try {
643
+ othersWithAttr = getCountOfXPath(xpathe, domNode, docmt);
644
+ }
645
+ catch (ign) {
646
+ continue;
647
+ }
648
+ if (othersWithAttr === 1 && !xpathe.includes("and")) {
649
+ return "";
650
+ }
651
+ // If the attribute isn't actually unique, get it's index too
652
+ if (othersWithAttr === 1 && xpathe.includes("and")) {
653
+ return xpathe;
654
+ }
655
+ }
656
+ }
657
+ }
658
+ }
659
+ catch (error) {
660
+ // If there's an unexpected exception, abort and don't get an XPath
661
+ console.log(`'${JSON.stringify(error, null, 2)}'`);
662
+ }
663
+ };
664
+ const intermediateXpathStep = (targetElemt, attr, isTarget) => {
665
+ let isSvgElement = isSvg(targetElemt);
666
+ let expression = "";
667
+ if (checkBlockedAttributes(attr, targetElemt, isTarget)) {
668
+ let attrValue = attr.value;
669
+ attrValue = attrValue.replace("removePointers", "");
670
+ const elementName = attr.name;
671
+ if (!reWhiteSpace$1.test(attrValue)) {
672
+ expression = isSvgElement
673
+ ? `*[local-name()='${targetElemt.tagName}' and normalize-space(@${elementName})=${escapeCharacters(attrValue)}]`
674
+ : `${targetElemt.tagName || "*"}[normalize-space(@${elementName})=${escapeCharacters(attrValue)}]`;
675
+ }
676
+ else {
677
+ expression = isSvgElement
678
+ ? `*[local-name()='${targetElemt.tagName}' and @${elementName}=${escapeCharacters(attrValue)}]`
679
+ : `${targetElemt.tagName || "*"}[@${elementName}=${escapeCharacters(attrValue)}]`;
680
+ }
681
+ }
682
+ return expression;
683
+ };
684
+ const getFilteredTextXPath = (node, docmt) => {
685
+ if (!node.textContent)
686
+ return "";
687
+ const filteredText = getFilteredText(node);
688
+ let xpathe;
689
+ if (!reWhiteSpace$1.test(filteredText)) {
690
+ xpathe = isSvg(node)
691
+ ? `//*[local-name()='${node.tagName}' and normalize-space(.)=${escapeCharacters(filteredText)}]`
692
+ : `//${node.tagName || "*"}[normalize-space(.)=${escapeCharacters(filteredText)}]`;
693
+ }
694
+ else {
695
+ xpathe = isSvg(node)
696
+ ? `//*[local-name()='${node.tagName}' and .=${escapeCharacters(filteredText)}]`
697
+ : `//${node.tagName || "*"}[.=${escapeCharacters(filteredText)}]`;
698
+ }
699
+ return xpathe;
700
+ };
701
+ const getTextXpathFunction = (domNode) => {
702
+ const trimmedText = getTextContent(domNode)?.trim();
703
+ const filteredText = trimmedText
704
+ ? escapeCharacters(deleteGarbageFromInnerText(trimmedText))
705
+ : trimmedText;
706
+ if (filteredText) {
707
+ if (filteredText !== `'${trimmedText}'`) {
708
+ return `contains(.,${filteredText})`;
709
+ }
710
+ return `normalize-space(.)='${trimmedText}'`;
711
+ }
712
+ };
713
+ const getXpathString = (node, attrName, attrValue) => {
714
+ const reWhiteSpace = new RegExp(/^[\S]+( [\S]+)*$/gi);
715
+ let xpathe = "";
716
+ if (attrValue) {
717
+ if (!reWhiteSpace.test(attrValue)) {
718
+ xpathe = isSvg(node)
719
+ ? `//*[local-name()='${node.tagName}' and contains(@${attrName},${escapeCharacters(attrValue)})]`
720
+ : `//${node.tagName || "*"}[contains(@${attrName},${escapeCharacters(attrValue)})]`;
721
+ }
722
+ else if (attrName === "class") {
723
+ xpathe = isSvg(node)
724
+ ? `//*[local-name()='${node.tagName}' and contains(@${attrName},${escapeCharacters(attrValue)})]`
725
+ : `//${node.tagName || "*"}[contains(@${attrName},${escapeCharacters(attrValue)})]`;
726
+ }
727
+ else {
728
+ xpathe = isSvg(node)
729
+ ? `//*[local-name()='${node.tagName}' and @${attrName}=${escapeCharacters(attrValue)}]`
730
+ : `//${node.tagName || "*"}[@${attrName}=${escapeCharacters(attrValue)}]`;
731
+ }
732
+ }
733
+ return xpathe;
734
+ };
735
+ const replaceActualAttributes = (str, element) => {
736
+ if (str) {
737
+ return str.replace(/\bdisabled\b/gi, "flndisabled");
738
+ }
739
+ return str;
740
+ };
741
+ const addAttributeSplitCombineXpaths = (attributes, targetElemt, docmt, isTarget) => {
742
+ const attributesArray = Array.prototype.slice.call(attributes);
743
+ const xpaths = [];
744
+ try {
745
+ attributesArray.map((element) => {
746
+ if (checkBlockedAttributes(element, targetElemt, isTarget)) {
747
+ const xpth = getCombinationXpath(element, targetElemt);
748
+ if (xpth) {
749
+ xpaths.push({
750
+ key: `split xpath by ${element.name}`,
751
+ value: xpth,
752
+ });
753
+ }
754
+ }
755
+ });
756
+ }
757
+ catch (error) {
758
+ console.log(error);
759
+ }
760
+ return xpaths;
761
+ };
762
+ const getReferenceElementsXpath = (domNode, docmt, isTarget) => {
763
+ let nodeXpath1;
764
+ const xpaths1 = [];
765
+ if (domNode.textContent &&
766
+ (!isTarget || (isTarget && !isNumberExist(domNode.textContent)))) {
767
+ if (!reWhiteSpace$1.test(domNode.textContent)) {
768
+ nodeXpath1 = isSvg(domNode)
769
+ ? `*[local-name()='${domNode.tagName}' and ${getTextXpathFunction(domNode)})]`
770
+ : `${domNode.tagName}[${getTextXpathFunction(domNode)}]`;
771
+ if (nodeXpath1) {
772
+ xpaths1.push({ key: "getReferenceElementsXpath", value: nodeXpath1 });
773
+ }
774
+ }
775
+ else {
776
+ nodeXpath1 = isSvg(domNode)
777
+ ? `*[local-name()='${domNode.tagName}' and .=${escapeCharacters(getTextContent(domNode))}]`
778
+ : `${domNode.tagName}[.=${escapeCharacters(getTextContent(domNode))}]`;
779
+ if (nodeXpath1) {
780
+ xpaths1.push({ key: "getReferenceElementsXpath", value: nodeXpath1 });
781
+ }
782
+ }
783
+ }
784
+ if (domNode.attributes) {
785
+ for (const attrName of domNode.attributes) {
786
+ if (checkBlockedAttributes(attrName, domNode, isTarget)) {
787
+ let attrValue = attrName.nodeValue;
788
+ if (attrValue) {
789
+ attrValue = attrValue.replace("removePointers", "");
790
+ const elementName = attrName.name;
791
+ if (elementName === "class") {
792
+ nodeXpath1 = isSvg(domNode)
793
+ ? `*[local-name()='${domNode.tagName}' and contains(@${elementName},${escapeCharacters(attrValue)})]`
794
+ : `${domNode.tagName}[contains(@${elementName},${escapeCharacters(attrValue)})]`;
795
+ }
796
+ else {
797
+ nodeXpath1 = isSvg(domNode)
798
+ ? `*[local-name()='${domNode.tagName}' and @${elementName}=${escapeCharacters(attrValue)}]`
799
+ : `${domNode.tagName}[@${elementName}=${escapeCharacters(attrValue)}]`;
800
+ }
801
+ if (nodeXpath1) {
802
+ xpaths1.push({
803
+ key: "getReferenceElementsXpath",
804
+ value: nodeXpath1,
805
+ });
806
+ }
807
+ }
808
+ }
809
+ }
810
+ }
811
+ if (!xpaths1?.length) {
812
+ const attributesArray = Array.prototype.slice.call(domNode.attributes);
813
+ if (attributesArray?.length > 1) {
814
+ const combinationXpath = getAttributeCombinationXpath(domNode, docmt, Array.prototype.slice.call(domNode.attributes), isTarget);
815
+ if (combinationXpath) {
816
+ xpaths1.push({
817
+ key: "getReferenceElementsXpath",
818
+ value: combinationXpath,
819
+ });
820
+ }
821
+ }
822
+ }
823
+ if (!xpaths1?.length) {
824
+ const combinePattern = [];
825
+ let pattern;
826
+ const tag = isSvg(domNode);
827
+ if (domNode.textContent && isTarget && isNumberExist(domNode.textContent)) {
828
+ const contentRes = [...new Set(domNode.textContent.match(/([^0-9]+)/g))];
829
+ if (contentRes?.length) {
830
+ for (let i = 0; i < contentRes?.length; i++) {
831
+ if (contentRes[i] &&
832
+ replaceWhiteSpaces(contentRes[i].trim())?.length > 1) {
833
+ if (!reWhiteSpace$1.test(contentRes[i])) {
834
+ combinePattern.push(`contains(.,${escapeCharacters(replaceWhiteSpaces(contentRes[i])).trim()})`);
835
+ }
836
+ else {
837
+ combinePattern.push(`contains(.,${escapeCharacters(contentRes[i]).trim()})`);
838
+ }
839
+ }
840
+ }
841
+ }
842
+ if (combinePattern?.length) {
843
+ if (tag) {
844
+ pattern = `//*[local-name()='${tag}' and ${combinePattern.join(" and ")}]`;
845
+ }
846
+ else {
847
+ pattern = `//${tag}[${combinePattern.join(" and ")}]`;
848
+ }
849
+ if (pattern)
850
+ xpaths1.push({ key: "getReferenceElementsXpath", value: pattern });
851
+ }
852
+ }
853
+ }
854
+ if (!xpaths1?.length) {
855
+ const xpaths = addAttributeSplitCombineXpaths(domNode.attributes, domNode, docmt, isTarget);
856
+ if (xpaths?.length) {
857
+ xpaths1.concat(xpaths);
858
+ }
859
+ }
860
+ return xpaths1;
861
+ };
862
+ function parseXml(xmlStr) {
863
+ if (window.DOMParser) {
864
+ return new window.DOMParser().parseFromString(xmlStr, "text/xml");
865
+ }
866
+ return null;
867
+ }
868
+ const normalizeXPath = (xpath) => {
869
+ // Replace text() = "value" or text()='value'
870
+ xpath = xpath.replace(/text\(\)\s*=\s*(['"])(.*?)\1/g, "normalize-space(.)=$1$2$1");
871
+ // Replace . = "value" or .='value'
872
+ xpath = xpath.replace(/\.\s*=\s*(['"])(.*?)\1/g, "normalize-space(.)=$1$2$1");
873
+ return xpath;
874
+ };
875
+ const findMatchingParenthesis = (text, openPos) => {
876
+ let closePos = openPos;
877
+ let counter = 1;
878
+ while (counter > 0) {
879
+ const c = text[++closePos];
880
+ if (c == "(") {
881
+ counter++;
882
+ }
883
+ else if (c == ")") {
884
+ counter--;
885
+ }
886
+ }
887
+ return closePos;
888
+ };
889
+ const xpathUtils = {
890
+ parseXml,
891
+ getReferenceElementsXpath,
892
+ getAbsoluteXPath,
893
+ getRelativeXPath,
894
+ getCombinationXpath,
895
+ getAttributeCombinationXpath,
896
+ getElementFromXpath,
897
+ isSvg,
898
+ findXpathWithIndex,
899
+ isNumberExist,
900
+ getTextContent,
901
+ getCountOfXPath,
902
+ normalizeXPath,
903
+ getShadowRoot,
904
+ escapeCharacters,
905
+ removeParenthesis,
906
+ checkBlockedAttributes,
907
+ getRelationship,
908
+ findMatchingParenthesis,
909
+ deleteGarbageFromInnerText,
910
+ replaceTempAttributes,
911
+ createObserver,
912
+ startObserver,
913
+ stopObserver,
914
+ modifiedElementAttributes: modifiedElementAttributes$1,
915
+ };
916
+
917
+ let xpathData$1 = [];
918
+ let xpathDataWithIndex$1 = [];
919
+ let referenceElementMode = false;
920
+ let xpathCache = new Map();
921
+ let cache = new Map();
922
+ const parentXpathCache = new Map(); // Cache for parent XPaths
923
+ const checkRelativeXpathRelation = (nodeXpath1, nodeXpath2, targetElemt, docmt, isIndex, relationType) => {
924
+ if (nodeXpath1 && !referenceElementMode) {
925
+ let xpaths;
926
+ if (relationType === "parent") {
927
+ xpaths = [
928
+ // `${nodeXpath1}/descendant::${nodeXpath2}`,
929
+ `${nodeXpath1}/descendant-or-self::${nodeXpath2}`,
930
+ `${nodeXpath1}/following::${nodeXpath2}`,
931
+ ];
932
+ }
933
+ else {
934
+ xpaths = [
935
+ // `${nodeXpath1}/descendant::${nodeXpath2}`,
936
+ `${nodeXpath1}/ancestor-or-self::${nodeXpath2}`,
937
+ `${nodeXpath1}/preceding::${nodeXpath2}`,
938
+ ];
939
+ }
940
+ // Iterate through XPath patterns
941
+ for (const xpath of xpaths) {
942
+ // Check if result is already cached to avoid recomputation
943
+ if (!xpathCache?.get(xpath)) {
944
+ // Compute and store result in cache
945
+ xpathCache.set(xpath, getCountOfXPath(xpath, targetElemt, docmt));
946
+ }
947
+ const count = xpathCache?.get(xpath);
948
+ // Short-circuit: Return the first valid XPath result found
949
+ if (count === 1) {
950
+ return xpath;
951
+ }
952
+ if (count > 1) {
953
+ if (xpathDataWithIndex$1.length) {
954
+ if (count < xpathDataWithIndex$1[0].count) {
955
+ xpathDataWithIndex$1.pop();
956
+ xpathDataWithIndex$1.push({
957
+ key: `relative xpath by unique parent ${isIndex ? "index" : ""}`,
958
+ value: xpath,
959
+ count,
960
+ });
961
+ }
962
+ }
963
+ else {
964
+ xpathDataWithIndex$1.push({
965
+ key: `relative xpath by unique parent ${isIndex ? "index" : ""}`,
966
+ value: xpath,
967
+ count,
968
+ });
969
+ }
970
+ }
971
+ if (count > 1 && isIndex && !xpathData$1.length) {
972
+ // Try finding XPath with index if count is greater than 1
973
+ const indexedXpath = findXpathWithIndex(xpath, targetElemt, docmt, count);
974
+ // Cache the indexed XPath result
975
+ if (indexedXpath &&
976
+ getCountOfXPath(indexedXpath, targetElemt, docmt) === 1) {
977
+ xpathData$1.push({
978
+ key: `relative xpath by unique parent ${isIndex ? "index" : ""}`,
979
+ value: indexedXpath,
980
+ });
981
+ }
982
+ }
983
+ }
984
+ }
985
+ return null;
986
+ };
987
+ const getUniqueParentXpath = (domNode, docmt, node, isTarget, nodeXpath, isIndex) => {
988
+ try {
989
+ if (parentXpathCache.has(domNode)) {
990
+ return parentXpathCache.get(domNode);
991
+ }
992
+ // Direct XPath construction without loops
993
+ const xpathParts = [];
994
+ let currentNode = domNode;
995
+ while (currentNode && currentNode.nodeType === 1) {
996
+ const hasUniqueAttr = false;
997
+ for (const attrName of currentNode.attributes) {
998
+ if (checkBlockedAttributes(attrName, currentNode, isTarget)) {
999
+ let attrValue = attrName.nodeValue;
1000
+ attrValue = attrValue?.replace("removePointers", "") ?? "";
1001
+ const elementName = attrName.name;
1002
+ const xpathe = getXpathString(currentNode, elementName, attrValue);
1003
+ let othersWithAttr;
1004
+ // If the XPath does not parse, move to the next unique attribute
1005
+ try {
1006
+ othersWithAttr = checkRelativeXpathRelation(xpathe, nodeXpath, node, docmt, isIndex, "parent");
1007
+ }
1008
+ catch (ign) {
1009
+ continue;
1010
+ }
1011
+ // If the attribute isn't actually unique, get it's index too
1012
+ if (othersWithAttr) {
1013
+ return othersWithAttr;
1014
+ }
1015
+ }
1016
+ }
1017
+ if (currentNode.textContent && !currentNode.textContent) {
1018
+ if (!isTarget ||
1019
+ (isTarget && !isNumberExist(currentNode.textContent))) {
1020
+ let xpathe;
1021
+ if (!reWhiteSpace$1.test(currentNode.textContent)) {
1022
+ xpathe = isSvg(currentNode)
1023
+ ? `//*[local-name()='${currentNode.tagName}' and normalize-space(.)=${escapeCharacters(getFilteredText(currentNode))}]`
1024
+ : `//${currentNode.tagName || "*"}[normalize-space(.)=${escapeCharacters(getFilteredText(currentNode))}]`;
1025
+ }
1026
+ else {
1027
+ xpathe = isSvg(currentNode)
1028
+ ? `//*[local-name()='${currentNode.tagName}' and .=${escapeCharacters(getFilteredText(currentNode))}]`
1029
+ : `//${currentNode.tagName || "*"}[.=${escapeCharacters(getFilteredText(currentNode))}]`;
1030
+ }
1031
+ const othersWithAttr = checkRelativeXpathRelation(xpathe, nodeXpath, node, docmt, isIndex, "parent");
1032
+ if (othersWithAttr) {
1033
+ return othersWithAttr;
1034
+ }
1035
+ }
1036
+ else {
1037
+ const combinePattern = [];
1038
+ const contentRes = [
1039
+ ...new Set(getFilteredText(currentNode).match(/([^0-9]+)/g)),
1040
+ ];
1041
+ const reWhiteSpace = new RegExp(/^[\S]+( [\S]+)*$/gi);
1042
+ if (contentRes?.length) {
1043
+ for (let i = 0; i < contentRes?.length; i++) {
1044
+ if (contentRes[i] && replaceWhiteSpaces(contentRes[i].trim())) {
1045
+ if (!reWhiteSpace.test(contentRes[i])) {
1046
+ combinePattern.push(`contains(.,${escapeCharacters(replaceWhiteSpaces(contentRes[i])).trim()})`);
1047
+ }
1048
+ else {
1049
+ combinePattern.push(`contains(.,${escapeCharacters(contentRes[i].trim()).trim()})`);
1050
+ }
1051
+ }
1052
+ }
1053
+ }
1054
+ if (combinePattern?.length) {
1055
+ const xpathe = isSvg(currentNode)
1056
+ ? `//*[local-name()='${currentNode.tagName}' and ${combinePattern.join(" and ")}]`
1057
+ : `//${currentNode.tagName || "*"}[${combinePattern.join(" and ")}]`;
1058
+ const othersWithAttr = checkRelativeXpathRelation(xpathe, nodeXpath, node, docmt, isIndex, "parent");
1059
+ if (othersWithAttr) {
1060
+ return othersWithAttr;
1061
+ }
1062
+ }
1063
+ }
1064
+ }
1065
+ // Construct the XPath based on the tag name
1066
+ if (!hasUniqueAttr) {
1067
+ const xpathe = isSvg(currentNode)
1068
+ ? `/*[local-name()='${currentNode.tagName}']`
1069
+ : `/${currentNode.tagName}`;
1070
+ xpathParts.unshift(xpathe);
1071
+ }
1072
+ // Move to the parent node for the next iteration
1073
+ currentNode = currentNode.parentElement;
1074
+ }
1075
+ // Final constructed XPath
1076
+ const finalXPath = xpathParts.join("");
1077
+ let count = getCountOfXPath(finalXPath, domNode, docmt);
1078
+ if (count === 1) {
1079
+ parentXpathCache.set(domNode, finalXPath); // Cache final result
1080
+ return finalXPath;
1081
+ }
1082
+ }
1083
+ catch (error) {
1084
+ console.error(error);
1085
+ return null;
1086
+ }
1087
+ };
1088
+ const getParentRelativeXpath = (domNode, docmt, node, isTarget) => {
1089
+ const cache = new Map(); // Cache to store computed results
1090
+ if (cache.has(domNode)) {
1091
+ return cache.get(domNode); // Return cached result if available
1092
+ }
1093
+ const xpathParts = []; // Initialize an array to hold parts of the XPath
1094
+ let currentNode = domNode; // Start with the provided DOM node
1095
+ try {
1096
+ while (currentNode && currentNode.nodeType === 1) {
1097
+ // BASE CASE #1: If this isn't an element, we're above the root, return empty string
1098
+ if (!currentNode.tagName) {
1099
+ return "";
1100
+ }
1101
+ // BASE CASE #2: Check for unique attributes
1102
+ let uniqueAttrFound = false;
1103
+ for (const attr of currentNode.attributes) {
1104
+ if (checkBlockedAttributes(attr, currentNode, isTarget)) {
1105
+ let attrValue = attr.nodeValue;
1106
+ attrValue = attrValue?.replace("removePointers", "") ?? "";
1107
+ const elementName = attr.name;
1108
+ const xpathe = getXpathString(currentNode, elementName, attrValue);
1109
+ let othersWithAttr;
1110
+ // If the XPath does not parse, move to the next unique attribute
1111
+ try {
1112
+ othersWithAttr = getCountOfXPath(xpathe, currentNode, docmt);
1113
+ }
1114
+ catch (ign) {
1115
+ continue;
1116
+ }
1117
+ // If the attribute is unique, return its XPath
1118
+ if (othersWithAttr === 1) {
1119
+ xpathParts.unshift(xpathe);
1120
+ uniqueAttrFound = true; // Mark that we found at least one unique attribute
1121
+ break;
1122
+ }
1123
+ }
1124
+ }
1125
+ // If no unique attributes, check for text content
1126
+ if (!uniqueAttrFound && currentNode.textContent && !node.textContent) {
1127
+ const textXPath = getFilteredTextXPath(currentNode, docmt);
1128
+ if (textXPath) {
1129
+ const othersWithAttr = getCountOfXPath(textXPath, currentNode, docmt);
1130
+ if (othersWithAttr === 1) {
1131
+ uniqueAttrFound = true; // Mark that we found at least one unique attribute
1132
+ xpathParts.unshift(textXPath);
1133
+ break;
1134
+ }
1135
+ }
1136
+ }
1137
+ if (!uniqueAttrFound) {
1138
+ // Construct the XPath based on the tag name
1139
+ const xpathe = isSvg(currentNode)
1140
+ ? `/*[local-name()='${currentNode.tagName}']`
1141
+ : `/${currentNode.tagName}`;
1142
+ // Prepend the current XPath part to the array
1143
+ xpathParts.unshift(xpathe);
1144
+ }
1145
+ else {
1146
+ break;
1147
+ }
1148
+ // Move to the parent node for the next iteration
1149
+ currentNode = currentNode.parentElement;
1150
+ }
1151
+ // Combine all parts into the final XPath
1152
+ const finalXpath = xpathParts.join("");
1153
+ cache.set(domNode, finalXpath); // Store result in cache
1154
+ return finalXpath;
1155
+ }
1156
+ catch (error) {
1157
+ console.log(error);
1158
+ return null;
1159
+ }
1160
+ };
1161
+ const getChildRelativeXpath = (domNode, docmt, node) => {
1162
+ const xpathParts = []; // Initialize an array to hold parts of the XPath.
1163
+ let currentNode;
1164
+ const st = [];
1165
+ if (domNode.firstElementChild != null &&
1166
+ domNode.firstElementChild.classList.contains("flntooltip")) {
1167
+ st.unshift(domNode.firstElementChild);
1168
+ }
1169
+ else if (domNode.nextElementSibling != null)
1170
+ st.unshift(domNode.nextElementSibling);
1171
+ for (let m = domNode.parentElement; m != null && m.nodeType === 1; m = m.parentElement) {
1172
+ if (m.nextElementSibling)
1173
+ st.unshift(m.nextElementSibling);
1174
+ }
1175
+ try {
1176
+ do {
1177
+ let uniqueAttrFound = false;
1178
+ for (currentNode = st.pop(); currentNode !== null;) {
1179
+ for (const attr of currentNode.attributes) {
1180
+ if (checkBlockedAttributes(attr, currentNode, true)) {
1181
+ let attrValue = attr.nodeValue;
1182
+ attrValue = attrValue?.replace("removePointers", "") ?? "";
1183
+ const elementName = attr.name;
1184
+ const xpathe = getXpathString(currentNode, elementName, attrValue);
1185
+ let othersWithAttr;
1186
+ // If the XPath does not parse, move to the next unique attribute
1187
+ try {
1188
+ othersWithAttr = getCountOfXPath(xpathe, currentNode, docmt);
1189
+ }
1190
+ catch (ign) {
1191
+ continue;
1192
+ }
1193
+ // If the attribute is unique, return its XPath
1194
+ if (othersWithAttr === 1) {
1195
+ uniqueAttrFound = true; // Mark that we found at least one unique attribute
1196
+ xpathParts.push(xpathe);
1197
+ break;
1198
+ }
1199
+ }
1200
+ }
1201
+ // If no unique attributes, check for text content
1202
+ if (!uniqueAttrFound && currentNode.textContent && !node.textContent) {
1203
+ const textXPath = getFilteredTextXPath(currentNode, docmt);
1204
+ if (textXPath) {
1205
+ const othersWithAttr = getCountOfXPath(textXPath, currentNode, docmt);
1206
+ if (othersWithAttr === 1) {
1207
+ uniqueAttrFound = true; // Mark that we found at least one unique attribute
1208
+ xpathParts.push(textXPath);
1209
+ break;
1210
+ }
1211
+ }
1212
+ }
1213
+ if (!uniqueAttrFound) {
1214
+ // Construct the XPath based on the tag name
1215
+ const xpathe = isSvg(currentNode)
1216
+ ? `/*[local-name()='${currentNode.tagName}']`
1217
+ : `/${currentNode.tagName}`;
1218
+ // Prepend the current XPath part to the array
1219
+ xpathParts.push(xpathe);
1220
+ if (currentNode.firstElementChild != null) {
1221
+ st.push(currentNode.nextElementSibling);
1222
+ currentNode = currentNode.firstElementChild;
1223
+ }
1224
+ else {
1225
+ currentNode = currentNode.nextElementSibling;
1226
+ }
1227
+ }
1228
+ else {
1229
+ break;
1230
+ }
1231
+ }
1232
+ } while (st.length > 0);
1233
+ // Combine all parts into the final XPath
1234
+ const finalXpath = xpathParts.join("");
1235
+ cache.set(domNode, finalXpath); // Store result in cache
1236
+ return finalXpath;
1237
+ }
1238
+ catch (error) {
1239
+ console.log(error);
1240
+ return null;
1241
+ }
1242
+ };
1243
+ const getSiblingRelativeXPath = (domNode, docmt, isTarget, nodeXpath) => {
1244
+ try {
1245
+ const markedSpan = document.querySelector(".flntooltip");
1246
+ for (let m = domNode.nextElementSibling; m !== null && m !== markedSpan; m = m.nextElementSibling) {
1247
+ processSibling(m, domNode, docmt, nodeXpath, "preceding-sibling", isTarget);
1248
+ }
1249
+ for (let n = domNode.previousElementSibling; n !== null && n !== markedSpan; n = n.previousElementSibling) {
1250
+ processSibling(n, domNode, docmt, nodeXpath, "following-sibling", isTarget);
1251
+ }
1252
+ }
1253
+ catch (error) {
1254
+ console.error("sibling error", error);
1255
+ return null;
1256
+ }
1257
+ };
1258
+ const processSibling = (sibling, domNode, docmt, nodeXpath, axis, isTarget) => {
1259
+ try {
1260
+ if (sibling.hasAttributes()) {
1261
+ for (const attr of sibling.attributes) {
1262
+ let xpathe = intermediateXpathStep(sibling, {
1263
+ name: attr.name,
1264
+ value: attr.value,
1265
+ }, isTarget);
1266
+ if (xpathe) {
1267
+ xpathe += `/${axis}::${nodeXpath}`;
1268
+ const count = getCountOfXPath(xpathe, sibling, docmt);
1269
+ if (count === 1) {
1270
+ xpathData$1.push({
1271
+ key: `xpath by ${axis}`,
1272
+ value: xpathe,
1273
+ });
1274
+ return;
1275
+ }
1276
+ else if (count > 1) {
1277
+ if (xpathDataWithIndex$1.length) {
1278
+ if (count < xpathDataWithIndex$1[0].count) {
1279
+ xpathDataWithIndex$1.pop();
1280
+ xpathDataWithIndex$1.push({
1281
+ key: `relative xpath by ${axis}`,
1282
+ value: xpathe,
1283
+ count,
1284
+ });
1285
+ }
1286
+ }
1287
+ else {
1288
+ xpathDataWithIndex$1.push({
1289
+ key: `relative xpath by ${axis}`,
1290
+ value: xpathe,
1291
+ count,
1292
+ });
1293
+ }
1294
+ }
1295
+ }
1296
+ }
1297
+ }
1298
+ if (!isTarget) {
1299
+ let xpathe;
1300
+ xpathe = intermediateXpathStep(sibling, {
1301
+ name: "text",
1302
+ value: sibling.textContent,
1303
+ }, isTarget);
1304
+ if (xpathe) {
1305
+ const count = getCountOfXPath(xpathe, sibling, docmt);
1306
+ if (count === 1) {
1307
+ xpathData$1.push({
1308
+ key: `xpath by ${axis}`,
1309
+ value: xpathe,
1310
+ });
1311
+ return;
1312
+ }
1313
+ else if (count > 1) {
1314
+ if (xpathDataWithIndex$1.length) {
1315
+ if (count < xpathDataWithIndex$1[0].count) {
1316
+ xpathDataWithIndex$1.pop();
1317
+ xpathDataWithIndex$1.push({
1318
+ key: `relative xpath by ${axis}`,
1319
+ value: xpathe,
1320
+ count,
1321
+ });
1322
+ }
1323
+ }
1324
+ else {
1325
+ xpathDataWithIndex$1.push({
1326
+ key: `relative xpath by ${axis}`,
1327
+ value: xpathe,
1328
+ count,
1329
+ });
1330
+ }
1331
+ }
1332
+ }
1333
+ }
1334
+ }
1335
+ catch (error) {
1336
+ console.log(`${axis} xpath-error`, error);
1337
+ }
1338
+ };
1339
+ function getXPathUsingAttributeAndText(attributes, targetElemt, docmt, isTarget) {
1340
+ const { tagName } = targetElemt;
1341
+ const textContent = targetElemt.textContent.trim();
1342
+ for (const attrName of attributes) {
1343
+ if (checkBlockedAttributes(attrName, targetElemt, isTarget)) {
1344
+ let attrValue = attrName.nodeValue;
1345
+ attrValue = attrValue?.replace("removePointers", "") ?? "";
1346
+ const elementName = attrName.name;
1347
+ const xpath = `//${tagName}[@${elementName}='${attrValue}' and text()='${textContent}']`;
1348
+ if (xpath) {
1349
+ const count = getCountOfXPath(xpath, targetElemt, docmt);
1350
+ if (count == 1) {
1351
+ return xpath;
1352
+ }
1353
+ }
1354
+ }
1355
+ }
1356
+ }
1357
+ const addRelativeXpaths = (targetElemt, docmt, isIndex, isTarget, attribute) => {
1358
+ try {
1359
+ let nodeXpath = [];
1360
+ let relativeXpath, relativeChildXpath;
1361
+ if (!xpathData$1.length && isIndex) {
1362
+ if (xpathDataWithIndex$1.length) {
1363
+ const xpathWithIndex = findXpathWithIndex(xpathDataWithIndex$1[0].value, targetElemt, docmt, xpathDataWithIndex$1[0].count);
1364
+ if (xpathWithIndex) {
1365
+ xpathData$1.push({
1366
+ key: xpathDataWithIndex$1[0].key,
1367
+ value: xpathWithIndex,
1368
+ });
1369
+ xpathDataWithIndex$1.pop();
1370
+ }
1371
+ }
1372
+ }
1373
+ console.log(attribute);
1374
+ if (!xpathData$1.length) {
1375
+ if (targetElemt.attributes) {
1376
+ for (const attrName of attribute) {
1377
+ let expression = intermediateXpathStep(targetElemt, {
1378
+ name: attrName.name,
1379
+ value: attrName.value,
1380
+ }, isTarget);
1381
+ console.log(expression);
1382
+ if (expression) {
1383
+ nodeXpath.push(expression);
1384
+ }
1385
+ }
1386
+ }
1387
+ if (targetElemt.textContent) {
1388
+ let expression = intermediateXpathStep(targetElemt, {
1389
+ name: "text",
1390
+ value: targetElemt.textContent,
1391
+ }, isTarget);
1392
+ console.log(expression);
1393
+ if (expression) {
1394
+ nodeXpath.push(expression);
1395
+ }
1396
+ }
1397
+ if (nodeXpath?.length) {
1398
+ for (let i = 0; i < nodeXpath.length; i++) {
1399
+ if (!xpathData$1.length) {
1400
+ getSiblingRelativeXPath(targetElemt, docmt, isTarget, nodeXpath[i]);
1401
+ if (!xpathData$1.length) {
1402
+ if (!relativeXpath) {
1403
+ relativeXpath = getParentRelativeXpath(targetElemt.parentElement, docmt, targetElemt, isTarget);
1404
+ }
1405
+ console.log(relativeXpath);
1406
+ if (relativeXpath &&
1407
+ (relativeXpath.includes("@") ||
1408
+ relativeXpath.includes("text()") ||
1409
+ relativeXpath.includes(".=")) &&
1410
+ relativeXpath.match(/\//g)?.length - 2 < 5) {
1411
+ const fullRelativeXpath = relativeXpath + `/${nodeXpath[i]}`;
1412
+ const count = getCountOfXPath(fullRelativeXpath, targetElemt, docmt);
1413
+ if (count === 1) {
1414
+ xpathData$1.push({
1415
+ key: "relative xpath by relative parent",
1416
+ value: fullRelativeXpath,
1417
+ });
1418
+ }
1419
+ else if (count > 1 && isIndex) {
1420
+ const relativeXpathIndex = findXpathWithIndex(fullRelativeXpath, targetElemt, docmt, count);
1421
+ if (relativeXpathIndex &&
1422
+ getCountOfXPath(relativeXpathIndex, targetElemt, docmt) ===
1423
+ 1) {
1424
+ xpathData$1.push({
1425
+ key: `relative xpath by relative parent ${isIndex ? "index" : ""}`,
1426
+ value: relativeXpathIndex,
1427
+ });
1428
+ }
1429
+ }
1430
+ else if (count > 1) {
1431
+ if (xpathDataWithIndex$1.length) {
1432
+ if (count < xpathDataWithIndex$1[0].count) {
1433
+ xpathDataWithIndex$1.pop();
1434
+ xpathDataWithIndex$1.push({
1435
+ key: `relative xpath by relative parent ${isIndex ? "index" : ""}`,
1436
+ value: fullRelativeXpath,
1437
+ count,
1438
+ });
1439
+ }
1440
+ }
1441
+ else {
1442
+ xpathDataWithIndex$1.push({
1443
+ key: `relative xpath by relative parent ${isIndex ? "index" : ""}`,
1444
+ value: fullRelativeXpath,
1445
+ count,
1446
+ });
1447
+ }
1448
+ }
1449
+ }
1450
+ }
1451
+ if (!xpathData$1.length) {
1452
+ if (!relativeChildXpath) {
1453
+ relativeChildXpath = getChildRelativeXpath(targetElemt, docmt, targetElemt);
1454
+ }
1455
+ if (relativeChildXpath &&
1456
+ (relativeChildXpath.includes("@") ||
1457
+ relativeChildXpath.includes("text()") ||
1458
+ relativeChildXpath.includes(".="))) {
1459
+ const fullRelativeXpath = `/${nodeXpath[i] + relativeChildXpath.substring(1)}`;
1460
+ const count = getCountOfXPath(fullRelativeXpath, targetElemt, docmt);
1461
+ if (count === 1) {
1462
+ xpathData$1.push({
1463
+ key: "relative xpath by relative child",
1464
+ value: fullRelativeXpath,
1465
+ });
1466
+ }
1467
+ else if (count > 1 && isIndex) {
1468
+ const relativeXpathIndex = findXpathWithIndex(fullRelativeXpath, targetElemt, docmt, count);
1469
+ if (relativeXpathIndex &&
1470
+ getCountOfXPath(relativeXpathIndex, targetElemt, docmt) ===
1471
+ 1) {
1472
+ xpathData$1.push({
1473
+ key: `relative xpath by relative parent ${isIndex ? "index" : ""}`,
1474
+ value: relativeXpathIndex,
1475
+ });
1476
+ }
1477
+ }
1478
+ else if (count > 1) {
1479
+ if (xpathDataWithIndex$1.length) {
1480
+ if (count < xpathDataWithIndex$1[0].count) {
1481
+ xpathDataWithIndex$1.pop();
1482
+ xpathDataWithIndex$1.push({
1483
+ key: `relative xpath by relative child ${isIndex ? "index" : ""}`,
1484
+ value: fullRelativeXpath,
1485
+ count,
1486
+ });
1487
+ }
1488
+ }
1489
+ else {
1490
+ xpathDataWithIndex$1.push({
1491
+ key: `relative xpath by relative child ${isIndex ? "index" : ""}`,
1492
+ value: fullRelativeXpath,
1493
+ count,
1494
+ });
1495
+ }
1496
+ }
1497
+ }
1498
+ }
1499
+ if (xpathData$1?.length === 1 &&
1500
+ xpathData$1?.[0]?.value?.match(/\[([0-9]+)\]/gm)?.length > 3 &&
1501
+ !referenceElementMode) {
1502
+ if (targetElemt.textContent) {
1503
+ const txtXpath = getTextXPath(targetElemt, docmt, isIndex, false);
1504
+ if (txtXpath) {
1505
+ xpathData$1.unshift({
1506
+ key: `xpath by text${isIndex ? "index" : ""}`,
1507
+ value: txtXpath,
1508
+ });
1509
+ }
1510
+ }
1511
+ }
1512
+ if (!xpathData$1.length) {
1513
+ let tempRelativeXpath = getUniqueParentXpath(targetElemt.parentElement, docmt, targetElemt, isTarget, nodeXpath[i], isIndex);
1514
+ if (tempRelativeXpath) {
1515
+ xpathData$1.push({
1516
+ key: "xpath by unique parent",
1517
+ value: tempRelativeXpath,
1518
+ });
1519
+ }
1520
+ }
1521
+ }
1522
+ }
1523
+ }
1524
+ }
1525
+ return xpathData$1;
1526
+ }
1527
+ catch (error) {
1528
+ console.log(error);
1529
+ }
1530
+ };
1531
+ const attributesBasedXPath = (attr, targetElemt, docmt, isIndex, isTarget) => {
1532
+ let attrName;
1533
+ attrName = attr.name;
1534
+ let xpath = getPropertyXPath(targetElemt, docmt, `@${attrName}`, attr.value, isIndex, isTarget);
1535
+ return xpath;
1536
+ };
1537
+ const getUniqueClassName = (element, docmt, isIndex, isTarget) => {
1538
+ let value = element.className;
1539
+ if (typeof value !== "string") {
1540
+ value = "";
1541
+ }
1542
+ value = value?.replace("flndisabled", "disabled");
1543
+ value = value?.replace("removePointers", "");
1544
+ value = value?.trim();
1545
+ if (value) {
1546
+ return getPropertyXPath(element, docmt, `@class`, value, isIndex, isTarget);
1547
+ }
1548
+ };
1549
+ const getTextXPath = (element, docmt, isIndex, isTarget) => {
1550
+ if (element.textContent != "") {
1551
+ const text = getTextContent(element);
1552
+ if (text) {
1553
+ return getPropertyXPath(element, docmt, ".", text, isIndex, isTarget);
1554
+ }
1555
+ }
1556
+ };
1557
+ const addAllXPathAttributes = (attributes, targetElemt, docmt, isIndex, isTarget) => {
1558
+ const attributesArray = attributes;
1559
+ try {
1560
+ attributesArray.map((attr) => {
1561
+ if (!(attr.name === "className" || attr.name === "class")) {
1562
+ if (checkBlockedAttributes(attr, targetElemt, isTarget)) {
1563
+ const xpth = attributesBasedXPath(attr, targetElemt, docmt, isIndex, isTarget);
1564
+ if (xpth) {
1565
+ xpathData$1.push({
1566
+ key: `xpath by ${attr.name}${isIndex ? " index" : ""}`,
1567
+ value: xpth,
1568
+ });
1569
+ }
1570
+ }
1571
+ }
1572
+ });
1573
+ const txtXpath = getTextXPath(targetElemt, docmt, isIndex, isTarget);
1574
+ if (txtXpath) {
1575
+ xpathData$1.push({
1576
+ key: `xpath by text${isIndex ? " index" : ""}`,
1577
+ value: txtXpath,
1578
+ });
1579
+ }
1580
+ if (attributesArray.find((element) => element.name === "className") &&
1581
+ checkBlockedAttributes(attributesArray?.find((element) => element.name === "className"), targetElemt, isTarget)) {
1582
+ let xpath = getUniqueClassName(targetElemt, docmt, isIndex, isTarget);
1583
+ if (xpath) {
1584
+ xpathData$1.push({
1585
+ key: "xpath by class",
1586
+ value: xpath,
1587
+ });
1588
+ }
1589
+ }
1590
+ if (!xpathData$1.length) {
1591
+ const textAttribute = getXPathUsingAttributeAndText(attributes, targetElemt, docmt, isTarget);
1592
+ if (textAttribute)
1593
+ xpathData$1.push({
1594
+ key: "xpath by textAttribute",
1595
+ value: textAttribute,
1596
+ });
1597
+ }
1598
+ if (!xpathData$1.length && attributesArray.length > 1) {
1599
+ const combinationXpath = getAttributeCombinationXpath(targetElemt, docmt, attributesArray, isTarget);
1600
+ if (combinationXpath)
1601
+ xpathData$1.push({
1602
+ key: "xpath by combination",
1603
+ value: combinationXpath,
1604
+ });
1605
+ }
1606
+ }
1607
+ catch (error) {
1608
+ console.log(error);
1609
+ }
1610
+ };
1611
+ const parseDOM = (element, doc, isIndex, isTarget) => {
1612
+ xpathData$1 = [];
1613
+ console.log(element);
1614
+ const targetElemt = element;
1615
+ const docmt = targetElemt?.ownerDocument || doc;
1616
+ const tag = targetElemt.tagName;
1617
+ const { attributes } = targetElemt;
1618
+ addAllXPathAttributes([...attributes], targetElemt, docmt, isIndex, isTarget);
1619
+ {
1620
+ if (xpathData$1.length) {
1621
+ const len = xpathData$1.length;
1622
+ for (let i = 0; i < len; i++) {
1623
+ let xpth = xpathData$1[i].value;
1624
+ xpth = xpth.replace(tag, "*");
1625
+ const count = getCountOfXPath(xpth, element, docmt);
1626
+ if (count === 1) {
1627
+ xpathData$1.push({
1628
+ key: `${xpathData$1[i].key} regex`,
1629
+ value: xpth,
1630
+ });
1631
+ }
1632
+ }
1633
+ }
1634
+ }
1635
+ console.log(xpathData$1);
1636
+ if (!xpathData$1.length) {
1637
+ addRelativeXpaths(targetElemt, docmt, isIndex, isTarget, [...targetElemt.attributes]);
1638
+ }
1639
+ return xpathData$1;
1640
+ };
1641
+ const xpath = {
1642
+ parseDOM,
1643
+ getTextXPath,
1644
+ getUniqueClassName,
1645
+ attributesBasedXPath,
1646
+ addAllXPathAttributes,
1647
+ addRelativeXpaths,
1648
+ getXPathUsingAttributeAndText,
1649
+ getSiblingRelativeXPath,
1650
+ getChildRelativeXpath,
1651
+ getParentRelativeXpath,
1652
+ getUniqueParentXpath,
1653
+ checkRelativeXpathRelation,
1654
+ };
1655
+
1656
+ let xpathDataWithIndex = [];
1657
+ let xpathData = [];
1658
+ const reWhiteSpace = /^[\S]+( [\S]+)*$/gi;
1659
+ const findRelativeXpath = (element1, element2, docmt, xpaths1, xpaths2, isIndex) => {
1660
+ // debugger;
1661
+ const par1 = element1.parentElement;
1662
+ const par2 = element2.parentElement;
1663
+ let rel_xpath = [];
1664
+ let tempElement;
1665
+ findRoot(element1);
1666
+ let finalXpaths = [];
1667
+ if (isIndex) {
1668
+ if (xpathDataWithIndex.length) {
1669
+ const xpathWithIndex = findXpathWithIndex(xpathDataWithIndex[0].value, element2, element2.ownerDocument, xpathDataWithIndex[0].count);
1670
+ if (xpathWithIndex) {
1671
+ finalXpaths = finalXpaths.concat({
1672
+ key: `${xpathDataWithIndex[0]?.key
1673
+ ? xpathDataWithIndex[0]?.key
1674
+ : "xpath with "} index`,
1675
+ value: xpathWithIndex,
1676
+ });
1677
+ xpathDataWithIndex.pop();
1678
+ }
1679
+ }
1680
+ }
1681
+ if (!finalXpaths.length) {
1682
+ // both are same
1683
+ if (element1.isSameNode(element2)) {
1684
+ // rel_xpath = xpath1 + "/self::" + element1.tagName;
1685
+ rel_xpath = getXpathRelationExpression(element1, element2, "self", xpaths1, xpaths2, isIndex);
1686
+ if (rel_xpath)
1687
+ finalXpaths = finalXpaths.concat(rel_xpath);
1688
+ }
1689
+ // parent
1690
+ tempElement = element1.parentElement;
1691
+ if (tempElement === element2) {
1692
+ rel_xpath = getXpathRelationExpression(element1, element2, "parent", xpaths1, xpaths2, isIndex);
1693
+ if (rel_xpath)
1694
+ finalXpaths = finalXpaths.concat(rel_xpath);
1695
+ }
1696
+ // ancestor
1697
+ tempElement = element1.parentElement;
1698
+ while (tempElement !== null) {
1699
+ if (tempElement === element2) {
1700
+ rel_xpath = getXpathRelationExpression(element1, element2, "ancestor", xpaths1, xpaths2, isIndex);
1701
+ if (rel_xpath) {
1702
+ finalXpaths = finalXpaths.concat(rel_xpath);
1703
+ break;
1704
+ }
1705
+ }
1706
+ tempElement = tempElement.parentNode;
1707
+ }
1708
+ // ancestor-or-self
1709
+ tempElement = element1;
1710
+ do {
1711
+ if (tempElement === element2) {
1712
+ rel_xpath = getXpathRelationExpression(element1, element2, "ancestor-or-self", xpaths1, xpaths2, isIndex);
1713
+ if (rel_xpath) {
1714
+ finalXpaths = finalXpaths.concat(rel_xpath);
1715
+ break;
1716
+ }
1717
+ }
1718
+ tempElement = tempElement.parentNode;
1719
+ } while (tempElement !== null);
1720
+ // both has same parent
1721
+ if (par1?.isSameNode(par2)) {
1722
+ for (let m = element1.nextElementSibling; m != null; m = m.nextElementSibling) {
1723
+ if (m != null && m.isSameNode(element2)) {
1724
+ rel_xpath = getXpathRelationExpression(element1, element2, "following-sibling", xpaths1, xpaths2, isIndex);
1725
+ if (rel_xpath) {
1726
+ finalXpaths = finalXpaths.concat(rel_xpath);
1727
+ break;
1728
+ }
1729
+ }
1730
+ }
1731
+ for (let n = element1.previousElementSibling; n != null; n = n.previousElementSibling) {
1732
+ if (n != null && n.isSameNode(element2)) {
1733
+ rel_xpath = getXpathRelationExpression(element1, element2, "preceding-sibling", xpaths1, xpaths2, isIndex);
1734
+ if (rel_xpath) {
1735
+ finalXpaths = finalXpaths.concat(rel_xpath);
1736
+ break;
1737
+ }
1738
+ }
1739
+ }
1740
+ }
1741
+ // child
1742
+ if (element1?.children?.length) {
1743
+ for (let m = element1.children[0]; m !== null; m = m?.nextElementSibling) {
1744
+ if (m === element2) {
1745
+ rel_xpath = getXpathRelationExpression(element1, element2, "child", xpaths1, xpaths2, isIndex);
1746
+ if (rel_xpath) {
1747
+ finalXpaths = finalXpaths.concat(rel_xpath);
1748
+ break;
1749
+ }
1750
+ }
1751
+ }
1752
+ }
1753
+ // following
1754
+ const relation = element1.compareDocumentPosition(element2);
1755
+ if (relation === 2) {
1756
+ rel_xpath = getXpathRelationExpression(element1, element2, "preceding", xpaths1, xpaths2, isIndex);
1757
+ }
1758
+ if (relation === 4) {
1759
+ rel_xpath = getXpathRelationExpression(element1, element2, "following", xpaths1, xpaths2, isIndex);
1760
+ }
1761
+ if (rel_xpath) {
1762
+ finalXpaths = finalXpaths.concat(rel_xpath);
1763
+ }
1764
+ const descendantXpath = getDescendantXpath([element1, element2], docmt, xpaths1, xpaths2, "descendant", isIndex);
1765
+ if (descendantXpath)
1766
+ finalXpaths = finalXpaths.concat(descendantXpath);
1767
+ const descendantSelfXpath = getDescendantXpath([element1, element2], docmt, xpaths1, xpaths2, "descedant-or-self", isIndex);
1768
+ if (descendantSelfXpath) {
1769
+ finalXpaths = finalXpaths.concat(descendantSelfXpath);
1770
+ }
1771
+ }
1772
+ if (finalXpaths.length) {
1773
+ if (finalXpaths.length > 1) {
1774
+ finalXpaths.sort(function (a, b) {
1775
+ return a.value.length - b.value.length;
1776
+ });
1777
+ }
1778
+ if (finalXpaths.filter((x) => !x.key?.includes("index"))?.length) {
1779
+ return [finalXpaths.filter((x) => !x.key?.includes("index"))[0]];
1780
+ }
1781
+ return [finalXpaths[0]];
1782
+ }
1783
+ };
1784
+ const descendantExpression = (refExpectElement, xpath2, relation, docmt, isIndex, expCommonParentXpathElements, step4, refCommonParentXpathElementLength) => {
1785
+ let finalExpectedElementXpath = "";
1786
+ if (xpath2.split(/\/(?=(?:[^']*\'[^\']*\')*[^\']*$)/g)?.length >=
1787
+ expCommonParentXpathElements.length) {
1788
+ const xpaths2Els = [];
1789
+ const xpath2Elements = xpath2.split(/\/(?=(?:[^']*\'[^\']*\')*[^\']*$)/g);
1790
+ for (let x = 1; x <= expCommonParentXpathElements.length; x++) {
1791
+ xpaths2Els.unshift(x === expCommonParentXpathElements.length
1792
+ ? expCommonParentXpathElements[expCommonParentXpathElements.length - x]
1793
+ : xpath2Elements[xpath2Elements.length - x]);
1794
+ }
1795
+ const traverseXpath = getTraverseXpathExpression(`${step4 +
1796
+ (refCommonParentXpathElementLength
1797
+ ? "]".repeat(refCommonParentXpathElementLength)
1798
+ : "")}`, xpaths2Els, refExpectElement[refExpectElement.length - 1], refExpectElement, docmt, relation, isIndex);
1799
+ if (traverseXpath) {
1800
+ return traverseXpath;
1801
+ }
1802
+ }
1803
+ else {
1804
+ finalExpectedElementXpath = `//${step4 +
1805
+ (refCommonParentXpathElementLength
1806
+ ? "]".repeat(refCommonParentXpathElementLength)
1807
+ : "")}/${relation}::${replaceActualAttributes(xpath2, refExpectElement[refExpectElement.length - 1])}`;
1808
+ let rel_count = getCountOfXPath(finalExpectedElementXpath, refExpectElement[refExpectElement.length - 1], docmt);
1809
+ if (rel_count === 1) {
1810
+ return [
1811
+ {
1812
+ key: `dynamic ${relation}`,
1813
+ value: replaceTempAttributes(finalExpectedElementXpath),
1814
+ },
1815
+ ];
1816
+ }
1817
+ if (rel_count > 1) {
1818
+ if (isIndex) {
1819
+ finalExpectedElementXpath = findXpathWithIndex(finalExpectedElementXpath, refExpectElement[refExpectElement.length - 1], docmt, rel_count);
1820
+ if (finalExpectedElementXpath) {
1821
+ rel_count = getCountOfXPath(finalExpectedElementXpath, refExpectElement[refExpectElement.length - 1], docmt);
1822
+ if (rel_count === 1) {
1823
+ return [
1824
+ {
1825
+ key: `dynamic ${relation} ${isIndex ? " index" : ""}`,
1826
+ value: replaceTempAttributes(finalExpectedElementXpath),
1827
+ },
1828
+ ];
1829
+ }
1830
+ }
1831
+ }
1832
+ }
1833
+ }
1834
+ };
1835
+ const getDescendantXpath = (refExpectElement, docmt, xpaths1, xpaths2, relation, isIndex) => {
1836
+ const refElement = refExpectElement[refExpectElement.length - 2];
1837
+ const expElement = refExpectElement[refExpectElement.length - 1];
1838
+ const expElementDocmnt = getShadowRoot(expElement) ?? expElement.ownerDocument;
1839
+ const refAbsoluteXpath = xpaths1.find((x) => x?.key?.includes("absolute"))?.value ||
1840
+ getAbsoluteXPath(refElement, refElement.ownerDocument);
1841
+ const refFullXpathElements = [];
1842
+ const refFullXpathElementsWithoutNumber = [];
1843
+ refAbsoluteXpath.split("/").map((x) => refFullXpathElements.push(x));
1844
+ refFullXpathElements.map((x) => refFullXpathElementsWithoutNumber.push(x.replace(/\[([0-9]+)\]/gm, "")));
1845
+ const expAbsoluteXpath = xpaths2.find((x) => x?.key?.includes("absolute"))?.value ||
1846
+ getAbsoluteXPath(expElement, expElement.ownerDocument);
1847
+ const expFullXpathElements = [];
1848
+ const expFullXpathElementsWithoutNumber = [];
1849
+ expAbsoluteXpath.split("/").map((x) => expFullXpathElements.push(x));
1850
+ expFullXpathElements.map((x) => expFullXpathElementsWithoutNumber.push(x.replace(/\[([0-9]+)\]/gm, "")));
1851
+ for (var parentElementNumber = 0; parentElementNumber < refFullXpathElements.length; parentElementNumber++) {
1852
+ if (refFullXpathElements[parentElementNumber] !=
1853
+ expFullXpathElements[parentElementNumber]) {
1854
+ break;
1855
+ }
1856
+ }
1857
+ const refCommonParentXpathElements = [];
1858
+ for (let i = parentElementNumber - 1; i < refFullXpathElements.length; i++) {
1859
+ if (refFullXpathElements[i]) {
1860
+ refCommonParentXpathElements.push(refFullXpathElementsWithoutNumber[i]);
1861
+ }
1862
+ }
1863
+ const expCommonParentXpathElements = [];
1864
+ for (let j = relation === "descendant" ? parentElementNumber : parentElementNumber - 1; j < expFullXpathElements.length; j++) {
1865
+ if (expFullXpathElements[j]) {
1866
+ if (expCommonParentXpathElements.length)
1867
+ expCommonParentXpathElements.push(expFullXpathElementsWithoutNumber[j]);
1868
+ else
1869
+ expCommonParentXpathElements.push(expFullXpathElementsWithoutNumber[j].replace(/\[([0-9]+)\]/gm, ""));
1870
+ }
1871
+ }
1872
+ xpathData = xpaths2;
1873
+ let nodeXpath2;
1874
+ if (refExpectElement[refExpectElement.length - 2].textContent) {
1875
+ if (!reWhiteSpace.test(refExpectElement[refExpectElement.length - 2].textContent)) {
1876
+ nodeXpath2 = isSvg(refExpectElement[refExpectElement.length - 2])
1877
+ ? `*[local-name()='${refExpectElement[refExpectElement.length - 2].tagName}' and ${getTextXpathFunction(refExpectElement[refExpectElement.length - 2])})]`
1878
+ : `${refExpectElement[refExpectElement.length - 2].tagName}[${getTextXpathFunction(refExpectElement[refExpectElement.length - 2])}]`;
1879
+ }
1880
+ else {
1881
+ nodeXpath2 = isSvg(refExpectElement[refExpectElement.length - 2])
1882
+ ? `*[local-name()='${refExpectElement[refExpectElement.length - 2].tagName}' and .=${escapeCharacters(getTextContent(refExpectElement[refExpectElement.length - 2]))}]`
1883
+ : `${refExpectElement[refExpectElement.length - 2].tagName}[.=${escapeCharacters(getTextContent(refExpectElement[refExpectElement.length - 2]))}]`;
1884
+ }
1885
+ refCommonParentXpathElements[refCommonParentXpathElements.length - 1] =
1886
+ nodeXpath2;
1887
+ const refCommonParentXpath = refCommonParentXpathElements.join("[");
1888
+ const refCommonParentXpathElementLength = refCommonParentXpathElements.length - 1;
1889
+ const step4 = refCommonParentXpath;
1890
+ for (let i = 0; i < xpathData.length; i++) {
1891
+ let xpath2;
1892
+ if (xpathData[i].value.startsWith("//")) {
1893
+ xpath2 = xpathData[i].value.substring(xpathData[i].value.indexOf("//") + 2);
1894
+ }
1895
+ else {
1896
+ xpath2 = xpathData[i].value; // No need to modify the value
1897
+ }
1898
+ if (xpath2) {
1899
+ return descendantExpression(refExpectElement, xpath2, relation, expElementDocmnt || docmt, isIndex, expCommonParentXpathElements, step4, refCommonParentXpathElementLength);
1900
+ }
1901
+ }
1902
+ }
1903
+ if (refExpectElement[refExpectElement.length - 2].attributes) {
1904
+ for (const attrName of refExpectElement[refExpectElement.length - 2]
1905
+ .attributes) {
1906
+ if (checkBlockedAttributes(attrName, refExpectElement[refExpectElement.length - 2], false)) {
1907
+ let attrValue = attrName.nodeValue;
1908
+ if (attrValue) {
1909
+ attrValue = attrValue.replace("removePointers", "");
1910
+ const elementName = attrName.name;
1911
+ nodeXpath2 = isSvg(refExpectElement[refExpectElement.length - 2])
1912
+ ? `*[local-name()='${refExpectElement[refExpectElement.length - 2].tagName}' and @${elementName}=${escapeCharacters(attrValue)}]`
1913
+ : `${refExpectElement[refExpectElement.length - 2].tagName}[@${elementName}=${escapeCharacters(attrValue)}]`;
1914
+ refCommonParentXpathElements[refCommonParentXpathElements.length - 1] = nodeXpath2;
1915
+ const refCommonParentXpath = refCommonParentXpathElements.join("[");
1916
+ const refCommonParentXpathElementLength = refCommonParentXpathElements.length - 1;
1917
+ const step4 = refCommonParentXpath;
1918
+ for (let i = 0; i < xpathData.length; i++) {
1919
+ let xpath2;
1920
+ if (xpathData[i].value.startsWith("//")) {
1921
+ xpath2 = xpathData[i].value.substring(xpathData[i].value.indexOf("//") + 2);
1922
+ }
1923
+ else {
1924
+ xpath2 = xpathData[i].value; // No need to modify the value
1925
+ }
1926
+ return descendantExpression(refExpectElement, xpath2, relation, expElementDocmnt || docmt, isIndex, expCommonParentXpathElements, step4, refCommonParentXpathElementLength);
1927
+ }
1928
+ }
1929
+ }
1930
+ }
1931
+ for (const attrName of refExpectElement[refExpectElement.length - 2]
1932
+ .attributes) {
1933
+ if (checkBlockedAttributes(attrName, refExpectElement[refExpectElement.length - 2], false)) {
1934
+ let attrValue = attrName.nodeValue;
1935
+ if (attrValue) {
1936
+ attrValue = attrValue.replace("removePointers", "");
1937
+ const combinationXpath = getCombinationXpath(attrName, refExpectElement[refExpectElement.length - 2]);
1938
+ if (combinationXpath) {
1939
+ if (combinationXpath.startsWith("//")) {
1940
+ nodeXpath2 = combinationXpath.substring(combinationXpath.indexOf("//") + 2);
1941
+ }
1942
+ else {
1943
+ nodeXpath2 = combinationXpath; // No need to modify the value
1944
+ }
1945
+ refCommonParentXpathElements[refCommonParentXpathElements.length - 1] = nodeXpath2;
1946
+ const refCommonParentXpath = refCommonParentXpathElements.join("[");
1947
+ const refCommonParentXpathElementLength = refCommonParentXpathElements.length - 1;
1948
+ const step4 = refCommonParentXpath;
1949
+ for (let i = 0; i < xpathData.length; i++) {
1950
+ let xpath2;
1951
+ if (xpathData[i].value.startsWith("//")) {
1952
+ xpath2 = xpathData[i].value.substring(xpathData[i].value.indexOf("//") + 2);
1953
+ }
1954
+ else {
1955
+ xpath2 = xpathData[i].value; // No need to modify the value
1956
+ }
1957
+ return descendantExpression(refExpectElement, xpath2, relation, expElementDocmnt || docmt, isIndex, expCommonParentXpathElements, step4, refCommonParentXpathElementLength);
1958
+ }
1959
+ }
1960
+ }
1961
+ }
1962
+ }
1963
+ }
1964
+ const refCommonParentXpath = refCommonParentXpathElements.join("[");
1965
+ const refCommonParentXpathElementLength = refCommonParentXpathElements.length - 1;
1966
+ const step4 = refCommonParentXpath;
1967
+ const traverseXpath = getTraverseXpathExpression(`${step4 +
1968
+ (refCommonParentXpathElementLength
1969
+ ? "]".repeat(refCommonParentXpathElementLength)
1970
+ : "")}`, expCommonParentXpathElements.reverse(), refExpectElement[refExpectElement.length - 1], refExpectElement, docmt, relation, isIndex);
1971
+ if (traverseXpath) {
1972
+ return traverseXpath;
1973
+ }
1974
+ };
1975
+ const getXpathRelationExpression = (element1, element2, relation, xpath1, xpath2, isIndex) => {
1976
+ let xpaths1;
1977
+ let xpaths2;
1978
+ console.log('getXpathRelationExpression', relation);
1979
+ const finalXpaths = [];
1980
+ try {
1981
+ xpaths1 = xpath1.filter((x) => !x?.key?.includes("absolute"));
1982
+ xpaths2 = xpath2.filter((x) => !x?.key?.includes("absolute"));
1983
+ for (let i = 0; i < xpaths1.length; i++) {
1984
+ for (let j = 0; j < xpaths2.length; j++) {
1985
+ let rel_xpath = `//${xpaths1[i].value.indexOf("//") !== 0
1986
+ ? replaceActualAttributes(xpaths1[i].value, element1)
1987
+ : replaceActualAttributes(xpaths1[i].value.substring(xpaths1[i].value.indexOf("//") + 2), element1)}/${relation}::${xpaths2[j].value.indexOf("//") !== 0
1988
+ ? replaceActualAttributes(xpaths2[j].value, element2)
1989
+ : replaceActualAttributes(xpaths2[j].value.substring(xpaths2[j].value.indexOf("//") + 2), element2)}`;
1990
+ console.log('getXpathRelationExpression', rel_xpath);
1991
+ const rel_count = getCountOfXPath(rel_xpath, element2, element2.ownerDocument);
1992
+ if (rel_count > 1) {
1993
+ if (isIndex) {
1994
+ rel_xpath = findXpathWithIndex(rel_xpath, element2, element2.ownerDocument, rel_count);
1995
+ if (rel_xpath) {
1996
+ finalXpaths.push({
1997
+ key: `dynamic ${relation}${isIndex ? " index" : ""}`,
1998
+ value: replaceTempAttributes(rel_xpath),
1999
+ });
2000
+ return finalXpaths;
2001
+ }
2002
+ }
2003
+ else if (rel_count > 1) {
2004
+ if (xpathDataWithIndex.length) {
2005
+ if (rel_count < xpathDataWithIndex[0].count) {
2006
+ xpathDataWithIndex.pop();
2007
+ xpathDataWithIndex.push({
2008
+ key: `relative xpath by relative child ${isIndex ? "index" : ""}`,
2009
+ value: rel_xpath,
2010
+ count: rel_count,
2011
+ });
2012
+ }
2013
+ }
2014
+ else {
2015
+ xpathDataWithIndex.push({
2016
+ key: `relative xpath by relative child ${isIndex ? "index" : ""}`,
2017
+ value: rel_xpath,
2018
+ count: rel_count,
2019
+ });
2020
+ }
2021
+ }
2022
+ }
2023
+ else if (rel_count === 1) {
2024
+ finalXpaths.push({
2025
+ key: `dynamic ${relation}`,
2026
+ value: replaceTempAttributes(rel_xpath),
2027
+ });
2028
+ return finalXpaths;
2029
+ }
2030
+ }
2031
+ }
2032
+ if (!finalXpaths.length) {
2033
+ for (let i = 0; i < xpaths1.length; i++) {
2034
+ for (let j = 0; j < xpaths2.length; j++) {
2035
+ const tempPath = `${xpaths2[j].value.indexOf("//") !== 0
2036
+ ? xpaths2[j].value
2037
+ : xpaths2[j].value.substring(xpaths2[j].value.indexOf("//") + 2)}`;
2038
+ const xpath2Elements = tempPath.split(/\/(?=(?:[^']*\'[^\']*\')*[^\']*$)/g);
2039
+ if (xpath2Elements.length > 1) {
2040
+ const traverseXpath = getTraverseXpathExpression(`${xpaths1[i].value.indexOf("//") !== 0
2041
+ ? replaceActualAttributes(xpaths1[i].value, element1)
2042
+ : replaceActualAttributes(xpaths1[i].value.substring(xpaths1[i].value.indexOf("//") + 2), element1)}`, xpath2Elements, element2, [element1, element2], element2.ownerDocument, relation, isIndex);
2043
+ console.log('getXpathRelationExpression traverseXpath', traverseXpath);
2044
+ if (traverseXpath) {
2045
+ finalXpaths.concat(traverseXpath);
2046
+ return finalXpaths;
2047
+ }
2048
+ }
2049
+ }
2050
+ }
2051
+ }
2052
+ }
2053
+ catch (error) {
2054
+ console.log(error);
2055
+ }
2056
+ return finalXpaths;
2057
+ };
2058
+ const getReferenceElementXpath = (element) => {
2059
+ let xpaths1 = [];
2060
+ xpaths1 = parseDOM(element, element.ownerDocument, false, false);
2061
+ if (!xpaths1?.length) {
2062
+ xpaths1 = parseDOM(element, element.ownerDocument, true, false);
2063
+ xpaths1 = xpaths1?.map((x) => x.value.charAt(0) == "(" &&
2064
+ findMatchingParenthesis(x.value, 0) + 1 === x.value.lastIndexOf("[")
2065
+ ? { key: "", value: removeParenthesis(x.value) }
2066
+ : { key: "", value: x.value });
2067
+ }
2068
+ else {
2069
+ let xpaths = parseDOM(element, element.ownerDocument, true, false);
2070
+ if (xpaths?.length) {
2071
+ xpaths = xpaths?.map((x) => x.value.charAt(0) == "(" &&
2072
+ findMatchingParenthesis(x.value, 0) + 1 === x.value.lastIndexOf("[")
2073
+ ? { key: "", value: removeParenthesis(x.value) }
2074
+ : { key: "", value: x.value });
2075
+ xpaths1 = xpaths1.concat(xpaths);
2076
+ }
2077
+ }
2078
+ if (!xpaths1?.length) {
2079
+ xpaths1 = [
2080
+ {
2081
+ key: "",
2082
+ value: getRelativeXPath(element, element.ownerDocument, false, false, [...element.attributes]),
2083
+ },
2084
+ ];
2085
+ }
2086
+ if (!xpaths1?.length) {
2087
+ xpaths1 = [
2088
+ {
2089
+ key: "",
2090
+ value: getRelativeXPath(element, element.ownerDocument, true, false, [...element.attributes]),
2091
+ },
2092
+ ];
2093
+ xpaths1 = xpaths1?.map((x) => x.value.charAt(0) == "(" &&
2094
+ findMatchingParenthesis(x.value, 0) + 1 === x.value.lastIndexOf("[")
2095
+ ? { key: "", value: removeParenthesis(x.value) }
2096
+ : { key: "", value: x.value });
2097
+ }
2098
+ if (!xpaths1?.length) {
2099
+ xpaths1 = getReferenceElementsXpath(element, element.ownerDocument, false);
2100
+ }
2101
+ else {
2102
+ const xpaths = getReferenceElementsXpath(element, element.ownerDocument, false);
2103
+ if (xpaths?.length) {
2104
+ xpaths1 = xpaths1.concat(xpaths);
2105
+ }
2106
+ }
2107
+ const referenceXpathElement = getAbsoluteXPath(element, element.ownerDocument);
2108
+ xpaths1 = xpaths1.filter((x) => x.value !== referenceXpathElement);
2109
+ xpaths1.push({
2110
+ key: "absolute xpath",
2111
+ value: referenceXpathElement.slice(1),
2112
+ });
2113
+ return xpaths1;
2114
+ };
2115
+ const getTraverseXpathExpression = (xpathe1, absoluteXpathElements, element2, refExpectElement, docmt, relation, isIndex) => {
2116
+ let finalExpectedElementXpath;
2117
+ {
2118
+ for (let x = 1; x <= absoluteXpathElements.length; x++) {
2119
+ const xpath2 = absoluteXpathElements
2120
+ .slice(absoluteXpathElements.length - x, absoluteXpathElements.length)
2121
+ .join("/");
2122
+ finalExpectedElementXpath = `//${xpathe1}/${relation}::${replaceActualAttributes(xpath2)}`;
2123
+ const rel_count = getCountOfXPath(finalExpectedElementXpath, element2, docmt);
2124
+ if (rel_count === 1) {
2125
+ return [
2126
+ {
2127
+ key: `dynamic ${relation}`,
2128
+ value: replaceTempAttributes(finalExpectedElementXpath),
2129
+ },
2130
+ ];
2131
+ }
2132
+ if (rel_count > 1) {
2133
+ if (isIndex) {
2134
+ finalExpectedElementXpath = findXpathWithIndex(finalExpectedElementXpath, refExpectElement[refExpectElement.length - 1], docmt, rel_count);
2135
+ if (finalExpectedElementXpath) {
2136
+ return [
2137
+ {
2138
+ key: `dynamic ${relation}${isIndex ? " index" : ""}`,
2139
+ value: replaceTempAttributes(finalExpectedElementXpath),
2140
+ },
2141
+ ];
2142
+ }
2143
+ }
2144
+ }
2145
+ }
2146
+ }
2147
+ };
2148
+ const referenceXpath = {
2149
+ findRelativeXpath,
2150
+ getDescendantXpath,
2151
+ getXpathRelationExpression,
2152
+ getTraverseXpathExpression,
2153
+ getReferenceElementXpath,
2154
+ };
2155
+
2156
+ const getElementFromShadowRoot = (element, selector) => {
2157
+ const shadowRoot = element.shadowRoot;
2158
+ if (shadowRoot && !selector.includes("dynamic")) {
2159
+ return shadowRoot.querySelector(selector);
2160
+ }
2161
+ return null;
2162
+ };
2163
+ const getId = (element) => {
2164
+ return element?.id || null;
2165
+ };
2166
+ const getClassName = (element) => {
2167
+ return element.className || null;
2168
+ };
2169
+ const getVisibleText = (element) => {
2170
+ return element.textContent?.trim() || null;
2171
+ };
2172
+ const getName = (element) => {
2173
+ const elementEl = element;
2174
+ if (elementEl.hasAttribute("name")) {
2175
+ const attrValue = elementEl.getAttribute("name");
2176
+ const name = `${attrValue}`;
2177
+ return name || null;
2178
+ }
2179
+ return null;
2180
+ };
2181
+ const relations = [
2182
+ "/preceding-sibling",
2183
+ "/following-sibling",
2184
+ "/parent",
2185
+ "/descendant",
2186
+ "/ancestor",
2187
+ "/self",
2188
+ "/ancestor-or-self",
2189
+ "/child",
2190
+ "/preceding",
2191
+ "/following",
2192
+ ];
2193
+ function getElementFromXPath(tempDiv, xpath) {
2194
+ let currentElement = tempDiv;
2195
+ const window = currentElement.ownerDocument.defaultView;
2196
+ if (!window)
2197
+ return null;
2198
+ const xpathEvaluator = new window.XPathEvaluator();
2199
+ const xpathResult = xpathEvaluator.evaluate(xpath, currentElement.ownerDocument, //here even tempDiv can be passed
2200
+ null, window.XPathResult.FIRST_ORDERED_NODE_TYPE, null);
2201
+ return xpathResult.singleNodeValue;
2202
+ }
2203
+ function checkReferenceElementIsValid(locator, relation, tempDiv) {
2204
+ if (locator.includes(relation)) {
2205
+ const locatotSplitArray = locator.split(relation);
2206
+ const sourceLoc = locatotSplitArray[0].trim();
2207
+ let currentElement = tempDiv;
2208
+ const window = currentElement.ownerDocument.defaultView;
2209
+ if (!window)
2210
+ return null;
2211
+ if (!locator.includes("dynamic")) {
2212
+ const xpathEvaluator = new window.XPathEvaluator();
2213
+ const xpathResult = xpathEvaluator.evaluate(sourceLoc, currentElement.ownerDocument, null, window.XPathResult.FIRST_ORDERED_NODE_TYPE, null);
2214
+ const sourceElement = xpathResult.singleNodeValue;
2215
+ if (sourceElement) {
2216
+ const xpathResultComplete = xpathEvaluator.evaluate(locator, currentElement.ownerDocument, null, window.XPathResult.FIRST_ORDERED_NODE_TYPE, null);
2217
+ const completeElement = xpathResultComplete.singleNodeValue;
2218
+ let relativeXpath;
2219
+ if (completeElement) {
2220
+ relativeXpath = locator;
2221
+ return relativeXpath;
2222
+ }
2223
+ else {
2224
+ console.error("Complete Locator is Invalid:", locator);
2225
+ relativeXpath = locator;
2226
+ return relativeXpath;
2227
+ }
2228
+ }
2229
+ else {
2230
+ console.error("Source Locator Not Found:", sourceLoc);
2231
+ }
2232
+ }
2233
+ }
2234
+ return null;
2235
+ }
2236
+ const getElementsFromHTML = (record, docmt) => {
2237
+ const document = docmt;
2238
+ // global.SVGElement = document.defaultView?.SVGElement!;
2239
+ const tempDiv = document.createElement("div");
2240
+ const elementsToRemove = document.querySelectorAll("script, style, link[rel='stylesheet'], meta, noscript, embed, object, param, source, svg");
2241
+ if (elementsToRemove) {
2242
+ elementsToRemove.forEach((tag) => {
2243
+ tag.remove();
2244
+ });
2245
+ }
2246
+ tempDiv.innerHTML = document.body.innerHTML;
2247
+ const finalLocatorsSet = new Set();
2248
+ let finalLocators = [];
2249
+ function createLocator(base, overrides = {}) {
2250
+ const newLocator = {
2251
+ name: overrides.name ?? base?.name,
2252
+ type: overrides.type ?? base?.type,
2253
+ value: overrides.value ?? base?.value,
2254
+ reference: overrides.reference ?? base?.reference,
2255
+ status: overrides.status ?? base?.status,
2256
+ isRecorded: overrides.isRecorded ?? base?.isRecorded,
2257
+ };
2258
+ if (overrides.hasOwnProperty("isSelfHealed")) {
2259
+ newLocator.isSelfHealed = overrides.isSelfHealed;
2260
+ }
2261
+ else if (base?.hasOwnProperty("isSelfHealed")) {
2262
+ newLocator.isSelfHealed = base.isSelfHealed;
2263
+ }
2264
+ pushUniqueLocator(newLocator);
2265
+ }
2266
+ function pushUniqueLocator(obj) {
2267
+ const key = `${obj.name}:${obj.value}`;
2268
+ if (!finalLocatorsSet.has(key)) {
2269
+ finalLocatorsSet.add(key);
2270
+ finalLocators.push(obj);
2271
+ }
2272
+ }
2273
+ /** Locator Value Cleaner (Handles Special Scenarios) **/
2274
+ const cleanLocatorValue = (val, type, isRecorded) => {
2275
+ if (!val)
2276
+ return null;
2277
+ let cleaned = val.trim();
2278
+ // Return null for empty or literal "null"
2279
+ if (!cleaned || cleaned.toLowerCase() === "null")
2280
+ return null;
2281
+ // Unescape any escaped quotes
2282
+ cleaned = cleaned.replace(/\\"/g, '"').replace(/\\'/g, "'");
2283
+ // Remove surrounding single or double quotes
2284
+ cleaned = cleaned.replace(/^['"](.+?)['"]$/, "$1");
2285
+ // Replace double single quotes with a single quote inside XPath
2286
+ cleaned = cleaned.replace(/''/g, "'");
2287
+ // Normalize double quotes in XPath attribute selectors [@id="" -> [@id='']
2288
+ cleaned = cleaned.replace(/\[@(id|name)=['"]{2}(.+?)['"]{2}\]/g, "[@$1='$2']");
2289
+ // For DOM selectors (id or name), remove ALL quotes
2290
+ if (type === "id" || type === "name") {
2291
+ cleaned = cleaned.replace(/['"]/g, "").trim();
2292
+ }
2293
+ if (type === "xpath" && isRecorded === "Y" && !val.startsWith("//"))
2294
+ return null;
2295
+ // Final check for empty strings
2296
+ if (!cleaned || /^['"]{2}$/.test(cleaned))
2297
+ return null;
2298
+ return cleaned;
2299
+ };
2300
+ locators: for (const locator of record.locators) {
2301
+ try {
2302
+ const isRecorded = String(locator.isRecorded || "");
2303
+ const recordedNLocators = record.locators.filter((l) => l.isRecorded === "N");
2304
+ if (recordedNLocators.length > 0) {
2305
+ for (const locator of recordedNLocators) {
2306
+ createLocator(locator);
2307
+ }
2308
+ }
2309
+ const isDynamic = String(locator.value || locator.type || "");
2310
+ if (isDynamic.includes("dynamic") ||
2311
+ isDynamic.match("dynamic") ||
2312
+ isDynamic.includes("{") ||
2313
+ isDynamic.includes("}")) {
2314
+ createLocator(locator);
2315
+ continue;
2316
+ }
2317
+ if (record.isShared.includes("Y")) {
2318
+ break locators;
2319
+ }
2320
+ for (const relation of relations) {
2321
+ try {
2322
+ let targetElement = null;
2323
+ if (locator.value.startsWith("iframe")) {
2324
+ const iframe = tempDiv.querySelector(locator.value);
2325
+ if (iframe) {
2326
+ const iframeDocument = iframe.contentDocument || iframe.contentWindow?.document;
2327
+ if (iframeDocument) {
2328
+ targetElement = iframeDocument.querySelector(locator.value.slice(6));
2329
+ }
2330
+ }
2331
+ }
2332
+ else {
2333
+ const selectors = locator.value.split(">>>"); // Custom delimiter for shadow DOM
2334
+ let currentElement = tempDiv;
2335
+ for (const selector of selectors) {
2336
+ if (currentElement) {
2337
+ const trimmedSelector = selector.trim();
2338
+ if (locator.name.includes("id") ||
2339
+ trimmedSelector.startsWith("#")) {
2340
+ targetElement = currentElement.querySelector("#" + trimmedSelector);
2341
+ }
2342
+ else if (locator.name.includes("className") ||
2343
+ trimmedSelector.startsWith(".")) {
2344
+ targetElement = currentElement.querySelector("." + trimmedSelector);
2345
+ }
2346
+ else if ((locator.name.includes("xpath") ||
2347
+ trimmedSelector.startsWith("//")) &&
2348
+ !locator.type.match("dynamic")) {
2349
+ if (tempDiv.innerHTML) {
2350
+ const normalizedXPath = normalizeXPath(trimmedSelector);
2351
+ targetElement = getElementFromXPath(tempDiv, normalizedXPath);
2352
+ if (targetElement) {
2353
+ createLocator(locator, {
2354
+ value: trimmedSelector,
2355
+ isRecorded: String(locator.isRecorded).includes("N")
2356
+ ? "N"
2357
+ : "Y",
2358
+ });
2359
+ }
2360
+ }
2361
+ }
2362
+ else {
2363
+ targetElement = currentElement.querySelector(trimmedSelector);
2364
+ if (!targetElement) {
2365
+ targetElement = getElementFromShadowRoot(currentElement, trimmedSelector);
2366
+ }
2367
+ }
2368
+ if (!targetElement &&
2369
+ isSvg(currentElement) &&
2370
+ !locator.type.match("dynamic")) {
2371
+ targetElement = currentElement.querySelector(trimmedSelector);
2372
+ }
2373
+ currentElement = targetElement;
2374
+ }
2375
+ else {
2376
+ console.error("Element not found at:", selector);
2377
+ break;
2378
+ }
2379
+ }
2380
+ }
2381
+ const locatorExists = (name, value) => {
2382
+ const key = `${name}:${value}`;
2383
+ return finalLocatorsSet.has(key);
2384
+ };
2385
+ if (targetElement) {
2386
+ const idValue = getId(targetElement);
2387
+ if (idValue && !locatorExists("id", idValue)) {
2388
+ record.locators.forEach((loc) => {
2389
+ createLocator(loc, {
2390
+ name: "id",
2391
+ value: idValue,
2392
+ isRecorded: loc.value === idValue && loc.name === "id"
2393
+ ? loc.isRecorded
2394
+ : "Y",
2395
+ isSelfHealed: loc.value === idValue && loc.name === "id"
2396
+ ? loc.isSelfHealed
2397
+ : "Y",
2398
+ });
2399
+ });
2400
+ }
2401
+ const textValue = getVisibleText(targetElement);
2402
+ if (textValue) {
2403
+ record.locators.forEach((loc) => {
2404
+ createLocator(loc, {
2405
+ name: "linkText",
2406
+ type: "static",
2407
+ value: textValue,
2408
+ isRecorded: loc.value === textValue ? loc.isRecorded : "Y",
2409
+ isSelfHealed: loc.value === textValue ? loc.isSelfHealed : "Y",
2410
+ });
2411
+ });
2412
+ }
2413
+ const nameLocator = getName(targetElement);
2414
+ if (nameLocator && !locatorExists("name", nameLocator)) {
2415
+ record.locators.forEach((loc) => {
2416
+ createLocator(loc, {
2417
+ name: "name",
2418
+ type: "static",
2419
+ value: nameLocator,
2420
+ isRecorded: loc.value === nameLocator && loc.name === "name"
2421
+ ? loc.isRecorded
2422
+ : "Y",
2423
+ isSelfHealed: loc.value === nameLocator && loc.name === "name"
2424
+ ? loc.isSelfHealed
2425
+ : "Y",
2426
+ });
2427
+ });
2428
+ }
2429
+ const classValue = getClassName(targetElement);
2430
+ if (classValue &&
2431
+ classValue.trim() !== "" &&
2432
+ !locatorExists("className", classValue)) {
2433
+ record.locators.forEach((loc) => {
2434
+ createLocator(loc, {
2435
+ name: "className",
2436
+ value: classValue,
2437
+ isRecorded: loc.value === classValue && loc.name === "className"
2438
+ ? loc.isRecorded
2439
+ : "Y",
2440
+ isSelfHealed: loc.value === classValue && loc.name === "className"
2441
+ ? loc.isSelfHealed
2442
+ : "Y",
2443
+ });
2444
+ });
2445
+ }
2446
+ const fnValue = parseDOM(targetElement, document, false, true);
2447
+ record.locators.forEach((loc) => {
2448
+ createLocator(loc, {
2449
+ name: 'xpath',
2450
+ value: fnValue,
2451
+ isRecorded: fnValue?.find((x) => x.value === loc.value)
2452
+ ? loc.isRecorded
2453
+ : "Y",
2454
+ isSelfHealed: fnValue?.find((x) => x.value === loc.value)
2455
+ ? loc.isSelfHealed
2456
+ : "Y",
2457
+ });
2458
+ });
2459
+ for (const locator of record.locators) {
2460
+ try {
2461
+ for (const loc of record.locators) {
2462
+ if (!loc.value)
2463
+ continue;
2464
+ for (const relation of relations) {
2465
+ if (loc.value.includes(relation)) {
2466
+ const relativeXpath = checkReferenceElementIsValid(loc.value, relation, tempDiv);
2467
+ if (relativeXpath) {
2468
+ createLocator(loc, {
2469
+ name: "xpath",
2470
+ value: relativeXpath,
2471
+ isRecorded: locator.isRecorded !== "" &&
2472
+ locator.isRecorded !== null
2473
+ ? locator.isRecorded
2474
+ : "Y",
2475
+ });
2476
+ break;
2477
+ }
2478
+ }
2479
+ }
2480
+ }
2481
+ }
2482
+ catch (error) {
2483
+ console.error("Error processing locator:", locator, error);
2484
+ }
2485
+ }
2486
+ const finalAutoHealedLocators = finalLocators.map((obj) => ({
2487
+ ...obj,
2488
+ value: cleanLocatorValue(obj.value, obj.name, obj.isRecorded),
2489
+ }));
2490
+ const finalUniqueAutoHealedLocators = finalAutoHealedLocators.reduce((unique, locator) => {
2491
+ if (locator.value &&
2492
+ !unique.some((l) => l.value === locator.value)) {
2493
+ unique.push(locator);
2494
+ }
2495
+ return unique;
2496
+ }, []);
2497
+ const jsonResult = [
2498
+ {
2499
+ name: `${record.name}`,
2500
+ desc: `${record.desc}`,
2501
+ type: `${record.type}`,
2502
+ locators: finalUniqueAutoHealedLocators.filter((locator) => locator?.value != null && locator.value !== ""),
2503
+ isShared: `${record.isShared}`,
2504
+ projectId: `${record.projectId}`,
2505
+ projectType: `${record.projectType}`,
2506
+ isRecorded: `${record.isRecorded}`,
2507
+ folder: `${record.folder}`,
2508
+ parentId: `${record.parentId}`,
2509
+ parentName: `${record.parentName}`,
2510
+ platform: `${record.platform}`,
2511
+ licenseId: `${record.licenseId}`,
2512
+ licenseType: `${record.licenseType}`,
2513
+ userId: `${record.userId}`,
2514
+ },
2515
+ ];
2516
+ return jsonResult;
2517
+ }
2518
+ }
2519
+ catch (error) {
2520
+ console.error("Error processing locator:", locator, error);
2521
+ continue;
2522
+ }
2523
+ }
2524
+ }
2525
+ catch (error) {
2526
+ console.error("Error processing locator:", locator, error);
2527
+ continue;
2528
+ }
2529
+ }
2530
+ return null;
2531
+ };
2532
+
2533
+ let modifiedElementAttributes = [];
2534
+ const parseCssSelectors = (el, docmt) => {
2535
+ let cssSelector = [];
2536
+ try {
2537
+ let idCssSelector = getIdCssPath(el, docmt);
2538
+ if (idCssSelector &&
2539
+ idCssSelector.includes('#') &&
2540
+ docmt.querySelectorAll(idCssSelector)?.length === 1 &&
2541
+ !(idCssSelector.includes('body') ||
2542
+ idCssSelector.includes('head') ||
2543
+ idCssSelector.includes('html'))) {
2544
+ cssSelector.push({ key: 'cssSelector by id', value: idCssSelector });
2545
+ }
2546
+ else {
2547
+ idCssSelector = '';
2548
+ }
2549
+ let nameCssSelector = getNameCssPath(el, docmt);
2550
+ if (nameCssSelector &&
2551
+ nameCssSelector !== idCssSelector &&
2552
+ nameCssSelector.includes('name') &&
2553
+ docmt.querySelectorAll(nameCssSelector)?.length === 1 &&
2554
+ !(nameCssSelector.includes('body') ||
2555
+ nameCssSelector.includes('head') ||
2556
+ nameCssSelector.includes('html'))) {
2557
+ cssSelector.push({ key: 'cssSelector by name', value: nameCssSelector });
2558
+ }
2559
+ else {
2560
+ nameCssSelector = '';
2561
+ }
2562
+ let classCssSelector = getClassCssPath(el, docmt);
2563
+ if (classCssSelector &&
2564
+ classCssSelector !== idCssSelector &&
2565
+ nameCssSelector !== classCssSelector &&
2566
+ classCssSelector.includes('.') &&
2567
+ docmt.querySelectorAll(classCssSelector)?.length === 1 &&
2568
+ !(classCssSelector.includes('body') ||
2569
+ classCssSelector.includes('head') ||
2570
+ classCssSelector.includes('html'))) {
2571
+ cssSelector.push({
2572
+ key: 'cssSelector by class',
2573
+ value: classCssSelector,
2574
+ });
2575
+ }
2576
+ else {
2577
+ classCssSelector = '';
2578
+ }
2579
+ }
2580
+ catch (error) {
2581
+ console.log(error);
2582
+ }
2583
+ if (!cssSelector.length) {
2584
+ let abSelector = getAbsoluteCssPath(el, docmt);
2585
+ if (abSelector &&
2586
+ docmt.querySelectorAll(abSelector)?.length === 1 &&
2587
+ !(abSelector.includes('body') ||
2588
+ abSelector.includes('head') ||
2589
+ abSelector.includes('html'))) {
2590
+ cssSelector.push({
2591
+ key: 'Absolute cssSelector',
2592
+ value: abSelector,
2593
+ });
2594
+ }
2595
+ else {
2596
+ abSelector = '';
2597
+ }
2598
+ }
2599
+ return cssSelector;
2600
+ };
2601
+ const getIdCssPath = (el, docmt) => {
2602
+ const tagName = el.tagName.toLowerCase();
2603
+ if (docmt?.defaultView?.Element &&
2604
+ !(el instanceof docmt?.defaultView?.Element))
2605
+ return;
2606
+ if (tagName.includes('style') || tagName.includes('script'))
2607
+ return;
2608
+ const path = [];
2609
+ while (el.nodeType === Node.ELEMENT_NODE) {
2610
+ let selector = el.nodeName?.toLowerCase();
2611
+ if (el.id && !isNumberExist(el.id)) {
2612
+ selector += `#${el.id}`;
2613
+ path.unshift(selector);
2614
+ break;
2615
+ }
2616
+ else {
2617
+ let sib = el;
2618
+ let nth = 1;
2619
+ if (sib.previousElementSibling) {
2620
+ while ((sib = sib.previousElementSibling)) {
2621
+ if (sib.nodeName?.toLowerCase() === selector)
2622
+ nth++;
2623
+ }
2624
+ }
2625
+ if (nth !== 1) {
2626
+ selector += `:nth-of-type(${nth})`;
2627
+ }
2628
+ if (nth === 1 && sib?.parentElement?.childElementCount > 1) {
2629
+ selector += `:nth-child(${nth})`;
2630
+ }
2631
+ }
2632
+ path.unshift(selector);
2633
+ el = el.parentElement;
2634
+ }
2635
+ return path.join(' > ');
2636
+ };
2637
+ const getNameCssPath = (el, docmt) => {
2638
+ const tagName = el.tagName.toLowerCase();
2639
+ if (docmt?.defaultView?.Element &&
2640
+ !(el instanceof docmt?.defaultView?.Element))
2641
+ return;
2642
+ if (tagName.includes('style') || tagName.includes('script'))
2643
+ return;
2644
+ const path = [];
2645
+ while (el.nodeType === Node.ELEMENT_NODE) {
2646
+ let selector = el.nodeName?.toLowerCase();
2647
+ let name = el.getAttribute('name');
2648
+ if (name && !isNumberExist(name)) {
2649
+ selector += `[name=${name}]`;
2650
+ path.unshift(selector);
2651
+ break;
2652
+ }
2653
+ else {
2654
+ let sib = el;
2655
+ let nth = 1;
2656
+ if (sib.previousElementSibling) {
2657
+ while ((sib = sib.previousElementSibling)) {
2658
+ if (sib.nodeName?.toLowerCase() === selector)
2659
+ nth++;
2660
+ }
2661
+ }
2662
+ if (nth !== 1) {
2663
+ selector += `:nth-of-type(${nth})`;
2664
+ }
2665
+ if (nth === 1 && sib?.parentElement?.childElementCount > 1) {
2666
+ selector += `:nth-child(${nth})`;
2667
+ }
2668
+ }
2669
+ path.unshift(selector);
2670
+ el = el.parentElement;
2671
+ }
2672
+ return path.join(' > ');
2673
+ };
2674
+ const getClassCssPath = (el, docmt) => {
2675
+ const tagName = el.tagName.toLowerCase();
2676
+ if (docmt?.defaultView?.Element &&
2677
+ !(el instanceof docmt?.defaultView?.Element))
2678
+ return;
2679
+ if (tagName.includes('style') || tagName.includes('script'))
2680
+ return;
2681
+ const path = [];
2682
+ while (el.nodeType === Node.ELEMENT_NODE) {
2683
+ let selector = el.nodeName?.toLowerCase();
2684
+ if (typeof el.className === 'string' &&
2685
+ el.className &&
2686
+ !isNumberExist(el.className) &&
2687
+ !modifiedElementAttributes?.find((x) => x.element === el && x.attributeName === 'class')) {
2688
+ el.classList.remove('marked-element-temp');
2689
+ el.classList.remove('removePointers');
2690
+ if (el.className) {
2691
+ selector += `.${el.className.trim().replace(/\s+/g, '.')}`;
2692
+ path.unshift(selector);
2693
+ break;
2694
+ }
2695
+ }
2696
+ else {
2697
+ let sib = el;
2698
+ let nth = 1;
2699
+ if (sib.previousElementSibling) {
2700
+ while ((sib = sib.previousElementSibling)) {
2701
+ if (sib.nodeName?.toLowerCase() === selector)
2702
+ nth++;
2703
+ }
2704
+ }
2705
+ if (nth !== 1) {
2706
+ selector += `:nth-of-type(${nth})`;
2707
+ }
2708
+ if (nth === 1 && sib?.parentElement?.childElementCount > 1) {
2709
+ selector += `:nth-child(${nth})`;
2710
+ }
2711
+ }
2712
+ path.unshift(selector);
2713
+ el = el.parentElement;
2714
+ }
2715
+ return path.join(' > ');
2716
+ };
2717
+ const getAbsoluteCssPath = (el, docmt) => {
2718
+ const tagName = el.tagName.toLowerCase();
2719
+ if (docmt?.defaultView?.Element &&
2720
+ !(el instanceof docmt?.defaultView?.Element))
2721
+ return;
2722
+ if (tagName.includes('style') || tagName.includes('script'))
2723
+ return;
2724
+ const path = [];
2725
+ while (el.nodeType === Node.ELEMENT_NODE) {
2726
+ let selector = el.nodeName?.toLowerCase();
2727
+ if (tagName.includes('body') ||
2728
+ tagName.includes('head') ||
2729
+ tagName.includes('html')) {
2730
+ selector += tagName;
2731
+ path.unshift(selector);
2732
+ break;
2733
+ }
2734
+ else {
2735
+ let sib = el;
2736
+ let nth = 1;
2737
+ if (sib.previousElementSibling) {
2738
+ while ((sib = sib.previousElementSibling)) {
2739
+ if (sib.nodeName?.toLowerCase() === selector)
2740
+ nth++;
2741
+ }
2742
+ }
2743
+ if (nth !== 1) {
2744
+ selector += `:nth-of-type(${nth})`;
2745
+ }
2746
+ if (nth === 1 && sib?.parentElement?.childElementCount > 1) {
2747
+ selector += `:nth-child(${nth})`;
2748
+ }
2749
+ }
2750
+ path.unshift(selector);
2751
+ el = el.parentElement;
2752
+ }
2753
+ return path.join(' > ');
2754
+ };
2755
+ const cssSelectors = {
2756
+ parseCssSelectors,
2757
+ getIdCssPath,
2758
+ getNameCssPath,
2759
+ getClassCssPath,
2760
+ getAbsoluteCssPath
2761
+ };
2762
+
2763
+ const createXPathAPI = () => ({
2764
+ xpath,
2765
+ referenceXpaths: referenceXpath,
2766
+ xpathUtils,
2767
+ getElementsFromHTML,
2768
+ cssSelectors
2769
+ });
2770
+
2771
+ exports.createXPathAPI = createXPathAPI;
2772
+ exports.default = createXPathAPI;
2773
+ //# sourceMappingURL=index.browser.cjs.map