@iobroker/js-controller-common-db
Version:
The Library contains the common utils for the ioBroker controller which can be used by db classes too, as they do not rely on the db (circular dependencies).
717 lines • 26.7 kB
TypeScript
/// <reference types="node" resolution-mode="require"/>
/// <reference types="@iobroker/types-dev" />
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
import { type ChildProcessPromise } from 'promisify-child-process';
import type { CommandResult, PackageManager } from '@alcalzone/pak';
import type { ExecOptions } from 'node:child_process';
type DockerInformation = {
/** If it is a Docker installation */
isDocker: boolean;
/** If it is the official Docker image */
isOfficial: true;
/** Semver string for official Docker image */
officialVersion: string;
} | {
/** If it is a Docker installation */
isDocker: boolean;
/** If it is the official Docker image */
isOfficial: false;
};
export interface HostInfo {
/** Converted OS for human readability */
Platform: NodeJS.Platform | 'docker' | 'Windows' | 'OSX';
/** The underlying OS */
os: NodeJS.Platform;
/** Information about the docker installation */
dockerInformation?: DockerInformation;
/** Host architecture */
Architecture: string;
/** Number of CPUs */
CPUs: number | null;
/** CPU speed */
Speed: number | null;
/** CPU model */
Model: string | null;
/** Total RAM of host */
RAM: number;
/** System uptime in seconds */
'System uptime': number;
/** Node.JS version */
'Node.js': string;
/** Current time to compare to local time */
time: number;
/** Timezone offset to compare to local time */
timeOffset: number;
/** Number of available adapters */
'adapters count': number;
/** NPM version */
NPM: string;
}
interface FormatAliasValueOptions {
/** Common attribute of a source object */
sourceCommon?: Partial<ioBroker.StateCommon>;
/** Common attribute of a target object */
targetCommon?: Partial<ioBroker.StateCommon>;
/** State to format */
state: ioBroker.State | null | undefined;
/** Logger used for logging */
logger: any;
/** Prefix for log messages */
logNamespace: string;
/** Id of the source object, used for logging */
sourceId?: string;
/** Id of the target object, used for logging */
targetId?: string;
}
export interface DockerImageInformation {
/** The official version like v10.0.0 */
version: string;
/** Time of last image update */
lastUpdated: string;
/** If the version is newer than the one currently running */
isNew: boolean;
}
export declare enum ERRORS {
ERROR_NOT_FOUND = "Not exists",
ERROR_EMPTY_OBJECT = "null object",
ERROR_NO_OBJECT = "no object",
ERROR_DB_CLOSED = "DB closed"
}
/** All characters that may not appear in an object ID. */
export declare const FORBIDDEN_CHARS: RegExp;
/**
* recursively copy values from an old object to new one
*
* @param oldObj source object
* @param newObj destination object
* @param originalObj optional object for read __no_change__ values
* @param isNonEdit optional indicator if copy is in nonEdit part
*/
export declare function copyAttributes(oldObj: Record<string, any>, newObj: Record<string, any>, originalObj?: Record<string, any>, isNonEdit?: boolean): void;
/**
* Checks the flag nonEdit and restores non-changeable values if required
*
* @param oldObject source object
* @param newObject destination object
*/
export declare function checkNonEditable(oldObject: ioBroker.SettableObject | null, newObject: ioBroker.SettableObject): boolean;
/**
* Checks if a version is up-to-date, throws error on invalid version strings
*
* @param repoVersion version in repository
* @param installedVersion the current installed version
*/
export declare function upToDate(repoVersion: string, installedVersion: string): boolean;
export declare function decryptPhrase(password: string, data: any, callback: (decrypted?: null | string) => void): void;
/**
* Checks if multiple host objects exists, without using object views
*
* @param objects the objects db
* @returns true if only one host object exists
*/
export declare function isSingleHost(objects: any): Promise<boolean>;
/**
* Checks if at least one host is running in a Multihost environment
*
* @param objects the objects db
* @param states the states db
* @returns true if one or more hosts running else false
*/
export declare function isHostRunning(objects: any, states: any): Promise<boolean>;
/**
* Checks if ioBroker is installed in a dev environment
*/
export declare function isDevInstallation(): boolean;
/** In dev installations with uppercase B to match GitHub repo name - try to get rid of it in the long run */
type AppName = 'iobroker' | 'ioBroker';
export declare const appNameLowerCase = "iobroker";
export declare const appName: AppName;
export declare function findIPs(): string[];
/**
* Fetch the image information of the newest available (official) ioBroker Docker image from DockerHub
*/
export declare function getNewestDockerImageVersion(): Promise<DockerImageInformation>;
/**
* Get information of a Docker installation
*/
export declare function getDockerInformation(): DockerInformation;
/**
* Controller UI upgrade is not supported on Windows and MacOS
*/
export declare function isControllerUiUpgradeSupported(): boolean;
/**
* Checks if we are running inside a docker container
*/
export declare function isDocker(): boolean;
/**
* Generates a new uuid if non-existing
*
* @param objects - objects DB
* @returns uuid if successfully created/updated
*/
export declare function createUuid(objects: any): Promise<void | string>;
/**
* Download file to tmp or return file name directly
*
* @param urlOrPath
* @param fileName
* @param callback
*/
export declare function getFile(urlOrPath: string, fileName: string, callback: (file?: string) => void): Promise<void>;
export declare function getJson(urlOrPath: string, agent: string, callback: (sources?: Record<string, any> | null, urlOrPath?: string | null) => void): Promise<void>;
/**
* Return content of the json file. Download it or read directly
*
* @param urlOrPath URL where the json file could be found
* @param agent optional agent identifier like "Windows Chrome 12.56"
* @returns json object
*/
export declare function getJsonAsync(urlOrPath: string, agent?: string): Promise<Record<string, any> | null>;
interface Multilingual {
en: string;
de?: string;
ru?: string;
pt?: string;
nl?: string;
fr?: string;
it?: string;
es?: string;
pl?: string;
uk?: string;
'zh-cn'?: string;
}
export interface AdapterInformation {
/** this flag is only true for the js-controller */
controller: boolean;
/** adapter version */
version: string;
/** path to icon of the adapter */
icon: string;
/** path to local icon of the adater */
localIcon?: string;
/** title of the adapter */
title: string;
/** title of the adapter in multiple languages */
titleLang: Multilingual;
/** description of the adapter in multiple languages */
desc: Multilingual;
/** platform of the adapter */
platform: 'Javascript/Node.js';
/** keywords of the adapter */
keywords: string[];
/** path to readme file */
readme: string;
/** The installed adapter version, not existing on controller */
runningVersion?: string;
/** type of the adapter */
type: string;
/** license of the adapter */
license: string;
/** url to license information */
licenseUrl?: string;
}
/**
* Get a list of all installed adapters and controller version on this host
*
* @param hostRunningVersion Version of the running js-controller, will be included in the returned information if provided
* @returns object containing information about installed host
*/
export declare function getInstalledInfo(hostRunningVersion?: string): Record<string, AdapterInformation>;
/**
* Get a list of all adapters and controller in some repository file or in /conf/source-dist.json
*
* @param urlOrPath URL starting with http:// or https:// or local file link
* @param additionalInfo destination object
* @param callback function (err, sources, actualHash) { }
*/
export declare function getRepositoryFile(urlOrPath: string, additionalInfo: Record<string, any>, callback: (err?: Error | null, sources?: Record<string, any>, actualHash?: string | number) => void): void;
export interface RepositoryFile {
json: ioBroker.RepositoryJson;
changed: boolean;
hash: string;
}
/**
* Read on repository
*
* @param url URL starting with http:// or https:// or local file link
* @param hash actual hash
* @param force Force repository update despite on hash
* @param _actualRepo Actual repository JSON content
*/
export declare function getRepositoryFileAsync(url: string, hash?: string, force?: boolean, _actualRepo?: ioBroker.RepositoryJson | null): Promise<RepositoryFile>;
/**
* Sends the given object to the diagnosis server
*
* @param obj - diagnosis object
*/
export declare function sendDiagInfo(obj: Record<string, any>): Promise<void>;
/**
* Finds the adapter directory of a given adapter
*
* @param adapter name of the adapter, e.g., hm-rpc
* @returns path to adapter directory or null if no directory found
*/
export declare function getAdapterDir(adapter: string): string | null;
/**
* Returns the hostname of this host
*/
export declare function getHostName(): string;
export interface InstallNodeModuleOptions {
unsafePerm?: boolean;
debug?: boolean;
cwd?: string;
}
/**
*
* Figure out which package manager is in charge, but with a fallback to npm.
*
* @param cwd Which directory to work in. If none is given, this defaults to ioBroker's root directory.
*/
export declare function detectPackageManagerWithFallback(cwd?: string): Promise<PackageManager>;
/**
* Installs a node module using npm or a similar package manager
*
* @param npmUrl Which node module to install
* @param options Options for the installation
*/
export declare function installNodeModule(npmUrl: string, options?: InstallNodeModuleOptions): Promise<CommandResult>;
export interface UninstallNodeModuleOptions {
debug?: boolean;
cwd?: string;
}
/**
* Uninstalls a node module using npm or a similar package manager
*
* @param packageName Which node module to uninstall
* @param options Options for the installation
*/
export declare function uninstallNodeModule(packageName: string, options?: UninstallNodeModuleOptions): Promise<CommandResult>;
export interface RebuildNodeModulesOptions {
debug?: boolean;
cwd?: string;
module?: string;
}
/**
* Rebuilds all native node_modules that are dependencies of the project in the current working directory / project root.
* If `options.cwd` is given, the directory must contain a lockfile.
*
* @param options Options for the rebuild
*/
export declare function rebuildNodeModules(options?: RebuildNodeModulesOptions): Promise<CommandResult>;
export interface GetDiskInfoResponse {
'Disk size': number;
'Disk free': number;
}
/**
* Read disk free space
*/
export declare function getDiskInfo(): Promise<GetDiskInfoResponse | null>;
export interface CertificateInfo {
certificateFilename: string | null;
/** the certificate itself */
certificate: string;
/** serial number */
serialNumber: string;
/** type of signature as text like "RSA" */
signature: string;
/** bits used for encryption key like 2048 */
keyLength: number;
/** issuer of the certificate */
issuer: Record<string, any>;
/** subject that is signed */
subject: Record<string, any>;
/** server name this certificate belong to */
dnsNames: {
type: number;
value: string;
}[];
/** this certificate can be used for the following purposes */
keyUsage: Record<string, any>;
/** usable or client, server or ... */
extKeyUsage: Record<string, any>;
/** certificate validity start datetime */
validityNotBefore: Date;
/** certificate validity end datetime */
validityNotAfter: Date;
}
/**
* Returns information about a certificate
*
* @param cert
* @returns certificate information object
*/
export declare function getCertificateInfo(cert: string): null | CertificateInfo;
export interface DefaultCertificates {
defaultPrivate: string;
defaultPublic: string;
}
/** Maximum time after which cert has to expire - 365 days in ms */
export declare const MAX_CERT_VALIDITY: number;
/**
* Returns default SSL certificates (private and public)
*
*
* The following info will be returned:
* - defaultPrivate: private RSA key
* - defaultPublic: public certificate
*
* <pre><code>
* const certificates = tools.generateDefaultCertificates();
* </code></pre>
*/
export declare function generateDefaultCertificates(): DefaultCertificates;
/**
* Collects information about host and available adapters
*
* Following info will be collected:
* - available adapters
* - node.js --version
* - npm --version
*
* @param objects db
*/
export declare function getHostInfo(objects: any): Promise<HostInfo>;
/**
* Finds the controller root directory
*
* @returns absolute path to controller dir without ending slash
*/
export declare function getControllerDir(): string;
/**
* Get the root dir of the ioBroker installation
*/
export declare function getRootDir(): string;
/** Returns whether the current process is executed via dev-server */
export declare function isDevServerInstallation(): boolean;
/**
* All paths are returned always relative to /node_modules/' + appName + '.js-controller
* the result has always "/" as last symbol
*/
export declare function getDefaultDataDir(): string;
/**
* Returns the path of the config file
*/
export declare function getConfigFileName(): string;
/**
* Promisifies a function which returns an error as the first argument in its callback
*
* @param fn The function to promisify
* @param context (optional) The context (value of `this` to bind the function to)
* @param returnArgNames (optional) If the callback contains multiple arguments,
* you can combine them into one object by passing the names as an array.
* Otherwise, the Promise will resolve with an array
*/
export declare function promisify(fn: (...args: any[]) => void, context?: any, returnArgNames?: string[]): (...args: any[]) => Promise<any>;
/**
* Promisifies a function which does not provide an error as the first argument in its callback
*
* @param fn The function to promisify
* @param context (optional) The context (value of `this` to bind the function to)
* @param returnArgNames (optional) If the callback contains multiple arguments,
* you can combine them into one object by passing the names as an array.
* Otherwise, the Promise will resolve with an array
*/
export declare function promisifyNoError(fn: (...args: any[]) => void, context?: any, returnArgNames?: string[]): (...args: any[]) => Promise<any>;
export declare function setQualityForInstance(objects: any, states: any, namespace: string, q: number): Promise<void>;
/**
* Converts ioB pattern into regex.
*
* @param pattern - Regex string to use it in new RegExp(pattern)
*/
export declare function pattern2RegEx(pattern: string): string;
/**
* Checks if a pattern is valid
*
* @param pattern
* @pattern pattern to check for validity
*/
export declare function isValidPattern(pattern: string): boolean;
/**
* Appends the stack trace generated by `captureStackTrace` to the given string
*
* @param str - The string to append the stack trace to
*/
export declare function appendStackTrace(str: string): string;
/**
* encrypts a value by a given key via AES-192-CBC
*
* @param key - Secret key
* @param value - value to decrypt
*/
export declare function encrypt(key: string, value: string): string;
/**
* encrypts a value by a given key via AES-192-CBC
*
* @param key - Secret key
* @param value - value to decrypt
*/
export declare function decrypt(key: string, value: string): string;
/**
* Tests whether the given variable is a real object and not an Array
*
* @param it The variable to test
* @returns true if it is Record<string, any>
*/
export declare function isObject(it: unknown): it is Record<string, any>;
/**
* Tests whether the given variable is really an Array
*
* @param it The variable to test
*/
export declare function isArray(it: unknown): it is any[];
/**
* Measure the Node.js event loop lag and repeatedly call the provided callback function with the updated results
*
* @param ms The number of milliseconds for monitoring
* @param cb Callback function to call for each new value
*/
export declare function measureEventLoopLag(ms: number, cb: (eventLoopLag?: number) => void): void;
/**
* This function convert state values by read and write of aliases. Function is synchronous.
* On errors, null is returned instead
*
* @param options
*/
export declare function formatAliasValue(options: FormatAliasValueOptions): ioBroker.State | null;
/**
* remove given id from all enums
*
* @param objects object to access objects db
* @param id the object id which will be deleted from enums
* @param allEnums objects with all enums to use - if not provided all enums will be queried
* @returns Promise All objects are tried to be updated - reject will happen as soon as one fails with the error of the first fail
*/
export declare function removeIdFromAllEnums(objects: any, id: string, allEnums?: Record<string, any>): Promise<void>;
/**
* Parses dependencies to standardized object of form
*
* @param dependencies dependencies array or single dependency
* @returns parsedDeps parsed dependencies
*/
export declare function parseDependencies(dependencies: string[] | Record<string, string>[] | string | Record<string, string> | undefined): Record<string, string>;
/**
* Validates types of `obj.common` properties and `object.type`, if invalid types are used, an error is thrown.
* If attributes of `obj.common` are not provided, no error is thrown. obj.type has to be there and has to be valid.
*
* @param obj an object which will be validated
* @param extend (optional) if true checks allow more optional cases for extendObject calls
* @throws Error if a property has the wrong type or `obj.type` is non-existing
*/
export declare function validateGeneralObjectProperties(obj: any, extend?: boolean): void;
/**
* get all instances of all adapters in the list
*
* @param adapters list of adapter names to get instances for
* @param objects class redis objects
* @returns array of IDs
*/
export declare function getAllInstances(adapters: string[], objects: any): Promise<string[]>;
/**
* Get all existing enums
*
* @param objects - objects db
* @returns Promise
*/
export declare function getAllEnums(objects: any): Promise<Record<string, ioBroker.EnumObject>>;
/**
* get async all instances of one adapter
*
* @param adapter name of the adapter
* @param objects objects DB
* @param withObjects return objects instead of only ids
*/
export declare function getInstances<TWithObjects extends boolean>(adapter: string, objects: any, withObjects: TWithObjects): Promise<TWithObjects extends true ? ioBroker.InstanceObject[] : ioBroker.ObjectIDs.Instance[]>;
/**
* Executes a command asynchronously. On success, the promise resolves with stdout and stderr.
* On error, the promise rejects with the exit code or signal, as well as stdout and stderr.
*
* @param command The command to execute
* @param execOptions The options for child_process.exec
* @returns child process promise
*/
export declare function execAsync(command: string, execOptions?: ExecOptions): ChildProcessPromise;
/**
* Takes input from one stream and writes it to another as soon as a complete line was read.
*
* @param input The stream to read from
* @param output The stream to write into
*/
export declare function pipeLinewise(input: NodeJS.ReadableStream, output: NodeJS.WritableStream): void;
/**
* Checks if an adapter is an ESM module or CJS
*
* @param adapter name of the adapter like hm-rpc
*/
export declare function isAdapterEsmModule(adapter: string): Promise<boolean>;
/**
* Find the adapter main file as full path
*
* @param adapter - adapter name of the adapter, e.g., hm-rpc
* @returns full file name
*/
export declare function resolveAdapterMainFile(adapter: string): Promise<string>;
/**
* Returns the default nodeArgs required to execute the main file, e.g., transpile hooks for TypeScript
*
* @param mainFile
* @returns default node args for cli
*/
export declare function getDefaultNodeArgs(mainFile: string): string[];
/**
* Returns the default paths used to resolve modules using `require.resolve()`
*
* @param callerModule The module that wants to resolve another module
*/
export declare function getDefaultRequireResolvePaths(callerModule: NodeModule): string[];
/**
* Tests if the given URL matches the format <githubname>/<githubrepo>[#<commit-ish>]
*
* @param url The URL to parse
*/
export declare function isShortGithubUrl(url: string): boolean;
export interface ParsedGithubUrl {
user: string;
repo: string;
commit?: string;
}
/**
* Tries to parse a URL in the format <githubname>/<githubrepo>[#<commit-ish>] into its separate parts
*
* @param url The URL to parse
*/
export declare function parseShortGithubUrl(url: string): ParsedGithubUrl | null;
/**
* Tests if the given pathname matches the format /<githubname>/<githubrepo>[.git][/<tarball|tree|archive>/<commit-ish>[.zip|.gz]]
*
* @param pathname The pathname part of a GitHub URL
*/
export declare function isGithubPathname(pathname: string): boolean;
/**
* Tries to a GitHub pathname format /<githubname>/<githubrepo>[.git][/<tarball|tree|archive>/<commit-ish>[.zip|.gz|.tar.gz]] into its separate parts
*
* @param pathname The pathname part of a GitHub URL
*/
export declare function parseGithubPathname(pathname: string): ParsedGithubUrl | null;
/**
* Removes properties which are given by preserve
*
* @param preserve - object which has true entries (or array of selected attributes) for all attributes that should be removed from currObj
* @param oldObj - old object
* @param newObj - new object
*/
export declare function removePreservedProperties(preserve: Record<string, any>, oldObj: Record<string, any>, newObj: Record<string, any>): void;
/**
* Returns the array of system.adapter.<namespace>.* objects which are created for every instance
*
* @param namespace - adapter namespace + id, e.g., hm-rpc.0
*/
export declare function getInstanceIndicatorObjects(namespace: string): ioBroker.StateObject[];
export type InternalLogger = Omit<ioBroker.Logger, 'level'>;
export declare function getLogger(log: any): InternalLogger;
/**
* Set capabilities of the given executable on Linux systems
*
* @param execPath - path to the executable for node you can determine it via process.execPath
* @param capabilities - capabilities to set, e.g. ['cap_net_admin', 'cap_net_bind_service']
* @param modeEffective - add effective mode
* @param modePermitted - add permitted mode
* @param modeInherited - add inherited mode
*/
export declare function setExecutableCapabilities(execPath: string, capabilities: string[], modeEffective?: boolean, modePermitted?: boolean, modeInherited?: boolean): Promise<void>;
/**
* Reads the licenses from iobroker.net
* Reads the licenses from iobroker.net and if no login/password provided stores it in `system.licenses`
*
* @param objects Object store instance
* @param login Login for ioBroker.net
* @param password Decoded password for ioBroker.net
* @returns array of all licenses stored on iobroker.net
*/
export declare function updateLicenses(objects: any, login: string, password: string): Promise<any[]>;
export interface GZipFileOptions {
deleteInput?: boolean;
}
/**
* Compresses an input file using GZip and writes it somewhere else
*
* @param inputFilename The filename of the input file that should be gzipped
* @param outputFilename The filename of the output file where the gzipped content should be written to
* @param options Options for the compression
*/
export declare function compressFileGZip(inputFilename: string, outputFilename: string, options?: GZipFileOptions): Promise<void>;
export interface DataDirValidation {
/** if data directory is valid */
valid: boolean;
/** absolute path it resolves too */
path: string;
/** reason of rejection */
reason: string;
}
/**
* Validate if the dir, is a valid dataDir
* Data dirs in node_modules are not allowed, note that dataDirs are relative to js-controller dir or absolute
*
* @param dataDir dataDir to check
*/
export declare function validateDataDir(dataDir: string): DataDirValidation;
/**
* If an array is passed it will be stringified, else the parameter is returned
*
* @param maybeArr parameter which will be stringified if it is an array
*/
export declare function maybeArrayToString<T>(maybeArr: T): T extends any[] ? string : T;
/**
* Checks if given ip address is matching ipv4 or ipv6 localhost
*
* @param ip ipv4 or ipv6 address
*/
export declare function isLocalAddress(ip: string): boolean;
/**
* Checks if given ip address is matching ipv4 or ipv6 "listen all" address
*
* @param ip ipv4 or ipv6 address
*/
export declare function isListenAllAddress(ip: string): boolean;
/**
* Retrieve the localhost address according to the configured DNS resolution strategy
*/
export declare function getLocalAddress(): '127.0.0.1' | '::1';
/**
* Get the ip to listen to all addresses according to configured DNS resolution strategy
*/
export declare function getListenAllAddress(): '0.0.0.0' | '::';
/**
* Ensure that DNS is resolved according to ioBroker config
*/
export declare function ensureDNSOrder(): void;
/**
* Determine if ioBroker is installed as systemd service
*/
export declare function isIoBrokerInstalledAsSystemd(): Promise<boolean>;
/**
* Get a new host object
*
* @param oldObj the previous host object
*/
export declare function getHostObject(oldObj?: ioBroker.HostObject | null): ioBroker.HostObject;
/**
* Get file name of the pids file
*
* @returns file name of the pids file
*/
export declare function getPidsFileName(): string;
/**
* Get all ioBroker process ids
*
* @returns process ids or empty array if no process running
*/
export declare function getPids(): Promise<number[]>;
/**
* Get the controller pid
*
* @returns pid if running else undefined
*/
export declare function getControllerPid(): Promise<number | undefined>;
export * from '../../lib/common/maybeCallback.js';
//# sourceMappingURL=tools.d.ts.map