+export const insertAt = (str: string, subStr: string, pos: number): string =>
+ `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
+
+/**
+ * Computes the retry delay in milliseconds using an exponential backoff algorithm.
+ *
+ * @param retryNumber - the number of retries that have already been attempted
+ * @param maxDelayRatio - the maximum ratio of the delay that can be randomized
+ * @returns delay in milliseconds
+ */
+export const exponentialDelay = (retryNumber = 0, maxDelayRatio = 0.2): number => {
+ const delay = Math.pow(2, retryNumber) * 100;
+ const randomSum = delay * maxDelayRatio * secureRandom(); // 0-(maxDelayRatio*100)% of the delay
+ return delay + randomSum;
+};
+
+const isPromisePending = (promise: Promise<unknown>): boolean => {
+ return inspect(promise).includes('pending');
+};
+
+export const promiseWithTimeout = async <T>(
+ promise: Promise<T>,
+ timeoutMs: number,
+ timeoutError: Error,
+ timeoutCallback: () => void = () => {
+ /* This is intentional */
+ },
+): Promise<T> => {
+ // Create a timeout promise that rejects in timeout milliseconds
+ const timeoutPromise = new Promise<never>((_, reject) => {
+ setTimeout(() => {
+ if (isPromisePending(promise)) {
+ timeoutCallback();
+ // FIXME: The original promise shall be canceled
+ }
+ reject(timeoutError);
+ }, timeoutMs);
+ });
+
+ // Returns a race between timeout promise and the passed promise
+ return Promise.race<T>([promise, timeoutPromise]);
+};
+
+/**
+ * Generates a cryptographically secure random number in the [0,1[ range
+ *
+ * @returns
+ */
+export const secureRandom = (): number => {
+ return randomBytes(4).readUInt32LE() / 0x100000000;
+};
+
+export const JSONStringifyWithMapSupport = (
+ obj: Record<string, unknown> | Record<string, unknown>[] | Map<unknown, unknown>,
+ space?: number,
+): string => {
+ return JSON.stringify(
+ obj,
+ (_, value: Record<string, unknown>) => {
+ if (value instanceof Map) {
+ return {
+ dataType: 'Map',
+ value: [...value],
+ };
+ }
+ return value;
+ },
+ space,
+ );
+};
+
+/**
+ * Converts websocket error code to human readable string message
+ *
+ * @param code - websocket error code
+ * @returns human readable string message
+ */
+export const getWebSocketCloseEventStatusString = (code: number): string => {
+ if (code >= 0 && code <= 999) {
+ return '(Unused)';
+ } else if (code >= 1016) {
+ if (code <= 1999) {
+ return '(For WebSocket standard)';
+ } else if (code <= 2999) {
+ return '(For WebSocket extensions)';
+ } else if (code <= 3999) {
+ return '(For libraries and frameworks)';
+ } else if (code <= 4999) {
+ return '(For applications)';