2019-11-19 05:18:28 +03:00
|
|
|
/**
|
|
|
|
* Copyright 2017 Google Inc. All rights reserved.
|
|
|
|
* Modifications copyright (c) Microsoft Corporation.
|
|
|
|
*
|
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
*
|
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
*
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
* limitations under the License.
|
|
|
|
*/
|
2019-12-06 01:48:39 +03:00
|
|
|
|
2019-12-13 07:54:40 +03:00
|
|
|
import { TimeoutError } from './errors';
|
2020-01-07 22:55:24 +03:00
|
|
|
import * as platform from './platform';
|
2019-11-19 05:18:28 +03:00
|
|
|
|
2020-01-13 20:14:28 +03:00
|
|
|
export const debugError = platform.debug(`pw:error`);
|
2019-11-19 05:18:28 +03:00
|
|
|
|
|
|
|
export type RegisteredListener = {
|
2020-01-07 22:55:24 +03:00
|
|
|
emitter: platform.EventEmitterType;
|
2019-11-19 05:18:28 +03:00
|
|
|
eventName: (string | symbol);
|
2019-12-10 01:41:20 +03:00
|
|
|
handler: (...args: any[]) => void;
|
2019-11-19 05:18:28 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
class Helper {
|
|
|
|
static evaluationString(fun: Function | string, ...args: any[]): string {
|
|
|
|
if (Helper.isString(fun)) {
|
|
|
|
assert(args.length === 0, 'Cannot evaluate a string with arguments');
|
2020-02-08 00:38:50 +03:00
|
|
|
return fun;
|
2019-11-19 05:18:28 +03:00
|
|
|
}
|
|
|
|
return `(${fun})(${args.map(serializeArgument).join(',')})`;
|
|
|
|
|
|
|
|
function serializeArgument(arg: any): string {
|
|
|
|
if (Object.is(arg, undefined))
|
|
|
|
return 'undefined';
|
|
|
|
return JSON.stringify(arg);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-17 04:48:38 +03:00
|
|
|
static installApiHooks(className: string, classType: any) {
|
|
|
|
const log = platform.debug('pw:api');
|
2019-11-19 05:18:28 +03:00
|
|
|
for (const methodName of Reflect.ownKeys(classType.prototype)) {
|
|
|
|
const method = Reflect.get(classType.prototype, methodName);
|
2020-01-17 04:48:38 +03:00
|
|
|
if (methodName === 'constructor' || typeof methodName !== 'string' || methodName.startsWith('_') || typeof method !== 'function')
|
|
|
|
continue;
|
|
|
|
const isAsync = method.constructor.name === 'AsyncFunction';
|
|
|
|
if (!isAsync && !log.enabled)
|
2019-11-19 05:18:28 +03:00
|
|
|
continue;
|
2020-01-14 00:33:25 +03:00
|
|
|
Reflect.set(classType.prototype, methodName, function(this: any, ...args: any[]) {
|
2020-01-17 04:48:38 +03:00
|
|
|
if (log.enabled) {
|
|
|
|
if (args.length)
|
|
|
|
log(`${className}.${methodName} %o`, args);
|
|
|
|
else
|
|
|
|
log(`${className}.${methodName}`);
|
|
|
|
}
|
|
|
|
if (!isAsync)
|
|
|
|
return method.call(this, ...args);
|
2019-11-19 05:18:28 +03:00
|
|
|
const syncStack: any = {};
|
|
|
|
Error.captureStackTrace(syncStack);
|
2020-01-14 00:33:25 +03:00
|
|
|
return method.call(this, ...args).catch((e: any) => {
|
2019-11-19 05:18:28 +03:00
|
|
|
const stack = syncStack.stack.substring(syncStack.stack.indexOf('\n') + 1);
|
|
|
|
const clientStack = stack.substring(stack.indexOf('\n'));
|
|
|
|
if (e instanceof Error && e.stack && !e.stack.includes(clientStack))
|
|
|
|
e.stack += '\n -- ASYNC --\n' + stack;
|
|
|
|
throw e;
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static addEventListener(
|
2020-01-07 22:55:24 +03:00
|
|
|
emitter: platform.EventEmitterType,
|
2019-11-19 05:18:28 +03:00
|
|
|
eventName: (string | symbol),
|
2019-12-10 01:41:20 +03:00
|
|
|
handler: (...args: any[]) => void): RegisteredListener {
|
2019-11-19 05:18:28 +03:00
|
|
|
emitter.on(eventName, handler);
|
|
|
|
return { emitter, eventName, handler };
|
|
|
|
}
|
|
|
|
|
|
|
|
static removeEventListeners(listeners: Array<{
|
2020-01-07 22:55:24 +03:00
|
|
|
emitter: platform.EventEmitterType;
|
2019-11-19 05:18:28 +03:00
|
|
|
eventName: (string | symbol);
|
2019-12-10 01:41:20 +03:00
|
|
|
handler: (...args: any[]) => void;
|
2019-11-19 05:18:28 +03:00
|
|
|
}>) {
|
|
|
|
for (const listener of listeners)
|
|
|
|
listener.emitter.removeListener(listener.eventName, listener.handler);
|
|
|
|
listeners.splice(0, listeners.length);
|
|
|
|
}
|
|
|
|
|
|
|
|
static isString(obj: any): obj is string {
|
|
|
|
return typeof obj === 'string' || obj instanceof String;
|
|
|
|
}
|
|
|
|
|
|
|
|
static isNumber(obj: any): obj is number {
|
|
|
|
return typeof obj === 'number' || obj instanceof Number;
|
|
|
|
}
|
|
|
|
|
2020-02-25 05:32:17 +03:00
|
|
|
static isRegExp(obj: any): obj is RegExp {
|
|
|
|
return obj instanceof RegExp || Object.prototype.toString.call(obj) === '[object RegExp]';
|
|
|
|
}
|
|
|
|
|
2020-02-22 17:16:28 +03:00
|
|
|
static isObject(obj: any): obj is NonNullable<object> {
|
|
|
|
return typeof obj === 'object' && obj !== null;
|
|
|
|
}
|
|
|
|
|
|
|
|
static isBoolean(obj: any): obj is boolean {
|
|
|
|
return typeof obj === 'boolean' || obj instanceof Boolean;
|
|
|
|
}
|
|
|
|
|
2019-11-19 05:18:28 +03:00
|
|
|
static async waitForEvent(
|
2020-01-07 22:55:24 +03:00
|
|
|
emitter: platform.EventEmitterType,
|
2019-11-19 05:18:28 +03:00
|
|
|
eventName: (string | symbol),
|
|
|
|
predicate: Function,
|
|
|
|
timeout: number,
|
|
|
|
abortPromise: Promise<Error>): Promise<any> {
|
2020-01-14 00:33:25 +03:00
|
|
|
let eventTimeout: NodeJS.Timer;
|
|
|
|
let resolveCallback: (event: any) => void = () => {};
|
|
|
|
let rejectCallback: (error: any) => void = () => {};
|
2019-11-19 05:18:28 +03:00
|
|
|
const promise = new Promise((resolve, reject) => {
|
|
|
|
resolveCallback = resolve;
|
|
|
|
rejectCallback = reject;
|
|
|
|
});
|
|
|
|
const listener = Helper.addEventListener(emitter, eventName, event => {
|
2019-12-18 01:00:39 +03:00
|
|
|
try {
|
|
|
|
if (!predicate(event))
|
|
|
|
return;
|
|
|
|
resolveCallback(event);
|
|
|
|
} catch (e) {
|
|
|
|
rejectCallback(e);
|
|
|
|
}
|
2019-11-19 05:18:28 +03:00
|
|
|
});
|
|
|
|
if (timeout) {
|
|
|
|
eventTimeout = setTimeout(() => {
|
2019-12-18 04:34:32 +03:00
|
|
|
rejectCallback(new TimeoutError(`Timeout exceeded while waiting for ${String(eventName)}`));
|
2019-11-19 05:18:28 +03:00
|
|
|
}, timeout);
|
|
|
|
}
|
|
|
|
function cleanup() {
|
|
|
|
Helper.removeEventListeners([listener]);
|
|
|
|
clearTimeout(eventTimeout);
|
|
|
|
}
|
|
|
|
const result = await Promise.race([promise, abortPromise]).then(r => {
|
|
|
|
cleanup();
|
|
|
|
return r;
|
|
|
|
}, e => {
|
|
|
|
cleanup();
|
|
|
|
throw e;
|
|
|
|
});
|
|
|
|
if (result instanceof Error)
|
|
|
|
throw result;
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
static async waitWithTimeout<T>(promise: Promise<T>, taskName: string, timeout: number): Promise<T> {
|
|
|
|
let reject: (error: Error) => void;
|
|
|
|
const timeoutError = new TimeoutError(`waiting for ${taskName} failed: timeout ${timeout}ms exceeded`);
|
|
|
|
const timeoutPromise = new Promise<T>((resolve, x) => reject = x);
|
|
|
|
let timeoutTimer = null;
|
|
|
|
if (timeout)
|
|
|
|
timeoutTimer = setTimeout(() => reject(timeoutError), timeout);
|
|
|
|
try {
|
|
|
|
return await Promise.race([promise, timeoutPromise]);
|
|
|
|
} finally {
|
|
|
|
if (timeoutTimer)
|
|
|
|
clearTimeout(timeoutTimer);
|
|
|
|
}
|
|
|
|
}
|
2020-02-04 01:23:24 +03:00
|
|
|
|
|
|
|
static globToRegex(glob: string): RegExp {
|
|
|
|
const tokens = ['^'];
|
|
|
|
let inGroup;
|
|
|
|
for (let i = 0; i < glob.length; ++i) {
|
|
|
|
const c = glob[i];
|
|
|
|
if (escapeGlobChars.has(c)) {
|
|
|
|
tokens.push('\\' + c);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if (c === '*') {
|
|
|
|
const beforeDeep = glob[i - 1];
|
|
|
|
let starCount = 1;
|
|
|
|
while (glob[i + 1] === '*') {
|
|
|
|
starCount++;
|
|
|
|
i++;
|
|
|
|
}
|
|
|
|
const afterDeep = glob[i + 1];
|
|
|
|
const isDeep = starCount > 1 &&
|
|
|
|
(beforeDeep === '/' || beforeDeep === undefined) &&
|
|
|
|
(afterDeep === '/' || afterDeep === undefined);
|
|
|
|
if (isDeep) {
|
|
|
|
tokens.push('((?:[^/]*(?:\/|$))*)');
|
|
|
|
i++;
|
|
|
|
} else {
|
|
|
|
tokens.push('([^/]*)');
|
|
|
|
}
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
switch (c) {
|
|
|
|
case '?':
|
|
|
|
tokens.push('.');
|
|
|
|
break;
|
|
|
|
case '{':
|
|
|
|
inGroup = true;
|
|
|
|
tokens.push('(');
|
|
|
|
break;
|
|
|
|
case '}':
|
|
|
|
inGroup = false;
|
|
|
|
tokens.push(')');
|
|
|
|
break;
|
|
|
|
case ',':
|
|
|
|
if (inGroup) {
|
|
|
|
tokens.push('|');
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
tokens.push('\\' + c);
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
tokens.push(c);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
tokens.push('$');
|
|
|
|
return new RegExp(tokens.join(''));
|
|
|
|
}
|
2020-02-05 06:39:52 +03:00
|
|
|
|
|
|
|
static completeUserURL(urlString: string): string {
|
|
|
|
if (urlString.startsWith('localhost') || urlString.startsWith('127.0.0.1'))
|
|
|
|
urlString = 'http://' + urlString;
|
|
|
|
return urlString;
|
|
|
|
}
|
2019-11-19 05:18:28 +03:00
|
|
|
}
|
|
|
|
|
2020-02-06 03:53:36 +03:00
|
|
|
export function assert(value: any, message?: string): asserts value {
|
2019-11-19 05:18:28 +03:00
|
|
|
if (!value)
|
|
|
|
throw new Error(message);
|
|
|
|
}
|
|
|
|
|
2020-02-04 01:23:24 +03:00
|
|
|
const escapeGlobChars = new Set(['/', '$', '^', '+', '.', '(', ')', '=', '!', '|']);
|
|
|
|
|
2019-11-19 05:18:28 +03:00
|
|
|
export const helper = Helper;
|