UNPKG

1.81 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.inferLabel = void 0;
4const fs = require("fs");
5const is_valid_identifier_1 = require("./is-valid-identifier");
6const is_node_1 = require("./node/is-node");
7// Regex to extract the label out of the `ow` function call
8const labelRegex = /^.*?\((?<label>.*?)[,)]/;
9/**
10Infer the label of the caller.
11
12@hidden
13
14@param callsites - List of stack frames.
15*/
16const inferLabel = (callsites) => {
17 var _a;
18 if (!is_node_1.default) {
19 // Exit if we are not running in a Node.js environment
20 return;
21 }
22 // Grab the stackframe with the `ow` function call
23 const functionCallStackFrame = callsites[1];
24 if (!functionCallStackFrame) {
25 return;
26 }
27 const fileName = functionCallStackFrame.getFileName();
28 const lineNumber = functionCallStackFrame.getLineNumber();
29 const columnNumber = functionCallStackFrame.getColumnNumber();
30 if (fileName === null || lineNumber === null || columnNumber === null) {
31 return;
32 }
33 let content = [];
34 try {
35 content = fs.readFileSync(fileName, 'utf8').split('\n');
36 }
37 catch (_b) {
38 return;
39 }
40 let line = content[lineNumber - 1];
41 if (!line) {
42 // Exit if the line number couldn't be found
43 return;
44 }
45 line = line.slice(columnNumber - 1);
46 const match = labelRegex.exec(line);
47 if (!((_a = match === null || match === void 0 ? void 0 : match.groups) === null || _a === void 0 ? void 0 : _a.label)) {
48 // Exit if we didn't find a label
49 return;
50 }
51 const token = match.groups.label;
52 if (is_valid_identifier_1.default(token) || is_valid_identifier_1.default(token.split('.').pop())) {
53 return token;
54 }
55 return;
56};
57exports.inferLabel = inferLabel;