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