|
| 1 | +import { assertOkResponse } from "../../lib/utils.js"; |
| 2 | +import config from "../../config.js"; |
| 3 | + |
| 4 | +interface SelectorMapping { |
| 5 | + originalSelector: string; |
| 6 | + healedSelector: string; |
| 7 | + context: { |
| 8 | + before: string; |
| 9 | + after: string; |
| 10 | + }; |
| 11 | +} |
| 12 | + |
| 13 | +export async function getSelfHealSelectors(sessionId: string) { |
| 14 | + const credentials = `${config.browserstackUsername}:${config.browserstackAccessKey}`; |
| 15 | + const auth = Buffer.from(credentials).toString("base64"); |
| 16 | + const url = `https://api.browserstack.com/automate/sessions/${sessionId}/logs`; |
| 17 | + |
| 18 | + const response = await fetch(url, { |
| 19 | + headers: { |
| 20 | + "Content-Type": "application/json", |
| 21 | + Authorization: `Basic ${auth}`, |
| 22 | + }, |
| 23 | + }); |
| 24 | + |
| 25 | + await assertOkResponse(response, "session logs"); |
| 26 | + const logText = await response.text(); |
| 27 | + return extractHealedSelectors(logText); |
| 28 | +} |
| 29 | + |
| 30 | +function extractHealedSelectors(logText: string): SelectorMapping[] { |
| 31 | + // Split log text into lines for easier context handling |
| 32 | + const logLines = logText.split("\n"); |
| 33 | + |
| 34 | + // Pattern to match successful SELFHEAL entries only |
| 35 | + const selfhealPattern = |
| 36 | + /SELFHEAL\s*{\s*"status":"true",\s*"data":\s*{\s*"using":"css selector",\s*"value":"(.*?)"}/; |
| 37 | + |
| 38 | + // Pattern to match preceding selector requests |
| 39 | + const requestPattern = |
| 40 | + /POST \/session\/[^/]+\/element.*?"using":"css selector","value":"(.*?)"/; |
| 41 | + |
| 42 | + // Find all successful healed selectors with their line numbers and context |
| 43 | + const healedMappings: SelectorMapping[] = []; |
| 44 | + |
| 45 | + for (let i = 0; i < logLines.length; i++) { |
| 46 | + const match = logLines[i].match(selfhealPattern); |
| 47 | + if (match) { |
| 48 | + const beforeLine = i > 0 ? logLines[i - 1] : ""; |
| 49 | + const afterLine = i < logLines.length - 1 ? logLines[i + 1] : ""; |
| 50 | + |
| 51 | + // Look backwards to find the most recent original selector request |
| 52 | + let originalSelector = "UNKNOWN"; |
| 53 | + for (let j = i - 1; j >= 0; j--) { |
| 54 | + const requestMatch = logLines[j].match(requestPattern); |
| 55 | + if (requestMatch) { |
| 56 | + originalSelector = requestMatch[1]; |
| 57 | + break; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + healedMappings.push({ |
| 62 | + originalSelector, |
| 63 | + healedSelector: match[1], |
| 64 | + context: { |
| 65 | + before: beforeLine, |
| 66 | + after: afterLine, |
| 67 | + }, |
| 68 | + }); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return healedMappings; |
| 73 | +} |
0 commit comments