///
import { Request, RequestInit, Response } from 'node-fetch';
import AsymmetricKeyPairs from '../main/internalApi/asymmetricKeyPairs';
import { AuthToken } from '../main/definitions/internal';
import { InternalServerConfig } from '../main/config/definitions/main/serverConfig';
import ServiceEngine from '../main/services/serviceEngine';
import { LogAPI } from '../main/log/logger';
import { ApiLevelSwitch, ApiLevelSwitchFunction } from '../main/apiLevel/apiLevelUtils';
import { DataboxClass } from './databox/Databox';
import DataboxContainer from './databox/container/databoxContainer';
import StaticDataboxContainer from './databox/container/staticDataboxContainer';
import { StaticDataboxClass } from './databox/StaticDatabox';
import { AnyChannelClass } from './channel/AnyChannelClass';
import { AnyDataboxClass } from './databox/AnyDataboxClass';
import { ChannelClass } from './channel/Channel';
import ChannelContainer from './channel/container/channelContainer';
import { StaticChannelClass } from './channel/StaticChannel';
import StaticChannelContainer from './channel/container/staticChannelContainer';
import Socket from './Socket';
import { AnyClass, Prototype } from '../main/utils/typeUtils';
import ZationToken from '../main/internalApi/zationToken';
import { AppConfig } from '../main/config/definitions/main/appConfig';
import { ServicesConfig } from '../main/config/definitions/main/servicesConfig';
import ZationServer from '../core/ZationServer';
import ConfigProvider from '../main/config/management/configProvider';
import { Server as CoreServer } from 'ziron-worker';
import { SignOptions, VerifyOptions } from 'jsonwebtoken';
import { RawSocket } from '../main/definitions/rawSocket';
import { ServerState } from './ServerState';
import { CleanupFunc } from '../main/utils/exitEngine';
import { License } from '../main/utils/licenseManager';
/**
* The bag instance of this process.
* and the bag instance is ready for use.
* Otherwise, it will throw an error when using this
* instance in an unready state or in a wrong context.
* You can be sure that the bag is already ready for use when
* using this variable in a event.
* But if you need to wait until the bag instance is ready for use,
* you should look at the static method Bag.ready, that returns a promise.
* @readonly
*/
export declare let bag: Bag;
export default class Bag {
protected readonly serviceEngine: ServiceEngine;
protected readonly cp: ConfigProvider;
/**
* @description
* The zation server instance.
*/
readonly server: ZationServer;
private static _instance;
private static readyPromise;
private static readyResolve;
private static readyRefresher;
protected constructor(server: ZationServer);
/**
* With this method, you can wait with the returned promise
* until the instance of the bag is ready for use.
* If the promise is resolved or you be sure that the bag is already
* ready for use, you can use the variable 'bag' to access the instance of the bag.
*/
static ready(): Promise;
/**
* @description
* Returns the config provider.
*/
get config(): ConfigProvider;
/**
* @description
* Returns the server config.
*/
get serverConfig(): InternalServerConfig;
/**
* @description
* Returns the app config.
*/
get appConfig(): AppConfig;
/**
* @description
* Returns the services config.
*/
get servicesConfig(): ServicesConfig;
/**
* @description
* Returns the server config variables.
* You can define them in the variables property of the server config.
*/
getServerConfigVariables(): V;
/**
* @description
* Returns the name of the default user group.
*/
get defaultUserGroupName(): string;
/**
* @description
* Checks if it is a valid auth user group.
*/
isValidAuthUserGroup(str: string): boolean;
/**
* @description
* Returns an array with all auth user group names.
*/
get authUserGroupNames(): string[];
/**
* @description
* Returns the root path of the project.
* In a typescript project, it will return the path to the dist folder.
*/
get rootPath(): string;
/**
* @description
* Returns the server ip address.
*/
get serverIpAddress(): string;
/**
* @description
* Returns the server port.
*/
get serverPort(): number;
/**
* @description
* Returns the server state.
*/
get serverState(): ServerState;
/**
* @description
* Returns the server id.
*/
get serverId(): string;
/**
* @description
* Returns a unique id for the hardware machine (based on mac address).
*/
get machineId(): string;
/**
* @description
* Returns the tags of the server.
*/
get serverTags(): Readonly<[string, string?][]>;
/**
* @description
* Returns the app name.
*/
get appName(): string;
/**
* @description
* Returns if the server is running in debug mode.
*/
get debug(): boolean;
/**
* @description
* Returns the server hostname.
*/
get serverHostname(): string;
/**
* @description
* Returns if the server is running with tls.
*/
get secure(): boolean;
/**
* @description
* Returns the server path.
*/
get serverPath(): string;
/**
* @description
* Returns if the server is running in launch debug mode.
*/
get launchDebug(): boolean;
/**
* @description
* Returns the server version.
*/
get serverVersion(): string;
/**
* @description
* Returns the launch timestamp of this server.
*/
get launchTimestamp(): number;
/**
* @description
* Returns the timestamp when the server has launched.
*/
get launchedTimestamp(): number;
/**
* @description
* Returns if the server is linked to a cluster.
*/
get clusterLinked(): boolean;
/**
* @description
* Returns the core server instance.
* Only for advanced use cases.
*/
get coreServer(): CoreServer;
/**
* @description
* Returns if this server instance is the leader of the cluster.
* Notice that it can change over time.
* If the cluster mode is not active (no join configured in the server config)
* it will always return true.
*/
get clusterLeader(): boolean;
/**
* @description
* Returns the server url with protocol,hostname and port.
* @example
* https://myhost:3000
*/
get serverUrl(): string;
/**
* @description
* Returns the ws handshake url (protocol,hostname,port and path).
* @example
* wss://myhost:3000/path
*/
get wsHandshakeUrl(): string;
get license(): License | undefined;
/**
* @description
* Returns the average Cpu usage in percentage of this server machine.
* Notice that the measurement will take at least 1 second.
*/
getCpuUsage(): Promise;
/**
* @description
* Returns the total and used memory in MB of this server.
*/
getMemoryUsage(): Promise<{
totalMemMb: number;
usedMemMb: number;
}>;
/**
* Returns the CPU usage in percentage and
* the memory usage in MB of this process.
*/
getPidUsage(): Promise<{
cpu: number;
memory: number;
}>;
/**
* @description
* Returns the name of the server os.
* @example
* 'Mac OS X 10.15', 'Microsoft Windows 7 Enterprise', 'Linux 4.4.0-112-generic'
*/
getOsName(): Promise;
/**
* @description
* Generates a random string.
* @param length
*/
generateRandomString(length?: number): string;
/**
* @description
* Generates a random number with fixed digits count.
* @param digits
*/
generateFixedRandomNumber(digits?: number): number;
/**
* @description
* Generates a random int in a range.
* @param min (inclusive)
* @param max (inclusive)
*/
generateRandomIntInRange(min?: number, max?: number): number;
/**
* @description
* Generates a random float in range.
* @param min (inclusive)
* @param max (exclusive)
*/
generateRandomFloatInRange(min?: number, max?: number): number;
/**
* @description
* Generates a random boolean.
* @param chanceForTrue
*/
generateRandomBoolean(chanceForTrue?: number): boolean;
/**
* @description
* Generates random bytes asynchronously.
* @param size The number of bytes to generate.
*/
generateRandomBytes(size?: number): Promise;
/**
* @description
* Returns a random item of the given array.
* If the array is empty, it returns undefined.
* @param array
*/
getRandomArrayItem(array: T[]): T | undefined;
/**
* @description
* Provides an asynchronous scrypt implementation.
* Scrypt is a password-based key derivation function designed to be expensive
* computationally and memory-wise to make brute-force attacks unrewarding.
* @param password
* @param salt
* This value should be as unique as possible.
* This is mainly used for encrypting the data.
* The minimum suggested length of salt is 16 bytes.
* @param keyLength
* @param binary
* @param blockSize
* @param cost
* @param maxmem
* @param parallelization
*/
scrypt(password: string | Buffer | NodeJS.TypedArray, salt: string | Buffer | NodeJS.TypedArray, { keyLength, binary, blockSize, cost, maxmem, parallelization }?: {
/**
* @description
* CPU/memory cost parameter.
* Must be a power of two greater than one.
* @default 16384
*/
cost?: number;
/**
* @description
* Block size parameter.
* @default 8
*/
blockSize?: number;
/**
* @description
* Parallelization parameter.
* @default 1
*/
parallelization?: number;
/**
* @description
* Memory upper bound.
* It is an error when (approximately) 128 * N * r > maxmem.
* @default 32 * 1024 * 1024
*/
maxmem?: number;
/**
* @description
* The key length.
* @default 32
*/
keyLength?: number;
/**
* @description
* Indicates if the method should return the key in binary.
* Otherwise, it returns it as a hex string.
* @default false
*/
binary?: B;
}): Promise;
/**
* @description
* Creates a sha512 hash from the given string.
* @param string
* @param salt
*/
hashSha512(string: string, salt?: string): string;
/**
* @description
* Creates a hash from the given string with the specified algorithms.
* @param algorithm
* @param string
* @param salt
*/
hash(algorithm: string, string: string, salt?: string): string;
/**
* @description
* Generates a private and public key pair for RSA asymmetric Encryption.
* @example
* const { privateKey, publicKey } = await generateRsaAsymmetricKeyPair();
*/
generateRsaAsymmetricKeyPair(): Promise;
/**
* Generates a private and public key pair for ECC asymmetric Sign/Verify.
* @example
* const { privateKey, publicKey } = await generateEccAsymmetricKeyPair();
*/
generateEccAsymmetricKeyPair(): Promise;
/**
* @description
* Creates a signature from the data with a private key and returns the signature.
* It will hash the data with SHA256 and encrypts it using RSA.
* @example
* const signature = await asymmetricRsaSign(data,privateKey);
* @param data
* @param privateKey
*/
asymmetricRsaSign(data: string, privateKey: string): Promise;
/**
* @description
* Verify the signature with the public key and the data.
* It returns if the signature is valid.
* It uses the SHA256 and RSA algorithm.
* @example
* const signature = await asymmetricRsaVerify(data,publicKey,signature);
* @param data
* @param publicKey
* @param signature
*/
asymmetricRsaVerify(data: string, publicKey: string, signature: string): Promise;
/**
* @description
* Creates a signature from data with a private key and returns the signature.
* It will hash the data with SHA256 and encrypts it using ECC (Elliptic curve cryptography).
* @example
* const signature = await asymmetricEccSign(data,privateKey);
* @param data
* @param privateKey
* @param encoding
*/
asymmetricEccSign(data: string | Buffer, privateKey: string, encoding?: string): string;
/**
* @description
* Verify the signature with the public key and the data.
* It returns if the signature is valid.
* It uses the SHA256 and ECC (Elliptic curve cryptography) algorithm.
* @example
* const signature = await asymmetricEccVerify(data,publicKey,signature);
* @param data
* @param publicKey
* @param signature
* @param encoding
*/
asymmetricEccVerify(data: string, publicKey: string, signature: string, encoding?: string): boolean;
/**
* @description
* Encrypts data with the public key and returns the encrypted data.
* It's using the asymmetric RSA encryption algorithm.
* Due to technical limitations of the RSA algorithm,
* the text to be encrypted can not be longer than 215 bytes when using keys with 2048 bits.
* @example
* const encryptedMessage = await asymmetricRsaEncrypt('MY-MESSAGE','PUBLIC-KEY');
* @param data
* @param publicKey
*/
asymmetricRsaEncrypt(data: string, publicKey: string): Promise;
/**
* @description
* Decrypts with the RSA algorithm the encrypted data
* with the private key and returns the decrypted message.
* @example
* const decryptedMessage = await asymmetricRsaDecrypt('ENCRYPTED-MESSAGE','PRIVATE-KEY');
* @param encryptedData
* @param privateKey
*/
asymmetricRsaDecrypt(encryptedData: string, privateKey: string): Promise;
/**
* @description
* Generates an password that you can use for symmetric encryption.
* @example
* const password = await generatePassword();
* @param secret
*/
generatePassword(secret?: String): Promise;
/**
* @description
* Generates an initialization vector that you can use for symmetric encryption.
* @example
* const iv = await generateIv();
*/
generateIv(): Promise;
/**
* @description
* Encrypts a message with a password and initialization vector and returns the encrypted message.
* It uses the aes256cbc algorithm.
* @example
* const encryptedMessage = await symmetricEncrypt('secret information',password,iv);
* @param message
* @param password
* @param iv
*/
symmetricEncrypt(message: string, password: string, iv: string): Promise;
/**
* @description
* Decrypts a message with a password and initialization vector and returns the decrypted message.
* It uses the aes256cbc algorithm.
* @example
* const password = await symmetricDecrypt(encryptedMessage,password,iv);
* @param encryptedMessage
* @param password
* @param iv
*/
symmetricDecrypt(encryptedMessage: string, password: string, iv: string): Promise;
/**
* @description
* Returns an generated uuid v4.
*/
generateUUIDv4(): string;
/**
* @description
* Returns an generated unique id.
* By using npm package 'uniqid'.
*/
generateUniqueId(): string;
/**
* @description
* Creates a cleaner that will be called when the server is about to exit.
* Don't run long tasks; otherwise, it can happen that the server process gets
* terminated before the cleaner was processed fully.
* The returned function can be used to remove the cleaner again;
* this is useful to create a temporary cleaner.
* @param handler
*/
cleanup(handler: CleanupFunc): () => void;
/**
* @description
* When the server is about to exit, it waits for fulfilment or rejection of multiple promises in a list.
* You can add a promise to the list with this function.
* The promise will be automatically removed when it fulfils or rejects before the exit case happens.
* But you also can remove the promise manually from the list by calling the returned function.
* @param promise
*/
exitAwait(promise: Promise): () => void;
/**
* Returns a promise that will be resolved in the defined time (milliseconds).
* Can be used to let the server wait a specific amount of time.
* @param milliseconds
* @example
* await wait(2000);
*/
wait(milliseconds: number): Promise;
/**
* Creates an asynchronous interval iterator.
* @example
* let i = 0;
* for await (const clear of interval(2000)){
* i++;
* if(i > 10) {
* clear();
* }
* }
* @param milliseconds
*/
interval(milliseconds: number): {
[Symbol.asyncIterator]: () => {
next: () => Promise<{
done: boolean;
value: () => void;
}>;
};
};
/**
* @description
* Creates a raw zation token.
* Can be signed by using the sign token method on the bag.
* @example
* createRawZationToken('user','tom12',{email: 'example@gmail.com'});
* @param authUserGroup
* The authUserGroup must exist in the app config.
* Otherwise, an error will be thrown.
* @param userId
* @param payload
* Sets the payload of the token.
* @throws UnknownAuthUserGroupError
*/
createRawZationToken(authUserGroup: string, userId?: string | number, payload?: Partial): AuthToken>;
/**
* Signs a zation token.
* A perfect use case for this method is to sign tokens in an HTTP endpoint.
* But use this method carefully and only sign authorized clients.
* Because the token can also be used for zation components on the WebSocket base.
* @param authUserGroup
* @param userId
* @param payload
* @param signOptions
*/
signZationToken(authUserGroup: string, userId?: string | number, payload?: object, signOptions?: SignOptions): Promise;
/**
* @description
* Verifies a Zation token.
* This method will also check the structure of the token and
* converts the raw token to a ZationToken instance.
* A perfect use case for this method is to verify tokens in an HTTP middleware.
* @param signedToken
* @throws AuthTokenExpiredError, AuthTokenInvalidError,AuthTokenNotBeforeError, AuthTokenError or
* BackError with names: TokenWithAuthUserGroupAndOnlyPanel, TokenSavedAuthUserGroupNotFound or TokenWithoutAuthUserGroup.
*/
verifyZationToken(signedToken: string): Promise>;
/**
* @description
* Signs a token.
* This method is only for advanced use cases.
* It will not create a token that is based on the zation token structure,
* also it will not attach this token to any client or request.
* It will use the default server settings,
* but you can override some options by providing jwt sign options as a second argument.
* The return value is the signed token as a string.
* @example
* await signToken({age: 21},{expiresIn: 200});
* @param data
* @param signOptions
*/
signToken(data: object, signOptions?: SignOptions): Promise;
/**
* @description
* Verifies a token.
* This method can be used to verify signed tokens.
* This method is only for advanced use cases.
* It will use the default server settings,
* but you can override some options by providing jwt verify options as a second argument.
* The return value is the plain decrypted token.
* @example
* await verifyToken('djf09ejd103je32ije0');
* @param signedToken
* @param verifyOptions
* @throws AuthTokenExpiredError, AuthTokenInvalidError,AuthTokenNotBeforeError or AuthTokenError
*/
verifyToken(signedToken: string, verifyOptions?: VerifyOptions): Promise>;
/**
* Checks if a specific port is available (closed).
* @param port
* @param host
*/
isPortAvailable(port: number, host?: string): Promise;
/**
* Finds the first port that is not in use (Closed).
* @param ports
* @param host
*/
findAPortNotInUse(ports: number[], host?: string): Promise;
/**
* Finds the first port that is in use (Open or blocked).
* @param ports
* @param host
*/
findAPortInUse(ports: number[], host?: string): Promise;
/**
* @description
* Returns the service when it exists; otherwise,
* it will throw a ServiceNotFoundError error.
* @throws ServiceNotFoundError
* @param serviceName
* @param instanceName Default: 'default'
*/
getService(serviceName: string, instanceName?: string): Promise;
/**
* @description
* This function returns a boolean that indicates if the service exists.
* @param serviceName
* @param instanceName Default: 'default'
*/
hasService(serviceName: string, instanceName?: string): boolean;
/**
* @description
* Returns the logger.
* This gives you the possibility to log information into the console, a log file or the panel.
* You can explicitly specify if global or local logging should be used.
* The defaultGlobal option defines what logging should be used when it is not explicitly specified.
* Global logging combines local (console or file) and remote (panel) logging.
* Notice that the server config settings are considered.
* @example
* //default logging (depends on defaultGlobal option)
* log.debug('Some debug message');
* //explicitly global
* log(true).info("Hello");
* //explicitly local
* log(false).info("Hello");
*/
get log(): LogAPI;
/**
* @description
* Fetch method witch can be use to make an http request.
* Look in npm package 'node-fetch'.
* @param url
* @param init
* @example
* fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' })
* .then(res => res.json()) // expecting a json response
* .then(json => console.log(json));
*/
fetch(url: string | Request, init?: RequestInit): Promise;
/**
* @description
* Disconnects all sockets with a specific user id (on every server).
* @example
* disconnectUser(['tim902','leonie23']);
* disconnectUser('tim902');
* disconnectUser('tim902','EXCEPT-SOCKET-SID');
* @param userId or more userIds in an array.
* @param info
* @param exceptSocketSids
*/
disconnectUser(userId: number | string | (number | string)[], info?: {
code?: any;
data?: any;
}, exceptSocketSids?: string[] | string): void;
/**
* @description
* Disconnects all sockets with a specific token id (on every server).
* @example
* disconnectToken(['TOKEN-UUID1','TOKEN-UUID2']);
* disconnectToken('TOKEN-UUID1');
* disconnectToken('TOKEN-UUID1','EXCEPT-SOCKET-SID');
* @param tokenId or more tokenIds in an array.
* @param info
* @param exceptSocketSids
*/
disconnectTokens(tokenId: string | string[], info?: {
code?: any;
data?: any;
}, exceptSocketSids?: string[] | string): void;
/**
* @description
* Disconnect all sockets (on every server).
* @example
* disconnectAllSockets('EXCEPT-SOCKET-SID');
* @param info
* @param exceptSocketSids
*/
disconnectAllSockets(info?: {
code?: any;
data?: any;
}, exceptSocketSids?: string[] | string): void;
/**
* @description
* Disconnect all sockets with a specific sid (on every server).
* @example
* disconnectSockets(['SOCKET-SID-1','SOCKET-SID-2']);
* disconnectSockets('SOCKET-SID');
* @param socketSid or more socketSids in an array.
* @param info
*/
disconnectSockets(socketSid: string | string[], info?: {
code?: any;
data?: any;
}): void;
/**
* @description
* Disconnect all sockets that belong to a specific auth user group (on every server).
* @example
* disconnectAuthUserGroups('admin');
* disconnectAuthUserGroups(['user','admin'],'EXCEPT-SOCKET-SID');
* @param authUserGroup or more authUserGroups in an array
* or true witch stands for all auth user groups
* @param info
* @param exceptSocketSids
*/
disconnectAuthUserGroups(authUserGroup: string | true | (string)[], info?: {
code?: any;
data?: any;
}, exceptSocketSids?: string[] | string): void;
/**
* @description
* Disconnect all sockets that belong to the default user group (on every server).
* @example
* disconnectDefaultUserGroup();
* disconnectDefaultUserGroup('EXCEPT-SOCKET-SID');
* @param info
* @param exceptSocketSids
*/
disconnectDefaultUserGroup(info?: {
code?: any;
data?: any;
}, exceptSocketSids?: string[] | string): void;
/**
* @description
* Deauthenticate all sockets with a specific user id (on every server).
* @example
* deauthenticateUser(['tim902','leonie23']);
* deauthenticateUser('tim902');
* deauthenticateUser('tim902','EXCEPT-SOCKET-SID');
* @param userId or more userIds in an array.
* @param exceptSocketSids
*/
deauthenticateUser(userId: number | string | (number | string)[], exceptSocketSids?: string[] | string): void;
/**
* @description
* Deauthenticate all sockets with a specific token id (on every server).
* @example
* deauthenticateToken(['TOKEN-UUID1','TOKEN-UUID2']);
* deauthenticateToken('TOKEN-UUID2');
* deauthenticateToken('TOKEN-UUID2','EXCEPT-SOCKET-SID');
* @param tokenId or more tokenIds in an array.
* @param exceptSocketSids
*/
deauthenticateTokens(tokenId: string | string[], exceptSocketSids?: string[] | string): void;
/**
* @description
* Deauthenticate all sockets (on every server).
* @example
* deauthenticateAllSockets('EXCEPT-SOCKET-SID');
* @param exceptSocketSids
*/
deauthenticateAllSockets(exceptSocketSids?: string[] | string): void;
/**
* @description
* Deauthenticate all sockets with a specific sid (on every server).
* @example
* deauthenticateSockets(['SOCKET-SID-1','SOCKET-SID-2']);
* deauthenticateSockets('SOCKET-SID');
* @param socketSid or more socketSids in an array.
*/
deauthenticateSockets(socketSid: string | string[]): void;
/**
* @description
* Deauthenticate all sockets that belong to a specific auth user group (on every server).
* @example
* deauthenticateAuthUserGroups('admin');
* deauthenticateAuthUserGroups(['user','admin'],'EXCEPT-SOCKET-SID');
* @param authUserGroup or more authUserGroups in an array
* or true witch stands for all auth user groups
* @param exceptSocketSids
*/
deauthenticateAuthUserGroups(authUserGroup: string | true | (string)[], exceptSocketSids?: string[] | string): void;
/**
* @description
* Returns the socket id from a socket sid.
* @example
* socketSidToSocketId('SOCKET-SID');
* @param socketSid
*/
socketSidToSocketId(socketSid: string): string;
/**
* @description
* Returns the server instance id from a socket sid.
* @example
* socketSidToSeverId(SOCKET-SID');
* @param socketSid
*/
socketSidToSeverId(socketSid: string): string;
/**
* @description
* Edit the auth token payload on all tokens with a specific user id.
* When using the bundle option, you can make several changes in one action.
* Don't forget to call the commit method after your changes in bundle mode.
* Every change on the token of a socket will update the authentication
* of this socket. (Like a new authentication on top).
* You can access the token payload on the client and server-side.
* But only delete or set from the server-side.
* @example
* //Single change
* editAuthTokenPayloadOnUserId('USER_ID').name = 'Luc';
* //Multiple changes
* const payloadEdit = editAuthTokenPayloadOnUserId('USER_ID',{seq: true});
* payloadEdit.name = "Lara";
* payloadEdit.age = 22;
* payloadEdit.commit();
* @param userId
* @param exceptSocketSids
* @param seq
*/
editAuthTokenPayloadOnUserId(userId: string | number, { exceptSocketSids, bundle }?: {
exceptSocketSids?: string[] | string;
bundle?: B;
}): true extends B ? import("../main/internalApi/pathEditContentAPICreator").PathEditContentBundle : import("../main/internalApi/pathEditContentAPICreator").PathEditContent;
/**
* @description
* Edit the auth token payload on all tokens with a specific auth user group.
* When using the bundle option, you can make several changes in one action.
* Don't forget to call the commit method after your changes in bundle mode.
* Every change on the token of a socket will update the authentication
* of this socket. (Like a new authentication on top).
* You can access the token payload on the client and server-side.
* But only delete or set from the server-side.
* @example
* //Single change
* editAuthTokenPayloadOnGroup('USER_GROUP').name = 'Luc';
* //Multiple changes
* const payloadEdit = editAuthTokenPayloadOnGroup('USER_GROUP',{seq: true});
* payloadEdit.age = 22;
* delete payloadEdit.car;
* payloadEdit.commit();
* @param authUserGroup
* @param exceptSocketSids
* @param seq
*/
editAuthTokenPayloadOnGroup(authUserGroup: string, { exceptSocketSids, bundle }?: {
exceptSocketSids?: string[] | string;
bundle?: B;
}): true extends B ? import("../main/internalApi/pathEditContentAPICreator").PathEditContentBundle : import("../main/internalApi/pathEditContentAPICreator").PathEditContent;
/**
* Build a closure for selecting the API level.
* The closure will return the correct mapped value with the best compatible API level.
* If there is no compatible API level, the closure returns undefined.
* Notice if you always have a 1 in the mapped values as an API level the closure will always return a value.
* @param apiLevelSwitch
* @example
* const switch = createApiLevelSwitcher({
* 1: 'apiLevel1',
* 5: 'apiLevel5',
* 8: 'apiLevel8',
* 2: 'apiLevel2'
* });
* switch(7); // apiLevel 5
* switch(20); // apiLevel 8
* switch(1); // apiLevel 1
*/
createApiLevelSwitcher(apiLevelSwitch: ApiLevelSwitch): ApiLevelSwitchFunction;
/**
* @description
* Calculates the byte size of an encoded base64 string.
* @example
* base64ByteSize("ENCODED-BASE64");
* @param encodedBase64
* The encoded base64 string.
*/
base64ByteSize(encodedBase64: string): number;
/**
* @description
* Returns the mimeType and mimeSubType of an encoded base64 string.
* @example
* base64ContentInfo("ENCODED-BASE64");
* @param encodedBase64
* The encoded base64 string.
* @return
* Can be null if the base64 string has no content type.
* Otherwise, it is an object with the properties: mimeSubType (png,jpg...), mimeType (image,video...).
*/
base64ContentInfo(encodedBase64: string): null | {
mimeSubType: string;
mimeType: string;
};
/**
* Encodes a string or buffer to a base64 string.
* @param input
* @param urlSafe
* Indicates if the base64 string should be URL safe.
* @param encoding
* The encoding of the provided input. Default to utf8.
*/
base64Encode(input: string | Buffer, urlSafe?: boolean, encoding?: BufferEncoding): string;
/**
* Decodes a base64 string.
* @param base64
* @param urlSafe
* Indicates if the encoded base64 string is URL safe.
* @param encoding
* The expected encoding of the decoded result. Default to utf8.
*/
base64Decode(base64: string, urlSafe?: boolean, encoding?: BufferEncoding): string;
/**
* @description
* Calculates the byte size of an utf-8 string.
* By using the npm package byte-length.
* @example
* stringByteSize("UTF-8_STRING");
* @param string
* The utf-8 string.
*/
stringByteSize(string: string): number;
/**
* @description
* Returns the Socket with the corresponding socket id.
* Notice that you only have access to the sockets
* which are connected to the current server.
* @example
* getSocket('SOCKET-ID');
* @param id
*/
getSocket(id: string): Socket | undefined;
/**
* @description
* Returns the sockets of the current server.
*/
get sockets(): Socket[];
/**
* @description
* Returns the count of connected clients to the current server.
*/
get clientsCount(): number;
/**
* @description
* Returns the sockets with a specific token id.
* Notice that you only have access to the sockets
* which are connected to the current server.
* @example
* getSocketsWithTokenId('TOKEN-ID');
* @param tokenId
*/
getSocketsWithTokenId(tokenId: string): Socket[];
/**
* @description
* Returns the sockets with a specific user id.
* Notice that you only have access to the sockets
* which are connected to the current server.
* @example
* getSocketsWithUserId('tom1554');
* @param userId
*/
getSocketsWithUserId(userId: string): Socket[];
/**
* @description
* Returns an object with authUserGroups as keys and the count of corresponding
* connected clients as a value (only of the current server).
*/
getAuthUserGroupsCounts(): Record;
/**
* @description
* Returns the count of the connected clients which belongs
* to the default user group (only of the current server).
*/
getDefaultUserGroupCount(): number;
/**
* @description
* Returns the count of connected
* panel clients (only of the current server).
*/
getPanelClientsCount(): number;
/**
* @description
* Returns the count of the connected clients which belongs
* to a specific auth user group (only of the current server).
*/
getAuthUserGroupCount(authUserGroup: string): number;
/**
* @description
* Returns an object with authUserGroups as keys and corresponding
* sockets of that user group as a value (only of the current server).
*/
getAuthUserGroupsSockets(): Record;
/**
* @description
* Returns an array of sockets which belongs to
* the default user group (only of the current server).
*/
getDefaultUserGroupSockets(): Socket[];
/**
* @description
* Returns an array of panel
* sockets (only of the current server).
*/
getPanelSockets(): Socket[];
/**
* @description
* Returns an array of sockets which belongs to
* a specific auth user group (only of the current server).
*/
getAuthUserGroupSockets(authUserGroup: string): Socket[];
/**
* @description
* Filter object properties by keys.
* @param obj
* @param keys
*/
filterObject(obj: T, ...keys: K): {
[K2 in Extract]: T[K2];
};
/**
* @description
* Deep clones any value.
* Notice that it only clones
* enumerable properties of an object.
* @param value
*/
deepClone(value: T): T;
/**
* @description
* Returns if the two given values are deeply equal.
* @param v1
* @param v2
*/
deepEqual(v1: any, v2: any): boolean;
/**
* @description
* Deep freezes object/functions deep and safe.
* @param value
*/
deepFreeze(value: T): T;
/**
* This method will create a JSON string from a value.
* It can also handle circular dependencies.
* @param value
*/
jsonStringifySafe(value: any): string;
/**
* @description
* This function helps to access your Singletons, Channels and Databoxes.
* You only need to call this method with the class/es and it returns the specific instance/s.
* If you want to access multiple Databoxes or Channels, the method returns a StaticDatabox/StaticChannelContainer
* or Databox/ChannelContainer.
* With these containers, you can interact with multiple Databoxes or Channels.
* So, for example, if you have two Databoxes/Channels with different API levels
* from the same type, you can communicate directly with both.
* But notice that the containers only provides a limited scope of methods.
* If you provide multiple Singletons the function will return an array with all instances.
* It is recommended if you use this method in a component that you prepare the access
* in the initialize method.
* If you use this method in an event function, use an initEvent to prepare the access.
* @example
* get(NavigatorManager)
* get(NavigatorManager,DbManager)
* get(ProfileDatabox_1,ProfileDatabox_2);
* get(PublicChatDatabox);
* get(ChatChannel_1,ChatChannel_2);
* get(InfoChannel);
*/
get(): undefined;
/**
* @description
* This function helps to access your Singletons, Channels and Databoxes.
* You only need to call this method with the class/es and it returns the specific instance/s.
* If you want to access multiple Databoxes or Channels, the method returns a StaticDatabox/StaticChannelContainer
* or Databox/ChannelContainer.
* With these containers, you can interact with multiple Databoxes or Channels.
* So, for example, if you have two Databoxes/Channels with different API levels
* from the same type, you can communicate directly with both.
* But notice that the containers only provides a limited scope of methods.
* If you provide multiple Singletons the function will return an array with all instances.
* It is recommended if you use this method in a component that you prepare the access
* in the initialize method.
* If you use this method in an event function, use an initEvent to prepare the access.
* @example
* get(NavigatorManager)
* get(NavigatorManager,DbManager)
* get(ProfileDatabox_1,ProfileDatabox_2);
* get(PublicChatDatabox);
* get(ChatChannel_1,ChatChannel_2);
* get(InfoChannel);
*/
get(classDef: T): T['prototype'];
/**
* @description
* This function helps to access your Singletons, Channels and Databoxes.
* You only need to call this method with the class/es and it returns the specific instance/s.
* If you want to access multiple Databoxes or Channels, the method returns a StaticDatabox/StaticChannelContainer
* or Databox/ChannelContainer.
* With these containers, you can interact with multiple Databoxes or Channels.
* So, for example, if you have two Databoxes/Channels with different API levels
* from the same type, you can communicate directly with both.
* But notice that the containers only provides a limited scope of methods.
* If you provide multiple Singletons the function will return an array with all instances.
* It is recommended if you use this method in a component that you prepare the access
* in the initialize method.
* If you use this method in an event function, use an initEvent to prepare the access.
* @example
* get(NavigatorManager)
* get(NavigatorManager,DbManager)
* get(ProfileDatabox_1,ProfileDatabox_2);
* get(PublicChatDatabox);
* get(ChatChannel_1,ChatChannel_2);
* get(InfoChannel);
*/
get(...databoxes: DataboxClass[]): DataboxContainer;
/**
* @description
* This function helps to access your Singletons, Channels and Databoxes.
* You only need to call this method with the class/es and it returns the specific instance/s.
* If you want to access multiple Databoxes or Channels, the method returns a StaticDatabox/StaticChannelContainer
* or Databox/ChannelContainer.
* With these containers, you can interact with multiple Databoxes or Channels.
* So, for example, if you have two Databoxes/Channels with different API levels
* from the same type, you can communicate directly with both.
* But notice that the containers only provides a limited scope of methods.
* If you provide multiple Singletons the function will return an array with all instances.
* It is recommended if you use this method in a component that you prepare the access
* in the initialize method.
* If you use this method in an event function, use an initEvent to prepare the access.
* @example
* get(NavigatorManager)
* get(NavigatorManager,DbManager)
* get(ProfileDatabox_1,ProfileDatabox_2);
* get(PublicChatDatabox);
* get(ChatChannel_1,ChatChannel_2);
* get(InfoChannel);
*/
get(...databoxes: StaticDataboxClass[]): StaticDataboxContainer;
/**
* @description
* This function helps to access your Singletons, Channels and Databoxes.
* You only need to call this method with the class/es and it returns the specific instance/s.
* If you want to access multiple Databoxes or Channels, the method returns a StaticDatabox/StaticChannelContainer
* or Databox/ChannelContainer.
* With these containers, you can interact with multiple Databoxes or Channels.
* So, for example, if you have two Databoxes/Channels with different API levels
* from the same type, you can communicate directly with both.
* But notice that the containers only provides a limited scope of methods.
* If you provide multiple Singletons the function will return an array with all instances.
* It is recommended if you use this method in a component that you prepare the access
* in the initialize method.
* If you use this method in an event function, use an initEvent to prepare the access.
* @example
* get(NavigatorManager)
* get(NavigatorManager,DbManager)
* get(ProfileDatabox_1,ProfileDatabox_2);
* get(PublicChatDatabox);
* get(ChatChannel_1,ChatChannel_2);
* get(InfoChannel);
*/
get(...channels: ChannelClass[]): ChannelContainer;
/**
* @description
* This function helps to access your Singletons, Channels and Databoxes.
* You only need to call this method with the class/es and it returns the specific instance/s.
* If you want to access multiple Databoxes or Channels, the method returns a StaticDatabox/StaticChannelContainer
* or Databox/ChannelContainer.
* With these containers, you can interact with multiple Databoxes or Channels.
* So, for example, if you have two Databoxes/Channels with different API levels
* from the same type, you can communicate directly with both.
* But notice that the containers only provides a limited scope of methods.
* If you provide multiple Singletons the function will return an array with all instances.
* It is recommended if you use this method in a component that you prepare the access
* in the initialize method.
* If you use this method in an event function, use an initEvent to prepare the access.
* @example
* get(NavigatorManager)
* get(NavigatorManager,DbManager)
* get(ProfileDatabox_1,ProfileDatabox_2);
* get(PublicChatDatabox);
* get(ChatChannel_1,ChatChannel_2);
* get(InfoChannel);
*/
get(...channels: StaticChannelClass[]): StaticChannelContainer;
/**
* @description
* This function helps to access your Singletons, Channels and Databoxes.
* You only need to call this method with the class/es and it returns the specific instance/s.
* If you want to access multiple Databoxes or Channels, the method returns a StaticDatabox/StaticChannelContainer
* or Databox/ChannelContainer.
* With these containers, you can interact with multiple Databoxes or Channels.
* So, for example, if you have two Databoxes/Channels with different API levels
* from the same type, you can communicate directly with both.
* But notice that the containers only provides a limited scope of methods.
* If you provide multiple Singletons the function will return an array with all instances.
* It is recommended if you use this method in a component that you prepare the access
* in the initialize method.
* If you use this method in an event function, use an initEvent to prepare the access.
* @example
* get(NavigatorManager)
* get(NavigatorManager,DbManager)
* get(ProfileDatabox_1,ProfileDatabox_2);
* get(PublicChatDatabox);
* get(ChatChannel_1,ChatChannel_2);
* get(InfoChannel);
*/
get(...classDef: T): {
[i in keyof T]: Prototype;
} & {
length: T['length'];
};
}