flagpole
Version:
Simple and fast DOM integration, headless or headful browser, and REST API testing framework.
402 lines • 14 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFunctionArgs = exports.validateSchema = exports.loadSchemaValidator = exports.cast = exports.randomIn = exports.randomInt = exports.random = exports.lastIn = exports.middleIn = exports.firstIn = exports.nthIn = exports.objectContainsKeys = exports.objectContains = exports.deepStrictEqual = exports.deepEqual = exports.getMessageAndCallbackFromOverloading = exports.exitProcess = exports.emptyFolder = exports.ensureFolderExists = exports.normalizePath = exports.arrayExactly = exports.arrayEquals = exports.flatten = exports.asyncCount = exports.asyncSome = exports.asyncNone = exports.asyncMapToObject = exports.asyncFlatMap = exports.asyncMap = exports.asyncFilter = exports.asyncEvery = exports.asyncForEach = exports.asyncUntil = exports.asyncFindNot = exports.asyncFind = exports.asyncFindIndex = exports.runAsync = exports.openInBrowser = exports.uniqueId = exports.arrayUnique = exports.toType = exports.toOrdinal = exports.isAsyncCallback = exports.isNullOrUndefined = exports.toJson = exports.toArray = void 0;
const fs = require("fs");
const path = require("path");
const nodeAssert = require("assert");
const util_1 = require("util");
const ajv_1 = require("ajv");
const jtd_1 = require("ajv/dist/jtd");
const toArray = (value) => Array.isArray(value) ? value : [value];
exports.toArray = toArray;
const toJson = (json) => {
try {
return JSON.parse(json);
}
catch (ex) { }
return {};
};
exports.toJson = toJson;
const isNullOrUndefined = (obj) => typeof obj === "undefined" || obj === null;
exports.isNullOrUndefined = isNullOrUndefined;
const isAsyncCallback = (func) => {
return (func.constructor.name == "AsyncFunction" ||
util_1.types.isAsyncFunction(func) ||
func.toString().indexOf("__awaiter(") > 0);
};
exports.isAsyncCallback = isAsyncCallback;
const toOrdinal = (n) => {
const suffix = ["th", "st", "nd", "rd"];
const value = n % 100;
return n + (suffix[(value - 20) % 10] || suffix[value] || suffix[0]);
};
exports.toOrdinal = toOrdinal;
const toType = (obj) => {
if (typeof obj === "undefined") {
return "undefined";
}
else if (obj === null) {
return "null";
}
else if (obj === NaN) {
return "nan";
}
else if (!!obj && obj.cheerio) {
return "cheerio";
}
else if (!!obj &&
(typeof obj === "object" || typeof obj === "function") &&
typeof obj.then === "function" &&
typeof obj.catch === "function") {
return "promise";
}
else if (obj && obj.constructor && obj.constructor.name) {
return String(obj.constructor.name).toLocaleLowerCase();
}
else if (obj && obj.constructor && obj.constructor.toString) {
const arr = obj.constructor.toString().match(/function\s*(\w+)/);
if (arr && arr.length == 2) {
return String(arr[1]).toLocaleLowerCase();
}
}
const match = {}.toString
.call(obj)
.match(/\s([a-zA-Z]+)/);
return match !== null ? String(match[1]).toLocaleLowerCase() : "";
};
exports.toType = toType;
const arrayUnique = (arr) => {
return [...new Set(arr)];
};
exports.arrayUnique = arrayUnique;
const uniqueId = () => "_" + Math.random().toString(36).substr(2, 9);
exports.uniqueId = uniqueId;
const openInBrowser = (content) => __awaiter(void 0, void 0, void 0, function* () {
const open = require("open");
const tmp = require("tmp");
const tmpObj = tmp.fileSync({ postfix: ".html" });
const filePath = tmpObj.name;
fs.writeFileSync(filePath, content);
yield open(filePath);
return filePath;
});
exports.openInBrowser = openInBrowser;
const runAsync = (callback, delay = 1) => {
setTimeout(callback, delay);
};
exports.runAsync = runAsync;
const asyncFindIndex = (array, callback) => __awaiter(void 0, void 0, void 0, function* () {
for (let i = 0; i < array.length; i++) {
if (yield callback(array[i], i, array)) {
return i;
}
}
return -1;
});
exports.asyncFindIndex = asyncFindIndex;
const asyncFind = (array, callback) => __awaiter(void 0, void 0, void 0, function* () {
for (let i = 0; i < array.length; i++) {
if (yield callback(array[i], i, array)) {
return array[i];
}
}
return null;
});
exports.asyncFind = asyncFind;
const asyncFindNot = (array, callback) => __awaiter(void 0, void 0, void 0, function* () {
for (let i = 0; i < array.length; i++) {
if (!(yield callback(array[i], i, array))) {
return array[i];
}
}
return null;
});
exports.asyncFindNot = asyncFindNot;
const asyncUntil = (array, callback) => __awaiter(void 0, void 0, void 0, function* () {
for (let i = 0; i < array.length; i++) {
const output = yield callback(array[i], i, array);
if (output) {
return output;
}
}
return null;
});
exports.asyncUntil = asyncUntil;
const asyncForEach = (array, callback) => __awaiter(void 0, void 0, void 0, function* () {
yield exports.asyncMap(array, callback);
});
exports.asyncForEach = asyncForEach;
const asyncEvery = (array, callback) => __awaiter(void 0, void 0, void 0, function* () {
for (const item of array) {
if (!(yield callback(item)))
return false;
}
return true;
});
exports.asyncEvery = asyncEvery;
const asyncFilter = (array, callback) => __awaiter(void 0, void 0, void 0, function* () {
const results = yield exports.asyncMap(array, callback);
return array.filter((_v, index) => !!results[index]);
});
exports.asyncFilter = asyncFilter;
const asyncMap = (array, callback) => __awaiter(void 0, void 0, void 0, function* () {
return Promise.all(array.map(callback));
});
exports.asyncMap = asyncMap;
const asyncFlatMap = (array, callback) => __awaiter(void 0, void 0, void 0, function* () {
const values = yield exports.asyncMap(array, callback);
return [].concat(...values);
});
exports.asyncFlatMap = asyncFlatMap;
const asyncMapToObject = (array, callback) => __awaiter(void 0, void 0, void 0, function* () {
const results = yield exports.asyncMap(array, callback);
return array.reduce((map, key, i) => {
map[key] = results[i];
return map;
}, {});
});
exports.asyncMapToObject = asyncMapToObject;
function asyncNone(array, callback) {
return __awaiter(this, void 0, void 0, function* () {
return !(yield asyncSome(array, callback));
});
}
exports.asyncNone = asyncNone;
function asyncSome(array, callback) {
return __awaiter(this, void 0, void 0, function* () {
for (const item of array) {
if (yield callback(item))
return true;
}
return false;
});
}
exports.asyncSome = asyncSome;
function asyncCount(array, callback) {
return __awaiter(this, void 0, void 0, function* () {
let n = 0;
for (const item of array) {
if (yield callback(item))
n++;
}
return n;
});
}
exports.asyncCount = asyncCount;
const flatten = (items) => {
return [].concat(...Object.values(items));
};
exports.flatten = flatten;
const arrayEquals = (a, b) => {
return (Array.isArray(a) &&
Array.isArray(b) &&
a.length === b.length &&
a.every((val, index) => val == b[index]));
};
exports.arrayEquals = arrayEquals;
const arrayExactly = (a, b) => {
return (Array.isArray(a) &&
Array.isArray(b) &&
a.length === b.length &&
a.every((val, index) => val === b[index]));
};
exports.arrayExactly = arrayExactly;
function normalizePath(uri) {
if (uri) {
uri = uri.endsWith(path.sep) ? uri : uri + path.sep;
}
return uri;
}
exports.normalizePath = normalizePath;
function ensureFolderExists(path) {
if (!fs.existsSync(path)) {
fs.mkdirSync(path, { recursive: true });
}
}
exports.ensureFolderExists = ensureFolderExists;
function emptyFolder(folderPath) {
return new Promise((resolve, reject) => {
folderPath = path.resolve(folderPath);
ensureFolderExists(folderPath);
fs.readdir(folderPath, (err, files) => {
if (err)
reject(err);
const promises = [];
for (const file of files) {
promises.push(fs.promises.unlink(path.join(folderPath, file)));
}
Promise.all(promises)
.then(() => {
resolve();
})
.catch((err) => {
reject(err);
});
});
});
}
exports.emptyFolder = emptyFolder;
function exitProcess(passed) {
process.exit(passed ? 0 : 1);
}
exports.exitProcess = exitProcess;
function getMessageAndCallbackFromOverloading(a, b, defaultMessage = "Untitled") {
const message = typeof a == "string" ? a : defaultMessage;
const callback = (() => {
if (typeof b == "function") {
return b;
}
else if (typeof a == "function") {
return a;
}
else {
return () => { };
}
})();
const scenario = (() => {
if (exports.toType(a) == "scenario") {
return a;
}
else if (exports.toType(b) == "scenario") {
return b;
}
return undefined;
})();
return {
isSubScenario: !!(a || b),
message: message,
callback: callback,
scenario: scenario,
};
}
exports.getMessageAndCallbackFromOverloading = getMessageAndCallbackFromOverloading;
const deepEqual = (thisValue, thatValue) => {
try {
nodeAssert.deepEqual(thisValue, thatValue);
return true;
}
catch (ex) {
return false;
}
};
exports.deepEqual = deepEqual;
const deepStrictEqual = (thisValue, thatValue) => {
try {
nodeAssert.deepStrictEqual(thisValue, thatValue);
return true;
}
catch (ex) {
return false;
}
};
exports.deepStrictEqual = deepStrictEqual;
const objectContains = (thisValue, thatValue) => {
return Object.keys(thatValue).every((key) => thatValue[key] == thisValue[key]);
};
exports.objectContains = objectContains;
const objectContainsKeys = (thisValue, keys) => {
return exports.toArray(keys)
.map((val) => String(val))
.every((val) => typeof thisValue[val] !== "undefined");
};
exports.objectContainsKeys = objectContainsKeys;
const nthIn = (obj, index) => {
try {
if (Array.isArray(obj)) {
return obj[index];
}
else if (typeof obj === "object" && obj !== null) {
return obj[Object.keys(obj)[index]];
}
}
catch (ex) { }
return null;
};
exports.nthIn = nthIn;
const firstIn = (obj) => {
return exports.nthIn(obj, 0);
};
exports.firstIn = firstIn;
const middleIn = (obj) => {
const index = Array.isArray(obj)
? Math.floor(obj.length / 2)
: typeof obj == "object" && obj !== null
? Math.floor(Object.keys(obj).length / 2)
: 0;
return exports.nthIn(obj, index);
};
exports.middleIn = middleIn;
const lastIn = (obj) => {
const index = Array.isArray(obj)
? obj.length - 1
: typeof obj == "object" && obj !== null
? Object.keys(obj).length - 1
: 0;
return exports.nthIn(obj, index);
};
exports.lastIn = lastIn;
const random = (min, max) => {
return Math.random() * (max - min) + min;
};
exports.random = random;
const randomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min);
};
exports.randomInt = randomInt;
const randomIn = (obj) => {
const index = Array.isArray(obj)
? exports.randomInt(0, obj.length - 1)
: typeof obj == "object" && obj !== null
? exports.randomInt(0, Object.keys(obj).length - 1)
: 0;
return exports.nthIn(obj, index);
};
exports.randomIn = randomIn;
const cast = (val) => {
return val;
};
exports.cast = cast;
const loadSchemaValidator = (schemaType, schema) => {
if (schemaType === "JsonSchema") {
const ajv = new ajv_1.default();
return ajv.compile(schema);
}
const ajv = new jtd_1.default();
return ajv.compile(schema);
};
exports.loadSchemaValidator = loadSchemaValidator;
const validateSchema = (thisValue, schema, schemaType) => {
const validator = exports.loadSchemaValidator(schemaType, schema);
const isValid = validator(thisValue);
const errors = validator.errors;
const errorMessages = [];
if (!isValid && !!errors) {
errors.forEach((err) => {
errorMessages.push(`${err.instancePath} ${err.message}`);
});
}
return errorMessages;
};
exports.validateSchema = validateSchema;
const getFunctionArgs = (func) => {
const STRIP_COMMENTS = /(\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s*=[^,\)]*(('(?:\\'|[^'\r\n])*')|("(?:\\"|[^"\r\n])*"))|(\s*=[^,\)]*))/gm;
const ARGUMENT_NAMES = /([^\s,]+)/g;
const fnStr = func.toString().replace(STRIP_COMMENTS, "");
const result = fnStr
.slice(fnStr.indexOf("(") + 1, fnStr.indexOf(")"))
.match(ARGUMENT_NAMES);
return result === null ? [] : result;
};
exports.getFunctionArgs = getFunctionArgs;
//# sourceMappingURL=util.js.map
;