swaf/src/Utils.ts

60 lines
1.6 KiB
TypeScript

import * as crypto from "crypto";
export async function sleep(ms: number): Promise<void> {
return await new Promise(resolve => {
setTimeout(() => resolve(), ms);
});
}
export abstract class WrappingError extends Error {
public readonly cause?: Error;
protected constructor(message: string, cause?: Error) {
super(message);
this.cause = cause;
if (cause !== undefined) {
this.stack = (this.stack || '') + `\n> Caused by: ${cause.stack}`;
}
}
get name(): string {
return this.constructor.name;
}
}
export function cryptoRandomDictionary(size: number, dictionary: string): string {
const randomBytes = crypto.randomBytes(size);
const output = new Array(size);
for (let i = 0; i < size; i++) {
output[i] = dictionary[Math.floor((randomBytes[i] / 255) * dictionary.length)];
}
return output.join('');
}
export type Type<T> = { new(...args: any[]): T };
export function bufferToUUID(buffer: Buffer): string {
const chars = buffer.toString('hex');
let out = '';
let i = 0;
for (const l of [8, 4, 4, 4, 12]) {
if (i > 0) out += '-';
out += chars.substr(i, l);
i += l;
}
return out;
}
export function getMethods<T>(obj: T): (string)[] {
let properties = new Set()
let currentObj = obj
do {
Object.getOwnPropertyNames(currentObj).map(item => properties.add(item))
} while ((currentObj = Object.getPrototypeOf(currentObj)))
// @ts-ignore
return [...properties.keys()].filter(item => typeof obj[item] === 'function')
}