@squared-functions/module
Advanced tools
Comparing version 1.2.7 to 2.0.0
578
index.js
@@ -1,6 +0,5 @@ | ||
/* @squared-functions/module 1.2.7 | ||
/* @squared-functions/module 2.0.0 | ||
https://github.com/anpham6/squared-functions */ | ||
"use strict"; | ||
/* eslint no-console: "off" */ | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
@@ -10,4 +9,6 @@ const types_1 = require("../types"); | ||
const fs = require("fs"); | ||
const EventEmitter = require("events"); | ||
const url = require("url"); | ||
const readdirp = require("readdirp"); | ||
const bytes = require("bytes"); | ||
const uuid = require("uuid"); | ||
@@ -29,5 +30,18 @@ const chalk = require("chalk"); | ||
message: {} | ||
}, | ||
meter: { | ||
http: 100, | ||
image: 250, | ||
process: 250 | ||
}, | ||
session_id: 0, | ||
process: { | ||
cpu: true, | ||
cpu_single_core: true, | ||
mem: true, | ||
mem_format: '%' | ||
} | ||
}; | ||
const ASYNC_FUNCTION = Object.getPrototypeOf(async () => { }).constructor; | ||
let ERROR_MODULE = null; | ||
const [CPU_CORETIME, CPU_CORETOTAL, MEM_TOTAL] = (function () { | ||
@@ -39,5 +53,2 @@ const lib = require('os'); | ||
const [VER_MAJOR, VER_MINOR, VER_PATCH] = process.version.substring(1).split('.').map(value => +value); | ||
function allSettled(values) { | ||
return Promise.all(values.map((promise) => promise.then(value => ({ status: 'fulfilled', value })).catch(reason => ({ status: 'rejected', reason })))); | ||
} | ||
function applyFailStyle(options) { | ||
@@ -69,10 +80,10 @@ for (const attr in Module.LOG_STYLE_FAIL) { | ||
} | ||
function getFormatWidth(format, fallback) { | ||
function getFormatWidth(format, fallback, offset = 0) { | ||
if (format) { | ||
const value = format.width; | ||
if (typeof value === 'number' && value > 0) { | ||
return value; | ||
return value - offset; | ||
} | ||
} | ||
return fallback; | ||
return fallback - offset; | ||
} | ||
@@ -100,13 +111,69 @@ function getFormatJustify(format, fallback) { | ||
} | ||
function formatHint(value, options) { | ||
let { hintColor, hintBgColor } = options; | ||
if (!hintColor && !hintBgColor) { | ||
({ color: hintColor, bgColor: hintBgColor } = SETTINGS.format.hint); | ||
} | ||
try { | ||
let result = value; | ||
if (hintColor) { | ||
result = chalk[hintColor](result); | ||
} | ||
if (hintBgColor) { | ||
result = chalk[hintBgColor](result); | ||
} | ||
return result; | ||
} | ||
catch (_a) { | ||
} | ||
return value; | ||
} | ||
function filterAllSettled(tasks, rejected, type) { | ||
const promise = Promise.allSettled ? Promise.allSettled(tasks) : Promise.all(tasks.map((task) => task.then(value => ({ status: 'fulfilled', value })).catch(reason => ({ status: 'rejected', reason })))); | ||
if (rejected) { | ||
promise.then(result => { | ||
const items = []; | ||
for (const item of result) { | ||
if (item.status === 'rejected') { | ||
this.writeFail(rejected, item.reason, type); | ||
} | ||
else { | ||
items.push(item); | ||
} | ||
} | ||
return items; | ||
}) | ||
.catch(err => this.writeFail(rejected, err, type)); | ||
} | ||
return promise; | ||
} | ||
function asErrorObject(message) { | ||
if (message instanceof Error) { | ||
return message; | ||
} | ||
switch (typeof message) { | ||
case 'string': | ||
return new Error(message); | ||
case 'number': | ||
return new Error(`Error code (${message})`); | ||
} | ||
try { | ||
return new Error(message.toString()); | ||
} | ||
catch (_a) { | ||
} | ||
return new Error('Unknown'); | ||
} | ||
const formatPercent = (value) => (value * 100).toPrecision(3) + '%'; | ||
const getTimeOffset = (time) => Array.isArray(time) ? Module.toTimeMs(process.hrtime(time)) : Date.now() - time; | ||
class Module { | ||
class Module extends EventEmitter { | ||
constructor() { | ||
super(...arguments); | ||
this.moduleName = 'unknown'; | ||
this.sessionId = ''; | ||
this.tempDir = 'tmp'; | ||
this.major = VER_MAJOR; | ||
this.minor = VER_MINOR; | ||
this.patch = VER_PATCH; | ||
this.errors = []; | ||
this._logEnabled = true; | ||
this._host = null; | ||
this._permission = null; | ||
this._logQueued = []; | ||
@@ -136,3 +203,3 @@ } | ||
static isPlainObject(value) { | ||
return Module.isObject(value) && (value.constructor === Object || Object.getPrototypeOf(Object(value)) === null); | ||
return this.isObject(value) && (value.constructor === Object || Object.getPrototypeOf(Object(value)) === null); | ||
} | ||
@@ -237,16 +304,18 @@ static cloneObject(data, options) { | ||
} | ||
static generateUUID(format = '8-4-4-4-12', dictionary) { | ||
const match = format.match(/(\d+|[^\d]+)/g); | ||
if (match) { | ||
dictionary || (dictionary = '0123456789abcdef'); | ||
return match.reduce((a, b) => { | ||
const length = +b; | ||
if (!isNaN(length)) { | ||
for (let i = 0, j = dictionary.length; i < length; ++i) { | ||
a += dictionary[Math.floor(Math.random() * j)]; | ||
static generateUUID(format, dictionary) { | ||
if (format && (format !== '8-4-4-4-12' || dictionary)) { | ||
const match = format.match(/(\d+|[^\d]+)/g); | ||
if (match) { | ||
dictionary || (dictionary = '0123456789abcdef'); | ||
return match.reduce((a, b) => { | ||
const length = +b; | ||
if (!isNaN(length)) { | ||
for (let i = 0, j = dictionary.length; i < length; ++i) { | ||
a += dictionary[Math.floor(Math.random() * j)]; | ||
} | ||
return a; | ||
} | ||
return a; | ||
} | ||
return a + b; | ||
}, ''); | ||
return a + b; | ||
}, ''); | ||
} | ||
} | ||
@@ -256,3 +325,10 @@ return uuid.v4(); | ||
static escapePattern(value) { | ||
return this.isString(value) ? value.replace(/[-|\\{}()[\]^$+*?.]/g, capture => capture === '-' ? '\\x2d' : '\\' + capture) : ''; | ||
switch (typeof value) { | ||
case 'string': | ||
return value.replace(/[-|\\{}()[\]^$+*?.]/g, capture => capture === '-' ? '\\x2d' : '\\' + capture); | ||
case 'number': | ||
return value.toString(); | ||
default: | ||
return ''; | ||
} | ||
} | ||
@@ -274,3 +350,4 @@ static hasLogType(value) { | ||
(value & 256 /* TIME_PROCESS */) && SETTINGS.time_process === false || | ||
(value & 1024 /* HTTP */) && SETTINGS.http === false) { | ||
(value & 1024 /* HTTP */) && SETTINGS.http === false || | ||
(value & 2048 /* IMAGE */) && SETTINGS.image === false) { | ||
return false; | ||
@@ -284,2 +361,10 @@ } | ||
} | ||
const sessionId = options.sessionId; | ||
if (ERROR_MODULE && (type & 512 /* FAIL */)) { | ||
try { | ||
ERROR_MODULE.call(process, asErrorObject(message), { type: type & ~512 /* FAIL */, value, timeStamp: options.timeStamp || Date.now(), sessionId }, require); | ||
} | ||
catch (_a) { | ||
} | ||
} | ||
if (!this.hasLogType(type)) { | ||
@@ -289,5 +374,15 @@ return; | ||
const format = SETTINGS.format; | ||
const unit = options.messageUnit ? type & 256 /* TIME_PROCESS */ ? options.messageUnit.padStart(options.messageUnitMinWidth || 0) + ' ' : ' ' + options.messageUnit : ''; | ||
const id = sessionId && SETTINGS.session_id ? ' ' + sessionId.padStart(SETTINGS.session_id, '0') + ' ' : ''; | ||
let output, error, hint, valueWidth = getFormatWidth(format.value, 71 /* VALUE */, id ? SETTINGS.session_id + 1 : 0), hintWidth = getFormatWidth(format.hint, 32 /* HINT */), titleJustify = (type & 512 /* FAIL */) || options.failed ? 'center' : getFormatJustify(format.title, 'right'); | ||
if (Array.isArray(value)) { | ||
[value, hint] = value; | ||
} | ||
if (message instanceof Error) { | ||
message = SETTINGS.stack_trace && message.stack || message.message; | ||
error = true; | ||
} | ||
const truncateString = (segment, length) => segment.length > length ? '...' + segment.substring(segment.length - length + 3) : segment; | ||
const useColor = () => !(options && options.useColor === false || SETTINGS.color === false); | ||
let valueWidth = getFormatWidth(format.value, 71 /* VALUE */), titleJustify = (type & 512 /* FAIL */) || options.failed ? 'center' : getFormatJustify(format.title, 'right'); | ||
const getValue = () => applyFormatPadding(truncateString(value, valueWidth - 1), valueWidth, getFormatJustify(format.value)); | ||
if (type & 1 /* SYSTEM */) { | ||
@@ -323,47 +418,15 @@ if (options.titleBgColor) { | ||
} | ||
if (Array.isArray(value)) { | ||
const [leading, hint] = value; | ||
if (this.isString(hint)) { | ||
let hintWidth = getFormatWidth(format.hint, 32 /* HINT */); | ||
const formatHint = (content) => { | ||
let { hintColor, hintBgColor } = options; | ||
if (!hintColor && !hintBgColor) { | ||
({ color: hintColor, bgColor: hintBgColor } = format.hint); | ||
} | ||
try { | ||
let output = content; | ||
if (hintColor) { | ||
output = chalk[hintColor](output); | ||
} | ||
if (hintBgColor) { | ||
output = chalk[hintBgColor](output); | ||
} | ||
return output; | ||
} | ||
catch (_a) { | ||
} | ||
return content; | ||
}; | ||
valueWidth -= Math.min(hint.length, hintWidth) + 2; | ||
if (hint.length > hintWidth && leading.length + 1 < valueWidth) { | ||
const offset = Math.min(valueWidth - (leading.length + 1), hint.length - hintWidth); | ||
hintWidth += offset; | ||
valueWidth -= offset; | ||
} | ||
value = applyFormatPadding(truncateString(leading, valueWidth - 1), valueWidth, getFormatJustify(format.value)) + (useColor() ? chalk.blackBright('[') + formatHint(truncateString(hint, hintWidth)) + chalk.blackBright(']') : `[${truncateString(hint, hintWidth)}]`); | ||
if (hint) { | ||
valueWidth -= Math.min(hint.length, hintWidth) + 2; | ||
if (hint.length > hintWidth && value.length + 1 < valueWidth) { | ||
const offset = Math.min(valueWidth - (value.length + 1), hint.length - hintWidth); | ||
hintWidth += offset; | ||
valueWidth -= offset; | ||
} | ||
else { | ||
value = applyFormatPadding(truncateString(leading, valueWidth - 1), valueWidth, getFormatJustify(format.value)); | ||
} | ||
value = getValue() + (useColor() ? chalk.blackBright('[') + formatHint(truncateString(hint, hintWidth), options) + chalk.blackBright(']') : `[${truncateString(hint, hintWidth)}]`); | ||
} | ||
else { | ||
value = applyFormatPadding(truncateString(value, valueWidth - 1), valueWidth, getFormatJustify(format.value)); | ||
value = getValue(); | ||
} | ||
const unit = options.messageUnit ? type & 256 /* TIME_PROCESS */ ? options.messageUnit + ' ' : ' ' + options.messageUnit : ''; | ||
title = applyFormatPadding(title.toUpperCase(), getFormatWidth(format.title, 6 /* TITLE */ + 1), titleJustify, 1); | ||
let output, error; | ||
if (message instanceof Error) { | ||
message = SETTINGS.stack_trace && message.stack || message.message; | ||
error = true; | ||
} | ||
if (useColor()) { | ||
@@ -389,3 +452,3 @@ let { titleColor, titleBgColor, valueColor, valueBgColor, messageColor, messageBgColor } = options; | ||
} | ||
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(')')); | ||
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(')'); | ||
} | ||
@@ -402,3 +465,3 @@ else { | ||
} | ||
output = chalk[titleBgColor || 'bgBlack'].bold[titleColor || 'green'](title) + chalk.blackBright(':') + ' ' + v + m; | ||
output = chalk[titleBgColor || 'bgBlack'].bold[titleColor || 'green'](title) + chalk.blackBright(':') + ' ' + v + (id ? chalk.bgBlue(chalk.white(id)) : ' ') + m; | ||
} | ||
@@ -409,7 +472,7 @@ catch (err) { | ||
} | ||
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); | ||
output || (output = title + ': ' + value + (id ? id : ' ') + (message && SETTINGS.message !== false ? (error ? '{' : '(') + (type & 256 /* TIME_PROCESS */ ? unit + message : message + unit) + (error ? '}' : ')') : '')); | ||
console[(type & 512 /* FAIL */) && (type & 32 /* FILE */) ? 'error' : 'log'](output); // eslint-disable-line no-console | ||
} | ||
static writeFail(value, message, type = 1 /* SYSTEM */) { | ||
this.formatMessage(type, 'FAIL!', value, message, { ...Module.LOG_STYLE_FAIL }); | ||
this.formatMessage((type | 512 /* FAIL */), 'FAIL!', value, message, { ...this.LOG_STYLE_FAIL }); | ||
} | ||
@@ -432,2 +495,3 @@ static asFunction(value, sync = true) { | ||
} | ||
return null; | ||
} | ||
@@ -442,7 +506,7 @@ static parseFunction(value, name, absolute, sync = true) { | ||
const handler = require(value); | ||
return typeof handler === 'function' && handler.name === name ? handler : undefined; | ||
return typeof handler === 'function' && handler.name === name ? handler : null; | ||
} | ||
catch (err) { | ||
this.writeFail(["Install required?" /* INSTALL */, value], err); | ||
return; | ||
return null; | ||
} | ||
@@ -457,3 +521,3 @@ } | ||
this.writeFail(["Unable to read file" /* READ_FILE */, uri], err, 32 /* FILE */); | ||
return; | ||
return null; | ||
} | ||
@@ -471,3 +535,3 @@ } | ||
const index = value.lastIndexOf('.'); | ||
return (index !== -1 ? value.substring(0, index) : value) + (ext[0] === ':' ? ext + path.extname(value) : '.' + ext); | ||
return (index !== -1 ? value.substring(0, index) : value) + '.' + ext; | ||
} | ||
@@ -479,3 +543,9 @@ static fromLocalPath(value) { | ||
try { | ||
return new URL(value).origin === new URL(other).origin; | ||
if (typeof value === 'string') { | ||
value = new URL(value); | ||
} | ||
if (typeof other === 'string') { | ||
other = new URL(other); | ||
} | ||
return value.origin === other.origin; | ||
} | ||
@@ -532,8 +602,6 @@ catch (_a) { | ||
static resolveUri(value) { | ||
if ((value = value.trim()).startsWith('file://')) { | ||
try { | ||
if (value.startsWith('file://')) { | ||
if (this.supported(10, 12)) { | ||
return url.fileURLToPath(value); | ||
} | ||
catch (_a) { | ||
} | ||
try { | ||
@@ -555,3 +623,3 @@ const file = new URL(value); | ||
} | ||
catch (_b) { | ||
catch (_a) { | ||
} | ||
@@ -563,37 +631,38 @@ return ''; | ||
static resolvePath(value, href) { | ||
if ((value = value.trim()).startsWith('http')) { | ||
if (value.startsWith('http')) { | ||
return value; | ||
} | ||
if (href.startsWith('http')) { | ||
if (typeof href === 'string') { | ||
try { | ||
const { origin, pathname } = new URL(href); | ||
const segments = pathname.split('/'); | ||
--segments.length; | ||
value = this.toPosix(value); | ||
if (value[0] === '/') { | ||
return origin + value; | ||
} | ||
if (value.startsWith('../')) { | ||
const trailing = []; | ||
for (const dir of value.split('/')) { | ||
if (dir === '..') { | ||
if (trailing.length === 0) { | ||
segments.pop(); | ||
} | ||
else { | ||
--trailing.length; | ||
} | ||
} | ||
else { | ||
trailing.push(dir); | ||
} | ||
} | ||
value = trailing.join('/'); | ||
} | ||
return Module.joinPath(origin, segments.join('/'), value); | ||
href = new URL(href); | ||
} | ||
catch (_a) { | ||
return ''; | ||
} | ||
} | ||
return ''; | ||
const { origin, pathname } = href; | ||
const segments = pathname.split('/'); | ||
--segments.length; | ||
value = this.toPosix(value); | ||
if (value[0] === '/') { | ||
return origin + value; | ||
} | ||
if (value.startsWith('../')) { | ||
const trailing = []; | ||
for (const dir of value.split('/')) { | ||
if (dir === '..') { | ||
if (trailing.length === 0) { | ||
segments.pop(); | ||
} | ||
else { | ||
--trailing.length; | ||
} | ||
} | ||
else { | ||
trailing.push(dir); | ||
} | ||
} | ||
value = trailing.join('/'); | ||
} | ||
return this.joinPath(origin, segments.join('/'), value); | ||
} | ||
@@ -619,10 +688,33 @@ static joinPath(...values) { | ||
} | ||
static createDir(value) { | ||
static createDir(value, permission, create = true) { | ||
if (!path.isAbsolute(value)) { | ||
return false; | ||
} | ||
if (permission) { | ||
if (this.isPathUNC(value)) { | ||
if (!permission.hasUNCWrite(value)) { | ||
throw new Error('UNC write is not permitted.'); | ||
} | ||
} | ||
else if (!permission.hasDiskWrite(value)) { | ||
throw new Error('Disk write is not permitted.'); | ||
} | ||
if (!create) { | ||
if (this.existsSafe(value)) { | ||
try { | ||
return fs.lstatSync(value).isDirectory(); | ||
} | ||
catch (_a) { | ||
} | ||
} | ||
return false; | ||
} | ||
} | ||
try { | ||
return fs.lstatSync(value).isDirectory(); | ||
} | ||
catch (_a) { | ||
catch (err) { | ||
if (this.isErrorCode(err, 'EBUSY', 'EPERM')) { | ||
return false; | ||
} | ||
} | ||
@@ -800,3 +892,3 @@ try { | ||
static readFileSafe(value, encoding = 'utf-8') { | ||
if (path.isAbsolute(value = path.resolve(value)) && this.existsSafe(value)) { | ||
if (this.existsSafe(value = path.resolve(value))) { | ||
try { | ||
@@ -811,3 +903,6 @@ return fs.readFileSync(value, encoding === 'buffer' ? undefined : encoding); | ||
} | ||
static getFileSize(value) { | ||
static byteLength(value, encoding) { | ||
return typeof value === 'string' && path.isAbsolute(value) ? this.getSize(value) : Buffer.byteLength(value, encoding); | ||
} | ||
static getSize(value) { | ||
try { | ||
@@ -820,5 +915,8 @@ return fs.statSync(value).size; | ||
} | ||
static getCpuUsage(previous, format) { | ||
const { user, system } = process.cpuUsage(previous); | ||
const result = (user + system) / (CPU_CORETIME * CPU_CORETOTAL); | ||
static formatSize(value, options) { | ||
return typeof value === 'number' ? bytes(value, options) : bytes(value); | ||
} | ||
static getCpuUsage(start, format) { | ||
const { system, user } = process.cpuUsage(start); | ||
const result = (user + system) / (CPU_CORETIME * (SETTINGS.process.cpu_single_core ? CPU_CORETOTAL : 1)); | ||
return format ? formatPercent(result) : result; | ||
@@ -834,8 +932,61 @@ } | ||
} | ||
if (typeof format === 'string') { | ||
const unit = format.toUpperCase(); | ||
switch (unit) { | ||
case 'B': | ||
case 'KB': | ||
return bytes(result, { unit, decimalPlaces: 0 }); | ||
case 'MB': | ||
return bytes(result, { unit, decimalPlaces: 1 }); | ||
case 'GB': | ||
case 'TB': | ||
case 'PB': | ||
return bytes(result, { unit }); | ||
} | ||
} | ||
return format ? formatPercent(result / MEM_TOTAL) : result; | ||
} | ||
static getPackageVersion(value) { | ||
try { | ||
const { name, version } = JSON.parse(fs.readFileSync(path.resolve(`./node_modules/${value}/package.json`), 'utf-8')); | ||
if (name === value && typeof version === 'string') { | ||
return version.trim(); | ||
} | ||
} | ||
catch (_a) { | ||
} | ||
return '0.0.0'; | ||
} | ||
static checkSemVer(name, min = 0, max = Infinity) { | ||
const minVersion = typeof min === 'string' ? min.split('.').map(ver => parseInt(ver)) : [min]; | ||
const maxVersion = typeof max === 'string' ? max.split('.').map(ver => parseInt(ver)) : [max]; | ||
let version = this.getPackageVersion(name); | ||
if (version === '0.0.0') { | ||
return false; | ||
} | ||
version = version.split('.').map(ver => parseInt(ver)); | ||
for (let i = 0, length = Math.max(version.length, minVersion.length); i < length; ++i) { | ||
const ver = version[i]; | ||
min = minVersion[i] || 0; | ||
max = maxVersion[i]; | ||
if (ver === undefined) { | ||
if (min > 0) { | ||
return false; | ||
} | ||
} | ||
else if (ver < min) { | ||
return false; | ||
} | ||
else if (ver > min) { | ||
length = version.length; | ||
minVersion.length = 0; | ||
} | ||
if (ver >= (max || Infinity) || max === NaN && ver > 0) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
} | ||
static cleanupStream(writable, uri) { | ||
if (!writable.destroyed) { | ||
writable.destroy(); | ||
} | ||
writable.destroy(); | ||
if (uri) { | ||
@@ -854,56 +1005,85 @@ try { | ||
} | ||
static allSettled(values, options) { | ||
const promise = Promise.allSettled ? Promise.allSettled(values) : allSettled(values); | ||
if (options) { | ||
const { rejected, errors, type } = options; | ||
if (rejected || errors) { | ||
promise.then(result => { | ||
const items = []; | ||
for (const item of result) { | ||
if (item.status === 'rejected') { | ||
const reason = item.reason; | ||
if (reason) { | ||
if (rejected) { | ||
this.writeFail(rejected, reason instanceof Error ? reason : new Error(reason), type); | ||
static allSettled(values, rejected, type) { | ||
return filterAllSettled.call(this, values, rejected, type); | ||
} | ||
static loadSettings(value) { | ||
const { error, logger } = value; | ||
if (this.isPlainObject(logger)) { | ||
for (const attr in logger) { | ||
switch (attr) { | ||
case 'format': { | ||
const current = SETTINGS.format; | ||
const format = logger.format; | ||
if (this.isPlainObject(format)) { | ||
for (const section in format) { | ||
const item = format[section]; | ||
if (this.isPlainObject(item)) { | ||
Object.assign(current[section], item); | ||
} | ||
if (errors) { | ||
errors.push(reason.toString()); | ||
} | ||
} | ||
break; | ||
} | ||
case 'meter': { | ||
const current = SETTINGS.meter; | ||
const meter = logger.meter; | ||
if (this.isPlainObject(meter)) { | ||
for (const name in meter) { | ||
const increment = +meter[name]; | ||
if (increment > 0) { | ||
current[name] = increment; | ||
} | ||
} | ||
} | ||
else { | ||
items.push(item); | ||
} | ||
break; | ||
} | ||
return items; | ||
}); | ||
} | ||
} | ||
return promise; | ||
} | ||
static loadSettings(value) { | ||
const logger = value.logger; | ||
if (this.isObject(logger)) { | ||
for (const attr in logger) { | ||
if (attr === 'format') { | ||
const current = SETTINGS.format; | ||
const format = logger.format; | ||
if (this.isObject(format)) { | ||
for (const section in format) { | ||
const item = format[section]; | ||
if (this.isObject(item)) { | ||
Object.assign(current[section], item); | ||
case 'session_id': { | ||
let session_id = logger.session_id; | ||
if (session_id !== undefined) { | ||
if (!session_id) { | ||
logger.session_id = 0; | ||
} | ||
else if (session_id === true) { | ||
logger.session_id = 3; | ||
} | ||
else if ((session_id = +session_id) > 0) { | ||
logger.session_id = session_id; | ||
} | ||
} | ||
} | ||
case 'process': { | ||
const current = SETTINGS.process; | ||
const process = logger.process; | ||
if (this.isPlainObject(process)) { | ||
Object.assign(current, process); | ||
} | ||
else if (process === false) { | ||
Object.assign(current, { cpu: false, mem: false }); | ||
} | ||
else if (process) { | ||
Object.assign(current, { cpu: true, mem: true }); | ||
} | ||
} | ||
default: | ||
SETTINGS[attr] = logger[attr]; | ||
break; | ||
} | ||
else { | ||
SETTINGS[attr] = logger[attr]; | ||
} | ||
} | ||
const stack_trace = logger.stack_trace; | ||
if (typeof stack_trace === 'number' && stack_trace > 0) { | ||
let stack_trace = logger.stack_trace; | ||
if (stack_trace && typeof stack_trace !== 'boolean' && (stack_trace = +stack_trace) && stack_trace > 0) { | ||
Error.stackTraceLimit = stack_trace; | ||
} | ||
} | ||
if (this.isPlainObject(error) && error.module) { | ||
try { | ||
ERROR_MODULE = require(error.module); | ||
if (typeof ERROR_MODULE !== 'function') { | ||
ERROR_MODULE = null; | ||
} | ||
return; | ||
} | ||
catch (_a) { | ||
} | ||
ERROR_MODULE = this.parseFunction(error.module); | ||
} | ||
} | ||
@@ -916,2 +1096,10 @@ supported(major, minor, patch, lts) { | ||
} | ||
canRead(uri) { | ||
const permission = this.permission; | ||
return permission ? Module.isFileUNC(uri) ? permission.hasUNCRead(uri) : path.isAbsolute(uri) && permission.hasDiskRead(uri) : false; | ||
} | ||
canWrite(uri) { | ||
const permission = this.permission; | ||
return permission ? Module.isFileUNC(uri) ? permission.hasUNCWrite(uri) : path.isAbsolute(uri) && permission.hasDiskWrite(uri) : false; | ||
} | ||
deleteFile(value, emptyDir = false) { | ||
@@ -924,3 +1112,3 @@ var _a; | ||
if (!Module.isErrorCode(err, 'ENOENT')) { | ||
this.writeFail(["Unable to delete file" /* DELETE_FILE */, value], err, this.logType.FILE); | ||
this.writeFail(["Unable to delete file" /* DELETE_FILE */, value], err, 32 /* FILE */); | ||
return false; | ||
@@ -932,8 +1120,17 @@ } | ||
} | ||
allSettled(tasks, value, type) { | ||
return filterAllSettled.call(this, tasks, value, type); | ||
} | ||
writeFail(value, message, type = 1 /* SYSTEM */) { | ||
type |= 512 /* FAIL */; | ||
this.formatFail(type, 'FAIL!', value, message); | ||
} | ||
writeTimeProcess(title, value, time, options = {}) { | ||
var _a; | ||
var _a, _b; | ||
const type = options.type || 0; | ||
const http = type & 1024 /* HTTP */; | ||
const meter = SETTINGS.meter; | ||
const increment = options.meterIncrement || (http ? meter.http | ||
: type & 2048 /* IMAGE */ ? meter.image | ||
: type & 8 /* COMPRESS */ ? meter.compress | ||
: meter.process); | ||
const offset = getTimeOffset(time); | ||
@@ -944,6 +1141,7 @@ const failed = isFailed(options); | ||
title, | ||
[((options.type || 0) & 1024 /* HTTP */ ? '' : (failed ? 'Failed' : 'Completed') + ' -> ') + value, (offset / 1000) + 's'], | ||
(failed ? 'X' : '>').repeat(Math.ceil(offset / (options.meterIncrement || 250))), | ||
[(http ? '' : (failed ? 'Failed' : 'Completed') + ' -> ') + value, (offset / 1000) + 's'], | ||
(failed ? 'X' : '>').repeat(Math.ceil(offset / (increment || 250))), | ||
options | ||
]; | ||
options.sessionId || (options.sessionId = this.sessionId || ((_a = this.host) === null || _a === void 0 ? void 0 : _a.sessionId)); | ||
if (options.queue) { | ||
@@ -954,5 +1152,8 @@ this._logQueued.push(args); | ||
if (!options.messageUnit) { | ||
const startCPU = options.startCPU || ((_a = this.host) === null || _a === void 0 ? void 0 : _a.startCPU); | ||
const startCPU = options.startCPU || ((_b = this.host) === null || _b === void 0 ? void 0 : _b.startCPU); | ||
if (startCPU) { | ||
options.messageUnit = Module.getCpuUsage(startCPU, true) + ` CPU ${Module.getMemUsage(true)} MEM`; | ||
const { cpu, cpu_single_core, mem, mem_format } = SETTINGS.process; | ||
if (cpu || mem) { | ||
options.messageUnit = (cpu ? Module.getCpuUsage(startCPU, true) + ' CPU' + (!cpu_single_core ? '/' + CPU_CORETOTAL : '') : '') + (cpu && mem ? ' ' : '') + (mem ? Module.getMemUsage(mem_format || true) + ' MEM' : ''); | ||
} | ||
} | ||
@@ -964,2 +1165,3 @@ } | ||
writeTimeElapsed(title, value, time, options = {}) { | ||
var _a; | ||
const args = [ | ||
@@ -972,2 +1174,3 @@ 128 /* TIME_ELAPSED */, | ||
]; | ||
options.sessionId || (options.sessionId = this.sessionId || ((_a = this.host) === null || _a === void 0 ? void 0 : _a.sessionId)); | ||
if (options.queue) { | ||
@@ -981,5 +1184,9 @@ this._logQueued.push(args); | ||
formatFail(type, title, value, message, options = {}) { | ||
type |= 512 /* FAIL */; | ||
const args = [type, title, value, message, applyFailStyle(options)]; | ||
var _a; | ||
const args = [(type | 512 /* FAIL */), title, value, message, applyFailStyle(options)]; | ||
options.sessionId || (options.sessionId = this.sessionId || ((_a = this.host) === null || _a === void 0 ? void 0 : _a.sessionId)); | ||
if (options.queue !== false) { | ||
if (ERROR_MODULE) { | ||
options.timeStamp = Date.now(); | ||
} | ||
this._logQueued.push(args); | ||
@@ -990,9 +1197,17 @@ } | ||
} | ||
if (message && this._logEnabled) { | ||
this.errors.push(message instanceof Error ? SETTINGS.stack_trace && message.stack || message.message : message.toString()); | ||
if (message) { | ||
if (this._logEnabled) { | ||
this.errors.push(message instanceof Error ? SETTINGS.stack_trace && message.stack || message.message : message); | ||
} | ||
this.emit('error', asErrorObject(message)); | ||
} | ||
} | ||
formatMessage(type, title, value, message, options = {}) { | ||
var _a; | ||
const args = [type, title, value, message, options]; | ||
options.sessionId || (options.sessionId = this.sessionId || ((_a = this.host) === null || _a === void 0 ? void 0 : _a.sessionId)); | ||
if (options.queue) { | ||
if (ERROR_MODULE && (type & 512 /* FAIL */)) { | ||
options.timeStamp = Date.now(); | ||
} | ||
this._logQueued.push(args); | ||
@@ -1014,2 +1229,17 @@ } | ||
} | ||
set host(value) { | ||
if (value) { | ||
this._host = value; | ||
this.sessionId = value.sessionId; | ||
} | ||
} | ||
get host() { | ||
return this._host; | ||
} | ||
set permission(value) { | ||
this._permission = value; | ||
} | ||
get permission() { | ||
return this._permission || (this._host ? this._host.permission : null); | ||
} | ||
get logType() { | ||
@@ -1016,0 +1246,0 @@ return types_1.LOG_TYPE; |
{ | ||
"name": "@squared-functions/module", | ||
"version": "1.2.7", | ||
"description": "Module extension class for squared-functions", | ||
"version": "2.0.0", | ||
"description": "Module base class for squared-functions", | ||
"main": "index.js", | ||
@@ -18,3 +18,4 @@ "types": "index.d.ts", | ||
"dependencies": { | ||
"@squared-functions/types": "1.2.7", | ||
"@squared-functions/types": "2.0.0", | ||
"bytes": "^3.1.0", | ||
"uuid": "^8.3.2", | ||
@@ -21,0 +22,0 @@ "chalk": "^4.1.2" |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
49005
1219
4
3
+ Addedbytes@^3.1.0
+ Added@squared-functions/types@2.0.0(transitive)
+ Addedbytes@3.1.2(transitive)
- Removed@squared-functions/types@1.2.7(transitive)