swaf/src/Utils.ts

35 lines
921 B
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('');
}