1 | import fs from 'node:fs';
|
2 | import { isNode } from 'environment';
|
3 | import isIdentifier from 'is-identifier';
|
4 |
|
5 | const labelRegex = /^.*?\((?<label>.*?)[,)]/;
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | export const inferLabel = (callsites) => {
|
14 | if (!isNode) {
|
15 |
|
16 | return;
|
17 | }
|
18 |
|
19 | const functionCallStackFrame = callsites[1];
|
20 | if (!functionCallStackFrame) {
|
21 | return;
|
22 | }
|
23 | const fileName = functionCallStackFrame.getFileName();
|
24 | const lineNumber = functionCallStackFrame.getLineNumber();
|
25 | const columnNumber = functionCallStackFrame.getColumnNumber();
|
26 | if (fileName === null || lineNumber === null || columnNumber === null) {
|
27 | return;
|
28 | }
|
29 | let content = [];
|
30 | try {
|
31 | content = fs.readFileSync(fileName, 'utf8').split('\n');
|
32 | }
|
33 | catch {
|
34 | return;
|
35 | }
|
36 | let line = content[lineNumber - 1];
|
37 | if (!line) {
|
38 |
|
39 | return;
|
40 | }
|
41 | line = line.slice(columnNumber - 1);
|
42 | const match = labelRegex.exec(line);
|
43 | const token = match?.groups?.['label'];
|
44 | if (!token) {
|
45 |
|
46 | return;
|
47 | }
|
48 |
|
49 | if (isIdentifier(token) || isIdentifier(token.split('.').pop() ?? '')) {
|
50 | return token;
|
51 | }
|
52 | return;
|
53 | };
|