2023-04-03 10:41:15 +00:00
|
|
|
import unescapeJS from "unescape-js";
|
2023-05-22 12:55:46 +00:00
|
|
|
import type { PropertyNode } from "../index";
|
|
|
|
|
import { isLiteralNode } from "../index";
|
2022-08-23 11:09:42 +00:00
|
|
|
|
|
|
|
|
const beginsWithLineBreakRegex = /^\s+|\s+$/;
|
|
|
|
|
|
|
|
|
|
export function sanitizeScript(js: string, evaluationVersion: number) {
|
|
|
|
|
// We remove any line breaks from the beginning of the script because that
|
|
|
|
|
// makes the final function invalid. We also unescape any escaped characters
|
|
|
|
|
// so that eval can happen
|
2022-10-18 06:37:06 +00:00
|
|
|
//default value of evalutaion version is 2
|
|
|
|
|
evaluationVersion = evaluationVersion ? evaluationVersion : 2;
|
2023-04-03 10:41:15 +00:00
|
|
|
const trimmedJS = js.replace(beginsWithLineBreakRegex, "");
|
2022-08-23 11:09:42 +00:00
|
|
|
return evaluationVersion > 1 ? trimmedJS : unescapeJS(trimmedJS);
|
|
|
|
|
}
|
2022-09-17 17:40:28 +00:00
|
|
|
|
|
|
|
|
// For the times when you need to know if something truly an object like { a: 1, b: 2}
|
|
|
|
|
// typeof, lodash.isObject and others will return false positives for things like array, null, etc
|
|
|
|
|
export const isTrueObject = (
|
2023-04-03 10:41:15 +00:00
|
|
|
item: unknown,
|
2022-09-17 17:40:28 +00:00
|
|
|
): item is Record<string, unknown> => {
|
2023-04-03 10:41:15 +00:00
|
|
|
return Object.prototype.toString.call(item) === "[object Object]";
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const getNameFromPropertyNode = (node: PropertyNode): string =>
|
|
|
|
|
isLiteralNode(node.key) ? String(node.key.value) : node.key.name;
|
|
|
|
|
|
|
|
|
|
type Position = {
|
|
|
|
|
line: number;
|
|
|
|
|
ch: number;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const extractContentByPosition = (
|
|
|
|
|
content: string,
|
|
|
|
|
position: { from: Position; to: Position },
|
|
|
|
|
) => {
|
|
|
|
|
const eachLine = content.split("\n");
|
|
|
|
|
|
|
|
|
|
let returnedString = "";
|
|
|
|
|
|
|
|
|
|
for (let i = position.from.line; i <= position.to.line; i++) {
|
|
|
|
|
if (i === position.from.line) {
|
|
|
|
|
returnedString =
|
|
|
|
|
position.from.line !== position.to.line
|
|
|
|
|
? eachLine[position.from.line].slice(position.from.ch)
|
|
|
|
|
: eachLine[position.from.line].slice(
|
|
|
|
|
position.from.ch,
|
|
|
|
|
position.to.ch + 1,
|
|
|
|
|
);
|
|
|
|
|
} else if (i === position.to.line) {
|
|
|
|
|
returnedString += eachLine[position.to.line].slice(0, position.to.ch + 1);
|
|
|
|
|
} else {
|
|
|
|
|
returnedString += eachLine[i];
|
|
|
|
|
}
|
|
|
|
|
if (i !== position.to.line) {
|
|
|
|
|
returnedString += "\n";
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return returnedString;
|
2022-09-17 17:40:28 +00:00
|
|
|
};
|