ff-dom 1.0.17 → 1.0.18-beta.2

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