UNPKG

1.62 kBJavaScriptView Raw
1import fs from 'node:fs';
2import { isNode } from 'environment';
3import isIdentifier from 'is-identifier';
4// Regex to extract the label out of the `ow` function call
5const labelRegex = /^.*?\((?<label>.*?)[,)]/;
6/**
7Infer the label of the caller.
8
9@hidden
10
11@param callsites - List of stack frames.
12*/
13export const inferLabel = (callsites) => {
14 if (!isNode) {
15 // Exit if we are not running in a Node.js environment
16 return;
17 }
18 // Grab the stackframe with the `ow` function call
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 // Exit if the line number couldn't be found
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 // Exit if we didn't find a label
46 return;
47 }
48 // @ts-expect-error - Doesn't seem like something I can work around.
49 if (isIdentifier(token) || isIdentifier(token.split('.').pop() ?? '')) { // eslint-disable-line @typescript-eslint/no-unsafe-call
50 return token;
51 }
52 return;
53};