Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@wdio/utils

Package Overview
Dependencies
Maintainers
7
Versions
298
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@wdio/utils - npm Package Compare versions

Comparing version 6.5.0 to 6.6.0

build/envDetector.d.ts

168

build/envDetector.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isW3C = isW3C;
exports.capabilitiesEnvironmentDetector = capabilitiesEnvironmentDetector;
exports.sessionEnvironmentDetector = sessionEnvironmentDetector;
exports.devtoolsEnvironmentDetector = devtoolsEnvironmentDetector;
exports.webdriverEnvironmentDetector = webdriverEnvironmentDetector;
Object.defineProperty(exports, "__esModule", { value: true });
exports.webdriverEnvironmentDetector = exports.devtoolsEnvironmentDetector = exports.sessionEnvironmentDetector = exports.capabilitiesEnvironmentDetector = exports.isW3C = void 0;
const MOBILE_BROWSER_NAMES = ['ipad', 'iphone', 'android'];
const MOBILE_CAPABILITIES = ['appium-version', 'appiumVersion', 'device-type', 'deviceType', 'device-orientation', 'deviceOrientation', 'deviceName'];
const MOBILE_CAPABILITIES = [
'appium-version', 'appiumVersion', 'device-type', 'deviceType',
'device-orientation', 'deviceOrientation', 'deviceName'
];
function isW3C(capabilities) {
if (!capabilities) {
return false;
}
const isAppium = capabilities.automationName || capabilities.deviceName || capabilities.appiumVersion;
const hasW3CCaps = capabilities.platformName && capabilities.browserVersion && (capabilities.platformVersion || Object.prototype.hasOwnProperty.call(capabilities, 'setWindowRect'));
return Boolean(hasW3CCaps || isAppium);
if (!capabilities) {
return false;
}
const isAppium = capabilities.automationName || capabilities.deviceName || (capabilities.appiumVersion);
const hasW3CCaps = (capabilities.platformName &&
capabilities.browserVersion &&
(capabilities.platformVersion || Object.prototype.hasOwnProperty.call(capabilities, 'setWindowRect')));
return Boolean(hasW3CCaps || isAppium);
}
exports.isW3C = isW3C;
function isChrome(caps) {
if (!caps) {
return false;
}
return Boolean(caps.chrome) || Boolean(caps['goog:chromeOptions']);
if (!caps) {
return false;
}
return (Boolean(caps.chrome) ||
Boolean(caps['goog:chromeOptions']));
}
function isMobile(caps) {
if (!caps) {
return false;
}
const browserName = (caps.browserName || '').toLowerCase();
return Boolean(Object.keys(caps).find(cap => MOBILE_CAPABILITIES.includes(cap)) || caps.browserName === '' || MOBILE_BROWSER_NAMES.includes(browserName));
if (!caps) {
return false;
}
const browserName = (caps.browserName || '').toLowerCase();
return Boolean(Object.keys(caps).find((cap) => MOBILE_CAPABILITIES.includes(cap)) ||
caps.browserName === '' ||
MOBILE_BROWSER_NAMES.includes(browserName));
}
function isIOS(caps) {
if (!caps) {
return false;
}
return Boolean(caps.platformName && caps.platformName.match(/iOS/i) || caps.deviceName && caps.deviceName.match(/(iPad|iPhone)/i));
if (!caps) {
return false;
}
return Boolean((caps.platformName && caps.platformName.match(/iOS/i)) ||
(caps.deviceName && caps.deviceName.match(/(iPad|iPhone)/i)));
}
function isAndroid(caps) {
if (!caps) {
return false;
}
return Boolean(caps.platformName && caps.platformName.match(/Android/i) || caps.browserName && caps.browserName.match(/Android/i));
if (!caps) {
return false;
}
return Boolean((caps.platformName && caps.platformName.match(/Android/i)) ||
(caps.browserName && caps.browserName.match(/Android/i)));
}
function isSauce(caps) {
return Boolean(caps.extendedDebugging || caps['sauce:options'] && caps['sauce:options'].extendedDebugging);
return Boolean(caps.extendedDebugging ||
(caps['sauce:options'] &&
caps['sauce:options'].extendedDebugging));
}
function isSeleniumStandalone(caps) {
if (!caps) {
return false;
}
return Boolean(caps['webdriver.remote.sessionid']);
if (!caps) {
return false;
}
return Boolean(caps['webdriver.remote.sessionid']);
}
function capabilitiesEnvironmentDetector(capabilities, automationProtocol) {
return automationProtocol === 'devtools' ? devtoolsEnvironmentDetector(capabilities) : webdriverEnvironmentDetector(capabilities);
return automationProtocol === 'devtools' ? devtoolsEnvironmentDetector(capabilities) : webdriverEnvironmentDetector(capabilities);
}
function sessionEnvironmentDetector({
capabilities,
requestedCapabilities
}) {
return {
isW3C: isW3C(capabilities),
isChrome: isChrome(capabilities),
isMobile: isMobile(capabilities),
isIOS: isIOS(capabilities),
isAndroid: isAndroid(capabilities),
isSauce: isSauce(requestedCapabilities),
isSeleniumStandalone: isSeleniumStandalone(capabilities)
};
exports.capabilitiesEnvironmentDetector = capabilitiesEnvironmentDetector;
function sessionEnvironmentDetector({ capabilities, requestedCapabilities }) {
return {
isW3C: isW3C(capabilities),
isChrome: isChrome(capabilities),
isMobile: isMobile(capabilities),
isIOS: isIOS(capabilities),
isAndroid: isAndroid(capabilities),
isSauce: isSauce(requestedCapabilities),
isSeleniumStandalone: isSeleniumStandalone(capabilities)
};
}
function devtoolsEnvironmentDetector({
browserName
}) {
return {
isDevTools: true,
isW3C: true,
isMobile: false,
isIOS: false,
isAndroid: false,
isChrome: browserName === 'chrome',
isSauce: false,
isSeleniumStandalone: false
};
exports.sessionEnvironmentDetector = sessionEnvironmentDetector;
function devtoolsEnvironmentDetector({ browserName }) {
return {
isDevTools: true,
isW3C: true,
isMobile: false,
isIOS: false,
isAndroid: false,
isChrome: browserName === 'chrome',
isSauce: false,
isSeleniumStandalone: false,
};
}
exports.devtoolsEnvironmentDetector = devtoolsEnvironmentDetector;
function webdriverEnvironmentDetector(capabilities) {
return {
isChrome: isChrome(capabilities),
isMobile: isMobile(capabilities),
isIOS: isIOS(capabilities),
isAndroid: isAndroid(capabilities),
isSauce: isSauce(capabilities)
};
}
return {
isChrome: isChrome(capabilities),
isMobile: isMobile(capabilities),
isIOS: isIOS(capabilities),
isAndroid: isAndroid(capabilities),
isSauce: isSauce(capabilities)
};
}
exports.webdriverEnvironmentDetector = webdriverEnvironmentDetector;
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "initialisePlugin", {
enumerable: true,
get: function () {
return _initialisePlugin.default;
}
});
Object.defineProperty(exports, "initialiseWorkerService", {
enumerable: true,
get: function () {
return _initialiseServices.initialiseWorkerService;
}
});
Object.defineProperty(exports, "initialiseLauncherService", {
enumerable: true,
get: function () {
return _initialiseServices.initialiseLauncherService;
}
});
Object.defineProperty(exports, "webdriverMonad", {
enumerable: true,
get: function () {
return _monad.default;
}
});
Object.defineProperty(exports, "commandCallStructure", {
enumerable: true,
get: function () {
return _utils.commandCallStructure;
}
});
Object.defineProperty(exports, "isValidParameter", {
enumerable: true,
get: function () {
return _utils.isValidParameter;
}
});
Object.defineProperty(exports, "getArgumentType", {
enumerable: true,
get: function () {
return _utils.getArgumentType;
}
});
Object.defineProperty(exports, "safeRequire", {
enumerable: true,
get: function () {
return _utils.safeRequire;
}
});
Object.defineProperty(exports, "isFunctionAsync", {
enumerable: true,
get: function () {
return _utils.isFunctionAsync;
}
});
Object.defineProperty(exports, "transformCommandLogResult", {
enumerable: true,
get: function () {
return _utils.transformCommandLogResult;
}
});
Object.defineProperty(exports, "canAccess", {
enumerable: true,
get: function () {
return _utils.canAccess;
}
});
Object.defineProperty(exports, "sleep", {
enumerable: true,
get: function () {
return _utils.sleep;
}
});
Object.defineProperty(exports, "wrapCommand", {
enumerable: true,
get: function () {
return _shim.wrapCommand;
}
});
Object.defineProperty(exports, "runFnInFiberContext", {
enumerable: true,
get: function () {
return _shim.runFnInFiberContext;
}
});
Object.defineProperty(exports, "executeHooksWithArgs", {
enumerable: true,
get: function () {
return _shim.executeHooksWithArgs;
}
});
Object.defineProperty(exports, "hasWdioSyncSupport", {
enumerable: true,
get: function () {
return _shim.hasWdioSyncSupport;
}
});
Object.defineProperty(exports, "executeSync", {
enumerable: true,
get: function () {
return _shim.executeSync;
}
});
Object.defineProperty(exports, "executeAsync", {
enumerable: true,
get: function () {
return _shim.executeAsync;
}
});
Object.defineProperty(exports, "testFnWrapper", {
enumerable: true,
get: function () {
return _testFramework.testFnWrapper;
}
});
Object.defineProperty(exports, "runTestInFiberContext", {
enumerable: true,
get: function () {
return _testFramework.runTestInFiberContext;
}
});
Object.defineProperty(exports, "isW3C", {
enumerable: true,
get: function () {
return _envDetector.isW3C;
}
});
Object.defineProperty(exports, "capabilitiesEnvironmentDetector", {
enumerable: true,
get: function () {
return _envDetector.capabilitiesEnvironmentDetector;
}
});
Object.defineProperty(exports, "sessionEnvironmentDetector", {
enumerable: true,
get: function () {
return _envDetector.sessionEnvironmentDetector;
}
});
Object.defineProperty(exports, "devtoolsEnvironmentDetector", {
enumerable: true,
get: function () {
return _envDetector.devtoolsEnvironmentDetector;
}
});
var _initialisePlugin = _interopRequireDefault(require("./initialisePlugin"));
var _initialiseServices = require("./initialiseServices");
var _monad = _interopRequireDefault(require("./monad"));
var _utils = require("./utils");
var _shim = require("./shim");
var _testFramework = require("./test-framework");
var _envDetector = require("./envDetector");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.devtoolsEnvironmentDetector = exports.capabilitiesEnvironmentDetector = exports.sessionEnvironmentDetector = exports.isW3C = exports.hasWdioSyncSupport = exports.executeHooksWithArgs = exports.testFnWrapper = exports.runTestInFiberContext = exports.runFnInFiberContext = exports.executeAsync = exports.executeSync = exports.wrapCommand = exports.sleep = exports.canAccess = exports.safeRequire = exports.getArgumentType = exports.isValidParameter = exports.commandCallStructure = exports.webdriverMonad = exports.transformCommandLogResult = exports.isFunctionAsync = exports.initialiseWorkerService = exports.initialiseLauncherService = exports.initialisePlugin = void 0;
const initialisePlugin_1 = __importDefault(require("./initialisePlugin"));
exports.initialisePlugin = initialisePlugin_1.default;
const initialiseServices_1 = require("./initialiseServices");
Object.defineProperty(exports, "initialiseWorkerService", { enumerable: true, get: function () { return initialiseServices_1.initialiseWorkerService; } });
Object.defineProperty(exports, "initialiseLauncherService", { enumerable: true, get: function () { return initialiseServices_1.initialiseLauncherService; } });
const monad_1 = __importDefault(require("./monad"));
exports.webdriverMonad = monad_1.default;
const utils_1 = require("./utils");
Object.defineProperty(exports, "commandCallStructure", { enumerable: true, get: function () { return utils_1.commandCallStructure; } });
Object.defineProperty(exports, "isValidParameter", { enumerable: true, get: function () { return utils_1.isValidParameter; } });
Object.defineProperty(exports, "getArgumentType", { enumerable: true, get: function () { return utils_1.getArgumentType; } });
Object.defineProperty(exports, "safeRequire", { enumerable: true, get: function () { return utils_1.safeRequire; } });
Object.defineProperty(exports, "isFunctionAsync", { enumerable: true, get: function () { return utils_1.isFunctionAsync; } });
Object.defineProperty(exports, "transformCommandLogResult", { enumerable: true, get: function () { return utils_1.transformCommandLogResult; } });
Object.defineProperty(exports, "canAccess", { enumerable: true, get: function () { return utils_1.canAccess; } });
Object.defineProperty(exports, "sleep", { enumerable: true, get: function () { return utils_1.sleep; } });
const shim_1 = require("./shim");
Object.defineProperty(exports, "wrapCommand", { enumerable: true, get: function () { return shim_1.wrapCommand; } });
Object.defineProperty(exports, "runFnInFiberContext", { enumerable: true, get: function () { return shim_1.runFnInFiberContext; } });
Object.defineProperty(exports, "executeHooksWithArgs", { enumerable: true, get: function () { return shim_1.executeHooksWithArgs; } });
Object.defineProperty(exports, "hasWdioSyncSupport", { enumerable: true, get: function () { return shim_1.hasWdioSyncSupport; } });
Object.defineProperty(exports, "executeSync", { enumerable: true, get: function () { return shim_1.executeSync; } });
Object.defineProperty(exports, "executeAsync", { enumerable: true, get: function () { return shim_1.executeAsync; } });
const test_framework_1 = require("./test-framework");
Object.defineProperty(exports, "testFnWrapper", { enumerable: true, get: function () { return test_framework_1.testFnWrapper; } });
Object.defineProperty(exports, "runTestInFiberContext", { enumerable: true, get: function () { return test_framework_1.runTestInFiberContext; } });
const envDetector_1 = require("./envDetector");
Object.defineProperty(exports, "isW3C", { enumerable: true, get: function () { return envDetector_1.isW3C; } });
Object.defineProperty(exports, "capabilitiesEnvironmentDetector", { enumerable: true, get: function () { return envDetector_1.capabilitiesEnvironmentDetector; } });
Object.defineProperty(exports, "sessionEnvironmentDetector", { enumerable: true, get: function () { return envDetector_1.sessionEnvironmentDetector; } });
Object.defineProperty(exports, "devtoolsEnvironmentDetector", { enumerable: true, get: function () { return envDetector_1.devtoolsEnvironmentDetector; } });
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const utils_1 = require("./utils");
function initialisePlugin(name, type) {
if (name[0] === '@' || path_1.default.isAbsolute(name)) {
const service = utils_1.safeRequire(name);
return service;
}
const scopedPlugin = utils_1.safeRequire(`@wdio/${name.toLowerCase()}-${type}`);
if (scopedPlugin) {
return scopedPlugin;
}
const plugin = utils_1.safeRequire(`wdio-${name.toLowerCase()}-${type}`);
if (plugin) {
return plugin;
}
throw new Error(`Couldn't find plugin "${name}" ${type}, neither as wdio scoped package ` +
`"@wdio/${name.toLowerCase()}-${type}" nor as community package ` +
`"wdio-${name.toLowerCase()}-${type}". Please make sure you have it installed!`);
}
exports.default = initialisePlugin;
var _path = _interopRequireDefault(require("path"));
var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function initialisePlugin(name, type) {
if (name[0] === '@' || _path.default.isAbsolute(name)) {
const service = (0, _utils.safeRequire)(name);
return service;
}
const scopedPlugin = (0, _utils.safeRequire)(`@wdio/${name.toLowerCase()}-${type}`);
if (scopedPlugin) {
return scopedPlugin;
}
const plugin = (0, _utils.safeRequire)(`wdio-${name.toLowerCase()}-${type}`);
if (plugin) {
return plugin;
}
throw new Error(`Couldn't find plugin "${name}" ${type}, neither as wdio scoped package ` + `"@wdio/${name.toLowerCase()}-${type}" nor as community package ` + `"wdio-${name.toLowerCase()}-${type}". Please make sure you have it installed!`);
}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.initialiseLauncherService = initialiseLauncherService;
exports.initialiseWorkerService = initialiseWorkerService;
var _logger = _interopRequireDefault(require("@wdio/logger"));
var _initialisePlugin = _interopRequireDefault(require("./initialisePlugin"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const log = (0, _logger.default)('@wdio/utils:initialiseServices');
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initialiseWorkerService = exports.initialiseLauncherService = void 0;
const logger_1 = __importDefault(require("@wdio/logger"));
const initialisePlugin_1 = __importDefault(require("./initialisePlugin"));
const log = logger_1.default('@wdio/utils:initialiseServices');
function initialiseServices(services) {
const initialisedServices = [];
for (let [serviceName, serviceConfig = {}] of services) {
if (typeof serviceName === 'object') {
log.debug('initialise custom initiated service');
initialisedServices.push([serviceName, {}]);
continue;
const initialisedServices = [];
for (let [serviceName, serviceConfig = {}] of services) {
if (typeof serviceName === 'object') {
log.debug('initialise custom initiated service');
initialisedServices.push([serviceName, {}]);
continue;
}
if (typeof serviceName === 'function') {
log.debug(`initialise custom service "${serviceName.name}"`);
initialisedServices.push([serviceName, serviceConfig]);
continue;
}
log.debug(`initialise service "${serviceName}" as NPM package`);
const service = initialisePlugin_1.default(serviceName, 'service');
initialisedServices.push([service, serviceConfig, serviceName]);
}
if (typeof serviceName === 'function') {
log.debug(`initialise custom service "${serviceName.name}"`);
initialisedServices.push([serviceName, serviceConfig]);
continue;
}
log.debug(`initialise service "${serviceName}" as NPM package`);
const service = (0, _initialisePlugin.default)(serviceName, 'service');
initialisedServices.push([service, serviceConfig, serviceName]);
}
return initialisedServices;
return initialisedServices;
}
function sanitizeServiceArray(service) {
return Array.isArray(service) ? service : [service, {}];
return Array.isArray(service) ? service : [service, {}];
}
function initialiseLauncherService(config, caps) {
const ignoredWorkerServices = [];
const launcherServices = [];
try {
const services = initialiseServices(config.services.map(sanitizeServiceArray));
for (const [service, serviceConfig, serviceName] of services) {
if (typeof service === 'object' && !serviceName) {
launcherServices.push(service);
continue;
}
const Launcher = service.launcher || service;
if (typeof Launcher === 'function') {
launcherServices.push(new Launcher(serviceConfig, caps, config));
}
if (serviceName && typeof service.default !== 'function' && typeof service !== 'function') {
ignoredWorkerServices.push(serviceName);
}
const ignoredWorkerServices = [];
const launcherServices = [];
try {
const services = initialiseServices(config.services.map(sanitizeServiceArray));
for (const [service, serviceConfig, serviceName] of services) {
if (typeof service === 'object' && !serviceName) {
launcherServices.push(service);
continue;
}
const Launcher = service.launcher || service;
if (typeof Launcher === 'function') {
launcherServices.push(new Launcher(serviceConfig, caps, config));
}
if (serviceName &&
typeof service.default !== 'function' &&
typeof service !== 'function') {
ignoredWorkerServices.push(serviceName);
}
}
}
} catch (err) {
log.error(err);
}
return {
ignoredWorkerServices,
launcherServices
};
catch (err) {
log.error(err);
}
return { ignoredWorkerServices, launcherServices };
}
exports.initialiseLauncherService = initialiseLauncherService;
function initialiseWorkerService(config, caps, ignoredWorkerServices = []) {
const workerServices = config.services.map(sanitizeServiceArray).filter(([serviceName]) => !ignoredWorkerServices.includes(serviceName));
try {
const services = initialiseServices(workerServices);
return services.map(([service, serviceConfig, serviceName]) => {
if (typeof service === 'object' && !serviceName) {
return service;
}
const Service = service.default || service;
if (typeof Service === 'function') {
return new Service(serviceConfig, caps, config);
}
}).filter(Boolean);
} catch (err) {
log.error(err);
return [];
}
}
const workerServices = config.services
.map(sanitizeServiceArray)
.filter(([serviceName]) => !ignoredWorkerServices.includes(serviceName));
try {
const services = initialiseServices(workerServices);
return services.map(([service, serviceConfig, serviceName]) => {
if (typeof service === 'object' && !serviceName) {
return service;
}
const Service = service.default || service;
if (typeof Service === 'function') {
return new Service(serviceConfig, caps, config);
}
}).filter(Boolean);
}
catch (err) {
log.error(err);
return [];
}
}
exports.initialiseWorkerService = initialiseWorkerService;
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = WebDriver;
var _events = require("events");
var _logger = _interopRequireDefault(require("@wdio/logger"));
var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const events_1 = require("events");
const logger_1 = __importDefault(require("@wdio/logger"));
const utils_1 = require("./utils");
const SCOPE_TYPES = {
'browser': function Browser() {},
'element': function Element() {}
'browser': function Browser() { },
'element': function Element() { }
};
function WebDriver(options, modifier, propertiesObject = {}) {
const scopeType = SCOPE_TYPES[propertiesObject.scope] || SCOPE_TYPES['browser'];
delete propertiesObject.scope;
const prototype = Object.create(scopeType.prototype);
const log = (0, _logger.default)('webdriver');
const eventHandler = new _events.EventEmitter();
const EVENTHANDLER_FUNCTIONS = Object.getPrototypeOf(eventHandler);
function unit(sessionId, commandWrapper) {
propertiesObject.commandList = {
value: Object.keys(propertiesObject)
};
propertiesObject.options = {
value: options
};
propertiesObject.requestedCapabilities = {
value: options.requestedCapabilities
};
if (typeof commandWrapper === 'function') {
for (const [commandName, {
value
}] of Object.entries(propertiesObject)) {
if (typeof value !== 'function') {
continue;
const scopeType = SCOPE_TYPES[propertiesObject.scope] || SCOPE_TYPES['browser'];
delete propertiesObject.scope;
const prototype = Object.create(scopeType.prototype);
const log = logger_1.default('webdriver');
const eventHandler = new events_1.EventEmitter();
const EVENTHANDLER_FUNCTIONS = Object.getPrototypeOf(eventHandler);
function unit(sessionId, commandWrapper) {
propertiesObject.commandList = { value: Object.keys(propertiesObject) };
propertiesObject.options = { value: options };
propertiesObject.requestedCapabilities = { value: options.requestedCapabilities };
if (typeof commandWrapper === 'function') {
for (const [commandName, { value }] of Object.entries(propertiesObject)) {
if (typeof value !== 'function') {
continue;
}
propertiesObject[commandName].value = commandWrapper(commandName, value);
propertiesObject[commandName].configurable = true;
}
}
propertiesObject[commandName].value = commandWrapper(commandName, value);
propertiesObject[commandName].configurable = true;
}
utils_1.overwriteElementCommands.call(this, propertiesObject);
const { puppeteer, ...propertiesObjectWithoutPuppeteer } = propertiesObject;
propertiesObject['__propertiesObject__'] = { value: propertiesObjectWithoutPuppeteer };
let client = Object.create(prototype, propertiesObject);
client.sessionId = sessionId;
if (scopeType.name === 'Browser') {
client.capabilities = options.capabilities;
}
if (typeof modifier === 'function') {
client = modifier(client, options);
}
client.addCommand = function (name, func, attachToElement = false, proto, instances) {
const customCommand = typeof commandWrapper === 'function'
? commandWrapper(name, func)
: func;
if (attachToElement) {
if (instances) {
Object.values(instances).forEach(instance => {
instance.__propertiesObject__[name] = {
value: customCommand
};
});
}
this.__propertiesObject__[name] = { value: customCommand };
}
else {
unit.lift(name, customCommand, proto);
}
};
client.overwriteCommand = function (name, func, attachToElement = false, proto, instances) {
let customCommand = typeof commandWrapper === 'function'
? commandWrapper(name, func)
: func;
if (attachToElement) {
if (instances) {
Object.values(instances).forEach(instance => {
instance.__propertiesObject__.__elementOverrides__.value[name] = customCommand;
});
}
else {
this.__propertiesObject__.__elementOverrides__.value[name] = customCommand;
}
}
else if (client[name]) {
const origCommand = client[name];
delete client[name];
unit.lift(name, customCommand, proto, (...args) => origCommand.apply(this, args));
}
else {
throw new Error('overwriteCommand: no command to be overwritten: ' + name);
}
};
return client;
}
_utils.overwriteElementCommands.call(this, propertiesObject);
const {
puppeteer
} = propertiesObject,
propertiesObjectWithoutPuppeteer = _objectWithoutProperties(propertiesObject, ["puppeteer"]);
propertiesObject['__propertiesObject__'] = {
value: propertiesObjectWithoutPuppeteer
unit.lift = function (name, func, proto, origCommand) {
(proto || prototype)[name] = function next(...args) {
log.info('COMMAND', utils_1.commandCallStructure(name, args));
Object.defineProperty(func, 'name', {
value: name,
writable: false,
});
const result = func.apply(this, origCommand ? [origCommand, ...args] : args);
Promise.resolve(result).then((res) => {
log.info('RESULT', res);
this.emit('result', { name, result: res });
}).catch(() => { });
return result;
};
};
let client = Object.create(prototype, propertiesObject);
client.sessionId = sessionId;
if (scopeType.name === 'Browser') {
client.capabilities = options.capabilities;
for (let eventCommand in EVENTHANDLER_FUNCTIONS) {
prototype[eventCommand] = function (...args) {
eventHandler[eventCommand](...args);
return this;
};
}
if (typeof modifier === 'function') {
client = modifier(client, options);
}
client.addCommand = function (name, func, attachToElement = false, proto, instances) {
const customCommand = typeof commandWrapper === 'function' ? commandWrapper(name, func) : func;
if (attachToElement) {
if (instances) {
Object.values(instances).forEach(instance => {
instance.__propertiesObject__[name] = {
value: customCommand
};
});
}
this.__propertiesObject__[name] = {
value: customCommand
};
} else {
unit.lift(name, customCommand, proto);
}
};
client.overwriteCommand = function (name, func, attachToElement = false, proto, instances) {
let customCommand = typeof commandWrapper === 'function' ? commandWrapper(name, func) : func;
if (attachToElement) {
if (instances) {
Object.values(instances).forEach(instance => {
instance.__propertiesObject__.__elementOverrides__.value[name] = customCommand;
});
} else {
this.__propertiesObject__.__elementOverrides__.value[name] = customCommand;
}
} else if (client[name]) {
const origCommand = client[name];
delete client[name];
unit.lift(name, customCommand, proto, (...args) => origCommand.apply(this, args));
} else {
throw new Error('overwriteCommand: no command to be overwritten: ' + name);
}
};
return client;
}
unit.lift = function (name, func, proto, origCommand) {
(proto || prototype)[name] = function next(...args) {
log.info('COMMAND', (0, _utils.commandCallStructure)(name, args));
Object.defineProperty(func, 'name', {
value: name,
writable: false
});
const result = func.apply(this, origCommand ? [origCommand, ...args] : args);
Promise.resolve(result).then(res => {
log.info('RESULT', res);
this.emit('result', {
name,
result: res
});
}).catch(() => {});
return result;
};
};
for (let eventCommand in EVENTHANDLER_FUNCTIONS) {
prototype[eventCommand] = function (...args) {
eventHandler[eventCommand](...args);
return this;
};
}
return unit;
}
return unit;
}
exports.default = WebDriver;
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runSync = exports.executeAsync = exports.executeSync = exports.hasWdioSyncSupport = exports.wrapCommand = exports.runFnInFiberContext = exports.executeHooksWithArgs = void 0;
var _logger = _interopRequireDefault(require("@wdio/logger"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const log = (0, _logger.default)('@wdio/utils:shim');
const logger_1 = __importDefault(require("@wdio/logger"));
const log = logger_1.default('@wdio/utils:shim');
let inCommandHook = false;

@@ -18,133 +14,110 @@ let hasWdioSyncSupport = false;

exports.runSync = runSync;
let executeHooksWithArgs = async function executeHooksWithArgsShim(hooks, args) {
if (!Array.isArray(hooks)) {
hooks = [hooks];
}
if (!Array.isArray(args)) {
args = [args];
}
hooks = hooks.map(hook => new Promise(resolve => {
let result;
try {
result = hook.apply(null, args);
} catch (e) {
log.error(e.stack);
return resolve(e);
if (!Array.isArray(hooks)) {
hooks = [hooks];
}
if (result && typeof result.then === 'function') {
return result.then(resolve, e => {
log.error(e.stack);
resolve(e);
});
if (!Array.isArray(args)) {
args = [args];
}
resolve(result);
}));
return Promise.all(hooks);
hooks = hooks.map((hook) => new Promise((resolve) => {
let result;
try {
result = hook.apply(null, args);
}
catch (e) {
log.error(e.stack);
return resolve(e);
}
if (result && typeof result.then === 'function') {
return result.then(resolve, (e) => {
log.error(e.stack);
resolve(e);
});
}
resolve(result);
}));
return Promise.all(hooks);
};
exports.executeHooksWithArgs = executeHooksWithArgs;
let runFnInFiberContext = function (fn) {
return function (...args) {
return Promise.resolve(fn.apply(this, args));
};
return function (...args) {
return Promise.resolve(fn.apply(this, args));
};
};
exports.runFnInFiberContext = runFnInFiberContext;
let wrapCommand = function wrapCommand(commandName, fn) {
return async function wrapCommandFn(...args) {
const beforeHookArgs = [commandName, args];
if (!inCommandHook && this.options.beforeCommand) {
inCommandHook = true;
await executeHooksWithArgs.call(this, this.options.beforeCommand, beforeHookArgs);
inCommandHook = false;
}
let commandResult;
let commandError;
return async function wrapCommandFn(...args) {
const beforeHookArgs = [commandName, args];
if (!inCommandHook && this.options.beforeCommand) {
inCommandHook = true;
await executeHooksWithArgs.call(this, this.options.beforeCommand, beforeHookArgs);
inCommandHook = false;
}
let commandResult;
let commandError;
try {
commandResult = await fn.apply(this, args);
}
catch (err) {
commandError = err;
}
if (!inCommandHook && this.options.afterCommand) {
inCommandHook = true;
const afterHookArgs = [...beforeHookArgs, commandResult, commandError];
await executeHooksWithArgs.call(this, this.options.afterCommand, afterHookArgs);
inCommandHook = false;
}
if (commandError) {
throw commandError;
}
return commandResult;
};
};
exports.wrapCommand = wrapCommand;
async function executeSyncFn(fn, retries, args = []) {
this.wdioRetries = retries.attempts;
try {
commandResult = await fn.apply(this, args);
} catch (err) {
commandError = err;
let res = fn.apply(this, args);
if (res instanceof Promise) {
return await res;
}
return res;
}
if (!inCommandHook && this.options.afterCommand) {
inCommandHook = true;
const afterHookArgs = [...beforeHookArgs, commandResult, commandError];
await executeHooksWithArgs.call(this, this.options.afterCommand, afterHookArgs);
inCommandHook = false;
catch (e) {
if (retries.limit > retries.attempts) {
retries.attempts++;
return await executeSync.call(this, fn, retries, args);
}
return Promise.reject(e);
}
if (commandError) {
throw commandError;
}
async function executeAsync(fn, retries, args = []) {
this.wdioRetries = retries.attempts;
try {
return await fn.apply(this, args);
}
return commandResult;
};
};
exports.wrapCommand = wrapCommand;
let executeSync = async function executeSync(fn, retries, args = []) {
this.wdioRetries = retries.attempts;
try {
let res = fn.apply(this, args);
if (res instanceof Promise) {
return await res;
catch (e) {
if (retries.limit > retries.attempts) {
retries.attempts++;
return await executeAsync.call(this, fn, retries, args);
}
throw e;
}
return res;
} catch (e) {
if (retries.limit > retries.attempts) {
retries.attempts++;
return await executeSync.call(this, fn, retries, args);
}
return Promise.reject(e);
}
};
}
exports.executeAsync = executeAsync;
let executeSync = executeSyncFn;
exports.executeSync = executeSync;
const executeAsync = async function executeAsync(fn, retries, args = []) {
this.wdioRetries = retries.attempts;
try {
return await fn.apply(this, args);
} catch (e) {
if (retries.limit > retries.attempts) {
retries.attempts++;
return await executeAsync.call(this, fn, retries, args);
try {
if (!process.env.WDIO_NO_SYNC_SUPPORT) {
const packageName = '@wdio/sync';
const wdioSync = require(packageName);
exports.hasWdioSyncSupport = hasWdioSyncSupport = true;
exports.runFnInFiberContext = runFnInFiberContext = wdioSync.runFnInFiberContext;
exports.wrapCommand = wrapCommand = wdioSync.wrapCommand;
exports.executeHooksWithArgs = executeHooksWithArgs = wdioSync.executeHooksWithArgs;
exports.executeSync = executeSync = wdioSync.executeSync;
exports.runSync = runSync = wdioSync.runSync;
}
throw e;
}
};
exports.executeAsync = executeAsync;
try {
if (!process.env.WDIO_NO_SYNC_SUPPORT) {
const packageName = '@wdio/sync';
const wdioSync = require(packageName);
exports.hasWdioSyncSupport = hasWdioSyncSupport = true;
exports.runFnInFiberContext = runFnInFiberContext = wdioSync.runFnInFiberContext;
exports.wrapCommand = wrapCommand = wdioSync.wrapCommand;
exports.executeHooksWithArgs = executeHooksWithArgs = wdioSync.executeHooksWithArgs;
exports.executeSync = executeSync = wdioSync.executeSync;
exports.runSync = runSync = wdioSync.runSync;
}
} catch (_unused) {}
}
catch (_a) {
}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
exports.logHookError = void 0;
const logHookError = (hookName, hookResults = [], cid) => {
const result = hookResults.find(result => result instanceof Error);
if (typeof result === 'undefined') {
return;
}
const error = {
message: result.message
};
const content = {
cid: cid,
error: error,
fullTitle: `${hookName} Hook`,
type: 'hook',
state: 'fail'
};
process.send({
origin: 'reporter',
name: 'printFailureMessage',
content
});
exports.logHookError = (hookName, hookResults = [], cid) => {
const result = hookResults.find(result => result instanceof Error);
if (typeof result === 'undefined') {
return;
}
const error = { message: result.message };
const content = {
cid: cid,
error: error,
fullTitle: `${hookName} Hook`,
type: 'hook',
state: 'fail'
};
process.send({
origin: 'reporter',
name: 'printFailureMessage',
content
});
};
exports.logHookError = logHookError;
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "testFnWrapper", {
enumerable: true,
get: function () {
return _testFnWrapper.testFnWrapper;
}
});
Object.defineProperty(exports, "runTestInFiberContext", {
enumerable: true,
get: function () {
return _testInterfaceWrapper.runTestInFiberContext;
}
});
var _testFnWrapper = require("./testFnWrapper");
var _testInterfaceWrapper = require("./testInterfaceWrapper");
Object.defineProperty(exports, "__esModule", { value: true });
exports.runTestInFiberContext = exports.testFnWrapper = void 0;
const testFnWrapper_1 = require("./testFnWrapper");
Object.defineProperty(exports, "testFnWrapper", { enumerable: true, get: function () { return testFnWrapper_1.testFnWrapper; } });
const testInterfaceWrapper_1 = require("./testInterfaceWrapper");
Object.defineProperty(exports, "runTestInFiberContext", { enumerable: true, get: function () { return testInterfaceWrapper_1.runTestInFiberContext; } });
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
exports.testFrameworkFnWrapper = exports.testFnWrapper = void 0;
var _utils = require("../utils");
var _errorHandler = require("./errorHandler");
var _shim = require("../shim");
const testFnWrapper = function (...args) {
return testFrameworkFnWrapper.call(this, {
executeHooksWithArgs: _shim.executeHooksWithArgs,
executeAsync: _shim.executeAsync,
runSync: _shim.runSync
}, ...args);
const utils_1 = require("../utils");
const errorHandler_1 = require("./errorHandler");
const shim_1 = require("../shim");
exports.testFnWrapper = function (...args) {
return exports.testFrameworkFnWrapper.call(this, { executeHooksWithArgs: shim_1.executeHooksWithArgs, executeAsync: shim_1.executeAsync, runSync: shim_1.runSync }, ...args);
};
exports.testFnWrapper = testFnWrapper;
const testFrameworkFnWrapper = async function ({
executeHooksWithArgs,
executeAsync,
runSync
}, type, {
specFn,
specFnArgs
}, {
beforeFn,
beforeFnArgs
}, {
afterFn,
afterFnArgs
}, cid, repeatTest = 0) {
const retries = {
attempts: 0,
limit: repeatTest
};
const beforeArgs = beforeFnArgs(this);
await (0, _errorHandler.logHookError)(`Before${type}`, await executeHooksWithArgs(beforeFn, beforeArgs), cid);
let promise;
let result;
let error;
if ((0, _utils.isFunctionAsync)(specFn) || !runSync) {
promise = executeAsync.call(this, specFn, retries, specFnArgs);
} else {
promise = new Promise(runSync.call(this, specFn, retries, specFnArgs));
}
const testStart = Date.now();
try {
result = await promise;
} catch (err) {
error = err;
}
const duration = Date.now() - testStart;
let afterArgs = afterFnArgs(this);
if (!error && afterArgs[0] && afterArgs[0].failedExpectations && afterArgs[0].failedExpectations.length) {
error = afterArgs[0].failedExpectations[0];
}
afterArgs.push({
retries,
error,
result,
duration,
passed: !error
});
await (0, _errorHandler.logHookError)(`After${type}`, await executeHooksWithArgs(afterFn, [...afterArgs]), cid);
if (error) {
throw error;
}
return result;
exports.testFrameworkFnWrapper = async function ({ executeHooksWithArgs, executeAsync, runSync }, type, { specFn, specFnArgs }, { beforeFn, beforeFnArgs }, { afterFn, afterFnArgs }, cid, repeatTest = 0) {
const retries = { attempts: 0, limit: repeatTest };
const beforeArgs = beforeFnArgs(this);
await errorHandler_1.logHookError(`Before${type}`, await executeHooksWithArgs(beforeFn, beforeArgs), cid);
let promise;
let result;
let error;
if (utils_1.isFunctionAsync(specFn) || !runSync) {
promise = executeAsync.call(this, specFn, retries, specFnArgs);
}
else {
promise = new Promise(runSync.call(this, specFn, retries, specFnArgs));
}
const testStart = Date.now();
try {
result = await promise;
}
catch (err) {
error = err;
}
const duration = Date.now() - testStart;
let afterArgs = afterFnArgs(this);
if (!error && afterArgs[0] && afterArgs[0].failedExpectations && afterArgs[0].failedExpectations.length) {
error = afterArgs[0].failedExpectations[0];
}
afterArgs.push({
retries,
error,
result,
duration,
passed: !error
});
await errorHandler_1.logHookError(`After${type}`, await executeHooksWithArgs(afterFn, [...afterArgs]), cid);
if (error) {
throw error;
}
return result;
};
exports.testFrameworkFnWrapper = testFrameworkFnWrapper;
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "__esModule", { value: true });
exports.runTestInFiberContext = exports.wrapTestFunction = exports.runSpec = exports.runHook = void 0;
var _utils = require("../utils");
var _testFnWrapper = require("./testFnWrapper");
const utils_1 = require("../utils");
const testFnWrapper_1 = require("./testFnWrapper");
const MOCHA_COMMANDS = ['skip', 'only'];
const runHook = function (hookFn, origFn, beforeFn, beforeFnArgs, afterFn, afterFnArgs, cid, repeatTest) {
return origFn(function (...hookFnArgs) {
return _testFnWrapper.testFnWrapper.call(this, 'Hook', {
specFn: hookFn,
specFnArgs: (0, _utils.filterSpecArgs)(hookFnArgs)
}, {
beforeFn,
beforeFnArgs
}, {
afterFn,
afterFnArgs
}, cid, repeatTest);
});
exports.runHook = function (hookFn, origFn, beforeFn, beforeFnArgs, afterFn, afterFnArgs, cid, repeatTest) {
return origFn(function (...hookFnArgs) {
return testFnWrapper_1.testFnWrapper.call(this, 'Hook', { specFn: hookFn, specFnArgs: utils_1.filterSpecArgs(hookFnArgs) }, { beforeFn, beforeFnArgs }, { afterFn, afterFnArgs }, cid, repeatTest);
});
};
exports.runHook = runHook;
const runSpec = function (specTitle, specFn, origFn, beforeFn, beforeFnArgs, afterFn, afterFnArgs, cid, repeatTest) {
return origFn(specTitle, function (...specFnArgs) {
return _testFnWrapper.testFnWrapper.call(this, 'Test', {
specFn,
specFnArgs: (0, _utils.filterSpecArgs)(specFnArgs)
}, {
beforeFn,
beforeFnArgs
}, {
afterFn,
afterFnArgs
}, cid, repeatTest);
});
exports.runSpec = function (specTitle, specFn, origFn, beforeFn, beforeFnArgs, afterFn, afterFnArgs, cid, repeatTest) {
return origFn(specTitle, function (...specFnArgs) {
return testFnWrapper_1.testFnWrapper.call(this, 'Test', { specFn, specFnArgs: utils_1.filterSpecArgs(specFnArgs) }, { beforeFn, beforeFnArgs }, { afterFn, afterFnArgs }, cid, repeatTest);
});
};
exports.runSpec = runSpec;
const wrapTestFunction = function (origFn, isSpec, beforeFn, beforeArgsFn, afterFn, afterArgsFn, cid) {
return function (...specArguments) {
let retryCnt = typeof specArguments[specArguments.length - 1] === 'number' ? specArguments.pop() : 0;
const specFn = typeof specArguments[0] === 'function' ? specArguments.shift() : typeof specArguments[1] === 'function' ? specArguments.pop() : undefined;
const specTitle = specArguments[0];
if (isSpec) {
if (specFn) return runSpec(specTitle, specFn, origFn, beforeFn, beforeArgsFn, afterFn, afterArgsFn, cid, retryCnt);
return origFn(specTitle);
}
return runHook(specFn, origFn, beforeFn, beforeArgsFn, afterFn, afterArgsFn, cid, retryCnt);
};
exports.wrapTestFunction = function (origFn, isSpec, beforeFn, beforeArgsFn, afterFn, afterArgsFn, cid) {
return function (...specArguments) {
let retryCnt = typeof specArguments[specArguments.length - 1] === 'number' ? specArguments.pop() : 0;
const specFn = typeof specArguments[0] === 'function' ? specArguments.shift()
: (typeof specArguments[1] === 'function' ? specArguments.pop() : undefined);
const specTitle = specArguments[0];
if (isSpec) {
if (specFn)
return exports.runSpec(specTitle, specFn, origFn, beforeFn, beforeArgsFn, afterFn, afterArgsFn, cid, retryCnt);
return origFn(specTitle);
}
return exports.runHook(specFn, origFn, beforeFn, beforeArgsFn, afterFn, afterArgsFn, cid, retryCnt);
};
};
exports.wrapTestFunction = wrapTestFunction;
const runTestInFiberContext = function (isSpec, beforeFn, beforeArgsFn, afterFn, afterArgsFn, fnName, cid, scope = global) {
const origFn = scope[fnName];
scope[fnName] = wrapTestFunction(origFn, isSpec, beforeFn, beforeArgsFn, afterFn, afterArgsFn, cid);
addMochaCommands(origFn, scope[fnName]);
exports.runTestInFiberContext = function (isSpec, beforeFn, beforeArgsFn, afterFn, afterArgsFn, fnName, cid, scope = global) {
const origFn = scope[fnName];
scope[fnName] = exports.wrapTestFunction(origFn, isSpec, beforeFn, beforeArgsFn, afterFn, afterArgsFn, cid);
addMochaCommands(origFn, scope[fnName]);
};
exports.runTestInFiberContext = runTestInFiberContext;
function addMochaCommands(origFn, newFn) {
MOCHA_COMMANDS.forEach(commandName => {
if (typeof origFn[commandName] === 'function') {
newFn[commandName] = origFn[commandName];
}
});
}
MOCHA_COMMANDS.forEach((commandName) => {
if (typeof origFn[commandName] === 'function') {
newFn[commandName] = origFn[commandName];
}
});
}
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.overwriteElementCommands = overwriteElementCommands;
exports.commandCallStructure = commandCallStructure;
exports.transformCommandLogResult = transformCommandLogResult;
exports.isValidParameter = isValidParameter;
exports.getArgumentType = getArgumentType;
exports.safeRequire = safeRequire;
exports.isFunctionAsync = isFunctionAsync;
exports.filterSpecArgs = filterSpecArgs;
exports.isBase64 = isBase64;
exports.sleep = exports.canAccess = void 0;
var _fs = _interopRequireDefault(require("fs"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sleep = exports.canAccess = exports.isBase64 = exports.filterSpecArgs = exports.isFunctionAsync = exports.safeRequire = exports.getArgumentType = exports.isValidParameter = exports.transformCommandLogResult = exports.commandCallStructure = exports.overwriteElementCommands = void 0;
const fs_1 = __importDefault(require("fs"));
const SCREENSHOT_REPLACEMENT = '"<Screenshot[base64]>"';
function overwriteElementCommands(propertiesObject) {
const elementOverrides = propertiesObject['__elementOverrides__'] ? propertiesObject['__elementOverrides__'].value : {};
for (const [commandName, userDefinedCommand] of Object.entries(elementOverrides)) {
if (typeof userDefinedCommand !== 'function') {
throw new Error('overwriteCommand: commands be overwritten only with functions, command: ' + commandName);
const elementOverrides = propertiesObject['__elementOverrides__'] ? propertiesObject['__elementOverrides__'].value : {};
for (const [commandName, userDefinedCommand] of Object.entries(elementOverrides)) {
if (typeof userDefinedCommand !== 'function') {
throw new Error('overwriteCommand: commands be overwritten only with functions, command: ' + commandName);
}
if (!propertiesObject[commandName]) {
throw new Error('overwriteCommand: no command to be overwritten: ' + commandName);
}
if (typeof propertiesObject[commandName].value !== 'function') {
throw new Error('overwriteCommand: only functions can be overwritten, command: ' + commandName);
}
const origCommand = propertiesObject[commandName].value;
delete propertiesObject[commandName];
const newCommand = function (...args) {
const element = this;
return userDefinedCommand.apply(element, [
function origCommandFunction() {
const context = this || element;
return origCommand.apply(context, arguments);
},
...args
]);
};
propertiesObject[commandName] = {
value: newCommand,
configurable: true
};
}
if (!propertiesObject[commandName]) {
throw new Error('overwriteCommand: no command to be overwritten: ' + commandName);
}
if (typeof propertiesObject[commandName].value !== 'function') {
throw new Error('overwriteCommand: only functions can be overwritten, command: ' + commandName);
}
const origCommand = propertiesObject[commandName].value;
delete propertiesObject[commandName];
const newCommand = function (...args) {
const element = this;
return userDefinedCommand.apply(element, [function origCommandFunction() {
const context = this || element;
return origCommand.apply(context, arguments);
}, ...args]);
};
propertiesObject[commandName] = {
value: newCommand,
configurable: true
};
}
delete propertiesObject['__elementOverrides__'];
propertiesObject['__elementOverrides__'] = {
value: {}
};
delete propertiesObject['__elementOverrides__'];
propertiesObject['__elementOverrides__'] = { value: {} };
}
exports.overwriteElementCommands = overwriteElementCommands;
function commandCallStructure(commandName, args) {
const callArgs = args.map(arg => {
if (typeof arg === 'string' && (arg.startsWith('!function(') || arg.startsWith('return (function'))) {
arg = '<fn>';
} else if (typeof arg === 'string' && !commandName.startsWith('findElement') && isBase64(arg)) {
arg = SCREENSHOT_REPLACEMENT;
} else if (typeof arg === 'string') {
arg = `"${arg}"`;
} else if (typeof arg === 'function') {
arg = '<fn>';
} else if (arg === null) {
arg = 'null';
} else if (typeof arg === 'object') {
arg = '<object>';
} else if (typeof arg === 'undefined') {
arg = typeof arg;
}
return arg;
}).join(', ');
return `${commandName}(${callArgs})`;
const callArgs = args.map((arg) => {
if (typeof arg === 'string' && (arg.startsWith('!function(') || arg.startsWith('return (function'))) {
arg = '<fn>';
}
else if (typeof arg === 'string' &&
!commandName.startsWith('findElement') &&
isBase64(arg)) {
arg = SCREENSHOT_REPLACEMENT;
}
else if (typeof arg === 'string') {
arg = `"${arg}"`;
}
else if (typeof arg === 'function') {
arg = '<fn>';
}
else if (arg === null) {
arg = 'null';
}
else if (typeof arg === 'object') {
arg = '<object>';
}
else if (typeof arg === 'undefined') {
arg = typeof arg;
}
return arg;
}).join(', ');
return `${commandName}(${callArgs})`;
}
exports.commandCallStructure = commandCallStructure;
function transformCommandLogResult(result) {
if (typeof result.file === 'string' && isBase64(result.file)) {
return SCREENSHOT_REPLACEMENT;
}
return result;
if (typeof result.file === 'string' && isBase64(result.file)) {
return SCREENSHOT_REPLACEMENT;
}
return result;
}
exports.transformCommandLogResult = transformCommandLogResult;
function isValidParameter(arg, expectedType) {
let shouldBeArray = false;
if (expectedType.slice(-2) === '[]') {
expectedType = expectedType.slice(0, -2);
shouldBeArray = true;
}
if (shouldBeArray) {
if (!Array.isArray(arg)) {
return false;
let shouldBeArray = false;
if (expectedType.slice(-2) === '[]') {
expectedType = expectedType.slice(0, -2);
shouldBeArray = true;
}
} else {
arg = [arg];
}
for (const argEntity of arg) {
const argEntityType = getArgumentType(argEntity);
if (!argEntityType.match(expectedType)) {
return false;
if (shouldBeArray) {
if (!Array.isArray(arg)) {
return false;
}
}
}
return true;
else {
arg = [arg];
}
for (const argEntity of arg) {
const argEntityType = getArgumentType(argEntity);
if (!argEntityType.match(expectedType)) {
return false;
}
}
return true;
}
exports.isValidParameter = isValidParameter;
function getArgumentType(arg) {
return arg === null ? 'null' : typeof arg;
return arg === null ? 'null' : typeof arg;
}
exports.getArgumentType = getArgumentType;
function safeRequire(name) {
let requirePath;
try {
const localNodeModules = `${process.cwd()}/node_modules`;
if (!require.main.paths.includes(localNodeModules)) {
require.main.paths.push(localNodeModules);
const requireOpts = process.env.JEST_WORKER_ID ? {} : {
paths: require.main.paths
};
requirePath = require.resolve(name, requireOpts);
} else {
requirePath = require.resolve(name);
let requirePath;
try {
const localNodeModules = `${process.cwd()}/node_modules`;
if (!require.main.paths.includes(localNodeModules)) {
require.main.paths.push(localNodeModules);
const requireOpts = process.env.JEST_WORKER_ID
? {}
: { paths: require.main.paths };
requirePath = require.resolve(name, requireOpts);
}
else {
requirePath = require.resolve(name);
}
}
} catch (e) {
return null;
}
try {
return require(requirePath);
} catch (e) {
throw new Error(`Couldn't initialise "${name}".\n${e.stack}`);
}
catch (e) {
return null;
}
try {
return require(requirePath);
}
catch (e) {
throw new Error(`Couldn't initialise "${name}".\n${e.stack}`);
}
}
exports.safeRequire = safeRequire;
function isFunctionAsync(fn) {
return fn.constructor && fn.constructor.name === 'AsyncFunction' || fn.name === 'async';
return (fn.constructor && fn.constructor.name === 'AsyncFunction') || fn.name === 'async';
}
exports.isFunctionAsync = isFunctionAsync;
function filterSpecArgs(args) {
return args.filter(arg => typeof arg !== 'function');
return args.filter((arg) => typeof arg !== 'function');
}
exports.filterSpecArgs = filterSpecArgs;
function isBase64(str) {
var notBase64 = new RegExp('[^A-Z0-9+\\/=]', 'i');
const isString = typeof str === 'string' || str instanceof String;
if (!isString) {
throw new Error('Expected string but received invalid type.');
}
const len = str.length;
if (!len || len % 4 !== 0 || notBase64.test(str)) {
return false;
}
const firstPaddingChar = str.indexOf('=');
return firstPaddingChar === -1 || firstPaddingChar === len - 1 || firstPaddingChar === len - 2 && str[len - 1] === '=';
var notBase64 = new RegExp('[^A-Z0-9+\\/=]', 'i');
const isString = (typeof str === 'string' || str instanceof String);
if (!isString) {
throw new Error('Expected string but received invalid type.');
}
const len = str.length;
if (!len || len % 4 !== 0 || notBase64.test(str)) {
return false;
}
const firstPaddingChar = str.indexOf('=');
return firstPaddingChar === -1 ||
firstPaddingChar === len - 1 ||
(firstPaddingChar === len - 2 && str[len - 1] === '=');
}
const canAccess = file => {
if (!file) {
return false;
}
try {
_fs.default.accessSync(file);
return true;
} catch (e) {
return false;
}
exports.isBase64 = isBase64;
exports.canAccess = (file) => {
if (!file) {
return false;
}
try {
fs_1.default.accessSync(file);
return true;
}
catch (e) {
return false;
}
};
exports.canAccess = canAccess;
const sleep = (ms = 0) => new Promise(r => setTimeout(r, ms));
exports.sleep = sleep;
exports.sleep = (ms = 0) => new Promise((r) => setTimeout(r, ms));
{
"name": "@wdio/utils",
"version": "6.5.0",
"version": "6.6.0",
"description": "A WDIO helper utility to provide several utility functions used across the project.",

@@ -12,11 +12,2 @@ "author": "Christian Bromann <christian@saucelabs.com>",

},
"scripts": {
"tsc": "tsc",
"build": "run-s clean compile",
"clean": "rimraf ./build",
"compile": "babel src/ -d build/ --config-file ../../babel.config.js",
"test": "run-s test:*",
"test:eslint": "eslint src test",
"test:unit": "jest"
},
"repository": {

@@ -36,3 +27,3 @@ "type": "git",

"dependencies": {
"@wdio/logger": "6.4.7"
"@wdio/logger": "6.6.0"
},

@@ -42,3 +33,3 @@ "publishConfig": {

},
"gitHead": "27e1326e46bf15ff4f6882a578aecd181e551656"
"gitHead": "643b1f237c0c7e4eb0e28fca31d963d3b19a073c"
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc