Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 | 1x 9x 9x 11060x 2211x 2211x 6x 6x 8x 8x 8x 3x 3x 3x 6x 3x 3x 2x 2x 9x 9x 9x 5x 4x 1x 1x 4x 1x 8x 6x 6x 2x 7x 1x 6x 7x 1x 1x 1x 6x 6x 1x 5x 1x 1x 4x 4x 4x 7x 7x 7x 6x 1x 5x 4x | import fs from 'fs';
import * as Path from 'path';
import https from 'https';
import http from 'http';
import {
type ColumnProps,
getEntityMeta,
type IEntity,
} from '../classes/annotation';
import CoreEntity from '../classes/CoreEntity';
import { Executable, type ExecutableOptions } from './Executable';
export interface ClassNameInterface {
className: string;
tableName: string;
}
export type WDat<T> = { dat: T; i: number };
export type XExecResult = {
exitCode: number | null;
error: boolean;
stdout: string;
stderr: string;
};
export const MineTypeMap = new Map<string, string>([
['text/html; charset=utf-8', 'html'],
['text/html', 'html'],
['text/plain', 'txt'],
['video/mp4', 'mp4'],
['video/mpeg', 'mpeg'],
['video/webm', 'webm'],
['audio/webm', 'weba'],
['audio/mpeg', 'mp3'],
['audio/wav', 'wav'],
['audio/aac', 'aac'],
['audio/webm', 'aac'],
['audio/opus', 'opus'],
['image/webp', 'webp'],
['image/png', 'png'],
['image/jpeg', 'jpg'],
['image/gif', 'gif'],
['image/webp', 'webp'],
['image/svg+xml', 'svg'],
['application/pdf', 'pdf'],
['application/zip', 'zip'],
['application/x-rar-compressed', 'rar'],
['application/x-7z-compressed', '7z'],
['application/x-tar', 'tar'],
['application/x-bzip2', 'bz2'],
['application/x-gzip', 'gz'],
['application/json; charset=utf-8', 'json'],
]);
/**
* Returns the appropriate HTTP client module based on the URL scheme.
*
* @param {string} url - The URL to evaluate. If it starts with "https", the https module is returned; otherwise, the http module is returned.
* @return {object} The HTTP client module to use (http or https).
*/
function selectClient(url: string) {
if (url.startsWith('https')) {
return https;
}
return http;
}
/**
* Utility class providing helper functions for timing, worker pools, file system operations,
* string manipulation, entity metadata handling, environment setup, command execution,
* and file downloading.
*/
export class XUtil {
/**
* Pauses execution for the specified duration.
*
* @param {number} ms - The number of milliseconds to wait before resolving the promise.
* @returns {Promise<void>} A promise that resolves after the specified delay.
*/
static sleep(ms: number) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
/**
* Formats a number as a two‑digit string. If the provided number is less than 10, a leading zero is added.
*
* @param {number} num - The number to format.
* @param length
* @return {string} The formatted number as a string, padded with a leading zero if necessary.
*/
static numPrint(num: number, length = 2): string {
return num.toString().padStart(length, '0');
}
/**
* Returns the current timestamp as a formatted string.
*
* @return {string} A string in the format "YYYY-MM-DD HH:mm:ss" representing the current date and time.
*/
static getTimeStamp(): string {
const date = new Date();
return `${date.getFullYear()}-${this.numPrint(
date.getMonth() + 1,
)}-${this.numPrint(date.getDate())} ${this.numPrint(
date.getHours(),
)}:${this.numPrint(date.getMinutes() + 1)}:${this.numPrint(
date.getSeconds(),
)}`;
}
/**
* Processes a stream of data asynchronously using a producer and a consumer.
*
* @template T - The type of the input data produced by the producer.
* @template F - The type of the output data produced by the consumer.
*
* @param {() => Promise<WDat<T> | null>} producer
* A function that asynchronously returns a `WDat<T>` instance or `null` when no
* more items are available to process.
*
* @param {(arg: WDat<T>) => Promise<WDat<F>>} consumer
* A function that consumes a `WDat<T>` object and asynchronously returns a
* `WDat<F>` instance containing the processed data.
*
* @param {Map<number, F>} oMap
* A map that will receive the results from the consumer. The key is the
* `i` property of the `WDat` object and the value is the processed data.
*
* @returns {Promise<void>}
* Resolves when the producer has returned `null` and all produced items have
* been consumed and stored in the provided map.
*/
static async workerFc<T, F>(
producer: () => Promise<WDat<T> | null>,
consumer: (arg: WDat<T>) => Promise<WDat<F>>,
oMap: Map<number, F>,
): Promise<void> {
let next = await producer();
while (next) {
const res = await consumer(next);
oMap.set(res.i, res.dat);
next = await producer();
}
}
/**
* Creates a set of concurrent workers that fetch items from a producer, process them with a consumer, and collects the results.
*
* @template T The type of data produced by the `producer` function.
* @template F The type of data produced by the `consumer` function.
*
* @param {number} count - The number of worker instances to run concurrently.
* @param {() => Promise<WDat<T> | null>} producer - An async function that yields a `WDat<T>` object or `null` to indicate no more items.
* @param {(arg: WDat<T>) => Promise<WDat<F>>} consumer - An async function that receives a `WDat<T>` item and returns a processed `WDat<F>` object.
*
* @returns {Promise<F[]>} A promise that resolves to an array containing the `F` values extracted from the processed `WDat<F>` objects.
*/
static async workerFactoryWithProducer<T, F>(
count: number,
producer: () => Promise<WDat<T> | null>,
consumer: (arg: WDat<T>) => Promise<WDat<F>>,
) {
const oMap = new Map<number, F>();
const promises = [];
for (let i = 0; i < count; i++) {
promises.push(this.workerFc(producer, consumer, oMap));
}
await Promise.all(promises);
return Array.from(oMap.values());
}
/**
* Creates a worker factory that processes an array of items using a pool of workers.
*
* @param {number} count
* The maximum number of workers that will run concurrently.
*
* @param {Array<X>} arr
* The array of input data items to be processed.
*
* @param {(arg: WDat<X>) => Promise<WDat<F>>} mapper
* A function that receives an element wrapped in a {@link WDat} object and returns a promise that resolves to a {@link WDat} containing the mapped result.
*
* @returns {Promise<unknown>}
* A promise that resolves when all workers have finished processing, with the value returned by {@link workerFactoryWithProducer}.
*/
static async workerFactoryFromArray<X, F>(
count: number,
arr: Array<X>,
mapper: (arg: WDat<X>) => Promise<WDat<F>>,
) {
let i = 0;
return this.workerFactoryWithProducer(
count,
async () => {
const cur = i++;
const curEl = arr[cur];
if (curEl) {
return {
i: cur,
dat: curEl,
};
}
return null;
},
mapper,
);
}
/**
* Creates multiple folders specified by the given paths.
* @param {...string} path - The list of directory paths to be created.
* @returns {boolean} Returns `true` if all folders were successfully created, otherwise `false` if some already exist.
*/
static createFolderBulk(...path: string[]): boolean {
let res = true;
path.forEach((e) => {
res = this.createFolderIfNotExist(e) && res;
});
return res;
}
/**
* Ensures that the specified folder exists by creating it if it does not.
*
* @param path - The filesystem path of the folder to verify or create.
* @returns `true` if the folder was created during this call; `false` if the folder already existed.
*/
static createFolderIfNotExist(path: string): boolean {
if (!fs.existsSync(path)) {
fs.mkdirSync(path, { recursive: true });
return true;
}
return false;
}
/**
* Removes the folder at the given path if it exists.
*
* @param {string} path - The file system path of the folder to delete.
* @returns {boolean} Returns true after attempting the removal. The method
* performs the deletion only when the folder is present; otherwise it
* simply returns true.
*/
static removeFolderIfExist(path: string): boolean {
if (fs.existsSync(path)) {
fs.rmSync(path, {
recursive: true,
force: true,
});
}
return true;
}
/**
* Converts a camelCase string to snake_case.
* @param {string} str - The camelCase string to convert.
* @returns {string} The converted snake_case string. If the input string is empty, the same empty string is returned.
*/
static camelToSnakeCase(str: string): string {
if (str.length === 0) {
return str;
}
const className = str.substring(0, 1).toLowerCase() + str.substring(1);
return className.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
}
/**
* Executes a promise with a maximum wait time. If the promise does not resolve or reject before the specified timeout,
* the returned promise is rejected with an Error.
*
* @param {Promise<T>} promise - The promise to execute.
* @param {number} [ms=45000] - The maximum number of milliseconds to wait before timing out.
* @return {Promise<T>} A promise that resolves or rejects with the original promise's outcome, or rejects with a timeout error if the specified time elapses. */
static async promiseWithTimeout<T>(
promise: Promise<T>,
ms: number = 45000,
): Promise<T | undefined> {
let timer: NodeJS.Timeout;
const timeout = new Promise<undefined>((_, reject) => {
timer = setTimeout(() => reject(new Error('Promise timeout')), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)); // don't leak the timer
}
/**
* Returns the relation metadata for a given entity.
*
* @param {T} entity - The entity instance for which to retrieve relation metadata.
* @param {string} [schema] - Optional database schema name to associate with the relation.
*
* @returns {{key: string, relation: string, schema?: string}}
* An object containing:
* - `key`: the fixed key name `'e_id'`.
* - `relation`: the table name derived from the entity.
* - `schema`: the optional schema name if provided.
*/
static entityRelation<T extends CoreEntity>(entity: T, schema?: string) {
const name = this.getEntityNames(entity);
return {
key: 'e_id',
relation: name.tableName,
schema,
};
}
/**
* Returns the column properties for a relation to the specified entity.
*
* @param {T} entity The entity to which the column will reference.
* @param {string} [schema] Optional schema name for the foreign key.
* @returns {ColumnProps} An object containing the column data type and foreign key definition.
*/
static entityRelationColumn<T extends CoreEntity>(
entity: T,
schema?: string,
): ColumnProps {
return {
dataType: 'string',
foreignKey: this.entityRelation(entity, schema),
};
}
/**
* Retrieves the class and table names for the supplied entity.
*
* @param {IEntity} entity - The entity instance from which to extract metadata.
* @returns {ClassNameInterface} An object containing the class name and the corresponding table name derived from the entity metadata.
*/
static getEntityNames(entity: IEntity): ClassNameInterface {
const meta = getEntityMeta(entity);
if (!meta) {
throw new Error('InvalidClassMeta');
}
return {
className: meta.name,
tableName: this.camelToSnakeCase(meta.name),
};
}
/**
* Executes the specified command with optional arguments and options.
*
* @param {string} cmd - The command to execute.
* @param {string[]} [args] - Optional list of arguments to pass to the command.
* @param {ExecutableOptions} [options] - Optional execution options.
* @returns {Promise<XExecResult>} A promise that resolves with the execution result.
*/
static exec(
cmd: string,
args?: string[],
options?: ExecutableOptions,
): Promise<XExecResult> {
const exe = new Executable(cmd, options);
return exe.run(args);
}
/**
* Downloads a file from the specified URL and writes it to the given path.
*
* @param {string} url - The URL from which to download the file.
* @param {string} path - The destination file path without extension. The file extension is derived from the response MIME type.
* @param {Map<string,string>} [extMap=MineTypeMap] - A map that associates MIME types with file extensions. Used to determine the file extension to append.
* @param fExt - override extension
* @returns {Promise<{name:string, size:number, type:string} | null>} A promise that resolves to an object containing the file name, size in bytes, and MIME type, or null if the download fails.
*/
static downloadFile(
url: string,
path: string,
extMap = MineTypeMap,
fExt?: string,
): Promise<{
name: string;
size: number;
type: string;
} | null> {
return new Promise((resolve) => {
try {
selectClient(url)
.get(url, (res) => {
if (res.statusCode === 301 || res.statusCode === 302) {
if (res.headers.location) {
this.downloadFile(
res.headers.location,
path,
extMap,
fExt,
).then(resolve);
return;
}
}
const raw = extMap.get(res.headers['content-type'] as string);
const ext = raw || 'blob';
const fName = `${path}.${fExt || ext}`;
const file = fs.createWriteStream(fName);
res.pipe(file);
file.on('finish', () => {
file.close((err) => {
if (err) {
resolve(null);
return;
}
const cl = res.headers['content-length'];
resolve({
size: parseInt(cl as string, 10),
name: Path.basename(fName),
type: res.headers['content-type'] || '',
});
});
});
})
.on('error', (err) => {
console.error(`Error: ${err.message}`);
resolve(null);
});
} catch (e) {
console.error(e);
resolve(null);
}
});
}
static async calcDirSize(
dirPath: string,
exclude?: string[],
): Promise<number> {
let totalSize = 0;
const files = await fs.promises.readdir(dirPath);
for (const file of files) {
const filePath = Path.join(dirPath, file);
const stats = await fs.promises.stat(filePath);
if (!exclude || !exclude.includes(file)) {
if (stats.isDirectory()) {
totalSize += await this.calcDirSize(filePath);
} else {
totalSize += stats.size;
}
}
}
return totalSize;
}
}
|