From edd1a4a1435a265931956fb33d327a87e17903dd Mon Sep 17 00:00:00 2001 From: foxriver76 Date: Mon, 23 Sep 2024 09:11:55 +0200 Subject: [PATCH] fix rest of lint errors --- .github/workflows/ci-tests.yml | 4 +- .github/workflows/nightly-dev-release.yml | 8 +- .github/workflows/official-release.yml | 8 +- package-lock.json | 8 +- package.json | 2 +- packages/adapter/src/lib/adapter/adapter.ts | 731 ++++++++--------- packages/adapter/src/lib/adapter/validator.ts | 2 +- packages/cli/src/lib/cli/cliCert.ts | 6 +- packages/cli/src/lib/cli/cliCompact.ts | 30 +- packages/cli/src/lib/cli/cliLogs.ts | 2 +- packages/cli/src/lib/cli/cliObjects.ts | 83 +- packages/cli/src/lib/cli/cliPlugin.ts | 2 +- packages/cli/src/lib/cli/cliProcess.ts | 49 +- packages/cli/src/lib/cli/cliStates.ts | 15 +- packages/cli/src/lib/cli/messages.ts | 20 +- packages/cli/src/lib/setup.ts | 452 +++++------ packages/cli/src/lib/setup/formatters.ts | 8 +- packages/cli/src/lib/setup/multihostClient.ts | 3 +- packages/cli/src/lib/setup/setupBackup.ts | 33 +- packages/cli/src/lib/setup/setupInstall.ts | 71 +- packages/cli/src/lib/setup/setupList.ts | 60 +- packages/cli/src/lib/setup/setupMultihost.ts | 2 +- .../cli/src/lib/setup/setupPacketManager.ts | 10 +- packages/cli/src/lib/setup/setupRepo.ts | 2 +- packages/cli/src/lib/setup/setupSetup.ts | 6 +- packages/cli/src/lib/setup/setupUpgrade.ts | 73 +- packages/cli/src/lib/setup/setupUpload.ts | 10 +- packages/cli/src/lib/setup/setupUsers.ts | 335 ++++---- packages/cli/src/lib/setup/setupVendor.ts | 2 +- .../src/lib/common/aliasProcessing.ts | 5 +- packages/common-db/src/lib/common/logger.ts | 9 +- packages/common-db/src/lib/common/tools.ts | 312 ++++--- packages/common/src/lib/common/zipFiles.ts | 6 +- .../controller/src/lib/multihostServer.js | 8 +- packages/controller/src/lib/restart.ts | 2 +- packages/controller/src/lib/upgradeManager.ts | 2 +- packages/controller/src/main.ts | 679 ++++++++-------- .../jsonl/testAdapterObjectsInFileJsonl.ts | 14 +- .../jsonl/testAdapterStatesInFilesJsonl.ts | 2 +- .../controller/test/lib/setup4controller.ts | 6 +- packages/controller/test/lib/testAdapter.ts | 153 ++-- .../controller/test/lib/testAdapterHelpers.ts | 99 ++- packages/controller/test/lib/testAliases.ts | 124 +-- packages/controller/test/lib/testConsole.ts | 42 +- packages/controller/test/lib/testFiles.ts | 30 +- .../controller/test/lib/testHelperStates.ts | 4 +- packages/controller/test/lib/testMessages.ts | 14 +- packages/controller/test/lib/testObjects.ts | 86 +- .../controller/test/lib/testObjectsACL.ts | 83 +- .../test/lib/testObjectsFunctions.ts | 191 +++-- packages/controller/test/lib/testStates.ts | 162 ++-- .../redis-sentinel/testAdapterStatesRedis.ts | 8 +- .../test/redis-sentinel/testStatesRedis.ts | 12 +- .../redis-socket/testAdapterStatesRedis.ts | 8 +- .../test/redis-socket/testStatesRedis.ts | 2 +- .../test/testAdapterObjectsInFile.ts | 12 +- .../test/testAdapterObjectsInRedis.ts | 18 +- .../test/testAdapterStatesInFile.ts | 2 +- .../controller/test/testAdapterStatesRedis.ts | 4 +- .../controller/test/testInternalUtilities.ts | 4 +- packages/controller/test/testPackageFiles.ts | 18 +- packages/controller/test/testStates.ts | 22 +- packages/controller/test/testStatesRedis.ts | 22 +- packages/db-base/src/lib/inMemFileDB.ts | 12 +- .../src/lib/objects/objectsInMemFileDB.js | 8 +- .../lib/objects/objectsInMemServerRedis.js | 36 +- .../src/lib/objects/objectsInMemJsonlDB.js | 2 +- .../lib/objects/objectsInMemServerRedis.js | 34 +- .../src/lib/objects/objectsInRedisClient.ts | 762 ++++++++---------- .../src/lib/objects/objectsUtils.ts | 13 +- .../src/lib/states/statesInMemFileDB.js | 8 +- .../src/lib/states/statesInMemServerRedis.js | 20 +- .../src/lib/states/statesInMemJsonlDB.js | 2 +- .../src/lib/states/statesInMemServerRedis.js | 18 +- .../src/lib/states/statesInRedisClient.ts | 48 +- 75 files changed, 2454 insertions(+), 2711 deletions(-) diff --git a/.github/workflows/ci-tests.yml b/.github/workflows/ci-tests.yml index 62dae1ad7..cf4d289d4 100644 --- a/.github/workflows/ci-tests.yml +++ b/.github/workflows/ci-tests.yml @@ -25,10 +25,10 @@ jobs: steps: - uses: actions/checkout@v4 - - name: Use Node.js 18 + - name: Use Node.js uses: actions/setup-node@v4 with: - node-version: 18 + node-version-file: '.nvmrc' - name: NPM install run: npm i --ignore-scripts # install typescript and @types do not `setup first` diff --git a/.github/workflows/nightly-dev-release.yml b/.github/workflows/nightly-dev-release.yml index 0f956b51c..658cc4873 100644 --- a/.github/workflows/nightly-dev-release.yml +++ b/.github/workflows/nightly-dev-release.yml @@ -9,20 +9,16 @@ jobs: publish-config: runs-on: ubuntu-20.04 - strategy: - matrix: - node: [18.x] # This should be LTS - steps: - name: Checkout code uses: actions/checkout@v4 with: fetch-depth: 0 # Fetch the history, or this action won't work - - name: Use Node.js ${{ matrix.node }} + - name: Use Node.js uses: actions/setup-node@v4 with: - node-version: ${{ matrix.node }} + node-version-file: '.nvmrc' - name: Detect changes (git) id: changes diff --git a/.github/workflows/official-release.yml b/.github/workflows/official-release.yml index 7cee35177..3c7650630 100644 --- a/.github/workflows/official-release.yml +++ b/.github/workflows/official-release.yml @@ -17,20 +17,16 @@ jobs: publish-config: runs-on: ubuntu-20.04 - strategy: - matrix: - node: [18.x] # This should be LTS - steps: - name: Checkout code uses: actions/checkout@v4 with: fetch-depth: 0 # Fetch the history, or this action won't work - - name: Use Node.js ${{ matrix.node }} + - name: Use Node.js uses: actions/setup-node@v4 with: - node-version: ${{ matrix.node }} + node-version-file: '.nvmrc' - name: Prepare installation uses: ./.github/actions/install-redis-linux diff --git a/package-lock.json b/package-lock.json index 74b896373..89861a07c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -31,7 +31,7 @@ "@alcalzone/release-script-plugin-lerna": "~3.7.0", "@alcalzone/release-script-plugin-license": "~3.5.0", "@alcalzone/release-script-plugin-manual-review": "~3.5.9", - "@iobroker/eslint-config": "0.1.5", + "@iobroker/eslint-config": "^0.1.6", "@iobroker/types": "file:packages/types-public", "@iobroker/types-dev": "file:packages/types-dev", "@microsoft/api-extractor": "^7.43.0", @@ -1018,9 +1018,9 @@ "link": true }, "node_modules/@iobroker/eslint-config": { - "version": "0.1.5", - "resolved": "https://registry.npmjs.org/@iobroker/eslint-config/-/eslint-config-0.1.5.tgz", - "integrity": "sha512-rSBnPMQ4N01ZIGz1MPYEvzKqy32F1lYZ6Cv8e82rV+RV3jEOLV5kmUnhNZQnkmcAYJSHqqylNvqprqD0MLcQmg==", + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/@iobroker/eslint-config/-/eslint-config-0.1.6.tgz", + "integrity": "sha512-7t3bllV/pD64flqUE96ndPmb3GRlc+gLkLTRT9UEUmHRDFjgalMVbPXNoB+ka129NieMo5HcD23XGuRJQ5VCQg==", "dev": true, "peerDependencies": { "@eslint/eslintrc": "^3.1.0", diff --git a/package.json b/package.json index e6a5c62f0..e0884aa50 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "@alcalzone/release-script-plugin-lerna": "~3.7.0", "@alcalzone/release-script-plugin-license": "~3.5.0", "@alcalzone/release-script-plugin-manual-review": "~3.5.9", - "@iobroker/eslint-config": "0.1.5", + "@iobroker/eslint-config": "^0.1.6", "@iobroker/types": "file:packages/types-public", "@iobroker/types-dev": "file:packages/types-dev", "@microsoft/api-extractor": "^7.43.0", diff --git a/packages/adapter/src/lib/adapter/adapter.ts b/packages/adapter/src/lib/adapter/adapter.ts index 6f1c63e8d..b75cefd8d 100644 --- a/packages/adapter/src/lib/adapter/adapter.ts +++ b/packages/adapter/src/lib/adapter/adapter.ts @@ -141,7 +141,7 @@ import type { CommandResult } from '@alcalzone/pak'; import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); tools.ensureDNSOrder(); /** @@ -1613,9 +1613,8 @@ export class AdapterClass extends EventEmitter { supportsFeature(featureName: unknown): boolean { if (typeof featureName === 'string') { return this.SUPPORTED_FEATURES.includes(featureName as SupportedFeature); - } else { - return false; } + return false; } // external signature @@ -1693,11 +1692,10 @@ export class AdapterClass extends EventEmitter { this.getForeignObject(user, options, (err, obj) => { if (err || !obj || !obj.common || (!obj.common.enabled && user !== SYSTEM_ADMIN_USER)) { return tools.maybeCallback(callback, false, user); - } else { - password(pw).check(obj.common.password, (err, res) => { - return tools.maybeCallback(callback, !!res, user); - }); } + password(pw).check(obj.common.password, (err, res) => { + return tools.maybeCallback(callback, !!res, user); + }); }); } @@ -1936,9 +1934,8 @@ export class AdapterClass extends EventEmitter { } if (obj.common.members.includes(options.user)) { return tools.maybeCallback(options.callback, true); - } else { - return tools.maybeCallback(options.callback, false); } + return tools.maybeCallback(options.callback, false); }); }); } @@ -2454,35 +2451,34 @@ export class AdapterClass extends EventEmitter { } return tools.maybeCallbackWithError(callback, tools.ERRORS.ERROR_NOT_FOUND); - } else { - let ca: string | undefined; - if (chainedName) { - const chained = this._readFileCertificate(obj.native.certificates[chainedName]).split( - '-----END CERTIFICATE-----\r\n', - ); - // it is still a file name, and the file maybe does not exist, but we can omit this error - if (chained.join('').length >= 512) { - const caArr = []; - for (const cert of chained) { - if (cert.replace(/(\r\n|\r|\n)/g, '').trim()) { - caArr.push(`${cert}-----END CERTIFICATE-----\r\n`); - } + } + let ca: string | undefined; + if (chainedName) { + const chained = this._readFileCertificate(obj.native.certificates[chainedName]).split( + '-----END CERTIFICATE-----\r\n', + ); + // it is still a file name, and the file maybe does not exist, but we can omit this error + if (chained.join('').length >= 512) { + const caArr = []; + for (const cert of chained) { + if (cert.replace(/(\r\n|\r|\n)/g, '').trim()) { + caArr.push(`${cert}-----END CERTIFICATE-----\r\n`); } - ca = caArr.join(''); } + ca = caArr.join(''); } - - return tools.maybeCallbackWithError( - callback, - null, - { - key: this._readFileCertificate(obj.native.certificates[privateName]), - cert: this._readFileCertificate(obj.native.certificates[publicName]), - ca, - }, - obj.native.letsEncrypt, - ); } + + return tools.maybeCallbackWithError( + callback, + null, + { + key: this._readFileCertificate(obj.native.certificates[privateName]), + cert: this._readFileCertificate(obj.native.certificates[publicName]), + ca, + }, + obj.native.letsEncrypt, + ); } /** @@ -2595,9 +2591,8 @@ export class AdapterClass extends EventEmitter { if (typeof value === 'string') { const secret = await this.getSystemSecret(); return tools.maybeCallbackWithError(callback, null, tools.decrypt(secret, value)); - } else { - return tools.maybeCallbackWithError(callback, `Attribute "${attribute}" not found`); } + return tools.maybeCallbackWithError(callback, `Attribute "${attribute}" not found`); } /** @@ -3259,78 +3254,77 @@ export class AdapterClass extends EventEmitter { // @ts-expect-error TODO we are returning type Object for ease of use to devs, but formally these are AnyObjects, e.g. not guaranteed to have common return this.#objects.setObject(options.id, options.obj, options.options, options.callback); - } else { - options.obj.from = options.obj.from || `system.adapter.${this.namespace}`; - options.obj.user = options.obj.user || (options.options ? options.options.user : '') || SYSTEM_ADMIN_USER; - options.obj.ts = options.obj.ts || Date.now(); + } + options.obj.from = options.obj.from || `system.adapter.${this.namespace}`; + options.obj.user = options.obj.user || (options.options ? options.options.user : '') || SYSTEM_ADMIN_USER; + options.obj.ts = options.obj.ts || Date.now(); + if ( + (options.obj.type && options.obj.type === 'state') || + (!options.obj.type && oldObj && oldObj.type === 'state') + ) { if ( - (options.obj.type && options.obj.type === 'state') || - (!options.obj.type && oldObj && oldObj.type === 'state') + options.obj.common && + 'custom' in options.obj.common && + options.obj.common.custom !== null && + !tools.isObject(options.obj.common.custom) ) { - if ( - options.obj.common && - 'custom' in options.obj.common && - options.obj.common.custom !== null && - !tools.isObject(options.obj.common.custom) - ) { - this._logger.error( - `${this.namespaceLog} extendObject ${options.id} (type=${ - options.obj.type - }) property common.custom is of type ${typeof options.obj.common.custom}, expected object.`, - ); - return tools.maybeCallbackWithError(options.callback, 'common.custom needs to be an object'); - } - } else { - if (options.obj.common && 'custom' in options.obj.common && options.obj.common.custom !== null) { - this._logger.warn( - `${this.namespaceLog} setObject ${options.id} (type=${options.obj.type}) property common.custom must not exist.`, - ); - delete options.obj.common.custom; - } + this._logger.error( + `${this.namespaceLog} extendObject ${options.id} (type=${ + options.obj.type + }) property common.custom is of type ${typeof options.obj.common.custom}, expected object.`, + ); + return tools.maybeCallbackWithError(options.callback, 'common.custom needs to be an object'); } - - if (!oldObj) { - // if old object is not existing we behave like setObject - return this.setForeignObject(options.id, options.obj, options.options, options.callback); + } else { + if (options.obj.common && 'custom' in options.obj.common && options.obj.common.custom !== null) { + this._logger.warn( + `${this.namespaceLog} setObject ${options.id} (type=${options.obj.type}) property common.custom must not exist.`, + ); + delete options.obj.common.custom; } + } - try { - const cbObj = await this.#objects.extendObjectAsync(options.id, options.obj, options.options || {}); - let defState; - if (options.obj.type === 'state' || oldObj.type === 'state') { - if (options.obj.common && 'def' in options.obj.common && options.obj.common.def !== undefined) { - defState = options.obj.common.def; - } else if (oldObj.common && oldObj.common.def !== undefined) { - defState = oldObj.common.def; - } + if (!oldObj) { + // if old object is not existing we behave like setObject + return this.setForeignObject(options.id, options.obj, options.options, options.callback); + } + + try { + const cbObj = await this.#objects.extendObjectAsync(options.id, options.obj, options.options || {}); + let defState; + if (options.obj.type === 'state' || oldObj.type === 'state') { + if (options.obj.common && 'def' in options.obj.common && options.obj.common.def !== undefined) { + defState = options.obj.common.def; + } else if (oldObj.common && oldObj.common.def !== undefined) { + defState = oldObj.common.def; } + } - if (defState !== undefined) { - let currentStateObj; + if (defState !== undefined) { + let currentStateObj; + try { + currentStateObj = await this.getForeignStateAsync(options.id); + } catch { + // do nothing + } + if (!currentStateObj) { try { - currentStateObj = await this.getForeignStateAsync(options.id); - } catch { - // do nothing - } - if (!currentStateObj) { - try { - await this.setForeignStateAsync(options.id, { - val: defState, - q: this.constants.STATE_QUALITY.SUBSTITUTE_INITIAL_VALUE, - ack: true, - }); - } catch (e) { - this._logger.info( - `${this.namespaceLog} Default value for state "${options.id}" could not be set: ${e.message}`, - ); - } + await this.setForeignStateAsync(options.id, { + val: defState, + q: this.constants.STATE_QUALITY.SUBSTITUTE_INITIAL_VALUE, + ack: true, + }); + } catch (e) { + this._logger.info( + `${this.namespaceLog} Default value for state "${options.id}" could not be set: ${e.message}`, + ); } } - return tools.maybeCallbackWithError(options.callback, null, cbObj); - } catch (e) { - return tools.maybeCallbackWithError(options.callback, e); } + return tools.maybeCallbackWithError(options.callback, null, cbObj); + } catch (e) { + return tools.maybeCallbackWithError(options.callback, e); } } @@ -3563,75 +3557,74 @@ export class AdapterClass extends EventEmitter { // @ts-expect-error TODO we are returning type Object for ease of use to devs, but formally these are AnyObjects, e.g. not guaranteed to have common return this.#objects.setObject(id, obj, options, callback); - } else { - obj.from = obj.from || `system.adapter.${this.namespace}`; - obj.user = obj.user || options?.user || SYSTEM_ADMIN_USER; - obj.ts = obj.ts || Date.now(); + } + obj.from = obj.from || `system.adapter.${this.namespace}`; + obj.user = obj.user || options?.user || SYSTEM_ADMIN_USER; + obj.ts = obj.ts || Date.now(); - if ((obj.type && obj.type === 'state') || (!obj.type && oldObj && oldObj.type === 'state')) { - if ( - obj.common && - 'custom' in obj.common && - obj.common.custom !== null && - !tools.isObject(obj.common.custom) - ) { - this._logger.error( - `${this.namespaceLog} extendObject ${id} (type=${ - obj.type - }) property common.custom is of type ${typeof obj.common.custom}, expected object.`, - ); - return tools.maybeCallbackWithError(callback, 'common.custom needs to be an object'); - } - } else { - if (obj.common && 'custom' in obj.common && obj.common.custom !== null) { - this._logger.warn( - `${this.namespaceLog} setObject ${id} (type=${obj.type}) property common.custom must not exist.`, - ); - delete obj.common.custom; - } + if ((obj.type && obj.type === 'state') || (!obj.type && oldObj && oldObj.type === 'state')) { + if ( + obj.common && + 'custom' in obj.common && + obj.common.custom !== null && + !tools.isObject(obj.common.custom) + ) { + this._logger.error( + `${this.namespaceLog} extendObject ${id} (type=${ + obj.type + }) property common.custom is of type ${typeof obj.common.custom}, expected object.`, + ); + return tools.maybeCallbackWithError(callback, 'common.custom needs to be an object'); } - - if (!oldObj) { - // if old object is not existing we behave like setObject - return this.setForeignObject(id, obj, options, callback); + } else { + if (obj.common && 'custom' in obj.common && obj.common.custom !== null) { + this._logger.warn( + `${this.namespaceLog} setObject ${id} (type=${obj.type}) property common.custom must not exist.`, + ); + delete obj.common.custom; } + } - try { - const cbObj = await this.#objects.extendObjectAsync(id, obj, options || {}); - if (cbObj?.value.type === 'state') { - let defState; - if (obj.common && 'def' in obj.common && obj.common.def !== undefined) { - defState = obj.common.def; - } else if (oldObj.common && oldObj.common.def !== undefined) { - defState = oldObj.common.def; + if (!oldObj) { + // if old object is not existing we behave like setObject + return this.setForeignObject(id, obj, options, callback); + } + + try { + const cbObj = await this.#objects.extendObjectAsync(id, obj, options || {}); + if (cbObj?.value.type === 'state') { + let defState; + if (obj.common && 'def' in obj.common && obj.common.def !== undefined) { + defState = obj.common.def; + } else if (oldObj.common && oldObj.common.def !== undefined) { + defState = oldObj.common.def; + } + if (defState !== undefined) { + let currentStateObj; + try { + currentStateObj = await this.getForeignStateAsync(id); + } catch { + // do nothing } - if (defState !== undefined) { - let currentStateObj; + if (!currentStateObj) { try { - currentStateObj = await this.getForeignStateAsync(id); - } catch { - // do nothing - } - if (!currentStateObj) { - try { - await this.setForeignStateAsync(id, { - val: defState, - q: this.constants.STATE_QUALITY.SUBSTITUTE_INITIAL_VALUE, - ack: true, - }); - } catch (e) { - this._logger.info( - `${this.namespaceLog} Default value for state "${id}" could not be set: ${e.message}`, - ); - } + await this.setForeignStateAsync(id, { + val: defState, + q: this.constants.STATE_QUALITY.SUBSTITUTE_INITIAL_VALUE, + ack: true, + }); + } catch (e) { + this._logger.info( + `${this.namespaceLog} Default value for state "${id}" could not be set: ${e.message}`, + ); } } } - - return tools.maybeCallbackWithError(callback, null, cbObj); - } catch (e) { - return tools.maybeCallbackWithError(callback, e); } + + return tools.maybeCallbackWithError(callback, null, cbObj); + } catch (e) { + return tools.maybeCallbackWithError(callback, e); } } @@ -4545,27 +4538,26 @@ export class AdapterClass extends EventEmitter { ): void | Promise { if (!tasks || !tasks.length) { return tools.maybeCallback(cb); - } else { - const task = tasks.shift(); - this.#objects!.delObject(task!.id, options, async err => { - if (err) { - return tools.maybeCallbackWithError(cb, err); - } - if (task!.state) { - try { - await this.delForeignStateAsync(task!.id, options); - } catch (e) { - this._logger.warn(`${this.namespaceLog} Could not remove state of ${task!.id}: ${e.message}`); - } - } + } + const task = tasks.shift(); + this.#objects!.delObject(task!.id, options, async err => { + if (err) { + return tools.maybeCallbackWithError(cb, err); + } + if (task!.state) { try { - await tools.removeIdFromAllEnums(this.#objects, task!.id, this.enums); + await this.delForeignStateAsync(task!.id, options); } catch (e) { - this._logger.warn(`${this.namespaceLog} Could not remove ${task!.id} from enums: ${e.message}`); + this._logger.warn(`${this.namespaceLog} Could not remove state of ${task!.id}: ${e.message}`); } - setImmediate(() => this._deleteObjects(tasks, options, cb)); - }); - } + } + try { + await tools.removeIdFromAllEnums(this.#objects, task!.id, this.enums); + } catch (e) { + this._logger.warn(`${this.namespaceLog} Could not remove ${task!.id} from enums: ${e.message}`); + } + setImmediate(() => this._deleteObjects(tasks, options, cb)); + }); } delForeignObject(id: string, callback?: ioBroker.ErrorCallback): void; @@ -4996,9 +4988,8 @@ export class AdapterClass extends EventEmitter { } return this._setObjectWithDefaultValue(options.id, options.obj, null, options.callback); - } else { - return tools.maybeCallbackWithError(options.callback, null); } + return tools.maybeCallbackWithError(options.callback, null); } // external signatures @@ -5091,9 +5082,8 @@ export class AdapterClass extends EventEmitter { } return this._setObjectWithDefaultValue(id, obj, null, callback); - } else { - return tools.maybeCallbackWithError(callback, null); } + return tools.maybeCallbackWithError(callback, null); } private _DCS2ID(device: string, channel: string, stateOrPoint?: boolean | string): string { @@ -5457,9 +5447,8 @@ export class AdapterClass extends EventEmitter { err = `Wrong type of ${id}.common.min`; this._logger.error(`${this.namespaceLog} ${err}`); return tools.maybeCallbackWithError(callback, err); - } else { - common.min = min; } + common.min = min; } } if (common.max !== undefined) { @@ -5470,9 +5459,8 @@ export class AdapterClass extends EventEmitter { err = `Wrong type of ${id}.common.max`; this._logger.error(`${this.namespaceLog} ${err}`); return tools.maybeCallbackWithError(callback, err); - } else { - common.max = max; } + common.max = max; } } if (common.def !== undefined) { @@ -5483,9 +5471,8 @@ export class AdapterClass extends EventEmitter { err = new Error(`Wrong type of ${id}.common.def`); this._logger.error(`${this.namespaceLog} ${err.message}`); return tools.maybeCallbackWithError(callback, err); - } else { - common.def = def; } + common.def = def; } } if (common.min !== undefined && common.max !== undefined && min > max) { @@ -7919,116 +7906,115 @@ export class AdapterClass extends EventEmitter { // User does not exists this._logger.error(`${this.namespaceLog} unknown user "${options.user}"`); return options; - } else { - let groups; - try { - groups = await this.getForeignObjectsAsync('*', 'group', null, null); - } catch { - // ignore - } + } + let groups; + try { + groups = await this.getForeignObjectsAsync('*', 'group', null, null); + } catch { + // ignore + } - // aggregate all groups permissions, where this user is - if (groups) { - for (const group of Object.values(groups)) { - if (group.common.members.includes(options.user)) { - options.groups.push(group._id); - } + // aggregate all groups permissions, where this user is + if (groups) { + for (const group of Object.values(groups)) { + if (group.common.members.includes(options.user)) { + options.groups.push(group._id); } } + } - // read all groups for this user - this.users[options.user] = { - groups: options.groups, - // @ts-expect-error TODO: UserCommon has no acl - acl: userAcl.common?.acl || {}, - }; - await this._getGroups(options.groups); - // combine all rights - const user = this.users[options.user]; - for (const gName of options.groups) { - if (!this.groups[gName].common?.acl) { - continue; - } - const group = this.groups[gName]; + // read all groups for this user + this.users[options.user] = { + groups: options.groups, + // @ts-expect-error TODO: UserCommon has no acl + acl: userAcl.common?.acl || {}, + }; + await this._getGroups(options.groups); + // combine all rights + const user = this.users[options.user]; + for (const gName of options.groups) { + if (!this.groups[gName].common?.acl) { + continue; + } + const group = this.groups[gName]; - if (group.common?.acl?.file) { - if (!user.acl || !user.acl.file) { - user.acl = user.acl || {}; - user.acl.file = user.acl.file || {}; + if (group.common?.acl?.file) { + if (!user.acl || !user.acl.file) { + user.acl = user.acl || {}; + user.acl.file = user.acl.file || {}; - user.acl.file.create = group.common.acl.file.create; - user.acl.file.read = group.common.acl.file.read; - user.acl.file.write = group.common.acl.file.write; - user.acl.file.delete = group.common.acl.file.delete; - user.acl.file.list = group.common.acl.file.list; - } else { - user.acl.file.create = user.acl.file.create || group.common.acl.file.create; - user.acl.file.read = user.acl.file.read || group.common.acl.file.read; - user.acl.file.write = user.acl.file.write || group.common.acl.file.write; - user.acl.file.delete = user.acl.file.delete || group.common.acl.file.delete; - user.acl.file.list = user.acl.file.list || group.common.acl.file.list; - } + user.acl.file.create = group.common.acl.file.create; + user.acl.file.read = group.common.acl.file.read; + user.acl.file.write = group.common.acl.file.write; + user.acl.file.delete = group.common.acl.file.delete; + user.acl.file.list = group.common.acl.file.list; + } else { + user.acl.file.create = user.acl.file.create || group.common.acl.file.create; + user.acl.file.read = user.acl.file.read || group.common.acl.file.read; + user.acl.file.write = user.acl.file.write || group.common.acl.file.write; + user.acl.file.delete = user.acl.file.delete || group.common.acl.file.delete; + user.acl.file.list = user.acl.file.list || group.common.acl.file.list; } + } - if (group.common?.acl?.object) { - if (!user.acl || !user.acl.object) { - user.acl = user.acl || {}; - user.acl.object = user.acl.object || {}; + if (group.common?.acl?.object) { + if (!user.acl || !user.acl.object) { + user.acl = user.acl || {}; + user.acl.object = user.acl.object || {}; - user.acl.object.create = group.common.acl.object.create; - user.acl.object.read = group.common.acl.object.read; - user.acl.object.write = group.common.acl.object.write; - user.acl.object.delete = group.common.acl.object.delete; - user.acl.object.list = group.common.acl.object.list; - } else { - user.acl.object.create = user.acl.object.create || group.common.acl.object.create; - user.acl.object.read = user.acl.object.read || group.common.acl.object.read; - user.acl.object.write = user.acl.object.write || group.common.acl.object.write; - user.acl.object.delete = user.acl.object.delete || group.common.acl.object.delete; - user.acl.object.list = user.acl.object.list || group.common.acl.object.list; - } + user.acl.object.create = group.common.acl.object.create; + user.acl.object.read = group.common.acl.object.read; + user.acl.object.write = group.common.acl.object.write; + user.acl.object.delete = group.common.acl.object.delete; + user.acl.object.list = group.common.acl.object.list; + } else { + user.acl.object.create = user.acl.object.create || group.common.acl.object.create; + user.acl.object.read = user.acl.object.read || group.common.acl.object.read; + user.acl.object.write = user.acl.object.write || group.common.acl.object.write; + user.acl.object.delete = user.acl.object.delete || group.common.acl.object.delete; + user.acl.object.list = user.acl.object.list || group.common.acl.object.list; } + } - if (group.common?.acl?.users) { - if (!user.acl || !user.acl.users) { - user.acl = user.acl || {}; - user.acl.users = user.acl.users || {}; + if (group.common?.acl?.users) { + if (!user.acl || !user.acl.users) { + user.acl = user.acl || {}; + user.acl.users = user.acl.users || {}; - user.acl.users.create = group.common.acl.users.create; - user.acl.users.read = group.common.acl.users.read; - user.acl.users.write = group.common.acl.users.write; - user.acl.users.delete = group.common.acl.users.delete; - user.acl.users.list = group.common.acl.users.list; - } else { - user.acl.users.create = user.acl.users.create || group.common.acl.users.create; - user.acl.users.read = user.acl.users.read || group.common.acl.users.read; - user.acl.users.write = user.acl.users.write || group.common.acl.users.write; - user.acl.users.delete = user.acl.users.delete || group.common.acl.users.delete; - user.acl.users.list = user.acl.users.list || group.common.acl.users.list; - } - } - if (group.common?.acl?.state) { - if (!user.acl || !user.acl.state) { - user.acl = user.acl || {}; - user.acl.state = user.acl.state || {}; - - user.acl.state.create = group.common.acl.state.create; - user.acl.state.read = group.common.acl.state.read; - user.acl.state.write = group.common.acl.state.write; - user.acl.state.delete = group.common.acl.state.delete; - user.acl.state.list = group.common.acl.state.list; - } else { - user.acl.state.create = user.acl.state.create || group.common.acl.state.create; - user.acl.state.read = user.acl.state.read || group.common.acl.state.read; - user.acl.state.write = user.acl.state.write || group.common.acl.state.write; - user.acl.state.delete = user.acl.state.delete || group.common.acl.state.delete; - user.acl.state.list = user.acl.state.list || group.common.acl.state.list; - } + user.acl.users.create = group.common.acl.users.create; + user.acl.users.read = group.common.acl.users.read; + user.acl.users.write = group.common.acl.users.write; + user.acl.users.delete = group.common.acl.users.delete; + user.acl.users.list = group.common.acl.users.list; + } else { + user.acl.users.create = user.acl.users.create || group.common.acl.users.create; + user.acl.users.read = user.acl.users.read || group.common.acl.users.read; + user.acl.users.write = user.acl.users.write || group.common.acl.users.write; + user.acl.users.delete = user.acl.users.delete || group.common.acl.users.delete; + user.acl.users.list = user.acl.users.list || group.common.acl.users.list; + } + } + if (group.common?.acl?.state) { + if (!user.acl || !user.acl.state) { + user.acl = user.acl || {}; + user.acl.state = user.acl.state || {}; + + user.acl.state.create = group.common.acl.state.create; + user.acl.state.read = group.common.acl.state.read; + user.acl.state.write = group.common.acl.state.write; + user.acl.state.delete = group.common.acl.state.delete; + user.acl.state.list = group.common.acl.state.list; + } else { + user.acl.state.create = user.acl.state.create || group.common.acl.state.create; + user.acl.state.read = user.acl.state.read || group.common.acl.state.read; + user.acl.state.write = user.acl.state.write || group.common.acl.state.write; + user.acl.state.delete = user.acl.state.delete || group.common.acl.state.delete; + user.acl.state.list = user.acl.state.list || group.common.acl.state.list; } } - options.acl = user.acl; - return options; } + options.acl = user.acl; + return options; } private _checkState(obj: ioBroker.StateObject, options: Record, command: CheckStateCommand): boolean { @@ -8172,43 +8158,42 @@ export class AdapterClass extends EventEmitter { } return { ids, objs }; - } else { - const objs: ioBroker.StateObject[] = []; - - for (const id of ids) { - let originalChecked: boolean | undefined; + } + const objs: ioBroker.StateObject[] = []; - if (options.checked !== undefined) { - originalChecked = options.checked; - } + for (const id of ids) { + let originalChecked: boolean | undefined; - options.checked = true; + if (options.checked !== undefined) { + originalChecked = options.checked; + } - if (!this.#objects) { - this._logger.info( - `${this.namespaceLog} checkStates not processed because Objects database not connected`, - ); + options.checked = true; - throw new Error(tools.ERRORS.ERROR_DB_CLOSED); - } + if (!this.#objects) { + this._logger.info( + `${this.namespaceLog} checkStates not processed because Objects database not connected`, + ); - const obj = (await this.#objects.getObject(id, options)) as ioBroker.StateObject; + throw new Error(tools.ERRORS.ERROR_DB_CLOSED); + } - objs.push(obj); + const obj = (await this.#objects.getObject(id, options)) as ioBroker.StateObject; - if (originalChecked !== undefined) { - options.checked = originalChecked; - } else { - options.checked = undefined; - } + objs.push(obj); - if (!this._checkState(obj, options, command)) { - throw new Error(ERROR_PERMISSION); - } + if (originalChecked !== undefined) { + options.checked = originalChecked; + } else { + options.checked = undefined; } - return { ids, objs }; + if (!this._checkState(obj, options, command)) { + throw new Error(ERROR_PERMISSION); + } } + + return { ids, objs }; } private async _getGroups(ids: string[]): Promise { @@ -8246,10 +8231,9 @@ export class AdapterClass extends EventEmitter { // id can be string or can have attribute write const aliasId = tools.isObject(obj.common.alias.id) ? obj.common.alias.id.write : obj.common.alias.id; return this._setStateChangedHelper(aliasId, state); - } else { - this._logger.warn(`${this.namespaceLog} ${err ? err.message : `Alias ${id} has no target 1`}`); - throw new Error(err ? err.message : `Alias ${id} has no target`); } + this._logger.warn(`${this.namespaceLog} ${err ? err.message : `Alias ${id} has no target 1`}`); + throw new Error(err ? err.message : `Alias ${id} has no target`); } else { const oldState = await this.getForeignStateAsync(id, null); @@ -8283,9 +8267,8 @@ export class AdapterClass extends EventEmitter { this.outputCount++; await this.#states!.setState(id, state); return { id, notChanged: false }; - } else { - return { id, notChanged: true }; } + return { id, notChanged: true }; } } @@ -8422,14 +8405,13 @@ export class AdapterClass extends EventEmitter { return tools.maybeCallbackWithError(callback, e); } - const res = await this._setStateChangedHelper(fixedId, stateObj); - // @ts-expect-error todo fix it - return tools.maybeCallbackWithError(callback, null, res.id, res.notChanged); - } else { const res = await this._setStateChangedHelper(fixedId, stateObj); // @ts-expect-error todo fix it return tools.maybeCallbackWithError(callback, null, res.id, res.notChanged); } + const res = await this._setStateChangedHelper(fixedId, stateObj); + // @ts-expect-error todo fix it + return tools.maybeCallbackWithError(callback, null, res.id, res.notChanged); } setForeignState( @@ -8874,12 +8856,11 @@ export class AdapterClass extends EventEmitter { return tools.maybeCallbackWithError(callback, e); } - const res = await this._setStateChangedHelper(id, state); - return tools.maybeCallbackWithError(callback, null, res.id, res.notChanged); - } else { const res = await this._setStateChangedHelper(id, state); return tools.maybeCallbackWithError(callback, null, res.id, res.notChanged); } + const res = await this._setStateChangedHelper(id, state); + return tools.maybeCallbackWithError(callback, null, res.id, res.notChanged); } getState(id: string, callback: ioBroker.GetStateCallback): void; @@ -9051,9 +9032,8 @@ export class AdapterClass extends EventEmitter { } else { if (this.oStates && this.oStates[id]) { return tools.maybeCallbackWithError(callback, null, this.oStates[id]); - } else { - return this.#states.getState(id, callback); } + return this.#states.getState(id, callback); } } @@ -9184,9 +9164,8 @@ export class AdapterClass extends EventEmitter { // read default history instance from system.config await this._getDefaultHistory(); return this.getHistory(id, options, callback); - } else { - options.instance = this.defaultHistory; } + options.instance = this.defaultHistory; } this.sendTo(options.instance || 'history.0', 'getHistory', { id: id, options: options }, res => { @@ -9467,9 +9446,8 @@ export class AdapterClass extends EventEmitter { const srcObjs = (await this._getObjectsByArray(keys)) as (ioBroker.StateObject | null)[]; return this._processStatesSecondary(keys, fullTargetObjs, srcObjs); - } else { - return this._processStatesSecondary(keys, null, null); } + return this._processStatesSecondary(keys, null, null); } getForeignStates(pattern: Pattern, callback: ioBroker.GetStatesCallback): void; @@ -9901,10 +9879,9 @@ export class AdapterClass extends EventEmitter { if (promises.length && pattern !== '*') { return tools.maybeCallback(callback); - } else { - // no alias objects found or pattern * - this.#states.subscribeUser(pattern, callback); } + // no alias objects found or pattern * + this.#states.subscribeUser(pattern, callback); } catch (e) { this._logger.warn(`${this.namespaceLog} Cannot subscribe to ${pattern}: ${e.message}`); return tools.maybeCallbackWithError(callback, e); @@ -9924,9 +9901,8 @@ export class AdapterClass extends EventEmitter { if (aliasObj) { await this._addAliasSubscribe(aliasObj, pattern); return tools.maybeCallback(callback); - } else { - return tools.maybeCallback(callback); } + return tools.maybeCallback(callback); } catch (e) { this._logger.warn(`${this.namespaceLog} cannot subscribe on alias "${pattern}": ${e.message}`); } @@ -10231,14 +10207,13 @@ export class AdapterClass extends EventEmitter { try { const obj = await this.getForeignObjectAsync('system.licenses'); const uuidObj = await this.getForeignObjectAsync('system.meta.uuid'); - let uuid: string; if (!uuidObj?.native?.uuid) { this._logger.warn(`${this.namespaceLog} No UUID found!`); return licenses; - } else { - uuid = uuidObj.native.uuid; } + const uuid: string = uuidObj.native.uuid; + if (obj?.native?.licenses?.length) { const now = Date.now(); const cert = fs.readFileSync(path.join(thisDir, '..', '..', 'cert', 'cloudCert.crt')); @@ -10765,9 +10740,8 @@ export class AdapterClass extends EventEmitter { } } return tools.maybeCallback(cb); - } else { - return tools.maybeCallback(cb); } + return tools.maybeCallback(cb); }, logger: this._logger, change: async (id, stateOrMessage) => { @@ -11316,57 +11290,56 @@ export class AdapterClass extends EventEmitter { if (this._options.instance !== undefined) { return this._initAdapter(this._options); - } else { - const resAlive = await this.#states.getState(`system.adapter.${this.namespace}.alive`); - const killRes = await this.#states.getState(`system.adapter.${this.namespace}.sigKill`); + } + const resAlive = await this.#states.getState(`system.adapter.${this.namespace}.alive`); + const killRes = await this.#states.getState(`system.adapter.${this.namespace}.sigKill`); - if (killRes?.val !== undefined) { - killRes.val = parseInt(killRes.val as any, 10); - } - if (!this._config.isInstall && this.startedInCompactMode && killRes && !killRes.ack && killRes.val === -1) { - this._logger.error( - `${this.namespaceLog} ${this.namespace} needs to be stopped because not correctly started in compact mode`, - ); - this.terminate(EXIT_CODES.ADAPTER_REQUESTED_TERMINATION); - } else if ( - !this._config.forceIfDisabled && - !this._config.isInstall && - !this.startedInCompactMode && - killRes && - killRes.from?.startsWith('system.host.') && - killRes.ack && - !isNaN(killRes.val as any) && - killRes.val !== process.pid - ) { + if (killRes?.val !== undefined) { + killRes.val = parseInt(killRes.val as any, 10); + } + if (!this._config.isInstall && this.startedInCompactMode && killRes && !killRes.ack && killRes.val === -1) { + this._logger.error( + `${this.namespaceLog} ${this.namespace} needs to be stopped because not correctly started in compact mode`, + ); + this.terminate(EXIT_CODES.ADAPTER_REQUESTED_TERMINATION); + } else if ( + !this._config.forceIfDisabled && + !this._config.isInstall && + !this.startedInCompactMode && + killRes && + killRes.from?.startsWith('system.host.') && + killRes.ack && + !isNaN(killRes.val as any) && + killRes.val !== process.pid + ) { + this._logger.error( + `${this.namespaceLog} ${this.namespace} invalid process id scenario ${killRes.val} vs. own ID ${process.pid}. Stopping`, + ); + this.terminate(EXIT_CODES.ADAPTER_REQUESTED_TERMINATION); + } else if ( + !this._config.isInstall && + resAlive && + resAlive.val === true && + resAlive.ack && + !this._config.forceIfDisabled + ) { + this._logger.error(`${this.namespaceLog} ${this.namespace} already running`); + this.terminate(EXIT_CODES.ADAPTER_ALREADY_RUNNING); + } else { + let res: ioBroker.InstanceObject | null | undefined; + try { + res = await this.#objects.getObject(`system.adapter.${this.namespace}`); + } catch (e) { this._logger.error( - `${this.namespaceLog} ${this.namespace} invalid process id scenario ${killRes.val} vs. own ID ${process.pid}. Stopping`, + `${this.namespaceLog} ${this.namespace} Could not get instance object: ${e.message}`, ); - this.terminate(EXIT_CODES.ADAPTER_REQUESTED_TERMINATION); - } else if ( - !this._config.isInstall && - resAlive && - resAlive.val === true && - resAlive.ack && - !this._config.forceIfDisabled - ) { - this._logger.error(`${this.namespaceLog} ${this.namespace} already running`); - this.terminate(EXIT_CODES.ADAPTER_ALREADY_RUNNING); - } else { - let res: ioBroker.InstanceObject | null | undefined; - try { - res = await this.#objects.getObject(`system.adapter.${this.namespace}`); - } catch (e) { - this._logger.error( - `${this.namespaceLog} ${this.namespace} Could not get instance object: ${e.message}`, - ); - } + } - if (!res && !this._config.isInstall) { - this._logger.error(`${this.namespaceLog} ${this.namespace} invalid config`); - this.terminate(EXIT_CODES.INVALID_ADAPTER_CONFIG); - } else { - return this._initAdapter(res); - } + if (!res && !this._config.isInstall) { + this._logger.error(`${this.namespaceLog} ${this.namespace} invalid config`); + this.terminate(EXIT_CODES.INVALID_ADAPTER_CONFIG); + } else { + return this._initAdapter(res); } } } diff --git a/packages/adapter/src/lib/adapter/validator.ts b/packages/adapter/src/lib/adapter/validator.ts index e49bcf52a..0fbfa5504 100644 --- a/packages/adapter/src/lib/adapter/validator.ts +++ b/packages/adapter/src/lib/adapter/validator.ts @@ -372,7 +372,7 @@ export class Validator { } else if (tools.isObject(id)) { // If ID is an object // Add namespace + device + channel - result = `${this.namespace}.${id.device ? id.device + '.' : ''}${id.channel ? id.channel + '.' : ''}${ + result = `${this.namespace}.${id.device ? `${id.device}.` : ''}${id.channel ? `${id.channel}.` : ''}${ id.state ? id.state : '' }`; } diff --git a/packages/cli/src/lib/cli/cliCert.ts b/packages/cli/src/lib/cli/cliCert.ts index 62378eadc..1f03fad8c 100644 --- a/packages/cli/src/lib/cli/cliCert.ts +++ b/packages/cli/src/lib/cli/cliCert.ts @@ -76,14 +76,12 @@ export class CLICert extends CLICommand { if (certInfo) { console.log(JSON.stringify(certInfo, null, 2)); return void callback(EXIT_CODES.NO_ERROR); - } else { - messages.error.cert(certName); - return void callback(3); } - } else { messages.error.cert(certName); return void callback(3); } + messages.error.cert(certName); + return void callback(3); }); }); } diff --git a/packages/cli/src/lib/cli/cliCompact.ts b/packages/cli/src/lib/cli/cliCompact.ts index 6b01484b4..4c816248a 100644 --- a/packages/cli/src/lib/cli/cliCompact.ts +++ b/packages/cli/src/lib/cli/cliCompact.ts @@ -120,18 +120,18 @@ export class CLICompact extends CLICommand { ); console.log(); } else { - console.log('Adapter supports compact mode: ' + !!obj.common.compact); + console.log(`Adapter supports compact mode: ${!!obj.common.compact}`); } - console.log('Compact mode enabled for instance: ' + !!obj.common.runAsCompactMode); + console.log(`Compact mode enabled for instance: ${!!obj.common.runAsCompactMode}`); console.log( - 'Compact group: ' + - (obj.common.compactGroup !== undefined ? obj.common.compactGroup : 1), + `Compact group: ${ + obj.common.compactGroup !== undefined ? obj.common.compactGroup : 1 + }`, ); return void callback(); - } else { - CLI.error.invalidInstance(instance); - return void callback(24); } + CLI.error.invalidInstance(instance); + return void callback(24); }); }); } @@ -170,7 +170,7 @@ export class CLICompact extends CLICommand { console.log('This adapter does not support compact mode. The below settings will have no effect!'); console.log(); } else { - console.log('Adapter supports compact mode : ' + !!obj.common.compact); + console.log(`Adapter supports compact mode : ${!!obj.common.compact}`); } let newRunAsCompactMode; if (targetState !== undefined && targetState !== !!obj.common.runAsCompactMode) { @@ -188,14 +188,16 @@ export class CLICompact extends CLICommand { } } console.log( - 'Compact mode enabled for instance: ' + - (newRunAsCompactMode !== undefined ? '--> ' + newRunAsCompactMode : !!obj.common.runAsCompactMode), + `Compact mode enabled for instance: ${ + newRunAsCompactMode !== undefined ? `--> ${newRunAsCompactMode}` : !!obj.common.runAsCompactMode + }`, ); console.log( - 'Compact group: ' + - (newCompactGroup !== undefined && obj.common.compactGroup !== newCompactGroup - ? '--> ' + newCompactGroup - : obj.common.compactGroup), + `Compact group: ${ + newCompactGroup !== undefined && obj.common.compactGroup !== newCompactGroup + ? `--> ${newCompactGroup}` + : obj.common.compactGroup + }`, ); if (newRunAsCompactMode !== undefined || newCompactGroup !== undefined) { if (newCompactGroup !== undefined) { diff --git a/packages/cli/src/lib/cli/cliLogs.ts b/packages/cli/src/lib/cli/cliLogs.ts index 63244bc78..b731fca24 100644 --- a/packages/cli/src/lib/cli/cliLogs.ts +++ b/packages/cli/src/lib/cli/cliLogs.ts @@ -6,7 +6,7 @@ import os from 'node:os'; import es from 'event-stream'; import { createRequire } from 'node:module'; // eslint-disable-next-line unicorn/prefer-module -const require = createRequire(import.meta.url || 'file://' + __filename); +const require = createRequire(import.meta.url || `file://${__filename}`); const { getConfigFileName } = tools; diff --git a/packages/cli/src/lib/cli/cliObjects.ts b/packages/cli/src/lib/cli/cliObjects.ts index b1bc3a863..189a3d73a 100644 --- a/packages/cli/src/lib/cli/cliObjects.ts +++ b/packages/cli/src/lib/cli/cliObjects.ts @@ -218,10 +218,10 @@ export class CLIObjects extends CLICommand { CLI.error.requiredArgumentMissing('user', 'object chown user system.*'); return void callback(1); } else if (!user.startsWith('system.user.')) { - user = 'system.user.' + user; + user = `system.user.${user}`; } if (group && !group.startsWith('system.group.')) { - group = 'system.group.' + group; + group = `system.group.${group}`; } if (!pattern) { @@ -292,19 +292,18 @@ export class CLIObjects extends CLICommand { if (err || !res) { CLI.error.objectNotFound(id, err?.message); return void callback(3); - } else { - if (typeof propPath === 'string') { - // We want to select a part of the object - try { - res = deepSelectProperty(res, propPath); - } catch { - CLI.error.objectPropertyNotFound(id, propPath); - return void callback(3); - } + } + if (typeof propPath === 'string') { + // We want to select a part of the object + try { + res = deepSelectProperty(res, propPath); + } catch { + CLI.error.objectPropertyNotFound(id, propPath); + return void callback(3); } - console.log(formatValue(res, pretty)); - return void callback(EXIT_CODES.NO_ERROR); } + console.log(formatValue(res, pretty)); + return void callback(EXIT_CODES.NO_ERROR); }); }); } @@ -338,10 +337,9 @@ export class CLIObjects extends CLICommand { if (err) { CLI.error.cannotUpdateObject(id, err.message); return void callback(1); - } else { - CLI.success.objectUpdated(id); - return void callback(EXIT_CODES.NO_ERROR); } + CLI.success.objectUpdated(id); + return void callback(EXIT_CODES.NO_ERROR); }); }; if (!propPath) { @@ -452,10 +450,9 @@ export class CLIObjects extends CLICommand { if (err) { CLI.error.cannotUpdateObject(id, err.message); return void callback(1); - } else { - CLI.success.objectUpdated(id); - return void callback(EXIT_CODES.NO_ERROR); } + CLI.success.objectUpdated(id); + return void callback(EXIT_CODES.NO_ERROR); }); }); } @@ -508,26 +505,25 @@ export class CLIObjects extends CLICommand { async _deleteObjects(objects: ObjectsClient, ids: string[], callback: (exitCode: number) => void): Promise { if (!ids || !ids.length) { return tools.maybeCallback(callback, EXIT_CODES.NO_ERROR); - } else { - let allEnums; + } + let allEnums; + try { + // cache all enums, else it will be slow to delete many objects + allEnums = await tools.getAllEnums(objects); + } catch (e) { + console.error(`Could not retrieve all enums: ${e.message}`); + } + + for (const id of ids) { try { - // cache all enums, else it will be slow to delete many objects - allEnums = await tools.getAllEnums(objects); + await objects.delObjectAsync(id); + await tools.removeIdFromAllEnums(objects, id, allEnums); } catch (e) { - console.error(`Could not retrieve all enums: ${e.message}`); + console.warn(`Could not delete object or remove "${id}" from enums: ${e.message}`); } - - for (const id of ids) { - try { - await objects.delObjectAsync(id); - await tools.removeIdFromAllEnums(objects, id, allEnums); - } catch (e) { - console.warn(`Could not delete object or remove "${id}" from enums: ${e.message}`); - } - } - return tools.maybeCallback(callback, EXIT_CODES.NO_ERROR); } + return tools.maybeCallback(callback, EXIT_CODES.NO_ERROR); } /** @@ -755,17 +751,16 @@ function parsePropPathAndAssignment(arg: string): ParsedPropPathAndAssignment | // For partial assignments, allow strings as the value const value = parseCLIValue(valueString); return { propPath, value }; - } else { - // This is a full assignment, allow only objects - try { - const value = JSON.parse(arg); - if (!tools.isObject(value)) { - return undefined; - } - return { value }; - } catch { - // nope! + } + // This is a full assignment, allow only objects + try { + const value = JSON.parse(arg); + if (!tools.isObject(value)) { return undefined; } + return { value }; + } catch { + // nope! + return undefined; } } diff --git a/packages/cli/src/lib/cli/cliPlugin.ts b/packages/cli/src/lib/cli/cliPlugin.ts index 48c85354f..c5958415a 100644 --- a/packages/cli/src/lib/cli/cliPlugin.ts +++ b/packages/cli/src/lib/cli/cliPlugin.ts @@ -7,7 +7,7 @@ import path from 'node:path'; import { createRequire } from 'node:module'; // eslint-disable-next-line unicorn/prefer-module -const require = createRequire(import.meta.url || 'file://' + __filename); +const require = createRequire(import.meta.url || `file://${__filename}`); const controllerIoPackPath = require.resolve('iobroker.js-controller/io-package.json'); diff --git a/packages/cli/src/lib/cli/cliProcess.ts b/packages/cli/src/lib/cli/cliProcess.ts index 7a7d94fa2..19f4e6e44 100644 --- a/packages/cli/src/lib/cli/cliProcess.ts +++ b/packages/cli/src/lib/cli/cliProcess.ts @@ -248,9 +248,8 @@ export class CLIProcess extends CLICommand { resolve(); }); }); - } else { - console.log('No "killall.sh" script found. Just stop.'); } + console.log('No "killall.sh" script found. Just stop.'); } try { @@ -305,31 +304,29 @@ export class CLIProcess extends CLICommand { console.log(`States type: ${config.states.type}`); } return void callback(isOffline ? EXIT_CODES.CONTROLLER_NOT_RUNNING : undefined); - } else { - // we want to know the status of an adapter - if (/\.\d+$/.test(adapterName)) { - // instance specified - await showInstanceStatus(states, adapterName); - return void callback(); - } else { - const adapterInstances = await enumInstances(objects, adapterName); - // If there are multiple instances of this adapter, ask the user to specify which one - if (adapterInstances.length > 1) { - CLI.error.specifyInstance( - adapterName, - adapterInstances.map(obj => obj._id.substring('system.adapter.'.length)), - ); - return void callback(EXIT_CODES.INVALID_ADAPTER_ID); - } else if (adapterInstances.length === 0) { - CLI.error.noInstancesFound(adapterName); - return void callback(EXIT_CODES.UNKNOWN_ERROR); - } - - const instanceId = adapterInstances[0]._id.split('.').pop(); - await showInstanceStatus(states, `${adapterName}.${instanceId}`); - return void callback(); - } } + // we want to know the status of an adapter + if (/\.\d+$/.test(adapterName)) { + // instance specified + await showInstanceStatus(states, adapterName); + return void callback(); + } + const adapterInstances = await enumInstances(objects, adapterName); + // If there are multiple instances of this adapter, ask the user to specify which one + if (adapterInstances.length > 1) { + CLI.error.specifyInstance( + adapterName, + adapterInstances.map(obj => obj._id.substring('system.adapter.'.length)), + ); + return void callback(EXIT_CODES.INVALID_ADAPTER_ID); + } else if (adapterInstances.length === 0) { + CLI.error.noInstancesFound(adapterName); + return void callback(EXIT_CODES.UNKNOWN_ERROR); + } + + const instanceId = adapterInstances[0]._id.split('.').pop(); + await showInstanceStatus(states, `${adapterName}.${instanceId}`); + return void callback(); }); } } diff --git a/packages/cli/src/lib/cli/cliStates.ts b/packages/cli/src/lib/cli/cliStates.ts index 91d516890..0dfbea44b 100644 --- a/packages/cli/src/lib/cli/cliStates.ts +++ b/packages/cli/src/lib/cli/cliStates.ts @@ -278,10 +278,9 @@ export class CLIStates extends CLICommand { if (err) { CLI.error.unknown(err.message); return void callback(1); // ? - } else { - CLI.success.stateUpdated(id, val, !!ack); - return void callback(0); } + CLI.success.stateUpdated(id, val, !!ack); + return void callback(0); }, ); }); @@ -326,10 +325,9 @@ export class CLIStates extends CLICommand { if (err) { CLI.error.unknown(err.message); return void callback(1); // ? - } else { - CLI.success.stateUpdated(id, val, !!ack); - return void callback(0); } + CLI.success.stateUpdated(id, val, !!ack); + return void callback(0); }); }); } @@ -356,10 +354,9 @@ export class CLIStates extends CLICommand { if (err) { CLI.error.stateNotFound(id, err.message); return void callback(3); - } else { - CLI.success.stateDeleted(id); - return void callback(0); } + CLI.success.stateDeleted(id); + return void callback(0); }); }); } diff --git a/packages/cli/src/lib/cli/messages.ts b/packages/cli/src/lib/cli/messages.ts index 5c6c3fd8e..771121eed 100644 --- a/packages/cli/src/lib/cli/messages.ts +++ b/packages/cli/src/lib/cli/messages.ts @@ -2,20 +2,20 @@ import { tools } from '@iobroker/js-controller-common'; const errorMessages = Object.freeze({ stateNotFound: (stateID: string, error?: string) => - `The state ${stateID} was not found!` + (error ? ` Reason: ${error}` : ''), + `The state ${stateID} was not found!${error ? ` Reason: ${error}` : ''}`, stateNotBinary: (stateId: string) => `State "${stateId}" is not binary.`, stateBinaryGetUnsupported: (stateId: string) => `State "${stateId}" is a binary state, please use getBinary.`, stateBinarySetUnsupported: (stateId: string) => `State "${stateId}" is a binary state and cannot be set via cli.`, objectNotFound: (objectID: string, error?: string) => - `The object ${objectID} was not found!` + (error ? ` Reason: ${error}` : ''), + `The object ${objectID} was not found!${error ? ` Reason: ${error}` : ''}`, cannotUpdateObject: (objectID: string, error?: string) => - `The object ${objectID} could not be updated!` + (error ? ` Reason: ${error}` : ''), + `The object ${objectID} could not be updated!${error ? ` Reason: ${error}` : ''}`, cannotDeleteObject: (objectID: string, error?: string) => - `The object ${objectID} cannot be deleted!` + (error ? ` Reason: ${error}` : ''), + `The object ${objectID} cannot be deleted!${error ? ` Reason: ${error}` : ''}`, cannotDeleteObjectFromEnums: (objectID: string, error?: string) => - `The object ${objectID} could not be deleted from enums!` + (error ? ` Reason: ${error}` : ''), + `The object ${objectID} could not be deleted from enums!${error ? ` Reason: ${error}` : ''}`, cannotChangeObject: (objectID: string, error?: string) => - `The object ${objectID} cannot be changed!` + (error ? ` Reason: ${error}` : ''), + `The object ${objectID} cannot be changed!${error ? ` Reason: ${error}` : ''}`, objectPropertyNotFound: (objectID: string, propPath: string) => `The requested property "${propPath}" or one of its parents was not found in the object "${objectID}"!`, invalidPropertyOrValue: () => `The property path or value is not valid. Please make sure the value is valid JSON.`, @@ -23,7 +23,7 @@ const errorMessages = Object.freeze({ unknownCommand: (prefix: string, command: string) => `Unknown command "${prefix} ${command}"!`, requiredArgumentMissing: (argName: string, exampleCommand?: string) => - `The required argument "${argName}" is missing!` + (exampleCommand ? ` Example: "${exampleCommand}"` : ''), + `The required argument "${argName}" is missing!${exampleCommand ? ` Example: "${exampleCommand}"` : ''}`, noInstancesFound: (adapter: string) => `Cannot find any instances of "${adapter}"!`, invalidInstance: (instance: string) => `The instance "${instance}" does not exist!`, @@ -36,9 +36,9 @@ const errorMessages = Object.freeze({ cannotLoadIoPackage: (adapter: string) => `Cannot load the io-package.json file for adapter "${adapter}"!`, wrongCommandPrefix: (wrongPrefix: string, command: string, correctPrefix?: string) => - `The command ${command} is not intended to be used with ${wrongPrefix}!` + correctPrefix - ? `Please use "${correctPrefix} ${command}" instead.` - : '', + `The command ${command} is not intended to be used with ${wrongPrefix}!${ + correctPrefix ? ` Please use "${correctPrefix} ${command}" instead.` : '' + }`, unknown: (err: string) => `An unknown error occurred: ${err}`, cannotChangeRunningSystem: () => `Cannot execute changes on running system. Stop ${tools.appName} first.`, diff --git a/packages/cli/src/lib/setup.ts b/packages/cli/src/lib/setup.ts index 9dd1f5f62..a06859fb6 100644 --- a/packages/cli/src/lib/setup.ts +++ b/packages/cli/src/lib/setup.ts @@ -28,10 +28,10 @@ import * as url from 'node:url'; import * as events from 'node:events'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); import { createRequire } from 'node:module'; // eslint-disable-next-line unicorn/prefer-module -const require = createRequire(import.meta.url || 'file://' + __filename); +const require = createRequire(import.meta.url || `file://${__filename}`); tools.ensureDNSOrder(); @@ -841,7 +841,7 @@ async function processCommand( ); } } catch (err) { - console.error('Cannot read host info: ' + (typeof err === 'object' ? JSON.stringify(err) : err)); + console.error(`Cannot read host info: ${typeof err === 'object' ? JSON.stringify(err) : err}`); return callback(EXIT_CODES.CANNOT_GET_HOST_INFO); } @@ -970,10 +970,9 @@ async function processCommand( console.log(); console.log(`Rebuilding native modules done`); return void callback(); - } else { - console.error('Rebuilding native modules failed'); - return void exitApplicationSave(result.exitCode); } + console.error('Rebuilding native modules failed'); + return void exitApplicationSave(result.exitCode); } case 'upload': @@ -1546,10 +1545,9 @@ async function processCommand( if (!mode) { CLIError.requiredArgumentMissing('mode', 'chmod 777 /vis-2.0/main/*'); return void callback(EXIT_CODES.INVALID_ARGUMENTS); - } else { - // yargs has converted it to number - mode = parseInt(mode.toString(), 16); } + // yargs has converted it to number + mode = parseInt(mode.toString(), 16); if (!pattern) { CLIError.requiredArgumentMissing('file path', 'chmod 777 /vis-2.0/main/*'); @@ -1798,70 +1796,63 @@ async function processCommand( if (err) { console.error(err); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`User "${user}" created (Group: ${group.replace('system.group.', '')})`); - return void callback(); } + console.log(`User "${user}" created (Group: ${group.replace('system.group.', '')})`); + return void callback(); }); } else if (command === 'del' || command === 'delete') { users.delUser(user, (err: any) => { if (err) { console.error(err); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`User "${user}" deleted`); - return void callback(); } + console.log(`User "${user}" deleted`); + return void callback(); }); } else if (command === 'check') { users.checkUserPassword(user, password, err => { if (err) { console.error(err.message); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`Password for user "${user}" matches.`); - return void callback(); } + console.log(`Password for user "${user}" matches.`); + return void callback(); }); } else if (command === 'set' || command === 'passwd') { users.setUserPassword(user, password, err => { if (err) { console.error(err.message); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`Password for "${user}" was successfully set.`); - return void callback(); } + console.log(`Password for "${user}" was successfully set.`); + return void callback(); }); } else if (command === 'enable' || command === 'e') { users.enableUser(user, true, err => { if (err) { console.error(err.message); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`User "${user}" was successfully enabled.`); - return void callback(); } + console.log(`User "${user}" was successfully enabled.`); + return void callback(); }); } else if (command === 'disable' || command === 'd') { users.enableUser(user, false, err => { if (err) { console.error(err.message); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`User "${user}" was successfully disabled.`); - return void callback(); } + console.log(`User "${user}" was successfully disabled.`); + return void callback(); }); } else if (command === 'get') { users.getUser(user, (err, isEnabled) => { if (err) { console.error(err.message); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`User "${user}" is ${isEnabled ? 'enabled' : 'disabled'}`); - return void callback(); } + console.log(`User "${user}" is ${isEnabled ? 'enabled' : 'disabled'}`); + return void callback(); }); } else { console.warn( @@ -1912,10 +1903,9 @@ async function processCommand( if (err) { console.error(err); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`User "${user}" was added to group "${group}"`); - return void callback(); } + console.log(`User "${user}" was added to group "${group}"`); + return void callback(); }); } else if (command === 'userdel' || command === 'deluser') { if (!user) { @@ -1926,10 +1916,9 @@ async function processCommand( if (err) { console.error(err); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`User "${user}" was deleted from group "${group}"`); - return void callback(); } + console.log(`User "${user}" was deleted from group "${group}"`); + return void callback(); }); } else if (command === 'add') { try { @@ -1944,57 +1933,52 @@ async function processCommand( if (err) { console.error(err); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`Group "${group}" was deleted`); - return void callback(); } + console.log(`Group "${group}" was deleted`); + return void callback(); }); } else if (command === 'list' || command === 'l') { users.getGroup(group, (err, isEnabled, members) => { if (err) { console.error(err); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log( - `Group "${group}" is ${isEnabled ? 'enabled' : 'disabled'} and has following members:`, - ); - if (members) { - for (const member of members) { - console.log(member.substring('system.user.'.length)); - } + } + console.log( + `Group "${group}" is ${isEnabled ? 'enabled' : 'disabled'} and has following members:`, + ); + if (members) { + for (const member of members) { + console.log(member.substring('system.user.'.length)); } - return void callback(); } + return void callback(); }); } else if (command === 'enable' || command === 'e') { users.enableGroup(group, true, (err: any) => { if (err) { console.error(err); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`Group "${group}" was successfully enabled.`); - return void callback(); } + console.log(`Group "${group}" was successfully enabled.`); + return void callback(); }); } else if (command === 'disable' || command === 'd') { users.enableGroup(group, false, (err: any) => { if (err) { console.error(err); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`Group "${group}" was successfully disabled.`); - return void callback(); } + console.log(`Group "${group}" was successfully disabled.`); + return void callback(); }); } else if (command === 'get') { users.getGroup(group, (err, isEnabled) => { if (err) { console.error(err); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`Group "${group}" is ${isEnabled ? 'enabled' : 'disabled'}`); - return void callback(); } + console.log(`Group "${group}" is ${isEnabled ? 'enabled' : 'disabled'}`); + return void callback(); }); } else { console.warn( @@ -2021,10 +2005,9 @@ async function processCommand( if (err) { console.error(err); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`User "${user}" created (Group: ${group.replace('system.group.', '')})`); - return void callback(); } + console.log(`User "${user}" created (Group: ${group.replace('system.group.', '')})`); + return void callback(); }); }); break; @@ -2043,10 +2026,9 @@ async function processCommand( if (err) { console.error(err); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`Password for "${user}" was successfully set.`); - return void callback(); } + console.log(`Password for "${user}" was successfully set.`); + return void callback(); }); }); break; @@ -2068,10 +2050,9 @@ async function processCommand( if (err) { console.error(err); return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); - } else { - console.log(`User "${user}" deleted`); - return void callback(); } + console.log(`User "${user}" deleted`); + return void callback(); }); }); break; @@ -2098,12 +2079,12 @@ async function processCommand( for (const s in sources) { if (Object.prototype.hasOwnProperty.call(sources, s)) { if (sources[s].url) { - if (!json.dependencies[tools.appName + '.' + s]) { - json.optionalDependencies[tools.appName + '.' + s] = sources[s].url; + if (!json.dependencies[`${tools.appName}.${s}`]) { + json.optionalDependencies[`${tools.appName}.${s}`] = sources[s].url; } } else { - if (!json.dependencies[tools.appName + '.' + s]) { - json.optionalDependencies[tools.appName + '.' + s] = '*'; + if (!json.dependencies[`${tools.appName}.${s}`]) { + json.optionalDependencies[`${tools.appName}.${s}`] = '*'; } } } @@ -2409,7 +2390,7 @@ async function processCommand( if (notifications.length) { console.log(); console.log('The following notifications happened during sync: '); - notifications.forEach((el: string) => console.log('- ' + el)); + notifications.forEach((el: string) => console.log(`- ${el}`)); } return void callback(EXIT_CODES.NO_ERROR); } catch (err) { @@ -2443,10 +2424,9 @@ async function processCommand( if (obj?.native) { console.log(obj.native.uuid); return void callback(); - } else { - console.error('Error: no UUID found'); - return void callback(EXIT_CODES.CANNOT_GET_UUID); } + console.error('Error: no UUID found'); + return void callback(EXIT_CODES.CANNOT_GET_UUID); }); }); break; @@ -2504,32 +2484,31 @@ async function processCommand( if (isOffline && hasLocalObjectsServer) { console.log(`${tools.appName} is not running`); return void callback(EXIT_CODES.CONTROLLER_NOT_RUNNING); - } else { - console.log(`${tools.appName} is running`); - objects.getObjectList( - { - startkey: 'system.host.', - endkey: `system.host.\u9999`, - }, - null, - (err, res) => { - if (!err && res?.rows.length) { - for (const row of res.rows) { - const parts = row.id.split('.'); - // ignore system.host.name.alive and so on - if (parts.length === 3) { - states.pushMessage(row.id, { - command: 'checkLogging', - message: null, - from: 'console', - }); - } + } + console.log(`${tools.appName} is running`); + objects.getObjectList( + { + startkey: 'system.host.', + endkey: `system.host.\u9999`, + }, + null, + (err, res) => { + if (!err && res?.rows.length) { + for (const row of res.rows) { + const parts = row.id.split('.'); + // ignore system.host.name.alive and so on + if (parts.length === 3) { + states.pushMessage(row.id, { + command: 'checkLogging', + message: null, + from: 'console', + }); } } - setTimeout(callback, 200); - }, - ); - } + } + setTimeout(callback, 200); + }, + ); }); break; } @@ -2575,66 +2554,63 @@ async function processCommand( if (!repoName || !repoName.match(/[-_\w\d]+/)) { console.error(`Invalid repository name: "${repoName}"`); return void callback(); - } else { - if (repoUrlOrCommand === 'add' || repoUrlOrCommand === 'addset') { - if (!repoUrl) { - console.warn( - `Please define repository URL or path: ${tools.appName.toLowerCase()} add `, - ); - return void callback(EXIT_CODES.INVALID_ARGUMENTS); - } else { - try { - await repo.add(repoName, repoUrl); - - if (repoUrlOrCommand === 'addset') { - await repo.setActive(repoName); - console.log(`Repository "${repoName}" set as active: "${repoUrl}"`); - await repo.showRepoStatus(); - return void callback(); - } else { - console.log(`Repository "${repoName}" added as "${repoUrl}"`); - await repo.showRepoStatus(); - return void callback(); - } - } catch (err) { - console.error(`Cannot add repository location: ${err.message}`); - return void callback(EXIT_CODES.INVALID_REPO); - } - } - } else if (repoUrlOrCommand === 'set') { - try { + } + if (repoUrlOrCommand === 'add' || repoUrlOrCommand === 'addset') { + if (!repoUrl) { + console.warn( + `Please define repository URL or path: ${tools.appName.toLowerCase()} add `, + ); + return void callback(EXIT_CODES.INVALID_ARGUMENTS); + } + try { + await repo.add(repoName, repoUrl); + + if (repoUrlOrCommand === 'addset') { await repo.setActive(repoName); - console.log(`Repository "${repoName}" set as active.`); + console.log(`Repository "${repoName}" set as active: "${repoUrl}"`); await repo.showRepoStatus(); return void callback(); - } catch (err) { - console.error(`Cannot activate repository: ${err.message}`); - return void callback(EXIT_CODES.INVALID_REPO); - } - } else if (repoUrlOrCommand === 'del') { - try { - await repo.del(repoName); - console.log(`Repository "${repoName}" deleted.`); - await repo.showRepoStatus(); - return void callback(); - } catch (err) { - console.error(`Cannot remove repository: ${err.message}`); - return void callback(EXIT_CODES.INVALID_REPO); } - } else if (repoUrlOrCommand === 'unset') { - try { - await repo.setInactive(repoName); - console.log(`Repository "${repoName}" deactivated.`); - await repo.showRepoStatus(); - return void callback(); - } catch (err) { - console.error(`Cannot deactivate repository: ${err.message}`); - return void callback(EXIT_CODES.INVALID_REPO); - } - } else { - console.warn(`Unknown repo command: ${repoUrlOrCommand as string}`); - return void callback(EXIT_CODES.INVALID_ARGUMENTS); + console.log(`Repository "${repoName}" added as "${repoUrl}"`); + await repo.showRepoStatus(); + return void callback(); + } catch (err) { + console.error(`Cannot add repository location: ${err.message}`); + return void callback(EXIT_CODES.INVALID_REPO); + } + } else if (repoUrlOrCommand === 'set') { + try { + await repo.setActive(repoName); + console.log(`Repository "${repoName}" set as active.`); + await repo.showRepoStatus(); + return void callback(); + } catch (err) { + console.error(`Cannot activate repository: ${err.message}`); + return void callback(EXIT_CODES.INVALID_REPO); + } + } else if (repoUrlOrCommand === 'del') { + try { + await repo.del(repoName); + console.log(`Repository "${repoName}" deleted.`); + await repo.showRepoStatus(); + return void callback(); + } catch (err) { + console.error(`Cannot remove repository: ${err.message}`); + return void callback(EXIT_CODES.INVALID_REPO); } + } else if (repoUrlOrCommand === 'unset') { + try { + await repo.setInactive(repoName); + console.log(`Repository "${repoName}" deactivated.`); + await repo.showRepoStatus(); + return void callback(); + } catch (err) { + console.error(`Cannot deactivate repository: ${err.message}`); + return void callback(EXIT_CODES.INVALID_REPO); + } + } else { + console.warn(`Unknown repo command: ${repoUrlOrCommand as string}`); + return void callback(EXIT_CODES.INVALID_ARGUMENTS); } } }); @@ -2658,66 +2634,64 @@ async function processCommand( ) { console.log('Invalid parameters. Following is possible: enable, browse, connect, status'); return void callback(EXIT_CODES.INVALID_ARGUMENTS); - } else { - dbConnect(params, async ({ objects, states }) => { - const { Multihost } = await import('./setup/setupMultihost.js'); - const mh = new Multihost({ - params, - objects, - }); + } + dbConnect(params, async ({ objects, states }) => { + const { Multihost } = await import('./setup/setupMultihost.js'); + const mh = new Multihost({ + params, + objects, + }); - if (cmd === 's' || cmd === 'status') { - mh.status(); + if (cmd === 's' || cmd === 'status') { + mh.status(); + return void callback(); + } else if (cmd === 'b' || cmd === 'browse') { + try { + const list = await mh.browse(); + mh.showHosts(list); return void callback(); - } else if (cmd === 'b' || cmd === 'browse') { - try { - const list = await mh.browse(); - mh.showHosts(list); - return void callback(); - } catch (e) { - console.error(e.message); - return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); + } catch (e) { + console.error(e.message); + return void callback(EXIT_CODES.CANNOT_CREATE_USER_OR_GROUP); + } + } else if (cmd === 'e' || cmd === 'enable') { + mh.enable(true, async (err: any) => { + if (err) { + console.error(err); + return void callback(EXIT_CODES.CANNOT_ENABLE_MULTIHOST); } - } else if (cmd === 'e' || cmd === 'enable') { - mh.enable(true, async (err: any) => { - if (err) { - console.error(err); - return void callback(EXIT_CODES.CANNOT_ENABLE_MULTIHOST); - } else { - await states.pushMessage(`system.host.${tools.getHostName()}`, { - command: 'updateMultihost', - message: null, - from: 'setup', - }); - - callback(); - } + await states.pushMessage(`system.host.${tools.getHostName()}`, { + command: 'updateMultihost', + message: null, + from: 'setup', }); - } else if (cmd === 'd' || cmd === 'disable') { - mh.enable(false, async (err: any) => { - if (err) { - console.error(err); - return void callback(EXIT_CODES.CANNOT_ENABLE_MULTIHOST); - } else { - await states.pushMessage(`system.host.${tools.getHostName()}`, { - command: 'updateMultihost', - message: null, - from: 'setup', - }); - callback(); - } - }); - } else if (cmd === 'c' || cmd === 'connect') { - mh.connect(parseInt(args[1]), args[2], (err: any) => { - if (err) { - console.error(err); - } - return void callback(err ? 1 : 0); + callback(); + }); + } else if (cmd === 'd' || cmd === 'disable') { + mh.enable(false, async (err: any) => { + if (err) { + console.error(err); + return void callback(EXIT_CODES.CANNOT_ENABLE_MULTIHOST); + } + await states.pushMessage(`system.host.${tools.getHostName()}`, { + command: 'updateMultihost', + message: null, + from: 'setup', }); - } - }); - } + + callback(); + }); + } else if (cmd === 'c' || cmd === 'connect') { + mh.connect(parseInt(args[1]), args[2], (err: any) => { + if (err) { + console.error(err); + } + return void callback(err ? 1 : 0); + }); + } + }); + break; } @@ -2770,20 +2744,20 @@ async function processCommand( `Please specify the path to the license file or place license text directly!\n${tools.appName.toLowerCase()} license `, ); return void callback(EXIT_CODES.INVALID_ARGUMENTS); - } else { - dbConnect(params, async ({ objects }) => { - const { License } = await import('./setup/setupLicense.js'); - const license = new License({ objects }); - try { - await license.setLicense(file); - console.log(`License updated.`); - return void callback(); - } catch (err) { - console.error(`Cannot update license: ${err.message}`); - return void callback(EXIT_CODES.CANNOT_UPDATE_LICENSE); - } - }); } + dbConnect(params, async ({ objects }) => { + const { License } = await import('./setup/setupLicense.js'); + const license = new License({ objects }); + try { + await license.setLicense(file); + console.log(`License updated.`); + return void callback(); + } catch (err) { + console.error(`Cannot update license: ${err.message}`); + return void callback(EXIT_CODES.CANNOT_UPDATE_LICENSE); + } + }); + break; } @@ -2875,25 +2849,24 @@ async function cleanDatabase(isDeleteDb: boolean): Promise { // Clean up states const keysCount = await delStates(); return keysCount; - } else { - // Clean only objects, not the views - let ids: string[] = []; - - try { - const res = await objects.getObjectListAsync({ startkey: '\u0000', endkey: '\u9999' }); - if (res.rows.length) { - console.log(`clean ${res.rows.length} objects...`); - ids = res.rows.map(e => e.id); - } - } catch { - // ignore + } + // Clean only objects, not the views + let ids: string[] = []; + + try { + const res = await objects.getObjectListAsync({ startkey: '\u0000', endkey: '\u9999' }); + if (res.rows.length) { + console.log(`clean ${res.rows.length} objects...`); + ids = res.rows.map(e => e.id); } - - await delObjects(ids); - // Clean up states - const keysCount = await delStates(); - return keysCount; + } catch { + // ignore } + + await delObjects(ids); + // Clean up states + const keysCount = await delStates(); + return keysCount; } function unsetup(params: Record, callback: ExitCodeCb): void { @@ -2921,10 +2894,9 @@ function unsetup(params: Record, callback: ExitCodeCb): void { if (err) { console.log(`not found: ${err.message}`); return void callback(EXIT_CODES.CANNOT_SET_OBJECT); - } else { - console.log('system.config reset'); - return void callback(); } + console.log('system.config reset'); + return void callback(); }); } else { console.log('system.config is OK'); diff --git a/packages/cli/src/lib/setup/formatters.ts b/packages/cli/src/lib/setup/formatters.ts index 7992b0a35..b5be04c8e 100644 --- a/packages/cli/src/lib/setup/formatters.ts +++ b/packages/cli/src/lib/setup/formatters.ts @@ -10,17 +10,17 @@ export function formatSeconds(seconds: number): string { _seconds %= 3_600 * 24; let hours: number | string = Math.floor(_seconds / 3_600); if (hours < 10) { - hours = '0' + hours; + hours = `0${hours}`; } _seconds %= 3_600; let minutes: number | string = Math.floor(_seconds / 60); if (minutes < 10) { - minutes = '0' + minutes; + minutes = `0${minutes}`; } _seconds %= 60; _seconds = Math.floor(_seconds); if (_seconds < 10) { - _seconds = '0' + _seconds; + _seconds = `0${_seconds}`; } let text = ''; if (days) { @@ -74,5 +74,5 @@ export function formatBytes(bytes: number): string { bytes /= 1024; ++u; } while (Math.abs(bytes) >= 1024 && u < units.length - 1); - return bytes.toFixed(1) + ' ' + units[u]; + return `${bytes.toFixed(1)} ${units[u]}`; } diff --git a/packages/cli/src/lib/setup/multihostClient.ts b/packages/cli/src/lib/setup/multihostClient.ts index be85e565d..06c82c30d 100644 --- a/packages/cli/src/lib/setup/multihostClient.ts +++ b/packages/cli/src/lib/setup/multihostClient.ts @@ -256,9 +256,8 @@ export class MHClient { console.log(msg.result); } return true; - } else { - console.warn(`Multihost discovery client: Unexpected message: ${JSON.stringify(msg)}`); } + console.warn(`Multihost discovery client: Unexpected message: ${JSON.stringify(msg)}`); return false; }, diff --git a/packages/cli/src/lib/setup/setupBackup.ts b/packages/cli/src/lib/setup/setupBackup.ts index 7dce6344a..950807494 100644 --- a/packages/cli/src/lib/setup/setupBackup.ts +++ b/packages/cli/src/lib/setup/setupBackup.ts @@ -259,19 +259,9 @@ export class BackupRestore { async createBackup(name: string, noConfig?: boolean): Promise { if (!name) { const d = new Date(); - name = - d.getFullYear() + - '_' + - ('0' + (d.getMonth() + 1)).slice(-2) + - '_' + - ('0' + d.getDate()).slice(-2) + - '-' + - ('0' + d.getHours()).slice(-2) + - '_' + - ('0' + d.getMinutes()).slice(-2) + - '_' + - ('0' + d.getSeconds()).slice(-2) + - `_backup${tools.appName}`; + name = `${d.getFullYear()}_${`0${d.getMonth() + 1}`.slice(-2)}_${`0${d.getDate()}`.slice(-2)}-${`0${d.getHours()}`.slice( + -2, + )}_${`0${d.getMinutes()}`.slice(-2)}_${`0${d.getSeconds()}`.slice(-2)}_backup${tools.appName}`; } name = name.toString().replace(/\\/g, '/'); @@ -328,7 +318,7 @@ export class BackupRestore { hostname, thisHostNameStartsWith, }); - await objectsFd.write(JSON.stringify(preprocessedValue) + '\n'); + await objectsFd.write(`${JSON.stringify(preprocessedValue)}\n`); } console.log(`host.${hostname} ${res.rows.length || 'no'} objects saved`); @@ -365,7 +355,7 @@ export class BackupRestore { } } - await statesFd.write(JSON.stringify({ id: keys[i], state: obj }) + '\n'); + await statesFd.write(`${JSON.stringify({ id: keys[i], state: obj })}\n`); } await statesFd.close(); @@ -947,11 +937,10 @@ export class BackupRestore { ); return EXIT_CODES.CANNOT_RESTORE_BACKUP; - } else { - console.info('The current version of js-controller differs from the version in the backup.'); - console.info('The js-controller version of the backup can not be restored automatically.'); - console.info('Note, that your backup might differ in behavior due to this version change!'); } + console.info('The current version of js-controller differs from the version in the backup.'); + console.info('The js-controller version of the backup can not be restored automatically.'); + console.info('Note, that your backup might differ in behavior due to this version change!'); } } catch { // ignore @@ -972,9 +961,8 @@ export class BackupRestore { } } return result; - } else { - return result; } + return result; } /** @@ -1078,9 +1066,8 @@ export class BackupRestore { console.log(`No existing backups. Create a backup, using "${tools.appName} backup" first`); } return void this.processExit(EXIT_CODES.INVALID_ARGUMENTS); - } else { - console.log(`host.${this.hostname} Using backup file ${name}`); } + console.log(`host.${this.hostname} Using backup file ${name}`); } name = name.toString().replace(/\\/g, '/'); diff --git a/packages/cli/src/lib/setup/setupInstall.ts b/packages/cli/src/lib/setup/setupInstall.ts index 633d7bdfd..0ad6b7f50 100644 --- a/packages/cli/src/lib/setup/setupInstall.ts +++ b/packages/cli/src/lib/setup/setupInstall.ts @@ -26,7 +26,7 @@ import { SYSTEM_ADAPTER_PREFIX } from '@iobroker/js-controller-common-db/constan import { createRequire } from 'node:module'; // eslint-disable-next-line unicorn/prefer-module -const require = createRequire(import.meta.url || 'file://' + __filename); +const require = createRequire(import.meta.url || `file://${__filename}`); const hostname = tools.getHostName(); const osPlatform = process.platform; @@ -438,15 +438,14 @@ export class Install { // command succeeded return { _url: npmUrl, installDir: path.dirname(installDir) }; - } else { - if (!isRetry && result.stderr.includes('ENOTEMPTY')) { - return this.handleNpmNotEmptyError({ npmUrl, options, debug, result }); - } - - console.error(result.stderr); - console.error(`host.${hostname} Cannot install ${npmUrl}: ${result.exitCode}`); - return this.processExit(EXIT_CODES.CANNOT_INSTALL_NPM_PACKET); } + if (!isRetry && result.stderr.includes('ENOTEMPTY')) { + return this.handleNpmNotEmptyError({ npmUrl, options, debug, result }); + } + + console.error(result.stderr); + console.error(`host.${hostname} Cannot install ${npmUrl}: ${result.exitCode}`); + return this.processExit(EXIT_CODES.CANNOT_INSTALL_NPM_PACKET); } /** @@ -537,9 +536,8 @@ export class Install { `host.${hostname} Invalid version of "${dName}". Installed "${packJson.version}", required "${version}"`, ); return this.processExit(EXIT_CODES.INVALID_DEPENDENCY_VERSION); - } else { - isFound = true; } + isFound = true; } else { isFound = true; } @@ -577,9 +575,8 @@ export class Install { `host.${hostname} Invalid version of "${dName}". Installed "${instanceVersion}", required "${deps[dName]}"`, ); return this.processExit(EXIT_CODES.INVALID_DEPENDENCY_VERSION); - } else { - isFound = true; } + isFound = true; } for (const instance of gInstances) { @@ -593,9 +590,8 @@ export class Install { `host.${hostname} Invalid version of "${dName}". Installed "${instanceVersion}", required "${globalDeps[dName]}"`, ); return this.processExit(EXIT_CODES.INVALID_DEPENDENCY_VERSION); - } else { - isFound = true; } + isFound = true; } } @@ -944,7 +940,7 @@ export class Install { _id: `system.adapter.${adapter}.upload`, type: 'state', common: { - name: adapter + '.upload', + name: `${adapter}.upload`, type: 'number', read: true, write: false, @@ -1100,12 +1096,11 @@ export class Install { .filter(row => { if (instance !== undefined || !row.value.common?.host || row.value.common?.host === hostname) { return true; - } else { - if (!notDeleted.includes(row.value._id)) { - notDeleted.push(row.value._id); - } - return false; } + if (!notDeleted.includes(row.value._id)) { + notDeleted.push(row.value._id); + } + return false; }) .map(row => row.value._id) .filter(id => !knownObjIDs.includes(id)); @@ -1184,13 +1179,12 @@ export class Install { await this.objects.setObjectAsync(obj._id, obj); return EXIT_CODES.CANNOT_DELETE_NON_DELETABLE; - } else { - // The adapter is deletable, remember it for deletion - knownObjIDs.push(obj._id); - console.log(`host.${hostname} Counted 1 adapter for ${adapter}`); - - return EXIT_CODES.NO_ERROR; } + // The adapter is deletable, remember it for deletion + knownObjIDs.push(obj._id); + console.log(`host.${hostname} Counted 1 adapter for ${adapter}`); + + return EXIT_CODES.NO_ERROR; } } catch (err) { console.error(`host.${hostname} Cannot enumerate adapters: ${err.message}`); @@ -1395,11 +1389,11 @@ export class Install { */ async _enumerateAdapterStates(knownStateIDs: string[], adapter: string, instance?: number): Promise { for (const pattern of [ - `io.${adapter}.${instance !== undefined ? instance + '.' : ''}*`, - `messagebox.${adapter}.${instance !== undefined ? instance + '.' : ''}*`, - `log.${adapter}.${instance !== undefined ? instance + '.' : ''}*`, - `${adapter}.${instance !== undefined ? instance + '.' : ''}*`, - `system.adapter.${adapter}.${instance !== undefined ? instance + '.' : ''}*`, + `io.${adapter}.${instance !== undefined ? `${instance}.` : ''}*`, + `messagebox.${adapter}.${instance !== undefined ? `${instance}.` : ''}*`, + `log.${adapter}.${instance !== undefined ? `${instance}.` : ''}*`, + `${adapter}.${instance !== undefined ? `${instance}.` : ''}*`, + `system.adapter.${adapter}.${instance !== undefined ? `${instance}.` : ''}*`, ]) { try { const ids = await this.states.getKeys(pattern); @@ -1892,14 +1886,13 @@ export class Install { if (instance === undefined) { // this adapter needs us locally and all instances should be deleted return `${row.value.common.name}.${row.id.split('.').pop()}`; + } + // check if another instance of us exists on this host + if (this._checkDependencyFulfilledThisHost(adapter, instance, doc.rows, scopedHostname)) { + // there are other instances of our adapter - ok + break; } else { - // check if another instance of us exists on this host - if (this._checkDependencyFulfilledThisHost(adapter, instance, doc.rows, scopedHostname)) { - // there are other instances of our adapter - ok - break; - } else { - return `${row.value.common.name}.${row.id.split('.').pop()}`; - } + return `${row.value.common.name}.${row.id.split('.').pop()}`; } } } diff --git a/packages/cli/src/lib/setup/setupList.ts b/packages/cli/src/lib/setup/setupList.ts index bd1b03214..67507f89a 100644 --- a/packages/cli/src/lib/setup/setupList.ts +++ b/packages/cli/src/lib/setup/setupList.ts @@ -130,7 +130,7 @@ export class List { const ts = new Date(file.modifiedAt); time = ts.toISOString(); time = time.replace('T', ' '); - time = time.substring(0, 16) + ' '; + time = `${time.substring(0, 16)} `; } text += time.padEnd(17); @@ -146,7 +146,7 @@ export class List { group = group.substring(13); text += ` ${group.padStart(14)}`; } else { - text += (file.isDir ? 'd' : '-') + '?????????' + new Array(31).join(' '); + text += `${file.isDir ? 'd' : '-'}?????????${new Array(31).join(' ')}`; } const size = file.stats && file.stats.size ? file.stats.size.toString() : ''; @@ -259,11 +259,11 @@ export class List { sortFiles(a: File, b: File): number { let a1 = a.path + a.file.file; if (a1[0] !== '/') { - a1 = '/' + a1; + a1 = `/${a1}`; } let b1 = b.path + b.file.file; if (b1[0] !== '/') { - b1 = '/' + b1; + b1 = `/${b1}`; } return a1.localeCompare(b1); } @@ -398,7 +398,7 @@ export class List { this.processExit(); return; } - const reg = filter ? new RegExp(tools.pattern2RegEx('system.adapter.' + filter)) : null; + const reg = filter ? new RegExp(tools.pattern2RegEx(`system.adapter.${filter}`)) : null; const adapterList: AdapterListEntry[] = []; for (const obj of objs.rows) { if (obj.value.type !== 'adapter') { @@ -497,15 +497,15 @@ export class List { }`; if (this.config.system && this.config.system.compact && row.value.common.compact) { - text += - ', compact ' + - (row.value.common.compact && row.value.common.runAsCompactMode + text += `, compact ${ + row.value.common.compact && row.value.common.runAsCompactMode ? `enabled (group ${ row.value.common.compactGroup !== undefined ? row.value.common.compactGroup : 1 })` - : 'disabled'); + : 'disabled' + }`; } if (row.value.native && row.value.native.port) { @@ -545,7 +545,7 @@ export class List { return; } const reg = filter - ? new RegExp(tools.pattern2RegEx('system.user.' + filter)) + ? new RegExp(tools.pattern2RegEx(`system.user.${filter}`)) : null; console.log( ' ID | Name | Active | Groups', @@ -608,7 +608,7 @@ export class List { this.processExit(); return; } - const reg = filter ? new RegExp(tools.pattern2RegEx('system.group.' + filter)) : null; + const reg = filter ? new RegExp(tools.pattern2RegEx(`system.group.${filter}`)) : null; console.log(''); console.log( ' system.group | object | state | file | user | others | users', @@ -675,40 +675,40 @@ export class List { let text = id.padEnd(19); text += ' | '; if (obj.value.common.acl?.object) { - text += (obj.value.common.acl.object.list ? '+' : '-') + ' '; - text += (obj.value.common.acl.object.read ? '+' : '-') + ' '; - text += (obj.value.common.acl.object.write ? '+' : '-') + ' '; - text += (obj.value.common.acl.object.delete ? '+' : '-') + ' '; + text += `${obj.value.common.acl.object.list ? '+' : '-'} `; + text += `${obj.value.common.acl.object.read ? '+' : '-'} `; + text += `${obj.value.common.acl.object.write ? '+' : '-'} `; + text += `${obj.value.common.acl.object.delete ? '+' : '-'} `; text += '|'; } else { text += ' |'; } if (obj.value.common.acl?.state) { text += ' '; - text += (obj.value.common.acl.state.list ? '+' : '-') + ' '; - text += (obj.value.common.acl.state.read ? '+' : '-') + ' '; - text += (obj.value.common.acl.state.write ? '+' : '-') + ' '; - text += (obj.value.common.acl.state.delete ? '+' : '-') + ' '; + text += `${obj.value.common.acl.state.list ? '+' : '-'} `; + text += `${obj.value.common.acl.state.read ? '+' : '-'} `; + text += `${obj.value.common.acl.state.write ? '+' : '-'} `; + text += `${obj.value.common.acl.state.delete ? '+' : '-'} `; text += '|'; } else { text += ' |'; } if (obj.value.common.acl?.file) { text += ' '; - text += (obj.value.common.acl.file.list ? '+' : '-') + ' '; - text += (obj.value.common.acl.file.read ? '+' : '-') + ' '; - text += (obj.value.common.acl.file.write ? '+' : '-') + ' '; - text += (obj.value.common.acl.file.create ? '+' : '-') + ' '; - text += (obj.value.common.acl.file.delete ? '+' : '-') + ' '; + text += `${obj.value.common.acl.file.list ? '+' : '-'} `; + text += `${obj.value.common.acl.file.read ? '+' : '-'} `; + text += `${obj.value.common.acl.file.write ? '+' : '-'} `; + text += `${obj.value.common.acl.file.create ? '+' : '-'} `; + text += `${obj.value.common.acl.file.delete ? '+' : '-'} `; text += '|'; } else { text += ' |'; } if (obj.value.common.acl?.users) { text += ' '; - text += (obj.value.common.acl.users.write ? '+' : '-') + ' '; - text += (obj.value.common.acl.users.create ? '+' : '-') + ' '; - text += (obj.value.common.acl.users.delete ? '+' : '-') + ' '; + text += `${obj.value.common.acl.users.write ? '+' : '-'} `; + text += `${obj.value.common.acl.users.create ? '+' : '-'} `; + text += `${obj.value.common.acl.users.delete ? '+' : '-'} `; text += '|'; } else { text += ' |'; @@ -717,12 +717,12 @@ export class List { text += ' '; let others = ''; for (const [r, otherPerm] of Object.entries(obj.value.common.acl.other)) { - others += r + (otherPerm ? '+' : '-') + ' '; + others += `${r + (otherPerm ? '+' : '-')} `; } text += `${others.padEnd(22)}|`; } else { - text += new Array(25).join(' ') + '|'; + text += `${new Array(25).join(' ')}|`; } if (obj.value.common.members) { @@ -767,7 +767,7 @@ export class List { } const reg = filter - ? new RegExp(tools.pattern2RegEx('system.host.' + filter)) + ? new RegExp(tools.pattern2RegEx(`system.host.${filter}`)) : null; for (const obj of objs.rows) { diff --git a/packages/cli/src/lib/setup/setupMultihost.ts b/packages/cli/src/lib/setup/setupMultihost.ts index 481e2870f..b6e8cc08e 100644 --- a/packages/cli/src/lib/setup/setupMultihost.ts +++ b/packages/cli/src/lib/setup/setupMultihost.ts @@ -278,7 +278,7 @@ export class Multihost { break; default: - process.stdout.write('\x1B[2K\x1B[200D' + query + new Array(rl.line.length + 1).join('*')); + process.stdout.write(`\x1B[2K\x1B[200D${query}${new Array(rl.line.length + 1).join('*')}`); break; } }); diff --git a/packages/cli/src/lib/setup/setupPacketManager.ts b/packages/cli/src/lib/setup/setupPacketManager.ts index a6f0a64f0..010622fb3 100644 --- a/packages/cli/src/lib/setup/setupPacketManager.ts +++ b/packages/cli/src/lib/setup/setupPacketManager.ts @@ -110,10 +110,9 @@ export class PacketManager { (err.stderr && err.stderr.includes('dpkg --help')) ) { return true; - } else { - this.logger.error(`Cannot detect dpkg: ${err.stderr || err.stdout || err}`); - return false; } + this.logger.error(`Cannot detect dpkg: ${err.stderr || err.stdout || err}`); + return false; } } @@ -125,10 +124,9 @@ export class PacketManager { // non zero exit code, however lets check if ok if ((err.stdout && err.stdout.includes('sudo -h')) || (err.stderr && err.stderr.includes('sudo -h'))) { return true; - } else { - this.logger.error(`Cannot detect sudo: ${err.stderr || err.stdout || err}`); - return false; } + this.logger.error(`Cannot detect sudo: ${err.stderr || err.stdout || err}`); + return false; } } diff --git a/packages/cli/src/lib/setup/setupRepo.ts b/packages/cli/src/lib/setup/setupRepo.ts index af2004eb6..3ead9b1e1 100644 --- a/packages/cli/src/lib/setup/setupRepo.ts +++ b/packages/cli/src/lib/setup/setupRepo.ts @@ -245,7 +245,7 @@ export class Repo { text = text.padEnd(11 + 15); if (sources[name].version) { - text += ': ' + sources[name].version; + text += `: ${sources[name].version}`; } text = text.padEnd(11 + 15 + 11); diff --git a/packages/cli/src/lib/setup/setupSetup.ts b/packages/cli/src/lib/setup/setupSetup.ts index 5dbf1eea3..2289e45a1 100644 --- a/packages/cli/src/lib/setup/setupSetup.ts +++ b/packages/cli/src/lib/setup/setupSetup.ts @@ -36,9 +36,9 @@ import { createRequire } from 'node:module'; import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); // eslint-disable-next-line unicorn/prefer-module -const require = createRequire(import.meta.url || 'file://' + __filename); +const require = createRequire(import.meta.url || `file://${__filename}`); const COLOR_RED = '\x1b[31m'; const COLOR_YELLOW = '\x1b[33m'; @@ -1487,7 +1487,7 @@ Please DO NOT copy files manually into ioBroker storage directories!`, // copy scripts to root directory if (fs.existsSync(path.join(CONTROLLER_DIR, '..', '..', 'node_modules'))) { const startFile = `#!/usr/bin/env node -require('${path.normalize(thisDir + '/..')}/setup').execute();`; +require('${path.normalize(`${thisDir}/..`)}/setup').execute();`; try { if (fs.existsSync(path.join(CONTROLLER_DIR, 'killall.sh'))) { diff --git a/packages/cli/src/lib/setup/setupUpgrade.ts b/packages/cli/src/lib/setup/setupUpgrade.ts index f7456b35a..0fb3b1f05 100644 --- a/packages/cli/src/lib/setup/setupUpgrade.ts +++ b/packages/cli/src/lib/setup/setupUpgrade.ts @@ -526,50 +526,49 @@ export class Upgrade { adapter.length < 15 ? new Array(15 - adapter.length).join(' ') : '' } is up to date.`, ); - } else { - const targetVersion = version || repoAdapter.version; + } + const targetVersion = version || repoAdapter.version; - const isIgnored = await isVersionIgnored({ - adapterName: adapter, - version: targetVersion, - objects: this.objects, - }); + const isIgnored = await isVersionIgnored({ + adapterName: adapter, + version: targetVersion, + objects: this.objects, + }); - if (isIgnored) { - console.log( - `No upgrade of "${adapter}" desired, because version "${targetVersion}" is configured to be ignored by the user. Run "${tools.appNameLowerCase} version ${adapter} --recognize" to allow this upgrade!`, - ); - return; - } + if (isIgnored) { + console.log( + `No upgrade of "${adapter}" desired, because version "${targetVersion}" is configured to be ignored by the user. Run "${tools.appNameLowerCase} version ${adapter} --recognize" to allow this upgrade!`, + ); + return; + } - try { - if (!showUpgradeDialog(installedVersion, targetVersion, adapter)) { - console.log(`No upgrade of "${adapter}" desired.`); - return; - } - } catch (e) { - console.log(`Can not check version information to display upgrade infos: ${e.message}`); + try { + if (!showUpgradeDialog(installedVersion, targetVersion, adapter)) { + console.log(`No upgrade of "${adapter}" desired.`); + return; } - console.log(`Update ${adapter} from @${installedVersion} to @${targetVersion}`); - const npmPacketName = `${tools.appNameLowerCase}.${adapter}`; + } catch (e) { + console.log(`Can not check version information to display upgrade infos: ${e.message}`); + } + console.log(`Update ${adapter} from @${installedVersion} to @${targetVersion}`); + const npmPacketName = `${tools.appNameLowerCase}.${adapter}`; - try { - if (!semver.diff(installedVersion, targetVersion)) { - console.log(`Uninstall npm packet "${npmPacketName}" for a clean re-installation`); - await tools.uninstallNodeModule(npmPacketName, { debug: process.argv.includes('--debug') }); - } - } catch (e) { - console.warn(`Could not uninstall npm packet "${npmPacketName}": ${e.message}`); + try { + if (!semver.diff(installedVersion, targetVersion)) { + console.log(`Uninstall npm packet "${npmPacketName}" for a clean re-installation`); + await tools.uninstallNodeModule(npmPacketName, { debug: process.argv.includes('--debug') }); } - - // Get the adapter from website - const { packetName, stoppedList } = await this.install.downloadPacket( - sources, - `${adapter}@${targetVersion}`, - ); - await finishUpgrade(packetName); - await this.install.enableInstances(stoppedList, true); + } catch (e) { + console.warn(`Could not uninstall npm packet "${npmPacketName}": ${e.message}`); } + + // Get the adapter from website + const { packetName, stoppedList } = await this.install.downloadPacket( + sources, + `${adapter}@${targetVersion}`, + ); + await finishUpgrade(packetName); + await this.install.enableInstances(stoppedList, true); } else if (repoAdapter.meta) { // Read repository from url or file const ioPack = (await tools.getJsonAsync(repoAdapter.meta)) as ioBroker.AdapterObject; diff --git a/packages/cli/src/lib/setup/setupUpload.ts b/packages/cli/src/lib/setup/setupUpload.ts index 41bba23d7..a4baf4331 100644 --- a/packages/cli/src/lib/setup/setupUpload.ts +++ b/packages/cli/src/lib/setup/setupUpload.ts @@ -40,7 +40,7 @@ type MinimalLogger = Omit; export class Upload { private readonly states: StatesRedisClient; private readonly objects: ObjectsRedisClient; - private readonly regApp = new RegExp('/' + tools.appName.replace(/\./g, '\\.') + '\\.', 'i'); + private readonly regApp = new RegExp(`/${tools.appName.replace(/\./g, '\\.')}\\.`, 'i'); private callbackId = 1; private readonly sendToHostFromCliAsync: (...args: any[]) => Promise; private callbacks: Record = {}; @@ -96,9 +96,8 @@ export class Upload { if (onlyAlive) { return this.checkHostsIfAlive(hosts); - } else { - return hosts; } + return hosts; } // Check if some adapters must be restarted and restart them @@ -540,10 +539,9 @@ export class Upload { if (isAdmin) { return adapter; - } else { - await this.checkRestartOther(adapter); - return adapter; } + await this.checkRestartOther(adapter); + return adapter; } // check for common.wwwDontUpload (required for legacy adapters and admin) diff --git a/packages/cli/src/lib/setup/setupUsers.ts b/packages/cli/src/lib/setup/setupUsers.ts index 5e422c0df..8376baec4 100644 --- a/packages/cli/src/lib/setup/setupUsers.ts +++ b/packages/cli/src/lib/setup/setupUsers.ts @@ -40,29 +40,28 @@ export class Users { this.objects.getObject(`system.user.${_user}`, (err, obj) => { if (obj) { return tools.maybeCallbackWithError(callback, 'User yet exists'); - } else { - this.objects.setObject( - `system.user.${_user}`, - { - type: 'user', - common: { - name: username, - enabled: true, - password: '', - }, - from: `system.host.${tools.getHostName()}.cli`, - ts: Date.now(), - native: {}, - }, - err => { - if (!err) { - this.setPassword(username, pw, callback); - } else { - return tools.maybeCallbackWithError(callback, err); - } - }, - ); } + this.objects.setObject( + `system.user.${_user}`, + { + type: 'user', + common: { + name: username, + enabled: true, + password: '', + }, + from: `system.host.${tools.getHostName()}.cli`, + ts: Date.now(), + native: {}, + }, + err => { + if (!err) { + this.setPassword(username, pw, callback); + } else { + return tools.maybeCallbackWithError(callback, err); + } + }, + ); }); } @@ -149,59 +148,51 @@ export class Users { this.objects.getObject(`system.user.${_user}`, (err, obj) => { if (err || !obj) { return tools.maybeCallbackWithError(callback, 'User does not exist'); - } else { - if (obj.common.dontDelete) { - return tools.maybeCallbackWithError(callback, 'Cannot delete user, while is system user'); - } else { - this.objects.delObject('system.user.' + _user, err => { - // Remove this user from all groups - if (!err) { - this.objects.getObjectList( - { startkey: 'system.group.', endkey: 'system.group.\u9999' }, - (err, groups) => { - if (!groups) { - return tools.maybeCallback(callback); - } - - let count = 0; - for (let i = 0; i < groups.rows.length; i++) { - if (groups.rows[i].value.type !== 'group') { - continue; - } - // find all groups - if ( - groups.rows[i].value.common.members && - groups.rows[i].value.common.members.indexOf('system.user.' + _user) !== -1 - ) { - const pos = groups.rows[i].value.common.members.indexOf( - 'system.user.' + _user, - ); - groups.rows[i].value.common.members.splice(pos, 1); - count++; - groups.rows[i].value.from = 'system.host.' + tools.getHostName() + '.cli'; - groups.rows[i].value.ts = Date.now(); - this.objects.setObject( - groups.rows[i].value._id, - groups.rows[i].value, - err => { - if (!--count) { - return tools.maybeCallbackWithError(callback, err); - } - }, - ); + } + if (obj.common.dontDelete) { + return tools.maybeCallbackWithError(callback, 'Cannot delete user, while is system user'); + } + this.objects.delObject(`system.user.${_user}`, err => { + // Remove this user from all groups + if (!err) { + this.objects.getObjectList( + { startkey: 'system.group.', endkey: 'system.group.\u9999' }, + (err, groups) => { + if (!groups) { + return tools.maybeCallback(callback); + } + + let count = 0; + for (let i = 0; i < groups.rows.length; i++) { + if (groups.rows[i].value.type !== 'group') { + continue; + } + // find all groups + if ( + groups.rows[i].value.common.members && + groups.rows[i].value.common.members.indexOf(`system.user.${_user}`) !== -1 + ) { + const pos = groups.rows[i].value.common.members.indexOf(`system.user.${_user}`); + groups.rows[i].value.common.members.splice(pos, 1); + count++; + groups.rows[i].value.from = `system.host.${tools.getHostName()}.cli`; + groups.rows[i].value.ts = Date.now(); + this.objects.setObject(groups.rows[i].value._id, groups.rows[i].value, err => { + if (!--count) { + return tools.maybeCallbackWithError(callback, err); } - } - if (!count) { - return tools.maybeCallback(callback); - } - }, - ); - } else { - return tools.maybeCallbackWithError(callback, err); - } - }); + }); + } + } + if (!count) { + return tools.maybeCallback(callback); + } + }, + ); + } else { + return tools.maybeCallbackWithError(callback, err); } - } + }); }); } @@ -234,7 +225,7 @@ export class Users { if (obj.common.members.indexOf(_user) === -1) { obj.common.members.push(_user); - obj.from = 'system.host.' + tools.getHostName() + '.cli'; + obj.from = `system.host.${tools.getHostName()}.cli`; obj.ts = Date.now(); this.objects.setObject(groupName, obj, err => { return tools.maybeCallbackWithError(callback, err); @@ -299,15 +290,13 @@ export class Users { this.addUser(username, result.password, err => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - this.addUserToGroup(username, groupName, err => { - if (err) { - return tools.maybeCallbackWithError(callback, err); - } else { - return tools.maybeCallback(callback); - } - }); } + this.addUserToGroup(username, groupName, err => { + if (err) { + return tools.maybeCallbackWithError(callback, err); + } + return tools.maybeCallback(callback); + }); }); } else { return tools.maybeCallbackWithError(callback, err); @@ -317,15 +306,13 @@ export class Users { this.addUser(username, password, err => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - this.addUserToGroup(username, groupName, err => { - if (err) { - return tools.maybeCallbackWithError(callback, err); - } else { - return tools.maybeCallback(callback); - } - }); } + this.addUserToGroup(username, groupName, err => { + if (err) { + return tools.maybeCallbackWithError(callback, err); + } + return tools.maybeCallback(callback); + }); }); } }); @@ -346,55 +333,52 @@ export class Users { const isExisting = await this.isUser(username); if (!isExisting) { return tools.maybeCallbackWithError(callback, `User "${username}" does not exist.`); - } else { - // Check group - if (!password) { - prompt.message = ''; - prompt.delimiter = ''; - const schema = { - properties: { - password: { - description: 'Enter your password:', - pattern: /^[^'"]*$/, - message: 'No " are allowed', - hidden: true, - }, - repeatPassword: { - description: 'Repeat your password:', - pattern: /^[^'"]*$/, - message: 'No " are allowed', - hidden: true, - }, + } + // Check group + if (!password) { + prompt.message = ''; + prompt.delimiter = ''; + const schema = { + properties: { + password: { + description: 'Enter your password:', + pattern: /^[^'"]*$/, + message: 'No " are allowed', + hidden: true, }, - } as const satisfies prompt.Schema; - prompt.start(); - - prompt.get>(schema, (err, result) => { - if (result) { - if (result.password !== result.repeatPassword) { - return tools.maybeCallbackWithError(callback, 'Passwords are not identical!'); - } + repeatPassword: { + description: 'Repeat your password:', + pattern: /^[^'"]*$/, + message: 'No " are allowed', + hidden: true, + }, + }, + } as const satisfies prompt.Schema; + prompt.start(); - this.setPassword(username, result.password, err => { - if (err) { - return tools.maybeCallbackWithError(callback, err); - } else { - return tools.maybeCallback(callback); - } - }); - } else { - return tools.maybeCallbackWithError(callback, 'No password entered!'); + prompt.get>(schema, (err, result) => { + if (result) { + if (result.password !== result.repeatPassword) { + return tools.maybeCallbackWithError(callback, 'Passwords are not identical!'); } - }); - } else { - this.setPassword(username, password, err => { - if (err) { - return tools.maybeCallbackWithError(callback, err); - } else { + + this.setPassword(username, result.password, err => { + if (err) { + return tools.maybeCallbackWithError(callback, err); + } return tools.maybeCallback(callback); - } - }); - } + }); + } else { + return tools.maybeCallbackWithError(callback, 'No password entered!'); + } + }); + } else { + this.setPassword(username, password, err => { + if (err) { + return tools.maybeCallbackWithError(callback, err); + } + return tools.maybeCallback(callback); + }); } } @@ -423,14 +407,13 @@ export class Users { } if (!obj) { return tools.maybeCallbackWithError(callback, `User "${username}" not found`); - } else { - obj.common.enabled = enable; - obj.from = `system.host.${tools.getHostName()}.cli`; - obj.ts = Date.now(); - this.objects.setObject(obj._id, obj, err => { - return tools.maybeCallbackWithError(callback, err); - }); } + obj.common.enabled = enable; + obj.from = `system.host.${tools.getHostName()}.cli`; + obj.ts = Date.now(); + this.objects.setObject(obj._id, obj, err => { + return tools.maybeCallbackWithError(callback, err); + }); }); } @@ -470,9 +453,8 @@ export class Users { callback, `Password for user "${result.username}" does not match${err ? `: ${err.message}` : ''}`, ); - } else { - return tools.maybeCallbackWithError(callback, null); } + return tools.maybeCallbackWithError(callback, null); }); }); } else if (!password) { @@ -497,9 +479,8 @@ export class Users { callback, `Password for user "${username}" does not match${err ? `: ${err.message}` : ''}`, ); - } else { - return tools.maybeCallbackWithError(callback, null); } + return tools.maybeCallbackWithError(callback, null); }); }); } else { @@ -509,9 +490,8 @@ export class Users { callback, `Password for user "${username}" does not match${err ? `: ${err.message}` : ''}`, ); - } else { - return tools.maybeCallbackWithError(callback, null); } + return tools.maybeCallbackWithError(callback, null); }); } } @@ -529,9 +509,8 @@ export class Users { } if (!obj) { return tools.maybeCallbackWithError(callback, `User "${username}" not found`); - } else { - return tools.maybeCallbackWithError(callback, null, obj.common.enabled); } + return tools.maybeCallbackWithError(callback, null, obj.common.enabled); }); } @@ -548,9 +527,8 @@ export class Users { } if (!obj) { return tools.maybeCallbackWithError(callback, `Group "${group}" not found`); - } else { - return tools.maybeCallbackWithError(callback, null, obj.common.enabled, obj.common.members); } + return tools.maybeCallbackWithError(callback, null, obj.common.enabled, obj.common.members); }); } @@ -579,14 +557,13 @@ export class Users { } if (!obj) { return tools.maybeCallbackWithError(callback, `Group "${group}" not found`); - } else { - obj.common.enabled = enable; - obj.from = `system.host.${tools.getHostName()}.cli`; - obj.ts = Date.now(); - this.objects.setObject(obj._id, obj, err => { - return tools.maybeCallbackWithError(callback, err); - }); } + obj.common.enabled = enable; + obj.from = `system.host.${tools.getHostName()}.cli`; + obj.ts = Date.now(); + this.objects.setObject(obj._id, obj, err => { + return tools.maybeCallbackWithError(callback, err); + }); }); } @@ -627,17 +604,15 @@ export class Users { if (group === 'administrator') { return tools.maybeCallbackWithError(callback, 'Group "administrator" cannot be deleted'); - } else { - this.objects.getObject(`system.group.${_group}`, (err, obj) => { - if (!obj) { - return tools.maybeCallbackWithError(callback, 'Group does not exists'); - } else { - this.objects.delObject(`system.group.${_group}`, err => { - return tools.maybeCallbackWithError(callback, err); - }); - } - }); } + this.objects.getObject(`system.group.${_group}`, (err, obj) => { + if (!obj) { + return tools.maybeCallbackWithError(callback, 'Group does not exists'); + } + this.objects.delObject(`system.group.${_group}`, err => { + return tools.maybeCallbackWithError(callback, err); + }); + }); } /** @@ -652,19 +627,17 @@ export class Users { this.objects.getObject(`system.group.${_group}`, (err, obj) => { if (!obj) { return tools.maybeCallbackWithError(callback, 'Group does not exists'); - } else { - const pos = obj.common.members.indexOf(`system.user.${username}`); - if (pos === -1) { - return tools.maybeCallbackWithError(callback, 'User not in group'); - } else { - obj.common.members.splice(pos, 1); - obj.from = `system.host.${tools.getHostName()}.cli`; - obj.ts = Date.now(); - this.objects.setObject(obj._id, obj, err => { - return tools.maybeCallbackWithError(callback, err); - }); - } } + const pos = obj.common.members.indexOf(`system.user.${username}`); + if (pos === -1) { + return tools.maybeCallbackWithError(callback, 'User not in group'); + } + obj.common.members.splice(pos, 1); + obj.from = `system.host.${tools.getHostName()}.cli`; + obj.ts = Date.now(); + this.objects.setObject(obj._id, obj, err => { + return tools.maybeCallbackWithError(callback, err); + }); }); } } diff --git a/packages/cli/src/lib/setup/setupVendor.ts b/packages/cli/src/lib/setup/setupVendor.ts index 1ff9ff14d..6b52556a0 100644 --- a/packages/cli/src/lib/setup/setupVendor.ts +++ b/packages/cli/src/lib/setup/setupVendor.ts @@ -178,7 +178,7 @@ export class Vendor { const arr = await this.objects.getObjectListAsync( { startkey: id, - endkey: id + '\u9999', + endkey: `${id}\u9999`, }, { checked: true }, ); diff --git a/packages/common-db/src/lib/common/aliasProcessing.ts b/packages/common-db/src/lib/common/aliasProcessing.ts index 78a69c003..e419e0bcf 100644 --- a/packages/common-db/src/lib/common/aliasProcessing.ts +++ b/packages/common-db/src/lib/common/aliasProcessing.ts @@ -69,10 +69,9 @@ export function applyAliasConvenienceConversion(options: ApplyAliasConvenienceCo const lowerVal = typeof state.val === 'string' ? state.val.toLowerCase() : state.val; if (lowerVal === 'off' || lowerVal === 'aus' || state.val === '0') { return false; - } else { - // this also handles strings like "EIN" or such that will be true - return !!state.val; } + // this also handles strings like "EIN" or such that will be true + return !!state.val; } else if (targetCommon.type === 'number' && typeof state.val === 'string') { return parseFloat(state.val); } else if (targetCommon.type === 'string') { diff --git a/packages/common-db/src/lib/common/logger.ts b/packages/common-db/src/lib/common/logger.ts index 205c81979..f6e39e7dc 100644 --- a/packages/common-db/src/lib/common/logger.ts +++ b/packages/common-db/src/lib/common/logger.ts @@ -13,10 +13,10 @@ import * as url from 'node:url'; import { createRequire } from 'node:module'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); // eslint-disable-next-line unicorn/prefer-module -const require = createRequire(import.meta.url || 'file://' + __filename); +const require = createRequire(import.meta.url || `file://${__filename}`); const hostname = tools.getHostName(); @@ -197,7 +197,7 @@ export function logger( transport.level = transport.level || level; if (transport.type === 'file' && transport.enabled !== false) { - transport.filename = transport.filename || 'log/' + tools.appName; + transport.filename = transport.filename || `log/${tools.appName}`; if (!transport.fileext && transport.filename.indexOf('.log') === -1) { transport.fileext = '.log'; @@ -419,9 +419,8 @@ export function logger( transport = transport.transport ? transport.transport : transport; /** @ts-expect-error we use undocumented stuff here TODO */ return `${transport.dirname}/${transport.filename.replace('%DATE%', getDate())}`; - } else { - return ''; } + return ''; }; log.on('error', error => { diff --git a/packages/common-db/src/lib/common/tools.ts b/packages/common-db/src/lib/common/tools.ts index ac38ba4c0..b531225c3 100644 --- a/packages/common-db/src/lib/common/tools.ts +++ b/packages/common-db/src/lib/common/tools.ts @@ -34,9 +34,9 @@ import { createRequire } from 'node:module'; import type { WithRequired } from '@iobroker/types-dev'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); // eslint-disable-next-line unicorn/prefer-module -const require = createRequire(import.meta.url || 'file://' + __filename); +const require = createRequire(import.meta.url || `file://${__filename}`); type DockerInformation = | { @@ -238,13 +238,12 @@ export function checkNonEditable( if (oldObject.nonEdit.passHash !== hash) { delete newObject.nonEdit; return false; - } else { - oldObject.nonEdit = deepClone(newObject.nonEdit); - delete oldObject.nonEdit.password; - delete newObject.nonEdit.password; - oldObject.nonEdit.passHash = hash; - newObject.nonEdit.passHash = hash; } + oldObject.nonEdit = deepClone(newObject.nonEdit); + delete oldObject.nonEdit.password; + delete newObject.nonEdit.password; + oldObject.nonEdit.passHash = hash; + newObject.nonEdit.passHash = hash; copyAttributes(newObject.nonEdit, newObject, newObject); @@ -256,9 +255,8 @@ export function checkNonEditable( } return true; - } else { - newObject.nonEdit = oldObject.nonEdit; } + newObject.nonEdit = oldObject.nonEdit; } else if (newObject.nonEdit) { oldObject.nonEdit = deepClone(newObject.nonEdit); if (newObject.nonEdit.password) { @@ -410,17 +408,14 @@ function findPath(path: string, url: string): string { } if (url.startsWith('http://') || url.startsWith('https://')) { return url; - } else { - if (path.startsWith('http://') || path.startsWith('https://')) { - return (path + url).replace(/\/\//g, '/').replace('http:/', 'http://').replace('https:/', 'https://'); - } else { - if (url[0] === '/') { - return `${thisDir}/..${url}`; - } else { - return `${thisDir}/../${path}${url}`; - } - } } + if (path.startsWith('http://') || path.startsWith('https://')) { + return (path + url).replace(/\/\//g, '/').replace('http:/', 'http://').replace('https:/', 'https://'); + } + if (url[0] === '/') { + return `${thisDir}/..${url}`; + } + return `${thisDir}/../${path}${url}`; } /** @@ -711,30 +706,25 @@ export async function createUuid(objects: any): Promise { const licObj: ioBroker.Object = objects.getObject('system.adapter.vis.0'); if (!licObj || !licObj.native || !licObj.native.license) { return updateUuid('', objects); - } else { - // decode obj.native.license - let data; - try { - data = jwt.decode(licObj.native.license); - } catch { - data = null; - } + } + // decode obj.native.license + let data; + try { + data = jwt.decode(licObj.native.license); + } catch { + data = null; + } - if (!data || typeof data === 'string' || !data.uuid) { - // generate new UUID - return updateUuid('', objects); - } else { - if (data.uuid !== obj.native.uuid) { - return updateUuid(data.correct ? data.uuid : '', objects); - } else { - // Show error - console.warn( - `Your iobroker.vis license must be updated. Please contact info@iobroker.net to get a new license!`, - ); - console.warn(`Provide following information in email: ${data.email}, invoice: ${data.invoice}`); - } - } + if (!data || typeof data === 'string' || !data.uuid) { + // generate new UUID + return updateUuid('', objects); } + if (data.uuid !== obj.native.uuid) { + return updateUuid(data.correct ? data.uuid : '', objects); + } + // Show error + console.warn(`Your iobroker.vis license must be updated. Please contact info@iobroker.net to get a new license!`); + console.warn(`Provide following information in email: ${data.email}, invoice: ${data.invoice}`); } /** @@ -904,48 +894,46 @@ export async function getJsonAsync(urlOrPath: string, agent?: string): Promise status !== 200, + }); + return result.data; + } catch (e) { + console.warn(`Cannot download json from ${urlOrPath}. Error: ${e.message}`); + return null; + } } else { - if (urlOrPath.startsWith('http://') || urlOrPath.startsWith('https://')) { + if (fs.existsSync(urlOrPath)) { try { - const result = await axios(urlOrPath, { - timeout: 10000, - headers: { 'User-Agent': agent }, - validateStatus: status => status !== 200, - }); - return result.data; + sources = fs.readJSONSync(urlOrPath); } catch (e) { - console.warn(`Cannot download json from ${urlOrPath}. Error: ${e.message}`); + console.warn(`Cannot parse json file from ${urlOrPath}. Error: ${e.message}`); return null; } - } else { - if (fs.existsSync(urlOrPath)) { - try { - sources = fs.readJSONSync(urlOrPath); - } catch (e) { - console.warn(`Cannot parse json file from ${urlOrPath}. Error: ${e.message}`); - return null; - } - return sources; - } else if (fs.existsSync(thisDir + '/../' + urlOrPath)) { - try { - sources = fs.readJSONSync(`${thisDir}/../${urlOrPath}`); - } catch (e) { - console.warn(`Cannot parse json file from ${thisDir}/../${urlOrPath}. Error: ${e.message}`); - return null; - } - return sources; - } else if (fs.existsSync(`${thisDir}/../tmp/${urlOrPath}`)) { - try { - sources = fs.readJSONSync(`${thisDir}/../tmp/${urlOrPath}`); - } catch (e) { - console.log(`Cannot parse json file from ${thisDir}/../tmp/${urlOrPath}. Error: ${e.message}`); - return null; - } - return sources; - } else { + return sources; + } else if (fs.existsSync(`${thisDir}/../${urlOrPath}`)) { + try { + sources = fs.readJSONSync(`${thisDir}/../${urlOrPath}`); + } catch (e) { + console.warn(`Cannot parse json file from ${thisDir}/../${urlOrPath}. Error: ${e.message}`); + return null; + } + return sources; + } else if (fs.existsSync(`${thisDir}/../tmp/${urlOrPath}`)) { + try { + sources = fs.readJSONSync(`${thisDir}/../tmp/${urlOrPath}`); + } catch (e) { + console.log(`Cannot parse json file from ${thisDir}/../tmp/${urlOrPath}. Error: ${e.message}`); return null; } + return sources; } + return null; } } @@ -1605,11 +1593,10 @@ export function getAdapterDir(adapter: string): string | null { if (!adapterPath) { return null; // inactive - } else { - const parts = path.normalize(adapterPath).split(/[\\/]/g); - parts.pop(); - return parts.join('/'); } + const parts = path.normalize(adapterPath).split(/[\\/]/g); + parts.pop(); + return parts.join('/'); } /** @@ -2352,30 +2339,29 @@ export function promisify( function (error: string | Error, result: any) { if (error) { return reject(error instanceof Error ? error : new Error(error)); - } else { - // decide on how we want to return the callback arguments - switch (arguments.length) { - case 1: // only an error was given - return resolve(); // Promise - case 2: // a single value (result) was returned - return resolve(result); - default: { - // multiple values should be returned - let ret: Record | any[]; - // eslint-disable-next-line prefer-rest-params - const extraArgs = sliceArgs(arguments, 1); - if (returnArgNames && returnArgNames.length === extraArgs.length) { - // we can build an object - ret = {}; - for (let i = 0; i < returnArgNames.length; i++) { - ret[returnArgNames[i]] = extraArgs[i]; - } - } else { - // we return the raw array - ret = extraArgs; + } + // decide on how we want to return the callback arguments + switch (arguments.length) { + case 1: // only an error was given + return resolve(); // Promise + case 2: // a single value (result) was returned + return resolve(result); + default: { + // multiple values should be returned + let ret: Record | any[]; + // eslint-disable-next-line prefer-rest-params + const extraArgs = sliceArgs(arguments, 1); + if (returnArgNames && returnArgNames.length === extraArgs.length) { + // we can build an object + ret = {}; + for (let i = 0; i < returnArgNames.length; i++) { + ret[returnArgNames[i]] = extraArgs[i]; } - return resolve(ret); + } else { + // we return the raw array + ret = extraArgs; } + return resolve(ret); } } }, @@ -3420,7 +3406,7 @@ export function getInstanceIndicatorObjects(namespace: string): ioBroker.StateOb _id: `${id}.cputime`, type: 'state', common: { - name: namespace + '.cputime', + name: `${namespace}.cputime`, type: 'number', read: true, write: false, @@ -3699,78 +3685,74 @@ export async function updateLicenses(objects: any, login: string, password: stri // if login and password provided in the message, just try to read without saving it in system.licenses if (login && password) { return _readLicenses(login, password); - } else { - // get actual object - const systemLicenses: ioBroker.Object = await objects.getObjectAsync('system.licenses'); - // If password and login exist - if (systemLicenses && systemLicenses.native && systemLicenses.native.password && systemLicenses.native.login) { - try { - // get the secret to decode the password - const systemConfig: ioBroker.Object = await objects.getObjectAsync('system.config'); + } + // get actual object + const systemLicenses: ioBroker.Object = await objects.getObjectAsync('system.licenses'); + // If password and login exist + if (systemLicenses && systemLicenses.native && systemLicenses.native.password && systemLicenses.native.login) { + try { + // get the secret to decode the password + const systemConfig: ioBroker.Object = await objects.getObjectAsync('system.config'); - // decode the password - let password; - try { - password = decrypt(systemConfig.native.secret, systemLicenses.native.password); - } catch (err) { - throw new Error(`Cannot decode password: ${err.message}`); - } + // decode the password + let password; + try { + password = decrypt(systemConfig.native.secret, systemLicenses.native.password); + } catch (err) { + throw new Error(`Cannot decode password: ${err.message}`); + } - // read licenses from iobroker.net - const licenses = await _readLicenses(systemLicenses.native.login, password); - // save licenses to system.licenses and remember the time. - // merge the information together - const oldLicenses: any[] = systemLicenses.native.licenses || []; - systemLicenses.native.licenses = licenses; - oldLicenses.forEach(oldLicense => { - if (oldLicense.usedBy) { - const newLicense = licenses.find(item => item.json === oldLicense.json); - if (newLicense) { - newLicense.usedBy = oldLicense.usedBy; - } + // read licenses from iobroker.net + const licenses = await _readLicenses(systemLicenses.native.login, password); + // save licenses to system.licenses and remember the time. + // merge the information together + const oldLicenses: any[] = systemLicenses.native.licenses || []; + systemLicenses.native.licenses = licenses; + oldLicenses.forEach(oldLicense => { + if (oldLicense.usedBy) { + const newLicense = licenses.find(item => item.json === oldLicense.json); + if (newLicense) { + newLicense.usedBy = oldLicense.usedBy; } - }); + } + }); - systemLicenses.native.readTime = new Date().toISOString(); + systemLicenses.native.readTime = new Date().toISOString(); - // update read time - await objects.setObjectAsync('system.licenses', systemLicenses); - return licenses; - } catch (err) { - // if password is invalid + // update read time + await objects.setObjectAsync('system.licenses', systemLicenses); + return licenses; + } catch (err) { + // if password is invalid + if (err.message.includes('Authentication required') || err.message.includes('Cannot decode password:')) { + // clear existing licenses if exist if ( - err.message.includes('Authentication required') || - err.message.includes('Cannot decode password:') + systemLicenses && + systemLicenses.native && + systemLicenses.native.licenses && + systemLicenses.native.licenses.length ) { - // clear existing licenses if exist - if ( - systemLicenses && - systemLicenses.native && - systemLicenses.native.licenses && - systemLicenses.native.licenses.length - ) { - systemLicenses.native.licenses = []; - systemLicenses.native.readTime = new Date().toISOString(); - await objects.setObjectAsync('system.licenses', systemLicenses); - } + systemLicenses.native.licenses = []; + systemLicenses.native.readTime = new Date().toISOString(); + await objects.setObjectAsync('system.licenses', systemLicenses); } - - throw err; } - } else { - // if password or login are empty => clear existing licenses if exist - if ( - systemLicenses && - systemLicenses.native && - systemLicenses.native.licenses && - systemLicenses.native.licenses.length - ) { - systemLicenses.native.licenses = []; - systemLicenses.native.readTime = new Date().toISOString(); - await objects.setObjectAsync('system.licenses', systemLicenses); - } - throw new Error('No password or login'); + + throw err; + } + } else { + // if password or login are empty => clear existing licenses if exist + if ( + systemLicenses && + systemLicenses.native && + systemLicenses.native.licenses && + systemLicenses.native.licenses.length + ) { + systemLicenses.native.licenses = []; + systemLicenses.native.readTime = new Date().toISOString(); + await objects.setObjectAsync('system.licenses', systemLicenses); } + throw new Error('No password or login'); } } diff --git a/packages/common/src/lib/common/zipFiles.ts b/packages/common/src/lib/common/zipFiles.ts index f3a093615..2d3edb55e 100644 --- a/packages/common/src/lib/common/zipFiles.ts +++ b/packages/common/src/lib/common/zipFiles.ts @@ -154,7 +154,7 @@ async function _checkDir(_options: CheckDirOptions): Promise { return; } - root += '/' + parts.shift(); + root += `/${parts.shift()}`; try { await objects.readDirAsync(id, root, options); @@ -262,10 +262,10 @@ export async function readObjectsAsZip( try { data = options.stringify(data, options ? options.settings : null); } catch { - data.id = keys[f].replace(/\./g, '/').substring(rootId.length + 1) + '.json'; + data.id = `${keys[f].replace(/\./g, '/').substring(rootId.length + 1)}.json`; } } else { - data.id = keys[f].replace(/\./g, '/').substring(rootId.length + 1) + '.json'; + data.id = `${keys[f].replace(/\./g, '/').substring(rootId.length + 1)}.json`; } if (typeof data.data === 'object') { data.data = JSON.stringify(data.data, null, 2); diff --git a/packages/controller/src/lib/multihostServer.js b/packages/controller/src/lib/multihostServer.js index 738c28161..4a1215831 100644 --- a/packages/controller/src/lib/multihostServer.js +++ b/packages/controller/src/lib/multihostServer.js @@ -112,7 +112,7 @@ export function MHServer(hostname, logger, config, info, ips, secret) { const ts = new Date().getTime(); checkAuthList(ts); - const id = rinfo.address + ':' + rinfo.port; + const id = `${rinfo.address}:${rinfo.port}`; switch (msg.cmd) { case 'browse': @@ -208,14 +208,14 @@ export function MHServer(hostname, logger, config, info, ips, secret) { if (count > 10) { return logger.warn( - 'host.' + hostname + ' Multi-host discovery server: Port ' + PORT + ' is occupied. Service stopped.', + `host.${hostname} Multi-host discovery server: Port ${PORT} is occupied. Service stopped.`, ); } server = dgram.createSocket({ type: 'udp4', reuseAddr: true }); server.on('error', err => { - logger.error('host.' + hostname + ' Multi-host discovery server: error: ' + err.stack); + logger.error(`host.${hostname} Multi-host discovery server: error: ${err.stack}`); server.close(); server = null; @@ -242,7 +242,7 @@ export function MHServer(hostname, logger, config, info, ips, secret) { // following messages are allowed const text = msg.toString(); const now = new Date().getTime(); - const id = rinfo.address + ':' + rinfo.port; + const id = `${rinfo.address}:${rinfo.port}`; for (const ids in buffer) { if (!lastFrame[ids]) { diff --git a/packages/controller/src/lib/restart.ts b/packages/controller/src/lib/restart.ts index b5bb34f29..4e672a554 100644 --- a/packages/controller/src/lib/restart.ts +++ b/packages/controller/src/lib/restart.ts @@ -56,7 +56,7 @@ export default async function restart(callback?: () => void): Promise { } // eslint-disable-next-line unicorn/prefer-module -const modulePath = url.fileURLToPath(import.meta.url || 'file://' + __filename); +const modulePath = url.fileURLToPath(import.meta.url || `file://${__filename}`); if (process.argv[1] === modulePath) { restart(); } diff --git a/packages/controller/src/lib/upgradeManager.ts b/packages/controller/src/lib/upgradeManager.ts index d539fb2ef..d9a0c04ad 100644 --- a/packages/controller/src/lib/upgradeManager.ts +++ b/packages/controller/src/lib/upgradeManager.ts @@ -428,7 +428,7 @@ function registerErrorHandlers(upgradeManager: UpgradeManager): void { * else it will be canceled when the file itself stops the controller */ // eslint-disable-next-line unicorn/prefer-module -const modulePath = url.fileURLToPath(import.meta.url || 'file://' + __filename); +const modulePath = url.fileURLToPath(import.meta.url || `file://${__filename}`); if (process.argv[1] === modulePath) { main(); } diff --git a/packages/controller/src/main.ts b/packages/controller/src/main.ts index faceba371..70269edb0 100644 --- a/packages/controller/src/main.ts +++ b/packages/controller/src/main.ts @@ -63,9 +63,9 @@ import { getHostObjects } from '@/lib/objects.js'; import * as url from 'node:url'; import { createRequire } from 'node:module'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); // eslint-disable-next-line unicorn/prefer-module -const require = createRequire(import.meta.url || 'file://' + __filename); +const require = createRequire(import.meta.url || `file://${__filename}`); type DiagInfoType = 'extended' | 'normal' | 'no-city' | 'none'; type Dependencies = string[] | Record[] | string | Record; @@ -1370,31 +1370,30 @@ async function checkHost(): Promise { logger.info(`${hostLogPrefix} no instances found`); // no instances found return; - } else { - // reassign all instances - await changeHost(instanceDoc.rows, oldHostname, hostname); - logger.info(`${hostLogPrefix} Delete host ${oldId}`); + } + // reassign all instances + await changeHost(instanceDoc.rows, oldHostname, hostname); + logger.info(`${hostLogPrefix} Delete host ${oldId}`); - try { - // delete host object - await objects!.delObjectAsync(oldId); - } catch { - // ignore - } + try { + // delete host object + await objects!.delObjectAsync(oldId); + } catch { + // ignore + } - try { - // delete all hosts states - const newHostDoc = await objects!.getObjectViewAsync('system', 'state', { - startkey: `system.host.${oldHostname}.`, - endkey: `system.host.${oldHostname}.\u9999`, - include_docs: true, - }); + try { + // delete all hosts states + const newHostDoc = await objects!.getObjectViewAsync('system', 'state', { + startkey: `system.host.${oldHostname}.`, + endkey: `system.host.${oldHostname}.\u9999`, + include_docs: true, + }); - await delObjects(newHostDoc.rows); - return; - } catch { - // ignore - } + await delObjects(newHostDoc.rows); + return; + } catch { + // ignore } } } @@ -1407,187 +1406,183 @@ async function checkHost(): Promise { async function collectDiagInfo(type: DiagInfoType): Promise | null> { if (type !== 'extended' && type !== 'normal' && type !== 'no-city') { return null; - } else { - let systemConfig; - let err; - - try { - systemConfig = await objects!.getObject(SYSTEM_CONFIG_ID); - } catch (e) { - err = e; - } + } + let systemConfig; + let err; - if (err || !systemConfig?.common) { - logger.warn( - `System config object is corrupt, please run "${tools.appNameLowerCase} setup first". Error: ${err.message}`, - ); - systemConfig = systemConfig || { common: {} }; - systemConfig.common = systemConfig.common || {}; - } + try { + systemConfig = await objects!.getObject(SYSTEM_CONFIG_ID); + } catch (e) { + err = e; + } - let obj; - try { - obj = await objects!.getObjectAsync('system.meta.uuid'); - } catch { - // ignore obj is undefined - } + if (err || !systemConfig?.common) { + logger.warn( + `System config object is corrupt, please run "${tools.appNameLowerCase} setup first". Error: ${err.message}`, + ); + systemConfig = systemConfig || { common: {} }; + systemConfig.common = systemConfig.common || {}; + } - // create uuid - if (!obj) { - obj = { native: { uuid: 'not found' } }; - } + let obj; + try { + obj = await objects!.getObjectAsync('system.meta.uuid'); + } catch { + // ignore obj is undefined + } - let doc; - err = null; + // create uuid + if (!obj) { + obj = { native: { uuid: 'not found' } }; + } - try { - doc = await objects!.getObjectViewAsync('system', 'host', { - startkey: 'system.host.', - endkey: 'system.host.\u9999', - }); - } catch (e) { - err = e; - } + let doc; + err = null; - const { noCompactInstances, noInstances } = await _getNumberOfInstances(); + try { + doc = await objects!.getObjectViewAsync('system', 'host', { + startkey: 'system.host.', + endkey: 'system.host.\u9999', + }); + } catch (e) { + err = e; + } + + const { noCompactInstances, noInstances } = await _getNumberOfInstances(); + + // we need to show city and country at the beginning, so include it now and delete it later if not allowed. + const diag: Record = { + uuid: obj.native.uuid, + language: systemConfig.common.language, + country: '', + city: '', + hosts: [], + node: process.version, + arch: os.arch(), + docker: tools.isDocker(), + adapters: {}, + statesType: config.states.type, // redis or file + objectsType: config.objects.type, // redis or file + noInstances, + compactMode: config.system.compact, + noCompactInstances, + }; - // we need to show city and country at the beginning, so include it now and delete it later if not allowed. - const diag: Record = { - uuid: obj.native.uuid, - language: systemConfig.common.language, - country: '', - city: '', - hosts: [], - node: process.version, - arch: os.arch(), - docker: tools.isDocker(), - adapters: {}, - statesType: config.states.type, // redis or file - objectsType: config.objects.type, // redis or file - noInstances, - compactMode: config.system.compact, - noCompactInstances, - }; + if (type === 'extended' || type === 'no-city') { + const cpus = os.cpus(); + diag.country = 'country' in systemConfig.common ? systemConfig.common.country : 'unknown'; + diag.model = cpus && cpus[0] && cpus[0].model ? cpus[0].model : 'unknown'; + diag.cpus = cpus ? cpus.length : 1; + diag.mem = os.totalmem(); + diag.ostype = os.type(); + delete diag.city; + } + if (type === 'extended') { + diag.city = 'city' in systemConfig.common ? systemConfig.common.city : 'unknown'; + } else if (type === 'normal') { + delete diag.city; + delete diag.country; + } - if (type === 'extended' || type === 'no-city') { - const cpus = os.cpus(); - diag.country = 'country' in systemConfig.common ? systemConfig.common.country : 'unknown'; - diag.model = cpus && cpus[0] && cpus[0].model ? cpus[0].model : 'unknown'; - diag.cpus = cpus ? cpus.length : 1; - diag.mem = os.totalmem(); - diag.ostype = os.type(); - delete diag.city; - } - if (type === 'extended') { - diag.city = 'city' in systemConfig.common ? systemConfig.common.city : 'unknown'; - } else if (type === 'normal') { - delete diag.city; - delete diag.country; - } + if (!err && doc?.rows.length) { + doc.rows.sort((a, b) => { + try { + return semver.lt(a.value.common.installedVersion ?? '0.0.0', b.value.common.installedVersion ?? '0.0.0') + ? 1 + : 0; + } catch { + logger.error( + `${hostLogPrefix} Invalid versions: ${a.value.common.installedVersion ?? '0.0.0'}[${ + a.value.common.name ?? 'unknown' + }] or ${b.value.common.installedVersion ?? '0.0.0'}[${b.value.common.name ?? 'unknown'}]`, + ); + return 0; + } + }); - if (!err && doc?.rows.length) { - doc.rows.sort((a, b) => { - try { - return semver.lt( - a.value.common.installedVersion ?? '0.0.0', - b.value.common.installedVersion ?? '0.0.0', - ) - ? 1 - : 0; - } catch { - logger.error( - `${hostLogPrefix} Invalid versions: ${a.value.common.installedVersion ?? '0.0.0'}[${ - a.value.common.name ?? 'unknown' - }] or ${b.value.common.installedVersion ?? '0.0.0'}[${b.value.common.name ?? 'unknown'}]`, - ); - return 0; - } + // Read installed versions of all hosts + for (const row of doc.rows) { + diag.hosts.push({ + version: row.value.common.installedVersion, + platform: row.value.common.platform, + type: row.value.native.os.platform, }); - - // Read installed versions of all hosts - for (const row of doc.rows) { - diag.hosts.push({ - version: row.value.common.installedVersion, - platform: row.value.common.platform, - type: row.value.native.os.platform, - }); - } } + } - doc = null; - err = null; + doc = null; + err = null; - try { - doc = await objects!.getObjectViewAsync('system', 'adapter', { - startkey: SYSTEM_ADAPTER_PREFIX, - endkey: `${SYSTEM_ADAPTER_PREFIX}\u9999`, - }); - } catch (e) { - err = e; - } + try { + doc = await objects!.getObjectViewAsync('system', 'adapter', { + startkey: SYSTEM_ADAPTER_PREFIX, + endkey: `${SYSTEM_ADAPTER_PREFIX}\u9999`, + }); + } catch (e) { + err = e; + } - const foundVisAdapters = new Set<(typeof VIS_ADAPTERS)[number]>(); + const foundVisAdapters = new Set<(typeof VIS_ADAPTERS)[number]>(); - if (!err && doc?.rows.length) { - // Read installed versions of all adapters - for (const row of doc.rows) { - diag.adapters[row.value.common.name] = { - version: row.value.common.version, - platform: row.value.common.platform, - installedFrom: row.value.common.installedFrom, - }; + if (!err && doc?.rows.length) { + // Read installed versions of all adapters + for (const row of doc.rows) { + diag.adapters[row.value.common.name] = { + version: row.value.common.version, + platform: row.value.common.platform, + installedFrom: row.value.common.installedFrom, + }; - if (VIS_ADAPTERS.includes(row.value.common.name as (typeof VIS_ADAPTERS)[number])) { - foundVisAdapters.add(row.value.common.name as (typeof VIS_ADAPTERS)[number]); - } + if (VIS_ADAPTERS.includes(row.value.common.name as (typeof VIS_ADAPTERS)[number])) { + foundVisAdapters.add(row.value.common.name as (typeof VIS_ADAPTERS)[number]); } } - // read the number of vis data points - for (const visAdapter of foundVisAdapters) { - const { calcProjects } = await import('./lib/vis/states.js'); - - try { - const points = await calcProjects({ objects: objects!, instance: 0, visAdapter }); - let total = null; - const tasks = []; - - if (points?.length) { - for (const point of points) { - if (point.id === `${visAdapter}.0.datapoints.total`) { - total = point.val; - } + } + // read the number of vis data points + for (const visAdapter of foundVisAdapters) { + const { calcProjects } = await import('./lib/vis/states.js'); - tasks.push({ - _id: point.id, - type: 'state', - native: {}, - common: { - name: 'Datapoints count', - role: 'state', - type: 'number', - read: true, - write: false, - }, - state: { - val: point.val, - ack: true, - }, - }); + try { + const points = await calcProjects({ objects: objects!, instance: 0, visAdapter }); + let total = null; + const tasks = []; + + if (points?.length) { + for (const point of points) { + if (point.id === `${visAdapter}.0.datapoints.total`) { + total = point.val; } - } - if (total !== null) { - diag[visAdapter] = total; + tasks.push({ + _id: point.id, + type: 'state', + native: {}, + common: { + name: 'Datapoints count', + role: 'state', + type: 'number', + read: true, + write: false, + }, + state: { + val: point.val, + ack: true, + }, + }); } + } - await extendObjects(tasks); - } catch (e) { - logger.error(`${hostLogPrefix} cannot call visUtils: ${e.message}`); + if (total !== null) { + diag[visAdapter] = total; } - } - return diag; + await extendObjects(tasks); + } catch (e) { + logger.error(`${hostLogPrefix} cannot call visUtils: ${e.message}`); + } } + + return diag; } // check if some IPv4 address found. If not try in 30 seconds one more time (max 10 times) @@ -1926,10 +1921,9 @@ async function getVersionFromHost(hostId: ioBroker.ObjectIDs.Host): Promise void): Promise { processNextScheduledInstance(); return; - } else { - !wakeUp && - logger.warn(`${hostLogPrefix} instance ${instance._id} already running with pid ${proc.process.pid}`); - skipped = true; } + !wakeUp && + logger.warn(`${hostLogPrefix} instance ${instance._id} already running with pid ${proc.process.pid}`); + skipped = true; } else { logger.warn( `${hostLogPrefix} instance ${instance._id} not started, because start has already been initialized less than 2 seconds ago`, @@ -4111,39 +4104,38 @@ async function startInstance(id: ioBroker.ObjectIDs.Instance, wakeUp = false): P } storePids(); return; + } + if (code === EXIT_CODES.ADAPTER_REQUESTED_TERMINATION && proc?.restartExpected) { + logger.info(`${hostLogPrefix} instance ${id} terminated for restart.`); + } else if (code === EXIT_CODES.ADAPTER_REQUESTED_TERMINATION) { + logger.info( + `${hostLogPrefix} instance ${id} terminated by request of the instance itself and will not be restarted, before user restarts it.`, + ); + } else if ( + code === EXIT_CODES.START_IMMEDIATELY_AFTER_STOP && + proc?.config?.common.restartSchedule + ) { + logger.info( + `${hostLogPrefix} instance ${id} scheduled normal terminated and will be restarted on schedule.`, + ); + } else if (code === EXIT_CODES.ADAPTER_REQUESTED_REBUILD && proc) { + logger.info( + `${hostLogPrefix} instance ${id} requested a rebuild of its dependencies and will be restarted after that is done.`, + ); + proc.needsRebuild = true; } else { - if (code === EXIT_CODES.ADAPTER_REQUESTED_TERMINATION && proc?.restartExpected) { - logger.info(`${hostLogPrefix} instance ${id} terminated for restart.`); - } else if (code === EXIT_CODES.ADAPTER_REQUESTED_TERMINATION) { - logger.info( - `${hostLogPrefix} instance ${id} terminated by request of the instance itself and will not be restarted, before user restarts it.`, - ); - } else if ( - code === EXIT_CODES.START_IMMEDIATELY_AFTER_STOP && - proc?.config?.common.restartSchedule + const text = `${hostLogPrefix} instance ${id} terminated with code ${code} (${ + getErrorText(code) || '' + })`; + if ( + !code || + code === EXIT_CODES.ADAPTER_REQUESTED_TERMINATION || + code === EXIT_CODES.NO_ERROR || + code === EXIT_CODES.START_IMMEDIATELY_AFTER_STOP ) { - logger.info( - `${hostLogPrefix} instance ${id} scheduled normal terminated and will be restarted on schedule.`, - ); - } else if (code === EXIT_CODES.ADAPTER_REQUESTED_REBUILD && proc) { - logger.info( - `${hostLogPrefix} instance ${id} requested a rebuild of its dependencies and will be restarted after that is done.`, - ); - proc.needsRebuild = true; + logger.info(text); } else { - const text = `${hostLogPrefix} instance ${id} terminated with code ${code} (${ - getErrorText(code) || '' - })`; - if ( - !code || - code === EXIT_CODES.ADAPTER_REQUESTED_TERMINATION || - code === EXIT_CODES.NO_ERROR || - code === EXIT_CODES.START_IMMEDIATELY_AFTER_STOP - ) { - logger.info(text); - } else { - logger.error(text); - } + logger.error(text); } } } @@ -4898,33 +4890,66 @@ async function stopInstance(id: string, force: boolean): Promise { !isStopping && logger.warn(`${hostLogPrefix} stopInstance ${instance._id} not running`); } return; - } else { - if (force && !proc.startedAsCompactGroup) { - logger.info(`${hostLogPrefix} stopInstance forced ${instance._id} killing pid ${proc.process.pid}`); - proc.stopping = true; - try { - proc.process.kill('SIGKILL'); // call stop directly in adapter.js or call kill of a process - } catch (e) { - logger.error(`${hostLogPrefix} Cannot stop ${id}: ${JSON.stringify(e)}`); + } + if (force && !proc.startedAsCompactGroup) { + logger.info(`${hostLogPrefix} stopInstance forced ${instance._id} killing pid ${proc.process.pid}`); + proc.stopping = true; + try { + proc.process.kill('SIGKILL'); // call stop directly in adapter.js or call kill of a process + } catch (e) { + logger.error(`${hostLogPrefix} Cannot stop ${id}: ${JSON.stringify(e)}`); + } + delete proc.process; + } else if ( + (instance.common.messagebox && instance.common.supportStopInstance) || + instance.common.supportedMessages?.stopInstance + ) { + // Send to adapter signal "stopInstance" because on some systems SIGTERM does not work + sendTo(instance._id, 'stopInstance', null, result => { + const stopTimeout = stopTimeouts[id]; + if (stopTimeout?.timeout) { + clearTimeout(stopTimeout.timeout); + stopTimeout.timeout = null; } - delete proc.process; - } else if ( - (instance.common.messagebox && instance.common.supportStopInstance) || - instance.common.supportedMessages?.stopInstance - ) { - // Send to adapter signal "stopInstance" because on some systems SIGTERM does not work - sendTo(instance._id, 'stopInstance', null, result => { + logger.info( + `${hostLogPrefix} stopInstance self ${instance._id} killing pid ${ + proc.process ? proc.process.pid : 'undefined' + }${result ? `: ${result}` : ''}`, + ); + if (proc.process && !proc.startedAsCompactGroup) { + proc.stopping = true; + try { + proc.process.kill('SIGKILL'); // call stop directly in adapter.js or call kill of a process + } catch (e) { + logger.error(`${hostLogPrefix} Cannot stop ${id}: ${JSON.stringify(e)}`); + } + delete proc.process; + } + + if (typeof stopTimeout?.callback === 'function') { + stopTimeout.callback(); + stopTimeout.callback = null; + } + }); + + const supportStopInstanceVal: boolean | number | undefined = + instance.common.supportStopInstance || instance.common.supportedMessages?.stopInstance; + + const timeoutDuration = supportStopInstanceVal === true ? 1_000 : supportStopInstanceVal || 1_000; + return new Promise(resolve => { + // If no response from adapter, kill it in 1 second + stopTimeout.callback = resolve; + stopTimeout.timeout = setTimeout(() => { const stopTimeout = stopTimeouts[id]; - if (stopTimeout?.timeout) { - clearTimeout(stopTimeout.timeout); + const proc = procs[id]; + + if (stopTimeout) { stopTimeout.timeout = null; } - logger.info( - `${hostLogPrefix} stopInstance self ${instance._id} killing pid ${ - proc.process ? proc.process.pid : 'undefined' - }${result ? `: ${result}` : ''}`, - ); - if (proc.process && !proc.startedAsCompactGroup) { + if (proc?.process && !proc.startedAsCompactGroup) { + logger.info( + `${hostLogPrefix} stopInstance timeout ${timeoutDuration} ${instance._id} killing pid ${proc.process.pid}`, + ); proc.stopping = true; try { proc.process.kill('SIGKILL'); // call stop directly in adapter.js or call kill of a process @@ -4932,104 +4957,71 @@ async function stopInstance(id: string, force: boolean): Promise { logger.error(`${hostLogPrefix} Cannot stop ${id}: ${JSON.stringify(e)}`); } delete proc.process; + } else if (!compactGroupController && proc?.process) { + // was compact mode in another group + delete proc.process; // we consider that the other group controller managed to stop it } - - if (typeof stopTimeout?.callback === 'function') { + if (stopTimeout && typeof stopTimeout.callback === 'function') { stopTimeout.callback(); stopTimeout.callback = null; } - }); - - const supportStopInstanceVal: boolean | number | undefined = - instance.common.supportStopInstance || instance.common.supportedMessages?.stopInstance; - - const timeoutDuration = supportStopInstanceVal === true ? 1_000 : supportStopInstanceVal || 1_000; - return new Promise(resolve => { - // If no response from adapter, kill it in 1 second - stopTimeout.callback = resolve; - stopTimeout.timeout = setTimeout(() => { - const stopTimeout = stopTimeouts[id]; - const proc = procs[id]; - - if (stopTimeout) { - stopTimeout.timeout = null; - } - if (proc?.process && !proc.startedAsCompactGroup) { - logger.info( - `${hostLogPrefix} stopInstance timeout ${timeoutDuration} ${instance._id} killing pid ${proc.process.pid}`, - ); - proc.stopping = true; - try { - proc.process.kill('SIGKILL'); // call stop directly in adapter.js or call kill of a process - } catch (e) { - logger.error(`${hostLogPrefix} Cannot stop ${id}: ${JSON.stringify(e)}`); - } - delete proc.process; - } else if (!compactGroupController && proc?.process) { - // was compact mode in another group - delete proc.process; // we consider that the other group controller managed to stop it - } - if (stopTimeout && typeof stopTimeout.callback === 'function') { - stopTimeout.callback(); - stopTimeout.callback = null; - } - }, timeoutDuration); - }); - } else if (!proc.startedAsCompactGroup) { - let err; - try { - // if started, let it end itself as first try - await states!.setState(`${id}.sigKill`, { val: -1, ack: false, from: hostObjectPrefix }); - } catch (e) { - err = e; - } - // send kill signal - logger.info(`${hostLogPrefix} stopInstance ${instance._id} send kill signal`); - const proc = procs[id]; - const stopTimeout = stopTimeouts[id]; + }, timeoutDuration); + }); + } else if (!proc.startedAsCompactGroup) { + let err; + try { + // if started, let it end itself as first try + await states!.setState(`${id}.sigKill`, { val: -1, ack: false, from: hostObjectPrefix }); + } catch (e) { + err = e; + } + // send kill signal + logger.info(`${hostLogPrefix} stopInstance ${instance._id} send kill signal`); + const proc = procs[id]; + const stopTimeout = stopTimeouts[id]; - if (!err) { - if (proc) { - proc.stopping = true; - } + if (!err) { + if (proc) { + proc.stopping = true; } - const timeoutDuration = instance.common.stopTimeout || 1_000; + } + const timeoutDuration = instance.common.stopTimeout || 1_000; - return new Promise(resolve => { - // If no response from adapter, kill it in 1 second - stopTimeout.callback = resolve; - stopTimeout.timeout = setTimeout(() => { - const proc = procs[id]; - const stopTimeout = stopTimeouts[id]; + return new Promise(resolve => { + // If no response from adapter, kill it in 1 second + stopTimeout.callback = resolve; + stopTimeout.timeout = setTimeout(() => { + const proc = procs[id]; + const stopTimeout = stopTimeouts[id]; - if (stopTimeout) { - stopTimeout.timeout = null; - } + if (stopTimeout) { + stopTimeout.timeout = null; + } - if (proc?.process && !proc.startedAsCompactGroup) { - logger.info( - `${hostLogPrefix} stopInstance timeout ${instance._id} killing pid ${proc.process.pid}`, - ); - proc.stopping = true; - try { - proc.process.kill('SIGKILL'); - } catch (e) { - logger.error(`${hostLogPrefix} Cannot stop ${id}: ${JSON.stringify(e)}`); - } - delete proc.process; - } - if (stopTimeout && typeof stopTimeout.callback === 'function') { - stopTimeout.callback(); - stopTimeout.callback = null; + if (proc?.process && !proc.startedAsCompactGroup) { + logger.info( + `${hostLogPrefix} stopInstance timeout ${instance._id} killing pid ${proc.process.pid}`, + ); + proc.stopping = true; + try { + proc.process.kill('SIGKILL'); + } catch (e) { + logger.error(`${hostLogPrefix} Cannot stop ${id}: ${JSON.stringify(e)}`); } - }, timeoutDuration); - }); - } else { - if (proc) { - delete proc.process; - } + delete proc.process; + } + if (stopTimeout && typeof stopTimeout.callback === 'function') { + stopTimeout.callback(); + stopTimeout.callback = null; + } + }, timeoutDuration); + }); + } else { + if (proc) { + delete proc.process; } } + break; case 'schedule': @@ -5187,9 +5179,9 @@ function stop(force?: boolean, callback?: () => void): void { ); if (typeof callback === 'function') { return void callback(); - } else { - setTimeout(() => process.exit(EXIT_CODES.JS_CONTROLLER_STOPPED), 1_000); } + setTimeout(() => process.exit(EXIT_CODES.JS_CONTROLLER_STOPPED), 1_000); + return; } outputCount++; @@ -5221,23 +5213,22 @@ function stop(force?: boolean, callback?: () => void): void { if (typeof callback === 'function') { return void callback(); - } else { - setTimeout(() => { - try { - // avoid pids been written after deletion - if (storeTimer) { - clearTimeout(storeTimer); - } - // delete pids.txt - fs.unlinkSync(tools.getPidsFileName()); - } catch (e) { - if (e.code !== 'ENOENT') { - logger.error(`${hostLogPrefix} Could not delete ${tools.getPidsFileName()}: ${e}`); - } - } - process.exit(EXIT_CODES.JS_CONTROLLER_STOPPED); - }, 1_000); } + setTimeout(() => { + try { + // avoid pids been written after deletion + if (storeTimer) { + clearTimeout(storeTimer); + } + // delete pids.txt + fs.unlinkSync(tools.getPidsFileName()); + } catch (e) { + if (e.code !== 'ENOENT') { + logger.error(`${hostLogPrefix} Could not delete ${tools.getPidsFileName()}: ${e}`); + } + } + process.exit(EXIT_CODES.JS_CONTROLLER_STOPPED); + }, 1_000); }); } @@ -5992,7 +5983,7 @@ async function disableBlocklistedInstances(): Promise { } // eslint-disable-next-line unicorn/prefer-module -const modulePath = url.fileURLToPath(import.meta.url || 'file://' + __filename); +const modulePath = url.fileURLToPath(import.meta.url || `file://${__filename}`); if (process.argv[1] === modulePath) { init(); } diff --git a/packages/controller/test/jsonl/testAdapterObjectsInFileJsonl.ts b/packages/controller/test/jsonl/testAdapterObjectsInFileJsonl.ts index 2cf98b95e..e25c746ee 100644 --- a/packages/controller/test/jsonl/testAdapterObjectsInFileJsonl.ts +++ b/packages/controller/test/jsonl/testAdapterObjectsInFileJsonl.ts @@ -5,7 +5,7 @@ import { register } from './../lib/testObjects.js'; import type { TestContext } from '../_Types.js'; import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); let objects = null; let states = null; @@ -23,7 +23,7 @@ const objectsConfig = { retry_max_delay: 100, retry_max_count: 2, }, - dataDir: thisDir + '/../tmp/data', + dataDir: `${thisDir}/../tmp/data`, type: 'jsonl', host: '127.0.0.1', port: 19001, @@ -32,12 +32,12 @@ const objectsConfig = { noFileCache: true, connectTimeout: 2000, onChange: (id: string, _obj: ioBroker.AnyObject) => { - console.log('object changed. ' + id); + console.log(`object changed. ${id}`); }, }; -describe(textName + ' Test Objects File-Redis', function () { - before(textName + ' Start js-controller', async function () { +describe(`${textName} Test Objects File-Redis`, function () { + before(`${textName} Start js-controller`, async function () { this.timeout(23_000); const { objects: _objects, states: _states } = await startController({ @@ -45,7 +45,7 @@ describe(textName + ' Test Objects File-Redis', function () { states: { dataDir: `${thisDir}/../tmp/data`, onChange: function (id: string, _state: ioBroker.State) { - console.log('state changed. ' + id); + console.log(`state changed. ${id}`); }, }, }); @@ -60,7 +60,7 @@ describe(textName + ' Test Objects File-Redis', function () { register(it, expect, context); - after(textName + ' Stop js-controller', async function () { + after(`${textName} Stop js-controller`, async function () { this.timeout(5_000); await stopController(); await new Promise(resolve => { diff --git a/packages/controller/test/jsonl/testAdapterStatesInFilesJsonl.ts b/packages/controller/test/jsonl/testAdapterStatesInFilesJsonl.ts index 44195b3ca..30f007893 100644 --- a/packages/controller/test/jsonl/testAdapterStatesInFilesJsonl.ts +++ b/packages/controller/test/jsonl/testAdapterStatesInFilesJsonl.ts @@ -2,7 +2,7 @@ import path from 'node:path'; import testAdapter from './../lib/testAdapter.js'; import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); const dataDir = path.join(thisDir, '..', 'tmp', 'data'); diff --git a/packages/controller/test/lib/setup4controller.ts b/packages/controller/test/lib/setup4controller.ts index 6f597b28e..6f957e9a4 100644 --- a/packages/controller/test/lib/setup4controller.ts +++ b/packages/controller/test/lib/setup4controller.ts @@ -5,7 +5,7 @@ import type { Client as StateRedisClient } from '@iobroker/db-states-redis'; import * as url from 'node:url'; import { appNameLowerCase } from '@iobroker/js-controller-common-db/tools'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); export const rootDir = path.normalize(`${thisDir}/../../`); @@ -33,7 +33,7 @@ export async function startController(options: Record): Promise): Promise): void { objects: objectsConfig, consoleOutput: true, }, - dirname: thisDir + '/', + dirname: `${thisDir}/`, name: context.adapterShortName, objectChange: (id, obj) => { context.onAdapterObjectChanged && context.onAdapterObjectChanged(id, obj); @@ -124,7 +124,7 @@ export default function testAdapter(options: Record): void { function checkConnectionOfAdapter(isConnected: boolean, cb: (err?: string) => void, counter?: number): void { counter = counter || 0; - console.log('Try check #' + counter); + console.log(`Try check #${counter}`); if (counter > 30) { if (cb) { cb('Cannot check connection'); @@ -165,8 +165,8 @@ export default function testAdapter(options: Record): void { } function addInstance(): void { - if (!fs.existsSync(rootDir + 'tmp/')) { - fs.mkdirSync(rootDir + 'tmp/'); + if (!fs.existsSync(`${rootDir}tmp/`)) { + fs.mkdirSync(`${rootDir}tmp/`); } if (statesConfig.dataDir && !fs.existsSync(statesConfig.dataDir)) { fs.mkdirSync(statesConfig.dataDir); @@ -175,15 +175,15 @@ export default function testAdapter(options: Record): void { fs.mkdirSync(objectsConfig.dataDir); } if (objectsConfig.dataDir) { - fs.writeFileSync(objectsConfig.dataDir + '/objects.json', fs.readFileSync(thisDir + '/objects.json')); + fs.writeFileSync(`${objectsConfig.dataDir}/objects.json`, fs.readFileSync(`${thisDir}/objects.json`)); } if (statesConfig.dataDir) { - fs.writeFileSync(statesConfig.dataDir + '/states.json', fs.readFileSync(thisDir + '/states.json')); + fs.writeFileSync(`${statesConfig.dataDir}/states.json`, fs.readFileSync(`${thisDir}/states.json`)); } } describe(`${options.name} ${context.adapterShortName} adapter`, function () { - before('Test ' + context.adapterShortName + ' adapter: Start js-controller and adapter', async function () { + before(`Test ${context.adapterShortName} adapter: Start js-controller and adapter`, async function () { this.timeout(10_000); // no installation addInstance(); @@ -191,13 +191,13 @@ export default function testAdapter(options: Record): void { const _objectsConfig = deepClone(objectsConfig); _statesConfig.onChange = (id: string, state: ioBroker.State) => { - console.log('state changed. ' + id); + console.log(`state changed. ${id}`); if (context.onControllerStateChanged) { context.onControllerStateChanged(id, state); } }; _objectsConfig.onChange = (id: string, obj: ioBroker.AnyObject) => { - console.log('object changed. ' + id); + console.log(`object changed. ${id}`); if (context.onControllerObjectChanged) { context.onControllerObjectChanged(id, obj); } @@ -233,81 +233,66 @@ export default function testAdapter(options: Record): void { }); }); - it( - options.name + ' ' + context.adapterShortName + ' adapter: check all important adapter attributes', - function (done) { - this.timeout(2000); - expect(context.adapter.namespace).to.be.equal(context.adapterShortName + '.0'); - expect(context.adapter.name).to.be.equal(context.adapterShortName); - expect(context.adapter.instance).to.be.equal(0); - // @ts-expect-error should not exist - expect(context.adapter.states).to.be.undefined; - // @ts-expect-error should not exist - expect(context.adapter.objects).to.be.undefined; - expect(context.adapter.log).to.be.ok; - expect(context.adapter.log.info).to.be.a('function'); - expect(context.adapter.log.debug).to.be.a('function'); - expect(context.adapter.log.warn).to.be.a('function'); - expect(context.adapter.log.error).to.be.a('function'); - expect(context.adapter.config.paramString).to.be.equal('value1'); - expect(context.adapter.config.paramNumber).to.be.equal(42); - expect(context.adapter.config.paramBoolean).to.be.equal(false); - expect(context.adapter.config.username).to.be.equal('tesla'); - // password has to be winning (decrypted via legacy - backward compatibility) - expect(context.adapter.config.password).to.be.equal('winning'); - // secondPassword should be decrypted with AES-256 correctly - expect(context.adapter.config.secondPassword).to.be.equal('ii-€+winning*-³§"'); - - let count = 0; - - context.states.getState( - `system.adapter.${context.adapterShortName}.0.compactMode`, - function (err, state) { - expect(state!.val).to.be.equal(true); - setTimeout(() => !--count && done(), 0); - }, - ); - - count++; - context.states.getState( - `system.adapter.${context.adapterShortName}.0.connected`, - function (err, state) { - expect(state!.val).to.be.equal(true); - setTimeout(() => !--count && done(), 0); - }, - ); - - count++; - context.states.getState(`system.adapter.${context.adapterShortName}.0.memRss`, function (err, state) { - expect(state!.val).to.be.equal(0); - setTimeout(() => !--count && done(), 0); - }); + it(`${options.name} ${context.adapterShortName} adapter: check all important adapter attributes`, function (done) { + this.timeout(2000); + expect(context.adapter.namespace).to.be.equal(`${context.adapterShortName}.0`); + expect(context.adapter.name).to.be.equal(context.adapterShortName); + expect(context.adapter.instance).to.be.equal(0); + // @ts-expect-error should not exist + expect(context.adapter.states).to.be.undefined; + // @ts-expect-error should not exist + expect(context.adapter.objects).to.be.undefined; + expect(context.adapter.log).to.be.ok; + expect(context.adapter.log.info).to.be.a('function'); + expect(context.adapter.log.debug).to.be.a('function'); + expect(context.adapter.log.warn).to.be.a('function'); + expect(context.adapter.log.error).to.be.a('function'); + expect(context.adapter.config.paramString).to.be.equal('value1'); + expect(context.adapter.config.paramNumber).to.be.equal(42); + expect(context.adapter.config.paramBoolean).to.be.equal(false); + expect(context.adapter.config.username).to.be.equal('tesla'); + // password has to be winning (decrypted via legacy - backward compatibility) + expect(context.adapter.config.password).to.be.equal('winning'); + // secondPassword should be decrypted with AES-256 correctly + expect(context.adapter.config.secondPassword).to.be.equal('ii-€+winning*-³§"'); + + let count = 0; + + context.states.getState(`system.adapter.${context.adapterShortName}.0.compactMode`, function (err, state) { + expect(state!.val).to.be.equal(true); + setTimeout(() => !--count && done(), 0); + }); - count++; - context.states.getState( - `system.adapter.${context.adapterShortName}.0.memHeapTotal`, - function (err, state) { - expect(state!.val).to.be.equal(0); - setTimeout(() => !--count && done(), 0); - }, - ); - - count++; - context.states.getState( - `system.adapter.${context.adapterShortName}.0.memHeapUsed`, - function (err, state) { - expect(state!.val).to.be.equal(0); - setTimeout(() => !--count && done(), 0); - }, - ); - - count++; - context.states.getState(`system.adapter.${context.adapterShortName}.0.uptime`, function (err, state) { - expect(state!.val).to.be.at.least(0); - setTimeout(() => !--count && done(), 0); - }); - }, - ); + count++; + context.states.getState(`system.adapter.${context.adapterShortName}.0.connected`, function (err, state) { + expect(state!.val).to.be.equal(true); + setTimeout(() => !--count && done(), 0); + }); + + count++; + context.states.getState(`system.adapter.${context.adapterShortName}.0.memRss`, function (err, state) { + expect(state!.val).to.be.equal(0); + setTimeout(() => !--count && done(), 0); + }); + + count++; + context.states.getState(`system.adapter.${context.adapterShortName}.0.memHeapTotal`, function (err, state) { + expect(state!.val).to.be.equal(0); + setTimeout(() => !--count && done(), 0); + }); + + count++; + context.states.getState(`system.adapter.${context.adapterShortName}.0.memHeapUsed`, function (err, state) { + expect(state!.val).to.be.equal(0); + setTimeout(() => !--count && done(), 0); + }); + + count++; + context.states.getState(`system.adapter.${context.adapterShortName}.0.uptime`, function (err, state) { + expect(state!.val).to.be.at.least(0); + setTimeout(() => !--count && done(), 0); + }); + }); for (const test of tests) { test(it, expect, context); diff --git a/packages/controller/test/lib/testAdapterHelpers.ts b/packages/controller/test/lib/testAdapterHelpers.ts index 9888f911c..9a1ef4583 100644 --- a/packages/controller/test/lib/testAdapterHelpers.ts +++ b/packages/controller/test/lib/testAdapterHelpers.ts @@ -11,7 +11,7 @@ chai.use(chaiAsPromised); export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, context: TestContext): void { //adapterGetPort - it(context.name + ' ' + context.adapterShortName + ' adapter: find next free port', function (done) { + it(`${context.name} ${context.adapterShortName} adapter: find next free port`, function (done) { this.timeout(3_000); // @ts-expect-error expects more args @@ -33,7 +33,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); //checkPassword - it(context.name + ' ' + context.adapterShortName + ' adapter: validates user and password', function (done) { + it(`${context.name} ${context.adapterShortName} adapter: validates user and password`, function (done) { this.timeout(3_000); //@ts-expect-error Expecting a callback @@ -53,7 +53,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); //checkPassword (async) - it(context.name + ' ' + context.adapterShortName + ' adapter: validates user and password (ASYNC)', () => { + it(`${context.name} ${context.adapterShortName} adapter: validates user and password (ASYNC)`, () => { const promises = [ // promisify always provides a callback, so that doesn't need to be tested // User doesn't exist @@ -70,7 +70,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(3_000); //setPassword - it(context.name + ' ' + context.adapterShortName + ' adapter: sets the users password', function (done) { + it(`${context.name} ${context.adapterShortName} adapter: sets the users password`, function (done) { this.timeout(3_000); // TODO: sync // TODO: async @@ -78,7 +78,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); //checkGroup - it(context.name + ' ' + context.adapterShortName + ' adapter: user exists and is in the group', function (done) { + it(`${context.name} ${context.adapterShortName} adapter: user exists and is in the group`, function (done) { this.timeout(3_000); // TODO: sync // TODO: async @@ -86,7 +86,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); //calculatePermissions - it(context.name + ' ' + context.adapterShortName + ' adapter: get the user permissions', function (done) { + it(`${context.name} ${context.adapterShortName} adapter: get the user permissions`, function (done) { this.timeout(3_000); // TODO: sync // TODO: async @@ -94,13 +94,13 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getCertificates - it(context.name + ' ' + context.adapterShortName + ' adapter: returns SSL certificates by name', async () => { + it(`${context.name} ${context.adapterShortName} adapter: returns SSL certificates by name`, async () => { // has to work without chained certificate const certs = await context.adapter.getCertificatesAsync('defaultPublic', 'defaultPrivate'); expect(certs).to.be.ok; }); - it(context.name + ' ' + context.adapterShortName + ' adapter: get the user id', async () => { + it(`${context.name} ${context.adapterShortName} adapter: get the user id`, async () => { let id = await context.adapter.getUserID('admin'); expect(id).to.be.equal('system.user.admin'); id = await context.adapter.getUserID('test'); @@ -112,7 +112,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // formatValue - it(context.name + ' ' + context.adapterShortName + ' adapter: Check formatValue', function (done) { + it(`${context.name} ${context.adapterShortName} adapter: Check formatValue`, function (done) { this.timeout(3_000); let testValue; @@ -160,7 +160,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // formatDate - it(context.name + ' ' + context.adapterShortName + ' adapter: Check formatDate', function (done) { + it(`${context.name} ${context.adapterShortName} adapter: Check formatDate`, function (done) { this.timeout(3_000); const testDate = new Date(0); let testStringDate; @@ -213,7 +213,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // Validator.fixId - it(context.name + ' ' + context.adapterShortName + ' adapter utils: check fixId', () => { + it(`${context.name} ${context.adapterShortName} adapter utils: check fixId`, () => { const utils = new Validator( context.objects, context.states, @@ -230,20 +230,20 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont const adapterInstance = context.adapter.instance; expect(adapterInstance).to.equal(0); const adapterNamespace = context.adapter.namespace; - expect(adapterNamespace).to.equal(adapterName + '.' + adapterInstance); + expect(adapterNamespace).to.equal(`${adapterName}.${adapterInstance}`); let testString; //test with Object empty testString = utils.fixId({}); expect(testString).to.be.a('string'); - expect(testString).to.equal(adapterNamespace + '.'); + expect(testString).to.equal(`${adapterNamespace}.`); //test with Object state testString = utils.fixId({ state: 'baz', }); expect(testString).to.be.a('string'); - expect(testString).to.equal(adapterNamespace + '.baz'); + expect(testString).to.equal(`${adapterNamespace}.baz`); //test with Object state + channel testString = utils.fixId({ @@ -251,7 +251,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont channel: 'bar', }); expect(testString).to.be.a('string'); - expect(testString).to.equal(adapterNamespace + '.bar.baz'); + expect(testString).to.equal(`${adapterNamespace}.bar.baz`); //test with Object state + channel + device testString = utils.fixId({ @@ -260,7 +260,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont device: 'foo', }); expect(testString).to.be.a('string'); - expect(testString).to.equal(adapterNamespace + '.foo.bar.baz'); + expect(testString).to.equal(`${adapterNamespace}.foo.bar.baz`); //test with string empty as state testString = utils.fixId(''); @@ -270,36 +270,36 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont //test with string empty as subscribe testString = utils.fixId('', true); expect(testString).to.be.a('string'); - expect(testString).to.equal(adapterNamespace + '.'); + expect(testString).to.equal(`${adapterNamespace}.`); //test with string state testString = utils.fixId('baz'); expect(testString).to.be.a('string'); - expect(testString).to.equal(adapterNamespace + '.baz'); + expect(testString).to.equal(`${adapterNamespace}.baz`); //test with string state + channel testString = utils.fixId('bar.baz'); expect(testString).to.be.a('string'); - expect(testString).to.equal(adapterNamespace + '.bar.baz'); + expect(testString).to.equal(`${adapterNamespace}.bar.baz`); //test with string state + channel + device testString = utils.fixId('foo.bar.baz'); expect(testString).to.be.a('string'); - expect(testString).to.equal(adapterNamespace + '.foo.bar.baz'); + expect(testString).to.equal(`${adapterNamespace}.foo.bar.baz`); //test with already fixed ID - testString = utils.fixId(adapterNamespace + '.foo.bar.baz'); + testString = utils.fixId(`${adapterNamespace}.foo.bar.baz`); expect(testString).to.be.a('string'); - expect(testString).to.equal(adapterNamespace + '.foo.bar.baz'); + expect(testString).to.equal(`${adapterNamespace}.foo.bar.baz`); //test composition testString = utils.fixId(utils.fixId('foo.bar.baz')); expect(testString).to.be.a('string'); - expect(testString).to.equal(adapterNamespace + '.foo.bar.baz'); + expect(testString).to.equal(`${adapterNamespace}.foo.bar.baz`); }).timeout(2_000); // Check setTimeout throw - it(context.name + ' ' + context.adapterShortName + ' adapter: check setTimeout', done => { + it(`${context.name} ${context.adapterShortName} adapter: check setTimeout`, done => { // is valid const timeout = context.adapter.setTimeout( () => { @@ -333,7 +333,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // Check setInterval throw - it(context.name + ' ' + context.adapterShortName + ' adapter: check setInterval', done => { + it(`${context.name} ${context.adapterShortName} adapter: check setInterval`, done => { // is valid let interval = context.adapter.setInterval( () => { @@ -369,7 +369,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // idToDCS - it(context.name + ' ' + context.adapterShortName + ' adapter: Check idToDCS', function (done) { + it(`${context.name} ${context.adapterShortName} adapter: Check idToDCS`, function (done) { this.timeout(3000); let testString; @@ -389,7 +389,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // _DCS2ID - it(context.name + ' ' + context.adapterShortName + ' adapter: Check _DCS2ID', function (done) { + it(`${context.name} ${context.adapterShortName} adapter: Check _DCS2ID`, function (done) { this.timeout(3_000); let testString; @@ -440,7 +440,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont done(); }); - it(context.name + ' ' + context.adapterShortName + ' adapter: encrypt decrypt functions', () => { + it(`${context.name} ${context.adapterShortName} adapter: encrypt decrypt functions`, () => { const encrypted = context.adapter.encrypt('topSecret'); // we only check not equal, because encryption can change and is not always deterministic expect(encrypted.length).to.equal(79); @@ -450,35 +450,28 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(decrypted).to.equal('topSecret'); }); - it( - context.name + ' ' + context.adapterShortName + ' adapter: updateConfig needs to respect encryptedNative', - async () => { - const oldConfig = await context.adapter.getForeignObjectAsync( - `system.adapter.${context.adapter.namespace}`, - ); + it(`${context.name} ${context.adapterShortName} adapter: updateConfig needs to respect encryptedNative`, async () => { + const oldConfig = await context.adapter.getForeignObjectAsync(`system.adapter.${context.adapter.namespace}`); - const passphrase = 'SavePassword123'; + const passphrase = 'SavePassword123'; - await context.adapter.updateConfig({ secondPassword: passphrase }); - const newConfig = await context.adapter.getForeignObjectAsync( - `system.adapter.${context.adapter.namespace}`, - ); + await context.adapter.updateConfig({ secondPassword: passphrase }); + const newConfig = await context.adapter.getForeignObjectAsync(`system.adapter.${context.adapter.namespace}`); - // non encrypted and non updated params stay the same - expect(newConfig?.native.paramString).to.exist; - expect(newConfig?.native.paramString).to.be.equal(oldConfig?.native.paramString); + // non encrypted and non updated params stay the same + expect(newConfig?.native.paramString).to.exist; + expect(newConfig?.native.paramString).to.be.equal(oldConfig?.native.paramString); - // encrypted non updated passwords, decrypt to the same value - expect(newConfig?.native.password).to.exist; - expect(context.adapter.decrypt(newConfig?.native.password)).to.be.equal( - context.adapter.decrypt(oldConfig?.native.password), - ); + // encrypted non updated passwords, decrypt to the same value + expect(newConfig?.native.password).to.exist; + expect(context.adapter.decrypt(newConfig?.native.password)).to.be.equal( + context.adapter.decrypt(oldConfig?.native.password), + ); - // updated encrypted value is correctly decrypted - expect(newConfig?.native.secondPassword).to.exist; - expect(context.adapter.decrypt(newConfig?.native.secondPassword)).to.be.equal(passphrase); - }, - ); + // updated encrypted value is correctly decrypted + expect(newConfig?.native.secondPassword).to.exist; + expect(context.adapter.decrypt(newConfig?.native.secondPassword)).to.be.equal(passphrase); + }); // setState object validation for (const method of ['setState', 'setStateChanged', 'setForeignState', 'setForeignStateChanged']) { @@ -599,7 +592,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); } - it(context.name + ' ' + context.adapterShortName + ' getAdapterScopedPackageIdentifier', () => { + it(`${context.name} ${context.adapterShortName} getAdapterScopedPackageIdentifier`, () => { const nonOrgaPacket = context.adapter.getAdapterScopedPackageIdentifier('axios'); const orgaPacket = context.adapter.getAdapterScopedPackageIdentifier('@iobroker/adapter-react-v5'); diff --git a/packages/controller/test/lib/testAliases.ts b/packages/controller/test/lib/testAliases.ts index a1f7f81d9..350ce5919 100644 --- a/packages/controller/test/lib/testAliases.ts +++ b/packages/controller/test/lib/testAliases.ts @@ -142,12 +142,12 @@ async function prepareGroupsAndUsers(objects: ObjectsInRedisClient): Promise { + it(`${testName}Read alias state`, done => { context.adapter.setForeignObject( gid, { @@ -215,7 +215,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont ); }).timeout(3_000); - it(testName + 'Read alias states', async () => { + it(`${testName}Read alias states`, async () => { const nonAliasId1 = `${gid}nonAlias1`; const nonAliasId2 = `${gid}nonAlias2`; // create some non-alias data to check that it works with mixed ids @@ -244,7 +244,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont native: {}, }); - await context.adapter.setForeignObjectAsync(gid + '1', { + await context.adapter.setForeignObjectAsync(`${gid}1`, { common: { name: 'forAlias1', type: 'number', @@ -262,12 +262,12 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }, }); - await context.adapter.setForeignStateAsync(gid + '1', 5, true); + await context.adapter.setForeignStateAsync(`${gid}1`, 5, true); await context.adapter.setForeignStateAsync(nonAliasId1, 3, true); await context.adapter.setForeignStateAsync(nonAliasId2, 2, true); // create alias - await context.adapter.setForeignObjectAsync(gAliasID + '1', { + await context.adapter.setForeignObjectAsync(`${gAliasID}1`, { common: { name: 'Test Alias1', type: 'number', @@ -275,7 +275,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont min: -10, max: 10, alias: { - id: gid + '1', + id: `${gid}1`, }, read: true, write: true, @@ -290,13 +290,13 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }, }); - let states = await context.adapter.getForeignStatesAsync(gAliasID + '1'); + let states = await context.adapter.getForeignStatesAsync(`${gAliasID}1`); // No scaling because no % and no min, max in source object - expect(states[gAliasID + '1'].val).to.be.equal(5); - expect(states[gAliasID + '1'].ack).to.be.true; + expect(states[`${gAliasID}1`].val).to.be.equal(5); + expect(states[`${gAliasID}1`].ack).to.be.true; // original array should not be changed - const ids = [nonAliasId1, gAliasID + '1', nonAliasId2]; + const ids = [nonAliasId1, `${gAliasID}1`, nonAliasId2]; states = await context.adapter.getForeignStatesAsync(ids); expect(ids[0]).to.be.equal(nonAliasId1); @@ -305,16 +305,16 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // It must be scaled from -100, 2, 100 // to -10, 0.2, 10 - expect(ids[1]).to.be.equal(gAliasID + '1'); - expect(states[gAliasID + '1'].val).to.be.equal(5); - expect(states[gAliasID + '1'].ack).to.be.true; + expect(ids[1]).to.be.equal(`${gAliasID}1`); + expect(states[`${gAliasID}1`].val).to.be.equal(5); + expect(states[`${gAliasID}1`].ack).to.be.true; expect(ids[2]).to.be.equal(nonAliasId2); expect(states[nonAliasId2].val).to.be.equal(2); expect(states[nonAliasId2].ack).to.be.true; }).timeout(3_000); - it(testName + 'Write alias state', done => { + it(`${testName}Write alias state`, done => { context.adapter.setForeignState(gAliasID, 10, false, () => { context.adapter.getForeignState(gid, (err, state) => { // It must be scaled from 0, 10, 100 @@ -327,9 +327,9 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(3_000); // custom read/write functions - it(testName + 'Use convert state', done => { + it(`${testName}Use convert state`, done => { context.adapter.setForeignObject( - gid + 'C', + `${gid}C`, { common: { name: 'forAliasC', @@ -344,12 +344,12 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont type: 'state', }, () => { - context.adapter.setForeignState(gid + 'C', 2, true, err => { + context.adapter.setForeignState(`${gid}C`, 2, true, err => { expect(err).to.be.not.ok; // create alias context.adapter.setForeignObject( - gAliasID + 'C', + `${gAliasID}C`, { common: { name: 'Test AliasC', @@ -360,7 +360,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont read: true, write: true, alias: { - id: gid + 'C', + id: `${gid}C`, read: 'val * 10 + 1', write: '(val - 1) / 10', }, @@ -369,15 +369,15 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont type: 'state', }, () => { - context.adapter.getForeignState(gAliasID + 'C', (err, state) => { + context.adapter.getForeignState(`${gAliasID}C`, (err, state) => { // It must be converted 2 * 10 + 1 expect((state!.val as number).toFixed(3)).to.be.equal('21.000'); expect(state!.ack).to.be.true; - context.adapter.setForeignState(gAliasID + 'C', 41, true, err => { + context.adapter.setForeignState(`${gAliasID}C`, 41, true, err => { expect(err).to.be.not.ok; - context.adapter.getForeignState(gid + 'C', (err, state) => { + context.adapter.getForeignState(`${gid}C`, (err, state) => { expect((state!.val as number).toFixed(3)).to.be.equal('4.000'); expect(state!.ack).to.be.true; @@ -392,7 +392,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont ); }).timeout(3_000); - it(testName + 'Read alias state by not admin', async () => { + it(`${testName}Read alias state by not admin`, async () => { await prepareGroupsAndUsers(context.objects); await context.adapter.setForeignStateAsync(gAliasID, 10, false, { user: 'system.user.userC' }); let state = await context.adapter.getForeignStateAsync(gid, { user: 'system.user.userC' }); @@ -409,7 +409,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(state!.ack).to.be.false; }).timeout(3_000); - it(testName + 'Read alias state by not admin without rights', async () => { + it(`${testName}Read alias state by not admin without rights`, async () => { await prepareGroupsAndUsers(context.objects); try { @@ -429,7 +429,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // test subscriptions // subscribeForeignStates - it(testName + 'Test subscribe aliases', done => { + it(`${testName}Test subscribe aliases`, done => { context.onAdapterStateChanged = (id, state) => { if (id === gAliasID) { expect(state).to.be.ok; @@ -445,7 +445,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont ); }).timeout(3_000); - it(testName + 'Test unsubscribe aliases', done => { + it(`${testName}Test unsubscribe aliases`, done => { context.onAdapterStateChanged = () => { expect(true).to.be.false; }; @@ -458,7 +458,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }).timeout(3_000); - it(testName + 'Test subscribe aliases pattern', done => { + it(`${testName}Test subscribe aliases pattern`, done => { context.onAdapterStateChanged = (id, state) => { if (id === gAliasID) { expect(state).to.be.ok; @@ -472,12 +472,12 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont const parts = gAliasID.split('.'); parts.pop(); - context.adapter.subscribeForeignStates(parts.join('.') + '.*', () => + context.adapter.subscribeForeignStates(`${parts.join('.')}.*`, () => context.states.setState(gid, 10, err => expect(err).to.be.not.ok), ); }).timeout(3_000); - it(testName + 'Test unsubscribe aliases pattern', done => { + it(`${testName}Test unsubscribe aliases pattern`, done => { context.onAdapterStateChanged = () => { expect(true).to.be.false; }; @@ -485,7 +485,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont const parts = gAliasID.split('.'); parts.pop(); - context.adapter.unsubscribeForeignStates(parts.join('.') + '.*', () => { + context.adapter.unsubscribeForeignStates(`${parts.join('.')}.*`, () => { context.states.setState(gid, 10, err => { expect(err).to.be.not.ok; setTimeout(() => done(), 500); @@ -494,7 +494,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(3_000); // Avoid Issue 2753 - it(testName + 'Test subscribe alias multiple times should only publish once', async () => { + it(`${testName}Test subscribe alias multiple times should only publish once`, async () => { let noTriggered = 0; context.onAdapterStateChanged = (id, state) => { @@ -513,10 +513,10 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(noTriggered).to.equal(1); }).timeout(3_000); - it(testName + 'Test negative subscribe aliases regex', done => { + it(`${testName}Test negative subscribe aliases regex`, done => { const parts = gAliasID.split('.'); parts.pop(); - const regexp = new RegExp(parts.join('\\.') + '\\..*'); + const regexp = new RegExp(`${parts.join('\\.')}\\..*`); // @ts-expect-error we are passing a regexp which is not allowed context.adapter.subscribeForeignStates(regexp, err => { @@ -526,10 +526,10 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }).timeout(3_000); - it(testName + 'Test unsubscribe aliases regex', done => { + it(`${testName}Test unsubscribe aliases regex`, done => { const parts = gAliasID.split('.'); parts.pop(); - const regexp = new RegExp(parts.join('\\.') + '\\..*'); + const regexp = new RegExp(`${parts.join('\\.')}\\..*`); // @ts-expect-error we are passing a regexp which is not allowed context.adapter.unsubscribeForeignStates(regexp, err => { @@ -538,7 +538,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }).timeout(3_000); - it(testName + 'Test subscribe aliases array', done => { + it(`${testName}Test subscribe aliases array`, done => { let count = 0; context.onAdapterStateChanged = (id, state) => { if (id === gAliasID) { @@ -565,7 +565,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont ); }).timeout(3_000); - it(testName + 'Test unsubscribe aliases array', done => { + it(`${testName}Test unsubscribe aliases array`, done => { context.onAdapterStateChanged = () => { expect(true).to.be.false; }; @@ -578,7 +578,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }).timeout(3_000); - it(testName + 'Test change subscribed aliases', done => { + it(`${testName}Test change subscribed aliases`, done => { context.onAdapterStateChanged = (id, state) => { if (id === gAliasID) { // A: @@ -597,7 +597,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont max: 100, unit: '%', alias: { - id: gid + 'A', + id: `${gid}A`, }, read: true, write: true, @@ -619,7 +619,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // -200, 10 , 200 => 0, 52.5, 100 expect(state!.val).to.equal(52.5); context.adapter.unsubscribeForeignStates(gAliasID, () => { - context.states.setState(gid + 'A', 11, () => { + context.states.setState(`${gid}A`, 11, () => { done(); }); }); @@ -630,7 +630,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont setTimeout(() => { // this change must be ignored context.states.setState(gid, 20, () => { - context.states.setState(gid + 'A', 10); + context.states.setState(`${gid}A`, 10); }); }, 100); }, @@ -640,7 +640,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // create new alias context.adapter.setForeignObject( - gid + 'A', + `${gid}A`, { common: { name: 'forAliasA', @@ -661,7 +661,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont ); // => GOTO A: }).timeout(3_000); - it(testName + 'Test subscribe "*"', done => { + it(`${testName}Test subscribe "*"`, done => { // 1. Create alias // 2. Create normal state (independent from alias) // 3. subscribe "*" @@ -671,7 +671,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // 1. create new alias context.adapter.setForeignObject( - gid + 'Star', + `${gid}Star`, { common: { name: 'forAliasStar', @@ -687,7 +687,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }, () => context.adapter.setForeignObject( - gAliasID + 'Star', + `${gAliasID}Star`, { common: { name: 'Test Alias', @@ -696,7 +696,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont min: -10, max: 10, alias: { - id: gid + 'Star', + id: `${gid}Star`, }, read: true, write: true, @@ -707,7 +707,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont () => // 2. Create normal state (independent from alias) context.adapter.setForeignObject( - gid + 'NotAlias', + `${gid}NotAlias`, { common: { name: 'NotForAliasStar', @@ -726,14 +726,14 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont let count = 0; context.onAdapterStateChanged = (id, state) => { // B: - if (id === gid + 'NotAlias') { + if (id === `${gid}NotAlias`) { expect(state!.val).to.be.equal(2); count++; - } else if (id === gAliasID + 'Star') { + } else if (id === `${gAliasID}Star`) { count++; // no % -> no scaling expect(state!.val).to.be.equal(10); - } else if (id === gid + 'Star') { + } else if (id === `${gid}Star`) { count++; expect(state!.val).to.be.equal(10); } @@ -747,8 +747,8 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // 5. unsubscribe "*" context.adapter.unsubscribeForeignStates('*', () => - context.states.setState(gid + 'NotAlias', 3, () => - context.states.setState(gAliasID + 'Star', 5, () => + context.states.setState(`${gid}NotAlias`, 3, () => + context.states.setState(`${gAliasID}Star`, 5, () => setTimeout(() => done(), 500), ), ), @@ -757,8 +757,8 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }; // 4. changes must come for alias and independent state - context.states.setState(gid + 'NotAlias', 2, () => - context.states.setState(gid + 'Star', 10, () => { + context.states.setState(`${gid}NotAlias`, 2, () => + context.states.setState(`${gid}Star`, 10, () => { // go to B: }), ); @@ -768,7 +768,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont ); }).timeout(3_000); - it(testName + 'Test newly created alias after subscribe', done => { + it(`${testName}Test newly created alias after subscribe`, done => { // at first we subscribe context.adapter.subscribeForeignStates('*', err => { // create orig object @@ -830,7 +830,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }).timeout(3_000); - it(testName + 'Test newly created alias after partial subscribe', done => { + it(`${testName}Test newly created alias after partial subscribe`, done => { // at first we subscribe, but only partial context.adapter.unsubscribeForeignStates('*', () => { context.adapter.subscribeForeignStates(`${gAliasID}okay*`, err => { @@ -898,7 +898,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }).timeout(3_000); - it(testName + 'should respect different read and write ids', done => { + it(`${testName}should respect different read and write ids`, done => { // first we subscribe to all context.adapter.subscribeForeignStates('*', err => { expect(err).to.not.be.ok; @@ -989,7 +989,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }).timeout(3_000); - it(testName + 'should respect alias read id on getForeignStates', async () => { + it(`${testName}should respect alias read id on getForeignStates`, async () => { // set our alias read obj await context.adapter.setForeignObjectAsync(`${gid}readGetStates`, { common: { @@ -1049,13 +1049,13 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(states[`${gAliasID}aliasReadWriteGetStates`].val).to.be.equal(5); }).timeout(3_000); - it(testName + 'Read alias states via getStates should apply permissions', async () => { + it(`${testName}Read alias states via getStates should apply permissions`, async () => { const states = await context.adapter.getForeignStatesAsync(`${gAliasID}*`, { user: 'system.user.queen' }); // on permission problems, we will receive only an id with null, ensure that this does not happen expect(states[`${gAliasID}C`]).to.be.ok; }); - it(testName + 'Alias setState ignores source permissions', async () => { + it(`${testName}Alias setState ignores source permissions`, async () => { const nonAliasId = `${gid}.permissionNonAlias`; const aliasId = `${gAliasID}.permissionOnlyAlias`; const val = 3; @@ -1115,7 +1115,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont ).to.be.eventually.rejectedWith('permissionError', 'Should have thrown a permission error'); }); - it(testName + 'Non-existing alias should return a null value just like other state', async () => { + it(`${testName}Non-existing alias should return a null value just like other state`, async () => { const normalState = await context.adapter.getForeignStateAsync(`${gid}.isNotExisting`); const aliasState = await context.adapter.getForeignStateAsync(`${gAliasID}.isNotExisting`); diff --git a/packages/controller/test/lib/testConsole.ts b/packages/controller/test/lib/testConsole.ts index 12cc4f607..9135bfcbe 100644 --- a/packages/controller/test/lib/testConsole.ts +++ b/packages/controller/test/lib/testConsole.ts @@ -5,7 +5,7 @@ import type { TestContext } from '../_Types.js'; import fs from 'fs-extra'; import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); const iobExecutable = path.join(thisDir, '..', '..', 'iobroker.js'); @@ -13,7 +13,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont const testName = `${context.name} ${context.adapterShortName} console: `; // passwd, user passwd, user check - it(testName + 'user passwd', async () => { + it(`${testName}user passwd`, async () => { let res; res = await execAsync( @@ -91,7 +91,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(40_000); // user get - it(testName + 'user get', async () => { + it(`${testName}user get`, async () => { // check if no args set try { await execAsync(`"${process.execPath}" "${iobExecutable}" user`); @@ -120,7 +120,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(20_000); // adduser user add - it(testName + 'user add', async () => { + it(`${testName}user add`, async () => { let res; // check if no args set try { @@ -166,7 +166,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(20_000); // user disable / enable - it(testName + 'user disable/enable', async () => { + it(`${testName}user disable/enable`, async () => { let res; // add second user @@ -215,7 +215,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(25_000); // ud udel userdel deluser user del - it(testName + 'user del', async () => { + it(`${testName}user del`, async () => { let res; // check if no args set try { @@ -248,7 +248,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(20_000); // group add - it(testName + 'group add', async () => { + it(`${testName}group add`, async () => { // check if no args set try { await execAsync(`"${process.execPath}" "${iobExecutable}" group add`); @@ -279,7 +279,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(20_000); // group del - it(testName + 'group del', async () => { + it(`${testName}group del`, async () => { // check if no args set try { await execAsync(`"${process.execPath}" "${iobExecutable}" group del`); @@ -310,7 +310,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(20_000); // group list - it(testName + 'group list', async () => { + it(`${testName}group list`, async () => { // check if no args set // no user defined try { @@ -334,7 +334,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(20_000); // group get - it(testName + 'group get', async () => { + it(`${testName}group get`, async () => { // check if no args set try { await execAsync(`"${process.execPath}" "${iobExecutable}" group`); @@ -365,7 +365,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(20_000); // group disable / enable - it(testName + 'group disable/enable', async () => { + it(`${testName}group disable/enable`, async () => { let res; // add second group res = await execAsync(`"${process.execPath}" "${iobExecutable}" group add group1`); @@ -413,7 +413,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(25_000); // group useradd - it(testName + 'group useradd', async () => { + it(`${testName}group useradd`, async () => { let res; // add non existing user @@ -446,7 +446,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(20_000); // group userdel - it(testName + 'group userdel', async () => { + it(`${testName}group userdel`, async () => { // delete non existing user try { await execAsync(`"${process.execPath}" "${iobExecutable}" group userdel group1 user5`); @@ -482,7 +482,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // stop ?? // status - it(testName + 'status', async () => { + it(`${testName}status`, async () => { // check status try { await execAsync(`"${process.execPath}" "${iobExecutable}" status`); @@ -508,7 +508,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // update // setup - it(testName + 'setup', async () => { + it(`${testName}setup`, async () => { let res; // check setup res = await execAsync(`"${process.execPath}" "${iobExecutable}" setup`); @@ -536,7 +536,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // message // update - it(testName + 'update', async () => { + it(`${testName}update`, async () => { // check update const res = await execAsync(`"${process.execPath}" "${iobExecutable}" update`); expect(res.stderr).to.be.not.ok; @@ -547,7 +547,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // clean // restore // backup - it(testName + 'backup', async () => { + it(`${testName}backup`, async () => { // create backup const dir = BackupRestore.getBackupDir(); @@ -599,7 +599,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // file f // id uuid - it(testName + 'uuid', async () => { + it(`${testName}uuid`, async () => { let res; // uuid res = await execAsync(`"${process.execPath}" "${iobExecutable}" uuid`); @@ -611,7 +611,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(20_000); // v version - it(testName + 'version', async () => { + it(`${testName}version`, async () => { let res; // version res = await execAsync(`"${process.execPath}" "${iobExecutable}" version`); @@ -623,7 +623,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(20_000); // repo - it(testName + 'repo', async () => { + it(`${testName}repo`, async () => { let res; // add non existing repo res = await execAsync(`"${process.execPath}" "${iobExecutable}" repo add local some/path`); @@ -686,7 +686,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(50_000); // license - it(testName + 'license', async () => { + it(`${testName}license`, async () => { // test license const licenseText = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiaW9icm9rZXIudmlzIiwidHlwZSI6InRlc3QiLCJlbWFpbCI6InRlc3RAZ21haWwuY29tIiwiZXhwaXJlcyI6MjQ0NDM5ODA5NSwidmVyc2lvbiI6IjwyIiwiaWQiOiI5NTBkYWEwMC01MzcxLTExZTctYjQwNS14eHh4eHh4eHh4eHh4IiwiaWF0IjoxNDk3NzEzMjk1fQ.K9t9ZtvAsdeNFTJed4Sidq2jrr9UFOYpMt6VLmBdVzWueI9DnCXFS5PwBFTBTmF9WMhVk6LBw5ujIVl130B_5NrHl21PHkCLvJeW7jGsMgWDINuBK5F9k8LZABdsv7uDbqNDSOsVrFwEKOu2V3N5sMWYOVE4N_COIg9saaLvyN69oIP27PTgk1GHuyU4giFKGLPTp10L5p2hxLX0lEPjSdDggbl7dEqEe1-u5WwkyBizp03pMtHGYtjnACtP_KBuOly7QpmAnoPlfFoW79xgRjICbd41wT43IvhKAAo1zfnRAeWfQ7QoUViKsc6N1es87QC4KKw-eToLPXOO5UzWOg'; diff --git a/packages/controller/test/lib/testFiles.ts b/packages/controller/test/lib/testFiles.ts index f77f58731..65baff64b 100644 --- a/packages/controller/test/lib/testFiles.ts +++ b/packages/controller/test/lib/testFiles.ts @@ -4,7 +4,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont const testName = `${context.name} ${context.adapterShortName} files: `; const testId = `testFilesObject.0`; - it(testName + 'writeFile with binary content and subscription', async () => { + it(`${testName}writeFile with binary content and subscription`, async () => { const objId = `vis.0`; const fileName = 'testFile.bin'; const dataBinary = Buffer.from('1234'); @@ -40,7 +40,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(file.toString('utf8')).to.be.equal(dataBinary.toString('utf8')); }); - it(testName + 'writeFile with textual content', async () => { + it(`${testName}writeFile with textual content`, async () => { const objId = `vis.0`; /** unknown extension but string content should lead to plain text */ const fileName = 'testFile.fn'; @@ -64,7 +64,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(file).to.be.equal(dataText); }); - it(testName + 'writeFile without extension should infer text from string content', async () => { + it(`${testName}writeFile without extension should infer text from string content`, async () => { const objId = `vis.0`; /** no extension but string content should lead to plain text */ const fileName = 'testFile'; @@ -88,7 +88,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(file).to.be.equal(dataText); }); - it(testName + 'writeFile with known extension should be inferred', async () => { + it(`${testName}writeFile with known extension should be inferred`, async () => { const objId = `vis.0`; /** no extension but string content should lead to plain text */ const fileName = 'testFile.json'; @@ -113,7 +113,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(file).to.be.equal(content); }); - it(testName + 'deleteFile', async () => { + it(`${testName}deleteFile`, async () => { const objId = `vis.0`; const fileName = 'testFile.bin'; @@ -138,7 +138,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont } }); - it(testName + 'should create and read file with callback', done => { + it(`${testName}should create and read file with callback`, done => { const objects = context.objects; objects.setObject( testId, @@ -176,7 +176,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont ); }); - it(testName + 'should create and read file async', async () => { + it(`${testName}should create and read file async`, async () => { const fileDir = 'myFile'; const fileName = 'abc2.txt'; const fullFileName = `${fileDir}/${fileName}`; @@ -205,7 +205,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont } }); - it(testName + 'should read directory', done => { + it(`${testName}should read directory`, done => { const objects = context.objects; objects.writeFile(testId, 'myFileA/abc1.txt', 'dataInFile', err => { expect(err).to.be.not.ok; @@ -223,7 +223,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should read file and prevent path traversing', done => { + it(`${testName}should read file and prevent path traversing`, done => { const objects = context.objects; objects.readFile(testId, '../../myFileA/abc1.txt', null, (err, data, _mimeType) => { expect(err).to.be.not.ok; @@ -271,7 +271,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should unlink file', done => { + it(`${testName}should unlink file`, done => { const objects = context.objects; objects.unlink(testId, 'myFileA/abc1.txt', null, err => { expect(err).to.be.not.ok; @@ -282,7 +282,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should rename file', done => { + it(`${testName}should rename file`, done => { const objects = context.objects; objects.writeFile(testId, 'myFile1/abcRename.txt', Buffer.from('abcd'), err => { expect(err).to.be.not.ok; @@ -300,7 +300,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should touch file', done => { + it(`${testName}should touch file`, done => { const objects = context.objects; objects.readDir(testId, 'myFileA', null, (err, files) => { expect(err).to.be.not.ok; @@ -319,15 +319,15 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should create directory', done => { + it(`${testName}should create directory`, done => { const objects = context.objects; - objects.mkdir(testId, 'myFile' + Math.round(Math.random() * 100_000), null, err => { + objects.mkdir(testId, `myFile${Math.round(Math.random() * 100_000)}`, null, err => { expect(err).to.be.not.ok; done(); }); }); - it(testName + 'should enable file cache', done => { + it(`${testName}should enable file cache`, done => { const objects = context.objects; objects.enableFileCache(true, err => { expect(err).to.be.not.ok; diff --git a/packages/controller/test/lib/testHelperStates.ts b/packages/controller/test/lib/testHelperStates.ts index 121042c01..a27289c99 100644 --- a/packages/controller/test/lib/testHelperStates.ts +++ b/packages/controller/test/lib/testHelperStates.ts @@ -5,7 +5,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // deleteChannel // deleteState - it(testName + 'delete state should validate the input', async () => { + it(`${testName}delete state should validate the input`, async () => { await context.adapter.deleteStateAsync('test'); await context.adapter.deleteStateAsync('dev', 'channel', 'state'); await context.adapter.deleteStateAsync('channel', 'state'); @@ -27,7 +27,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // createState // deleteDevice - it(testName + 'requireLog should activate corresponding state', async () => { + it(`${testName}requireLog should activate corresponding state`, async () => { // default should be false or non-existent let state = await context.states.getState(`system.adapter.${context.adapter.namespace}.logging`); expect(state?.val).to.be.not.ok; diff --git a/packages/controller/test/lib/testMessages.ts b/packages/controller/test/lib/testMessages.ts index b9c690b14..471e30f90 100644 --- a/packages/controller/test/lib/testMessages.ts +++ b/packages/controller/test/lib/testMessages.ts @@ -1,9 +1,9 @@ import type { TestContext } from '../_Types.js'; export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, context: TestContext): void { - const testName = context.name + ' ' + context.adapterShortName + ' adapter: '; - const gid = 'system.adapter.' + context.adapterShortName + '.0'; - it(testName + 'check pushMessage', function (done) { + const testName = `${context.name} ${context.adapterShortName} adapter: `; + const gid = `system.adapter.${context.adapterShortName}.0`; + it(`${testName}check pushMessage`, function (done) { context.states.subscribeMessage(gid, function (err) { expect(err).to.be.not.ok; @@ -21,7 +21,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); }); - it(testName + 'check pushMessage Buffer', function (done) { + it(`${testName}check pushMessage Buffer`, function (done) { context.states.subscribeMessage(gid, function (err) { expect(err).to.be.not.ok; @@ -40,14 +40,14 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); }); - it(testName + 'check unsubscribeMessage', function (done) { + it(`${testName}check unsubscribeMessage`, function (done) { context.states.unsubscribeMessage(gid, function (err) { expect(err).to.be.not.ok; done(); }); }); - it(testName + 'check pushLog', function (done) { + it(`${testName}check pushLog`, function (done) { context.states.subscribeLog(gid, function (err) { expect(err).to.be.not.ok; context.states.pushLog( @@ -62,7 +62,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'check unsubscribeLog', function (done) { + it(`${testName}check unsubscribeLog`, function (done) { context.states.unsubscribeLog(gid, function (err) { expect(err).to.be.not.ok; done(); diff --git a/packages/controller/test/lib/testObjects.ts b/packages/controller/test/lib/testObjects.ts index a4d3b9e2b..da85fa7fa 100644 --- a/packages/controller/test/lib/testObjects.ts +++ b/packages/controller/test/lib/testObjects.ts @@ -5,12 +5,12 @@ import type { TestContext } from '../_Types.js'; */ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, context: TestContext): void { - const testName = context.name + ' objects: '; + const testName = `${context.name} objects: `; const namespace = 'testObject.0'; - const testId = namespace + '.test2'; + const testId = `${namespace}.test2`; - it(testName + 'should create and read object', done => { + it(`${testName}should create and read object`, done => { const objects = context.objects; objects.setObject( testId, @@ -42,10 +42,10 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont ); }); - it(testName + 'should create object async', done => { + it(`${testName}should create object async`, done => { const objects = context.objects; objects - .setObjectAsync(testId + 'async', { + .setObjectAsync(`${testId}async`, { type: 'state', common: { type: 'string', @@ -58,7 +58,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }) .then(res => { expect(res).to.be.ok; - expect(res!.id).to.be.equal(testId + 'async'); + expect(res!.id).to.be.equal(`${testId}async`); done(); }) .catch(err => { @@ -66,14 +66,14 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should read object async', done => { + it(`${testName}should read object async`, done => { const objects = context.objects; objects - .getObjectAsync(testId + 'async') + .getObjectAsync(`${testId}async`) .then(obj => { expect(obj).to.be.ok; expect(obj!.common.name).to.be.equal('test1a'); - expect(obj!._id).to.be.equal(testId + 'async'); + expect(obj!._id).to.be.equal(`${testId}async`); console.log(JSON.stringify(obj)); done(); }) @@ -82,7 +82,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }).timeout(3_000); - it(testName + 'should find object', done => { + it(`${testName}should find object`, done => { const objects = context.objects; objects.findObject(testId, null, (err, id, idOrName) => { expect(err).to.be.not.ok; @@ -110,7 +110,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should find object async', done => { + it(`${testName}should find object async`, done => { const objects = context.objects; objects .findObject(testId) @@ -137,7 +137,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should read objects by pattern', done => { + it(`${testName}should read objects by pattern`, done => { const objects = context.objects; objects.getObjectsByPattern(`${testId}*`, null, (err, objs) => { expect(err).to.be.not.ok; @@ -149,7 +149,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(typeof objs![0]).to.be.equal('object'); expect(objs![0]._id).to.be.equal(testId); - objects.getObjectsByPattern(testId + 'non', null, (err, objs) => { + objects.getObjectsByPattern(`${testId}non`, null, (err, objs) => { expect(err).to.be.not.ok; expect(objs?.length).to.be.equal(0); @@ -159,7 +159,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should read objects by pattern async', done => { + it(`${testName}should read objects by pattern async`, done => { const objects = context.objects; objects .getObjectsByPattern(`${testId}*`, null) @@ -185,9 +185,9 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should read keys', done => { + it(`${testName}should read keys`, done => { const objects = context.objects; - objects.getKeys(testId + '*', (err, keys) => { + objects.getKeys(`${testId}*`, (err, keys) => { expect(err).to.be.not.ok; expect(keys?.length).to.be.equal(2); @@ -196,7 +196,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(keys?.length).to.be.equal(1); expect(keys![0]).to.be.equal(testId); - objects.getKeys(testId + 'non', (err, keys) => { + objects.getKeys(`${testId}non`, (err, keys) => { expect(err).to.be.not.ok; expect(keys?.length).to.be.equal(0); @@ -206,10 +206,10 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should read keys async', done => { + it(`${testName}should read keys async`, done => { const objects = context.objects; objects - .getKeys(testId + '*') + .getKeys(`${testId}*`) .then(keys => { expect(keys?.length).to.be.equal(2); @@ -219,7 +219,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(keys?.length).to.be.equal(1); expect(keys![0]).to.be.equal(testId); - return objects.getKeys(testId + 'non'); + return objects.getKeys(`${testId}non`); }) .then(keys => { expect(keys?.length).to.be.equal(0); @@ -231,9 +231,9 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should read objects', done => { + it(`${testName}should read objects`, done => { const objects = context.objects; - objects.getKeys(testId + '*', (err, keys) => { + objects.getKeys(`${testId}*`, (err, keys) => { expect(err).to.be.not.ok; objects.getObjects(keys!, (err, objs) => { expect(err).to.be.not.ok; @@ -245,11 +245,11 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should read objects async', done => { + it(`${testName}should read objects async`, done => { const objects = context.objects; let gKeys: string[] | undefined; objects - .getKeys(testId + '*') + .getKeys(`${testId}*`) .then(keys => { gKeys = keys; return objects.getObjects(keys!); @@ -265,7 +265,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should extend object', done => { + it(`${testName}should extend object`, done => { const objects = context.objects; objects.extendObject(testId, { common: { def: 'default' } }, null, (err, res, id) => { expect(err).to.be.not.ok; @@ -279,10 +279,10 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(obj!.common.def).to.be.equal('default'); expect(obj!.common.name).to.be.equal('test2'); - objects.extendObject(namespace + '.other', { common: { def: 'default' } }, null, (err, res, id) => { + objects.extendObject(`${namespace}.other`, { common: { def: 'default' } }, null, (err, res, id) => { expect(err).to.be.not.ok; - expect(id).to.be.equal(namespace + '.other'); - expect(res!.id).to.be.equal(namespace + '.other'); + expect(id).to.be.equal(`${namespace}.other`); + expect(res!.id).to.be.equal(`${namespace}.other`); expect(res!.value.common.def).to.be.equal('default'); done(); @@ -291,17 +291,17 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should extend object async', done => { + it(`${testName}should extend object async`, done => { const objects = context.objects; objects .extendObject(testId, { common: { def: 'default' } }) .then(res => { expect(res!.id).to.be.equal(testId); expect(res!.value.common.def).to.be.equal('default'); - return objects.extendObject(namespace + '.otherAsync', { common: { def: 'default' } }); + return objects.extendObject(`${namespace}.otherAsync`, { common: { def: 'default' } }); }) .then(res => { - expect(res!.id).to.be.equal(namespace + '.otherAsync'); + expect(res!.id).to.be.equal(`${namespace}.otherAsync`); expect(res!.value.common.def).to.be.equal('default'); done(); }) @@ -310,7 +310,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should getObjectList', done => { + it(`${testName}should getObjectList`, done => { const objects = context.objects; objects.getObjectList({ startkey: namespace, endkey: testId }, (err, res) => { console.log(res!.rows.map(e => e.id)); @@ -328,7 +328,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should getObjectList async', done => { + it(`${testName}should getObjectList async`, done => { const objects = context.objects; objects .getObjectList({ startkey: namespace, endkey: testId }) @@ -350,7 +350,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should getObjectView without sets', async () => { + it(`${testName}should getObjectView without sets`, async () => { // @ts-expect-error turn off useSets and reinitialize scripts, thus we will have old scripts and do not use SADD on setting objects context.objects.useSets = false; await context.objects.loadLuaScripts(); @@ -398,7 +398,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont await context.objects.loadLuaScripts(); }); - it(testName + 'Should check object existence', async () => { + it(`${testName}Should check object existence`, async () => { // object should not exist let exists = await context.objects.objectExists('test.0.objectExistenceCheck'); expect(exists).to.be.false; @@ -417,7 +417,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // todo chmod // tofo chown - it(testName + 'should delete object', done => { + it(`${testName}should delete object`, done => { const objects = context.objects; objects.delObject(testId, err => { expect(err).to.be.not.ok; @@ -425,10 +425,10 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should delete object async', done => { + it(`${testName}should delete object async`, done => { const objects = context.objects; objects - .delObjectAsync(testId + 'async') + .delObjectAsync(`${testId}async`) .then(() => { done(); }) @@ -437,18 +437,18 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should not delete non existing object', done => { + it(`${testName}should not delete non existing object`, done => { const objects = context.objects; - objects.delObject(testId + 'not', err => { + objects.delObject(`${testId}not`, err => { expect(err).to.be.not.ok; done(); }); }); - it(testName + 'should not delete non existing object async', done => { + it(`${testName}should not delete non existing object async`, done => { const objects = context.objects; objects - .delObjectAsync(testId + 'async1') + .delObjectAsync(`${testId}async1`) .then(() => { done(); }) @@ -457,7 +457,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'should close DB', () => { + it(`${testName}should close DB`, () => { const objects = context.objects; // we're running as a server, so nothing should happen return objects.destroy(); diff --git a/packages/controller/test/lib/testObjectsACL.ts b/packages/controller/test/lib/testObjectsACL.ts index ba1bd4ea1..96e176eb8 100644 --- a/packages/controller/test/lib/testObjectsACL.ts +++ b/packages/controller/test/lib/testObjectsACL.ts @@ -1,11 +1,11 @@ import type { TestContext } from '../_Types.js'; export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, context: TestContext): void { - const textName = context.name + ' objects: '; + const textName = `${context.name} objects: `; const secretId = 'system.adapter.userMayNotReadIt'; - it(textName + 'should create users and groups', () => { + it(`${textName}should create users and groups`, () => { const objects = context.objects; return objects @@ -103,7 +103,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont ); }).timeout(2_000); - it(textName + 'invalid user name must be checked #1', async () => { + it(`${textName}invalid user name must be checked #1`, async () => { const objects = context.objects; try { await objects.getObject(secretId, { user: 'admin' }); @@ -114,7 +114,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont } }).timeout(2_000); - it(textName + 'invalid user name must be checked #2', () => { + it(`${textName}invalid user name must be checked #2`, () => { const objects = context.objects; return objects .getObject(secretId, { user: 'system.user.admin1' }) @@ -127,7 +127,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }).timeout(2_000); - it(textName + 'admin may read secret object', () => { + it(`${textName}admin may read secret object`, () => { const objects = context.objects; return objects .getObject(secretId, { user: 'system.user.admin' }) @@ -140,7 +140,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }).timeout(2_000); - it(textName + 'user may not read secret object', () => { + it(`${textName}user may not read secret object`, () => { const objects = context.objects; return objects .getObject(secretId, { user: 'system.user.user' }) @@ -152,7 +152,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }).timeout(2_000); - it(textName + 'default acl from system.config should be used', async () => { + it(`${textName}default acl from system.config should be used`, async () => { const objects = context.objects; await objects.setObjectAsync('test.defAcl', { @@ -172,7 +172,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(obj!.acl!.ownerGroup).to.be.equal('system.group.senatorGroup'); }).timeout(2_000); - it(textName + 'default acl from system.config can be overwritten via acl', async () => { + it(`${textName}default acl from system.config can be overwritten via acl`, async () => { const objects = context.objects; await objects.setObjectAsync('test.overwriteAclDef', { type: 'state', @@ -196,7 +196,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(obj!.acl!.ownerGroup).to.be.equal('system.group.administrator'); }).timeout(2_000); - it(textName + 'default acl from system.config is used when user is admin', async () => { + it(`${textName}default acl from system.config is used when user is admin`, async () => { const objects = context.objects; await objects.setObjectAsync( 'test.aclAdmin', @@ -218,43 +218,40 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(obj!.acl!.ownerGroup).to.be.equal('system.group.senatorGroup'); }).timeout(2_000); - it( - textName + 'default acl from system.config is used when user is admin and can be modified on the fly', - async () => { - const objects = context.objects; + it(`${textName}default acl from system.config is used when user is admin and can be modified on the fly`, async () => { + const objects = context.objects; - // get the system.config to save the acl - const config = await objects.getObject('system.config'); + // get the system.config to save the acl + const config = await objects.getObject('system.config'); - config!.common.defaultNewAcl = { - object: 1636, - state: 1636, - file: 1636, - owner: 'system.user.notGovernor', - ownerGroup: 'system.group.notSenatorGroup', - }; + config!.common.defaultNewAcl = { + object: 1636, + state: 1636, + file: 1636, + owner: 'system.user.notGovernor', + ownerGroup: 'system.group.notSenatorGroup', + }; - // we change the acl during runtime - it has to be applied on next setObject - await objects.setObject('system.config', config!); + // we change the acl during runtime - it has to be applied on next setObject + await objects.setObject('system.config', config!); - await objects.setObject( - 'test.aclAdminChange', - { - type: 'state', - common: { - type: 'string', - role: 'state', - name: 'test', - read: true, - write: true, - }, - native: {}, + await objects.setObject( + 'test.aclAdminChange', + { + type: 'state', + common: { + type: 'string', + role: 'state', + name: 'test', + read: true, + write: true, }, - { user: 'system.user.admin' }, - ); - const obj = await objects.getObjectAsync('test.aclAdminChange'); - expect(obj!.acl!.owner).to.be.equal('system.user.notGovernor'); - expect(obj!.acl!.ownerGroup).to.be.equal('system.group.notSenatorGroup'); - }, - ).timeout(2_000); + native: {}, + }, + { user: 'system.user.admin' }, + ); + const obj = await objects.getObjectAsync('test.aclAdminChange'); + expect(obj!.acl!.owner).to.be.equal('system.user.notGovernor'); + expect(obj!.acl!.ownerGroup).to.be.equal('system.group.notSenatorGroup'); + }).timeout(2_000); } diff --git a/packages/controller/test/lib/testObjectsFunctions.ts b/packages/controller/test/lib/testObjectsFunctions.ts index 1b73e5d94..c8590dbaf 100644 --- a/packages/controller/test/lib/testObjectsFunctions.ts +++ b/packages/controller/test/lib/testObjectsFunctions.ts @@ -12,7 +12,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont const gid = 'myTestObject'; // setObject positive - it(testName + 'Check if objects will be created', function (done) { + it(`${testName}Check if objects will be created`, function (done) { this.timeout(3_000); context.adapter.setObject( gid, @@ -48,7 +48,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // setObject negative - it(testName + 'Check if objects will not be created without mandatory attribute type', function (done) { + it(`${testName}Check if objects will not be created without mandatory attribute type`, function (done) { this.timeout(3_000); const id = 'myTestObjectNoType'; context.adapter.setObject( @@ -65,7 +65,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont (err: any) => { expect(err).to.be.ok; - context.objects.getObject(context.adapterShortName + '.0.' + id, function (err, obj) { + context.objects.getObject(`${context.adapterShortName}.0.${id}`, function (err, obj) { expect(err).to.be.not.ok; // there is no message, that object does not exist. Errors will be given back only if no access rights expect(obj).to.be.not.ok; done(); @@ -75,7 +75,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getAdapterObjects - it(testName + 'Read all objects of adapter', function (done) { + it(`${testName}Read all objects of adapter`, function (done) { context.adapter.getAdapterObjects(objects => { expect(objects).to.be.ok; expect(objects[`${context.adapterShortName}.0.${gid}`]).to.be.ok; @@ -85,7 +85,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); //extendObject - it(testName + 'Check if objects will be extended', function (done) { + it(`${testName}Check if objects will be extended`, function (done) { context.adapter.extendObject( gid, { @@ -113,12 +113,12 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // setForeignObject - it(testName + 'Check if foreign objects will be created', function (done) { + it(`${testName}Check if foreign objects will be created`, function (done) { this.timeout(3_000); // create testf.0.myTestObject context.adapter.setForeignObject( - context.adapterShortName + 'f.0.' + gid, + `${context.adapterShortName}f.0.${gid}`, { type: 'state', common: { @@ -144,7 +144,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(err).to.be.not.ok; expect(obj).to.be.ok; expect(obj!.native).to.be.ok; - expect(obj!._id).equal(context.adapterShortName + 'f.0.' + gid); + expect(obj!._id).equal(`${context.adapterShortName}f.0.${gid}`); expect(obj!.common.name).equal('test1'); expect(obj!.type).equal('state'); //expect(obj.acl).to.be.ok; @@ -155,7 +155,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // extendForeignObject - it(testName + 'Check if foreign objects will be extended', function (done) { + it(`${testName}Check if foreign objects will be extended`, function (done) { context.adapter.extendForeignObject( `${context.adapterShortName}f.0.${gid}`, { @@ -196,7 +196,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getObject - it(testName + 'Check get object', function (done) { + it(`${testName}Check get object`, function (done) { context.adapter.getObject(`${context.adapterShortName}.0.${gid}`, function (err, obj) { expect(err).to.be.null; @@ -214,18 +214,18 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getForeignObjects - it(testName + 'Check get foreign objects (pattern)', done => { - context.adapter.getForeignObjects(context.adapterShortName + 'f.0.*', (err, objs) => { + it(`${testName}Check get foreign objects (pattern)`, done => { + context.adapter.getForeignObjects(`${context.adapterShortName}f.0.*`, (err, objs) => { expect(err).to.be.null; expect(objs).to.be.ok; - expect(objs![context.adapterShortName + 'f.0.' + gid].type).to.be.equal('state'); - expect(objs![context.adapterShortName + 'f.0.' + gid].native.attr1).to.be.equal('11'); + expect(objs![`${context.adapterShortName}f.0.${gid}`].type).to.be.equal('state'); + expect(objs![`${context.adapterShortName}f.0.${gid}`].native.attr1).to.be.equal('11'); done(); }); }); - it(testName + 'Check get foreign objects (array)', async () => { + it(`${testName}Check get foreign objects (array)`, async () => { const id = `${context.adapterShortName}f.0.${gid}`; const id2 = `${context.adapterShortName}.0.${gid}`; @@ -237,7 +237,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(objs[id2].type).to.be.equal('state'); }); - it(testName + 'Check get foreign objects - default enum functionality', async () => { + it(`${testName}Check get foreign objects - default enum functionality`, async () => { const id = `${context.adapterShortName}.0.${gid}`; // add the state to the enum, so we can check enum functionality @@ -257,14 +257,14 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // findForeignObject - it(testName + 'Check find foreign object', function (done) { + it(`${testName}Check find foreign object`, function (done) { context.adapter.findForeignObject('test1', null, function (err, id) { expect(err).to.be.null; - expect(id).to.be.equal(context.adapterShortName + '.0.' + gid); + expect(id).to.be.equal(`${context.adapterShortName}.0.${gid}`); context.adapter.findForeignObject('test1', 'number', function (err, id) { expect(err).to.be.null; - expect(id).to.be.equal(context.adapterShortName + '.0.' + gid); + expect(id).to.be.equal(`${context.adapterShortName}.0.${gid}`); context.adapter.findForeignObject('test1', 'channel', function (err, id) { expect(err).to.be.null; @@ -277,8 +277,8 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getForeignObject - it(testName + 'Check get foreign object', function (done) { - context.adapter.getForeignObject(context.adapterShortName + 'f.0.' + gid, function (err, obj) { + it(`${testName}Check get foreign object`, function (done) { + context.adapter.getForeignObject(`${context.adapterShortName}f.0.${gid}`, function (err, obj) { expect(err).to.be.null; expect(obj).to.be.ok; @@ -294,7 +294,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // protection check for getForeignObject - it(testName + 'Check if foreign system adapters protectedNative is not accessible', function (done) { + it(`${testName}Check if foreign system adapters protectedNative is not accessible`, function (done) { this.timeout(3_000); // create a system.adapter object of another adapter context.adapter.setForeignObject( @@ -339,11 +339,11 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // own protectedNative should be available - it(testName + 'Check if own system adapters protectedNative is available via getForeignObject', function (done) { + it(`${testName}Check if own system adapters protectedNative is available via getForeignObject`, function (done) { this.timeout(3_000); // create a system.adapter object of own adapter context.adapter.setForeignObject( - 'system.adapter.' + context.adapterShortName + '.0', + `system.adapter.${context.adapterShortName}.0`, { type: 'instance', common: { @@ -368,26 +368,23 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont function (err) { expect(err).to.be.null; - context.adapter.getForeignObject( - 'system.adapter.' + context.adapterShortName + '.0', - function (err, obj) { - expect(err).to.be.not.ok; - expect(obj).to.be.ok; - expect(obj!.native).to.be.ok; - expect(obj!.common.name).equal('tesla'); - expect(obj!.native.model).equal('S P85D'); - expect(obj!.native.password).equal('winning'); - expect(obj!.native.username).equal('tesla'); - expect(obj!._id).equal('system.adapter.' + context.adapterShortName + '.0'); - done(); - }, - ); + context.adapter.getForeignObject(`system.adapter.${context.adapterShortName}.0`, function (err, obj) { + expect(err).to.be.not.ok; + expect(obj).to.be.ok; + expect(obj!.native).to.be.ok; + expect(obj!.common.name).equal('tesla'); + expect(obj!.native.model).equal('S P85D'); + expect(obj!.native.password).equal('winning'); + expect(obj!.native.username).equal('tesla'); + expect(obj!._id).equal(`system.adapter.${context.adapterShortName}.0`); + done(); + }); }, ); }); // setObjectNotExists - it(testName + 'Try to set existing object', function (done) { + it(`${testName}Try to set existing object`, function (done) { context.adapter.setObjectNotExists( gid, { @@ -413,7 +410,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(obj1!.native.pparam).to.be.not.ok; context.adapter.setObjectNotExists( - gid + 'A', + `${gid}A`, { common: { name: 'must be set', @@ -430,7 +427,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont function (err) { expect(err).to.be.null; - context.adapter.getObject(gid + 'A', function (err, obj1) { + context.adapter.getObject(`${gid}A`, function (err, obj1) { expect(err).to.be.null; expect(obj1!.native).to.be.ok; @@ -445,9 +442,9 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // setForeignObjectNotExists - it(testName + 'Try to set existing foreign object', function (done) { + it(`${testName}Try to set existing foreign object`, function (done) { context.adapter.setForeignObjectNotExists( - context.adapterShortName + '.0.' + gid, + `${context.adapterShortName}.0.${gid}`, { common: { name: 'not must be set', @@ -464,14 +461,14 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont function (err) { expect(err).to.be.null; - context.adapter.getForeignObject(context.adapterShortName + '.0.' + gid, function (err, obj1) { + context.adapter.getForeignObject(`${context.adapterShortName}.0.${gid}`, function (err, obj1) { expect(err).to.be.null; expect(obj1!.native).to.be.ok; expect(obj1!.native.ppparam).to.be.not.ok; context.adapter.setForeignObjectNotExists( - context.adapterShortName + 'ff.0.' + gid, + `${context.adapterShortName}ff.0.${gid}`, { common: { name: 'must be set', @@ -489,7 +486,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(err).to.be.null; context.adapter.getForeignObject( - context.adapterShortName + 'ff.0.' + gid, + `${context.adapterShortName}ff.0.${gid}`, function (err, obj1) { expect(err).to.be.null; @@ -506,9 +503,9 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // setForeignObject merge of custom settings - it(testName + 'Try to merge custom settings', done => { + it(`${testName}Try to merge custom settings`, done => { context.adapter.setForeignObject( - context.adapterShortName + '.0.' + gid, + `${context.adapterShortName}.0.${gid}`, { type: 'state', common: { @@ -528,7 +525,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont err => { expect(err).to.be.null; context.adapter.setForeignObject( - context.adapterShortName + '.0.' + gid, + `${context.adapterShortName}.0.${gid}`, { common: { type: 'string', @@ -547,7 +544,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }, err => { expect(err).to.be.null; - context.adapter.getForeignObject(context.adapterShortName + '.0.' + gid, (err, obj1) => { + context.adapter.getForeignObject(`${context.adapterShortName}.0.${gid}`, (err, obj1) => { expect(err).to.be.null; expect(obj1!.common.custom!.material).to.be.ok; @@ -561,8 +558,8 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // setForeignObject merge of custom settings - it(testName + 'Try to delete custom settings', done => { - const id = context.adapterShortName + '.0.' + gid; + it(`${testName}Try to delete custom settings`, done => { + const id = `${context.adapterShortName}.0.${gid}`; context.adapter.setForeignObject( id, { @@ -618,8 +615,8 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // setForeignObject merge of custom settings - it(testName + 'Try to delete custom settings in new object', done => { - const id = context.adapterShortName + '.0.' + gid + '6'; + it(`${testName}Try to delete custom settings in new object`, done => { + const id = `${context.adapterShortName}.0.${gid}6`; context.adapter.setForeignObject( id, @@ -676,7 +673,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getObjectView - it(testName + 'Try to get object view', done => { + it(`${testName}Try to get object view`, done => { // create the view context.adapter .setForeignObjectAsync('_design/hm-rpc', { @@ -730,7 +727,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getObjectViewAsync - it(testName + 'Try to get object view in async setup', async () => { + it(`${testName}Try to get object view in async setup`, async () => { // create the view await context.adapter.setForeignObjectAsync('_design/hm-rpc', { language: 'javascript', @@ -770,7 +767,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(doc.rows[0].value._id).to.be.equal('hm-rpc.meta.VALUES.HM-CC-RT-DN.CLIMATECONTROL_RECEIVER.19'); }); - it(testName + 'Try to get object view with custom', async function () { + it(`${testName}Try to get object view with custom`, async function () { this.timeout(3_000); const customObj = { @@ -813,7 +810,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getObjectList - it(testName + 'Try to get object list', done => { + it(`${testName}Try to get object list`, done => { // let's create an object matching the list context.adapter .setForeignObjectAsync('hm-rpc.meta.VALUES.HM-CC-RT-DN.CLIMATECONTROL_RECEIVER.19', { @@ -853,7 +850,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getObjectListAsync - it(testName + 'Try to get object list async', done => { + it(`${testName}Try to get object list async`, done => { // let's create an object matching the list context.adapter .setForeignObjectAsync('hm-rpc.meta.VALUES.HM-CC-RT-DN.CLIMATECONTROL_RECEIVER.19', { @@ -888,7 +885,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // delObject - it(testName + 'Try to delete existing object', done => { + it(`${testName}Try to delete existing object`, done => { context.adapter.delObject(gid, err => { expect(err).to.not.be.ok; @@ -907,17 +904,17 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // delForeignObject - it(testName + 'Try to delete foreign existing object', function (done) { - context.adapter.delForeignObject(context.adapterShortName + 'f.0.' + gid, function (err) { + it(`${testName}Try to delete foreign existing object`, function (done) { + context.adapter.delForeignObject(`${context.adapterShortName}f.0.${gid}`, function (err) { expect(err).to.not.be.ok; - context.adapter.getForeignObject(context.adapterShortName + 'f.0.' + gid, function (err, obj) { + context.adapter.getForeignObject(`${context.adapterShortName}f.0.${gid}`, function (err, obj) { expect(err).to.be.not.ok; expect(obj).to.be.null; // deleting non existing object should not result in an error - context.adapter.delForeignObject(context.adapterShortName + 'f.0.' + gid, function (err) { + context.adapter.delForeignObject(`${context.adapterShortName}f.0.${gid}`, function (err) { expect(err).to.be.not.ok; done(); }); @@ -926,7 +923,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // check that enum membership is removed on delForeignObject - it(testName + 'should delete enum membership on object deletion', done => { + it(`${testName}should delete enum membership on object deletion`, done => { const objects = context.objects; const enumObj: ioBroker.SettableEnumObject = { common: { @@ -969,10 +966,10 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // subscribeObjects - it(testName + 'Try to subscribe on objects changes', done => { + it(`${testName}Try to subscribe on objects changes`, done => { context.adapter.subscribeObjects('*', () => { context.onAdapterObjectChanged = (id, obj) => { - if (id === context.adapterShortName + '.0.' + gid) { + if (id === `${context.adapterShortName}.0.${gid}`) { expect(obj).to.be.ok; expect(obj!.common.name).to.equal('must be set'); context.onAdapterObjectChanged = null; @@ -1002,11 +999,11 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // unsubscribeObjects - it(testName + 'Try to unsubscribe on objects changes', function (done) { + it(`${testName}Try to unsubscribe on objects changes`, function (done) { this.timeout(3_000); context.adapter.unsubscribeObjects('*', () => { context.onAdapterObjectChanged = function (id, obj) { - if (id === context.adapterShortName + '.0.' + gid) { + if (id === `${context.adapterShortName}.0.${gid}`) { expect(obj).to.be.ok; expect(obj).to.be.not.ok; } @@ -1037,10 +1034,10 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // subscribeForeignObjects - it(testName + 'Try to subscribe on foreign objects changes', function (done) { - context.adapter.subscribeForeignObjects(context.adapterShortName + 'f.*', () => { + it(`${testName}Try to subscribe on foreign objects changes`, function (done) { + context.adapter.subscribeForeignObjects(`${context.adapterShortName}f.*`, () => { context.onAdapterObjectChanged = function (id, obj) { - if (id === context.adapterShortName + 'f.0.' + gid) { + if (id === `${context.adapterShortName}f.0.${gid}`) { expect(obj).to.be.ok; expect(obj!.common.name).to.equal('must be set'); context.onAdapterObjectChanged = null; @@ -1048,7 +1045,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont } }; context.adapter.setForeignObject( - context.adapterShortName + 'f.0.' + gid, + `${context.adapterShortName}f.0.${gid}`, { common: { type: 'string', @@ -1070,7 +1067,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // check proteciton for subscribeForeignObjects - it(testName + 'Check if protectedNative is protected in subscribeForeignObjects', function (done) { + it(`${testName}Check if protectedNative is protected in subscribeForeignObjects`, function (done) { context.adapter.subscribeForeignObjects('system.adapter.tesla.0', () => { context.onAdapterObjectChanged = function (id, obj) { if (id === 'system.adapter.tesla.0') { @@ -1116,11 +1113,11 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'Check if own protectedNative is available in subscribeForeignObjects', function (done) { + it(`${testName}Check if own protectedNative is available in subscribeForeignObjects`, function (done) { // If own adapter, protectedNative has to be available - context.adapter.subscribeForeignObjects('system.adapter.' + context.adapterShortName + '.0', () => { + context.adapter.subscribeForeignObjects(`system.adapter.${context.adapterShortName}.0`, () => { context.onAdapterObjectChanged = (id, obj) => { - if (id === 'system.adapter.' + context.adapterShortName + '.0') { + if (id === `system.adapter.${context.adapterShortName}.0`) { expect(obj).to.be.ok; expect(obj!.common.name).to.equal('tesla'); expect(obj!.native).to.be.ok; @@ -1128,13 +1125,13 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(obj!.native.model).equal('S P85D'); expect(obj!.native.username).to.equal('tesla'); expect(obj!.native.password).to.equal('winning'); - expect(obj!._id).equal('system.adapter.' + context.adapterShortName + '.0'); + expect(obj!._id).equal(`system.adapter.${context.adapterShortName}.0`); context.onAdapterObjectChanged = null; done(); } }; context.adapter.setForeignObject( - 'system.adapter.' + context.adapterShortName + '.0', + `system.adapter.${context.adapterShortName}.0`, { type: 'instance', common: { @@ -1164,17 +1161,17 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // unsubscribeForeignObjects - it(testName + 'Try to unsubscribe on foreign objects changes', function (done) { + it(`${testName}Try to unsubscribe on foreign objects changes`, function (done) { this.timeout(3_000); - context.adapter.unsubscribeForeignObjects(context.adapterShortName + 'f.*', () => { + context.adapter.unsubscribeForeignObjects(`${context.adapterShortName}f.*`, () => { context.onAdapterObjectChanged = function (id, obj) { - if (id === context.adapterShortName + 'f.0.' + gid) { + if (id === `${context.adapterShortName}f.0.${gid}`) { expect(obj).to.be.ok; expect(obj).to.be.not.ok; } }; context.adapter.setForeignObject( - context.adapterShortName + 'f.0.' + gid, + `${context.adapterShortName}f.0.${gid}`, { common: { type: 'string', @@ -1199,7 +1196,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // Try to access system configuration - it(testName + 'Try to access system configuration', function (done) { + it(`${testName}Try to access system configuration`, function (done) { this.timeout(3_000); context.adapter.getForeignObject('system.config', (err, obj) => { @@ -1212,7 +1209,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getObject with acls - it(testName + 'Check getObjects with ACLs', function (done) { + it(`${testName}Check getObjects with ACLs`, function (done) { this.timeout(3_000); // create testf.0.myTestObject @@ -1292,7 +1289,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(err).to.be.null; context.adapter.setForeignObject( - context.adapterShortName + 'f.0.' + gid, + `${context.adapterShortName}f.0.${gid}`, { type: 'state', common: { @@ -1321,13 +1318,13 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(err).to.be.null; context.objects.getObject( - context.adapterShortName + 'f.0.' + gid, + `${context.adapterShortName}f.0.${gid}`, { user: 'system.user.write-only' }, function (err, obj) { expect(err).to.be.not.ok; expect(obj).to.be.ok; expect(obj!.native).to.be.ok; - expect(obj!._id).equal(context.adapterShortName + 'f.0.' + gid); + expect(obj!._id).equal(`${context.adapterShortName}f.0.${gid}`); expect(obj!.common.name).equal('test1'); expect(obj!.type).equal('state'); //expect(obj.acl).to.be.ok; @@ -1343,7 +1340,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // should use def as default state value - it(testName + 'Check setObject state with def', async () => { + it(`${testName}Check setObject state with def`, async () => { await context.adapter.setObjectNotExistsAsync('testDefaultVal', { type: 'state', common: { @@ -1364,7 +1361,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // should use def as default state value on extendObject when obj non-existing - it(testName + 'Check extendObject state with def', async function () { + it(`${testName}Check extendObject state with def`, async function () { this.timeout(3_000); let obj = await context.adapter.extendObjectAsync('testDefaultValExtend', { type: 'state', @@ -1410,7 +1407,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // should use def as default state value on extendForeignObject when obj non-existing - it(testName + 'Check extendForeignObject state with def', async () => { + it(`${testName}Check extendForeignObject state with def`, async () => { let obj = await context.adapter.extendForeignObjectAsync('foreign.0.testDefaultValExtend', { type: 'state', common: { @@ -1454,7 +1451,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(state!.ack).to.equal(true); }); - it(testName + 'Check extendForeignObject with preserve option', async () => { + it(`${testName}Check extendForeignObject with preserve option`, async () => { const obj = await context.adapter.extendForeignObjectAsync('foreign.0.testExtendPreserve', { type: 'state', common: { @@ -1615,7 +1612,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // test that real errors of methods promisified via tools.promisify are propagated, can be adapted to a more generic test - it(testName + 'Check that crashes of promisified methods are propagated', function () { + it(`${testName}Check that crashes of promisified methods are propagated`, function () { return expect( context.adapter.extendObjectAsync('testDefaultValExtend', { type: 'state', @@ -1632,7 +1629,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont ); }); - it(testName + 'Should check object existence', async () => { + it(`${testName}Should check object existence`, async () => { const id = 'objectExistenceCheckAdapter'; // object should not exist let exists = await context.adapter.objectExists(id); @@ -1650,7 +1647,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(exists).to.be.true; }); - it(testName + 'Should check foreign object existence', async () => { + it(`${testName}Should check foreign object existence`, async () => { const id = `${context.adapterShortName}.0.objectForeignExistenceCheckAdapter`; // object should not exist let exists = await context.adapter.foreignObjectExists(id); @@ -1669,7 +1666,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // files - it(testName + 'Should check file existence', async () => { + it(`${testName}Should check file existence`, async () => { // create meta object await context.objects.setObjectAsync('fileTest.0', { type: 'meta', @@ -1688,7 +1685,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // write file meta check - it(testName + 'Should not write file w/o meta', async () => { + it(`${testName}Should not write file w/o meta`, async () => { try { await context.adapter.writeFileAsync('nonExisting.0', 'test.txt', '...'); } catch (e) { diff --git a/packages/controller/test/lib/testStates.ts b/packages/controller/test/lib/testStates.ts index 8bb23caab..cdd7a4a97 100644 --- a/packages/controller/test/lib/testStates.ts +++ b/packages/controller/test/lib/testStates.ts @@ -1,11 +1,11 @@ import type { TestContext } from '../_Types.js'; export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, context: TestContext): void { - const testName = context.name + ' ' + context.adapterShortName + ' adapter: '; + const testName = `${context.name} ${context.adapterShortName} adapter: `; const gid = 'testStates'; // setState - it(testName + 'Set local state', function (done) { + it(`${testName}Set local state`, function (done) { this.timeout(3_000); context.adapter.setObject( gid, @@ -25,13 +25,13 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont function (err) { expect(err).to.be.null; - context.states.getState(context.adapterShortName + '.0.' + gid, function (err, _state) { + context.states.getState(`${context.adapterShortName}.0.${gid}`, function (err, _state) { expect(err).to.be.null; context.adapter.setState(gid, 1, function (err) { expect(err).to.be.not.ok; - context.states.getState(context.adapterShortName + '.0.' + gid, function (err, state) { + context.states.getState(`${context.adapterShortName}.0.${gid}`, function (err, state) { expect(err).to.be.null; expect(state).to.be.ok; expect(state!.val).to.equal(1); @@ -40,7 +40,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont context.adapter.setState(gid, 2, true, function (err) { expect(err).to.be.not.ok; - context.states.getState(context.adapterShortName + '.0.' + gid, function (err, state) { + context.states.getState(`${context.adapterShortName}.0.${gid}`, function (err, state) { expect(err).to.be.null; expect(state).to.be.ok; expect(state!.val).to.equal(2); @@ -50,7 +50,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(err).to.be.not.ok; context.states.getState( - context.adapterShortName + '.0.' + gid, + `${context.adapterShortName}.0.${gid}`, function (err, state) { expect(err).to.be.null; expect(state).to.be.ok; @@ -61,7 +61,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(err).to.be.not.ok; context.states.getState( - context.adapterShortName + '.0.' + gid, + `${context.adapterShortName}.0.${gid}`, function (err, state) { expect(err).to.be.null; expect(state).to.be.ok; @@ -75,7 +75,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(err).to.be.not.ok; context.states.getState( - context.adapterShortName + '.0.' + gid, + `${context.adapterShortName}.0.${gid}`, function (err, state) { expect(err).to.be.null; expect(state).to.be.ok; @@ -102,19 +102,19 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getState - it(testName + 'Get local state', function (done) { + it(`${testName}Get local state`, function (done) { this.timeout(3_000); context.adapter.getState(gid, function (err) { expect(err).to.be.not.ok; - context.adapter.getState(context.adapterShortName + '.0.' + gid, function (err, state) { + context.adapter.getState(`${context.adapterShortName}.0.${gid}`, function (err, state) { expect(err).to.be.null; expect(state).to.be.ok; expect(state!.val).to.equal(3); expect(state!.ack).to.equal(true); // ask for non-existing state - context.adapter.getState(gid + '6', function (err, state) { + context.adapter.getState(`${gid}6`, function (err, state) { expect(err).to.be.not.ok; expect(state).to.be.null; done(); @@ -124,14 +124,14 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getStates - it(testName + 'Get local states', function (done) { + it(`${testName}Get local states`, function (done) { this.timeout(3_000); context.adapter.getStates('*', function (err, states) { expect(err).to.be.not.ok; expect(states).to.be.an('object'); - expect(states![context.adapterShortName + '.0.' + gid]).to.be.an('object'); - expect(states![context.adapterShortName + '.0.' + gid].val).to.equal(3); - expect(states![context.adapterShortName + '.0.' + gid].ack).equal(true); + expect(states![`${context.adapterShortName}.0.${gid}`]).to.be.an('object'); + expect(states![`${context.adapterShortName}.0.${gid}`].val).to.equal(3); + expect(states![`${context.adapterShortName}.0.${gid}`].ack).equal(true); context.adapter.getStates('abc*', function (err, states) { expect(err).to.be.not.ok; @@ -140,12 +140,12 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // no states should match expect(Object.keys(states!).length).to.be.equal(0); - context.adapter.getStates(gid.substring(0, gid.length - 2) + '*', function (err, states) { + context.adapter.getStates(`${gid.substring(0, gid.length - 2)}*`, function (err, states) { expect(err).to.be.not.ok; expect(states).to.be.an('object'); - expect(states![context.adapterShortName + '.0.' + gid]).to.be.an('object'); - expect(states![context.adapterShortName + '.0.' + gid].val).to.equal(3); - expect(states![context.adapterShortName + '.0.' + gid].ack).equal(true); + expect(states![`${context.adapterShortName}.0.${gid}`]).to.be.an('object'); + expect(states![`${context.adapterShortName}.0.${gid}`].val).to.equal(3); + expect(states![`${context.adapterShortName}.0.${gid}`].ack).equal(true); done(); }); @@ -154,7 +154,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // delState - it(testName + 'Delete local state', function (done) { + it(`${testName}Delete local state`, function (done) { this.timeout(3_000); context.adapter.delState(gid, function (err) { expect(err).to.be.not.ok; @@ -173,7 +173,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // setStateChanged - it(testName + 'Set local state if changed', function (done) { + it(`${testName}Set local state if changed`, function (done) { // create object context.adapter.setObject( gid, @@ -198,20 +198,20 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont context.adapter.setStateChanged(gid, 1, function (err, id, notChanged) { expect(err).to.be.not.ok; // redis do not return ID - expect(id).to.be.equal(context.adapterShortName + '.0.' + gid); + expect(id).to.be.equal(`${context.adapterShortName}.0.${gid}`); expect(notChanged).to.be.true; - context.states.getState(context.adapterShortName + '.0.' + gid, function (err, state) { + context.states.getState(`${context.adapterShortName}.0.${gid}`, function (err, state) { expect(err).to.be.not.ok; expect(state).to.be.ok; expect(state!.ts).to.be.equal(ts); context.adapter.setStateChanged(gid, 1, true, function (err, id, notChanged) { expect(err).to.be.not.ok; - expect(id).to.be.equal(context.adapterShortName + '.0.' + gid); + expect(id).to.be.equal(`${context.adapterShortName}.0.${gid}`); expect(notChanged).to.be.false; - context.states.getState(context.adapterShortName + '.0.' + gid, function (err, state) { + context.states.getState(`${context.adapterShortName}.0.${gid}`, function (err, state) { expect(err).to.be.not.ok; expect(state).to.be.ok; expect(state!.ack).to.be.true; @@ -227,9 +227,9 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // subscribeStates - it(testName + 'Test subscribe local states', function (done) { + it(`${testName}Test subscribe local states`, function (done) { this.timeout(3_000); - const sGid = gid + '5'; + const sGid = `${gid}5`; context.adapter.setObject( sGid, @@ -249,11 +249,11 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont function (err) { expect(err).to.be.null; - context.states.setState(context.adapterShortName + '.0.' + sGid, 9, function (err) { + context.states.setState(`${context.adapterShortName}.0.${sGid}`, 9, function (err) { expect(err).to.be.not.ok; context.onAdapterStateChanged = function (id, state) { - if (id === context.adapterShortName + '.0.' + sGid) { + if (id === `${context.adapterShortName}.0.${sGid}`) { expect(state).to.be.ok; expect(state!.val).to.equal(10); context.onAdapterStateChanged = null; @@ -262,7 +262,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }; context.adapter.subscribeStates('*', function () { - context.states.setState(context.adapterShortName + '.0.' + sGid, 10, function (err) { + context.states.setState(`${context.adapterShortName}.0.${sGid}`, 10, function (err) { expect(err).to.be.not.ok; }); }); @@ -271,7 +271,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont ); }); - it(testName + 'Test subscribe local states on array', async () => { + it(`${testName}Test subscribe local states on array`, async () => { const sGid = `${gid}subscribeArray`; const testVal = 50; @@ -306,22 +306,22 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // unsubscribeStates - it(testName + 'Test unsubscribe local states', function (done) { + it(`${testName}Test unsubscribe local states`, function (done) { this.timeout(3_000); - const sGid = gid + '5'; + const sGid = `${gid}5`; context.onAdapterStateChanged = function (id, state) { - if (id === context.adapterShortName + '.0.' + sGid) { + if (id === `${context.adapterShortName}.0.${sGid}`) { expect(state).to.be.ok; expect(state!.val).to.equal(9); } }; - context.states.setState(context.adapterShortName + '.0.' + sGid, 9, function (err) { + context.states.setState(`${context.adapterShortName}.0.${sGid}`, 9, function (err) { expect(err).to.be.not.ok; context.adapter.unsubscribeStates('*', function () { - context.states.setState(context.adapterShortName + '.0.' + sGid, 10, function (err) { + context.states.setState(`${context.adapterShortName}.0.${sGid}`, 10, function (err) { expect(err).to.be.not.ok; }); setTimeout(function () { @@ -334,9 +334,9 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont // ------------------------------------------------------------------------------------- // setForeignState - it(testName + 'Set foreign state', function (done) { + it(`${testName}Set foreign state`, function (done) { this.timeout(3_000); - const fGid = context.adapterShortName + '1.0.' + gid; + const fGid = `${context.adapterShortName}1.0.${gid}`; context.objects.setObject( fGid, { @@ -397,9 +397,9 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // setForeignState with acl all - it(testName + 'Set foreign state with acl', function (done) { + it(`${testName}Set foreign state with acl`, function (done) { this.timeout(3_000); - const fGid = context.adapterShortName + '3.0.' + gid; + const fGid = `${context.adapterShortName}3.0.${gid}`; context.adapter.setForeignObject( 'system.group.writer2', { @@ -539,9 +539,9 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // setForeignState with acl failure - it(testName + 'Set foreign state with acl failure', function (done) { + it(`${testName}Set foreign state with acl failure`, function (done) { this.timeout(3_000); - const fGid = context.adapterShortName + '3.1.' + gid; + const fGid = `${context.adapterShortName}3.1.${gid}`; context.objects.setObject( fGid, @@ -580,9 +580,9 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // setForeignState with acl write only - it(testName + 'Set foreign state with acl write only', function (done) { + it(`${testName}Set foreign state with acl write only`, function (done) { this.timeout(3_000); - const fGid = context.adapterShortName + '3.0.' + gid; + const fGid = `${context.adapterShortName}3.0.${gid}`; context.objects.setObject( fGid, { @@ -633,9 +633,9 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // setForeignStateChanged - it(testName + 'Set foreign state if changed', function (done) { + it(`${testName}Set foreign state if changed`, function (done) { // create object - const fGid = context.adapterShortName + '1.0.1' + gid; + const fGid = `${context.adapterShortName}1.0.1${gid}`; context.adapter.setForeignObject( fGid, { @@ -688,9 +688,9 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getForeignState - it(testName + 'Get foreign state', function (done) { + it(`${testName}Get foreign state`, function (done) { this.timeout(3_000); - const fGid = context.adapterShortName + '1.0.' + gid; + const fGid = `${context.adapterShortName}1.0.${gid}`; context.adapter.getForeignState(fGid, function (err, state) { expect(err).to.be.null; expect(state).to.be.ok; @@ -698,7 +698,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(state!.ack).to.equal(true); // ask for non-existing state - context.adapter.getForeignState(fGid + '5', function (err, state) { + context.adapter.getForeignState(`${fGid}5`, function (err, state) { expect(err).to.be.not.ok; expect(state).to.be.null; done(); @@ -707,16 +707,16 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getForeignStates - it(testName + 'Get foreign states', function (done) { + it(`${testName}Get foreign states`, function (done) { this.timeout(3_000); - context.adapter.getForeignStates(context.adapterShortName + '1.0.*', function (err, states) { + context.adapter.getForeignStates(`${context.adapterShortName}1.0.*`, function (err, states) { expect(err).to.be.not.ok; expect(states).to.be.an('object'); - expect(states![context.adapterShortName + '1.0.' + gid]).to.be.ok; - expect(states![context.adapterShortName + '1.0.' + gid].val).to.equal(3); - expect(states![context.adapterShortName + '1.0.' + gid].ack).equal(true); + expect(states![`${context.adapterShortName}1.0.${gid}`]).to.be.ok; + expect(states![`${context.adapterShortName}1.0.${gid}`].val).to.equal(3); + expect(states![`${context.adapterShortName}1.0.${gid}`].ack).equal(true); - context.adapter.getForeignStates(context.adapterShortName + '1.0.abc*', function (err, states) { + context.adapter.getForeignStates(`${context.adapterShortName}1.0.abc*`, function (err, states) { expect(err).to.be.not.ok; expect(states).to.be.an('object'); @@ -724,13 +724,13 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(Object.keys(states!).length).to.be.equal(0); context.adapter.getForeignStates( - context.adapterShortName + '1.0.' + gid.substring(0, gid.length - 2) + '*', + `${context.adapterShortName}1.0.${gid.substring(0, gid.length - 2)}*`, function (err, states) { expect(err).to.be.not.ok; expect(states).to.be.an('object'); - expect(states![context.adapterShortName + '1.0.' + gid]).to.be.ok; - expect(states![context.adapterShortName + '1.0.' + gid].val).to.equal(3); - expect(states![context.adapterShortName + '1.0.' + gid].ack).equal(true); + expect(states![`${context.adapterShortName}1.0.${gid}`]).to.be.ok; + expect(states![`${context.adapterShortName}1.0.${gid}`].val).to.equal(3); + expect(states![`${context.adapterShortName}1.0.${gid}`].ack).equal(true); done(); }, @@ -740,16 +740,16 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // delForeignState - it(testName + 'Delete foreign state', function (done) { + it(`${testName}Delete foreign state`, function (done) { this.timeout(3_000); - context.adapter.delForeignState(context.adapterShortName + '1.0.' + gid, function (err) { + context.adapter.delForeignState(`${context.adapterShortName}1.0.${gid}`, function (err) { expect(err).to.be.not.ok; - context.adapter.getForeignState(context.adapterShortName + '1.0.' + gid, function (err, state) { + context.adapter.getForeignState(`${context.adapterShortName}1.0.${gid}`, function (err, state) { expect(err).to.be.not.ok; expect(state).to.be.not.ok; - context.adapter.delForeignState(context.adapterShortName + '1.0.' + gid, function (err) { + context.adapter.delForeignState(`${context.adapterShortName}1.0.${gid}`, function (err) { expect(err).to.be.not.ok; done(); @@ -759,7 +759,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // get foreign system state - it(testName + 'Get System State', function (done) { + it(`${testName}Get System State`, function (done) { this.timeout(3_000); context.adapter.getForeignState('system.adapter.test.0.memRss', (err, state) => { @@ -771,7 +771,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // subscribeForeignStates - it(testName + 'Test subscribe foreign states', function (done) { + it(`${testName}Test subscribe foreign states`, function (done) { this.timeout(3_000); const sGid = `${context.adapterShortName}2.0.${gid}6`; @@ -805,7 +805,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont } }; - context.adapter.subscribeForeignStates(context.adapterShortName + '2.0.*', function () { + context.adapter.subscribeForeignStates(`${context.adapterShortName}2.0.*`, function () { context.states.setState(sGid, 10, function (err) { expect(err).to.be.not.ok; }); @@ -816,7 +816,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // subscribeForeignStates with array - it(testName + 'Test subscribe foreign states with array', async () => { + it(`${testName}Test subscribe foreign states with array`, async () => { const stateIds = [ `${context.adapterShortName}3.0.${gid}76`, `${context.adapterShortName}3.0.${gid}77`, @@ -867,9 +867,9 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }).timeout(3_000); // unsubscribeForeignStates - it(testName + 'Test unsubscribe foreign states', function (done) { + it(`${testName}Test unsubscribe foreign states`, function (done) { this.timeout(3_000); - const sGid = context.adapterShortName + '2.0.' + gid + '6'; + const sGid = `${context.adapterShortName}2.0.${gid}6`; context.onAdapterStateChanged = function (id, state) { if (id === sGid) { @@ -882,7 +882,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont context.states.setState(sGid, 9, err => { expect(err).to.be.not.ok; - context.adapter.unsubscribeForeignStates(context.adapterShortName + '2.0.*', () => + context.adapter.unsubscribeForeignStates(`${context.adapterShortName}2.0.*`, () => context.states.setState(sGid, 10, err => { expect(err).to.be.not.ok; setTimeout(() => { @@ -895,10 +895,10 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); // getState - it(testName + 'Set/Get local state wit expiry', function (done) { + it(`${testName}Set/Get local state wit expiry`, function (done) { this.timeout(10000); - const eGid = context.adapterShortName + '.0.' + gid + '_expire'; + const eGid = `${context.adapterShortName}.0.${gid}_expire`; context.adapter.setForeignObject( eGid, { @@ -926,10 +926,10 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont } }; - context.adapter.setState(gid + '_expire', { val: 1, expire: 4, ack: true }, function (err) { + context.adapter.setState(`${gid}_expire`, { val: 1, expire: 4, ack: true }, function (err) { expect(err).to.be.not.ok; - context.adapter.getState(gid + '_expire', function (err, state) { + context.adapter.getState(`${gid}_expire`, function (err, state) { // read directly, should work expect(err).to.be.null; expect(state).to.be.ok; @@ -939,7 +939,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont context.adapter.subscribeForeignStates(eGid, function () { setTimeout(() => { // read after timeout, should not work - context.adapter.getState(gid + '_expire', function (err, state) { + context.adapter.getState(`${gid}_expire`, function (err, state) { expect(err).to.be.not.ok; expect(state).to.be.null; expect(published).to.be.true; @@ -953,7 +953,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont ); }); - it(testName + 'Should respect from', done => { + it(`${testName}Should respect from`, done => { // we set a state and set a custom from property context.adapter.setState(`${gid}stateWithFrom`, { val: 1, from: 'Paris with love' }, err => { expect(err).to.be.not.ok; @@ -965,7 +965,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); }); - it(testName + 'Should use default from', done => { + it(`${testName}Should use default from`, done => { // we set a state without providing `from` property context.adapter.setState(`${gid}stateWithFrom`, { val: 1 }, err => { expect(err).to.be.not.ok; @@ -998,7 +998,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont }); */ - it(testName + 'Should also set object id', async () => { + it(`${testName}Should also set object id`, async () => { // set state with device, channel, state it is supported (legacy) but not recommended, so pass as any await context.adapter.setStateAsync({ device: `${gid}derGeraet`, channel: 'donau', state: 'awake' } as any, { val: 5, @@ -1015,7 +1015,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont return Promise.resolve(); }); - it(testName + 'Should round to next 5', async () => { + it(`${testName}Should round to next 5`, async () => { // we test the step attribute here await context.adapter.setObjectAsync(`${gid}step`, { common: { @@ -1045,7 +1045,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont expect(state!.val).to.equal(-20); }); - it(testName + 'Should throw on invalid subscribe', async () => { + it(`${testName}Should throw on invalid subscribe`, async () => { expect(context.adapter.subscribeStatesAsync('hm-rpc.0.§.test')).to.be.rejectedWith( /is not a valid ID pattern/g, 'Should throw on invalid pattern', @@ -1053,7 +1053,7 @@ export function register(it: Mocha.TestFunction, expect: Chai.ExpectStatic, cont await context.adapter.subscribeStatesAsync('*hm-rpc.0._.**test/*'); }); - it(testName + 'sendTo with timeout should reject in time', () => { + it(`${testName}sendTo with timeout should reject in time`, () => { return expect( context.adapter.sendToAsync('testInstance.0', 'test', {}, { timeout: 500 }), ).to.be.eventually.rejectedWith('Timeout exceeded', 'Should have thrown after timeout is over'); diff --git a/packages/controller/test/redis-sentinel/testAdapterStatesRedis.ts b/packages/controller/test/redis-sentinel/testAdapterStatesRedis.ts index 5e3c5c0ad..5f2180e98 100644 --- a/packages/controller/test/redis-sentinel/testAdapterStatesRedis.ts +++ b/packages/controller/test/redis-sentinel/testAdapterStatesRedis.ts @@ -3,9 +3,9 @@ import fs from 'node:fs'; import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); -const dataDir = thisDir + '/../../tmp/data-redis'; +const dataDir = `${thisDir}/../../tmp/data-redis`; const statesConfig = { options: { @@ -18,8 +18,8 @@ const statesConfig = { port: [26380, 26381, 26382], }; -if (!fs.existsSync(thisDir + '/../tmp')) { - fs.mkdirSync(thisDir + '/../tmp'); +if (!fs.existsSync(`${thisDir}/../tmp`)) { + fs.mkdirSync(`${thisDir}/../tmp`); } const objectsConfig = { diff --git a/packages/controller/test/redis-sentinel/testStatesRedis.ts b/packages/controller/test/redis-sentinel/testStatesRedis.ts index 5762dc0f6..454e553e0 100644 --- a/packages/controller/test/redis-sentinel/testStatesRedis.ts +++ b/packages/controller/test/redis-sentinel/testStatesRedis.ts @@ -7,7 +7,7 @@ import type { Client as StateRedisClient } from '@iobroker/db-states-redis'; import { startController, stopController } from '../lib/setup4controller.js'; import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); const dataDir = path.join(thisDir, '..', '..', 'tmp', 'data'); let objects: ObjectsInRedisClient | null = null; @@ -38,7 +38,7 @@ describe('States-Redis-Sentinel: Test states', function () { objects: { dataDir: dataDir, onChange: (id: string, _obj: ioBroker.AnyObject) => { - console.log('object changed. ' + id); + console.log(`object changed. ${id}`); }, }, states: { @@ -46,7 +46,7 @@ describe('States-Redis-Sentinel: Test states', function () { host: ['127.0.0.1', '127.0.0.1', '127.0.0.1'], port: [26380, 26381, 26382], onChange: (id: string, state: ioBroker.State) => { - console.log('Redis-state-Sentinel changed. ' + id); + console.log(`Redis-state-Sentinel changed. ${id}`); if (onStatesChanged) { onStatesChanged(id, state); } @@ -101,7 +101,7 @@ describe('States-Redis-Sentinel: Test states', function () { const testID = 'testObject.0.test1'; onStatesChanged = (id, state) => { if (id === testID) { - console.log('Receive state value: ' + state!.val); + console.log(`Receive state value: ${state!.val}`); expect(state).to.be.ok; if (state!.val !== sendCounter - 1) { // timing special case for failover ... sometimes we loose some resubmits @@ -120,7 +120,7 @@ describe('States-Redis-Sentinel: Test states', function () { expect(state!.ack).to.be.false; expect(state!.ts).to.be.ok; expect(state!.q).to.be.equal(0); - console.log('Get state: ' + state!.val); + console.log(`Get state: ${state!.val}`); if (receiveCounter === 30) { // eslint-disable-next-line @typescript-eslint/no-use-before-define @@ -143,7 +143,7 @@ describe('States-Redis-Sentinel: Test states', function () { }; const stateInterval = setInterval(() => { - console.log('Set state: ' + sendCounter); + console.log(`Set state: ${sendCounter}`); states!.setState(testID, sendCounter++, function (err) { expect(err).to.be.not.ok; }); diff --git a/packages/controller/test/redis-socket/testAdapterStatesRedis.ts b/packages/controller/test/redis-socket/testAdapterStatesRedis.ts index 03503a8fe..8db316cfe 100644 --- a/packages/controller/test/redis-socket/testAdapterStatesRedis.ts +++ b/packages/controller/test/redis-socket/testAdapterStatesRedis.ts @@ -1,9 +1,9 @@ import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); import testAdapter from './../lib/testAdapter.js'; -const dataDir = thisDir + '/../../tmp/data-redis'; +const dataDir = `${thisDir}/../../tmp/data-redis`; import fs from 'node:fs'; const statesConfig = { @@ -17,8 +17,8 @@ const statesConfig = { port: 0, }; -if (!fs.existsSync(thisDir + '/../tmp')) { - fs.mkdirSync(thisDir + '/../tmp'); +if (!fs.existsSync(`${thisDir}/../tmp`)) { + fs.mkdirSync(`${thisDir}/../tmp`); } const objectsConfig = { diff --git a/packages/controller/test/redis-socket/testStatesRedis.ts b/packages/controller/test/redis-socket/testStatesRedis.ts index f9659a1e5..ac30bd416 100644 --- a/packages/controller/test/redis-socket/testStatesRedis.ts +++ b/packages/controller/test/redis-socket/testStatesRedis.ts @@ -6,7 +6,7 @@ import type { Client as ObjectsInRedisClient } from '@iobroker/db-objects-redis' import type { Client as StateRedisClient } from '@iobroker/db-states-redis'; import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); const dataDir = path.join(thisDir, '..', '..', 'tmp', 'data'); let objects: ObjectsInRedisClient | null = null; diff --git a/packages/controller/test/testAdapterObjectsInFile.ts b/packages/controller/test/testAdapterObjectsInFile.ts index 5c9cae086..c1b5ca78d 100644 --- a/packages/controller/test/testAdapterObjectsInFile.ts +++ b/packages/controller/test/testAdapterObjectsInFile.ts @@ -8,7 +8,7 @@ import { register } from './lib/testObjects.js'; import type { TestContext } from './_Types.js'; import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); const context: TestContext = { // @ts-expect-error will be filled before usage @@ -16,21 +16,21 @@ const context: TestContext = { name: textName, }; -describe(textName + ' Test Objects File-Redis', function () { - before(textName + ' Start js-controller', async function () { +describe(`${textName} Test Objects File-Redis`, function () { + before(`${textName} Start js-controller`, async function () { this.timeout(23_000); const { objects: _objects, states: _states } = await startController({ objects: { dataDir: `${thisDir}/../tmp/data`, onChange: function (id: string, _obj: ioBroker.AnyObject) { - console.log('object changed. ' + id); + console.log(`object changed. ${id}`); }, }, states: { dataDir: `${thisDir}/../tmp/data`, onChange: function (id: string, _state: ioBroker.State) { - console.log('state changed. ' + id); + console.log(`state changed. ${id}`); }, }, }); @@ -45,7 +45,7 @@ describe(textName + ' Test Objects File-Redis', function () { register(it, expect, context); - after(textName + ' Stop js-controller', async function () { + after(`${textName} Stop js-controller`, async function () { this.timeout(5_000); await stopController(); await new Promise(resolve => { diff --git a/packages/controller/test/testAdapterObjectsInRedis.ts b/packages/controller/test/testAdapterObjectsInRedis.ts index 2db8b2fc5..59e5c9e28 100644 --- a/packages/controller/test/testAdapterObjectsInRedis.ts +++ b/packages/controller/test/testAdapterObjectsInRedis.ts @@ -10,19 +10,19 @@ import { register } from './lib/testObjects.js'; import * as url from 'node:url'; import type { TestContext } from './_Types.js'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); const context: TestContext = { // @ts-expect-error will be filled in time objects: null, name: textName, }; -if (!fs.existsSync(thisDir + '/../tmp')) { - fs.mkdirSync(thisDir + '/../tmp'); +if (!fs.existsSync(`${thisDir}/../tmp`)) { + fs.mkdirSync(`${thisDir}/../tmp`); } const objectsConfig = { - dataDir: thisDir + '/../tmp/data', + dataDir: `${thisDir}/../tmp/data`, type: 'redis', host: '127.0.0.1', port: 6379, @@ -36,16 +36,16 @@ const objectsConfig = { }, }; -describe(textName + 'Test Objects Redis', function () { - before(textName + 'Start js-controller', async function () { +describe(`${textName}Test Objects Redis`, function () { + before(`${textName}Start js-controller`, async function () { this.timeout(23_000); const { objects: _objects, states: _states } = await startController({ objects: objectsConfig, states: { - dataDir: thisDir + '/../tmp/data', + dataDir: `${thisDir}/../tmp/data`, onChange: (id: string, _state: ioBroker.State) => { - console.log('state changed. ' + id); + console.log(`state changed. ${id}`); }, }, }); @@ -60,7 +60,7 @@ describe(textName + 'Test Objects Redis', function () { register(it, expect, context); - after(textName + 'Stop js-controller', async function () { + after(`${textName}Stop js-controller`, async function () { this.timeout(5_000); await stopController(); await new Promise(resolve => { diff --git a/packages/controller/test/testAdapterStatesInFile.ts b/packages/controller/test/testAdapterStatesInFile.ts index 9a7dfacde..3692c2264 100644 --- a/packages/controller/test/testAdapterStatesInFile.ts +++ b/packages/controller/test/testAdapterStatesInFile.ts @@ -1,7 +1,7 @@ import path from 'node:path'; import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); import testAdapter from './lib/testAdapter.js'; const dataDir = path.join(thisDir, '..', 'tmp', 'data'); diff --git a/packages/controller/test/testAdapterStatesRedis.ts b/packages/controller/test/testAdapterStatesRedis.ts index e53940ca4..e1c00ff01 100644 --- a/packages/controller/test/testAdapterStatesRedis.ts +++ b/packages/controller/test/testAdapterStatesRedis.ts @@ -1,7 +1,7 @@ import testAdapter from './lib/testAdapter.js'; import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); const statesConfig = { options: { @@ -15,7 +15,7 @@ const statesConfig = { }; const objectsConfig = { - dataDir: thisDir + '/../tmp/data', + dataDir: `${thisDir}/../tmp/data`, options: { auth_pass: null, retry_max_delay: 100, diff --git a/packages/controller/test/testInternalUtilities.ts b/packages/controller/test/testInternalUtilities.ts index afd2342e1..b3e677400 100644 --- a/packages/controller/test/testInternalUtilities.ts +++ b/packages/controller/test/testInternalUtilities.ts @@ -17,13 +17,13 @@ describe('test internal helpers', () => { objects: { dataDir: `${thisDir}/../tmp/data`, onChange: function (id: string, _obj: ioBroker.AnyObject) { - console.log('object changed. ' + id); + console.log(`object changed. ${id}`); }, }, states: { dataDir: `${thisDir}/../tmp/data`, onChange: function (id: string, _state: ioBroker.State) { - console.log('state changed. ' + id); + console.log(`state changed. ${id}`); }, }, }); diff --git a/packages/controller/test/testPackageFiles.ts b/packages/controller/test/testPackageFiles.ts index 59043913b..543fb10ba 100644 --- a/packages/controller/test/testPackageFiles.ts +++ b/packages/controller/test/testPackageFiles.ts @@ -3,16 +3,16 @@ import fs from 'node:fs'; import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); describe('Test package.json and io-package.json', () => { it('Test package files', done => { console.log(); - const fileContentIOPackage = fs.readFileSync(thisDir + '/../io-package.json', 'utf8'); + const fileContentIOPackage = fs.readFileSync(`${thisDir}/../io-package.json`, 'utf8'); const ioPackage = JSON.parse(fileContentIOPackage); - const fileContentNPMPackage = fs.readFileSync(thisDir + '/../package.json', 'utf8'); + const fileContentNPMPackage = fs.readFileSync(`${thisDir}/../package.json`, 'utf8'); const npmPackage = JSON.parse(fileContentNPMPackage); expect(ioPackage).to.be.an('object'); @@ -64,7 +64,7 @@ describe('Test package.json and io-package.json', () => { console.log(); } expect( - fs.existsSync(thisDir + '/../README.md'), + fs.existsSync(`${thisDir}/../README.md`), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.', ).to.be.true; if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') { @@ -86,22 +86,22 @@ describe('Test package.json and io-package.json', () => { if (!ioPackage.common.controller && !ioPackage.common.onlyWWW && !ioPackage.common.noConfig) { if ( !ioPackage.common.materialize || - !fs.existsSync(thisDir + '/../admin/index_m.html') || - !fs.existsSync(thisDir + '/../gulpfile.js') + !fs.existsSync(`${thisDir}/../admin/index_m.html`) || + !fs.existsSync(`${thisDir}/../gulpfile.js`) ) { console.log('WARNING: Admin3 support is missing! Please add it'); console.log(); } if (ioPackage.common.materialize) { expect( - fs.existsSync(thisDir + '/../admin/index_m.html'), + fs.existsSync(`${thisDir}/../admin/index_m.html`), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!', ).to.be.true; } } - const licenseFileExists = fs.existsSync(thisDir + '/../LICENSE'); - const fileContentReadme = fs.readFileSync(thisDir + '/../README.md', 'utf8'); + const licenseFileExists = fs.existsSync(`${thisDir}/../LICENSE`); + const fileContentReadme = fs.readFileSync(`${thisDir}/../README.md`, 'utf8'); if (fileContentReadme.indexOf('## Changelog') === -1) { console.log('Warning: The README.md should have a section ## Changelog'); console.log(); diff --git a/packages/controller/test/testStates.ts b/packages/controller/test/testStates.ts index 151383522..b702ad906 100644 --- a/packages/controller/test/testStates.ts +++ b/packages/controller/test/testStates.ts @@ -10,21 +10,21 @@ let states: StateRedisClient | null = null; let onStatesChanged: ioBroker.StateChangeHandler | null = null; import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); const dataDir = path.join(thisDir, '..', 'tmp', 'data'); function cleanDbs(): void { - if (fs.existsSync(dataDir + '/objects.json')) { - fs.unlinkSync(dataDir + '/objects.json'); + if (fs.existsSync(`${dataDir}/objects.json`)) { + fs.unlinkSync(`${dataDir}/objects.json`); } - if (fs.existsSync(dataDir + '/objects.json.bak')) { - fs.unlinkSync(dataDir + '/objects.json.bak'); + if (fs.existsSync(`${dataDir}/objects.json.bak`)) { + fs.unlinkSync(`${dataDir}/objects.json.bak`); } - if (fs.existsSync(dataDir + '/states.json')) { - fs.unlinkSync(dataDir + '/states.json'); + if (fs.existsSync(`${dataDir}/states.json`)) { + fs.unlinkSync(`${dataDir}/states.json`); } - if (fs.existsSync(dataDir + '/states.json.bak')) { - fs.unlinkSync(dataDir + '/states.json.bak'); + if (fs.existsSync(`${dataDir}/states.json.bak`)) { + fs.unlinkSync(`${dataDir}/states.json.bak`); } } @@ -36,12 +36,12 @@ describe('States: Test states in File-Redis', function () { const { objects: _objects, states: _states } = await startController({ objects: { dataDir: dataDir, - onChange: (id: string, _obj: ioBroker.AnyObject) => console.log('object changed. ' + id), + onChange: (id: string, _obj: ioBroker.AnyObject) => console.log(`object changed. ${id}`), }, states: { dataDir: dataDir, onChange: (id: string, state: ioBroker.State) => { - console.log('state changed. ' + id); + console.log(`state changed. ${id}`); onStatesChanged && onStatesChanged(id, state); }, }, diff --git a/packages/controller/test/testStatesRedis.ts b/packages/controller/test/testStatesRedis.ts index 77e42a94d..bb5d922fe 100644 --- a/packages/controller/test/testStatesRedis.ts +++ b/packages/controller/test/testStatesRedis.ts @@ -9,21 +9,21 @@ let states: StateRedisClient | null = null; let onStatesChanged: ioBroker.StateChangeHandler | null = null; import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); const dataDir = path.join(thisDir, '..', 'tmp', 'data'); function cleanDbs(): void { - if (fs.existsSync(dataDir + '/objects.json')) { - fs.unlinkSync(dataDir + '/objects.json'); + if (fs.existsSync(`${dataDir}/objects.json`)) { + fs.unlinkSync(`${dataDir}/objects.json`); } - if (fs.existsSync(dataDir + '/objects.json.bak')) { - fs.unlinkSync(dataDir + '/objects.json.bak'); + if (fs.existsSync(`${dataDir}/objects.json.bak`)) { + fs.unlinkSync(`${dataDir}/objects.json.bak`); } - if (fs.existsSync(dataDir + '/states.json')) { - fs.unlinkSync(dataDir + '/states.json'); + if (fs.existsSync(`${dataDir}/states.json`)) { + fs.unlinkSync(`${dataDir}/states.json`); } - if (fs.existsSync(dataDir + '/states.json.bak')) { - fs.unlinkSync(dataDir + '/states.json.bak'); + if (fs.existsSync(`${dataDir}/states.json.bak`)) { + fs.unlinkSync(`${dataDir}/states.json.bak`); } } @@ -35,14 +35,14 @@ describe('States-Redis: Test states in Redis', function () { const { objects: _objects, states: _states } = await startController({ objects: { dataDir: dataDir, - onChange: (id: string, _obj: ioBroker.AnyObject) => console.log('object changed. ' + id), + onChange: (id: string, _obj: ioBroker.AnyObject) => console.log(`object changed. ${id}`), }, states: { type: 'redis', host: '127.0.0.1', port: 6379, onChange: (id: string, state: ioBroker.State) => { - console.log('Redis-state changed. ' + id); + console.log(`Redis-state changed. ${id}`); if (onStatesChanged) { onStatesChanged(id, state); } diff --git a/packages/db-base/src/lib/inMemFileDB.ts b/packages/db-base/src/lib/inMemFileDB.ts index fe1c04097..38ecbc7af 100644 --- a/packages/db-base/src/lib/inMemFileDB.ts +++ b/packages/db-base/src/lib/inMemFileDB.ts @@ -365,7 +365,7 @@ export class InMemoryFileDB { files.sort(); const limit = Date.now() - this.settings.backup.hours * 3600000; - files = files.filter(f => f.endsWith(baseFilename + '.gz')); + files = files.filter(f => f.endsWith(`${baseFilename}.gz`)); while (files.length > this.settings.backup.files) { const file = files.shift(); @@ -389,24 +389,24 @@ export class InMemoryFileDB { getTimeStr(date: number): string { const dateObj = new Date(date); - let text = dateObj.getFullYear().toString() + '-'; + let text = `${dateObj.getFullYear().toString()}-`; let v = dateObj.getMonth() + 1; if (v < 10) { text += '0'; } - text += v.toString() + '-'; + text += `${v.toString()}-`; v = dateObj.getDate(); if (v < 10) { text += '0'; } - text += v.toString() + '_'; + text += `${v.toString()}_`; v = dateObj.getHours(); if (v < 10) { text += '0'; } - text += v.toString() + '-'; + text += `${v.toString()}-`; v = dateObj.getMinutes(); if (v < 10) { @@ -507,7 +507,7 @@ export class InMemoryFileDB { this.lastSave = now; const backFileName = path.join( this.backupDir, - this.getTimeStr(now) + '_' + this.settings.fileDB.fileName + '.gz', + `${this.getTimeStr(now)}_${this.settings.fileDB.fileName}.gz`, ); try { diff --git a/packages/db-objects-file/src/lib/objects/objectsInMemFileDB.js b/packages/db-objects-file/src/lib/objects/objectsInMemFileDB.js index fe3fc9b7b..e51b4f657 100644 --- a/packages/db-objects-file/src/lib/objects/objectsInMemFileDB.js +++ b/packages/db-objects-file/src/lib/objects/objectsInMemFileDB.js @@ -160,7 +160,7 @@ export class ObjectsInMemoryFileDB extends InMemoryFileDB { let results = []; const list = fs.readdirSync(dir); list.forEach(file => { - file = dir + '/' + file; + file = `${dir}/${file}`; const stat = fs.statSync(file); if (stat && stat.isDirectory()) { /* Recurse into a subdirectory */ @@ -539,7 +539,7 @@ export class ObjectsInMemoryFileDB extends InMemoryFileDB { if (stat.isDirectory()) { // read all entries and delete every one - fs.readdirSync(location).forEach(dir => this._unlink(id, name + '/' + dir)); + fs.readdirSync(location).forEach(dir => this._unlink(id, `${name}/${dir}`)); this.log.debug(`Delete directory ${path.join(id, name)}`); try { @@ -556,7 +556,7 @@ export class ObjectsInMemoryFileDB extends InMemoryFileDB { delete this.files[id]; } } else { - this.log.debug('Delete file ' + path.join(id, name)); + this.log.debug(`Delete file ${path.join(id, name)}`); try { fs.removeSync(location); } catch (e) { @@ -950,7 +950,7 @@ export class ObjectsInMemoryFileDB extends InMemoryFileDB { result.rows.push({ id: id, value: obj }); } - const f = eval('(' + func.map.replace(/emit/g, '_emit_') + ')'); + const f = eval(`(${func.map.replace(/emit/g, '_emit_')})`); for (const [id, obj] of Object.entries(this.dataset)) { if (params) { diff --git a/packages/db-objects-file/src/lib/objects/objectsInMemServerRedis.js b/packages/db-objects-file/src/lib/objects/objectsInMemServerRedis.js index b2f8b1b53..0145a3c1b 100644 --- a/packages/db-objects-file/src/lib/objects/objectsInMemServerRedis.js +++ b/packages/db-objects-file/src/lib/objects/objectsInMemServerRedis.js @@ -54,12 +54,12 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryFileDB { super(settings); this.serverConnections = {}; - this.namespaceObjects = - (this.settings.redisNamespace || (settings.connection && settings.connection.redisNamespace) || 'cfg') + - '.'; - this.namespaceFile = this.namespaceObjects + 'f.'; - this.namespaceObj = this.namespaceObjects + 'o.'; - this.namespaceSet = this.namespaceObjects + 's.'; + this.namespaceObjects = `${ + this.settings.redisNamespace || (settings.connection && settings.connection.redisNamespace) || 'cfg' + }.`; + this.namespaceFile = `${this.namespaceObjects}f.`; + this.namespaceObj = `${this.namespaceObjects}o.`; + this.namespaceSet = `${this.namespaceObjects}s.`; this.namespaceSetLen = this.namespaceSet.length; // this.namespaceObjectsLen = this.namespaceObjects.length; @@ -79,11 +79,9 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryFileDB { }) .then(() => { this.log.debug( - this.namespace + - ' ' + - (settings.secure ? 'Secure ' : '') + - ' Redis inMem-objects listening on port ' + - (settings.port || 9001), + `${this.namespace} ${settings.secure ? 'Secure ' : ''} Redis inMem-objects listening on port ${ + settings.port || 9001 + }`, ); if (typeof this.settings.connected === 'function') { @@ -223,7 +221,7 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryFileDB { } } - return this.namespaceFile + id + '$%$' + name + (isMeta !== undefined ? (isMeta ? '$%$meta' : '$%$data') : ''); + return `${this.namespaceFile + id}$%$${name}${isMeta !== undefined ? (isMeta ? '$%$meta' : '$%$data') : ''}`; } /** @@ -253,7 +251,7 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryFileDB { // Handle Redis "QUIT" request handler.on('quit', (_data, responseId) => { - this.log.silly(namespaceLog + ' Redis QUIT received, close connection'); + this.log.silly(`${namespaceLog} Redis QUIT received, close connection`); handler.sendString(responseId, 'OK'); handler.close(); }); @@ -418,7 +416,7 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryFileDB { try { result = this._getObjects(keys); } catch (err) { - return void handler.sendError(responseId, new Error('ERROR _getObjects: ' + err.message)); + return void handler.sendError(responseId, new Error(`ERROR _getObjects: ${err.message}`)); } result = result.map(el => (el ? JSON.stringify(el) : null)); handler.sendArray(responseId, result); @@ -820,7 +818,7 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryFileDB { // we ignore these type of commands for now, irrelevant handler.sendString(responseId, 'OK'); } else { - handler.sendError(responseId, new Error('CONFIG-UNSUPPORTED for ' + JSON.stringify(data))); + handler.sendError(responseId, new Error(`CONFIG-UNSUPPORTED for ${JSON.stringify(data)}`)); } }); @@ -973,7 +971,7 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryFileDB { */ _initSocket(socket) { if (this.settings.connection.enhancedLogging) { - this.log.silly(this.namespace + ' Handling new Redis Objects connection'); + this.log.silly(`${this.namespace} Handling new Redis Objects connection`); } const options = { log: this.log, @@ -984,10 +982,10 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryFileDB { const handler = new RedisHandler(socket, options); this._socketEvents(handler); - this.serverConnections[socket.remoteAddress + ':' + socket.remotePort] = handler; + this.serverConnections[`${socket.remoteAddress}:${socket.remotePort}`] = handler; socket.on('close', () => { - if (this.serverConnections[socket.remoteAddress + ':' + socket.remotePort]) { - delete this.serverConnections[socket.remoteAddress + ':' + socket.remotePort]; + if (this.serverConnections[`${socket.remoteAddress}:${socket.remotePort}`]) { + delete this.serverConnections[`${socket.remoteAddress}:${socket.remotePort}`]; } }); } diff --git a/packages/db-objects-jsonl/src/lib/objects/objectsInMemJsonlDB.js b/packages/db-objects-jsonl/src/lib/objects/objectsInMemJsonlDB.js index aea5fa9e0..682377c5b 100644 --- a/packages/db-objects-jsonl/src/lib/objects/objectsInMemJsonlDB.js +++ b/packages/db-objects-jsonl/src/lib/objects/objectsInMemJsonlDB.js @@ -174,7 +174,7 @@ export class ObjectsInMemoryJsonlDB extends ObjectsInMemoryFileDB { async _maybeMigrateFileDB() { const jsonlFileName = path.join(this.dataDir, this.settings.jsonlDB.fileName); const jsonFileName = path.join(this.dataDir, this.settings.fileDB.fileName); - const bakFileName = path.join(this.dataDir, this.settings.fileDB.fileName + '.bak'); + const bakFileName = path.join(this.dataDir, `${this.settings.fileDB.fileName}.bak`); // Check the timestamps of each file, defaulting to 0 if they don't exist let jsonlTimeStamp = 0; diff --git a/packages/db-objects-jsonl/src/lib/objects/objectsInMemServerRedis.js b/packages/db-objects-jsonl/src/lib/objects/objectsInMemServerRedis.js index 86cc23fdb..571fb313a 100644 --- a/packages/db-objects-jsonl/src/lib/objects/objectsInMemServerRedis.js +++ b/packages/db-objects-jsonl/src/lib/objects/objectsInMemServerRedis.js @@ -54,12 +54,12 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryJsonlDB { super(settings); this.serverConnections = {}; - this.namespaceObjects = - (this.settings.redisNamespace || (settings.connection && settings.connection.redisNamespace) || 'cfg') + - '.'; - this.namespaceFile = this.namespaceObjects + 'f.'; - this.namespaceObj = this.namespaceObjects + 'o.'; - this.namespaceSet = this.namespaceObjects + 's.'; + this.namespaceObjects = `${ + this.settings.redisNamespace || (settings.connection && settings.connection.redisNamespace) || 'cfg' + }.`; + this.namespaceFile = `${this.namespaceObjects}f.`; + this.namespaceObj = `${this.namespaceObjects}o.`; + this.namespaceSet = `${this.namespaceObjects}s.`; this.namespaceSetLen = this.namespaceSet.length; // this.namespaceObjectsLen = this.namespaceObjects.length; @@ -79,11 +79,9 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryJsonlDB { }) .then(() => { this.log.debug( - this.namespace + - ' ' + - (settings.secure ? 'Secure ' : '') + - ' Redis inMem-objects listening on port ' + - (settings.port || 9001), + `${this.namespace} ${settings.secure ? 'Secure ' : ''} Redis inMem-objects listening on port ${ + settings.port || 9001 + }`, ); if (typeof this.settings.connected === 'function') { @@ -223,7 +221,7 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryJsonlDB { } } - return this.namespaceFile + id + '$%$' + name + (isMeta !== undefined ? (isMeta ? '$%$meta' : '$%$data') : ''); + return `${this.namespaceFile + id}$%$${name}${isMeta !== undefined ? (isMeta ? '$%$meta' : '$%$data') : ''}`; } /** @@ -253,7 +251,7 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryJsonlDB { // Handle Redis "QUIT" request handler.on('quit', (_data, responseId) => { - this.log.silly(namespaceLog + ' Redis QUIT received, close connection'); + this.log.silly(`${namespaceLog} Redis QUIT received, close connection`); handler.sendString(responseId, 'OK'); handler.close(); }); @@ -418,7 +416,7 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryJsonlDB { try { result = this._getObjects(keys); } catch (err) { - return void handler.sendError(responseId, new Error('ERROR _getObjects: ' + err.message)); + return void handler.sendError(responseId, new Error(`ERROR _getObjects: ${err.message}`)); } result = result.map(el => (el ? JSON.stringify(el) : null)); handler.sendArray(responseId, result); @@ -973,7 +971,7 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryJsonlDB { */ _initSocket(socket) { if (this.settings.connection.enhancedLogging) { - this.log.silly(this.namespace + ' Handling new Redis Objects connection'); + this.log.silly(`${this.namespace} Handling new Redis Objects connection`); } const options = { log: this.log, @@ -984,10 +982,10 @@ export class ObjectsInMemoryServer extends ObjectsInMemoryJsonlDB { const handler = new RedisHandler(socket, options); this._socketEvents(handler); - this.serverConnections[socket.remoteAddress + ':' + socket.remotePort] = handler; + this.serverConnections[`${socket.remoteAddress}:${socket.remotePort}`] = handler; socket.on('close', () => { - if (this.serverConnections[socket.remoteAddress + ':' + socket.remotePort]) { - delete this.serverConnections[socket.remoteAddress + ':' + socket.remotePort]; + if (this.serverConnections[`${socket.remoteAddress}:${socket.remotePort}`]) { + delete this.serverConnections[`${socket.remoteAddress}:${socket.remotePort}`]; } }); } diff --git a/packages/db-objects-redis/src/lib/objects/objectsInRedisClient.ts b/packages/db-objects-redis/src/lib/objects/objectsInRedisClient.ts index c8298beb7..559dd2747 100644 --- a/packages/db-objects-redis/src/lib/objects/objectsInRedisClient.ts +++ b/packages/db-objects-redis/src/lib/objects/objectsInRedisClient.ts @@ -29,7 +29,7 @@ import type { ConnectionOptions, DbStatus } from '@iobroker/db-base/inMemFileDB' import * as url from 'node:url'; // eslint-disable-next-line unicorn/prefer-module -const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename)); +const thisDir = url.fileURLToPath(new URL('.', import.meta.url || `file://${__filename}`)); const ERRORS = CONSTS.ERRORS; @@ -262,9 +262,8 @@ export class ObjectsInRedisClient { if (!ready) { return 300; - } else { - return retry_max_delay; } + return retry_max_delay; }; delete this.settings.connection.options.retry_max_delay; @@ -735,9 +734,8 @@ export class ObjectsInRedisClient { if (!e.message.includes('UNSUPPORTED')) { this.log.error(`${this.namespace} Cannot determine Set feature status: ${e.message}`); return; - } else { - this.useSets = false; } + this.useSets = false; } try { @@ -950,9 +948,8 @@ export class ObjectsInRedisClient { const fileOptions = { notExists: true }; if (utils.checkFile(fileOptions, options, flag, this.defaultNewAcl)) { return tools.maybeCallback(callback, false, options, fileOptions); // NO error - } else { - return tools.maybeCallback(callback, true, options); // error } + return tools.maybeCallback(callback, true, options); // error } if (!this.client) { // @ts-expect-error TODO: not in specs, better just maybe cb check false? @@ -973,9 +970,8 @@ export class ObjectsInRedisClient { } if (utils.checkFile(fileOptions, options, flag, this.defaultNewAcl)) { return tools.maybeCallback(callback, false, options, fileOptions); // NO error - } else { - return tools.maybeCallback(callback, true, options); // error } + return tools.maybeCallback(callback, true, options); // error } checkFileRights( @@ -1181,9 +1177,8 @@ export class ObjectsInRedisClient { return this.checkFileRights(id, name, options, CONSTS.ACCESS_WRITE, (err, options, meta) => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - return this._writeFile(id, name, data, options, callback, meta); } + return this._writeFile(id, name, data, options, callback, meta); }); } @@ -1256,13 +1251,12 @@ export class ObjectsInRedisClient { this.checkFileRights(id, name, options, CONSTS.ACCESS_READ, async (err, options, meta) => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - try { - const { file, mimeType } = await this._readFile(id, name, meta); - return tools.maybeCallbackWithError(callback, null, file, mimeType); - } catch (e) { - return tools.maybeCallbackWithError(callback, e); - } + } + try { + const { file, mimeType } = await this._readFile(id, name, meta); + return tools.maybeCallbackWithError(callback, null, file, mimeType); + } catch (e) { + return tools.maybeCallbackWithError(callback, e); } }); } @@ -1350,12 +1344,11 @@ export class ObjectsInRedisClient { } if (meta && meta.notExists) { return this._rm(id, name, options); - } else { - const metaID = this.getFileId(id, name, true); - const dataID = this.getFileId(id, name, false); - await this._delBinaryState(dataID); - await this.client.del(metaID); } + const metaID = this.getFileId(id, name, true); + const dataID = this.getFileId(id, name, false); + await this._delBinaryState(dataID); + await this.client.del(metaID); } unlink(id: string, name: string, options: CallOptions | null | undefined, callback?: ioBroker.RmCallback): void { @@ -1378,17 +1371,15 @@ export class ObjectsInRedisClient { this.checkFileRights(id, name, options, CONSTS.ACCESS_DELETE, async (err, options, meta) => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - if (!options.acl.file.delete) { - return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); - } else { - try { - const files = await this._unlink(id, name, options, meta); - return tools.maybeCallbackWithError(callback, null, files); - } catch (e) { - return tools.maybeCallbackWithError(callback, e); - } - } + } + if (!options.acl.file.delete) { + return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); + } + try { + const files = await this._unlink(id, name, options, meta); + return tools.maybeCallbackWithError(callback, null, files); + } catch (e) { + return tools.maybeCallbackWithError(callback, e); } }); } @@ -1478,11 +1469,10 @@ export class ObjectsInRedisClient { const parts = key.substr(start, key.length - end).split('/'); if (parts.length === deepLevel) { return !key.includes('/_data.json$%$') && key !== '_data.json'; // sort out "virtual" files that are used to mark directories - } else { - const dir = parts[deepLevel - 1]; - if (dirs.indexOf(dir) === -1) { - dirs.push(dir); - } + } + const dir = parts[deepLevel - 1]; + if (dirs.indexOf(dir) === -1) { + dirs.push(dir); } } }); @@ -1594,13 +1584,11 @@ export class ObjectsInRedisClient { this.checkFileRights(id, name, options, CONSTS.ACCESS_READ, (err, options) => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - if (!options.acl.file.list) { - return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); - } else { - this._readDir(id, name, options, callback); - } } + if (!options.acl.file.list) { + return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); + } + this._readDir(id, name, options, callback); }); } @@ -1618,30 +1606,29 @@ export class ObjectsInRedisClient { ): Promise { if (!keys || !keys.length) { return tools.maybeCallback(callback); - } else { - if (!this.client) { - return tools.maybeCallbackWithError(callback, ERRORS.ERROR_DB_CLOSED); - } - for (const id of keys) { + } + if (!this.client) { + return tools.maybeCallbackWithError(callback, ERRORS.ERROR_DB_CLOSED); + } + for (const id of keys) { + try { try { - try { - await this.client.rename( - id.replace(/\$%\$meta$/, '$%$data'), - id.replace(oldBase, newBase).replace(/\$%\$meta$/, '$%$data'), - ); - } catch (e) { - // _data.json is not having a data key, so ignore error - if (!(id.endsWith('/_data.json$%$meta') && e.message.includes('no such key'))) { - throw e; - } - } - await this.client.rename(id, id.replace(oldBase, newBase)); + await this.client.rename( + id.replace(/\$%\$meta$/, '$%$data'), + id.replace(oldBase, newBase).replace(/\$%\$meta$/, '$%$data'), + ); } catch (e) { - return tools.maybeCallbackWithRedisError(callback, e); + // _data.json is not having a data key, so ignore error + if (!(id.endsWith('/_data.json$%$meta') && e.message.includes('no such key'))) { + throw e; + } } + await this.client.rename(id, id.replace(oldBase, newBase)); + } catch (e) { + return tools.maybeCallbackWithRedisError(callback, e); } - return tools.maybeCallback(callback); } + return tools.maybeCallback(callback); } private async _rename( @@ -1729,14 +1716,13 @@ export class ObjectsInRedisClient { result = keys; } return this._renameHelper(result, oldBase, newBase, callback); - } else { - try { - await this.client.rename(oldDataID, newDataID); - await this.client.rename(oldMetaID, newMetaID); - return tools.maybeCallback(callback); - } catch (e) { - return tools.maybeCallbackWithRedisError(callback, e); - } + } + try { + await this.client.rename(oldDataID, newDataID); + await this.client.rename(oldMetaID, newMetaID); + return tools.maybeCallback(callback); + } catch (e) { + return tools.maybeCallbackWithRedisError(callback, e); } } @@ -1782,13 +1768,11 @@ export class ObjectsInRedisClient { this.checkFileRights(id, oldName, options, CONSTS.ACCESS_WRITE, (err, options, meta) => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - if (!options.acl.file.write) { - return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); - } else { - this._rename(id, oldName, newName, options, callback, meta); - } } + if (!options.acl.file.write) { + return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); + } + this._rename(id, oldName, newName, options, callback, meta); }); } @@ -1835,9 +1819,8 @@ export class ObjectsInRedisClient { this.checkFileRights(id, name, options, CONSTS.ACCESS_WRITE, (err, options, meta) => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - return this._touch(id, name, callback, meta); } + return this._touch(id, name, callback, meta); }); } @@ -1848,15 +1831,14 @@ export class ObjectsInRedisClient { private async _rmHelper(keys: string[]): Promise { if (!keys.length) { return; - } else { - if (!this.client) { - throw new Error(ERRORS.ERROR_DB_CLOSED); - } + } + if (!this.client) { + throw new Error(ERRORS.ERROR_DB_CLOSED); + } - for (const id of keys) { - await this._delBinaryState(id.replace(/\$%\$meta$/, '$%$data')); - await this.client.del(id); - } + for (const id of keys) { + await this._delBinaryState(id.replace(/\$%\$meta$/, '$%$data')); + await this.client.del(id); } } @@ -1933,9 +1915,8 @@ export class ObjectsInRedisClient { const pos = name.lastIndexOf('/'); if (pos !== -1) { return { file: name.substring(pos + 1), path: name.substring(0, pos) }; - } else { - return { file: id, path: '' }; } + return { file: id, path: '' }; }); try { @@ -1964,17 +1945,15 @@ export class ObjectsInRedisClient { this.checkFileRights(id, null, options, CONSTS.ACCESS_DELETE, async (err, options, meta) => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - if (!options.acl.file.delete) { - return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); - } else { - try { - const files = await this._rm(id, name, options, meta && meta.notExists ? null : meta); - return tools.maybeCallbackWithError(callback, null, files); - } catch (e) { - return tools.maybeCallbackWithError(callback, e); - } - } + } + if (!options.acl.file.delete) { + return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); + } + try { + const files = await this._rm(id, name, options, meta && meta.notExists ? null : meta); + return tools.maybeCallbackWithError(callback, null, files); + } catch (e) { + return tools.maybeCallbackWithError(callback, e); } }); } @@ -2002,16 +1981,14 @@ export class ObjectsInRedisClient { this.checkFileRights(id, dirName, options, CONSTS.ACCESS_WRITE, (err, options) => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - if (!options.acl.file.write) { - return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); - } else { - // we create a dummy file (for file this file exists to store meta data) - do not override passed options - options = { ...options, virtualFile: true }; - const realName = dirName + (dirName.endsWith('/') ? '' : '/'); - this.writeFile(id, `${realName}_data.json`, '', options, callback); - } } + if (!options.acl.file.write) { + return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); + } + // we create a dummy file (for file this file exists to store meta data) - do not override passed options + options = { ...options, virtualFile: true }; + const realName = dirName + (dirName.endsWith('/') ? '' : '/'); + this.writeFile(id, `${realName}_data.json`, '', options, callback); }); } @@ -2199,9 +2176,9 @@ export class ObjectsInRedisClient { this.getUserGroup(options.owner, (user, groups) => { if (!groups || !groups[0]) { return tools.maybeCallbackWithError(callback, `user "${options.owner}" belongs to no group`); - } else { - options.ownerGroup = groups[0]; } + options.ownerGroup = groups[0]; + this.chownFile(id, name, options, callback); }); return; @@ -2210,13 +2187,11 @@ export class ObjectsInRedisClient { this.checkFileRights(id, name, options, CONSTS.ACCESS_WRITE, (err, options, meta) => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - if (!options.acl.file.write) { - return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); - } else { - return this._chownFile(id, name, options, callback, meta); - } } + if (!options.acl.file.write) { + return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); + } + return this._chownFile(id, name, options, callback, meta); }); } @@ -2410,13 +2385,11 @@ export class ObjectsInRedisClient { this.checkFileRights(id, name, options, CONSTS.ACCESS_WRITE, (err, options, meta) => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - if (!options.acl.file.write) { - return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); - } else { - return this._chmodFile(id, name, options, callback, meta); - } } + if (!options.acl.file.write) { + return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); + } + return this._chmodFile(id, name, options, callback, meta); }); } @@ -2455,10 +2428,9 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, CONSTS.ACCESS_WRITE, (err, _options) => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - // cache cannot be enabled - return tools.maybeCallbackWithError(callback, null, false); } + // cache cannot be enabled + return tools.maybeCallbackWithError(callback, null, false); }); } @@ -2592,9 +2564,8 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, 'list', err => { if (err) { return tools.maybeCallbackWithRedisError(callback, err); - } else { - return this._subscribe(pattern, false, callback); } + return this._subscribe(pattern, false, callback); }); } @@ -2630,9 +2601,8 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, 'list', err => { if (err) { return tools.maybeCallbackWithRedisError(callback, err); - } else { - return this._subscribe(pattern, true, callback); } + return this._subscribe(pattern, true, callback); }); } @@ -2675,13 +2645,12 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, 'list', async err => { if (err) { return tools.maybeCallbackWithRedisError(callback, err); - } else { - try { - await this._unsubscribe(pattern, false); - return tools.maybeCallback(callback); - } catch (e) { - return tools.maybeCallbackWithRedisError(callback, e); - } + } + try { + await this._unsubscribe(pattern, false); + return tools.maybeCallback(callback); + } catch (e) { + return tools.maybeCallbackWithRedisError(callback, e); } }); } @@ -2717,13 +2686,12 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, 'list', async err => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - try { - await this._unsubscribe(pattern, true); - return tools.maybeCallback(callback); - } catch (e) { - return tools.maybeCallbackWithRedisError(callback, e); - } + } + try { + await this._unsubscribe(pattern, true); + return tools.maybeCallback(callback); + } catch (e) { + return tools.maybeCallbackWithRedisError(callback, e); } }); } @@ -2737,37 +2705,36 @@ export class ObjectsInRedisClient { private async _objectHelper(keys: string[], objs: any[]): Promise { if (!keys.length) { return; - } else { - if (!this.client) { - throw new Error(ERRORS.ERROR_DB_CLOSED); - } - for (const id of keys) { - const obj = objs.shift(); - const message = JSON.stringify(obj); - const commands = []; - if (this.useSets) { - if (obj.type) { - // e.g. _design/ has no type - // add the object to the set + set object atomic - commands.push(['sadd', `${this.setNamespace}object.type.${obj.type}`, id]); - } - - if (obj.common?.custom) { - // add to "common" set - commands.push(['sadd', `${this.setNamespace}object.common.custom`, id]); - } + } + if (!this.client) { + throw new Error(ERRORS.ERROR_DB_CLOSED); + } + for (const id of keys) { + const obj = objs.shift(); + const message = JSON.stringify(obj); + const commands = []; + if (this.useSets) { + if (obj.type) { + // e.g. _design/ has no type + // add the object to the set + set object atomic + commands.push(['sadd', `${this.setNamespace}object.type.${obj.type}`, id]); } - if (!commands.length) { - // only set - await this.client.set(id, message); - } else { - // set all commands atomic - commands.push(['set', id, message]); - await this.client.multi(commands).exec(); + if (obj.common?.custom) { + // add to "common" set + commands.push(['sadd', `${this.setNamespace}object.common.custom`, id]); } - await this.client.publish(id, message); } + + if (!commands.length) { + // only set + await this.client.set(id, message); + } else { + // set all commands atomic + commands.push(['set', id, message]); + await this.client.multi(commands).exec(); + } + await this.client.publish(id, message); } } @@ -2869,9 +2836,9 @@ export class ObjectsInRedisClient { this.getUserGroup(options.owner, (user, groups /* , permissions*/) => { if (!groups || !groups[0]) { return tools.maybeCallbackWithError(callback, `user "${options.owner}" belongs to no group`); - } else { - options.ownerGroup = groups[0]; } + options.ownerGroup = groups[0]; + this.chownObject(pattern, options, callback); }); return; @@ -2880,13 +2847,11 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, CONSTS.ACCESS_WRITE, (err, options) => { if (err) { return tools.maybeCallbackWithRedisError(callback, err); - } else { - if (!options.acl.object || !options.acl.object.write) { - return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); - } else { - return this._chownObject(pattern, options, callback); - } } + if (!options.acl.object || !options.acl.object.write) { + return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); + } + return this._chownObject(pattern, options, callback); }); } @@ -3003,13 +2968,11 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, CONSTS.ACCESS_WRITE, (err, options) => { if (err) { return tools.maybeCallbackWithRedisError(callback, err); - } else { - if (!options.acl.file.write) { - return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); - } else { - return this._chmodObject(pattern, options, callback); - } } + if (!options.acl.file.write) { + return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); + } + return this._chmodObject(pattern, options, callback); }); } @@ -3051,12 +3014,10 @@ export class ObjectsInRedisClient { // Check permissions if (utils.checkObject(obj, options, CONSTS.ACCESS_READ)) { return tools.maybeCallbackWithError(callback, null, obj); - } else { - return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); } - } else { - return tools.maybeCallbackWithRedisError(callback, err, obj); + return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); } + return tools.maybeCallbackWithRedisError(callback, err, obj); } // cb version with options @@ -3092,9 +3053,8 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, CONSTS.ACCESS_READ, (err, options) => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - return this._getObject(id, options, callback); } + return this._getObject(id, options, callback); }); } } @@ -3161,38 +3121,36 @@ export class ObjectsInRedisClient { } } return tools.maybeCallbackWithError(callback, null, result); - } else { - // Check permissions - let metas: (string | null)[]; + } + // Check permissions + let metas: (string | null)[]; + try { + metas = await this.client.mget(keys); + } catch (e) { + return tools.maybeCallbackWithRedisError(callback, e); + } + metas = metas || []; + for (let i = 0; i < keys.length; i++) { + const metaStr = metas[i]; + let meta: ioBroker.AnyObject; try { - metas = await this.client.mget(keys); - } catch (e) { - return tools.maybeCallbackWithRedisError(callback, e); + meta = metaStr ? JSON.parse(metaStr) : null; + } catch { + this.log.error(`${this.namespace} Cannot parse JSON ${keys[i]}: ${metaStr}`); + continue; } - metas = metas || []; - for (let i = 0; i < keys.length; i++) { - const metaStr = metas[i]; - let meta: ioBroker.AnyObject; - try { - meta = metaStr ? JSON.parse(metaStr) : null; - } catch { - this.log.error(`${this.namespace} Cannot parse JSON ${keys[i]}: ${metaStr}`); - continue; - } - if (r.test(keys[i]) && utils.checkObject(meta, options, CONSTS.ACCESS_READ)) { - if (!dontModify) { - result.push(keys[i].substring(this.objNamespaceL)); - } else { - result.push(keys[i]); - } + if (r.test(keys[i]) && utils.checkObject(meta, options, CONSTS.ACCESS_READ)) { + if (!dontModify) { + result.push(keys[i].substring(this.objNamespaceL)); + } else { + result.push(keys[i]); } } - return tools.maybeCallbackWithError(callback, null, result); } - } else { return tools.maybeCallbackWithError(callback, null, result); } + return tools.maybeCallbackWithError(callback, null, result); } // User has provided a callback, thus we call the callback function @@ -3230,9 +3188,8 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, 'list', (err, options) => { if (err) { return tools.maybeCallbackWithRedisError(callback, err); - } else { - return this._getKeys(pattern, options, callback, dontModify); } + return this._getKeys(pattern, options, callback, dontModify); }); } } @@ -3351,9 +3308,8 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, CONSTS.ACCESS_READ, (err, options) => { if (err) { return tools.maybeCallbackWithRedisError(callback, err); - } else { - return this._getObjects(keys, options, callback, dontModify); } + return this._getObjects(keys, options, callback, dontModify); }); } } @@ -3417,9 +3373,8 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, CONSTS.ACCESS_READ, (err, options) => { if (err) { return tools.maybeCallbackWithRedisError(callback, err); - } else { - return this._getObjectsByPattern(pattern, options, callback); } + return this._getObjectsByPattern(pattern, options, callback); }); } } @@ -3685,13 +3640,12 @@ export class ObjectsInRedisClient { // do not use options from checkObjectRights because this will mess up configured default acl if (err) { return tools.maybeCallbackWithRedisError(callback, err); - } else { - try { - const res = await this._setObject(id, obj, options || {}); - return tools.maybeCallbackWithError(callback, null, res); - } catch (e) { - return tools.maybeCallbackWithError(callback, e); - } + } + try { + const res = await this._setObject(id, obj, options || {}); + return tools.maybeCallbackWithError(callback, null, res); + } catch (e) { + return tools.maybeCallbackWithError(callback, e); } }); } @@ -3805,13 +3759,12 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, CONSTS.ACCESS_DELETE, async (err, options) => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - try { - await this._delObject(id, options); - return tools.maybeCallback(callback); - } catch (e) { - return tools.maybeCallbackWithRedisError(callback, e); - } + } + try { + await this._delObject(id, options); + return tools.maybeCallback(callback); + } catch (e) { + return tools.maybeCallbackWithRedisError(callback, e); } }); } @@ -3862,17 +3815,15 @@ export class ObjectsInRedisClient { return arr.filter(obj => { if (included.has(obj.id) || obj.value === null) { return false; - } else { - included.set(obj.id, true); - return true; } - }); - } else { - return arr.filter(obj => { - // only filter parse Errors - return obj.value !== null; + included.set(obj.id, true); + return true; }); } + return arr.filter(obj => { + // only filter parse Errors + return obj.value !== null; + }); }; params = params || {}; @@ -3948,16 +3899,13 @@ export class ObjectsInRedisClient { if (typeof obj.common.name === 'object') { if (obj.common.name.en) { return { id: obj.common.name.en, value: obj }; - } else { - return { id: JSON.stringify(obj.common.name), value: obj }; } - } else { - return { id: obj.common.name, value: obj }; + return { id: JSON.stringify(obj.common.name), value: obj }; } - } else { - this.log.error(`${this.namespace} Cannot filter "${matches[2]}": ${JSON.stringify(obj)}`); - return { id: 'parseError', value: null }; + return { id: obj.common.name, value: obj }; } + this.log.error(`${this.namespace} Cannot filter "${matches[2]}": ${JSON.stringify(obj)}`); + return { id: 'parseError', value: null }; }); if (currRows.length) { result.rows = [...result.rows, ...currRows]; @@ -4210,102 +4158,100 @@ export class ObjectsInRedisClient { // apply filter if needed result.rows = filterEntries(result.rows, filterRequired); return result; + } + if (!wildCardLastPos) { + this.log.debug( + `${this.namespace} Search can't be optimized because wildcard not at the end, fallback to keys!: ${func.map}`, + ); } else { - if (!wildCardLastPos) { - this.log.debug( - `${this.namespace} Search can't be optimized because wildcard not at the end, fallback to keys!: ${func.map}`, - ); - } else { - this.log.debug(`${this.namespace} No suitable Lua script, fallback to keys!: ${func.map}`); - } + this.log.debug(`${this.namespace} No suitable Lua script, fallback to keys!: ${func.map}`); + } - let searchKeys = `${this.objNamespace}*`; - if (wildcardPos !== -1) { - // Wildcard included - searchKeys = this.objNamespace + params.endkey.replace(/\u9999/g, '*'); - } + let searchKeys = `${this.objNamespace}*`; + if (wildcardPos !== -1) { + // Wildcard included + searchKeys = this.objNamespace + params.endkey.replace(/\u9999/g, '*'); + } - let keys; - keys = await this._getKeysViaScan(searchKeys); + let keys; + keys = await this._getKeysViaScan(searchKeys); - if (!this.client) { - throw new Error(ERRORS.ERROR_DB_CLOSED); - } + if (!this.client) { + throw new Error(ERRORS.ERROR_DB_CLOSED); + } - const endAfterWildcard = params.endkey.substr(wildcardPos + 1); - params.startkey = this.objNamespace + params.startkey; - params.endkey = this.objNamespace + params.endkey; + const endAfterWildcard = params.endkey.substr(wildcardPos + 1); + params.startkey = this.objNamespace + params.startkey; + params.endkey = this.objNamespace + params.endkey; - keys = keys.sort().filter(key => { - if (key && !utils.REG_CHECK_ID.test(key)) { - if (params && wildcardPos > 0) { - if (params.startkey && key < params.startkey) { - return false; - } - if (params.endkey && key > params.endkey) { - return false; - } - } else if (params && wildcardPos === 0) { - if (!key.endsWith(endAfterWildcard)) { - return false; - } + keys = keys.sort().filter(key => { + if (key && !utils.REG_CHECK_ID.test(key)) { + if (params && wildcardPos > 0) { + if (params.startkey && key < params.startkey) { + return false; + } + if (params.endkey && key > params.endkey) { + return false; + } + } else if (params && wildcardPos === 0) { + if (!key.endsWith(endAfterWildcard)) { + return false; } - return true; - } else { - return false; } - }); + return true; + } + return false; + }); + + let objs: (null | string)[]; + try { + objs = await this.client.mget(keys); + } catch { + objs = []; + } + + const _emit_ = (id: string, obj: ioBroker.AnyObject): void => { + result.rows.push({ id: id, value: obj }); + }; + + const f = eval(`(${func.map.replace(/^function\(([a-z0-9A-Z_]+)\)/g, 'function($1, emit)')})`); - let objs: (null | string)[]; + for (let i = 0; i < keys.length; i++) { + const strObj = objs[i]; + let obj: ioBroker.AnyObject | null; try { - objs = await this.client.mget(keys); + obj = strObj !== null ? JSON.parse(strObj) : null; } catch { - objs = []; + this.log.error(`${this.namespace} Cannot parse JSON ${keys[i]}: ${objs[i]}`); + continue; + } + if (!utils.checkObject(obj, options, CONSTS.ACCESS_READ)) { + continue; } - const _emit_ = (id: string, obj: ioBroker.AnyObject): void => { - result.rows.push({ id: id, value: obj }); - }; - - const f = eval(`(${func.map.replace(/^function\(([a-z0-9A-Z_]+)\)/g, 'function($1, emit)')})`); - - for (let i = 0; i < keys.length; i++) { - const strObj = objs[i]; - let obj: ioBroker.AnyObject | null; + if (obj) { try { - obj = strObj !== null ? JSON.parse(strObj) : null; - } catch { - this.log.error(`${this.namespace} Cannot parse JSON ${keys[i]}: ${objs[i]}`); - continue; - } - if (!utils.checkObject(obj, options, CONSTS.ACCESS_READ)) { - continue; - } - - if (obj) { - try { - f(obj, _emit_); - } catch (e) { - this.log.error(`${this.namespace} Cannot execute map: ${e.message}`); - } + f(obj, _emit_); + } catch (e) { + this.log.error(`${this.namespace} Cannot execute map: ${e.message}`); } } - // Calculate max - if (func.reduce === '_stats') { - let max = null; - for (let i = 0; i < result.rows.length; i++) { - if (max === null || result.rows[i].value > max) { - max = result.rows[i].value; - } - } - if (max !== null) { - result.rows = [{ id: '_stats', value: { max: max } }]; - } else { - result.rows = []; + } + // Calculate max + if (func.reduce === '_stats') { + let max = null; + for (let i = 0; i < result.rows.length; i++) { + if (max === null || result.rows[i].value > max) { + max = result.rows[i].value; } } - return result; + if (max !== null) { + result.rows = [{ id: '_stats', value: { max: max } }]; + } else { + result.rows = []; + } } + return result; } private async _getObjectView( @@ -4336,10 +4282,9 @@ export class ObjectsInRedisClient { if (obj.views?.[search]) { return this._applyViewFunc(obj.views[search], params, options); - } else { - this.log.error(`${this.namespace} Cannot find search "${search}" in "${design}"`); - throw new Error(`Cannot find search "${search}" in "${design}"`); } + this.log.error(`${this.namespace} Cannot find search "${search}" in "${design}"`); + throw new Error(`Cannot find search "${search}" in "${design}"`); } else { this.log.error(`${this.namespace} Cannot find view "${design}" for search "${search}"`); throw new Error(`Cannot find view "${design}"`); @@ -4396,13 +4341,12 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, 'list', async (err, options) => { if (err) { return tools.maybeCallbackWithRedisError(callback, err); - } else { - try { - const res = await this._getObjectView(design, search, params, options); - return tools.maybeCallbackWithError(callback, null, res); - } catch (e) { - return tools.maybeCallbackWithRedisError(callback, e); - } + } + try { + const res = await this._getObjectView(design, search, params, options); + return tools.maybeCallbackWithError(callback, null, res); + } catch (e) { + return tools.maybeCallbackWithRedisError(callback, e); } }); } @@ -4531,13 +4475,12 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, 'list', async (err, options) => { if (err) { return tools.maybeCallbackWithRedisError(callback, err); - } else { - try { - const res = await this._getObjectList(params, options || {}); - return tools.maybeCallbackWithError(callback, null, res); - } catch (e) { - return tools.maybeCallbackWithError(callback, e); - } + } + try { + const res = await this._getObjectList(params, options || {}); + return tools.maybeCallbackWithError(callback, null, res); + } catch (e) { + return tools.maybeCallbackWithError(callback, e); } }); } @@ -4743,10 +4686,9 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, CONSTS.ACCESS_WRITE, (err, options) => { if (err) { return tools.maybeCallbackWithRedisError(callback, err); - } else { - // @ts-expect-error TODO we are returning type Object for ease of use to devs, but formally these are AnyObjects, e.g. not guaranteed to have common - return this._extendObject(id, obj, options, callback); } + // @ts-expect-error TODO we are returning type Object for ease of use to devs, but formally these are AnyObjects, e.g. not guaranteed to have common + return this._extendObject(id, obj, options, callback); }); } @@ -4782,49 +4724,48 @@ export class ObjectsInRedisClient { (!type || (obj.common && obj.common.type === type)) ) { return tools.maybeCallbackWithError(callback, null, idOrName, obj.common.name); - } else { - this._getKeys( - '*', - options, - async (err, keys) => { - if (!this.client) { - return tools.maybeCallbackWithError(callback, ERRORS.ERROR_DB_CLOSED); - } + } + this._getKeys( + '*', + options, + async (err, keys) => { + if (!this.client) { + return tools.maybeCallbackWithError(callback, ERRORS.ERROR_DB_CLOSED); + } - if (!keys || err) { - return tools.maybeCallbackWithError(callback, err); - } + if (!keys || err) { + return tools.maybeCallbackWithError(callback, err); + } - let objs; + let objs; + try { + objs = await this.client.mget(keys); + } catch (e) { + return tools.maybeCallbackWithRedisError(callback, e); + } + objs = objs || []; + // Assume it is name + for (let i = 0; i < keys.length; i++) { + const strObj = objs[i]; + let obj: ioBroker.AnyObject | null; try { - objs = await this.client.mget(keys); - } catch (e) { - return tools.maybeCallbackWithRedisError(callback, e); + obj = strObj ? JSON.parse(strObj) : null; + } catch { + this.log.error(`${this.namespace} Cannot parse JSON ${keys[i]}: ${objs[i]}`); + continue; } - objs = objs || []; - // Assume it is name - for (let i = 0; i < keys.length; i++) { - const strObj = objs[i]; - let obj: ioBroker.AnyObject | null; - try { - obj = strObj ? JSON.parse(strObj) : null; - } catch { - this.log.error(`${this.namespace} Cannot parse JSON ${keys[i]}: ${objs[i]}`); - continue; - } - if ( - obj?.common && - obj.common.name === idOrName && - (!type || ('type' in obj.common && obj.common.type === type)) - ) { - return tools.maybeCallbackWithError(callback, null, obj._id, idOrName); - } + if ( + obj?.common && + obj.common.name === idOrName && + (!type || ('type' in obj.common && obj.common.type === type)) + ) { + return tools.maybeCallbackWithError(callback, null, obj._id, idOrName); } - return tools.maybeCallbackWithError(callback, null, undefined, idOrName); - }, - true, - ); - } + } + return tools.maybeCallbackWithError(callback, null, undefined, idOrName); + }, + true, + ); }); } @@ -4875,9 +4816,8 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, CONSTS.ACCESS_LIST, (err, options) => { if (err) { return tools.maybeCallbackWithError(callback, err); - } else { - return this._findObject(idOrName, type, options, callback); } + return this._findObject(idOrName, type, options, callback); }); } } @@ -4900,33 +4840,31 @@ export class ObjectsInRedisClient { private async _destroyDBHelper(keys: string[], callback: ioBroker.ErrorCallback): Promise { if (!keys || !keys.length) { return tools.maybeCallback(callback); - } else { - if (!this.client) { - return tools.maybeCallbackWithError(callback, ERRORS.ERROR_DB_CLOSED); - } + } + if (!this.client) { + return tools.maybeCallbackWithError(callback, ERRORS.ERROR_DB_CLOSED); + } - for (const id of keys) { - try { - await this.client.del(id); - } catch { - // ignore - } + for (const id of keys) { + try { + await this.client.del(id); + } catch { + // ignore } - - return tools.maybeCallback(callback); } + + return tools.maybeCallback(callback); } private async _destroyDB(callback: ioBroker.ErrorCallback): Promise { if (!this.client) { return tools.maybeCallbackWithError(callback, ERRORS.ERROR_DB_CLOSED); - } else { - try { - const keys = await this._getKeysViaScan(`${this.redisNamespace}*`); - return this._destroyDBHelper(keys, callback); - } catch (e) { - return tools.maybeCallbackWithRedisError(callback, e); - } + } + try { + const keys = await this._getKeysViaScan(`${this.redisNamespace}*`); + return this._destroyDBHelper(keys, callback); + } catch (e) { + return tools.maybeCallbackWithRedisError(callback, e); } } @@ -4940,13 +4878,11 @@ export class ObjectsInRedisClient { utils.checkObjectRights(this, null, null, options, CONSTS.ACCESS_WRITE, (err, options) => { if (err) { return tools.maybeCallbackWithRedisError(callback, err); - } else { - if (!options.acl.file.write || options.user !== CONSTS.SYSTEM_ADMIN_USER) { - return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); - } else { - return this._destroyDB(callback); - } } + if (!options.acl.file.write || options.user !== CONSTS.SYSTEM_ADMIN_USER) { + return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION); + } + return this._destroyDB(callback); }); } diff --git a/packages/db-objects-redis/src/lib/objects/objectsUtils.ts b/packages/db-objects-redis/src/lib/objects/objectsUtils.ts index aa9bcab1e..b78a10ed7 100644 --- a/packages/db-objects-redis/src/lib/objects/objectsUtils.ts +++ b/packages/db-objects-redis/src/lib/objects/objectsUtils.ts @@ -119,9 +119,8 @@ export function getMimeType(ext: string, isTextData: boolean): FileMimeInformati const mimeInfo = getKnownMimeType(ext); if (mimeInfo) { return mimeInfo; - } else { - return { mimeType: isTextData ? 'text/plain' : 'application/octet-stream', isBinary: !isTextData }; } + return { mimeType: isTextData ? 'text/plain' : 'application/octet-stream', isBinary: !isTextData }; } export function checkFile( @@ -219,9 +218,8 @@ export function checkFileRights( objects.checkFile(id, name, _options, flag, (err: Error, options: Record, opt: any) => { if (err) { return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION, options); - } else { - return tools.maybeCallbackWithError(callback, null, options, opt); } + return tools.maybeCallbackWithError(callback, null, options, opt); }); } @@ -495,12 +493,12 @@ export function sanitizePath( id = id.replace(/\.\./g, ''); // do not allow to write in parent directories if (name.includes('..')) { - name = path.normalize('/' + name); + name = path.normalize(`/${name}`); } if (name.includes('..')) { // Also after normalization we still have .. in it - should not happen if normalize worked correctly name = name.replace(/\.\./g, ''); - name = path.normalize('/' + name); + name = path.normalize(`/${name}`); } name = name.replace(/\\/g, '/'); // replace win path backslashes @@ -673,7 +671,6 @@ export function checkObjectRights( if (id && !checkObject(object, options, flag)) { return tools.maybeCallbackWithError(callback, ERRORS.ERROR_PERMISSION, options); - } else { - return tools.maybeCallbackWithError(callback, null, options); } + return tools.maybeCallbackWithError(callback, null, options); } diff --git a/packages/db-states-file/src/lib/states/statesInMemFileDB.js b/packages/db-states-file/src/lib/states/statesInMemFileDB.js index 88860601e..5291b6809 100644 --- a/packages/db-states-file/src/lib/states/statesInMemFileDB.js +++ b/packages/db-states-file/src/lib/states/statesInMemFileDB.js @@ -253,22 +253,22 @@ export class StatesInMemoryFileDB extends InMemoryFileDB { // needed by Server _subscribeMessageForClient(client, id) { - this.handleSubscribe(client, 'messagebox', 'messagebox.' + id); + this.handleSubscribe(client, 'messagebox', `messagebox.${id}`); } // needed by Server _unsubscribeMessageForClient(client, id) { - this.handleUnsubscribe(client, 'messagebox', 'messagebox.' + id); + this.handleUnsubscribe(client, 'messagebox', `messagebox.${id}`); } // needed by Server _subscribeLogForClient(client, id) { - this.handleSubscribe(client, 'log', 'log.' + id); + this.handleSubscribe(client, 'log', `log.${id}`); } // needed by Server _unsubscribeLogForClient(client, id) { - this.handleUnsubscribe(client, 'log', 'log.' + id); + this.handleUnsubscribe(client, 'log', `log.${id}`); } // needed by Server diff --git a/packages/db-states-file/src/lib/states/statesInMemServerRedis.js b/packages/db-states-file/src/lib/states/statesInMemServerRedis.js index ffd5d4bfb..28075b2fe 100644 --- a/packages/db-states-file/src/lib/states/statesInMemServerRedis.js +++ b/packages/db-states-file/src/lib/states/statesInMemServerRedis.js @@ -50,15 +50,15 @@ export class StatesInMemoryServer extends StatesInMemoryFileDB { super(settings); this.serverConnections = {}; - this.namespaceStates = (this.settings.redisNamespace || 'io') + '.'; - this.namespaceMsg = (this.settings.namespaceMsg || 'messagebox') + '.'; - this.namespaceLog = (this.settings.namespaceLog || 'log') + '.'; - this.namespaceSession = (this.settings.namespaceSession || 'session') + '.'; + this.namespaceStates = `${this.settings.redisNamespace || 'io'}.`; + this.namespaceMsg = `${this.settings.namespaceMsg || 'messagebox'}.`; + this.namespaceLog = `${this.settings.namespaceLog || 'log'}.`; + this.namespaceSession = `${this.settings.namespaceSession || 'session'}.`; //this.namespaceStatesLen = this.namespaceStates.length; this.namespaceMsgLen = this.namespaceMsg.length; this.namespaceLogLen = this.namespaceLog.length; //this.namespaceSessionlen = this.namespaceSession.length; - this.metaNamespace = (this.settings.metaNamespace || 'meta') + '.'; + this.metaNamespace = `${this.settings.metaNamespace || 'meta'}.`; this.metaNamespaceLen = this.metaNamespace.length; this.open() @@ -216,7 +216,7 @@ export class StatesInMemoryServer extends StatesInMemoryFileDB { const result = states.map(el => (el ? JSON.stringify(el) : null)); handler.sendArray(responseId, result); } catch (err) { - handler.sendError(responseId, new Error('ERROR _getStates: ' + err.message)); + handler.sendError(responseId, new Error(`ERROR _getStates: ${err.message}`)); } } else { handler.sendError( @@ -503,18 +503,18 @@ export class StatesInMemoryServer extends StatesInMemoryFileDB { const options = { log: this.log, - logScope: this.namespace + ' States', + logScope: `${this.namespace} States`, handleAsBuffers: true, enhancedLogging: this.settings.connection.enhancedLogging, }; const handler = new RedisHandler(socket, options); this._socketEvents(handler); - this.serverConnections[socket.remoteAddress + ':' + socket.remotePort] = handler; + this.serverConnections[`${socket.remoteAddress}:${socket.remotePort}`] = handler; socket.on('close', () => { - if (this.serverConnections[socket.remoteAddress + ':' + socket.remotePort]) { - delete this.serverConnections[socket.remoteAddress + ':' + socket.remotePort]; + if (this.serverConnections[`${socket.remoteAddress}:${socket.remotePort}`]) { + delete this.serverConnections[`${socket.remoteAddress}:${socket.remotePort}`]; } }); } diff --git a/packages/db-states-jsonl/src/lib/states/statesInMemJsonlDB.js b/packages/db-states-jsonl/src/lib/states/statesInMemJsonlDB.js index 6ca7f51b0..4957381ee 100644 --- a/packages/db-states-jsonl/src/lib/states/statesInMemJsonlDB.js +++ b/packages/db-states-jsonl/src/lib/states/statesInMemJsonlDB.js @@ -196,7 +196,7 @@ export class StatesInMemoryJsonlDB extends StatesInMemoryFileDB { async _maybeMigrateFileDB() { const jsonlFileName = path.join(this.dataDir, this.settings.jsonlDB.fileName); const jsonFileName = path.join(this.dataDir, this.settings.fileDB.fileName); - const bakFileName = path.join(this.dataDir, this.settings.fileDB.fileName + '.bak'); + const bakFileName = path.join(this.dataDir, `${this.settings.fileDB.fileName}.bak`); // Check the timestamps of each file, defaulting to 0 if they don't exist let jsonlTimeStamp = 0; diff --git a/packages/db-states-jsonl/src/lib/states/statesInMemServerRedis.js b/packages/db-states-jsonl/src/lib/states/statesInMemServerRedis.js index 9e795dcc1..e95d1ac1c 100644 --- a/packages/db-states-jsonl/src/lib/states/statesInMemServerRedis.js +++ b/packages/db-states-jsonl/src/lib/states/statesInMemServerRedis.js @@ -50,15 +50,15 @@ export class StatesInMemoryServer extends StatesInMemoryJsonlDB { super(settings); this.serverConnections = {}; - this.namespaceStates = (this.settings.redisNamespace || 'io') + '.'; - this.namespaceMsg = (this.settings.namespaceMsg || 'messagebox') + '.'; - this.namespaceLog = (this.settings.namespaceLog || 'log') + '.'; - this.namespaceSession = (this.settings.namespaceSession || 'session') + '.'; + this.namespaceStates = `${this.settings.redisNamespace || 'io'}.`; + this.namespaceMsg = `${this.settings.namespaceMsg || 'messagebox'}.`; + this.namespaceLog = `${this.settings.namespaceLog || 'log'}.`; + this.namespaceSession = `${this.settings.namespaceSession || 'session'}.`; //this.namespaceStatesLen = this.namespaceStates.length; this.namespaceMsgLen = this.namespaceMsg.length; this.namespaceLogLen = this.namespaceLog.length; //this.namespaceSessionlen = this.namespaceSession.length; - this.metaNamespace = (this.settings.metaNamespace || 'meta') + '.'; + this.metaNamespace = `${this.settings.metaNamespace || 'meta'}.`; this.metaNamespaceLen = this.metaNamespace.length; this.open() @@ -503,18 +503,18 @@ export class StatesInMemoryServer extends StatesInMemoryJsonlDB { const options = { log: this.log, - logScope: this.namespace + ' States', + logScope: `${this.namespace} States`, handleAsBuffers: true, enhancedLogging: this.settings.connection.enhancedLogging, }; const handler = new RedisHandler(socket, options); this._socketEvents(handler); - this.serverConnections[socket.remoteAddress + ':' + socket.remotePort] = handler; + this.serverConnections[`${socket.remoteAddress}:${socket.remotePort}`] = handler; socket.on('close', () => { - if (this.serverConnections[socket.remoteAddress + ':' + socket.remotePort]) { - delete this.serverConnections[socket.remoteAddress + ':' + socket.remotePort]; + if (this.serverConnections[`${socket.remoteAddress}:${socket.remotePort}`]) { + delete this.serverConnections[`${socket.remoteAddress}:${socket.remotePort}`]; } }); } diff --git a/packages/db-states-redis/src/lib/states/statesInRedisClient.ts b/packages/db-states-redis/src/lib/states/statesInRedisClient.ts index 4046173de..c80fe154b 100644 --- a/packages/db-states-redis/src/lib/states/statesInRedisClient.ts +++ b/packages/db-states-redis/src/lib/states/statesInRedisClient.ts @@ -92,12 +92,12 @@ export class StateRedisClient { constructor(settings: StatesSettings) { this.settings = settings || {}; - this.namespaceRedis = (this.settings.redisNamespace || 'io') + '.'; + this.namespaceRedis = `${this.settings.redisNamespace || 'io'}.`; this.namespaceRedisL = this.namespaceRedis.length; - this.namespaceMsg = (this.settings.namespaceMsg || 'messagebox') + '.'; - this.namespaceLog = (this.settings.namespaceLog || 'log') + '.'; - this.namespaceSession = (this.settings.namespaceSession || 'session') + '.'; - this.metaNamespace = (this.settings.metaNamespace || 'meta') + '.'; + this.namespaceMsg = `${this.settings.namespaceMsg || 'messagebox'}.`; + this.namespaceLog = `${this.settings.namespaceLog || 'log'}.`; + this.namespaceSession = `${this.settings.namespaceSession || 'session'}.`; + this.metaNamespace = `${this.settings.metaNamespace || 'meta'}.`; this.globalMessageId = Math.round(Math.random() * 100_000_000); this.globalLogId = Math.round(Math.random() * 100_000_000); @@ -982,21 +982,20 @@ export class StateRedisClient { async _destroyDBHelper(keys: string[], callback?: ioBroker.ErrorCallback): Promise { if (!keys || !keys.length) { return tools.maybeCallback(callback); - } else { - if (!this.client) { - return tools.maybeCallbackWithError(callback, tools.ERRORS.ERROR_DB_CLOSED); - } + } + if (!this.client) { + return tools.maybeCallbackWithError(callback, tools.ERRORS.ERROR_DB_CLOSED); + } - for (const id of keys) { - try { - await this.client.del(id); - } catch { - // ignore - } + for (const id of keys) { + try { + await this.client.del(id); + } catch { + // ignore } - - return tools.maybeCallback(callback); } + + return tools.maybeCallback(callback); } /** @@ -1005,15 +1004,14 @@ export class StateRedisClient { async destroyDB(callback?: ioBroker.ErrorCallback): Promise { if (!this.client) { return tools.maybeCallbackWithError(callback, tools.ERRORS.ERROR_DB_CLOSED); - } else { - let keys; - try { - keys = await this.client.keys(`${this.namespaceRedis}*`); - } catch { - //ignore - } - return this._destroyDBHelper(keys || [], callback); } + let keys; + try { + keys = await this.client.keys(`${this.namespaceRedis}*`); + } catch { + //ignore + } + return this._destroyDBHelper(keys || [], callback); } // Destructor of the class. Called by shutting down.