From d972af76b6d7d1d2a099d254eacf45245b5316ac Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Tue, 4 Jul 2023 23:56:41 +0200 Subject: [PATCH] refactor: cleanup imports MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- mikro-orm.config-template.ts | 6 +-- src/charging-station/Bootstrap.ts | 12 ++--- src/charging-station/ChargingStation.ts | 52 ++++++++++--------- src/charging-station/ChargingStationUtils.ts | 19 +++---- src/charging-station/IdTagsCache.ts | 6 +-- .../ocpp/1.6/OCPP16IncomingRequestService.ts | 18 +++---- src/charging-station/ocpp/OCPPServiceUtils.ts | 8 +-- .../ui-server/UIWebSocketServer.ts | 2 +- src/performance/storage/JsonFileStorage.ts | 16 +++--- src/utils/Configuration.ts | 21 ++++---- src/utils/FileUtils.ts | 10 ++-- src/utils/Utils.ts | 16 +++--- src/worker/WorkerAbstract.ts | 10 ++-- src/worker/WorkerDynamicPool.ts | 6 +-- src/worker/WorkerSet.ts | 6 +-- src/worker/WorkerStaticPool.ts | 6 +-- tsconfig-base.json | 4 +- 17 files changed, 101 insertions(+), 117 deletions(-) diff --git a/mikro-orm.config-template.ts b/mikro-orm.config-template.ts index b89b975f..ff08b534 100644 --- a/mikro-orm.config-template.ts +++ b/mikro-orm.config-template.ts @@ -1,4 +1,4 @@ -import path from 'node:path'; +import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { TsMorphMetadataProvider } from '@mikro-orm/reflection'; @@ -10,8 +10,8 @@ export default { metadataProvider: TsMorphMetadataProvider, entities: [PerformanceRecord, PerformanceData], type: 'sqlite', - clientUrl: `file://${path.join( - path.dirname(fileURLToPath(import.meta.url)), + clientUrl: `file://${join( + dirname(fileURLToPath(import.meta.url)), `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db` )}`, }; diff --git a/src/charging-station/Bootstrap.ts b/src/charging-station/Bootstrap.ts index bed2692b..8a3f9078 100644 --- a/src/charging-station/Bootstrap.ts +++ b/src/charging-station/Bootstrap.ts @@ -1,7 +1,7 @@ // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. import { EventEmitter } from 'node:events'; -import path from 'node:path'; +import { dirname, extname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { isMainThread } from 'node:worker_threads'; @@ -69,9 +69,9 @@ export class Bootstrap extends EventEmitter { this.initializedCounters = false; this.initializeCounters(); this.workerImplementation = null; - this.workerScript = path.join( - path.dirname(fileURLToPath(import.meta.url)), - `ChargingStationWorker${path.extname(fileURLToPath(import.meta.url))}` + this.workerScript = join( + dirname(fileURLToPath(import.meta.url)), + `ChargingStationWorker${extname(fileURLToPath(import.meta.url))}` ); Configuration.getUIServer().enabled === true && (this.uiServer = UIServerFactory.getUIServerImplementation(Configuration.getUIServer())); @@ -334,8 +334,8 @@ export class Bootstrap extends EventEmitter { ): Promise { await this.workerImplementation?.addElement({ index, - templateFile: path.join( - path.dirname(fileURLToPath(import.meta.url)), + templateFile: join( + dirname(fileURLToPath(import.meta.url)), 'assets', 'station-templates', stationTemplateUrl.file diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index 86206712..fd974556 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -1,13 +1,21 @@ // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. -import crypto from 'node:crypto'; -import fs from 'node:fs'; -import path from 'node:path'; +import { createHash } from 'node:crypto'; +import { + type FSWatcher, + closeSync, + existsSync, + mkdirSync, + openSync, + readFileSync, + writeFileSync, +} from 'node:fs'; +import { dirname, join } from 'node:path'; import { URL } from 'node:url'; import { parentPort } from 'node:worker_threads'; import merge from 'just-merge'; -import WebSocket, { type RawData } from 'ws'; +import { type RawData, WebSocket } from 'ws'; import { AutomaticTransactionGenerator } from './AutomaticTransactionGenerator'; import { ChargingStationWorkerBroadcastChannel } from './broadcast-channel/ChargingStationWorkerBroadcastChannel'; @@ -133,7 +141,7 @@ export class ChargingStation { private configuredSupervisionUrl!: URL; private wsConnectionRestarted: boolean; private autoReconnectRetryCount: number; - private templateFileWatcher!: fs.FSWatcher | undefined; + private templateFileWatcher!: FSWatcher | undefined; private templateFileHash!: string; private readonly sharedLRUCache: SharedLRUCache; private webSocketPingSetInterval!: NodeJS.Timeout; @@ -1123,12 +1131,9 @@ export class ChargingStation { } else { const measureId = `${FileType.ChargingStationTemplate} read`; const beginId = PerformanceStatistics.beginMeasure(measureId); - template = JSON.parse( - fs.readFileSync(this.templateFile, 'utf8') - ) as ChargingStationTemplate; + template = JSON.parse(readFileSync(this.templateFile, 'utf8')) as ChargingStationTemplate; PerformanceStatistics.endMeasure(measureId, beginId); - template.templateHash = crypto - .createHash(Constants.DEFAULT_HASH_ALGORITHM) + template.templateHash = createHash(Constants.DEFAULT_HASH_ALGORITHM) .update(JSON.stringify(template)) .digest('hex'); this.sharedLRUCache.setChargingStationTemplate(template); @@ -1268,8 +1273,8 @@ export class ChargingStation { private initialize(): void { const stationTemplate = this.getTemplateFromFile(); ChargingStationUtils.checkTemplate(stationTemplate, this.logPrefix(), this.templateFile); - this.configurationFile = path.join( - path.dirname(this.templateFile.replace('station-templates', 'configurations')), + this.configurationFile = join( + dirname(this.templateFile.replace('station-templates', 'configurations')), `${ChargingStationUtils.getHashId(this.index, stationTemplate)}.json` ); const chargingStationConfiguration = this.getConfigurationFromFile(); @@ -1582,8 +1587,7 @@ export class ChargingStation { this.logPrefix(), this.templateFile ); - const connectorsConfigHash = crypto - .createHash(Constants.DEFAULT_HASH_ALGORITHM) + const connectorsConfigHash = createHash(Constants.DEFAULT_HASH_ALGORITHM) .update( `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}` ) @@ -1655,8 +1659,7 @@ export class ChargingStation { ); } if (stationTemplate?.Evses) { - const evsesConfigHash = crypto - .createHash(Constants.DEFAULT_HASH_ALGORITHM) + const evsesConfigHash = createHash(Constants.DEFAULT_HASH_ALGORITHM) .update(JSON.stringify(stationTemplate?.Evses)) .digest('hex'); const evsesConfigChanged = @@ -1701,7 +1704,7 @@ export class ChargingStation { private getConfigurationFromFile(): ChargingStationConfiguration | undefined { let configuration: ChargingStationConfiguration | undefined; - if (Utils.isNotEmptyString(this.configurationFile) && fs.existsSync(this.configurationFile)) { + if (Utils.isNotEmptyString(this.configurationFile) && existsSync(this.configurationFile)) { try { if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) { configuration = this.sharedLRUCache.getChargingStationConfiguration( @@ -1711,7 +1714,7 @@ export class ChargingStation { const measureId = `${FileType.ChargingStationConfiguration} read`; const beginId = PerformanceStatistics.beginMeasure(measureId); configuration = JSON.parse( - fs.readFileSync(this.configurationFile, 'utf8') + readFileSync(this.configurationFile, 'utf8') ) as ChargingStationConfiguration; PerformanceStatistics.endMeasure(measureId, beginId); this.sharedLRUCache.setChargingStationConfiguration(configuration); @@ -1746,8 +1749,8 @@ export class ChargingStation { private saveConfiguration(): void { if (Utils.isNotEmptyString(this.configurationFile)) { try { - if (!fs.existsSync(path.dirname(this.configurationFile))) { - fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true }); + if (!existsSync(dirname(this.configurationFile))) { + mkdirSync(dirname(this.configurationFile), { recursive: true }); } let configurationData: ChargingStationConfiguration = Utils.cloneObject(this.getConfigurationFromFile()) ?? {}; @@ -1782,8 +1785,7 @@ export class ChargingStation { delete configurationData.evsesStatus; } delete configurationData.configurationHash; - const configurationHash = crypto - .createHash(Constants.DEFAULT_HASH_ALGORITHM) + const configurationHash = createHash(Constants.DEFAULT_HASH_ALGORITHM) .update( JSON.stringify({ stationInfo: configurationData.stationInfo, @@ -1798,9 +1800,9 @@ export class ChargingStation { configurationData.configurationHash = configurationHash; const measureId = `${FileType.ChargingStationConfiguration} write`; const beginId = PerformanceStatistics.beginMeasure(measureId); - const fileDescriptor = fs.openSync(this.configurationFile, 'w'); - fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8'); - fs.closeSync(fileDescriptor); + const fileDescriptor = openSync(this.configurationFile, 'w'); + writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8'); + closeSync(fileDescriptor); PerformanceStatistics.endMeasure(measureId, beginId); this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash); this.sharedLRUCache.setChargingStationConfiguration(configurationData); diff --git a/src/charging-station/ChargingStationUtils.ts b/src/charging-station/ChargingStationUtils.ts index 4d51b0ea..ab781fae 100644 --- a/src/charging-station/ChargingStationUtils.ts +++ b/src/charging-station/ChargingStationUtils.ts @@ -1,6 +1,6 @@ -import crypto from 'node:crypto'; -import type EventEmitter from 'node:events'; -import path from 'node:path'; +import { createHash, randomBytes } from 'node:crypto'; +import type { EventEmitter } from 'node:events'; +import { basename, dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import chalk from 'chalk'; @@ -85,8 +85,7 @@ export class ChargingStationUtils { meterType: stationTemplate.meterType, }), }; - return crypto - .createHash(Constants.DEFAULT_HASH_ALGORITHM) + return createHash(Constants.DEFAULT_HASH_ALGORITHM) .update( `${JSON.stringify(chargingStationInfo)}${ChargingStationUtils.getChargingStationId( index, @@ -546,11 +545,7 @@ export class ChargingStationUtils { public static getIdTagsFile(stationInfo: ChargingStationInfo): string | undefined { return ( stationInfo.idTagsFile && - path.join( - path.dirname(fileURLToPath(import.meta.url)), - 'assets', - path.basename(stationInfo.idTagsFile) - ) + join(dirname(fileURLToPath(import.meta.url)), 'assets', basename(stationInfo.idTagsFile)) ); } @@ -778,9 +773,7 @@ export class ChargingStationUtils { randomBytesLength?: number; upperCase?: boolean; }): string { - const randomSerialNumberSuffix = crypto - .randomBytes(params?.randomBytesLength ?? 16) - .toString('hex'); + const randomSerialNumberSuffix = randomBytes(params?.randomBytesLength ?? 16).toString('hex'); if (params?.upperCase) { return randomSerialNumberSuffix.toUpperCase(); } diff --git a/src/charging-station/IdTagsCache.ts b/src/charging-station/IdTagsCache.ts index 55fcb924..c0f4d2b9 100644 --- a/src/charging-station/IdTagsCache.ts +++ b/src/charging-station/IdTagsCache.ts @@ -1,4 +1,4 @@ -import fs from 'node:fs'; +import { type FSWatcher, readFileSync } from 'node:fs'; import type { ChargingStation } from './ChargingStation'; import { ChargingStationUtils } from './ChargingStationUtils'; @@ -7,7 +7,7 @@ import { Utils, handleFileException, logger, watchJsonFile } from '../utils'; type IdTagsCacheValueType = { idTags: string[]; - idTagsFileWatcher: fs.FSWatcher | undefined; + idTagsFileWatcher: FSWatcher | undefined; }; export class IdTagsCache { @@ -172,7 +172,7 @@ export class IdTagsCache { private getIdTagsFromFile(file: string): string[] { if (Utils.isNotEmptyString(file)) { try { - return JSON.parse(fs.readFileSync(file, 'utf8')) as string[]; + return JSON.parse(readFileSync(file, 'utf8')) as string[]; } catch (error) { handleFileException( file, diff --git a/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts b/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts index a838377f..73943d4e 100644 --- a/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts +++ b/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts @@ -1,12 +1,12 @@ // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. -import fs from 'node:fs'; -import path from 'node:path'; +import { createWriteStream, readdirSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; import { URL, fileURLToPath } from 'node:url'; import type { JSONSchemaType } from 'ajv'; import { Client, type FTPResponse } from 'basic-ftp'; -import tar from 'tar'; +import { create } from 'tar'; import { OCPP16Constants } from './OCPP16Constants'; import { OCPP16ServiceUtils } from './OCPP16ServiceUtils'; @@ -1271,12 +1271,11 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { if (uri.protocol.startsWith('ftp:')) { let ftpClient: Client; try { - const logFiles = fs - .readdirSync(path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../')) + const logFiles = readdirSync(resolve(dirname(fileURLToPath(import.meta.url)), '../')) .filter((file) => file.endsWith('.log')) - .map((file) => path.join('./', file)); + .map((file) => join('./', file)); const diagnosticsArchive = `${chargingStation.stationInfo.chargingStationId}_logs.tar.gz`; - tar.create({ gzip: true }, logFiles).pipe(fs.createWriteStream(diagnosticsArchive)); + create({ gzip: true }, logFiles).pipe(createWriteStream(diagnosticsArchive)); ftpClient = new Client(); const accessResponse = await ftpClient.access({ host: uri.host, @@ -1308,10 +1307,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { }); }); uploadResponse = await ftpClient.uploadFrom( - path.join( - path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'), - diagnosticsArchive - ), + join(resolve(dirname(fileURLToPath(import.meta.url)), '../'), diagnosticsArchive), `${uri.pathname}${diagnosticsArchive}` ); if (uploadResponse.code === 226) { diff --git a/src/charging-station/ocpp/OCPPServiceUtils.ts b/src/charging-station/ocpp/OCPPServiceUtils.ts index b01ff1e0..7433f71d 100644 --- a/src/charging-station/ocpp/OCPPServiceUtils.ts +++ b/src/charging-station/ocpp/OCPPServiceUtils.ts @@ -1,5 +1,5 @@ -import fs from 'node:fs'; -import path from 'node:path'; +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import type { DefinedError, ErrorObject, JSONSchemaType } from 'ajv'; @@ -269,9 +269,9 @@ export class OCPPServiceUtils { moduleName?: string, methodName?: string ): JSONSchemaType { - const filePath = path.join(path.dirname(fileURLToPath(import.meta.url)), relativePath); + const filePath = join(dirname(fileURLToPath(import.meta.url)), relativePath); try { - return JSON.parse(fs.readFileSync(filePath, 'utf8')) as JSONSchemaType; + return JSON.parse(readFileSync(filePath, 'utf8')) as JSONSchemaType; } catch (error) { handleFileException( filePath, diff --git a/src/charging-station/ui-server/UIWebSocketServer.ts b/src/charging-station/ui-server/UIWebSocketServer.ts index dd5b6163..09842bf6 100644 --- a/src/charging-station/ui-server/UIWebSocketServer.ts +++ b/src/charging-station/ui-server/UIWebSocketServer.ts @@ -2,7 +2,7 @@ import type { IncomingMessage } from 'node:http'; import type { Duplex } from 'node:stream'; import { StatusCodes } from 'http-status-codes'; -import WebSocket, { type RawData, WebSocketServer } from 'ws'; +import { type RawData, WebSocket, WebSocketServer } from 'ws'; import { AbstractUIServer } from './AbstractUIServer'; import { UIServerUtils } from './UIServerUtils'; diff --git a/src/performance/storage/JsonFileStorage.ts b/src/performance/storage/JsonFileStorage.ts index 0fd29d02..e1a9a44e 100644 --- a/src/performance/storage/JsonFileStorage.ts +++ b/src/performance/storage/JsonFileStorage.ts @@ -1,7 +1,7 @@ // Copyright Jerome Benoit. 2021-2023. All Rights Reserved. -import fs from 'node:fs'; -import path from 'node:path'; +import { closeSync, existsSync, mkdirSync, openSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname } from 'node:path'; import { Storage } from './Storage'; import { BaseError } from '../../exception'; @@ -20,12 +20,12 @@ export class JsonFileStorage extends Storage { this.checkPerformanceRecordsFile(); AsyncLock.acquire(AsyncLockType.performance) .then(() => { - const fileData = fs.readFileSync(this.dbName, 'utf8'); + const fileData = readFileSync(this.dbName, 'utf8'); const performanceRecords: Statistics[] = fileData ? (JSON.parse(fileData) as Statistics[]) : []; performanceRecords.push(performanceStatistics); - fs.writeFileSync( + writeFileSync( this.dbName, Utils.JSONStringifyWithMapSupport(performanceRecords, 2), 'utf8' @@ -47,10 +47,10 @@ export class JsonFileStorage extends Storage { public open(): void { try { if (Utils.isNullOrUndefined(this?.fd)) { - if (!fs.existsSync(path.dirname(this.dbName))) { - fs.mkdirSync(path.dirname(this.dbName), { recursive: true }); + if (!existsSync(dirname(this.dbName))) { + mkdirSync(dirname(this.dbName), { recursive: true }); } - this.fd = fs.openSync(this.dbName, 'a+'); + this.fd = openSync(this.dbName, 'a+'); } } catch (error) { handleFileException( @@ -65,7 +65,7 @@ export class JsonFileStorage extends Storage { public close(): void { try { if (this?.fd) { - fs.closeSync(this.fd); + closeSync(this.fd); this.fd = null; } } catch (error) { diff --git a/src/utils/Configuration.ts b/src/utils/Configuration.ts index 3e3adbc2..e115aeb3 100644 --- a/src/utils/Configuration.ts +++ b/src/utils/Configuration.ts @@ -1,5 +1,5 @@ -import fs from 'node:fs'; -import path from 'node:path'; +import { type FSWatcher, readFileSync, watch } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import chalk from 'chalk'; @@ -23,13 +23,13 @@ import { import { WorkerConstants, WorkerProcessType } from '../worker'; export class Configuration { - private static configurationFile = path.join( - path.dirname(fileURLToPath(import.meta.url)), + private static configurationFile = join( + dirname(fileURLToPath(import.meta.url)), 'assets', 'config.json' ); - private static configurationFileWatcher: fs.FSWatcher | undefined; + private static configurationFileWatcher: FSWatcher | undefined; private static configuration: ConfigurationData | null = null; private static configurationChangeCallback: () => Promise; @@ -404,7 +404,7 @@ export class Configuration { if (!Configuration.configuration) { try { Configuration.configuration = JSON.parse( - fs.readFileSync(Configuration.configurationFile, 'utf8') + readFileSync(Configuration.configurationFile, 'utf8') ) as ConfigurationData; } catch (error) { Configuration.handleFileException( @@ -421,9 +421,9 @@ export class Configuration { return Configuration.configuration; } - private static getConfigurationFileWatcher(): fs.FSWatcher | undefined { + private static getConfigurationFileWatcher(): FSWatcher | undefined { try { - return fs.watch(Configuration.configurationFile, (event, filename): void => { + return watch(Configuration.configurationFile, (event, filename): void => { if (filename?.trim().length > 0 && event === 'change') { // Nullify to force configuration file reading Configuration.configuration = null; @@ -488,9 +488,6 @@ export class Configuration { } private static buildPerformanceUriFilePath(file: string) { - return `file://${path.join( - path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'), - file - )}`; + return `file://${join(resolve(dirname(fileURLToPath(import.meta.url)), '../'), file)}`; } } diff --git a/src/utils/FileUtils.ts b/src/utils/FileUtils.ts index 51871884..5e40b724 100644 --- a/src/utils/FileUtils.ts +++ b/src/utils/FileUtils.ts @@ -1,4 +1,4 @@ -import fs from 'node:fs'; +import { type FSWatcher, type WatchListener, readFileSync, watch } from 'node:fs'; import { handleFileException } from './ErrorUtils'; import { logger } from './Logger'; @@ -10,11 +10,11 @@ export const watchJsonFile = ( fileType: FileType, logPrefix: string, refreshedVariable?: T, - listener: fs.WatchListener = (event, filename) => { + listener: WatchListener = (event, filename) => { if (Utils.isNotEmptyString(filename) && event === 'change') { try { logger.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`); - refreshedVariable && (refreshedVariable = JSON.parse(fs.readFileSync(file, 'utf8')) as T); + refreshedVariable && (refreshedVariable = JSON.parse(readFileSync(file, 'utf8')) as T); } catch (error) { handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, { throwError: false, @@ -22,10 +22,10 @@ export const watchJsonFile = ( } } } -): fs.FSWatcher | undefined => { +): FSWatcher | undefined => { if (Utils.isNotEmptyString(file)) { try { - return fs.watch(file, listener); + return watch(file, listener); } catch (error) { handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, { throwError: false, diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index fb449213..7b0c9239 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -1,5 +1,5 @@ -import crypto from 'node:crypto'; -import util from 'node:util'; +import { randomBytes, randomInt, randomUUID } from 'node:crypto'; +import { inspect } from 'node:util'; import clone from 'just-clone'; @@ -16,7 +16,7 @@ export class Utils { }; public static generateUUID(): string { - return crypto.randomUUID(); + return randomUUID(); } public static validateUUID(uuid: string): boolean { @@ -128,16 +128,16 @@ export class Utils { if (max - min === Infinity) { throw new RangeError('Invalid interval'); } - return (crypto.randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min; + return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min; } public static getRandomInteger(max = Constants.MAX_RANDOM_INTEGER, min = 0): number { max = Math.floor(max); if (!Utils.isNullOrUndefined(min) && min !== 0) { min = Math.ceil(min); - return Math.floor(crypto.randomInt(min, max + 1)); + return Math.floor(randomInt(min, max + 1)); } - return Math.floor(crypto.randomInt(max + 1)); + return Math.floor(randomInt(max + 1)); } /** @@ -265,7 +265,7 @@ export class Utils { } public static isPromisePending(promise: Promise): boolean { - return util.inspect(promise).includes('pending'); + return inspect(promise).includes('pending'); } public static async promiseWithTimeout( @@ -297,7 +297,7 @@ export class Utils { * @returns */ public static secureRandom(): number { - return crypto.randomBytes(4).readUInt32LE() / 0x100000000; + return randomBytes(4).readUInt32LE() / 0x100000000; } public static JSONStringifyWithMapSupport( diff --git a/src/worker/WorkerAbstract.ts b/src/worker/WorkerAbstract.ts index 7d8eebd5..59610667 100644 --- a/src/worker/WorkerAbstract.ts +++ b/src/worker/WorkerAbstract.ts @@ -1,8 +1,8 @@ -import type EventEmitterAsyncResource from 'node:events'; -import fs from 'node:fs'; +import type { EventEmitter } from 'node:events'; +import { existsSync } from 'node:fs'; import type { Worker } from 'node:worker_threads'; -import type { ErrorHandler, ExitHandler, PoolInfo } from 'poolifier'; +import type { ErrorHandler, ExitHandler, PoolEmitter, PoolInfo } from 'poolifier'; import { WorkerConstants } from './WorkerConstants'; import type { SetInfo, WorkerData, WorkerOptions } from './WorkerTypes'; @@ -14,7 +14,7 @@ export abstract class WorkerAbstract { public abstract readonly info: PoolInfo | SetInfo; public abstract readonly size: number; public abstract readonly maxElementsPerWorker: number | undefined; - public abstract readonly emitter: EventEmitterAsyncResource | undefined; + public abstract readonly emitter: EventEmitter | PoolEmitter | undefined; /** * `WorkerAbstract` constructor. @@ -39,7 +39,7 @@ export abstract class WorkerAbstract { if (typeof workerScript === 'string' && workerScript.trim().length === 0) { throw new Error('Worker script is empty'); } - if (!fs.existsSync(workerScript)) { + if (!existsSync(workerScript)) { throw new Error('Worker script file does not exist'); } this.workerScript = workerScript; diff --git a/src/worker/WorkerDynamicPool.ts b/src/worker/WorkerDynamicPool.ts index 0af77e72..45bc6a7a 100644 --- a/src/worker/WorkerDynamicPool.ts +++ b/src/worker/WorkerDynamicPool.ts @@ -1,6 +1,4 @@ -import type EventEmitterAsyncResource from 'node:events'; - -import { DynamicThreadPool, type PoolInfo } from 'poolifier'; +import { DynamicThreadPool, type PoolEmitter, type PoolInfo } from 'poolifier'; import { WorkerAbstract } from './WorkerAbstract'; import type { WorkerData, WorkerOptions } from './WorkerTypes'; @@ -37,7 +35,7 @@ export class WorkerDynamicPool extends WorkerAbstract { return undefined; } - get emitter(): EventEmitterAsyncResource | undefined { + get emitter(): PoolEmitter | undefined { return this.pool?.emitter; } diff --git a/src/worker/WorkerSet.ts b/src/worker/WorkerSet.ts index 270f57b1..a2e6faf0 100644 --- a/src/worker/WorkerSet.ts +++ b/src/worker/WorkerSet.ts @@ -1,6 +1,6 @@ // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. -import EventEmitterAsyncResource from 'node:events'; +import { EventEmitter } from 'node:events'; import { SHARE_ENV, Worker } from 'node:worker_threads'; import { WorkerAbstract } from './WorkerAbstract'; @@ -16,7 +16,7 @@ import { import { sleep } from './WorkerUtils'; export class WorkerSet extends WorkerAbstract { - public readonly emitter: EventEmitterAsyncResource; + public readonly emitter: EventEmitter; private readonly workerSet: Set; /** @@ -36,7 +36,7 @@ export class WorkerSet extends WorkerAbstract { }; this.workerSet = new Set(); if (this.workerOptions?.poolOptions?.enableEvents) { - this.emitter = new EventEmitterAsyncResource(); + this.emitter = new EventEmitter(); } } diff --git a/src/worker/WorkerStaticPool.ts b/src/worker/WorkerStaticPool.ts index e49ac261..39298123 100644 --- a/src/worker/WorkerStaticPool.ts +++ b/src/worker/WorkerStaticPool.ts @@ -1,6 +1,4 @@ -import type EventEmitterAsyncResource from 'node:events'; - -import { FixedThreadPool, type PoolInfo } from 'poolifier'; +import { FixedThreadPool, type PoolEmitter, type PoolInfo } from 'poolifier'; import { WorkerAbstract } from './WorkerAbstract'; import type { WorkerData, WorkerOptions } from './WorkerTypes'; @@ -36,7 +34,7 @@ export class WorkerStaticPool extends WorkerAbstract { return undefined; } - get emitter(): EventEmitterAsyncResource | undefined { + get emitter(): PoolEmitter | undefined { return this.pool?.emitter; } diff --git a/tsconfig-base.json b/tsconfig-base.json index 658bfcfc..d72fc5e5 100644 --- a/tsconfig-base.json +++ b/tsconfig-base.json @@ -51,8 +51,8 @@ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ + "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + // "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ -- 2.34.1