Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Socket
Sign inDemoInstall

@squared-functions/module

Package Overview
Dependencies
Maintainers
1
Versions
355
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@squared-functions/module - npm Package Compare versions

Comparing version 1.2.0 to 1.2.1

355

index.js

@@ -1,2 +0,2 @@

/* @squared-functions/module 1.2.0
/* @squared-functions/module 1.2.1
https://github.com/anpham6/squared-functions */

@@ -7,23 +7,9 @@

Object.defineProperty(exports, "__esModule", { value: true });
exports.LOG_TYPE = void 0;
const types_1 = require("../types");
const path = require("path");
const fs = require("fs");
const url = require("url");
const readdirp = require("readdirp");
const uuid = require("uuid");
const chalk = require("chalk");
var LOG_TYPE;
(function (LOG_TYPE) {
LOG_TYPE[LOG_TYPE["UNKNOWN"] = 0] = "UNKNOWN";
LOG_TYPE[LOG_TYPE["SYSTEM"] = 1] = "SYSTEM";
LOG_TYPE[LOG_TYPE["NODE"] = 2] = "NODE";
LOG_TYPE[LOG_TYPE["PROCESS"] = 4] = "PROCESS";
LOG_TYPE[LOG_TYPE["COMPRESS"] = 8] = "COMPRESS";
LOG_TYPE[LOG_TYPE["WATCH"] = 16] = "WATCH";
LOG_TYPE[LOG_TYPE["FILE"] = 32] = "FILE";
LOG_TYPE[LOG_TYPE["CLOUD"] = 64] = "CLOUD";
LOG_TYPE[LOG_TYPE["TIME_ELAPSED"] = 128] = "TIME_ELAPSED";
LOG_TYPE[LOG_TYPE["TIME_PROCESS"] = 256] = "TIME_PROCESS";
LOG_TYPE[LOG_TYPE["FAIL"] = 512] = "FAIL";
LOG_TYPE[LOG_TYPE["HTTP"] = 1024] = "HTTP";
})(LOG_TYPE = exports.LOG_TYPE || (exports.LOG_TYPE = {}));
const SETTINGS = {

@@ -45,4 +31,9 @@ format: {

};
const PROCESS_VERSION = process.version.substring(1).split('.').map(value => +value);
const ASYNC_FUNCTION = Object.getPrototypeOf(async () => { }).constructor;
const [CPU_CORETIME, MEM_TOTAL] = (function () {
const lib = require('os');
const cpus = lib.cpus();
return [cpus.reduce((a, b) => a + b.times.user + b.times.sys, 0) / cpus.length, lib.totalmem()];
})();
const [VER_MAJOR, VER_MINOR, VER_PATCH] = process.version.substring(1).split('.').map(value => +value);
function allSettled(values) {

@@ -98,13 +89,13 @@ return Promise.all(values.map((promise) => promise.then(value => ({ status: 'fulfilled', value })).catch(reason => ({ status: 'rejected', reason }))));

function isFailed(options) {
if (options) {
if (options.failed) {
if (!options.titleColor && !options.titleBgColor) {
options.titleColor = 'white';
options.titleBgColor = 'bgGray';
}
return true;
if (options.failed) {
if (!options.titleColor && !options.titleBgColor) {
options.titleColor = 'white';
options.titleBgColor = 'bgGray';
}
return true;
}
return false;
}
const formatPercent = (value) => (value * 100).toPrecision(3) + '%';
const getTimeOffset = (time) => Array.isArray(time) ? Module.toTimeMs(process.hrtime(time)) : Date.now() - time;
class Module {

@@ -114,5 +105,5 @@ constructor() {

this.tempDir = 'tmp';
this.major = PROCESS_VERSION[0];
this.minor = PROCESS_VERSION[1];
this.patch = PROCESS_VERSION[2];
this.major = VER_MAJOR;
this.minor = VER_MINOR;
this.patch = VER_PATCH;
this.errors = [];

@@ -123,11 +114,11 @@ this._logEnabled = true;

static supported(major, minor = 0, patch = 0, lts) {
if (PROCESS_VERSION[0] < major) {
if (VER_MAJOR < major) {
return false;
}
else if (PROCESS_VERSION[0] === major) {
if (PROCESS_VERSION[1] < minor) {
if (VER_MAJOR === major) {
if (VER_MINOR < minor) {
return false;
}
else if (PROCESS_VERSION[1] === minor) {
return PROCESS_VERSION[2] >= patch;
if (VER_MINOR === minor) {
return VER_PATCH >= patch;
}

@@ -138,8 +129,58 @@ return true;

}
static isString(value) {
return typeof value === 'string' && value.length > 0;
}
static isObject(value) {
return typeof value === 'object' && value !== null;
}
static isString(value) {
return typeof value === 'string' && value.length > 0;
static isPlainObject(value) {
return Module.isObject(value) && (value.constructor === Object || Object.getPrototypeOf(Object(value)) === null);
}
static cloneObject(data, options) {
let target, deep;
if (options) {
({ target, deep } = options);
}
const nested = deep ? { deep } : undefined;
if (Array.isArray(data)) {
const length = data.length;
if (!target || !Array.isArray(target)) {
target = new Array(length);
}
else {
target.length = 0;
}
for (let i = 0; i < length; ++i) {
const value = data[i];
target[i] = Array.isArray(value) || deep && this.isPlainObject(value) ? this.cloneObject(value, nested) : value;
}
}
else if (this.isPlainObject(data)) {
if (!target || !this.isObject(target)) {
target = {};
}
for (const attr in data) {
const value = data[attr];
target[attr] = Array.isArray(value) || deep && this.isPlainObject(value) ? this.cloneObject(value, nested) : value;
}
}
else {
if (deep && this.isObject(data)) {
if (data instanceof Map) {
return new Map(data);
}
if (data instanceof Set) {
return new Set(data);
}
if (data instanceof Date) {
return new Date(data);
}
if (data instanceof RegExp) {
return new RegExp(data);
}
}
return data;
}
return target;
}
static generateUUID(format = '8-4-4-4-12', dictionary) {

@@ -171,15 +212,15 @@ const match = format.match(/(\d+|[^\d]+)/g);

}
else if (value & LOG_TYPE.FAIL) {
else if (value & 512 /* FAIL */) {
return true;
}
else if ((value & LOG_TYPE.SYSTEM) && SETTINGS.system === false ||
(value & LOG_TYPE.NODE) && SETTINGS.node === false ||
(value & LOG_TYPE.PROCESS) && SETTINGS.process === false ||
(value & LOG_TYPE.COMPRESS) && SETTINGS.compress === false ||
(value & LOG_TYPE.WATCH) && SETTINGS.watch === false ||
(value & LOG_TYPE.FILE) && SETTINGS.file === false ||
(value & LOG_TYPE.CLOUD) && SETTINGS.cloud === false ||
(value & LOG_TYPE.TIME_ELAPSED) && SETTINGS.time_elapsed === false ||
(value & LOG_TYPE.TIME_PROCESS) && SETTINGS.time_process === false ||
(value & LOG_TYPE.HTTP) && SETTINGS.http === false) {
else if ((value & 1 /* SYSTEM */) && SETTINGS.system === false ||
(value & 2 /* NODE */) && SETTINGS.node === false ||
(value & 4 /* PROCESS */) && SETTINGS.process === false ||
(value & 8 /* COMPRESS */) && SETTINGS.compress === false ||
(value & 16 /* WATCH */) && SETTINGS.watch === false ||
(value & 32 /* FILE */) && SETTINGS.file === false ||
(value & 64 /* CLOUD */) && SETTINGS.cloud === false ||
(value & 128 /* TIME_ELAPSED */) && SETTINGS.time_elapsed === false ||
(value & 256 /* TIME_PROCESS */) && SETTINGS.time_process === false ||
(value & 1024 /* HTTP */) && SETTINGS.http === false) {
return false;

@@ -199,4 +240,4 @@ }

const useColor = () => !(options && options.useColor === false || SETTINGS.color === false);
let valueWidth = getFormatWidth(format.value, 71 /* VALUE */), titleJustify = (type & LOG_TYPE.FAIL) || options.failed ? 'center' : getFormatJustify(format.title, 'right');
if (type & LOG_TYPE.SYSTEM) {
let valueWidth = getFormatWidth(format.value, 71 /* VALUE */), titleJustify = (type & 512 /* FAIL */) || options.failed ? 'center' : getFormatJustify(format.title, 'right');
if (type & 1 /* SYSTEM */) {
if (options.titleBgColor) {

@@ -206,3 +247,3 @@ titleJustify = 'center';

}
if (type & LOG_TYPE.NODE) {
if (type & 2 /* NODE */) {
options.titleColor || (options.titleColor = 'black');

@@ -213,9 +254,9 @@ options.titleBgColor || (options.titleBgColor = 'bgWhite');

}
if (type & LOG_TYPE.PROCESS) {
if (type & 4 /* PROCESS */) {
options.titleColor || (options.titleColor = 'magenta');
}
if (type & LOG_TYPE.WATCH) {
if (type & 16 /* WATCH */) {
titleJustify = 'center';
}
if (type & LOG_TYPE.TIME_ELAPSED) {
if (type & 128 /* TIME_ELAPSED */) {
if (options.titleBgColor) {

@@ -226,6 +267,6 @@ titleJustify = 'center';

}
if (type & LOG_TYPE.TIME_PROCESS) {
if (type & 256 /* TIME_PROCESS */) {
options.messageBgColor || (options.messageBgColor = options.failed ? 'bgGray' : 'bgCyan');
}
if (type & LOG_TYPE.HTTP) {
if (type & 1024 /* HTTP */) {
options.titleColor || (options.titleColor = 'white');

@@ -272,3 +313,3 @@ options.titleBgColor || (options.titleBgColor = options.failed ? 'bgGray' : 'bgGreen');

}
const unit = options.messageUnit ? ' ' + options.messageUnit : '';
const unit = options.messageUnit ? type & 256 /* TIME_PROCESS */ ? options.messageUnit + ' ' : ' ' + options.messageUnit : '';
title = applyFormatPadding(title.toUpperCase(), getFormatWidth(format.title, 6 /* TITLE */ + 1), titleJustify, 1);

@@ -300,3 +341,3 @@ let output, error;

}
m = ' ' + (error ? chalk.redBright('{') + chalk.bgWhite.blackBright(m) + chalk.grey(unit) + chalk.redBright('}') : chalk.blackBright('(') + m + chalk.grey(unit) + chalk.blackBright(')'));
m = ' ' + (error ? chalk.redBright('{') + chalk.bgWhite.blackBright(m) + chalk.redBright('}') : chalk.blackBright('(') + (type & 256 /* TIME_PROCESS */ ? chalk.grey(unit) + m : m + chalk.grey(unit)) + chalk.blackBright(')'));
}

@@ -319,7 +360,7 @@ else {

}
output || (output = title + ': ' + value + (message && SETTINGS.message !== false ? ' ' + (error ? '{' : '(') + message + unit + (error ? '}' : ')') : ''));
console[(type & LOG_TYPE.FAIL) && (type & LOG_TYPE.FILE) ? 'error' : 'log'](output);
output || (output = title + ': ' + value + (message && SETTINGS.message !== false ? ' ' + (error ? '{' : '(') + (type & 256 /* TIME_PROCESS */ ? unit + message : message + unit) + (error ? '}' : ')') : ''));
console[(type & 512 /* FAIL */) && (type & 32 /* FILE */) ? 'error' : 'log'](output);
}
static writeFail(value, message, type) {
this.formatMessage(type || LOG_TYPE.SYSTEM, 'FAIL!', value, message, { ...Module.LOG_STYLE_FAIL });
this.formatMessage(type || 1 /* SYSTEM */, 'FAIL!', value, message, { ...Module.LOG_STYLE_FAIL });
}

@@ -350,3 +391,3 @@ static asFunction(value, sync = true) {

catch (err) {
this.writeFail(["Unable to read file" /* READ_FILE */, uri], err, LOG_TYPE.FILE);
this.writeFail(["Unable to read file" /* READ_FILE */, uri], err, 32 /* FILE */);
return;

@@ -373,2 +414,5 @@ }

}
static toTimeMs(hrtime) {
return Math.ceil((hrtime[0] * 1000000000 + hrtime[1]) / 1000000);
}
static renameExt(value, ext) {

@@ -437,11 +481,23 @@ const index = value.lastIndexOf('.');

try {
let url = new URL(value).pathname;
if (path.isAbsolute(url)) {
if (path.sep === '\\' && /^\/[A-Za-z]:\//.test(url)) {
url = url.substring(1);
return url.fileURLToPath(value);
}
catch (_a) {
}
try {
const file = new URL(value);
let pathname = file.pathname;
if (value[7] !== '/') {
if (path.sep === '\\') {
pathname = `\\\\${file.host}\\` + pathname.substring(1);
}
return path.resolve(url);
else {
return '';
}
}
else if (path.sep === '\\' && /^\/[A-Za-z]:\//.test(pathname)) {
pathname = pathname.substring(1);
}
return path.resolve(decodeURIComponent(pathname));
}
catch (_a) {
catch (_b) {
}

@@ -458,6 +514,5 @@ return '';

try {
const url = new URL(href);
const origin = url.origin;
const pathname = url.pathname.split('/');
--pathname.length;
const { origin, pathname } = new URL(href);
const segments = pathname.split('/');
--segments.length;
value = this.toPosix(value);

@@ -472,3 +527,3 @@ if (value[0] === '/') {

if (trailing.length === 0) {
pathname.pop();
segments.pop();
}

@@ -485,3 +540,3 @@ else {

}
return Module.joinPath(origin, pathname.join('/'), value);
return Module.joinPath(origin, segments.join('/'), value);
}

@@ -540,3 +595,3 @@ catch (_a) {

catch (err) {
if (!this.isErrorCode(err, 'EEXIST', 'EPERM')) {
if (!this.isErrorCode(err, 'EEXIST')) {
return false;

@@ -559,3 +614,3 @@ }

catch (err) {
this.writeFail(["Unable to create directory" /* CREATE_DIRECTORY */, value], err, LOG_TYPE.FILE);
this.writeFail(["Unable to create directory" /* CREATE_DIRECTORY */, value], err, 32 /* FILE */);
}

@@ -618,3 +673,3 @@ return false;

if (file.isDirectory()) {
this.writeFail(["Unable to remove directory" /* REMOVE_DIRECTORY */, fullpath], err, LOG_TYPE.FILE);
this.writeFail(["Unable to remove directory" /* REMOVE_DIRECTORY */, fullpath], err, 32 /* FILE */);
}

@@ -625,3 +680,3 @@ ++failed;

if (failed) {
this.formatMessage(LOG_TYPE.FILE, 'WARN!', ["Unable to remove directory" /* REMOVE_DIRECTORY */, failed + ' error' + (failed > 1 ? 's' : '')], '', { titleBgColor: 'bgGray', titleColor: 'yellow' });
this.formatMessage(32 /* FILE */, 'WARN!', ["Unable to remove directory" /* REMOVE_DIRECTORY */, failed + ' error' + (failed > 1 ? 's' : '')], '', { titleBgColor: 'bgGray', titleColor: 'yellow' });
}

@@ -634,3 +689,3 @@ else if (!empty) {

catch (err) {
this.writeFail(["Unable to remove directory" /* REMOVE_DIRECTORY */, value], err, LOG_TYPE.FILE);
this.writeFail(["Unable to remove directory" /* REMOVE_DIRECTORY */, value], err, 32 /* FILE */);
}

@@ -640,36 +695,44 @@ return false;

static async copyDir(src, dest, move) {
dest = this.normalizePath(dest, true);
if (!this.createDir(dest)) {
return;
}
src = this.normalizePath(src, true);
const tasks = [];
const success = [];
const failed = [];
const methodName = move ? 'rename' : 'copyFile';
for (const { fullPath } of await readdirp.promise(src, { depth: Infinity })) {
const destFile = path.join(dest, fullPath.substring(src.length));
if (this.createDir(path.dirname(destFile))) {
tasks.push(new Promise(resolve => {
fs[methodName](fullPath, destFile, err => {
if (err) {
failed.push(fullPath);
this.writeFail(["Unable to move file" /* MOVE_FILE */, fullPath], err, this.LOG_TYPE.FILE);
}
else {
success.push(destFile);
}
resolve();
});
return new Promise(async (resolve, reject) => {
if (!this.createDir(dest = this.normalizePath(dest, true))) {
reject(new Error('Unknown: ' + dest));
return;
}
const tasks = [];
const success = [];
const failed = [];
const methodName = move ? 'rename' : 'copyFile';
readdirp(src = this.normalizePath(src, true), { depth: Infinity })
.on('data', (entry) => {
tasks.push(new Promise(complete => {
const fullPath = entry.fullPath;
const destFile = path.join(dest, entry.path);
if (this.createDir(path.dirname(destFile))) {
fs[methodName](fullPath, destFile, err => {
if (err) {
failed.push(fullPath);
this.writeFail(["Unable to move file" /* MOVE_FILE */, fullPath], err, 32 /* FILE */);
}
else {
success.push(destFile);
}
complete();
});
}
else {
failed.push(fullPath);
complete();
}
}));
}
else {
failed.push(fullPath);
}
}
await Promise.all(tasks);
if (move && failed.length === 0) {
this.removeDir(src);
}
return { success, failed };
})
.on('error', err => reject(err))
.on('end', () => {
Promise.all(tasks).then(() => {
if (move && failed.length === 0) {
this.removeDir(src);
}
resolve({ success, failed });
});
});
});
}

@@ -693,3 +756,3 @@ static existsSafe(value) {

catch (err) {
this.writeFail(["Unable to read file" /* READ_FILE */, value], err, this.LOG_TYPE.FILE);
this.writeFail(["Unable to read file" /* READ_FILE */, value], err, 32 /* FILE */);
}

@@ -707,2 +770,18 @@ }

}
static getCpuUsage(previous, format) {
const { user, system } = process.cpuUsage(previous);
const result = (user + system) / CPU_CORETIME;
return format ? formatPercent(result) : result;
}
static getMemUsage(format) {
const usage = process.memoryUsage();
let result = 0;
for (const name in usage) {
if (name !== 'heapUsed') {
result += usage[name];
}
}
result /= MEM_TOTAL;
return format ? formatPercent(result) : result;
}
static cleanupStream(writable, uri) {

@@ -714,7 +793,9 @@ if (!writable.destroyed) {

try {
fs.unlinkSync(uri);
if (fs.existsSync(uri)) {
fs.unlinkSync(uri);
}
}
catch (err) {
if (!this.isErrorCode(err, 'ENOENT')) {
this.writeFail(["Unable to delete file" /* DELETE_FILE */, uri], err, LOG_TYPE.FILE);
this.writeFail(["Unable to delete file" /* DELETE_FILE */, uri], err, 32 /* FILE */);
}

@@ -799,21 +880,39 @@ }

}
writeFail(value, message, type = LOG_TYPE.SYSTEM) {
type |= LOG_TYPE.FAIL;
writeFail(value, message, type = 1 /* SYSTEM */) {
type |= 512 /* FAIL */;
this.formatFail(type, 'FAIL!', value, message);
}
writeTimeProcess(title, value, time, options = {}) {
time = Date.now() - time;
var _a;
const offset = getTimeOffset(time);
const failed = isFailed(options);
const meter = (failed ? 'X' : '>').repeat(Math.ceil(time / (options.meterIncrement || 250)));
const args = [LOG_TYPE.TIME_PROCESS, title, [((options.type || 0) & LOG_TYPE.HTTP ? '' : (failed ? 'Failed' : 'Completed') + ' -> ') + value, (time / 1000) + 's'], meter, options];
if (options && options.queue) {
const args = [
256 /* TIME_PROCESS */,
title,
[((options.type || 0) & 1024 /* HTTP */ ? '' : (failed ? 'Failed' : 'Completed') + ' -> ') + value, (offset / 1000) + 's'],
(failed ? 'X' : '>').repeat(Math.ceil(offset / (options.meterIncrement || 250))),
options
];
if (options.queue) {
this._logQueued.push(args);
}
else {
if (!options.messageUnit) {
const startCPU = options.startCPU || ((_a = this.host) === null || _a === void 0 ? void 0 : _a.startCPU);
if (startCPU) {
options.messageUnit = Module.getCpuUsage(startCPU, true) + ` CPU ${Module.getMemUsage(true)} MEM`;
}
}
Module.formatMessage(...args);
}
}
writeTimeElapsed(title, value, time, options) {
const args = [LOG_TYPE.TIME_ELAPSED, title, [isFailed(options) ? 'Failed' : 'Completed', (Date.now() - time) / 1000 + 's'], value, options];
if (options && options.queue) {
writeTimeElapsed(title, value, time, options = {}) {
const args = [
128 /* TIME_ELAPSED */,
title,
[isFailed(options) ? 'Failed' : 'Completed', getTimeOffset(time) / 1000 + 's'],
value,
options
];
if (options.queue) {
this._logQueued.push(args);

@@ -826,5 +925,5 @@ }

formatFail(type, title, value, message, options = {}) {
type |= LOG_TYPE.FAIL;
type |= 512 /* FAIL */;
const args = [type, title, value, message, applyFailStyle(options)];
if (options && options.queue !== false) {
if (options.queue !== false) {
this._logQueued.push(args);

@@ -839,5 +938,5 @@ }

}
formatMessage(type, title, value, message, options) {
formatMessage(type, title, value, message, options = {}) {
const args = [type, title, value, message, options];
if (options && options.queue) {
if (options.queue) {
this._logQueued.push(args);

@@ -860,6 +959,6 @@ }

get logType() {
return LOG_TYPE;
return types_1.LOG_TYPE;
}
}
Module.LOG_TYPE = LOG_TYPE;
Module.LOG_TYPE = types_1.LOG_TYPE;
Module.LOG_STYLE_FAIL = { titleColor: 'white', titleBgColor: 'bgRed' };

@@ -866,0 +965,0 @@ Module.MAX_TIMEOUT = 2147483647;

{
"name": "@squared-functions/module",
"version": "1.2.0",
"version": "1.2.1",
"description": "Module extension class for squared-functions",

@@ -18,3 +18,3 @@ "main": "index.js",

"dependencies": {
"@squared-functions/types": "^1.2.0",
"@squared-functions/types": "^1.2.1",
"uuid": "^8.3.2",

@@ -21,0 +21,0 @@ "chalk": "^4.1.2"

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc