Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ulixee
GitHub Repository: ulixee/secret-agent
Path: blob/main/commons/utils.ts
1028 views
1
import IResolvablePromise from '@secret-agent/interfaces/IResolvablePromise';
2
import Resolvable from './Resolvable';
3
import CallSite = NodeJS.CallSite;
4
5
export function assert(value: unknown, message?: string, reject?): void {
6
if (value) return;
7
const error = new Error(message);
8
if (reject) {
9
reject(error);
10
} else {
11
throw error;
12
}
13
}
14
15
export function getCallSite(priorToFilename?: string, endFilename?: string): CallSite[] {
16
const err = new Error();
17
18
Error.prepareStackTrace = (_, stack) => stack;
19
20
let stack = (err.stack as unknown) as CallSite[];
21
22
Error.prepareStackTrace = undefined;
23
let startIndex = 1;
24
25
if (priorToFilename) {
26
const idx = stack.findIndex(
27
x => x.getFileName() === priorToFilename || x.getFileName()?.endsWith(priorToFilename),
28
);
29
if (idx >= 0) startIndex = idx + 1;
30
}
31
stack = stack.slice(startIndex);
32
33
if (endFilename) {
34
const lastIdx = stack.findIndex(
35
x => x.getFileName() === endFilename || x.getFileName()?.endsWith(endFilename),
36
);
37
if (lastIdx >= 0) stack = stack.slice(0, lastIdx + 1);
38
}
39
return stack.filter(x => !!x.getFileName() && !x.getFileName()?.startsWith('internal'));
40
}
41
42
export function pickRandom<T>(array: T[]): T {
43
if (array.length === 1) return array[0];
44
if (!array.length) throw new Error('Empty array provided to "pickRandom"');
45
return array[Math.floor(Math.random() * array.length)];
46
}
47
48
export function bindFunctions(self: any): void {
49
let object = self;
50
do {
51
for (const key of Reflect.ownKeys(object)) {
52
if (key === 'constructor') {
53
continue;
54
}
55
const descriptor = Reflect.getOwnPropertyDescriptor(object, key);
56
if (descriptor && typeof descriptor.value === 'function') {
57
self[key] = self[key].bind(self);
58
}
59
}
60
object = Reflect.getPrototypeOf(object);
61
} while (object && object !== Object.prototype);
62
}
63
64
export function createPromise<T = any>(
65
timeoutMillis?: number,
66
timeoutMessage?: string,
67
): IResolvablePromise<T> {
68
return new Resolvable<T>(timeoutMillis, timeoutMessage);
69
}
70
71