alapa
Version:
A cutting-edge web development framework designed to revolutionize the way developers build modern web applications.
147 lines (146 loc) • 5.7 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadYaml = exports.escapeRegex = exports.toAbsolutePath = exports.md5 = exports.randomNumber = exports.randomMd5 = void 0;
exports.logToFile = logToFile;
exports.toNumberOnly = toNumberOnly;
/* eslint-disable @typescript-eslint/no-explicit-any */
const string_1 = require("./string");
const crypto_1 = __importDefault(require("crypto"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const yaml_1 = __importDefault(require("yaml"));
const logger_1 = require("./logger");
const randomMd5 = () => {
return (0, exports.md5)(Math.random().toString() + Date.now().toString());
};
exports.randomMd5 = randomMd5;
const randomNumber = (len = 0) => {
let number = (0, string_1.shuffle)((Math.random() + Date.now()).toString().replace(".", ""));
if (len > 0)
number = number.toString().substring(0, len);
return number.toString();
};
exports.randomNumber = randomNumber;
const md5 = function (data) {
return crypto_1.default.createHash("md5").update(data).digest("hex").toString();
};
exports.md5 = md5;
/**
* Logs a message to a specified text file.
* @param message - The message to log.
* @param filePath - The path to the text file where the message should be logged.
*/
function logToFile(message, type = "info", filePath) {
const date = new Date();
const logDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} ${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}:${String(date.getSeconds()).padStart(2, "0")}`;
const logMessage = `[${logDate}] [${type.toUpperCase()}] ${message}\n`;
if (!filePath)
filePath = path.resolve("logs", ".log");
// Ensure the directory exists
const dir = path.dirname(filePath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
// Append the message to the file
fs.appendFile(filePath, logMessage, (err) => {
if (err) {
console.error("Failed to write to log file:", err);
}
});
}
const toAbsolutePath = (...paths) => path.resolve(...paths);
exports.toAbsolutePath = toAbsolutePath;
const escapeRegex = (str) => {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
};
exports.escapeRegex = escapeRegex;
const loadYaml = (filePath) => {
try {
const content = fs.readFileSync(path.resolve(filePath), "utf8");
const doc = yaml_1.default.parse(content);
return doc;
}
catch (e) {
logger_1.Logger.error(e);
return null;
}
};
exports.loadYaml = loadYaml;
/**
* A utility function that converts a given value to a number, removing any non-numeric characters except for a decimal point.
* It handles cases with multiple decimal points, null, undefined, or empty strings, and returns 0 in those cases.
*
* @param {any} value - The input value to be converted to a number.
* @returns {number} - The numeric value derived from the input, or 0 if the input is invalid.
*
* @example
* // Returns 123456.78
* NumberOnly('123abc456.78xyz');
*
* @example
* // Returns 12.3456
* NumberOnly('12.34.56');
*
* @example
* // Returns 0
* NumberOnly('abc');
*
* @example
* // Returns 0
* NumberOnly(null);
*
* @example
* // Returns 0
* NumberOnly('');
*/
function toNumberOnly(value) {
// Handle cases where value is null, undefined, or an empty string
if (value === null || value === undefined || value === "")
return 0;
// Convert the value to a string and remove any characters that are not digits or a decimal point
let sanitizedValue = value
.toString()
.trim()
.replace(/[^0-9.]/g, "");
// Check if there are multiple decimal points in the sanitized value
const decimalCount = sanitizedValue.split(".").length - 1;
// If there are more than one decimal point, remove all extra decimals
if (decimalCount > 1) {
// Keep only the first decimal point, remove subsequent ones
sanitizedValue =
sanitizedValue.substring(0, sanitizedValue.indexOf(".") + 1) +
sanitizedValue
.substring(sanitizedValue.indexOf(".") + 1)
.replace(".", "");
}
// Convert the sanitized value to a number
const result = Number(sanitizedValue);
// If the result is NaN (invalid number), return 0
return isNaN(result) ? 0 : result;
}
;