|
| 1 | +export type PDFTextNode = { |
| 2 | + text: string; |
| 3 | + x: number; |
| 4 | + y: number; |
| 5 | + page: number; |
| 6 | + width: number; |
| 7 | +}; |
| 8 | + |
| 9 | +export type KeycardEntry = { |
| 10 | + label: string; |
| 11 | + value: string; |
| 12 | +}; |
| 13 | + |
| 14 | +const sectionHeaderRegex = /^([A-D])\s*[:.)-]\s*(.+?)\s*$/i; |
| 15 | +const dataLineRegex = /^data\s*:\s*(.*)$/i; |
| 16 | +const faqHeaderRegex = /^BitGo\s+KeyCard\s+FAQ$/i; |
| 17 | + |
| 18 | +// PDF coordinate tolerance in points. Nodes within this distance on the Y-axis |
| 19 | +// are treated as belonging to the same line; nodes further apart are separate lines. |
| 20 | +const PDF_LINE_Y_TOLERANCE = 2; |
| 21 | +// Horizontal gap in points above which a space is inserted between adjacent nodes. |
| 22 | +const PDF_NODE_GAP_THRESHOLD = 2; |
| 23 | + |
| 24 | +function sanitizeText(input: string): string { |
| 25 | + return input.replace(/\s+/g, ' ').trim(); |
| 26 | +} |
| 27 | + |
| 28 | +function normalizeSectionValue(rawValue: string): string { |
| 29 | + // Two-pass removal of "Part N" page-continuation labels: |
| 30 | + // 1. Line filter: removes labels that appear as standalone lines. |
| 31 | + // 2. Regex replace: removes labels embedded mid-line when |
| 32 | + // buildLinesFromPDFNodes merges them with adjacent content at the same |
| 33 | + // y-coordinate (e.g. "...X88bPart 2 lFPMd..."). |
| 34 | + // join('') intentionally uses no separator — section values are continuous |
| 35 | + // strings (base64 / xpub) that wrap across PDF lines without spaces. |
| 36 | + return rawValue |
| 37 | + .split('\n') |
| 38 | + .filter((line) => !/^Part\s+\d+$/i.test(line.trim())) |
| 39 | + .join('') |
| 40 | + .replace(/\s*Part\s+\d+\s*/gi, '') |
| 41 | + .trim(); |
| 42 | +} |
| 43 | + |
| 44 | +function countChar(input: string, char: string): number { |
| 45 | + return input.split(char).length - 1; |
| 46 | +} |
| 47 | + |
| 48 | +function isEncryptedWalletPasswordSectionTitle(title: string): boolean { |
| 49 | + return title.toLowerCase().includes('encrypted wallet password'); |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * Reconstructs logical text lines from an unordered set of PDF text nodes. |
| 54 | + * |
| 55 | + * PDF text extraction returns individual positioned fragments. This function |
| 56 | + * sorts them by page then Y-coordinate (top-to-bottom), groups fragments |
| 57 | + * within PDF_LINE_Y_TOLERANCE points of each other onto the same line, and |
| 58 | + * inserts a space between fragments that are separated by more than |
| 59 | + * PDF_NODE_GAP_THRESHOLD points horizontally. |
| 60 | + */ |
| 61 | +export function buildLinesFromPDFNodes(nodes: PDFTextNode[]): string[] { |
| 62 | + const sortedNodes = [...nodes].sort((a, b) => { |
| 63 | + if (a.page !== b.page) { |
| 64 | + return a.page - b.page; |
| 65 | + } |
| 66 | + const yDiff = Math.abs(a.y - b.y); |
| 67 | + if (yDiff > PDF_LINE_Y_TOLERANCE) { |
| 68 | + return b.y - a.y; |
| 69 | + } |
| 70 | + return a.x - b.x; |
| 71 | + }); |
| 72 | + |
| 73 | + const lines: string[] = []; |
| 74 | + let currentLineNodes: PDFTextNode[] = []; |
| 75 | + let currentPage = -1; |
| 76 | + let currentY = Number.NaN; |
| 77 | + |
| 78 | + function flushLine() { |
| 79 | + if (currentLineNodes.length === 0) { |
| 80 | + return; |
| 81 | + } |
| 82 | + |
| 83 | + const sortedLineNodes = [...currentLineNodes].sort((a, b) => a.x - b.x); |
| 84 | + let line = ''; |
| 85 | + let previousRightEdge: number | null = null; |
| 86 | + for (const node of sortedLineNodes) { |
| 87 | + const piece = sanitizeText(node.text); |
| 88 | + if (!piece) { |
| 89 | + continue; |
| 90 | + } |
| 91 | + |
| 92 | + if (previousRightEdge !== null && node.x - previousRightEdge > PDF_NODE_GAP_THRESHOLD) { |
| 93 | + line += ' '; |
| 94 | + } |
| 95 | + line += piece; |
| 96 | + previousRightEdge = node.x + node.width; |
| 97 | + } |
| 98 | + |
| 99 | + const normalizedLine = line.trim(); |
| 100 | + if (normalizedLine) { |
| 101 | + lines.push(normalizedLine); |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + for (const node of sortedNodes) { |
| 106 | + const pageChanged = node.page !== currentPage; |
| 107 | + const lineChanged = Number.isNaN(currentY) || Math.abs(node.y - currentY) > PDF_LINE_Y_TOLERANCE; |
| 108 | + if (pageChanged || lineChanged) { |
| 109 | + flushLine(); |
| 110 | + currentLineNodes = [node]; |
| 111 | + currentPage = node.page; |
| 112 | + currentY = node.y; |
| 113 | + continue; |
| 114 | + } |
| 115 | + |
| 116 | + currentLineNodes.push(node); |
| 117 | + } |
| 118 | + |
| 119 | + flushLine(); |
| 120 | + return lines; |
| 121 | +} |
| 122 | + |
| 123 | +export function parseKeycardFromLines(lines: string[]): KeycardEntry[] { |
| 124 | + const sections: Array<{ |
| 125 | + section: string; |
| 126 | + title: string; |
| 127 | + values: string[]; |
| 128 | + isCapturingData: boolean; |
| 129 | + openCurlyCount: number; |
| 130 | + }> = []; |
| 131 | + let currentSectionIndex = -1; |
| 132 | + |
| 133 | + for (const line of lines) { |
| 134 | + const labelMatch = line.match(sectionHeaderRegex); |
| 135 | + if (labelMatch) { |
| 136 | + const section = labelMatch[1]?.toUpperCase(); |
| 137 | + const title = sanitizeText(labelMatch[2] ?? ''); |
| 138 | + if (section && title) { |
| 139 | + sections.push({ |
| 140 | + section, |
| 141 | + title, |
| 142 | + values: [], |
| 143 | + isCapturingData: false, |
| 144 | + openCurlyCount: 0, |
| 145 | + }); |
| 146 | + currentSectionIndex = sections.length - 1; |
| 147 | + continue; |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + if (currentSectionIndex < 0) { |
| 152 | + continue; |
| 153 | + } |
| 154 | + |
| 155 | + const currentSection = sections[currentSectionIndex]; |
| 156 | + if (!currentSection) { |
| 157 | + continue; |
| 158 | + } |
| 159 | + |
| 160 | + const dataLineMatch = line.match(dataLineRegex); |
| 161 | + if (dataLineMatch) { |
| 162 | + currentSection.isCapturingData = true; |
| 163 | + const inlineValue = sanitizeText(dataLineMatch[1] ?? ''); |
| 164 | + if (inlineValue) { |
| 165 | + currentSection.values.push(inlineValue); |
| 166 | + currentSection.openCurlyCount += countChar(inlineValue, '{') - countChar(inlineValue, '}'); |
| 167 | + } |
| 168 | + continue; |
| 169 | + } |
| 170 | + |
| 171 | + if (currentSection.isCapturingData) { |
| 172 | + if (faqHeaderRegex.test(line)) { |
| 173 | + currentSection.isCapturingData = false; |
| 174 | + continue; |
| 175 | + } |
| 176 | + |
| 177 | + currentSection.values.push(line); |
| 178 | + |
| 179 | + // For encrypted wallet password, data is a single JSON object. Stop as |
| 180 | + // soon as the object closes so footer/FAQ content is not appended. |
| 181 | + if (isEncryptedWalletPasswordSectionTitle(currentSection.title)) { |
| 182 | + currentSection.openCurlyCount += countChar(line, '{') - countChar(line, '}'); |
| 183 | + if (currentSection.values.length > 0 && currentSection.openCurlyCount <= 0) { |
| 184 | + currentSection.isCapturingData = false; |
| 185 | + } |
| 186 | + } |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + return sections |
| 191 | + .filter(({ section, values }) => ['A', 'B', 'C', 'D'].includes(section) && values.length > 0) |
| 192 | + .map(({ section, title, values }) => ({ |
| 193 | + label: `${section}: ${title}`, |
| 194 | + value: normalizeSectionValue(values.join('\n')), |
| 195 | + })); |
| 196 | +} |
0 commit comments