added all files to project

This commit is contained in:
2022-03-10 10:36:59 +01:00
parent 09dd957b33
commit 46a936d7de
25351 changed files with 3883356 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
export default class SevereServiceError extends Error {
constructor(message?: string);
}
//# sourceMappingURL=SevereServiceError.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"SevereServiceError.d.ts","sourceRoot":"","sources":["../../src/utils/SevereServiceError.ts"],"names":[],"mappings":"AAGA,MAAM,CAAC,OAAO,OAAO,kBAAmB,SAAQ,KAAK;gBACrC,OAAO,SAAmC;CAIzD"}
+9
View File
@@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class SevereServiceError extends Error {
constructor(message = 'Severe Service Error occurred.') {
super(message);
this.name = 'SevereServiceError';
}
}
exports.default = SevereServiceError;
+24
View File
@@ -0,0 +1,24 @@
declare class Timer {
private _delay;
private _timeout;
private _fn;
private _leading;
private _conditionExecutedCnt;
private _resolve;
private _reject;
private _startTime?;
private _ticks;
private _timeoutId?;
private _mainTimeoutId?;
private _lastError?;
constructor(_delay: number, _timeout: number, _fn: Function, _leading?: boolean);
private _start;
private _stop;
private _stopMain;
private _tick;
private _checkCondition;
private _hasTime;
private _wasConditionExecuted;
}
export default Timer;
//# sourceMappingURL=Timer.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"Timer.d.ts","sourceRoot":"","sources":["../../src/utils/Timer.ts"],"names":[],"mappings":"AAcA,cAAM,KAAK;IAYH,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,GAAG;IACX,OAAO,CAAC,QAAQ;IAdpB,OAAO,CAAC,qBAAqB,CAAI;IACjC,OAAO,CAAC,QAAQ,CAAiB;IACjC,OAAO,CAAC,OAAO,CAAiB;IAEhC,OAAO,CAAC,UAAU,CAAC,CAAQ;IAC3B,OAAO,CAAC,MAAM,CAAI;IAClB,OAAO,CAAC,UAAU,CAAC,CAAgB;IACnC,OAAO,CAAC,cAAc,CAAC,CAAgB;IACvC,OAAO,CAAC,UAAU,CAAC,CAAO;gBAGd,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,GAAG,EAAE,QAAQ,EACb,QAAQ,UAAQ;IAsB5B,OAAO,CAAC,MAAM;IAwBd,OAAO,CAAC,KAAK;IAOb,OAAO,CAAC,SAAS;IAOjB,OAAO,CAAC,KAAK;IAiBb,OAAO,CAAC,eAAe;IA6BvB,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,qBAAqB;CAGhC;AAYD,eAAe,KAAK,CAAA"}
+100
View File
@@ -0,0 +1,100 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@wdio/utils");
const TIMEOUT_ERROR = 'timeout';
const NOOP = () => { };
class Timer {
constructor(_delay, _timeout, _fn, _leading = false) {
this._delay = _delay;
this._timeout = _timeout;
this._fn = _fn;
this._leading = _leading;
this._conditionExecutedCnt = 0;
this._resolve = NOOP;
this._reject = NOOP;
this._ticks = 0;
if (utils_1.hasWdioSyncSupport && !_fn.name.includes('async') && Boolean(global.browser)) {
this._fn = () => utils_1.runFnInFiberContext(_fn)();
}
const retPromise = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
this._start();
return retPromise;
}
_start() {
this._startTime = Date.now();
emitTimerEvent({ id: this._startTime, start: true });
if (this._leading) {
this._tick();
}
else {
this._timeoutId = setTimeout(this._tick.bind(this), this._delay);
}
this._mainTimeoutId = setTimeout(() => {
if (!this._wasConditionExecuted()) {
return;
}
emitTimerEvent({ id: this._startTime, timeout: true });
const reason = this._lastError || new Error(TIMEOUT_ERROR);
this._reject(reason);
this._stop();
}, this._timeout);
}
_stop() {
if (this._timeoutId) {
clearTimeout(this._timeoutId);
}
delete this._timeoutId;
}
_stopMain() {
emitTimerEvent({ id: this._startTime });
if (this._mainTimeoutId) {
clearTimeout(this._mainTimeoutId);
}
}
_tick() {
const result = this._fn();
if (typeof result.then !== 'function') {
if (!result) {
return this._checkCondition(new Error('return value was never truthy'));
}
return this._checkCondition(undefined, result);
}
result.then((res) => this._checkCondition(undefined, res), (err) => this._checkCondition(err));
}
_checkCondition(err, res) {
++this._conditionExecutedCnt;
this._lastError = err;
if (res) {
this._resolve(res);
this._stop();
this._stopMain();
return;
}
let diff = (Date.now() - (this._startTime || 0)) - (this._ticks++ * this._delay);
let delay = Math.max(0, this._delay - diff);
this._stop();
if (this._hasTime(delay)) {
this._timeoutId = setTimeout(this._tick.bind(this), delay);
}
else {
this._stopMain();
const reason = this._lastError || new Error(TIMEOUT_ERROR);
this._reject(reason);
}
}
_hasTime(delay) {
return (Date.now() - (this._startTime || 0) + delay) <= this._timeout;
}
_wasConditionExecuted() {
return this._conditionExecutedCnt > 0;
}
}
function emitTimerEvent(payload) {
if (utils_1.hasWdioSyncSupport) {
process.emit('WDIO_TIMER', payload);
}
}
exports.default = Timer;
+10
View File
@@ -0,0 +1,10 @@
declare type SelectorStrategy = string | {
name: string;
args: string;
};
export declare const findStrategy: (selector: SelectorStrategy, isW3C?: boolean | undefined, isMobile?: boolean | undefined) => {
using: string;
value: string;
};
export {};
//# sourceMappingURL=findStrategy.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"findStrategy.d.ts","sourceRoot":"","sources":["../../src/utils/findStrategy.ts"],"names":[],"mappings":"AA2BA,aAAK,gBAAgB,GAAG,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAA;AA6E/D,eAAO,MAAM,YAAY,aAAuB,gBAAgB;;;CA8H/D,CAAA"}
+186
View File
@@ -0,0 +1,186 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.findStrategy = void 0;
const fs_1 = __importDefault(require("fs"));
const lodash_isplainobject_1 = __importDefault(require("lodash.isplainobject"));
const constants_1 = require("../constants");
const DEFAULT_STRATEGY = 'css selector';
const DIRECT_SELECTOR_REGEXP = /^(id|css selector|xpath|link text|partial link text|name|tag name|class name|-android uiautomator|-android datamatcher|-android viewmatcher|-android viewtag|-ios uiautomation|-ios predicate string|-ios class chain|accessibility id):(.+)/;
const XPATH_SELECTORS_START = [
'/', '(', '../', './', '*/'
];
const NAME_MOBILE_SELECTORS_START = [
'uia', 'xcuielementtype', 'android.widget', 'cyi'
];
const XPATH_SELECTOR_REGEXP = [
/^([a-z0-9|-]*)/,
/(?:(\.|#)(-?[_a-zA-Z]+[_a-zA-Z0-9-]*))?/,
/(?:\[(-?[_a-zA-Z]+[_a-zA-Z0-9-]*)(?:=(?:"|')([a-zA-z0-9\-_. ]+)(?:"|'))?\])?/,
/(\*)?=(.+)$/,
];
const IMAGEPATH_MOBILE_SELECTORS_ENDSWITH = [
'.jpg', '.jpeg', '.gif', '.png', '.bmp', '.svg'
];
const defineStrategy = function (selector) {
if (lodash_isplainobject_1.default(selector)) {
if (JSON.stringify(selector).indexOf('test.espresso.matcher.ViewMatchers') < 0)
return '-android datamatcher';
return '-android viewmatcher';
}
const stringSelector = selector;
if (stringSelector.match(DIRECT_SELECTOR_REGEXP)) {
return 'directly';
}
if (IMAGEPATH_MOBILE_SELECTORS_ENDSWITH.some(path => stringSelector.toLowerCase().endsWith(path))) {
return '-image';
}
if (XPATH_SELECTORS_START.some(option => stringSelector.startsWith(option))) {
return 'xpath';
}
if (stringSelector.startsWith('=')) {
return 'link text';
}
if (stringSelector.startsWith('*=')) {
return 'partial link text';
}
if (stringSelector.startsWith('id=')) {
return 'id';
}
if (stringSelector.startsWith('android=')) {
return '-android uiautomator';
}
if (stringSelector.startsWith('ios=')) {
return '-ios uiautomation';
}
if (stringSelector.startsWith('~')) {
return 'accessibility id';
}
if (NAME_MOBILE_SELECTORS_START.some(option => stringSelector.toLowerCase().startsWith(option))) {
return 'class name';
}
if (stringSelector.search(/<[0-9a-zA-Z-]+( \/)*>/g) >= 0) {
return 'tag name';
}
if (stringSelector.search(/^\[name=("|')([a-zA-z0-9\-_.@=[\] ']+)("|')]$/) >= 0) {
return 'name';
}
if (selector === '..' || selector === '.') {
return 'xpath';
}
if (stringSelector.match(new RegExp(XPATH_SELECTOR_REGEXP.map(rx => rx.source).join('')))) {
return 'xpath extended';
}
};
exports.findStrategy = function (selector, isW3C, isMobile) {
const stringSelector = selector;
let using = DEFAULT_STRATEGY;
let value = selector;
switch (defineStrategy(selector)) {
case 'directly': {
const match = stringSelector.match(DIRECT_SELECTOR_REGEXP);
if (!match || !isMobile && isW3C && !constants_1.W3C_SELECTOR_STRATEGIES.includes(match[1])) {
throw new Error('InvalidSelectorStrategy');
}
using = match[1];
value = match[2];
break;
}
case 'xpath': {
using = 'xpath';
break;
}
case 'id': {
using = 'id';
value = stringSelector.slice(3);
break;
}
case 'link text': {
using = 'link text';
value = stringSelector.slice(1);
break;
}
case 'partial link text': {
using = 'partial link text';
value = stringSelector.slice(2);
break;
}
case '-android uiautomator': {
using = '-android uiautomator';
value = stringSelector.slice(8);
break;
}
case '-android datamatcher': {
using = '-android datamatcher';
value = JSON.stringify(value);
break;
}
case '-android viewmatcher': {
using = '-android viewmatcher';
value = JSON.stringify(value);
break;
}
case '-ios uiautomation': {
using = '-ios uiautomation';
value = stringSelector.slice(4);
break;
}
case 'accessibility id': {
using = 'accessibility id';
value = stringSelector.slice(1);
break;
}
case 'class name': {
using = 'class name';
break;
}
case 'tag name': {
using = 'tag name';
value = stringSelector.replace(/<|>|\/|\s/g, '');
break;
}
case 'name': {
if (isMobile || !isW3C) {
const match = stringSelector.match(/^\[name=("|')([a-zA-z0-9\-_.@=[\] ']+)("|')]$/);
if (!match) {
throw new Error(`InvalidSelectorMatch. Strategy 'name' has failed to match '${stringSelector}'`);
}
using = 'name';
value = match[2];
}
break;
}
case 'xpath extended': {
using = 'xpath';
const match = stringSelector.match(new RegExp(XPATH_SELECTOR_REGEXP.map(rx => rx.source).join('')));
if (!match) {
throw new Error(`InvalidSelectorMatch: Strategy 'xpath extended' has failed to match '${stringSelector}'`);
}
const PREFIX_NAME = { '.': 'class', '#': 'id' };
const conditions = [];
const [tag, prefix, name, attrName, attrValue, partial, query] = match.slice(1);
if (prefix) {
conditions.push(`contains(@${PREFIX_NAME[prefix]}, "${name}")`);
}
if (attrName) {
conditions.push(attrValue
? `contains(@${attrName}, "${attrValue}")`
: `@${attrName}`);
}
conditions.push(partial ? `contains(., "${query}")` : `normalize-space() = "${query}"`);
value = `.//${tag || '*'}[${conditions.join(' and ')}]`;
break;
}
case '-image': {
using = '-image';
value = fs_1.default.readFileSync(stringSelector, { encoding: 'base64' });
break;
}
}
if (!isMobile && isW3C && !constants_1.W3C_SELECTOR_STRATEGIES.includes(using)) {
throw new Error('InvalidSelectorStrategy');
}
return { using, value };
};
+7
View File
@@ -0,0 +1,7 @@
/// <reference types="webdriverio/webdriverio-core" />
/// <reference types="webdriverio" />
/// <reference types="@wdio/cucumber-framework" />
import type { ElementReference, Selector } from '../types';
export declare const getElement: (this: WebdriverIO.BrowserObject | WebdriverIO.Element, selector?: string | Record<"element-6066-11e4-a52e-4f735466cecf", string> | ((elem: HTMLElement) => Record<"element-6066-11e4-a52e-4f735466cecf", string>) | ((elem: HTMLElement) => Record<"element-6066-11e4-a52e-4f735466cecf", string>[]) | undefined, res?: Error | Record<"element-6066-11e4-a52e-4f735466cecf", string> | undefined, isReactElement?: boolean) => WebdriverIO.Element;
export declare const getElements: (this: WebdriverIO.BrowserObject | WebdriverIO.Element, selector: Selector, elemResponse: ElementReference[], isReactElement?: boolean) => WebdriverIO.ElementArray;
//# sourceMappingURL=getElementObject.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"getElementObject.d.ts","sourceRoot":"","sources":["../../src/utils/getElementObject.ts"],"names":[],"mappings":";;;AAMA,OAAO,KAAK,EAAE,gBAAgB,EAAiB,QAAQ,EAAE,MAAM,UAAU,CAAA;AAQzE,eAAO,MAAM,UAAU,SACb,YAAY,aAAa,GAAG,mBAAmB,2WAItD,mBA8CF,CAAA;AAQD,eAAO,MAAM,WAAW,SACd,YAAY,aAAa,GAAG,mBAAmB,YAC3C,QAAQ,gBACJ,gBAAgB,EAAE,+BAEjC,YAAY,YA+Cd,CAAA"}
+81
View File
@@ -0,0 +1,81 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getElements = exports.getElement = void 0;
const utils_1 = require("@wdio/utils");
const lodash_clonedeep_1 = __importDefault(require("lodash.clonedeep"));
const _1 = require(".");
const middlewares_1 = require("../middlewares");
const constants_1 = require("../constants");
exports.getElement = function findElement(selector, res, isReactElement = false) {
const browser = _1.getBrowserObject(this);
const propertiesObject = {
...lodash_clonedeep_1.default(browser.__propertiesObject__),
..._1.getPrototype('element'),
scope: { value: 'element' }
};
const element = utils_1.webdriverMonad(this.options, (client) => {
const elementId = _1.getElementFromResponse(res);
if (elementId) {
client.elementId = elementId;
if (this.isW3C) {
client[constants_1.ELEMENT_KEY] = elementId;
}
else {
client.ELEMENT = elementId;
}
}
else {
client.error = res;
}
client.selector = selector;
client.parent = this;
client.emit = this.emit.bind(this);
client.isReactElement = isReactElement;
return client;
}, propertiesObject);
const elementInstance = element(this.sessionId, middlewares_1.elementErrorHandler(utils_1.wrapCommand));
const origAddCommand = elementInstance.addCommand.bind(elementInstance);
elementInstance.addCommand = (name, fn) => {
browser.__propertiesObject__[name] = { value: fn };
origAddCommand(name, utils_1.runFnInFiberContext(fn));
};
return elementInstance;
};
exports.getElements = function getElements(selector, elemResponse, isReactElement = false) {
const browser = _1.getBrowserObject(this);
const propertiesObject = {
...lodash_clonedeep_1.default(browser.__propertiesObject__),
..._1.getPrototype('element')
};
const elements = elemResponse.map((res, i) => {
propertiesObject.scope = { value: 'element' };
const element = utils_1.webdriverMonad(this.options, (client) => {
const elementId = _1.getElementFromResponse(res);
if (elementId) {
client.elementId = elementId;
const elementKey = this.isW3C ? constants_1.ELEMENT_KEY : 'ELEMENT';
client[elementKey] = elementId;
}
else {
client.error = res;
}
client.selector = selector;
client.parent = this;
client.index = i;
client.emit = this.emit.bind(this);
client.isReactElement = isReactElement;
return client;
}, propertiesObject);
const elementInstance = element(this.sessionId, middlewares_1.elementErrorHandler(utils_1.wrapCommand));
const origAddCommand = elementInstance.addCommand.bind(elementInstance);
elementInstance.addCommand = (name, fn) => {
browser.__propertiesObject__[name] = { value: fn };
origAddCommand(name, utils_1.runFnInFiberContext(fn));
};
return elementInstance;
});
return elements;
};
+3
View File
@@ -0,0 +1,3 @@
/// <reference types="webdriverio/webdriverio-core" />
export default function implicitWait(currentElement: WebdriverIO.Element, commandName: string): Promise<WebdriverIO.Element>;
//# sourceMappingURL=implicitWait.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"implicitWait.d.ts","sourceRoot":"","sources":["../../src/utils/implicitWait.ts"],"names":[],"mappings":";AAQA,wBAA8B,YAAY,CAAE,cAAc,EAAE,WAAW,CAAC,OAAO,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAmClI"}
+31
View File
@@ -0,0 +1,31 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = __importDefault(require("@wdio/logger"));
const log = logger_1.default('webdriverio');
async function implicitWait(currentElement, commandName) {
if (!currentElement.elementId && !commandName.match(/(waitUntil|waitFor|isExisting|is?\w+Displayed|is?\w+Clickable)/)) {
log.debug(`command ${commandName} was called on an element ("${currentElement.selector}") ` +
'that wasn\'t found, waiting for it...');
try {
await currentElement.waitForExist();
return await currentElement.parent.$(currentElement.selector);
}
catch (_a) {
if (currentElement.selector.toString().includes('this.previousElementSibling')) {
throw new Error(`Can't call ${commandName} on previous element of element with selector "${currentElement.parent.selector}" because sibling wasn't found`);
}
if (currentElement.selector.toString().includes('this.nextElementSibling')) {
throw new Error(`Can't call ${commandName} on next element of element with selector "${currentElement.parent.selector}" because sibling wasn't found`);
}
if (currentElement.selector.toString().includes('this.parentElement')) {
throw new Error(`Can't call ${commandName} on parent element of element with selector "${currentElement.parent.selector}" because it wasn't found`);
}
throw new Error(`Can't call ${commandName} on element with selector "${currentElement.selector}" because element wasn't found`);
}
}
return currentElement;
}
exports.default = implicitWait;
+30
View File
@@ -0,0 +1,30 @@
/// <reference types="webdriverio/webdriverio-core" />
/// <reference types="webdriverio" />
/// <reference types="webdriver" />
/// <reference types="@wdio/cucumber-framework" />
import type { ElementReference, Selector, ParsedCSSValue, Options } from '../types';
export declare const getPrototype: (scope: 'browser' | 'element') => Record<string, PropertyDescriptor>;
export declare const getElementFromResponse: (res: ElementReference) => any;
export declare function getBrowserObject(elem: WebdriverIO.Element | WebdriverIO.BrowserObject): WebdriverIO.BrowserObject;
export declare function transformToCharString(value: any, translateToUnicode?: boolean): string[];
export declare function parseCSS(cssPropertyValue: string, cssProperty?: string): ParsedCSSValue;
export declare function checkUnicode(value: string, isDevTools?: boolean): string[];
export declare function findElement(this: WebdriverIO.Element, selector: Selector): Promise<Error | Record<"element-6066-11e4-a52e-4f735466cecf", string>>;
export declare function findElements(this: WebdriverIO.Element, selector: Selector): Promise<Record<"element-6066-11e4-a52e-4f735466cecf", string>[]>;
export declare function verifyArgsAndStripIfElement(args: any): any;
export declare function getElementRect(scope: WebdriverIO.Element): Promise<WebDriver.RectReturn>;
export declare function getAbsoluteFilepath(filepath: string): string;
export declare function assertDirectoryExists(filepath: string): void;
export declare function validateUrl(url: string, origError?: Error): string;
export declare function getScrollPosition(scope: WebdriverIO.Element): Promise<{
scrollX: number;
scrollY: number;
}>;
export declare function hasElementId(element: WebdriverIO.Element): Promise<boolean>;
export declare function addLocatorStrategyHandler(scope: WebdriverIO.BrowserObject): (name: string, script: () => ElementReference | ElementReference[]) => void;
export declare const enhanceElementsArray: (elements: WebdriverIO.ElementArray, parent: WebdriverIO.BrowserObject | WebdriverIO.Element, selector: string, foundWith?: string, props?: any[]) => import("webdriverio").ElementArray;
export declare const isStub: (automationProtocol?: string | undefined) => boolean;
export declare const getAutomationProtocol: (config: Options) => Promise<"webdriver" | "devtools" | "./protocol-stub">;
export declare const updateCapabilities: (params: Options, automationProtocol?: string | undefined) => Promise<void>;
export declare const containsHeaderObject: (base: Record<string, string>, match: Record<string, string>) => boolean;
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":";;;;AAeA,OAAO,KAAK,EACR,gBAAgB,EAAkC,QAAQ,EAAE,cAAc,EAC1E,OAAO,EACV,MAAM,UAAU,CAAA;AAwBjB,eAAO,MAAM,YAAY,UAAW,SAAS,GAAG,SAAS,uCAmBxD,CAAA;AAOD,eAAO,MAAM,sBAAsB,QAAS,gBAAgB,QAuB3D,CAAA;AAKD,wBAAgB,gBAAgB,CAAE,IAAI,EAAE,WAAW,CAAC,OAAO,GAAG,WAAW,CAAC,aAAa,GAAG,WAAW,CAAC,aAAa,CAGlH;AAKD,wBAAgB,qBAAqB,CAAE,KAAK,EAAE,GAAG,EAAE,kBAAkB,UAAO,YA0B3E;AAiBD,wBAAgB,QAAQ,CAAE,gBAAgB,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,kBAkDvE;AAOD,wBAAgB,YAAY,CACxB,KAAK,EAAE,MAAM,EACb,UAAU,UAAQ,YAKrB;AAqBD,wBAAsB,WAAW,CAC7B,IAAI,EAAE,WAAW,CAAC,OAAO,EACzB,QAAQ,EAAE,QAAQ,0EAwBrB;AAKD,wBAAsB,YAAY,CAC9B,IAAI,EAAE,WAAW,CAAC,OAAO,EACzB,QAAQ,EAAE,QAAQ,oEAuBrB;AAKD,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,GAAG,OAkBpD;AAKD,wBAAsB,cAAc,CAAC,KAAK,EAAE,WAAW,CAAC,OAAO,iCAuC9D;AAED,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,UAInD;AAKD,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,QAIrD;AAQD,wBAAgB,WAAW,CAAE,GAAG,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,KAAK,GAAG,MAAM,CAcnE;AAMD,wBAAgB,iBAAiB,CAAE,KAAK,EAAE,WAAW,CAAC,OAAO;;;GAK5D;AAED,wBAAsB,YAAY,CAAE,OAAO,EAAE,WAAW,CAAC,OAAO,oBAiB/D;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,WAAW,CAAC,aAAa,UACxD,MAAM,UAAU,MAAM,gBAAgB,GAAG,gBAAgB,EAAE,UAO5E;AAWD,eAAO,MAAM,oBAAoB,aACnB,YAAY,YAAY,UAC1B,YAAY,aAAa,GAAG,mBAAmB,YAC7C,MAAM,8BAET,GAAG,EAAE,uCAOf,CAAA;AAMD,eAAO,MAAM,MAAM,sDAA4E,CAAA;AAE/F,eAAO,MAAM,qBAAqB,WAAkB,OAAO,0DAyD1D,CAAA;AAQD,eAAO,MAAM,kBAAkB,WAAkB,OAAO,2DAsBvD,CAAA;AAOD,eAAO,MAAM,oBAAoB,SACvB,OAAO,MAAM,EAAE,MAAM,CAAC,SACrB,OAAO,MAAM,EAAE,MAAM,CAAC,YAShC,CAAA"}
+339
View File
@@ -0,0 +1,339 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.containsHeaderObject = exports.updateCapabilities = exports.getAutomationProtocol = exports.isStub = exports.enhanceElementsArray = exports.addLocatorStrategyHandler = exports.hasElementId = exports.getScrollPosition = exports.validateUrl = exports.assertDirectoryExists = exports.getAbsoluteFilepath = exports.getElementRect = exports.verifyArgsAndStripIfElement = exports.findElements = exports.findElement = exports.checkUnicode = exports.parseCSS = exports.transformToCharString = exports.getBrowserObject = exports.getElementFromResponse = exports.getPrototype = void 0;
const fs_1 = __importDefault(require("fs"));
const http_1 = __importDefault(require("http"));
const path_1 = __importDefault(require("path"));
const css_value_1 = __importDefault(require("css-value"));
const rgb2hex_1 = __importDefault(require("rgb2hex"));
const get_port_1 = __importDefault(require("get-port"));
const grapheme_splitter_1 = __importDefault(require("grapheme-splitter"));
const logger_1 = __importDefault(require("@wdio/logger"));
const lodash_isobject_1 = __importDefault(require("lodash.isobject"));
const lodash_isplainobject_1 = __importDefault(require("lodash.isplainobject"));
const url_1 = require("url");
const devtools_1 = require("devtools");
const constants_1 = require("../constants");
const findStrategy_1 = require("./findStrategy");
const browserCommands = require('../commands/browser');
const elementCommands = require('../commands/element');
const log = logger_1.default('webdriverio');
const INVALID_SELECTOR_ERROR = 'selector needs to be typeof `string` or `function`';
const scopes = {
browser: browserCommands,
element: elementCommands
};
const applyScopePrototype = (prototype, scope) => {
Object.entries(scopes[scope]).forEach(([commandName, command]) => {
prototype[commandName] = { value: command };
});
};
exports.getPrototype = (scope) => {
const prototype = {
puppeteer: { value: null, writable: true },
_NOT_FIBER: { value: false, writable: true, configurable: true }
};
applyScopePrototype(prototype, scope);
prototype.strategies = { value: new Map() };
return prototype;
};
exports.getElementFromResponse = (res) => {
if (!res) {
return null;
}
if (res.ELEMENT) {
return res.ELEMENT;
}
if (res[constants_1.ELEMENT_KEY]) {
return res[constants_1.ELEMENT_KEY];
}
return null;
};
function getBrowserObject(elem) {
const elemObject = elem;
return elemObject.parent ? getBrowserObject(elemObject.parent) : elem;
}
exports.getBrowserObject = getBrowserObject;
function transformToCharString(value, translateToUnicode = true) {
const ret = [];
if (!Array.isArray(value)) {
value = [value];
}
for (const val of value) {
if (typeof val === 'string') {
translateToUnicode
? ret.push(...checkUnicode(val))
: ret.push(...`${val}`.split(''));
}
else if (typeof val === 'number') {
const entry = `${val}`.split('');
ret.push(...entry);
}
else if (val && typeof val === 'object') {
try {
ret.push(...JSON.stringify(val).split(''));
}
catch (e) { }
}
else if (typeof val === 'boolean') {
const entry = val ? 'true'.split('') : 'false'.split('');
ret.push(...entry);
}
}
return ret;
}
exports.transformToCharString = transformToCharString;
function sanitizeCSS(value) {
if (!value) {
return value;
}
return value.trim().replace(/'/g, '').replace(/"/g, '').toLowerCase();
}
function parseCSS(cssPropertyValue, cssProperty) {
var _a;
const parsedValue = {
property: cssProperty,
value: cssPropertyValue.toLowerCase().trim(),
parsed: {}
};
if (((_a = parsedValue.value) === null || _a === void 0 ? void 0 : _a.indexOf('rgb')) === 0) {
parsedValue.value = parsedValue.value.replace(/\s/g, '');
let color = parsedValue.value;
parsedValue.parsed = rgb2hex_1.default(parsedValue.value);
parsedValue.parsed.type = 'color';
const colorType = /[rgba]+/g.exec(color) || [];
parsedValue.parsed[colorType[0]] = color;
}
else if (parsedValue.property === 'font-family') {
let font = css_value_1.default(cssPropertyValue);
let string = parsedValue.value;
let value = cssPropertyValue.split(/,/).map(sanitizeCSS);
parsedValue.value = sanitizeCSS(font[0].value || font[0].string);
parsedValue.parsed = { value, type: 'font', string };
}
else {
try {
const value = css_value_1.default(cssPropertyValue);
if (value.length === 1) {
parsedValue.parsed = value[0];
}
if (parsedValue.parsed.type && parsedValue.parsed.type === 'number' && parsedValue.parsed.unit === '') {
parsedValue.value = parsedValue.parsed.value;
}
}
catch (e) {
}
}
return parsedValue;
}
exports.parseCSS = parseCSS;
function checkUnicode(value, isDevTools = false) {
return Object.prototype.hasOwnProperty.call(constants_1.UNICODE_CHARACTERS, value)
? isDevTools ? [value] : [constants_1.UNICODE_CHARACTERS[value]]
: new grapheme_splitter_1.default().splitGraphemes(value);
}
exports.checkUnicode = checkUnicode;
function fetchElementByJSFunction(selector, scope) {
if (!scope.elementId) {
return scope.execute(selector);
}
const script = (function (elem) {
return selector.call(elem);
}).toString().replace('selector', `(${selector.toString()})`);
return getBrowserObject(scope).execute(`return (${script}).apply(null, arguments)`, scope);
}
async function findElement(selector) {
if (typeof selector === 'string' || lodash_isplainobject_1.default(selector)) {
const { using, value } = findStrategy_1.findStrategy(selector, this.isW3C, this.isMobile);
return this.elementId
? this.findElementFromElement(this.elementId, using, value)
: this.findElement(using, value);
}
if (typeof selector === 'function') {
const notFoundError = new Error(`Function selector "${selector.toString()}" did not return an HTMLElement`);
let elem = await fetchElementByJSFunction(selector, this);
elem = Array.isArray(elem) ? elem[0] : elem;
return exports.getElementFromResponse(elem) ? elem : notFoundError;
}
throw new Error(INVALID_SELECTOR_ERROR);
}
exports.findElement = findElement;
async function findElements(selector) {
if (typeof selector === 'string' || lodash_isplainobject_1.default(selector)) {
const { using, value } = findStrategy_1.findStrategy(selector, this.isW3C, this.isMobile);
return this.elementId
? this.findElementsFromElement(this.elementId, using, value)
: this.findElements(using, value);
}
if (typeof selector === 'function') {
const elems = await fetchElementByJSFunction(selector, this);
const elemArray = Array.isArray(elems) ? elems : [elems];
return elemArray.filter((elem) => elem && exports.getElementFromResponse(elem));
}
throw new Error(INVALID_SELECTOR_ERROR);
}
exports.findElements = findElements;
function verifyArgsAndStripIfElement(args) {
function verify(arg) {
if (lodash_isobject_1.default(arg) && arg.constructor.name === 'Element') {
const elem = arg;
if (!elem.elementId) {
throw new Error(`The element with selector "${elem.selector}" you trying to pass into the execute method wasn't found`);
}
return {
[constants_1.ELEMENT_KEY]: elem.elementId,
ELEMENT: elem.elementId
};
}
return arg;
}
return !Array.isArray(args) ? verify(args) : args.map(verify);
}
exports.verifyArgsAndStripIfElement = verifyArgsAndStripIfElement;
async function getElementRect(scope) {
const rect = await scope.getElementRect(scope.elementId);
let defaults = { x: 0, y: 0, width: 0, height: 0 };
if (Object.keys(defaults).some((key) => rect[key] == null)) {
const rectJs = await getBrowserObject(scope).execute(function (el) {
if (!el || !el.getBoundingClientRect) {
return;
}
const { left, top, width, height } = el.getBoundingClientRect();
return {
x: left + this.scrollX,
y: top + this.scrollY,
width,
height
};
}, scope);
Object.keys(defaults).forEach((key) => {
if (rect[key] != null) {
return;
}
if (rectJs && typeof rectJs[key] === 'number') {
rect[key] = Math.floor(rectJs[key]);
}
else {
log.error('getElementRect', { rect, rectJs, key });
throw new Error('Failed to receive element rects via execute command');
}
});
}
return rect;
}
exports.getElementRect = getElementRect;
function getAbsoluteFilepath(filepath) {
return filepath.startsWith('/') || filepath.startsWith('\\') || filepath.match(/^[a-zA-Z]:\\/)
? filepath
: path_1.default.join(process.cwd(), filepath);
}
exports.getAbsoluteFilepath = getAbsoluteFilepath;
function assertDirectoryExists(filepath) {
if (!fs_1.default.existsSync(path_1.default.dirname(filepath))) {
throw new Error(`directory (${path_1.default.dirname(filepath)}) doesn't exist`);
}
}
exports.assertDirectoryExists = assertDirectoryExists;
function validateUrl(url, origError) {
try {
const urlObject = new url_1.URL(url);
return urlObject.href;
}
catch (e) {
if (origError) {
throw origError;
}
return validateUrl(`http://${url}`, e);
}
}
exports.validateUrl = validateUrl;
function getScrollPosition(scope) {
return getBrowserObject(scope)
.execute(function () {
return { scrollX: this.pageXOffset, scrollY: this.pageYOffset };
});
}
exports.getScrollPosition = getScrollPosition;
async function hasElementId(element) {
if (!element.elementId) {
const method = element.isReactElement ? 'react$' : '$';
element.elementId = (await element.parent[method](element.selector)).elementId;
}
if (!element.elementId) {
return false;
}
return true;
}
exports.hasElementId = hasElementId;
function addLocatorStrategyHandler(scope) {
return (name, script) => {
if (scope.strategies.get(name)) {
throw new Error(`Strategy ${name} already exists`);
}
scope.strategies.set(name, script);
};
}
exports.addLocatorStrategyHandler = addLocatorStrategyHandler;
exports.enhanceElementsArray = (elements, parent, selector, foundWith = '$$', props = []) => {
elements.parent = parent;
elements.selector = selector;
elements.foundWith = foundWith;
elements.props = props;
return elements;
};
exports.isStub = (automationProtocol) => automationProtocol === './protocol-stub';
exports.getAutomationProtocol = async (config) => {
var _a;
if (config.automationProtocol) {
return config.automationProtocol;
}
if (config.hostname || config.port || config.path || (config.user && config.key)) {
return 'webdriver';
}
if (config.capabilities &&
typeof config.capabilities.browserName === 'string' &&
!devtools_1.SUPPORTED_BROWSER.includes((_a = config.capabilities.browserName) === null || _a === void 0 ? void 0 : _a.toLowerCase())) {
return 'webdriver';
}
if (config.capabilities && config.capabilities.alwaysMatch) {
return 'webdriver';
}
const resp = await new Promise((resolve) => {
const req = http_1.default.request(constants_1.DRIVER_DEFAULT_ENDPOINT, resolve);
req.on('error', (error) => resolve({ error }));
req.end();
});
const driverEndpointHeaders = resp;
if (driverEndpointHeaders.req && driverEndpointHeaders.req.agent) {
driverEndpointHeaders.req.agent.destroy();
}
if (driverEndpointHeaders && driverEndpointHeaders.statusCode === 200) {
return 'webdriver';
}
return 'devtools';
};
exports.updateCapabilities = async (params, automationProtocol) => {
const caps = params.capabilities;
if (automationProtocol === 'webdriver' && caps.browserName === 'firefox') {
if (!caps['moz:firefoxOptions']) {
caps['moz:firefoxOptions'] = {};
}
if (!caps['moz:firefoxOptions'].args) {
caps['moz:firefoxOptions'].args = [];
}
if (!caps['moz:firefoxOptions'].args.includes(constants_1.FF_REMOTE_DEBUG_ARG)) {
caps['moz:firefoxOptions'].args.push(constants_1.FF_REMOTE_DEBUG_ARG, (await get_port_1.default()).toString());
}
}
};
exports.containsHeaderObject = (base, match) => {
for (const [key, value] of Object.entries(match)) {
if (typeof base[key] === 'undefined' || base[key] !== value) {
return false;
}
}
return true;
};
+39
View File
@@ -0,0 +1,39 @@
/// <reference types="webdriverio/webdriverio-core" />
/// <reference types="node" />
/// <reference types="webdriverio" />
/// <reference types="@wdio/cucumber-framework" />
import Interception from '.';
declare type RequestOptions = {
requestId: string;
responseCode?: number;
responseHeaders?: Record<string, string>[];
body?: string | WebdriverIO.JsonCompatible;
errorReason?: string;
};
declare type ClientResponse = {
body: string;
base64Encoded?: boolean;
};
declare type Client = {
send: (requestName: string, requestOptions: RequestOptions) => Promise<ClientResponse>;
};
declare type Event = {
requestId: string;
request: WebdriverIO.Matches & {
mockedResponse: string | Buffer;
};
responseStatusCode?: number;
responseHeaders: Record<string, string>[];
};
export default class DevtoolsInterception extends Interception {
static handleRequestInterception(client: Client, mocks: Set<Interception>): (event: Event) => Promise<void | ClientResponse>;
get calls(): import("webdriverio").Matches[];
clear(): void;
restore(): void;
respond(overwrite: WebdriverIO.MockOverwrite, params?: WebdriverIO.MockResponseParams): void;
respondOnce(overwrite: WebdriverIO.MockOverwrite, params?: WebdriverIO.MockResponseParams): void;
abort(errorReason: string, sticky?: boolean): void;
abortOnce(errorReason: string): void;
}
export {};
//# sourceMappingURL=devtools.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"devtools.d.ts","sourceRoot":"","sources":["../../../src/utils/interception/devtools.ts"],"names":[],"mappings":";;;;AAMA,OAAO,YAAY,MAAM,GAAG,CAAA;AAM5B,aAAK,cAAc,GAAG;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC;IAC3C,IAAI,CAAC,EAAE,MAAM,GAAG,WAAW,CAAC,cAAc,CAAC;IAC3C,WAAW,CAAC,EAAE,MAAM,CAAC;CACxB,CAAA;AAED,aAAK,cAAc,GAAG;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,aAAa,CAAC,EAAE,OAAO,CAAA;CAC1B,CAAA;AAED,aAAK,MAAM,GAAG;IACV,IAAI,EAAE,CAAC,WAAW,EAAE,MAAM,EAAE,cAAc,EAAE,cAAc,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;CAC1F,CAAA;AAED,aAAK,KAAK,GAAG;IACT,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,WAAW,CAAC,OAAO,GAAG;QAAE,cAAc,EAAE,MAAM,GAAG,MAAM,CAAC;KAAE,CAAC;IACpE,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC;CAC7C,CAAA;AAID,MAAM,CAAC,OAAO,OAAO,oBAAqB,SAAQ,YAAY;IAC1D,MAAM,CAAC,yBAAyB,CAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,KAAK,OAAO,CAAC,IAAI,GAAG,cAAc,CAAC;IAiJ7H,IAAI,KAAK,oCAER;IAKD,KAAK;IAQL,OAAO;IAUP,OAAO,CAAE,SAAS,EAAE,WAAW,CAAC,aAAa,EAAE,MAAM,GAAE,WAAW,CAAC,kBAAuB;IAS1F,WAAW,CAAE,SAAS,EAAE,WAAW,CAAC,aAAa,EAAE,MAAM,GAAE,WAAW,CAAC,kBAAuB;IAQ9F,KAAK,CAAE,WAAW,EAAE,MAAM,EAAE,MAAM,GAAE,OAAc;IAWlD,SAAS,CAAE,WAAW,EAAE,MAAM;CAGjC"}
+184
View File
@@ -0,0 +1,184 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const atob_1 = __importDefault(require("atob"));
const minimatch_1 = __importDefault(require("minimatch"));
const logger_1 = __importDefault(require("@wdio/logger"));
const _1 = __importDefault(require("."));
const __1 = require("..");
const constants_1 = require("../../constants");
const log = logger_1.default('webdriverio');
class DevtoolsInterception extends _1.default {
static handleRequestInterception(client, mocks) {
return async (event) => {
const isRequest = !event.responseHeaders;
const eventResponseHeaders = event.responseHeaders || [];
const responseHeaders = eventResponseHeaders.reduce((headers, { name, value }) => {
headers[name] = value;
return headers;
}, {});
const { requestId, request, responseStatusCode = 200 } = event;
for (const mock of mocks) {
if (isRequest && (mock.respondOverwrites.length === 0 ||
(!mock.respondOverwrites[0].errorReason &&
mock.respondOverwrites[0].params &&
mock.respondOverwrites[0].params.fetchResponse !== false))) {
continue;
}
if (!minimatch_1.default(request.url, mock.url)) {
continue;
}
request.statusCode = responseStatusCode;
request.responseHeaders = { ...responseHeaders };
if (filterMethod(request.method, mock.filterOptions.method) ||
filterHeaders(request.headers, mock.filterOptions.requestHeaders) ||
filterHeaders(responseHeaders, mock.filterOptions.headers) ||
filterRequest(request.postData, mock.filterOptions.postData) ||
filterStatusCode(responseStatusCode, mock.filterOptions.statusCode)) {
continue;
}
const { body, base64Encoded = undefined } = isRequest ? { body: '' } : await client.send('Fetch.getResponseBody', { requestId }).catch(() => ({}));
request.body = base64Encoded ? atob_1.default(body) : body;
const contentTypeHeader = Object.keys(responseHeaders).find(h => h.toLowerCase() === 'content-type') || '';
const responseContentType = responseHeaders[contentTypeHeader];
request.body = responseContentType && responseContentType.includes('application/json')
? tryParseJson(request.body)
: request.body;
mock.matches.push(request);
if (mock.respondOverwrites.length === 0) {
continue;
}
const { errorReason, overwrite, params = {} } = mock.respondOverwrites[0].sticky
? mock.respondOverwrites[0]
: mock.respondOverwrites.shift() || {};
if (overwrite !== undefined) {
let newBody = overwrite;
if (typeof overwrite === 'function') {
newBody = await overwrite(request, client);
}
const isBodyUndefined = typeof newBody === 'undefined';
if (isBodyUndefined) {
newBody = '';
}
if (typeof newBody !== 'string') {
newBody = JSON.stringify(newBody);
}
let responseCode = typeof params.statusCode === 'function' ? params.statusCode(request) : params.statusCode || responseStatusCode;
let responseHeaders = [
...eventResponseHeaders,
...Object.entries(typeof params.headers === 'function' ? params.headers(request) : params.headers || {}).map(([name, value]) => ({ name, value }))
];
const responseFilePath = path_1.default.isAbsolute(newBody) ? newBody : path_1.default.join(process.cwd(), newBody);
if (newBody.length > 0 && await fs_extra_1.default.pathExists(responseFilePath) && await canAccess(responseFilePath)) {
newBody = await fs_extra_1.default.readFile(responseFilePath);
}
else if (newBody.startsWith('http')) {
responseCode = 301;
responseHeaders = responseHeaders.filter(({ name }) => name.toLowerCase() !== 'location');
responseHeaders.push({ name: 'Location', value: newBody });
}
request.mockedResponse = newBody;
return client.send('Fetch.fulfillRequest', {
requestId,
responseCode,
responseHeaders,
body: isBodyUndefined ? undefined : (newBody instanceof Buffer ? newBody : Buffer.from(newBody, 'utf8')).toString('base64')
}).catch(logFetchError);
}
if (errorReason) {
return client.send('Fetch.failRequest', {
requestId,
errorReason
}).catch(logFetchError);
}
}
return client.send('Fetch.continueRequest', { requestId }).catch(logFetchError);
};
}
get calls() {
return this.matches;
}
clear() {
this.matches = [];
}
restore() {
this.clear();
this.respondOverwrites = [];
}
respond(overwrite, params = {}) {
this.respondOverwrites.push({ overwrite, params, sticky: true });
}
respondOnce(overwrite, params = {}) {
this.respondOverwrites.push({ overwrite, params });
}
abort(errorReason, sticky = true) {
if (typeof errorReason !== 'string' || !constants_1.ERROR_REASON.includes(errorReason)) {
throw new Error(`Invalid value for errorReason, allowed are: ${constants_1.ERROR_REASON.join(', ')}`);
}
this.respondOverwrites.push({ errorReason, sticky });
}
abortOnce(errorReason) {
this.abort(errorReason, false);
}
}
exports.default = DevtoolsInterception;
const filterMethod = (method, expected) => {
if (typeof expected === 'undefined') {
return false;
}
if (typeof expected === 'function') {
return expected(method) !== true;
}
return expected.toLowerCase() !== method.toLowerCase();
};
const filterHeaders = (responseHeaders, expected) => {
if (typeof expected === 'undefined') {
return false;
}
if (typeof expected === 'function') {
return expected(responseHeaders) !== true;
}
return !__1.containsHeaderObject(responseHeaders, expected);
};
const filterRequest = (postData, expected) => {
if (typeof expected === 'undefined') {
return false;
}
if (typeof expected === 'function') {
return expected(postData) !== true;
}
return postData !== expected;
};
const filterStatusCode = (statusCode, expected) => {
if (typeof expected === 'undefined') {
return false;
}
if (typeof expected === 'function') {
return expected(statusCode) !== true;
}
return statusCode !== expected;
};
const canAccess = async (filepath) => {
try {
await fs_extra_1.default.access(filepath);
return true;
}
catch (_a) {
return false;
}
};
const tryParseJson = (body) => {
try {
return JSON.parse(body) || body;
}
catch (_a) {
return body;
}
};
const logFetchError = (err) => {
log.debug(err === null || err === void 0 ? void 0 : err.message);
};
+19
View File
@@ -0,0 +1,19 @@
/// <reference types="webdriverio/webdriverio-core" />
/// <reference types="webdriverio" />
/// <reference types="@wdio/cucumber-framework" />
export default class Interception {
url: string;
filterOptions: WebdriverIO.MockFilterOptions;
browser: WebdriverIO.BrowserObject;
respondOverwrites: {
overwrite?: WebdriverIO.MockOverwrite;
params?: WebdriverIO.MockResponseParams;
sticky?: boolean;
errorReason?: string;
}[];
matches: WebdriverIO.Matches[];
constructor(url: string, filterOptions: import("webdriverio").MockFilterOptions | undefined, browser: WebdriverIO.BrowserObject);
get calls(): WebdriverIO.Matches[] | Promise<WebdriverIO.Matches[]>;
waitForResponse({ timeout, interval, timeoutMsg, }?: WebdriverIO.WaitForOptions): Promise<boolean>;
}
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/utils/interception/index.ts"],"names":[],"mappings":";;;AAEA,MAAM,CAAC,OAAO,OAAO,YAAY;IAC7B,GAAG,EAAE,MAAM,CAAA;IACX,aAAa,EAAE,WAAW,CAAC,iBAAiB,CAAA;IAC5C,OAAO,EAAE,WAAW,CAAC,aAAa,CAAA;IAClC,iBAAiB,EAAE;QACf,SAAS,CAAC,EAAE,WAAW,CAAC,aAAa,CAAA;QACrC,MAAM,CAAC,EAAE,WAAW,CAAC,kBAAkB,CAAA;QACvC,MAAM,CAAC,EAAE,OAAO,CAAA;QAChB,WAAW,CAAC,EAAE,MAAM,CAAA;KACvB,EAAE,CAAK;IACR,OAAO,EAAE,WAAW,CAAC,OAAO,EAAE,CAAK;gBAEtB,GAAG,EAAE,MAAM,EAAE,aAAa,qDAAoC,EAAE,OAAO,EAAE,WAAW,CAAC,aAAa;IAM/G,IAAI,KAAK,IAAK,WAAW,CAAC,OAAO,EAAE,GAAG,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC,CAEnE;IAED,eAAe,CAAE,EACb,OAA6C,EAC7C,QAA+C,EAC/C,UAAU,GACb,GAAE,WAAW,CAAC,cAAmB;CA2BrC"}
+38
View File
@@ -0,0 +1,38 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Timer_1 = __importDefault(require("../Timer"));
class Interception {
constructor(url, filterOptions = {}, browser) {
this.respondOverwrites = [];
this.matches = [];
this.url = url;
this.filterOptions = filterOptions;
this.browser = browser;
}
get calls() {
throw new Error('Implement me');
}
waitForResponse({ timeout = this.browser.options.waitforTimeout, interval = this.browser.options.waitforInterval, timeoutMsg, } = {}) {
if (typeof timeout !== 'number') {
timeout = this.browser.options.waitforTimeout;
}
if (typeof interval !== 'number') {
interval = this.browser.options.waitforInterval;
}
const fn = async () => this.calls && (await this.calls).length > 0;
const timer = new Timer_1.default(interval, timeout, fn, true);
return this.browser.call(() => timer.catch((e) => {
if (e.message === 'timeout') {
if (typeof timeoutMsg === 'string') {
throw new Error(timeoutMsg);
}
throw new Error(`waitForResponse timed out after ${timeout}ms`);
}
throw new Error(`waitForResponse failed with the following reason: ${(e && e.message) || e}`);
}));
}
}
exports.default = Interception;
+16
View File
@@ -0,0 +1,16 @@
/// <reference types="webdriverio/webdriverio-core" />
/// <reference types="webdriverio" />
/// <reference types="@wdio/cucumber-framework" />
import Interception from '.';
export default class WebDriverInterception extends Interception {
mockId?: string;
init(): Promise<void>;
get calls(): Promise<import("webdriverio").Matches[]>;
clear(): Promise<void>;
restore(): Promise<void>;
respond(overwrite: WebdriverIO.MockOverwrite, params?: WebdriverIO.MockResponseParams): Promise<void>;
respondOnce(overwrite: WebdriverIO.MockOverwrite, params?: WebdriverIO.MockResponseParams): Promise<void>;
abort(errorReason: string, sticky?: boolean): Promise<void>;
abortOnce(errorReason: string): Promise<void>;
}
//# sourceMappingURL=webdriver.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"webdriver.d.ts","sourceRoot":"","sources":["../../../src/utils/interception/webdriver.ts"],"names":[],"mappings":";;;AAAA,OAAO,YAAY,MAAM,GAAG,CAAA;AAS5B,MAAM,CAAC,OAAO,OAAO,qBAAsB,SAAQ,YAAY;IAC3D,MAAM,CAAC,EAAE,MAAM,CAAC;IAEV,IAAI;IAQV,IAAI,KAAK,6CAIR;IAKD,KAAK;IASL,OAAO;IAUP,OAAO,CAAE,SAAS,EAAE,WAAW,CAAC,aAAa,EAAE,MAAM,GAAE,WAAW,CAAC,kBAAuB;IAc1F,WAAW,CAAE,SAAS,EAAE,WAAW,CAAC,aAAa,EAAE,MAAM,GAAE,WAAW,CAAC,kBAAuB;IAa9F,KAAK,CAAE,WAAW,EAAE,MAAM,EAAE,MAAM,GAAE,OAAc;IAgBlD,SAAS,CAAE,WAAW,EAAE,MAAM;CAGjC"}
+38
View File
@@ -0,0 +1,38 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const _1 = __importDefault(require("."));
const constants_1 = require("../../constants");
class WebDriverInterception extends _1.default {
async init() {
const { mockId } = await this.browser.mockRequest(this.url, this.filterOptions);
this.mockId = mockId;
}
get calls() {
return this.browser.call(async () => this.browser.getMockCalls(this.mockId));
}
clear() {
return this.browser.call(async () => this.browser.clearMockCalls(this.mockId));
}
restore() {
return this.browser.call(async () => this.browser.clearMockCalls(this.mockId, true));
}
respond(overwrite, params = {}) {
return this.browser.call(async () => this.browser.respondMock(this.mockId, { overwrite, params, sticky: true }));
}
respondOnce(overwrite, params = {}) {
return this.browser.call(async () => this.browser.respondMock(this.mockId, { overwrite, params }));
}
abort(errorReason, sticky = true) {
if (typeof errorReason !== 'string' || !constants_1.ERROR_REASON.includes(errorReason)) {
throw new Error(`Invalid value for errorReason, allowed are: ${constants_1.ERROR_REASON.join(', ')}`);
}
return this.browser.call(async () => this.browser.respondMock(this.mockId, { errorReason, sticky }));
}
abortOnce(errorReason) {
return this.abort(errorReason, false);
}
}
exports.default = WebDriverInterception;
+3
View File
@@ -0,0 +1,3 @@
/// <reference types="webdriverio/webdriverio-core" />
export default function refetchElement(currentElement: WebdriverIO.Element, commandName: string): Promise<WebdriverIO.Element>;
//# sourceMappingURL=refetchElement.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"refetchElement.d.ts","sourceRoot":"","sources":["../../src/utils/refetchElement.ts"],"names":[],"mappings":";AAMA,wBAA8B,cAAc,CACxC,cAAc,EAAE,WAAW,CAAC,OAAO,EACnC,WAAW,EAAE,MAAM,GACpB,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAuB9B"}
+22
View File
@@ -0,0 +1,22 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const implicitWait_1 = __importDefault(require("./implicitWait"));
async function refetchElement(currentElement, commandName) {
let selectors = [];
while (currentElement.elementId && currentElement.parent) {
selectors.push({ selector: currentElement.selector, index: currentElement.index || 0 });
currentElement = currentElement.parent;
}
selectors.reverse();
const length = selectors.length;
return selectors.reduce(async (elementPromise, { selector, index }, currentIndex) => {
const resolvedElement = await elementPromise;
let nextElement = index > 0 ? (await resolvedElement.$$(selector))[index] : null;
nextElement = nextElement || await resolvedElement.$(selector);
return await implicitWait_1.default(nextElement, currentIndex + 1 < length ? '$' : commandName);
}, Promise.resolve(currentElement));
}
exports.default = refetchElement;