appium-android-driver 5.4.1 → 5.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/lib/android-helpers.js +12 -3
- package/build/lib/android-helpers.js.map +1 -0
- package/build/lib/bootstrap.js.map +1 -0
- package/build/lib/commands/actions.js.map +1 -0
- package/build/lib/commands/alert.js.map +1 -0
- package/build/lib/commands/app-management.js.map +1 -0
- package/build/lib/commands/context.js.map +1 -0
- package/build/lib/commands/coverage.js.map +1 -0
- package/build/lib/commands/element.js.map +1 -0
- package/build/lib/commands/emu-console.js.map +1 -0
- package/build/lib/commands/execute.js.map +1 -0
- package/build/lib/commands/file-actions.js.map +1 -0
- package/build/lib/commands/find.js.map +1 -0
- package/build/lib/commands/general.js.map +1 -0
- package/build/lib/commands/ime.js.map +1 -0
- package/build/lib/commands/index.js.map +1 -0
- package/build/lib/commands/intent.js.map +1 -0
- package/build/lib/commands/log.js.map +1 -0
- package/build/lib/commands/media-projection.js.map +1 -0
- package/build/lib/commands/network.js.map +1 -0
- package/build/lib/commands/performance.js.map +1 -0
- package/build/lib/commands/recordscreen.js.map +1 -0
- package/build/lib/commands/shell.js.map +1 -0
- package/build/lib/commands/streamscreen.js.map +1 -0
- package/build/lib/commands/system-bars.js.map +1 -0
- package/build/lib/commands/touch.js.map +1 -0
- package/build/lib/desired-caps.js.map +1 -0
- package/build/lib/driver.js.map +1 -0
- package/build/lib/logger.js.map +1 -0
- package/build/lib/uiautomator.js.map +1 -0
- package/build/lib/unlock-helpers.js.map +1 -0
- package/build/lib/utils.js.map +1 -0
- package/build/lib/webview-helpers.js.map +1 -0
- package/lib/android-helpers.js +8 -2
- package/package.json +2 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bootstrap.js","names":["log","logger","getLogger","COMMAND_TYPES","ACTION","SHUTDOWN","SEND_COMMAND_TIMEOUT","getModuleRoot","_","memoize","currentDir","path","dirname","resolve","__filename","isAtFsRoot","manifestPath","join","fs","exists","JSON","parse","readFile","name","ign","length","Error","AndroidBootstrap","constructor","adb","systemPort","webSocket","undefined","ignoreUnexpectedShutdown","onUnexpectedShutdown","_onUnexpectedShutdownPromise","reject","B","_resolve","_reject","cancel","start","appPackage","disableAndroidWatchers","acceptSslCerts","startDetector","s","test","bootstrapJar","init","forwardPort","process","uiAutomator","on","stdout","stderr","alertRe","debug","sockets","emit","message","stdoutLines","split","uiautoLog","line","trim","innerLine","exec","logMethod","info","bind","stderrLines","socketClient","net","connect","err","once","errorAndThrow","sendCommand","type","extra","cmd","Object","assign","cmdJson","stringify","truncate","write","setEncoding","streamData","sendCommandTimeoutHandler","data","clearTimeout","removeAllListeners","status","value","errorFromCode","isString","error","stack","setTimeout","errMsg","sendAction","action","params","shutdown","warn","UiAutomator","EVENT_CHANGED","msg","state","STATE_STOPPED","ignore","_ignoreUnexpectedShutdown"],"sources":["../../lib/bootstrap.js"],"sourcesContent":["import UiAutomator from './uiautomator';\nimport net from 'net';\nimport path from 'path';\nimport _ from 'lodash';\nimport { errorFromCode } from 'appium/driver';\nimport B from 'bluebird';\nimport { logger, fs } from 'appium/support';\n\n\nconst log = logger.getLogger('AndroidBootstrap');\nconst COMMAND_TYPES = {\n ACTION: 'action',\n SHUTDOWN: 'shutdown'\n};\nconst SEND_COMMAND_TIMEOUT = 1 * 60 * 1000;\n\n/**\n * Calculates the path to the current module's root folder\n *\n * @returns {string} The full path to module root\n * @throws {Error} If the current module root folder cannot be determined\n */\nconst getModuleRoot = _.memoize(async function getModuleRoot () {\n let currentDir = path.dirname(path.resolve(__filename));\n let isAtFsRoot = false;\n while (!isAtFsRoot) {\n const manifestPath = path.join(currentDir, 'package.json');\n try {\n if (await fs.exists(manifestPath) &&\n JSON.parse(await fs.readFile(manifestPath, 'utf8')).name === 'appium-android-driver') {\n return currentDir;\n }\n } catch (ign) {}\n currentDir = path.dirname(currentDir);\n isAtFsRoot = currentDir.length <= path.dirname(currentDir).length;\n }\n throw new Error('Cannot find the root folder of the appium-android-driver Node.js module');\n});\n\nclass AndroidBootstrap {\n constructor (adb, systemPort = 4724, webSocket = undefined) {\n this.adb = adb;\n this.systemPort = systemPort;\n this.webSocket = webSocket;\n this.ignoreUnexpectedShutdown = false;\n }\n\n get onUnexpectedShutdown () {\n if (!this._onUnexpectedShutdownPromise) {\n let reject;\n this._onUnexpectedShutdownPromise = new B(function _onUnexpectedShutdownPromise (_resolve, _reject) {\n reject = _reject;\n });\n this._onUnexpectedShutdownPromise.cancel = reject;\n }\n return this._onUnexpectedShutdownPromise;\n }\n\n async start (appPackage, disableAndroidWatchers = false, acceptSslCerts = false) {\n try {\n const startDetector = (s) => /Appium Socket Server Ready/.test(s);\n const bootstrapJar = path.resolve(await getModuleRoot(), 'bootstrap', 'bin', 'AppiumBootstrap.jar');\n\n await this.init();\n await this.adb.forwardPort(this.systemPort, 4724);\n this.process = await this.uiAutomator.start(\n bootstrapJar, 'io.appium.android.bootstrap.Bootstrap',\n startDetector, '-e', 'pkg', appPackage,\n '-e', 'disableAndroidWatchers', disableAndroidWatchers,\n '-e', 'acceptSslCerts', acceptSslCerts);\n\n // process the output\n this.process.on('output', (stdout, stderr) => {\n const alertRe = /Emitting system alert message/;\n if (alertRe.test(stdout)) {\n log.debug('Emitting alert message...');\n if (this.webSocket) {\n this.webSocket.sockets.emit('alert', {message: stdout});\n }\n }\n\n // the bootstrap logger wraps its own log lines with\n // [APPIUM-UIAUTO] ... [APPIUM-UIAUTO]\n // and leaves actual UiAutomator logs as they are\n let stdoutLines = (stdout || '').split('\\n');\n const uiautoLog = /\\[APPIUM-UIAUTO\\](.+)\\[\\/APPIUM-UIAUTO\\]/;\n for (let line of stdoutLines) {\n if (line.trim()) {\n if (uiautoLog.test(line)) {\n let innerLine = uiautoLog.exec(line)[1].trim();\n let logMethod = log.info.bind(log);\n // if the bootstrap log considers something debug, log that as\n // debug and not info\n if (/\\[debug\\]/.test(innerLine)) {\n logMethod = log.debug.bind(log);\n }\n logMethod(`[BOOTSTRAP LOG] ${innerLine}`);\n } else {\n log.debug(`[UIAUTO STDOUT] ${line}`);\n }\n }\n }\n\n let stderrLines = (stderr || '').split('\\n');\n for (let line of stderrLines) {\n if (line.trim()) {\n log.debug(`[UIAUTO STDERR] ${line}`);\n }\n }\n });\n\n // only return when the socket client has connected\n return await new B((resolve, reject) => {\n try {\n this.socketClient = net.connect(this.systemPort);\n // Windows: the socket errors out when ADB restarts. Let's catch it to avoid crashing.\n this.socketClient.on('error', (err) => {\n if (!this.ignoreUnexpectedShutdown) {\n throw new Error(`Android bootstrap socket crashed: ${err}`);\n }\n });\n this.socketClient.once('connect', () => {\n log.info('Android bootstrap socket is now connected');\n resolve();\n });\n } catch (err) {\n reject(err);\n }\n });\n } catch (err) {\n log.errorAndThrow(`Error occured while starting AndroidBootstrap. Original error: ${err}`);\n }\n }\n\n async sendCommand (type, extra = {}) {\n if (!this.socketClient) {\n throw new Error('Socket connection closed unexpectedly');\n }\n\n return await new B((resolve, reject) => {\n let cmd = Object.assign({cmd: type}, extra);\n let cmdJson = `${JSON.stringify(cmd)} \\n`;\n log.debug(`Sending command to android: ${_.truncate(cmdJson, {length: 1000}).trim()}`);\n this.socketClient.write(cmdJson);\n this.socketClient.setEncoding('utf8');\n let streamData = '';\n let sendCommandTimeoutHandler = null;\n this.socketClient.on('data', (data) => {\n if (sendCommandTimeoutHandler) {\n clearTimeout(sendCommandTimeoutHandler);\n }\n log.debug('Received command result from bootstrap');\n try {\n streamData = JSON.parse(streamData + data);\n // we successfully parsed JSON so we've got all the data,\n // remove the socket listener and evaluate\n this.socketClient.removeAllListeners('data');\n if (streamData.status === 0) {\n return resolve(streamData.value);\n }\n reject(errorFromCode(streamData.status, streamData.value));\n } catch (err) {\n if (!_.isString(streamData)) {\n log.error('Got an unexpected error inside socket listener');\n log.error(err.stack);\n return reject(errorFromCode(13, err.message));\n }\n log.debug(`Stream still not complete, waiting up to ${SEND_COMMAND_TIMEOUT}ms for the data to arrive`);\n streamData += data;\n sendCommandTimeoutHandler = setTimeout(() => {\n const errMsg = `Server socket stopped responding. The recent response was '${streamData}'`;\n log.error(errMsg);\n this.socketClient.removeAllListeners('data');\n reject(errorFromCode(13, errMsg));\n }, SEND_COMMAND_TIMEOUT);\n }\n });\n });\n }\n\n async sendAction (action, params = {}) {\n let extra = {action, params};\n return await this.sendCommand(COMMAND_TYPES.ACTION, extra);\n }\n\n async shutdown () {\n if (!this.uiAutomator) {\n log.warn('Cannot shut down Android bootstrap; it has already shut down');\n return;\n }\n\n // remove listners so we don't trigger unexpected shutdown\n this.uiAutomator.removeAllListeners(UiAutomator.EVENT_CHANGED);\n if (this.socketClient) {\n await this.sendCommand(COMMAND_TYPES.SHUTDOWN);\n }\n await this.uiAutomator.shutdown();\n this.uiAutomator = null;\n }\n\n // this helper function makes unit testing easier.\n async init () { // eslint-disable-line require-await\n this.uiAutomator = new UiAutomator(this.adb);\n\n // Handle unexpected UiAutomator shutdown\n this.uiAutomator.on(UiAutomator.EVENT_CHANGED, (msg) => {\n if (msg.state === UiAutomator.STATE_STOPPED) {\n this.uiAutomator = null;\n this.onUnexpectedShutdown.cancel(new Error('UiAUtomator shut down unexpectedly'));\n }\n });\n }\n\n set ignoreUnexpectedShutdown (ignore) {\n log.debug(`${ignore ? 'Ignoring' : 'Watching for'} bootstrap disconnect`);\n this._ignoreUnexpectedShutdown = ignore;\n }\n\n get ignoreUnexpectedShutdown () {\n return this._ignoreUnexpectedShutdown;\n }\n}\n\nexport { AndroidBootstrap, COMMAND_TYPES };\nexport default AndroidBootstrap;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAGA,MAAMA,GAAG,GAAGC,eAAA,CAAOC,SAAP,CAAiB,kBAAjB,CAAZ;;AACA,MAAMC,aAAa,GAAG;EACpBC,MAAM,EAAE,QADY;EAEpBC,QAAQ,EAAE;AAFU,CAAtB;;AAIA,MAAMC,oBAAoB,GAAG,IAAI,EAAJ,GAAS,I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ands","helpers","extensions","keyevent","keycode","metastate","log","warn","pressKeyCode","bootstrap","sendAction","longPressKeyCode","getOrientation","params","naturalOrientation","opts","androidNaturalOrientation","orientation","toUpperCase","setOrientation","fakeFlick","xSpeed","ySpeed","fakeFlickElement","elementId","xoffset","yoffset","speed","swipe","startX","startY","endX","endY","duration","touchCount","elId","swipeOpts","steps","Math","round","util","hasValue","doSwipe","pinchClose","percent","pinchOpts","direction","pinchOpen","flick","element","xOffset","yOffset","drag","destElId","dragOpts","doDrag","lock","seconds","adb","isNaN","floatSeconds","parseFloat","B","delay","unlock","isLocked","isScreenLocked","androidHelpers","caps","openNotifications","setLocation","latitude","longitude","sendTelnetCommand","fingerprint","fingerprintId","isEmulator","errorAndThrow","sendSMS","phoneNumber","message","gsmCall","action","gsmSignal","signalStrengh","gsmVoice","state","powerAC","powerCapacity","batteryPercent","networkSpeed","sensorSet","sensor","sensorType","value","getScreenshotDataWithAdbShell","localFile","tempDir","path","prefix","suffix","fs","exists","unlink","pngDir","androidScreenshotPath","png","posix","resolve","cmd","shell","fileSize","Error","pull","jimp","read","getScreenshotDataWithAdbExecOut","stdout","stderr","code","exec","executable","defaultArgs","concat","encoding","isBuffer","length","toString","getScreenshot","apiLevel","getApiLevel","image","e","info","err","screenOrientation","getScreenOrientation","rotate","getBuffer","promisify","context","imgBuffer","MIME_PNG","Object","assign"],"sources":["../../../lib/commands/actions.js"],"sourcesContent":["import androidHelpers from '../android-helpers';\nimport { fs, util, tempDir} from 'appium/support';\nimport path from 'path';\nimport B from 'bluebird';\nimport jimp from 'jimp';\nimport { exec } from 'teen_process';\n\nconst swipeStepsPerSec = 28;\nconst dragStepsPerSec = 40;\n\nlet commands = {}, helpers = {}, extensions = {};\n\ncommands.keyevent = async function keyevent (keycode, metastate = null) {\n // TODO deprecate keyevent; currently wd only implements keyevent\n this.log.warn('keyevent will be deprecated use pressKeyCode');\n return await this.pressKeyCode(keycode, metastate);\n};\n\ncommands.pressKeyCode = async function pressKeyCode (keycode, metastate = null) {\n return await this.bootstrap.sendAction('pressKeyCode', {keycode, metastate});\n};\n\ncommands.longPressKeyCode = async function longPressKeyCode (keycode, metastate = null) {\n return await this.bootstrap.sendAction('longPressKeyCode', {keycode, metastate});\n};\n\ncommands.getOrientation = async function getOrientation () {\n let params = {\n naturalOrientation: !!this.opts.androidNaturalOrientation,\n };\n let orientation = await this.bootstrap.sendAction('orientation', params);\n return orientation.toUpperCase();\n};\n\ncommands.setOrientation = async function setOrientation (orientation) {\n orientation = orientation.toUpperCase();\n let params = {\n orientation,\n naturalOrientation: !!this.opts.androidNaturalOrientation,\n };\n return await this.bootstrap.sendAction('orientation', params);\n};\n\ncommands.fakeFlick = async function fakeFlick (xSpeed, ySpeed) {\n return await this.bootstrap.sendAction('flick', {xSpeed, ySpeed});\n};\n\ncommands.fakeFlickElement = async function fakeFlickElement (elementId, xoffset, yoffset, speed) {\n let params = {xoffset, yoffset, speed, elementId};\n return await this.bootstrap.sendAction('element:flick', params);\n};\n\ncommands.swipe = async function swipe (startX, startY, endX, endY, duration, touchCount, elId) {\n if (startX === 'null') {\n startX = 0.5;\n }\n if (startY === 'null') {\n startY = 0.5;\n }\n let swipeOpts = {startX, startY, endX, endY,\n steps: Math.round(duration * swipeStepsPerSec)};\n // going the long way and checking for undefined and null since\n // we can't be assured `elId` is a string and not an int\n if (util.hasValue(elId)) {\n swipeOpts.elementId = elId;\n }\n return await this.doSwipe(swipeOpts);\n};\n\ncommands.doSwipe = async function doSwipe (swipeOpts) {\n if (util.hasValue(swipeOpts.elementId)) {\n return await this.bootstrap.sendAction('element:swipe', swipeOpts);\n } else {\n return await this.bootstrap.sendAction('swipe', swipeOpts);\n }\n};\n\ncommands.pinchClose = async function pinchClose (startX, startY, endX, endY, duration, percent, steps, elId) {\n let pinchOpts = {\n direction: 'in',\n elementId: elId,\n percent,\n steps\n };\n return await this.bootstrap.sendAction('element:pinch', pinchOpts);\n};\n\ncommands.pinchOpen = async function pinchOpen (startX, startY, endX, endY, duration, percent, steps, elId) {\n let pinchOpts = {direction: 'out', elementId: elId, percent, steps};\n return await this.bootstrap.sendAction('element:pinch', pinchOpts);\n};\n\ncommands.flick = async function flick (element, xSpeed, ySpeed, xOffset, yOffset, speed) {\n if (element) {\n await this.fakeFlickElement(element, xOffset, yOffset, speed);\n } else {\n await this.fakeFlick(xSpeed, ySpeed);\n }\n};\n\ncommands.drag = async function drag (startX, startY, endX, endY, duration, touchCount, elementId, destElId) {\n let dragOpts = {\n elementId, destElId, startX, startY, endX, endY,\n steps: Math.round(duration * dragStepsPerSec)\n };\n return await this.doDrag(dragOpts);\n\n};\n\ncommands.doDrag = async function doDrag (dragOpts) {\n if (util.hasValue(dragOpts.elementId)) {\n return await this.bootstrap.sendAction('element:drag', dragOpts);\n } else {\n return await this.bootstrap.sendAction('drag', dragOpts);\n }\n};\n\ncommands.lock = async function lock (seconds) {\n await this.adb.lock();\n if (isNaN(seconds)) {\n return;\n }\n\n const floatSeconds = parseFloat(seconds);\n if (floatSeconds <= 0) {\n return;\n }\n await B.delay(1000 * floatSeconds);\n await this.unlock();\n};\n\ncommands.isLocked = async function isLocked () {\n return await this.adb.isScreenLocked();\n};\n\ncommands.unlock = async function unlock () {\n return await androidHelpers.unlock(this, this.adb, this.caps);\n};\n\ncommands.openNotifications = async function openNotifications () {\n return await this.bootstrap.sendAction('openNotification');\n};\n\ncommands.setLocation = async function setLocation (latitude, longitude) {\n return await this.adb.sendTelnetCommand(`geo fix ${longitude} ${latitude}`);\n};\n\ncommands.fingerprint = async function fingerprint (fingerprintId) {\n if (!this.isEmulator()) {\n this.log.errorAndThrow('fingerprint method is only available for emulators');\n }\n await this.adb.fingerprint(fingerprintId);\n};\n\ncommands.sendSMS = async function sendSMS (phoneNumber, message) {\n if (!this.isEmulator()) {\n this.log.errorAndThrow('sendSMS method is only available for emulators');\n }\n await this.adb.sendSMS(phoneNumber, message);\n};\n\ncommands.gsmCall = async function gsmCall (phoneNumber, action) {\n if (!this.isEmulator()) {\n this.log.errorAndThrow('gsmCall method is only available for emulators');\n }\n await this.adb.gsmCall(phoneNumber, action);\n};\n\ncommands.gsmSignal = async function gsmSignal (signalStrengh) {\n if (!this.isEmulator()) {\n this.log.errorAndThrow('gsmSignal method is only available for emulators');\n }\n await this.adb.gsmSignal(signalStrengh);\n};\n\ncommands.gsmVoice = async function gsmVoice (state) {\n if (!this.isEmulator()) {\n this.log.errorAndThrow('gsmVoice method is only available for emulators');\n }\n await this.adb.gsmVoice(state);\n};\n\ncommands.powerAC = async function powerAC (state) {\n if (!this.isEmulator()) {\n this.log.errorAndThrow('powerAC method is only available for emulators');\n }\n await this.adb.powerAC(state);\n};\n\ncommands.powerCapacity = async function powerCapacity (batteryPercent) {\n if (!this.isEmulator()) {\n this.log.errorAndThrow('powerCapacity method is only available for emulators');\n }\n await this.adb.powerCapacity(batteryPercent);\n};\n\ncommands.networkSpeed = async function networkSpeed (networkSpeed) {\n if (!this.isEmulator()) {\n this.log.errorAndThrow('networkSpeed method is only available for emulators');\n }\n await this.adb.networkSpeed(networkSpeed);\n};\n\n/**\n * Emulate sensors values on the connected emulator.\n *\n * @typedef {Object} Sensor\n * @property {string} sensorType - sensor type declared in adb.SENSORS\n * @property {string} value - value to set to the sensor\n *\n * @param {Object} Sensor\n * @throws {Error} - If sensorType is not defined\n * @throws {Error} - If value for the se sor is not defined\n * @throws {Error} - If deviceType is not an emulator\n */\ncommands.sensorSet = async function sensorSet (sensor = {}) {\n const {sensorType, value} = sensor;\n if (!util.hasValue(sensorType)) {\n this.log.errorAndThrow(`'sensorType' argument is required`);\n }\n if (!util.hasValue(value)) {\n this.log.errorAndThrow(`'value' argument is required`);\n }\n if (!this.isEmulator()) {\n this.log.errorAndThrow('sensorSet method is only available for emulators');\n }\n await this.adb.sensorSet(sensorType, value);\n};\n\nhelpers.getScreenshotDataWithAdbShell = async function getScreenshotDataWithAdbShell (adb, opts) {\n const localFile = await tempDir.path({prefix: 'appium', suffix: '.png'});\n if (await fs.exists(localFile)) {\n await fs.unlink(localFile);\n }\n try {\n const pngDir = opts.androidScreenshotPath || '/data/local/tmp/';\n const png = path.posix.resolve(pngDir, 'screenshot.png');\n const cmd = ['/system/bin/rm', `${png};`, '/system/bin/screencap', '-p', png];\n await adb.shell(cmd);\n if (!await adb.fileSize(png)) {\n throw new Error('The size of the taken screenshot equals to zero.');\n }\n await adb.pull(png, localFile);\n return await jimp.read(localFile);\n } finally {\n if (await fs.exists(localFile)) {\n await fs.unlink(localFile);\n }\n }\n};\n\nhelpers.getScreenshotDataWithAdbExecOut = async function getScreenshotDataWithAdbExecOut (adb) {\n let {stdout, stderr, code} = await exec(adb.executable.path,\n adb.executable.defaultArgs\n .concat(['exec-out', '/system/bin/screencap', '-p']),\n {encoding: 'binary', isBuffer: true});\n // if there is an error, throw\n if (code || stderr.length) {\n throw new Error(`Screenshot returned error, code: '${code}', stderr: '${stderr.toString()}'`);\n }\n // if we don't get anything at all, throw\n if (!stdout.length) {\n throw new Error('Screenshot returned no data');\n }\n\n return await jimp.read(stdout);\n};\n\ncommands.getScreenshot = async function getScreenshot () {\n const apiLevel = await this.adb.getApiLevel();\n let image = null;\n if (apiLevel > 20) {\n try {\n // This screenshoting approach is way faster, since it requires less external commands\n // to be executed. Unfortunately, exec-out option is only supported by newer Android/SDK versions (5.0 and later)\n image = await this.getScreenshotDataWithAdbExecOut(this.adb);\n } catch (e) {\n this.log.info(`Cannot get screenshot data with 'adb exec-out' because of '${e.message}'. ` +\n `Defaulting to 'adb shell' call`);\n }\n }\n if (!image) {\n try {\n image = await this.getScreenshotDataWithAdbShell(this.adb, this.opts);\n } catch (e) {\n const err = `Cannot get screenshot data because of '${e.message}'. ` +\n `Make sure the 'LayoutParams.FLAG_SECURE' is not set for ` +\n `the current view`;\n this.log.errorAndThrow(err);\n }\n }\n if (apiLevel < 23) {\n // Android bug 8433742 - rotate screenshot if screen is rotated\n let screenOrientation = await this.adb.getScreenOrientation();\n try {\n image = await image.rotate(-90 * screenOrientation);\n } catch (err) {\n this.log.warn(`Could not rotate screenshot due to error: ${err}`);\n }\n }\n const getBuffer = B.promisify(image.getBuffer, {context: image});\n const imgBuffer = await getBuffer(jimp.MIME_PNG);\n return imgBuffer.toString('base64');\n};\n\nObject.assign(extensions, commands, helpers);\nexport { commands, helpers };\nexport default extensions;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA,MAAMA,gBAAgB,GAAG,EAAzB;AACA,MAAMC,eAAe,GAAG,EAAxB;AAEA,IAAIC,QAAQ,GAAG,EAAf;AAAA,IAAmBC,OAAO,GAAG,EAA7B;AAAA,IAAiCC,UAAU,GAAG,EAA9C;;;;AAEAF,QAAQ,CAACG,QAAT,GAAoB,eAAeA,QAAf,CAAyBC,OAAzB,EAAkCC,SAAS,GAAG,IAA9C,EAAoD;EAEtE,KAAKC,GAAL,CAASC,IAAT,CAAc,8CAAd;EACA,OAAO,MAAM,KAAKC,YAAL,CAAkBJ,OAAlB,EAA2BC,SAA3B,CAAb;AACD,CAJD;;AAMAL,QAAQ,CAACQ,YAAT,GAAwB,eAAeA,YAAf,CAA6BJ,OAA7B,EAAsCC,SAAS,GAAG,IAAlD,EAAwD;EAC9E,OAAO,MAAM,KAAKI,SAAL,CAAeC,UAAf,CAA0B,cAA1B,EAA0C;IAACN,OAAD;IAAUC;EAAV,CAA1C,CAAb;AACD,CAFD;;AAIAL,QAAQ,CAACW,gBAAT,GAA4B,eAAeA,gBAAf,CAAiCP,OAAjC,EAA0CC,SAAS,GAAG,IAAtD,EAA4D;EACtF,OAAO,MAAM,KAAKI,SAAL,CAAeC,UAAf,CAA0B,kBAA1B,EAA8C;IAACN,OAAD;IAAUC;EAAV,CAA9C,CAAb;AACD,CAFD;;AAIAL,QAAQ,CAACY,cAAT,GAA0B,eAAeA,cAAf,GAAiC;EACzD,IAAIC,MAAM,GAAG;IACXC,kBAAkB,EAAE,CAAC,CAAC,KAAKC,IAAL,CAAUC;EADrB,CAAb;EAGA,IAAIC,W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AAQ,KAApD,GACT,0DADS,GAET,kBAFH;MAGA,KAAK1E,GAAL,CAASuE,aAAT,CAAuByD,GAAvB;IACD;EACF;;EACD,IAAIL,QAAQ,GAAG,EAAf,EAAmB;IAEjB,IAAIM,iBAAiB,GAAG,MAAM,KAAK7E,GAAL,CAAS8E,oBAAT,EAA9B;;IACA,IAAI;MACFL,KAAK,GAAG,MAAMA,KAAK,CAACM,MAAN,CAAa,CAAC,EAAD,GAAMF,iBAAnB,CAAd;IACD,CAFD,CAEE,OAAOD,GAAP,EAAY;MACZ,KAAKhI,GAAL,CAASC,IAAT,CAAe,6CAA4C+H,GAAI,EAA/D;IACD;EACF;;EACD,MAAMI,SAAS,GAAG5E,iBAAA,CAAE6E,SAAF,CAAYR,KAAK,CAACO,SAAlB,EAA6B;IAACE,OAAO,EAAET;EAAV,CAA7B,CAAlB;;EACA,MAAMU,SAAS,GAAG,MAAMH,SAAS,CAACxB,aAAA,CAAK4B,QAAN,CAAjC;EACA,OAAOD,SAAS,CAACd,QAAV,CAAmB,QAAnB,CAAP;AACD,CAnCD;;AAqCAgB,MAAM,CAACC,MAAP,CAAc9I,UAAd,EAA0BF,QAA1B,EAAoCC,OAApC;eAEeC,U"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"alert.js","names":["commands","helpers","extensions","getAlertText","errors","NotYetImplementedError","setAlertText","postAcceptAlert","postDismissAlert","Object","assign"],"sources":["../../../lib/commands/alert.js"],"sourcesContent":["/* eslint-disable require-await */\nimport { errors } from 'appium/driver';\n\nlet commands = {}, helpers = {}, extensions = {};\n\ncommands.getAlertText = async function getAlertText () {\n throw new errors.NotYetImplementedError();\n};\n\ncommands.setAlertText = async function setAlertText () {\n throw new errors.NotYetImplementedError();\n};\n\ncommands.postAcceptAlert = async function postAcceptAlert () {\n throw new errors.NotYetImplementedError();\n};\n\ncommands.postDismissAlert = async function postDismissAlert () {\n throw new errors.NotYetImplementedError();\n};\n\nObject.assign(extensions, commands, helpers);\nexport { commands, helpers };\nexport default extensions;\n"],"mappings":";;;;;;;;;AACA;;AAEA,IAAIA,QAAQ,GAAG,EAAf;AAAA,IAAmBC,OAAO,GAAG,EAA7B;AAAA,IAAiCC,UAAU,GAAG,EAA9C;;;;AAEAF,QAAQ,CAACG,YAAT,GAAwB,eAAeA,YAAf,GAA+B;EACrD,MAAM,IAAIC,cAAA,CAAOC,sBAAX,EAAN;AACD,CAFD;;AAIAL,QAAQ,CAACM,YAAT,GAAwB,eAAeA,YAAf,GAA+B;EACrD,MAAM,IAAIF,cAAA,CAAOC,sBAAX,EAAN;AACD,CAFD;;AAIAL,QAAQ,CAACO,eAAT,GAA2B,eAAeA,eAAf,GAAkC;EAC3D,MAAM,IAAIH,cAAA,CAAOC,sBAAX,EAAN;AACD,CAFD;;AAIAL,QAAQ,CAACQ,gBAAT,GAA4B,eAAeA,gBAAf,GAAmC;EAC7D,MAAM,IAAIJ,cAAA,CAAOC,sBAAX,EAAN;AACD,CAFD;;AAIAI,MAAM,CAACC,MAAP,CAAcR,UAAd,EAA0BF,QAA1B,EAAoCC,OAApC;eAEeC,U"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app-management.js","names":["APP_EXTENSIONS","RESOLVER_ACTIVITY_NAME","commands","isAppInstalled","appId","adb","mobileIsAppInstalled","opts","requireArgs","queryAppState","log","info","APP_STATE","NOT_INSTALLED","processExists","NOT_RUNNING","appIdRe","RegExp","_","escapeRegExp","line","dumpWindows","split","test","some","x","includes","RUNNING_IN_FOREGROUND","RUNNING_IN_BACKGROUND","mobileQueryAppState","activateApp","debug","apiLevel","getApiLevel","cmd","output","shell","e","errorAndThrow","message","activityName","resolveLaunchableActivity","preferCmd","stdout","Error","mobileActivateApp","removeApp","options","uninstallApk","mobileRemoveApp","terminateApp","forceStop","timeout","util","hasValue","isNaN","parseInt","waitForCondition","waitMs","intervalMs","mobileTerminateApp","installApp","appPath","localPath","helpers","configureApp","install","mobileInstallApp","mobileClearApp","errors","InvalidArgumentError","clear"],"sources":["../../../lib/commands/app-management.js"],"sourcesContent":["import _ from 'lodash';\nimport { waitForCondition } from 'asyncbox';\nimport { util } from 'appium/support';\nimport { APP_STATE } from '../android-helpers';\nimport { errors } from 'appium/driver';\nimport { requireArgs } from '../utils';\n\nconst APP_EXTENSIONS = ['.apk', '.apks'];\nconst RESOLVER_ACTIVITY_NAME = 'android/com.android.internal.app.ResolverActivity';\n\nconst commands = {};\n\n/**\n * Verify whether an application is installed or not\n *\n * @param {string} appId - Application package identifier\n * @returns {boolean} true if the app is installed\n */\ncommands.isAppInstalled = async function isAppInstalled (appId) {\n return await this.adb.isAppInstalled(appId);\n};\n\n/**\n * @typedef {Object} MobileAppInstalledOptions\n * @property {string} appId - Application package identifier. Must be always provided.\n */\n\n/**\n * Verify whether an application is installed or not\n *\n * @param {MobileAppInstalledOptions} opts\n * @returns {boolean} Same as in `isAppInstalled`\n */\ncommands.mobileIsAppInstalled = async function mobileIsAppInstalled (opts = {}) {\n const { appId } = requireArgs('appId', opts);\n return await this.isAppInstalled(appId);\n};\n\n/**\n * Queries the current state of the app.\n *\n * @param {string} appId - Application package identifier\n * @returns {number} The corresponding constant, which describes\n * the current application state:\n * 0 - is the app is not installed\n * 1 - if the app is installed, but is not running\n * 3 - if the app is running in the background\n * 4 - if the app is running in the foreground\n */\ncommands.queryAppState = async function queryAppState (appId) {\n this.log.info(`Querying the state of '${appId}'`);\n if (!await this.adb.isAppInstalled(appId)) {\n return APP_STATE.NOT_INSTALLED;\n }\n if (!await this.adb.processExists(appId)) {\n return APP_STATE.NOT_RUNNING;\n }\n const appIdRe = new RegExp(`\\\\b${_.escapeRegExp(appId)}/`);\n for (const line of (await this.adb.dumpWindows()).split('\\n')) {\n if (appIdRe.test(line) && ['mCurrentFocus', 'mFocusedApp'].some((x) => line.includes(x))) {\n return APP_STATE.RUNNING_IN_FOREGROUND;\n }\n }\n return APP_STATE.RUNNING_IN_BACKGROUND;\n};\n\n/**\n * @typedef {Object} MobileQueryAppStateOptions\n * @property {string} appId - Application package identifier. Must be always provided.\n */\n\n/**\n * Queries the current state of the app.\n *\n * @param {MobileQueryAppStateOptions} opts\n * @returns {number} Same as in `queryAppState`\n */\ncommands.mobileQueryAppState = async function mobileQueryAppState (opts = {}) {\n const { appId } = requireArgs('appId', opts);\n return await this.queryAppState(appId);\n};\n\n/**\n * Activates the given application or launches it if necessary.\n * The action literally simulates\n * clicking the corresponding application icon on the dashboard.\n *\n * @param {string} appId - Application package identifier\n * @throws {Error} If the app cannot be activated\n */\ncommands.activateApp = async function activateApp (appId) {\n this.log.debug(`Activating '${appId}'`);\n const apiLevel = await this.adb.getApiLevel();\n // Fallback to Monkey in older APIs\n if (apiLevel < 24) {\n // The monkey command could raise an issue as https://stackoverflow.com/questions/44860475/how-to-use-the-monkey-command-with-an-android-system-that-doesnt-have-physical\n // but '--pct-syskeys 0' could cause another background process issue. https://github.com/appium/appium/issues/16941#issuecomment-1129837285\n const cmd = ['monkey',\n '-p', appId,\n '-c', 'android.intent.category.LAUNCHER',\n '1'];\n let output = '';\n try {\n output = await this.adb.shell(cmd);\n this.log.debug(`Command stdout: ${output}`);\n } catch (e) {\n this.log.errorAndThrow(`Cannot activate '${appId}'. Original error: ${e.message}`);\n }\n if (output.includes('monkey aborted')) {\n this.log.errorAndThrow(`Cannot activate '${appId}'. Are you sure it is installed?`);\n }\n return;\n }\n\n let activityName = await this.adb.resolveLaunchableActivity(appId);\n if (activityName === RESOLVER_ACTIVITY_NAME) {\n // https://github.com/appium/appium/issues/17128\n this.log.debug(\n `The launchable activity name of '${appId}' was resolved to '${activityName}'. ` +\n `Switching the resolver to not use cmd`\n );\n activityName = await this.adb.resolveLaunchableActivity(appId, {preferCmd: false});\n }\n\n const stdout = await this.adb.shell([\n 'am', (apiLevel < 26) ? 'start' : 'start-activity',\n '-a', 'android.intent.action.MAIN',\n '-c', 'android.intent.category.LAUNCHER',\n // FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED\n // https://developer.android.com/reference/android/content/Intent#FLAG_ACTIVITY_NEW_TASK\n // https://developer.android.com/reference/android/content/Intent#FLAG_ACTIVITY_RESET_TASK_IF_NEEDED\n '-f', '0x10200000',\n '-n', activityName,\n ]);\n this.log.debug(stdout);\n if (/^error:/mi.test(stdout)) {\n throw new Error(`Cannot activate '${appId}'. Original error: ${stdout}`);\n }\n};\n\n/**\n * @typedef {Object} MobileActivateAppOptions\n * @property {string} appId - Application package identifier. Must be always provided.\n */\n\n/**\n * Activates the given application or launches it if necessary.\n * The action literally simulates\n * clicking the corresponding application icon on the dashboard.\n *\n * @param {MobileActivateAppOptions} opts\n * @throws {Error} If the app cannot be activated\n */\ncommands.mobileActivateApp = async function mobileActivateApp (opts = {}) {\n const { appId } = requireArgs('appId', opts);\n return await this.activateApp(appId);\n};\n\n/**\n * @typedef {Object} UninstallOptions\n * @property {number} timeout [20000] - The count of milliseconds to wait until the\n * app is uninstalled.\n * @property {boolean} keepData [false] - Set to true in order to keep the\n * application data and cache folders after uninstall.\n */\n\n/**\n * Remove the corresponding application if is installed.\n * The call is ignored if the app is not installed.\n *\n * @param {string} appId - Application package identifier\n * @param {?UninstallOptions} options - The set of removal options\n * @returns {boolean} True if the package was found on the device and\n * successfully uninstalled.\n */\ncommands.removeApp = async function removeApp (appId, options = {}) {\n return await this.adb.uninstallApk(appId, options);\n};\n\n/**\n * @typedef {Object} MobileRemoveAppOptions\n * @property {string} appId - Application package identifier. Must be always provided.\n */\n\n/**\n * Remove the corresponding application if is installed.\n * The call is ignored if the app is not installed.\n *\n * @param {MobileRemoveAppOptions} opts\n * @returns {boolean} Same as in `removeApp`\n */\ncommands.mobileRemoveApp = async function mobileRemoveApp (opts = {}) {\n const { appId } = requireArgs('appId', opts);\n return await this.removeApp(appId, opts);\n};\n\n/**\n * @typedef {Object} TerminateOptions\n * @property {number|string} timeout [500] - The count of milliseconds to wait until the\n * app is terminated.\n */\n\n/**\n * Terminates the app if it is running.\n *\n * @param {string} appId - Application package identifier\n * @param {?TerminateOptions} options - The set of application termination options\n * @returns {boolean} True if the app has been successfully terminated.\n * @throws {Error} if the app has not been terminated within the given timeout.\n */\ncommands.terminateApp = async function terminateApp (appId, options = {}) {\n this.log.info(`Terminating '${appId}'`);\n if (!(await this.adb.processExists(appId))) {\n this.log.info(`The app '${appId}' is not running`);\n return false;\n }\n await this.adb.forceStop(appId);\n const timeout = util.hasValue(options.timeout) && !isNaN(options.timeout) ? parseInt(options.timeout, 10) : 500;\n try {\n await waitForCondition(async () => await this.queryAppState(appId) <= APP_STATE.NOT_RUNNING,\n {waitMs: timeout, intervalMs: 100});\n } catch (e) {\n this.log.errorAndThrow(`'${appId}' is still running after ${timeout}ms timeout`);\n }\n this.log.info(`'${appId}' has been successfully terminated`);\n return true;\n};\n\n/**\n * @typedef {Object} MobileTerminateAppOptions\n * @property {string} appId - Application package identifier. Must be always provided.\n * @property {number|string} timeout [500] - The count of milliseconds to wait until the\n * app is terminated.\n */\n\n/**\n * Terminates the app if it is running.\n *\n * @param {MobileTerminateAppOptions} opts\n * @returns {boolean} Same as in `terminateApp`\n * @throws {Error} if the app has not been terminated within the given timeout.\n */\ncommands.mobileTerminateApp = async function mobileTerminateApp (opts = {}) {\n const { appId } = requireArgs('appId', opts);\n return await this.terminateApp(appId, opts);\n};\n\n/**\n * @typedef {Object} InstallOptions\n * @property {number} timeout [60000] - The count of milliseconds to wait until the\n * app is installed.\n * @property {boolean} allowTestPackages [false] - Set to true in order to allow test\n * packages installation.\n * @property {boolean} useSdcard [false] - Set to true to install the app on sdcard\n * instead of the device memory.\n * @property {boolean} grantPermissions [false] - Set to true in order to grant all the\n * permissions requested in the application's manifest\n * automatically after the installation is completed\n * under Android 6+.\n * @property {boolean} replace [true] - Set it to false if you don't want\n * the application to be upgraded/reinstalled\n * if it is already present on the device.\n */\n\n/**\n * Installs the given application to the device under test\n *\n * @param {string} appPath - The local apk path or a remote url\n * @param {?InstallOptions} options - The set of installation options\n * @throws {Error} if the given apk does not exist or is not reachable\n */\ncommands.installApp = async function installApp (appPath, options = {}) {\n const localPath = await this.helpers.configureApp(appPath, APP_EXTENSIONS);\n await this.adb.install(localPath, options);\n};\n\n/**\n * @typedef {Object} MobileInstallAppOptions\n * @property {string} appPath - The local apk path or a remote url. Must be always provided.\n * @property {number} timeout [60000] - The count of milliseconds to wait until the\n * app is installed.\n * @property {boolean} allowTestPackages [false] - Set to true in order to allow test\n * packages installation.\n * @property {boolean} useSdcard [false] - Set to true to install the app on sdcard\n * instead of the device memory.\n * @property {boolean} grantPermissions [false] - Set to true in order to grant all the\n * permissions requested in the application's manifest\n * automatically after the installation is completed\n * under Android 6+.\n * @property {boolean} replace [true] - Set it to false if you don't want\n * the application to be upgraded/reinstalled\n * if it is already present on the device.\n */\n\n/**\n * Installs the given application to the device under test\n *\n * @param {MobileInstallAppOptions} opts\n * @throws {Error} if the given apk does not exist or is not reachable\n */\ncommands.mobileInstallApp = async function mobileInstallApp (opts = {}) {\n const { appPath } = requireArgs('appPath', opts);\n return await this.installApp(appPath, opts);\n};\n\n/**\n * @typedef {Object} ClearAppOptions\n * @property {!string} appId The identifier of the application package to be cleared\n */\n\n/**\n * Deletes all data associated with a package.\n *\n * @param {ClearAppOptions} opts\n * @throws {Error} If cleaning of the app data fails\n */\ncommands.mobileClearApp = async function mobileClearApp (opts = {}) {\n const {appId} = opts;\n if (!appId) {\n throw new errors.InvalidArgumentError(`The 'appId' argument is required`);\n }\n await this.adb.clear(appId);\n};\n\nexport { commands };\nexport default commands;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA,MAAMA,cAAc,GAAG,CAAC,MAAD,EAAS,OAAT,CAAvB;AACA,MAAMC,sBAAsB,GAAG,mDAA/B;AAEA,MAAMC,QAAQ,GAAG,EAAjB;;;AAQAA,QAAQ,CAACC,cAAT,GAA0B,eAAeA,cAAf,CAA+BC,KAA/B,EAAsC;EAC9D,OAAO,MAAM,KA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yBG,IAAzB,CAAb;AACD,CAHD;;AA6BAL,QAAQ,CAAC2D,UAAT,GAAsB,eAAeA,UAAf,CAA2BC,OAA3B,EAAoCf,OAAO,GAAG,EAA9C,EAAkD;EACtE,MAAMgB,SAAS,GAAG,MAAM,KAAKC,OAAL,CAAaC,YAAb,CAA0BH,OAA1B,EAAmC9D,cAAnC,CAAxB;EACA,MAAM,KAAKK,GAAL,CAAS6D,OAAT,CAAiBH,SAAjB,EAA4BhB,OAA5B,CAAN;AACD,CAHD;;AA6BA7C,QAAQ,CAACiE,gBAAT,GAA4B,eAAeA,gBAAf,CAAiC5D,IAAI,GAAG,EAAxC,EAA4C;EACtE,MAAM;IAAEuD;EAAF,IAAc,IAAAtD,kBAAA,EAAY,SAAZ,EAAuBD,IAAvB,CAApB;EACA,OAAO,MAAM,KAAKsD,UAAL,CAAgBC,OAAhB,EAAyBvD,IAAzB,CAAb;AACD,CAHD;;AAgBAL,QAAQ,CAACkE,cAAT,GAA0B,eAAeA,cAAf,CAA+B7D,IAAI,GAAG,EAAtC,EAA0C;EAClE,MAAM;IAACH;EAAD,IAAUG,IAAhB;;EACA,IAAI,CAACH,KAAL,EAAY;IACV,MAAM,IAAIiE,cAAA,CAAOC,oBAAX,CAAiC,kCAAjC,CAAN;EACD;;EACD,MAAM,KAAKjE,GAAL,CAASkE,KAAT,CAAenE,KAAf,CAAN;AACD,CAND;;eASeF,Q"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","names":["CHROMEDRIVER_AUTODOWNLOAD_FEATURE","commands","helpers","extensions","getCurrentContext","curContext","defaultContextName","getContexts","webviewsMapping","webviewHelpers","getWebViewsMapping","adb","opts","assignContexts","setContext","name","util","hasValue","WEBVIEW_WIN","defaultWebviewName","contexts","_","includes","errors","NoSuchContextError","switchContext","mobileGetContexts","androidDeviceSocket","ensureWebviewsHavePages","webviewDevtoolsPort","enableWebviewDetailsCollection","Object","assign","isChromeSession","webviews","parseWebviewNames","NATIVE_WIN","log","debug","JSON","stringify","isChromedriverContext","startChromedriverProxy","recreateChromeDriverSessions","stopChromedriverProxies","suspendChromedriverProxy","Error","WEBVIEW_BASE","appPackage","isWebContext","context","cd","sessionChromedrivers","setupExistingChromedriver","cloneDeep","chromeUseRunningApp","extractChromeAndroidPackageFromContextName","androidPackage","match","length","chromeAndroidPackage","has","map","wm","webviewName","knownPackage","KNOWN_CHROME_PACKAGE_NAMES","appState","queryAppState","APP_STATE","RUNNING_IN_BACKGROUND","RUNNING_IN_FOREGROUND","info","setupNewChromedriver","curDeviceId","on","Chromedriver","EVENT_CHANGED","msg","state","STATE_STOPPED","onChromedriverStop","chromedriver","proxyReqRes","proxyReq","bind","proxyCommand","jwproxy","command","jwpProxyActive","warn","err","startUnexpectedShutdown","keys","removeAllListeners","stop","message","viewName","CHROMIUM_WIN","shouldDismissChromeWelcome","chromeOptions","isArray","args","dismissChromeWelcome","activity","getCurrentActivity","el","findElOrEls","click","ELEMENT","e","startChromeSession","knownPackages","chromeBundleId","chromeAndroidActivity","appActivity","hasWorkingWebview","restart","getChromedriverPort","portSpec","getPort","B","promisify","PortFinder","port","foundPort","potentialPort","stopPort","parseInt","isChromedriverAutodownloadEnabled","isFeatureEnabled","chromeDriverPort","chromedriverPort","chromedriverPorts","details","getWebviewDetails","undefined","isEmpty","executable","chromedriverExecutable","cmdArgs","chromedriverArgs","verbose","showChromedriverLog","executableDir","chromedriverExecutableDir","mappingPath","chromedriverChromeMappingFile","bundleId","useSystemExecutable","chromedriverUseSystemExecutable","disableBuildCheck","chromedriverDisableBuildCheck","isAutodownloadEnabled","opt","endsWith","merge","caps","createChromedriverCaps","start"],"sources":["../../../lib/commands/context.js"],"sourcesContent":["import _ from 'lodash';\nimport Chromedriver from 'appium-chromedriver';\nimport PortFinder from 'portfinder';\nimport B from 'bluebird';\nimport { util } from 'appium/support';\nimport { errors } from 'appium/driver';\nimport {\n default as webviewHelpers,\n NATIVE_WIN, WEBVIEW_BASE, WEBVIEW_WIN, CHROMIUM_WIN, KNOWN_CHROME_PACKAGE_NAMES\n} from '../webview-helpers';\nimport { APP_STATE } from '../android-helpers';\n\nconst CHROMEDRIVER_AUTODOWNLOAD_FEATURE = 'chromedriver_autodownload';\n\nlet commands = {}, helpers = {}, extensions = {};\n\n\n/* -------------------------------\n * Actual MJSONWP command handlers\n * ------------------------------- */\ncommands.getCurrentContext = async function getCurrentContext () { // eslint-disable-line require-await\n // if the current context is `null`, indicating no context\n // explicitly set, it is the default context\n return this.curContext || this.defaultContextName();\n};\n\ncommands.getContexts = async function getContexts () {\n const webviewsMapping = await webviewHelpers.getWebViewsMapping(this.adb, this.opts);\n return this.assignContexts(webviewsMapping);\n};\n\ncommands.setContext = async function setContext (name) {\n if (!util.hasValue(name)) {\n name = this.defaultContextName();\n } else if (name === WEBVIEW_WIN) {\n // handle setContext \"WEBVIEW\"\n name = this.defaultWebviewName();\n }\n // if we're already in the context we want, do nothing\n if (name === this.curContext) {\n return;\n }\n\n const webviewsMapping = await webviewHelpers.getWebViewsMapping(this.adb, this.opts);\n const contexts = this.assignContexts(webviewsMapping);\n // if the context we want doesn't exist, fail\n if (!_.includes(contexts, name)) {\n throw new errors.NoSuchContextError();\n }\n\n await this.switchContext(name, webviewsMapping);\n this.curContext = name;\n};\n\n/**\n * @typedef {Object} WebviewsMapping\n * @property {string} proc The name of the Devtools Unix socket\n * @property {string} webview The web view alias. Looks like `WEBVIEW_`\n * prefix plus PID or package name\n * @property {?Object} info Webview information as it is retrieved by\n * /json/version CDP endpoint\n * @property {?Array<Object>} pages Webview pages list as it is retrieved by\n * /json/list CDP endpoint\n * @propery {?string} webviewName An actual webview name for switching context.\n * This value becomes null when failing to find a PID for a webview.\n *\n * The following json demonstrates the example of WebviewsMapping object.\n * Note that `description` in `page` can be an empty string most likely when it comes to Mobile Chrome)\n * {\n * \"proc\": \"@webview_devtools_remote_22138\",\n * \"webview\": \"WEBVIEW_22138\",\n * \"info\": {\n * \"Android-Package\": \"io.appium.settings\",\n * \"Browser\": \"Chrome/74.0.3729.185\",\n * \"Protocol-Version\": \"1.3\",\n * \"User-Agent\": \"Mozilla/5.0 (Linux; Android 10; Android SDK built for x86 Build/QSR1.190920.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.185 Mobile Safari/537.36\",\n * \"V8-Version\": \"7.4.288.28\",\n * \"WebKit-Version\": \"537.36 (@22955682f94ce09336197bfb8dffea991fa32f0d)\",\n * \"webSocketDebuggerUrl\": \"ws://127.0.0.1:10900/devtools/browser\"\n * },\n * \"pages\": [\n * {\n * \"description\": \"{\\\"attached\\\":true,\\\"empty\\\":false,\\\"height\\\":1458,\\\"screenX\\\":0,\\\"screenY\\\":336,\\\"visible\\\":true,\\\"width\\\":1080}\",\n * \"devtoolsFrontendUrl\": \"http://chrome-devtools-frontend.appspot.com/serve_rev/@22955682f94ce09336197bfb8dffea991fa32f0d/inspector.html?ws=127.0.0.1:10900/devtools/page/27325CC50B600D31B233F45E09487B1F\",\n * \"id\": \"27325CC50B600D31B233F45E09487B1F\",\n * \"title\": \"Releases · appium/appium · GitHub\",\n * \"type\": \"page\",\n * \"url\": \"https://github.com/appium/appium/releases\",\n * \"webSocketDebuggerUrl\": \"ws://127.0.0.1:10900/devtools/page/27325CC50B600D31B233F45E09487B1F\"\n * }\n * ],\n * \"webviewName\": \"WEBVIEW_com.io.appium.setting\"\n * }\n */\n\n/**\n * Returns a webviewsMapping based on CDP endpoints\n *\n * @return {Array<WebviewsMapping>} webviewsMapping\n */\ncommands.mobileGetContexts = async function mobileGetContexts () {\n const opts = {\n androidDeviceSocket: this.opts.androidDeviceSocket,\n ensureWebviewsHavePages: true,\n webviewDevtoolsPort: this.opts.webviewDevtoolsPort,\n enableWebviewDetailsCollection: true\n };\n return await webviewHelpers.getWebViewsMapping(this.adb, opts);\n};\n\nhelpers.assignContexts = function assignContexts (webviewsMapping) {\n const opts = Object.assign({isChromeSession: this.isChromeSession}, this.opts);\n const webviews = webviewHelpers.parseWebviewNames(webviewsMapping, opts);\n this.contexts = [NATIVE_WIN, ...webviews];\n this.log.debug(`Available contexts: ${JSON.stringify(this.contexts)}`);\n return this.contexts;\n};\n\nhelpers.switchContext = async function switchContext (name, webviewsMapping) {\n // We have some options when it comes to webviews. If we want a\n // Chromedriver webview, we can only control one at a time.\n if (this.isChromedriverContext(name)) {\n // start proxying commands directly to chromedriver\n await this.startChromedriverProxy(name, webviewsMapping);\n } else if (this.isChromedriverContext(this.curContext)) {\n // if we're moving to a non-chromedriver webview, and our current context\n // _is_ a chromedriver webview, if caps recreateChromeDriverSessions is set\n // to true then kill chromedriver session using stopChromedriverProxies or\n // else simply suspend proxying to the latter\n if (this.opts.recreateChromeDriverSessions) {\n this.log.debug('recreateChromeDriverSessions set to true; killing existing chromedrivers');\n await this.stopChromedriverProxies();\n } else {\n await this.suspendChromedriverProxy();\n }\n } else {\n throw new Error(`Didn't know how to handle switching to context '${name}'`);\n }\n};\n\n\n/* ---------------------------------\n * On-object context-related helpers\n * --------------------------------- */\n\n// The reason this is a function and not just a constant is that both android-\n// driver and selendroid-driver use this logic, and each one returns\n// a different default context name\nhelpers.defaultContextName = function defaultContextName () {\n return NATIVE_WIN;\n};\n\nhelpers.defaultWebviewName = function defaultWebviewName () {\n return WEBVIEW_BASE + this.opts.appPackage;\n};\n\nhelpers.isWebContext = function isWebContext () {\n return this.curContext !== null && this.curContext !== NATIVE_WIN;\n};\n\n// Turn on proxying to an existing Chromedriver session or a new one\nhelpers.startChromedriverProxy = async function startChromedriverProxy (context, webviewsMapping) {\n this.log.debug(`Connecting to chrome-backed webview context '${context}'`);\n\n let cd;\n if (this.sessionChromedrivers[context]) {\n // in the case where we've already set up a chromedriver for a context,\n // we want to reconnect to it, not create a whole new one\n this.log.debug(`Found existing Chromedriver for context '${context}'. Using it.`);\n cd = this.sessionChromedrivers[context];\n await setupExistingChromedriver(this.log, cd);\n } else {\n let opts = _.cloneDeep(this.opts);\n opts.chromeUseRunningApp = true;\n\n // if requested, tell chromedriver to attach to the android package we have\n // associated with the context name, rather than the package of the AUT.\n // And turn this on by default for chrome--if chrome pops up with a webview\n // and someone wants to switch to it, we should let chromedriver connect to\n // chrome rather than staying stuck on the AUT\n if (opts.extractChromeAndroidPackageFromContextName || context === `${WEBVIEW_BASE}chrome`) {\n let androidPackage = context.match(`${WEBVIEW_BASE}(.+)`);\n if (androidPackage && androidPackage.length > 0) {\n opts.chromeAndroidPackage = androidPackage[1];\n }\n if (!opts.extractChromeAndroidPackageFromContextName) {\n if (_.has(this.opts, 'enableWebviewDetailsCollection') && !this.opts.enableWebviewDetailsCollection) {\n // When enableWebviewDetailsCollection capability is explicitly disabled, try to identify\n // chromeAndroidPackage based on contexts, known chrome variant packages and queryAppState result\n // since webviewsMapping does not have info object\n const contexts = webviewsMapping.map((wm) => wm.webviewName);\n for (const knownPackage of KNOWN_CHROME_PACKAGE_NAMES) {\n if (_.includes(contexts, `${WEBVIEW_BASE}${knownPackage}`)) {\n continue;\n }\n const appState = await this.queryAppState(knownPackage);\n if (_.includes([APP_STATE.RUNNING_IN_BACKGROUND, APP_STATE.RUNNING_IN_FOREGROUND], appState)) {\n opts.chromeAndroidPackage = knownPackage;\n this.log.debug(`Identified chromeAndroidPackage as '${opts.chromeAndroidPackage}' ` +\n `for context '${context}' by querying states of Chrome app packages`);\n break;\n }\n }\n } else {\n for (const wm of webviewsMapping) {\n if (wm.webviewName === context && _.has(wm?.info, 'Android-Package')) {\n opts.chromeAndroidPackage = wm.info['Android-Package'];\n this.log.debug(`Identified chromeAndroidPackage as '${opts.chromeAndroidPackage}' ` +\n `for context '${context}' by CDP`);\n break;\n }\n }\n }\n }\n }\n\n cd = await this.setupNewChromedriver(opts, this.adb.curDeviceId, this.adb, context);\n // bind our stop/exit handler, passing in context so we know which\n // one stopped unexpectedly\n cd.on(Chromedriver.EVENT_CHANGED, (msg) => {\n if (msg.state === Chromedriver.STATE_STOPPED) {\n this.onChromedriverStop(context);\n }\n });\n // save the chromedriver object under the context\n this.sessionChromedrivers[context] = cd;\n }\n // hook up the local variables so we can proxy this biz\n this.chromedriver = cd;\n this.proxyReqRes = this.chromedriver.proxyReq.bind(this.chromedriver);\n this.proxyCommand = this.chromedriver.jwproxy.command.bind(this.chromedriver.jwproxy);\n this.jwpProxyActive = true;\n};\n\n// Stop proxying to any Chromedriver\nhelpers.suspendChromedriverProxy = function suspendChromedriverProxy () {\n this.chromedriver = null;\n this.proxyReqRes = null;\n this.proxyCommand = null;\n this.jwpProxyActive = false;\n};\n\n// Handle an out-of-band Chromedriver stop event\nhelpers.onChromedriverStop = async function onChromedriverStop (context) {\n this.log.warn(`Chromedriver for context ${context} stopped unexpectedly`);\n if (context === this.curContext) {\n // we exited unexpectedly while automating the current context and so want\n // to shut down the session and respond with an error\n let err = new Error('Chromedriver quit unexpectedly during session');\n await this.startUnexpectedShutdown(err);\n } else {\n // if a Chromedriver in the non-active context barfs, we don't really\n // care, we'll just make a new one next time we need the context.\n this.log.warn(\"Chromedriver quit unexpectedly, but it wasn't the active \" +\n 'context, ignoring');\n delete this.sessionChromedrivers[context];\n }\n};\n\n// Intentionally stop all the chromedrivers currently active, and ignore\n// their exit events\nhelpers.stopChromedriverProxies = async function stopChromedriverProxies () {\n this.suspendChromedriverProxy(); // make sure we turn off the proxy flag\n for (let context of _.keys(this.sessionChromedrivers)) {\n let cd = this.sessionChromedrivers[context];\n this.log.debug(`Stopping chromedriver for context ${context}`);\n // stop listening for the stopped state event\n cd.removeAllListeners(Chromedriver.EVENT_CHANGED);\n try {\n await cd.stop();\n } catch (err) {\n this.log.warn(`Error stopping Chromedriver: ${err.message}`);\n }\n delete this.sessionChromedrivers[context];\n }\n};\n\nhelpers.isChromedriverContext = function isChromedriverContext (viewName) {\n return _.includes(viewName, WEBVIEW_WIN) || viewName === CHROMIUM_WIN;\n};\n\nhelpers.shouldDismissChromeWelcome = function shouldDismissChromeWelcome () {\n return !!this.opts.chromeOptions &&\n _.isArray(this.opts.chromeOptions.args) &&\n this.opts.chromeOptions.args.includes('--no-first-run');\n};\n\nhelpers.dismissChromeWelcome = async function dismissChromeWelcome () {\n this.log.info('Trying to dismiss Chrome welcome');\n let activity = await this.getCurrentActivity();\n if (activity !== 'org.chromium.chrome.browser.firstrun.FirstRunActivity') {\n this.log.info('Chrome welcome dialog never showed up! Continuing');\n return;\n }\n let el = await this.findElOrEls('id', 'com.android.chrome:id/terms_accept', false);\n await this.click(el.ELEMENT);\n try {\n let el = await this.findElOrEls('id', 'com.android.chrome:id/negative_button', false);\n await this.click(el.ELEMENT);\n } catch (e) {\n // DO NOTHING, THIS DEVICE DIDNT LAUNCH THE SIGNIN DIALOG\n // IT MUST BE A NON GMS DEVICE\n this.log.warn(`This device did not show Chrome SignIn dialog, ${e.message}`);\n }\n};\n\nhelpers.startChromeSession = async function startChromeSession () {\n this.log.info('Starting a chrome-based browser session');\n let opts = _.cloneDeep(this.opts);\n\n const knownPackages = [\n 'org.chromium.chrome.shell',\n 'com.android.chrome',\n 'com.chrome.beta',\n 'org.chromium.chrome',\n 'org.chromium.webview_shell',\n ];\n\n if (_.includes(knownPackages, this.opts.appPackage)) {\n opts.chromeBundleId = this.opts.appPackage;\n } else {\n opts.chromeAndroidActivity = this.opts.appActivity;\n }\n this.chromedriver = await this.setupNewChromedriver(opts, this.adb.curDeviceId, this.adb);\n this.chromedriver.on(Chromedriver.EVENT_CHANGED, (msg) => {\n if (msg.state === Chromedriver.STATE_STOPPED) {\n this.onChromedriverStop(CHROMIUM_WIN);\n }\n });\n\n // Now that we have a Chrome session, we ensure that the context is\n // appropriately set and that this chromedriver is added to the list\n // of session chromedrivers so we can switch back and forth\n this.curContext = CHROMIUM_WIN;\n this.sessionChromedrivers[CHROMIUM_WIN] = this.chromedriver;\n this.proxyReqRes = this.chromedriver.proxyReq.bind(this.chromedriver);\n this.proxyCommand = this.chromedriver.jwproxy.command.bind(this.chromedriver.jwproxy);\n this.jwpProxyActive = true;\n\n if (this.shouldDismissChromeWelcome()) {\n // dismiss Chrome welcome dialog\n await this.dismissChromeWelcome();\n }\n};\n\n\n/* --------------------------\n * Internal library functions\n * -------------------------- */\n\nasync function setupExistingChromedriver (log, chromedriver) {\n // check the status by sending a simple window-based command to ChromeDriver\n // if there is an error, we want to recreate the ChromeDriver session\n if (!await chromedriver.hasWorkingWebview()) {\n log.debug('ChromeDriver is not associated with a window. ' +\n 'Re-initializing the session.');\n await chromedriver.restart();\n }\n return chromedriver;\n}\n\n/**\n * Find a free port to have Chromedriver listen on.\n *\n * @param {array} portSpec - Array which is a list of ports. A list item may\n * also itself be an array of length 2 specifying a start and end port of\n * a range. Some valid port specs:\n * - [8000, 8001, 8002]\n * - [[8000, 8005]]\n * - [8000, [9000, 9100]]\n * @param {Object?} log Logger instance\n *\n * @return {number} A free port\n */\nasync function getChromedriverPort (portSpec, log = null) {\n const getPort = B.promisify(PortFinder.getPort, {context: PortFinder});\n\n // if the user didn't give us any specific information about chromedriver\n // port ranges, just find any free port\n if (!portSpec) {\n const port = await getPort();\n log?.debug(`A port was not given, using random free port: ${port}`);\n return port;\n }\n\n // otherwise find the free port based on a list or range provided by the user\n log?.debug(`Finding a free port for chromedriver using spec ${JSON.stringify(portSpec)}`);\n let foundPort = null;\n for (const potentialPort of portSpec) {\n let port, stopPort;\n if (_.isArray(potentialPort)) {\n ([port, stopPort] = potentialPort);\n } else {\n port = parseInt(potentialPort, 10); // ensure we have a number and not a string\n stopPort = port;\n }\n try {\n log?.debug(`Checking port range ${port}:${stopPort}`);\n foundPort = await getPort({port, stopPort});\n break;\n } catch (e) {\n log?.debug(`Nothing in port range ${port}:${stopPort} was available`);\n }\n }\n\n if (foundPort === null) {\n throw new Error(`Could not find a free port for chromedriver using ` +\n `chromedriverPorts spec ${JSON.stringify(portSpec)}`);\n }\n\n log?.debug(`Using free port ${foundPort} for chromedriver`);\n return foundPort;\n}\n\nhelpers.isChromedriverAutodownloadEnabled = function isChromedriverAutodownloadEnabled () {\n if (this.isFeatureEnabled(CHROMEDRIVER_AUTODOWNLOAD_FEATURE)) {\n return true;\n }\n this?.log?.debug(`Automated Chromedriver download is disabled. ` +\n `Use '${CHROMEDRIVER_AUTODOWNLOAD_FEATURE}' server feature to enable it`);\n return false;\n};\n\nhelpers.setupNewChromedriver = async function setupNewChromedriver (opts, curDeviceId, adb, context = null) {\n if (opts.chromeDriverPort) {\n this?.log?.warn(`The 'chromeDriverPort' capability is deprecated. Please use 'chromedriverPort' instead`);\n opts.chromedriverPort = opts.chromeDriverPort;\n }\n\n if (opts.chromedriverPort) {\n this?.log?.debug(`Using user-specified port ${opts.chromedriverPort} for chromedriver`);\n } else {\n // if a single port wasn't given, we'll look for a free one\n opts.chromedriverPort = await getChromedriverPort(opts.chromedriverPorts, this?.log);\n }\n\n const details = context ? webviewHelpers.getWebviewDetails(adb, context) : undefined;\n if (!_.isEmpty(details)) {\n this?.log?.debug('Passing web view details to the Chromedriver constructor: ' +\n JSON.stringify(details, null, 2));\n }\n\n const chromedriver = new Chromedriver({\n port: opts.chromedriverPort,\n executable: opts.chromedriverExecutable,\n adb,\n cmdArgs: opts.chromedriverArgs,\n verbose: !!opts.showChromedriverLog,\n executableDir: opts.chromedriverExecutableDir,\n mappingPath: opts.chromedriverChromeMappingFile,\n bundleId: opts.chromeBundleId,\n useSystemExecutable: opts.chromedriverUseSystemExecutable,\n disableBuildCheck: opts.chromedriverDisableBuildCheck,\n details,\n isAutodownloadEnabled: this?.isChromedriverAutodownloadEnabled?.()\n });\n\n // make sure there are chromeOptions\n opts.chromeOptions = opts.chromeOptions || {};\n // try out any prefixed chromeOptions,\n // and strip the prefix\n for (const opt of _.keys(opts)) {\n if (opt.endsWith(':chromeOptions')) {\n this?.log?.warn(`Merging '${opt}' into 'chromeOptions'. This may cause unexpected behavior`);\n _.merge(opts.chromeOptions, opts[opt]);\n }\n }\n\n const caps = webviewHelpers.createChromedriverCaps(opts, curDeviceId, details);\n this?.log?.debug(`Before starting chromedriver, androidPackage is '${caps.chromeOptions.androidPackage}'`);\n await chromedriver.start(caps);\n return chromedriver;\n};\nconst setupNewChromedriver = helpers.setupNewChromedriver;\n\n\nObject.assign(extensions, commands, helpers);\nexport { commands, helpers, setupNewChromedriver };\nexport default extensions;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAIA;;;;;;AAEA,MAAMA,iCAAiC,GAAG,2BAA1C;AAEA,IAAIC,QAAQ,GAAG,EAAf;AAAA,IAAmBC,OAAO,GAAG,EAA7B;AAAA,IAAiCC,UAAU,GAAG,EAA9C;;;;AAMAF,QAAQ,CAACG,iBAAT,GAA6B,eAAeA,iBAAf,GAAoC;EAG/D,OAAO,KAAKC,UAAL,IAAmB,KAAKC,kBAAL,EAA1B;AACD,CAJD;;AAMAL,QAAQ,CAACM,WAAT,GAAuB,eAAeA,WAAf,GAA8B;EACnD,MAAMC,eAAe,GAAG,MAAMC,uBAAA,CAAeC,kBAAf,CAAkC,KAAKC,GAAvC,EAA4C,KAAKC,IAAjD,CAA9B;EACA,OAAO,KAAKC,cAAL,CAAoBL,eAApB,CAAP;AACD,CAHD;;AAKAP,QAAQ,CAACa,UAAT,GAAsB,eAAeA,UAAf,CAA2BC,IAA3B,EAAiC;EACrD,IAAI,CAACC,aAAA,CAAKC,QAAL,CAAcF,IAAd,CAAL,EAA0B;IACxBA,IAAI,GAAG,KAAKT,kBAAL,EAAP;EACD,CAFD,MAEO,IAAIS,IAAI,KAAKG,2BAAb,EAA0B;IAE/BH,IAAI,GAAG,KAAKI,kBAAL,EAAP;EACD;;EAED,IAAIJ,IAAI,KAAK,KAAKV,UAAlB,EAA8B;IAC5B;EACD;;EAED,MAAMG,eAAe,GAAG,MAAMC,uBAAA,CAAeC,kBAAf,CAAkC,KAAKC,GAAvC,EAA4C,KAAKC,IAAjD,CAA9B;EACA,MAAMQ,QAAQ,GAAG,KAAKP,cAAL,CAAoBL,eAApB,CAAjB;;EAEA,IAAI,CAACa,eAAA,CAAEC,QAAF,CAAWF,QAAX,E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,EAA4BxF,IAAI,CAAC8I,GAAD,CAAhC;IACD;EACF;;EAED,MAAMG,IAAI,GAAGpJ,uBAAA,CAAeqJ,sBAAf,CAAsClJ,IAAtC,EAA4C8D,WAA5C,EAAyD4D,OAAzD,CAAb;;EACA,+DAAMjG,GAAN,0DAAWC,KAAX,CAAkB,oDAAmDuH,IAAI,CAACzD,aAAL,CAAmB3C,cAAe,GAAvG;EACA,MAAMyB,YAAY,CAAC6E,KAAb,CAAmBF,IAAnB,CAAN;EACA,OAAO3E,YAAP;AACD,CAjDD;;AAkDA,MAAMT,oBAAoB,GAAGvE,OAAO,CAACuE,oBAArC;;AAGA1C,MAAM,CAACC,MAAP,CAAc7B,UAAd,EAA0BF,QAA1B,EAAoCC,OAApC;eAEeC,U"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"coverage.js","names":["commands","endCoverage","intentToBroadcast","ecOnDevicePath","adb","rimraf","broadcastProcessEnd","appProcess","pullFile","err","log","warn","message"],"sources":["../../../lib/commands/coverage.js"],"sourcesContent":["const commands = {};\n\n\ncommands.endCoverage = async function endCoverage (intentToBroadcast, ecOnDevicePath) {\n try {\n // ensure the ec we're pulling is newly created as a result of the intent.\n await this.adb.rimraf(ecOnDevicePath);\n await this.adb.broadcastProcessEnd(intentToBroadcast, this.appProcess);\n return await this.pullFile(ecOnDevicePath);\n } catch (err) {\n this.log.warn(`Error ending test coverage: ${err.message}`);\n }\n return '';\n};\n\n\nexport { commands };\nexport default commands;\n"],"mappings":";;;;;;;;;AAAA,MAAMA,QAAQ,GAAG,EAAjB;;;AAGAA,QAAQ,CAACC,WAAT,GAAuB,eAAeA,WAAf,CAA4BC,iBAA5B,EAA+CC,cAA/C,EAA+D;EACpF,IAAI;IAEF,MAAM,KAAKC,GAAL,CAASC,MAAT,CAAgBF,cAAhB,CAAN;IACA,MAAM,KAAKC,GAAL,CAASE,mBAAT,CAA6BJ,iBAA7B,EAAgD,KAAKK,UAArD,CAAN;IACA,OAAO,MAAM,KAAKC,QAAL,CAAcL,cAAd,CAAb;EACD,CALD,CAKE,OAAOM,GAAP,EAAY;IACZ,KAAKC,GAAL,CAASC,IAAT,CAAe,+BAA8BF,GAAG,CAACG,OAAQ,EAAzD;EACD;;EACD,OAAO,EAAP;AACD,CAVD;;eAceZ,Q"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"element.js","names":["commands","helpers","extensions","getAttribute","attribute","elementId","p","bootstrap","sendAction","getName","elementDisplayed","elementEnabled","elementSelected","setElementValue","keys","replace","text","Array","join","params","unicodeKeyboard","opts","doSetElementValue","setValue","replaceValue","setValueImmediate","click","adb","inputText","getText","clear","length","log","debug","retryInterval","remainingLength","lengthToSend","clearTextField","getLocation","getLocationInView","getSize","getElementRect","touchLongClick","x","y","duration","androidHelpers","removeNullProperties","touchDown","touchUp","touchMove","complexTap","tapCount","touchCount","tap","count","util","hasValue","Error","i","Object","assign"],"sources":["../../../lib/commands/element.js"],"sourcesContent":["import androidHelpers from '../android-helpers';\nimport { retryInterval } from 'asyncbox';\nimport { util } from 'appium/support';\n\n\nlet commands = {}, helpers = {}, extensions = {};\n\ncommands.getAttribute = async function getAttribute (attribute, elementId) {\n let p = {attribute, elementId};\n return await this.bootstrap.sendAction('element:getAttribute', p);\n};\n\ncommands.getName = async function getName (elementId) {\n return await this.getAttribute('className', elementId);\n};\n\ncommands.elementDisplayed = async function elementDisplayed (elementId) {\n return await this.getAttribute('displayed', elementId) === 'true';\n};\n\ncommands.elementEnabled = async function elementEnabled (elementId) {\n return await this.getAttribute('enabled', elementId) === 'true';\n};\n\ncommands.elementSelected = async function elementSelected (elementId) {\n return await this.getAttribute('selected', elementId) === 'true';\n};\n\nhelpers.setElementValue = async function setElementValue (keys, elementId, replace = false) {\n let text = keys;\n if (keys instanceof Array) {\n text = keys.join('');\n }\n\n let params = {\n elementId,\n text,\n replace,\n unicodeKeyboard: this.opts.unicodeKeyboard\n };\n\n return await this.doSetElementValue(params);\n};\n\n/**\n * Reason for isolating doSetElementValue from setElementValue is for reusing setElementValue\n * across android-drivers (like appium-uiautomator2-driver) and to avoid code duplication.\n * Other android-drivers (like appium-uiautomator2-driver) need to override doSetElementValue\n * to facilitate setElementValue.\n */\nhelpers.doSetElementValue = async function doSetElementValue (params) {\n return await this.bootstrap.sendAction('element:setText', params);\n};\n\ncommands.setValue = async function setValue (keys, elementId) {\n return await this.setElementValue(keys, elementId, false);\n};\n\ncommands.replaceValue = async function replaceValue (keys, elementId) {\n return await this.setElementValue(keys, elementId, true);\n};\n\ncommands.setValueImmediate = async function setValueImmediate (keys, elementId) {\n let text = keys;\n if (keys instanceof Array) {\n text = keys.join('');\n }\n\n // first, make sure we are focused on the element\n await this.click(elementId);\n\n // then send through adb\n await this.adb.inputText(text);\n};\n\ncommands.getText = async function getText (elementId) {\n return await this.bootstrap.sendAction('element:getText', {elementId});\n};\n\ncommands.clear = async function clear (elementId) {\n let text = (await this.getText(elementId)) || '';\n let length = text.length;\n if (length === 0) {\n // if length is zero there are two possibilities:\n // 1. there is nothing in the text field\n // 2. it is a password field\n // since there is little overhead to the adb call, delete 100 elements\n // if we get zero, just in case it is #2\n length = 100;\n }\n await this.click(elementId);\n this.log.debug(`Sending up to ${length} clear characters to device`);\n return await retryInterval(5, 500, async () => {\n let remainingLength = length;\n while (remainingLength > 0) {\n let lengthToSend = remainingLength < 50 ? remainingLength : 50;\n this.log.debug(`Sending ${lengthToSend} clear characters to device`);\n await this.adb.clearTextField(lengthToSend);\n remainingLength -= lengthToSend;\n }\n });\n};\n\ncommands.click = async function click (elementId) {\n return await this.bootstrap.sendAction('element:click', {elementId});\n};\n\ncommands.getLocation = async function getLocation (elementId) {\n return await this.bootstrap.sendAction('element:getLocation', {elementId});\n};\n\ncommands.getLocationInView = async function getLocationInView (elementId) {\n return await this.getLocation(elementId);\n};\n\ncommands.getSize = async function getSize (elementId) {\n return await this.bootstrap.sendAction('element:getSize', {elementId});\n};\n\ncommands.getElementRect = async function getElementRect (elementId) {\n return await this.bootstrap.sendAction('element:getRect', {elementId});\n};\n\ncommands.touchLongClick = async function touchLongClick (elementId, x, y, duration) {\n let params = {elementId, x, y, duration};\n androidHelpers.removeNullProperties(params);\n return await this.bootstrap.sendAction('element:touchLongClick', params);\n};\n\ncommands.touchDown = async function touchDown (elementId, x, y) {\n let params = {elementId, x, y};\n androidHelpers.removeNullProperties(params);\n return await this.bootstrap.sendAction('element:touchDown', params);\n};\n\ncommands.touchUp = async function touchUp (elementId, x, y) {\n let params = {elementId, x, y};\n androidHelpers.removeNullProperties(params);\n return await this.bootstrap.sendAction('element:touchUp', params);\n};\n\ncommands.touchMove = async function touchMove (elementId, x, y) {\n let params = {elementId, x, y};\n androidHelpers.removeNullProperties(params);\n return await this.bootstrap.sendAction('element:touchMove', params);\n};\n\ncommands.complexTap = async function complexTap (tapCount, touchCount, duration, x, y) {\n return await this.bootstrap.sendAction('click', {x, y});\n};\n\ncommands.tap = async function (elementId = null, x = null, y = null, count = 1) {\n if (!util.hasValue(elementId) && !util.hasValue(x) && !util.hasValue(y)) {\n throw new Error(`Either element to tap or both absolute coordinates should be defined`);\n }\n for (let i = 0; i < count; i++) {\n if (util.hasValue(elementId)) {\n // FIXME: bootstrap ignores relative coordinates\n await this.bootstrap.sendAction('element:click', {elementId, x, y});\n } else {\n await this.bootstrap.sendAction('click', {x, y});\n }\n }\n};\n\nObject.assign(extensions, commands, helpers);\nexport { commands, helpers };\nexport default extensions;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AACA;;AAGA,IAAIA,QAAQ,GAAG,EAAf;AAAA,IAAmBC,OAAO,GAAG,EAA7B;AAAA,IAAiCC,UAAU,GAAG,EAA9C;;;;AAEAF,QAAQ,CAACG,YAAT,GAAwB,eAAeA,YAAf,CAA6BC,SAA7B,EAAwCC,SAAxC,EAAmD;EACzE,IAAIC,CAAC,GAAG;IAACF,SAAD;IAAYC;EAAZ,CAAR;EACA,OAAO,MAAM,KAAKE,SAAL,CAAeC,UAAf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ACF,CAZD;;AAcAgB,MAAM,CAACC,MAAP,CAAc3D,UAAd,EAA0BF,QAA1B,EAAoCC,OAApC;eAEeC,U"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"emu-console.js","names":["EMU_CONSOLE_FEATURE","commands","mobileExecEmuConsoleCommand","opts","ensureFeatureEnabled","command","execTimeout","connTimeout","initTimeout","errors","InvalidArgumentError","adb","execEmuConsoleCommand"],"sources":["../../../lib/commands/emu-console.js"],"sourcesContent":["import { errors } from 'appium/driver';\n\nconst EMU_CONSOLE_FEATURE = 'emulator_console';\n\nconst commands = {};\n\n/**\n * @typedef {Object} ExecOptions\n * @property {!Array<string>|string} command - The actual command to execute. See\n * https://developer.android.com/studio/run/emulator-console for more details\n * on available commands\n * @property {number} execTimeout [60000] A timeout used to wait for a server\n * reply to the given command in milliseconds\n * @property {number} connTimeout [5000] Console connection timeout in milliseconds\n * @property {number} initTimeout [5000] Telnet console initialization timeout\n * in milliseconds (the time between the connection happens and the command prompt\n * is available)\n */\n\n/**\n * Executes a command through emulator telnet console interface and returns its output.\n * The `emulator_console` server feature must be enabled in order to use this method.\n *\n * @param {ExecOptions} opts\n * @returns {string} The command output\n * @throws {Error} If there was an error while connecting to the Telnet console\n * or if the given command returned non-OK response\n */\ncommands.mobileExecEmuConsoleCommand = async function mobileExecEmuConsoleCommand (opts = {}) {\n this.ensureFeatureEnabled(EMU_CONSOLE_FEATURE);\n\n const {\n command,\n execTimeout,\n connTimeout,\n initTimeout,\n } = opts;\n\n if (!command) {\n throw new errors.InvalidArgumentError(`The 'command' argument is mandatory`);\n }\n\n return await this.adb.execEmuConsoleCommand(command, {\n execTimeout,\n connTimeout,\n initTimeout,\n });\n};\n\nexport { commands };\nexport default commands;\n"],"mappings":";;;;;;;;;AAAA;;AAEA,MAAMA,mBAAmB,GAAG,kBAA5B;AAEA,MAAMC,QAAQ,GAAG,EAAjB;;;AAwBAA,QAAQ,CAACC,2BAAT,GAAuC,eAAeA,2BAAf,CAA4CC,IAAI,GAAG,EAAnD,EAAuD;EAC5F,KAAKC,oBAAL,CAA0BJ,mBAA1B;EAEA,MAAM;IACJK,OADI;IAEJC,WAFI;IAGJC,WAHI;IAIJC;EAJI,IAKFL,IALJ;;EAOA,IAAI,CAACE,OAAL,EAAc;IACZ,MAAM,IAAII,cAAA,CAAOC,oBAAX,CAAiC,qCAAjC,CAAN;EACD;;EAED,OAAO,MAAM,KAAKC,GAAL,CAASC,qBAAT,CAA+BP,OAA/B,EAAwC;IACnDC,WADmD;IAEnDC,WAFmD;IAGnDC;EAHmD,CAAxC,CAAb;AAKD,CAnBD;;eAsBeP,Q"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"execute.js","names":["extensions","execute","script","args","match","log","info","replace","trim","executeMobile","_","isArray","isWebContext","errors","NotImplementedError","endpoint","chromedriver","jwproxy","downstreamProtocol","PROTOCOLS","MJSONWP","command","mobileCommand","opts","mobileCommandsMapping","shell","execEmuConsoleCommand","startLogsBroadcast","stopLogsBroadcast","changePermissions","getPermissions","performEditorAction","sensorSet","getDeviceTime","startScreenStreaming","stopScreenStreaming","getNotifications","listSms","pushFile","pullFile","pullFolder","deleteFile","isAppInstalled","queryAppState","activateApp","removeApp","terminateApp","installApp","clearApp","startService","stopService","startActivity","broadcast","getContexts","unlock","refreshGpsCache","startMediaProjectionRecording","isMediaProjectionRecordingRunning","stopMediaProjectionRecording","has","UnknownCommandError","keys"],"sources":["../../../lib/commands/execute.js"],"sourcesContent":["import _ from 'lodash';\nimport { errors, PROTOCOLS } from 'appium/driver';\n\nconst extensions = {};\n\nextensions.execute = async function execute (script, args) {\n if (script.match(/^mobile:/)) {\n this.log.info(`Executing native command '${script}'`);\n script = script.replace(/^mobile:/, '').trim();\n return await this.executeMobile(script, _.isArray(args) ? args[0] : args);\n }\n if (!this.isWebContext()) {\n throw new errors.NotImplementedError();\n }\n const endpoint = this.chromedriver.jwproxy.downstreamProtocol === PROTOCOLS.MJSONWP\n ? '/execute'\n : '/execute/sync';\n return await this.chromedriver.jwproxy.command(endpoint, 'POST', {\n script,\n args,\n });\n};\n\nextensions.executeMobile = async function executeMobile (mobileCommand, opts = {}) {\n const mobileCommandsMapping = {\n shell: 'mobileShell',\n\n execEmuConsoleCommand: 'mobileExecEmuConsoleCommand',\n\n startLogsBroadcast: 'mobileStartLogsBroadcast',\n stopLogsBroadcast: 'mobileStopLogsBroadcast',\n\n changePermissions: 'mobileChangePermissions',\n getPermissions: 'mobileGetPermissions',\n\n performEditorAction: 'mobilePerformEditorAction',\n\n sensorSet: 'sensorSet',\n\n getDeviceTime: 'mobileGetDeviceTime',\n\n startScreenStreaming: 'mobileStartScreenStreaming',\n stopScreenStreaming: 'mobileStopScreenStreaming',\n\n getNotifications: 'mobileGetNotifications',\n\n listSms: 'mobileListSms',\n\n pushFile: 'mobilePushFile',\n pullFile: 'mobilePullFile',\n pullFolder: 'mobilePullFolder',\n deleteFile: 'mobileDeleteFile',\n\n isAppInstalled: 'mobileIsAppInstalled',\n queryAppState: 'mobileQueryAppState',\n activateApp: 'mobileActivateApp',\n removeApp: 'mobileRemoveApp',\n terminateApp: 'mobileTerminateApp',\n installApp: 'mobileInstallApp',\n clearApp: 'mobileClearApp',\n\n startService: 'mobileStartService',\n stopService: 'mobileStopService',\n startActivity: 'mobileStartActivity',\n broadcast: 'mobileBroadcast',\n\n getContexts: 'mobileGetContexts',\n\n unlock: 'mobileUnlock',\n\n refreshGpsCache: 'mobileRefreshGpsCache',\n\n startMediaProjectionRecording: 'mobileStartMediaProjectionRecording',\n isMediaProjectionRecordingRunning: 'mobileIsMediaProjectionRecordingRunning',\n stopMediaProjectionRecording: 'mobileStopMediaProjectionRecording',\n };\n\n if (!_.has(mobileCommandsMapping, mobileCommand)) {\n throw new errors.UnknownCommandError(`Unknown mobile command \"${mobileCommand}\". ` +\n `Only ${_.keys(mobileCommandsMapping)} commands are supported.`);\n }\n return await this[mobileCommandsMapping[mobileCommand]](opts);\n};\n\n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ER_PATH_MARKER","CONTAINER_PATH_PATTERN","RegExp","ANDROID_MEDIA_RESCAN_INTENT","commands","parseContainerPath","remotePath","match","exec","Error","path","posix","resolve","scanMedia","adb","log","debug","getApiLevel","shell","e","warn","stderr","message","escapePath","p","replace","pullFile","endsWith","errors","InvalidArgumentError","tmpDestination","startsWith","packageId","pathInContainer","basename","errorAndThrow","localFile","tempDir","prefix","suffix","pull","util","toInMemoryBase64","toString","fs","exists","unlink","mobilePullFile","opts","requireArgs","pushFile","base64Data","_","isArray","Buffer","from","content","writeFile","dirname","push","mobilePushFile","payload","pullFolder","tmpRoot","openDir","zip","toInMemoryZip","encodeToBase64","rimraf","mobilePullFolder","deleteFileOrFolder","performRemoteFsCheck","op","runAs","passFlag","checkCmd","fullCmd","includes","ign","isFile","isDir","isPresent","dstPath","pkgId","info","expectsFile","mobileDeleteFile"],"sources":["../../../lib/commands/file-actions.js"],"sourcesContent":["import _ from 'lodash';\nimport { fs, util, zip, tempDir } from 'appium/support';\nimport path from 'path';\nimport { errors } from 'appium/driver';\nimport { requireArgs } from '../utils';\n\n\nconst CONTAINER_PATH_MARKER = '@';\n// https://regex101.com/r/PLdB0G/2\nconst CONTAINER_PATH_PATTERN = new RegExp(`^${CONTAINER_PATH_MARKER}([^/]+)/(.+)`);\nconst ANDROID_MEDIA_RESCAN_INTENT = 'android.intent.action.MEDIA_SCANNER_SCAN_FILE';\n\n\nconst commands = {};\n\n/**\n * Parses the actual destination path from the given value\n *\n * @param {string} remotePath The preformatted remote path, which looks like\n * `@my.app.id/my/path`\n * @returns {Array<string>} An array, where the first item is the parsed package\n * identifier and the second one is the actual destination path inside the package.\n * @throws {Error} If the given string cannot be parsed\n */\nfunction parseContainerPath (remotePath) {\n const match = CONTAINER_PATH_PATTERN.exec(remotePath);\n if (!match) {\n throw new Error(`It is expected that package identifier is separated from the relative path with a single slash. ` +\n `'${remotePath}' is given instead`);\n }\n return [match[1], path.posix.resolve(`/data/data/${match[1]}`, match[2])];\n}\n\n/**\n * Scans the given file/folder on the remote device\n * and adds matching items to the device's media library.\n * Exceptions are ignored and written into the log.\n *\n * @param {ADB} adb ADB instance\n * @param {Object?} log Logger instance\n * @param {string} remotePath The file/folder path on the remote device\n */\nasync function scanMedia (adb, remotePath, log = null) {\n log?.debug(`Performing media scan of '${remotePath}'`);\n try {\n // https://github.com/appium/appium/issues/16184\n if (await adb.getApiLevel() >= 29) {\n await adb.scanMedia(remotePath);\n } else {\n await adb.shell([\n 'am', 'broadcast',\n '-a', ANDROID_MEDIA_RESCAN_INTENT,\n '-d', `file://${remotePath}`\n ]);\n }\n } catch (e) {\n log?.warn(`Ignoring an unexpected error upon media scanning of '${remotePath}': ${e.stderr || e.message}`);\n }\n}\n\n/**\n * A small helper, which escapes single quotes in paths,\n * so they are safe to be passed as arguments of shell commands\n *\n * @param {string} p The initial remote path\n * @returns {string} The escaped path value\n */\nfunction escapePath (p) {\n return p.replace(/'/g, `\\\\'`);\n}\n\n/**\n * Pulls a remote file from the device.\n * It is required, that a package has debugging flag enabled\n * in order to access its files.\n *\n * @param {string} remotePath The full path to the remote file\n * or a specially formatted path, which points to an item inside app bundle\n * @returns {string} Base64 encoded content of the pulled file\n * @throws {Error} If the pull operation failed\n */\ncommands.pullFile = async function pullFile (remotePath) {\n if (remotePath.endsWith('/')) {\n throw new errors.InvalidArgumentError(`It is expected that remote path points to a file and not to a folder. ` +\n `'${remotePath}' is given instead`);\n }\n let tmpDestination = null;\n if (remotePath.startsWith(CONTAINER_PATH_MARKER)) {\n const [packageId, pathInContainer] = parseContainerPath(remotePath);\n this.log.debug(`Parsed package identifier '${packageId}' from '${remotePath}'. Will get the data from '${pathInContainer}'`);\n tmpDestination = `/data/local/tmp/${path.posix.basename(pathInContainer)}`;\n try {\n await this.adb.shell(['run-as', packageId, `chmod 777 '${escapePath(pathInContainer)}'`]);\n await this.adb.shell([\n 'run-as', packageId,\n `cp -f '${escapePath(pathInContainer)}' '${escapePath(tmpDestination)}'`\n ]);\n } catch (e) {\n this.log.errorAndThrow(`Cannot access the container of '${packageId}' application. ` +\n `Is the application installed and has 'debuggable' build option set to true? ` +\n `Original error: ${e.message}`);\n }\n }\n const localFile = await tempDir.path({prefix: 'appium', suffix: '.tmp'});\n try {\n await this.adb.pull(tmpDestination || remotePath, localFile);\n return (await util.toInMemoryBase64(localFile)).toString();\n } finally {\n if (await fs.exists(localFile)) {\n await fs.unlink(localFile);\n }\n if (tmpDestination) {\n await this.adb.shell(['rm', '-f', tmpDestination]);\n }\n }\n};\n\n/**\n * @typedef {Object} PullFileOptions\n * @property {string} remotePath The full path to the remote file\n * or a specially formatted path, which points to an item inside an app bundle,\n * for example `@my.app.id/my/path`. It is mandatory for the app bundle to have\n * debugging enabled in order to use the latter remotePath format.\n */\n\n/**\n * Pulls a remote file from the device.\n *\n * @param {PullFileOptions} opts\n * @returns {string} The same as `pullFile`\n */\ncommands.mobilePullFile = async function mobilePullFile (opts = {}) {\n const { remotePath } = requireArgs('remotePath', opts);\n return await this.pullFile(remotePath);\n};\n\n/**\n * Pushes the given data to a file on the remote device\n * It is required, that a package has debugging flag enabled\n * in order to access its files.\n * After a file is pushed it gets automatically scanned for possible\n * media occurrences. If the scan succeeds then the file is added to the\n * media library.\n *\n * @param {string} remotePath The full path to the remote file or\n * a file inside a package bundle\n * @param {string} base64Data Base64 encoded data to be written to the\n * remote file. The remote file will be silently overridden if it already exists.\n * @throws {Error} If there was an error while pushing the data\n */\ncommands.pushFile = async function pushFile (remotePath, base64Data) {\n if (remotePath.endsWith('/')) {\n throw new errors.InvalidArgumentError(\n `It is expected that remote path points to a file and not to a folder. ` +\n `'${remotePath}' is given instead`\n );\n }\n const localFile = await tempDir.path({prefix: 'appium', suffix: '.tmp'});\n if (_.isArray(base64Data)) {\n // some clients (ahem) java, send a byte array encoding utf8 characters\n // instead of a string, which would be infinitely better!\n base64Data = Buffer.from(base64Data).toString('utf8');\n }\n const content = Buffer.from(base64Data, 'base64');\n let tmpDestination = null;\n try {\n await fs.writeFile(localFile, content.toString('binary'), 'binary');\n if (remotePath.startsWith(CONTAINER_PATH_MARKER)) {\n const [packageId, pathInContainer] = parseContainerPath(remotePath);\n this.log.debug(`Parsed package identifier '${packageId}' from '${remotePath}'. ` +\n `Will put the data into '${pathInContainer}'`);\n tmpDestination = `/data/local/tmp/${path.posix.basename(pathInContainer)}`;\n try {\n await this.adb.shell(\n ['run-as', packageId, `mkdir -p '${escapePath(path.posix.dirname(pathInContainer))}'`]\n );\n await this.adb.shell(['run-as', packageId, `touch '${escapePath(pathInContainer)}'`]);\n await this.adb.shell(['run-as', packageId, `chmod 777 '${escapePath(pathInContainer)}'`]);\n await this.adb.push(localFile, tmpDestination);\n await this.adb.shell([\n 'run-as', packageId,\n `cp -f '${escapePath(tmpDestination)}' '${escapePath(pathInContainer)}'`\n ]);\n } catch (e) {\n this.log.errorAndThrow(`Cannot access the container of '${packageId}' application. ` +\n `Is the application installed and has 'debuggable' build option set to true? ` +\n `Original error: ${e.message}`);\n }\n } else {\n // adb push creates folders and overwrites existing files.\n await this.adb.push(localFile, remotePath);\n\n // if we have pushed a file, it might be a media file, so ensure that\n // apps know about it\n await scanMedia(this.adb, remotePath, this.log);\n }\n } finally {\n if (await fs.exists(localFile)) {\n await fs.unlink(localFile);\n }\n if (tmpDestination) {\n await this.adb.shell(['rm', '-f', tmpDestination]);\n }\n }\n};\n\n/**\n * @typedef {Object} PushFileOptions\n * @property {string} remotePath The full path to the remote file\n * or a specially formatted path, which points to an item inside an app bundle,\n * for example `@my.app.id/my/path`. It is mandatory for the app bundle to have\n * debugging enabled in order to use the latter remotePath format.\n * @property {string} payload Base64-encoded content of the file to be pushed.\n */\n\n/**\n * Pushes the given data to a file on the remote device.\n *\n * @param {PushFileOptions} opts\n */\ncommands.mobilePushFile = async function mobilePushFile (opts = {}) {\n const { remotePath, payload } = requireArgs(['remotePath', 'payload'], opts);\n return await this.pushFile(remotePath, payload);\n};\n\n/**\n * Pulls the whole folder from the remote device\n *\n * @param {string} remotePath The full path to a folder on the\n * remote device or a folder inside an application bundle\n * @returns {string} Base64-encoded and zipped content of the folder\n * @throws {Error} If there was a failure while getting the folder content\n */\ncommands.pullFolder = async function pullFolder (remotePath) {\n const tmpRoot = await tempDir.openDir();\n try {\n await this.adb.pull(remotePath, tmpRoot);\n return (await zip.toInMemoryZip(tmpRoot, {\n encodeToBase64: true,\n })).toString();\n } finally {\n await fs.rimraf(tmpRoot);\n }\n};\n\n/**\n * @typedef {Object} PullFolderOptions\n * @property {string} remotePath The full path to the remote folder.\n */\n\n/**\n * Pulls the whole folder from the device under test.\n *\n * @param {PullFolderOptions} opts\n * @returns {string} The same as `pullFolder`\n */\ncommands.mobilePullFolder = async function mobilePullFolder (opts = {}) {\n const { remotePath } = requireArgs('remotePath', opts);\n return await this.pullFolder(remotePath);\n};\n\n/**\n * Deletes the given folder or file from the remote device\n *\n * @param {ADB} adb\n * @param {string} remotePath The full path to the remote folder\n * or file (folder names must end with a single slash)\n * @throws {Error} If the provided remote path is invalid or\n * the package content cannot be accessed\n * @returns {boolean} `true` if the remote item has been successfully deleted.\n * If the remote path is valid, but the remote path does not exist\n * this function return `false`.\n */\nasync function deleteFileOrFolder (adb, remotePath) {\n const performRemoteFsCheck = async (p, op, runAs = null) => {\n const passFlag = '__PASS__';\n const checkCmd = `[ -${op} '${escapePath(p)}' ] && echo ${passFlag}`;\n const fullCmd = runAs ? `run-as ${runAs} ${checkCmd}` : checkCmd;\n try {\n return _.includes(await adb.shell([fullCmd]), passFlag);\n } catch (ign) {\n return false;\n }\n };\n const isFile = async (p, runAs = null) => await performRemoteFsCheck(p, 'f', runAs);\n const isDir = async (p, runAs = null) => await performRemoteFsCheck(p, 'd', runAs);\n const isPresent = async (p, runAs = null) => await performRemoteFsCheck(p, 'e', runAs);\n\n let dstPath = remotePath;\n let pkgId = null;\n if (remotePath.startsWith(CONTAINER_PATH_MARKER)) {\n const [packageId, pathInContainer] = parseContainerPath(remotePath);\n this.log.debug(`Parsed package identifier '${packageId}' from '${remotePath}'`);\n dstPath = pathInContainer;\n pkgId = packageId;\n }\n\n if (pkgId) {\n try {\n await adb.shell(['run-as', pkgId, 'ls']);\n } catch (e) {\n this.log.errorAndThrow(`Cannot access the container of '${pkgId}' application. ` +\n `Is the application installed and has 'debuggable' build option set to true? ` +\n `Original error: ${e.message}`);\n }\n }\n\n if (!await isPresent(dstPath, pkgId)) {\n this.log.info(`The item at '${dstPath}' does not exist. Perhaps, already deleted?`);\n return false;\n }\n\n const expectsFile = !remotePath.endsWith('/');\n if (expectsFile && !await isFile(dstPath, pkgId)) {\n this.log.errorAndThrow(`The item at '${dstPath}' is not a file`);\n } else if (!expectsFile && !await isDir(dstPath, pkgId)) {\n this.log.errorAndThrow(`The item at '${dstPath}' is not a folder`);\n }\n\n if (pkgId) {\n await adb.shell(\n ['run-as', pkgId, `rm -f${expectsFile ? '' : 'r'} '${escapePath(dstPath)}'`]);\n } else {\n await adb.shell(['rm', `-f${expectsFile ? '' : 'r'}`, dstPath]);\n }\n if (await isPresent(dstPath, pkgId)) {\n this.log.errorAndThrow(`The item at '${dstPath}' still exists after being deleted. ` +\n `Is it writable?`);\n }\n return true;\n}\n\n/**\n * @typedef {Object} DeleteFileOpts\n * @property {!string} remotePath The full path to the remote file\n * or a file inside an application bundle (for example `@my.app.id/path/in/bundle`)\n */\n\n/**\n * Deletes a file on the remote device\n *\n * @param {DeleteFileOpts} opts\n * @returns {boolean} `true` if the remote file has been successfully deleted.\n * If the path to a remote file is valid, but the file itself does not exist\n * then `false` is returned.\n * @throws {Error} If the argument is invalid or there was an error while\n * deleting the file\n */\ncommands.mobileDeleteFile = async function mobileDeleteFile (opts = {}) {\n const {remotePath} = opts;\n if (!remotePath) {\n throw new errors.InvalidArgumentError(`The 'remotePath' argument is mandatory`);\n }\n if (remotePath.endsWith('/')) {\n throw new errors.InvalidArgumentError(\n `It is expected that remote path points to a folder and not to a file. ` +\n `'${remotePath}' is given instead`\n );\n }\n return await deleteFileOrFolder(this.adb, remotePath);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;AACD,CAZD;;eAeeF,Q"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"find.js","names":["helpers","extensions","doFindElementOrEls","params","bootstrap","sendAction","findElOrEls","strategy","selector","mult","context","Error","multiple","element","doFind","err","isErrorType","errors","ProxyRequestError","getActualError","NoSuchElementError","_","isEmpty","implicitWaitForCondition","message","match","Object","assign"],"sources":["../../../lib/commands/find.js"],"sourcesContent":["import _ from 'lodash';\nimport { errors, isErrorType } from 'appium/driver';\n\n\nlet helpers = {}, extensions = {};\n\n/**\n * Reason for isolating doFindElementOrEls from findElOrEls is for reusing findElOrEls\n * across android-drivers (like appium-uiautomator2-driver) to avoid code duplication.\n * Other android-drivers (like appium-uiautomator2-driver) need to override doFindElementOrEls\n * to facilitate findElOrEls.\n */\nhelpers.doFindElementOrEls = async function doFindElementOrEls (params) {\n return await this.bootstrap.sendAction('find', params);\n};\n\n// stategy: locator strategy\n// selector: the actual selector for finding an element\n// mult: multiple elements or just one?\n// context: finding an element from the root context? or starting from another element\nhelpers.findElOrEls = async function findElOrEls (strategy, selector, mult, context = '') {\n if (!selector) {\n throw new Error('Must provide a selector when finding elements');\n }\n\n let params = {\n strategy,\n selector,\n context,\n multiple: mult\n };\n\n let element;\n let doFind = async () => {\n try {\n element = await this.doFindElementOrEls(params);\n } catch (err) {\n\n // if the error that comes back is from a proxied request, we need to\n // unwrap it to its actual protocol error first\n if (isErrorType(err, errors.ProxyRequestError)) {\n err = err.getActualError(); // eslint-disable-line no-ex-assign\n }\n\n // now we have to inspect the error to determine if it is a no such\n // element error, based on the shape of the error object from\n // appium/driver\n if (isErrorType(err, errors.NoSuchElementError)) {\n // we are fine with this, just indicate a retry\n return false;\n }\n throw err;\n }\n\n // we want to return false if we want to potentially try again\n return !_.isEmpty(element);\n };\n\n try {\n await this.implicitWaitForCondition(doFind);\n } catch (err) {\n if (err.message && err.message.match(/Condition unmet/)) {\n // only get here if we are looking for multiple elements\n // condition was not met setting res to empty array\n element = [];\n } else {\n throw err;\n }\n }\n\n if (mult) {\n return element;\n }\n if (_.isEmpty(element)) {\n throw new errors.NoSuchElementError();\n }\n return element;\n};\n\nObject.assign(extensions, helpers);\nexport { helpers };\nexport default extensions;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AAGA,IAAIA,OAAO,GAAG,EAAd;AAAA,IAAkBC,UAAU,GAAG,EAA/B;;;AAQAD,OAAO,CAACE,kBAAR,GAA6B,eAAeA,kBAAf,CAAmCC,MAAnC,EAA2C;EACtE,OAAO,MAAM,KAAKC,SAAL,CAAeC,UAAf,CAA0B,MAA1B,EAAkCF,MAAlC,CAAb;AACD,CAFD;;AAQAH,OAAO,CAACM,WAAR,GAAsB,eAAeA,WAAf,CAA4BC,QAA5B,EAAsCC,QAAtC,EAAgDC,IAAhD,EAAsDC,OAAO,GAAG,EAAhE,EAAoE;EACxF,IAAI,CAACF,QAAL,EAAe;IACb,MAAM,IAAIG,KAAJ,CAAU,+CAAV,CAAN;EACD;;EAED,IAAIR,MAAM,GAAG;IACXI,QADW;IAEXC,QAFW;IAGXE,OAHW;IAIXE,QAAQ,EAAEH;EAJC,CAAb;EAOA,IAAII,OAAJ;;EACA,IAAIC,MAAM,GAAG,YAAY;IACvB,IAAI;MACFD,OAAO,GAAG,MAAM,KAAKX,kBAAL,CAAwBC,MAAxB,CAAhB;IACD,CAFD,CAEE,OAAOY,GAAP,EAAY;MAIZ,IAAI,IAAAC,mBAAA,EAAYD,GAAZ,EAAiBE,cAAA,CAAOC,iBAAxB,CAAJ,EAAgD;QAC9CH,GAAG,GAAGA,GAAG,CAACI,cAAJ,EAAN;MACD;;MAKD,IAAI,IAAAH,mBAAA,EAAYD,GAAZ,EAAiBE,cAAA,CAAOG,kBAAxB,CAAJ,EAAiD;QAE/C,OAAO,KAAP;MACD;;MACD,MAAML,GAAN;IACD;;IAGD,OAAO,CAACM,eAAA,CAAEC,OAAF,CAAUT,OAAV,CAAR;EACD,CAvBD;;EAyBA,IAAI;IACF,MAAM,KAAKU,wBAAL,CAA8BT,MAA9B,CAAN;EACD,CAFD,CAEE,OAAOC,GAAP,EAAY;IACZ,IAAIA,GAAG,CAACS,OAAJ,IAAeT,GAAG,CAACS,OAAJ,CAAYC,KAAZ,CAAkB,iBAAlB,CAAnB,EAAyD;MAGvDZ,OAAO,GAAG,EAAV;IACD,CAJD,MAIO;MACL,MAAME,GAAN;IACD;EACF;;EAED,IAAIN,IAAJ,EAAU;IACR,OAAOI,OAAP;EACD;;EACD,IAAIQ,eAAA,CAAEC,OAAF,CAAUT,OAAV,CAAJ,EAAwB;IACtB,MAAM,IAAII,cAAA,CAAOG,kBAAX,EAAN;EACD;;EACD,OAAOP,OAAP;AACD,CAzDD;;AA2DAa,MAAM,CAACC,MAAP,CAAc1B,UAAd,EAA0BD,OAA1B;eAEeC,U"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"general.js","names":["MOMENT_FORMAT_ISO8601","commands","helpers","extensions","keys","_","isArray","join","params","text","replace","opts","unicodeKeyboard","doSendKeys","bootstrap","sendAction","getDeviceTime","format","log","debug","deviceTimestamp","adb","shell","trim","parsedTimestamp","moment","utc","isValid","warn","utcOffset","_tzm","mobileGetDeviceTime","getPageSource","back","isKeyboardShown","isSoftKeyboardPresent","hideKeyboard","openSettingsActivity","setting","appPackage","appActivity","getFocusedPackageAndActivity","waitForNotActivity","getWindowSize","getWindowRect","width","height","x","y","getCurrentActivity","getCurrentPackage","background","seconds","goToHome","sleepMs","thresholdMs","intervalMs","min","parseInt","progressCb","elapsedMs","progress","waitSecs","toFixed","progressPct","longSleep","args","_cachedActivityArgs","activateApp","ign","appWaitPackage","appWaitActivity","split","includes","pkg","activity","action","intentAction","category","intentCategory","flags","intentFlags","waitPkg","waitActivity","waitForLaunch","appWaitForLaunch","waitDuration","appWaitDuration","optionalIntentArguments","stopApp","user","userProfile","util","filterObject","JSON","stringify","startApp","getStrings","language","getDeviceLanguage","info","preprocessStringsMap","mapping","result","key","value","toPairs","isString","apkStrings","androidHelpers","pushStrings","launchApp","initAUT","startAUT","startActivity","dontStopAppOnReset","hasValue","reset","resetApp","Object","assign","fastReset","setContext","isChromeSession","startChromeSession","setUrl","uri","startUri","closeApp","forceStop","getDisplayDensity","out","val","isNaN","errorAndThrow","mobilePerformEditorAction","errors","InvalidArgumentError","performEditorAction","PERMISSION_ACTION","GRANT","REVOKE","mobileChangePermissions","permissions","actionFunc","toLower","permission","grantPermission","revokePermission","values","PERMISSIONS_TYPE","DENIED","GRANTED","REQUESTED","mobileGetPermissions","type","getReqPermissions","getGrantedPermissions","getDeniedPermissions","mobileGetNotifications","getNotifications","mobileListSms","getSmsList","mobileUnlock","strategy","timeoutMs","unlock","unlockKey","unlockType","unlockStrategy","unlockSuccessTimeout"],"sources":["../../../lib/commands/general.js"],"sourcesContent":["import _ from 'lodash';\nimport androidHelpers from '../android-helpers';\nimport { util } from 'appium/support';\nimport moment from 'moment';\nimport { longSleep } from 'asyncbox';\nimport { errors } from 'appium/driver';\n\nconst MOMENT_FORMAT_ISO8601 = 'YYYY-MM-DDTHH:mm:ssZ';\n\nlet commands = {}, helpers = {}, extensions = {};\n\ncommands.keys = async function keys (keys) {\n // Protocol sends an array; rethink approach\n keys = _.isArray(keys) ? keys.join('') : keys;\n let params = {\n text: keys,\n replace: false\n };\n if (this.opts.unicodeKeyboard) {\n params.unicodeKeyboard = true;\n }\n await this.doSendKeys(params);\n};\n\ncommands.doSendKeys = async function doSendKeys (params) {\n return await this.bootstrap.sendAction('setText', params);\n};\n\n/**\n * Retrieves the current device's timestamp.\n *\n * @param {string} format - The set of format specifiers. Read\n * https://momentjs.com/docs/ to get the full list of supported\n * datetime format specifiers. The default format is\n * `YYYY-MM-DDTHH:mm:ssZ`, which complies to ISO-8601\n * @return {string} Formatted datetime string or the raw command output if formatting fails\n */\ncommands.getDeviceTime = async function getDeviceTime (format = MOMENT_FORMAT_ISO8601) {\n this.log.debug('Attempting to capture android device date and time. ' +\n `The format specifier is '${format}'`);\n const deviceTimestamp = (await this.adb.shell(['date', '+%Y-%m-%dT%T%z'])).trim();\n this.log.debug(`Got device timestamp: ${deviceTimestamp}`);\n const parsedTimestamp = moment.utc(deviceTimestamp, 'YYYY-MM-DDTHH:mm:ssZZ');\n if (!parsedTimestamp.isValid()) {\n this.log.warn('Cannot parse the returned timestamp. Returning as is');\n return deviceTimestamp;\n }\n return parsedTimestamp.utcOffset(parsedTimestamp._tzm || 0).format(format);\n};\n\n/**\n * @typedef {Object} DeviceTimeOptions\n * @property {string} format [YYYY-MM-DDTHH:mm:ssZ] - See getDeviceTime#format\n */\n\n/**\n * Retrieves the current device time\n *\n * @param {DeviceTimeOptions} opts\n * @return {string} Formatted datetime string or the raw command output if formatting fails\n */\ncommands.mobileGetDeviceTime = async function mobileGetDeviceTime (opts = {}) {\n return await this.getDeviceTime(opts.format);\n};\n\ncommands.getPageSource = async function getPageSource () {\n return await this.bootstrap.sendAction('source');\n};\n\ncommands.back = async function back () {\n return await this.bootstrap.sendAction('pressBack');\n};\n\ncommands.isKeyboardShown = async function isKeyboardShown () {\n const {isKeyboardShown} = await this.adb.isSoftKeyboardPresent();\n return isKeyboardShown;\n};\n\ncommands.hideKeyboard = async function hideKeyboard () {\n return await this.adb.hideKeyboard();\n};\n\ncommands.openSettingsActivity = async function openSettingsActivity (setting) {\n let {appPackage, appActivity} = await this.adb.getFocusedPackageAndActivity();\n await this.adb.shell(['am', 'start', '-a', `android.settings.${setting}`]);\n await this.adb.waitForNotActivity(appPackage, appActivity, 5000);\n};\n\ncommands.getWindowSize = async function getWindowSize () {\n return await this.bootstrap.sendAction('getDeviceSize');\n};\n\n// For W3C\ncommands.getWindowRect = async function getWindowRect () {\n const { width, height } = await this.getWindowSize();\n return {\n width,\n height,\n x: 0,\n y: 0\n };\n};\n\ncommands.getCurrentActivity = async function getCurrentActivity () {\n return (await this.adb.getFocusedPackageAndActivity()).appActivity;\n};\n\ncommands.getCurrentPackage = async function getCurrentPackage () {\n return (await this.adb.getFocusedPackageAndActivity()).appPackage;\n};\n\ncommands.background = async function background (seconds) {\n if (seconds < 0) {\n // if user passes in a negative seconds value, interpret that as the instruction\n // to not bring the app back at all\n await this.adb.goToHome();\n return true;\n }\n let {appPackage, appActivity} = await this.adb.getFocusedPackageAndActivity();\n await this.adb.goToHome();\n\n // people can wait for a long time, so to be safe let's use the longSleep function and log\n // progress periodically.\n const sleepMs = seconds * 1000;\n const thresholdMs = 30 * 1000; // use the spin-wait for anything over this threshold\n // for our spin interval, use 1% of the total wait time, but nothing bigger than 30s\n const intervalMs = _.min([30 * 1000, parseInt(sleepMs / 100, 10)]);\n const progressCb = ({elapsedMs, progress}) => {\n const waitSecs = (elapsedMs / 1000).toFixed(0);\n const progressPct = (progress * 100).toFixed(2);\n this.log.debug(`Waited ${waitSecs}s so far (${progressPct}%)`);\n };\n await longSleep(sleepMs, {thresholdMs, intervalMs, progressCb});\n\n let args;\n if (this._cachedActivityArgs && this._cachedActivityArgs[`${appPackage}/${appActivity}`]) {\n // the activity was started with `startActivity`, so use those args to restart\n args = this._cachedActivityArgs[`${appPackage}/${appActivity}`];\n } else {\n try {\n this.log.debug(`Activating app '${appPackage}' in order to restore it`);\n await this.activateApp(appPackage);\n return true;\n } catch (ign) {}\n args = ((appPackage === this.opts.appPackage && appActivity === this.opts.appActivity) ||\n (appPackage === this.opts.appWaitPackage && (this.opts.appWaitActivity || '').split(',').includes(appActivity)))\n ? {// the activity is the original session activity, so use the original args\n pkg: this.opts.appPackage,\n activity: this.opts.appActivity,\n action: this.opts.intentAction,\n category: this.opts.intentCategory,\n flags: this.opts.intentFlags,\n waitPkg: this.opts.appWaitPackage,\n waitActivity: this.opts.appWaitActivity,\n waitForLaunch: this.opts.appWaitForLaunch,\n waitDuration: this.opts.appWaitDuration,\n optionalIntentArguments: this.opts.optionalIntentArguments,\n stopApp: false,\n user: this.opts.userProfile}\n : {// the activity was started some other way, so use defaults\n pkg: appPackage,\n activity: appActivity,\n waitPkg: appPackage,\n waitActivity: appActivity,\n stopApp: false};\n }\n args = await util.filterObject(args);\n this.log.debug(`Bringing application back to foreground with arguments: ${JSON.stringify(args)}`);\n return await this.adb.startApp(args);\n};\n\ncommands.getStrings = async function getStrings (language) {\n if (!language) {\n language = await this.adb.getDeviceLanguage();\n this.log.info(`No language specified, returning strings for: ${language}`);\n }\n\n // Clients require the resulting mapping to have both keys\n // and values of type string\n const preprocessStringsMap = (mapping) => {\n const result = {};\n for (const [key, value] of _.toPairs(mapping)) {\n result[key] = _.isString(value) ? value : JSON.stringify(value);\n }\n return result;\n };\n\n if (this.apkStrings[language]) {\n // Return cached strings\n return preprocessStringsMap(this.apkStrings[language]);\n }\n\n this.apkStrings[language] = await androidHelpers.pushStrings(language, this.adb, this.opts);\n if (this.bootstrap) {\n // TODO: This is mutating the current language, but it's how appium currently works\n await this.bootstrap.sendAction('updateStrings');\n }\n\n return preprocessStringsMap(this.apkStrings[language]);\n};\n\ncommands.launchApp = async function launchApp () {\n await this.initAUT();\n await this.startAUT();\n};\n\ncommands.startActivity = async function startActivity (appPackage, appActivity,\n appWaitPackage, appWaitActivity, intentAction, intentCategory, intentFlags,\n optionalIntentArguments, dontStopAppOnReset) {\n this.log.debug(`Starting package '${appPackage}' and activity '${appActivity}'`);\n\n // dontStopAppOnReset is both an argument here, and a desired capability\n // if the argument is set, use it, otherwise use the cap\n if (!util.hasValue(dontStopAppOnReset)) {\n dontStopAppOnReset = !!this.opts.dontStopAppOnReset;\n }\n\n let args = {\n pkg: appPackage,\n activity: appActivity,\n waitPkg: appWaitPackage || appPackage,\n waitActivity: appWaitActivity || appActivity,\n action: intentAction,\n category: intentCategory,\n flags: intentFlags,\n optionalIntentArguments,\n stopApp: !dontStopAppOnReset\n };\n this._cachedActivityArgs = this._cachedActivityArgs || {};\n this._cachedActivityArgs[`${args.waitPkg}/${args.waitActivity}`] = args;\n await this.adb.startApp(args);\n};\n\ncommands.reset = async function reset () {\n await androidHelpers.resetApp(this.adb, Object.assign({}, this.opts, {fastReset: true}));\n // reset context since we don't know what kind on context we will end up after app launch.\n await this.setContext();\n return await this.isChromeSession ? this.startChromeSession() : this.startAUT();\n};\n\ncommands.startAUT = async function startAUT () {\n await this.adb.startApp({\n pkg: this.opts.appPackage,\n activity: this.opts.appActivity,\n action: this.opts.intentAction,\n category: this.opts.intentCategory,\n flags: this.opts.intentFlags,\n waitPkg: this.opts.appWaitPackage,\n waitActivity: this.opts.appWaitActivity,\n waitForLaunch: this.opts.appWaitForLaunch,\n waitDuration: this.opts.appWaitDuration,\n optionalIntentArguments: this.opts.optionalIntentArguments,\n stopApp: !this.opts.dontStopAppOnReset,\n user: this.opts.userProfile,\n });\n};\n\n// we override setUrl to take an android URI which can be used for deep-linking\n// inside an app, similar to starting an intent\ncommands.setUrl = async function setUrl (uri) {\n await this.adb.startUri(uri, this.opts.appPackage);\n};\n\n// closing app using force stop\ncommands.closeApp = async function closeApp () {\n await this.adb.forceStop(this.opts.appPackage);\n // reset context since we don't know what kind on context we will end up after app launch.\n await this.setContext();\n};\n\ncommands.getDisplayDensity = async function getDisplayDensity () {\n // first try the property for devices\n let out = await this.adb.shell(['getprop', 'ro.sf.lcd_density']);\n if (out) {\n let val = parseInt(out, 10);\n // if the value is NaN, try getting the emulator property\n if (!isNaN(val)) {\n return val;\n }\n this.log.debug(`Parsed density value was NaN: \"${out}\"`);\n }\n // fallback to trying property for emulators\n out = await this.adb.shell(['getprop', 'qemu.sf.lcd_density']);\n if (out) {\n let val = parseInt(out, 10);\n if (!isNaN(val)) {\n return val;\n }\n this.log.debug(`Parsed density value was NaN: \"${out}\"`);\n }\n // couldn't get anything, so error out\n this.log.errorAndThrow('Failed to get display density property.');\n};\n\ncommands.mobilePerformEditorAction = async function mobilePerformEditorAction (opts = {}) {\n const {action} = opts;\n if (!util.hasValue(action)) {\n throw new errors.InvalidArgumentError(`'action' argument is required`);\n }\n\n await this.adb.performEditorAction(action);\n};\n\nconst PERMISSION_ACTION = {\n GRANT: 'grant',\n REVOKE: 'revoke',\n};\n\n/**\n * @typedef {Object} ChangePermissionsOptions\n * @property {!string|Array<string>} permissions - The full name of the permission to be changed\n * or a list of permissions. Mandatory argument.\n * @property {string} appPackage [this.opts.appPackage] - The application package to set change\n * permissions on. Defaults to the package name under test.\n * @property {string} action [grant] - One of `PERMISSION_ACTION` values\n */\n\n/**\n * Changes package permissions in runtime.\n *\n * @param {?ChangePermissionsOptions} opts - Available options mapping.\n * @throws {Error} if there was a failure while changing permissions\n */\ncommands.mobileChangePermissions = async function mobileChangePermissions (opts = {}) {\n const {\n permissions,\n appPackage = this.opts.appPackage,\n action = PERMISSION_ACTION.GRANT,\n } = opts;\n if (!util.hasValue(permissions)) {\n throw new errors.InvalidArgumentError(`'permissions' argument is required`);\n }\n\n let actionFunc;\n switch (_.toLower(action)) {\n case PERMISSION_ACTION.GRANT:\n actionFunc = (appPackage, permission) => this.adb.grantPermission(appPackage, permission);\n break;\n case PERMISSION_ACTION.REVOKE:\n actionFunc = (appPackage, permission) => this.adb.revokePermission(appPackage, permission);\n break;\n default:\n throw new errors.InvalidArgumentError(`Unknown action '${action}'. ` +\n `Only ${JSON.stringify(_.values(PERMISSION_ACTION))} actions are supported`);\n }\n for (const permission of (_.isArray(permissions) ? permissions : [permissions])) {\n await actionFunc(appPackage, permission);\n }\n};\n\nconst PERMISSIONS_TYPE = {\n DENIED: 'denied',\n GRANTED: 'granted',\n REQUESTED: 'requested',\n};\n\n/**\n * @typedef {Object} GetPermissionsOptions\n * @property {string} type [requested] - One of possible permission types to get.\n * Can be any of `PERMISSIONS_TYPE` values.\n * @property {string} appPackage [this.opts.appPackage] - The application package to set change\n * permissions on. Defaults to the package name under test.\n */\n\n/**\n * Gets runtime permissions list for the given application package.\n *\n * @param {GetPermissionsOptions} opts - Available options mapping.\n * @returns {Array<string>} The list of retrieved permissions for the given type\n * (can also be empty).\n * @throws {Error} if there was an error while getting permissions.\n */\ncommands.mobileGetPermissions = async function mobileGetPermissions (opts = {}) {\n const {\n type = PERMISSIONS_TYPE.REQUESTED,\n appPackage = this.opts.appPackage,\n } = opts;\n\n let actionFunc;\n switch (_.toLower(type)) {\n case PERMISSIONS_TYPE.REQUESTED:\n actionFunc = (appPackage) => this.adb.getReqPermissions(appPackage);\n break;\n case PERMISSIONS_TYPE.GRANTED:\n actionFunc = (appPackage) => this.adb.getGrantedPermissions(appPackage);\n break;\n case PERMISSIONS_TYPE.DENIED:\n actionFunc = (appPackage) => this.adb.getDeniedPermissions(appPackage);\n break;\n default:\n throw new errors.InvalidArgumentError(`Unknown permissions type '${type}'. ` +\n `Only ${JSON.stringify(_.values(PERMISSIONS_TYPE))} types are supported`);\n }\n return await actionFunc(appPackage);\n};\n\n/**\n * Retrieves the list of recent system notifications.\n *\n * @returns {Object} See the documentation on `adb.getNotifications` for\n * more details\n */\ncommands.mobileGetNotifications = async function mobileGetNotifications () {\n return await this.adb.getNotifications();\n};\n\n/**\n * @typedef {Object} SmsListOptions\n * @property {number} max [100] - The maximum count of recent SMS messages\n * to retrieve\n */\n\n/**\n * Retrieves the list of recent SMS messages with their properties.\n *\n * @param {SmsListOptions} opts\n * @returns {Object} See the documentation on `adb.getSmsList` for\n * more details\n */\ncommands.mobileListSms = async function mobileListSms (opts = {}) {\n return await this.adb.getSmsList(opts);\n};\n\n/**\n * @typedef {Object} UnlockOptions\n * @property {string} key The unlock key. The value of this key depends\n * on the actual unlock type and could be a pin/password/pattern value or\n * a biometric finger id.\n * @property {string} type The unlock type. The following unlock types\n * are supported: `pin`, `pinWithKeyEvent`, `password`, `pattern` and `fingerprint`.\n * @property {?string} strategy Either 'locksettings' (default) or 'uiautomator'.\n * Setting it to 'uiautomator' will enforce the driver to avoid using special\n * ADB shortcuts in order to speed up the unlock procedure.\n * @property {?number} timeoutMs [2000] The maximum time in milliseconds\n * to wait until the screen gets unlocked\n */\n\n/**\n * Unlocks the device if it is locked. Noop if the device's screen is not locked.\n *\n * @param {?UnlockOptions} opts\n * @throws {Error} if unlock operation fails or the provided\n * arguments are not valid\n */\ncommands.mobileUnlock = async function mobileUnlock (opts = {}) {\n const { key, type, strategy, timeoutMs } = opts;\n await androidHelpers.unlock(this, this.adb, {\n unlockKey: key,\n unlockType: type,\n unlockStrategy: strategy,\n unlockSuccessTimeout: timeoutMs,\n });\n};\n\nObject.assign(extensions, commands, helpers);\nexport { commands, helpers };\nexport default extensions;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEA,MAAMA,qBAAqB,GAAG,sBAA9B;AAEA,IAAIC,QAAQ,GAAG,EAAf;AAAA,IAAmBC,OAAO,GAAG,EAA7B;AAAA,IAAiCC,UAAU,GAAG,EAA9C;;;;AAEAF,QAAQ,CAACG,IAAT,GAAgB,eAAeA,IAAf,CAAqBA,IAArB,EAA2B;EAEzCA,IAAI,GAAGC,eAAA,CAAEC,OAAF,CAAUF,IAAV,IAAkBA,IAAI,CAACG,IAAL,CAAU,EAAV,CAAlB,GAAkCH,IAAzC;EACA,IAAII,MAAM,GAAG;IACXC,IAAI,EAAEL,IADK;IAEXM,OAAO,EAAE;EAFE,CAAb;;EAIA,IAAI,KAAKC,IAAL,CAAUC,eAAd,EAA+B;IAC7BJ,MAAM,CAACI,eAAP,GAAyB,IAAzB;EACD;;EACD,MAAM,KAAKC,UAAL,CAAgBL,MAAhB,CAAN;AACD,CAXD;;AAaAP,QAAQ,CAACY,UAAT,GAAsB,eAAeA,UAAf,CAA2BL,MAA3B,EAAmC;EACvD,OAAO,MAAM,KAAKM,SAAL,CAAeC,UAAf,CAA0B,SAA1B,EAAqCP,MAArC,CAAb;AACD,CAFD;;AAaAP,QAAQ,CAACe,aAAT,GAAyB,eAAeA,aAAf,CAA8BC,MAAM,GAAGjB,qBAAvC,EAA8D;EACrF,KAAKkB,GAAL,CAASC,KAAT,CAAe,yDACZ,4BAA2BF,MAAO,GADrC;EAEA,MAAMG,eAAe,GAAG,CAAC,MAAM,KAAKC,GAAL,CAASC,KAAT,CAAe,CAAC,MAAD,EAAS,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Af,CAAsB,IAAtB,EAA4B,KAAKjJ,GAAjC,EAAsC;IAC1CkJ,SAAS,EAAE/D,GAD+B;IAE1CgE,UAAU,EAAEb,IAF8B;IAG1Cc,cAAc,EAAEL,QAH0B;IAI1CM,oBAAoB,EAAEL;EAJoB,CAAtC,CAAN;AAMD,CARD;;AAUA9C,MAAM,CAACC,MAAP,CAAcrH,UAAd,EAA0BF,QAA1B,EAAoCC,OAApC;eAEeC,U"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ime.js","names":["commands","helpers","extensions","isIMEActivated","availableIMEEngines","log","debug","engines","adb","availableIMEs","JSON","stringify","getActiveIMEEngine","defaultIME","activateIMEEngine","imeId","availableEngines","indexOf","errors","IMENotAvailableError","enableIME","setIME","deactivateIMEEngine","currentEngine","disableIME","Object","assign"],"sources":["../../../lib/commands/ime.js"],"sourcesContent":["import { errors } from 'appium/driver';\n\nlet commands = {}, helpers = {}, extensions = {};\n\ncommands.isIMEActivated = async function isIMEActivated () { // eslint-disable-line require-await\n // IME is always activated on Android devices\n return true;\n};\n\ncommands.availableIMEEngines = async function availableIMEEngines () {\n this.log.debug('Retrieving available IMEs');\n let engines = await this.adb.availableIMEs();\n this.log.debug(`Engines: ${JSON.stringify(engines)}`);\n return engines;\n};\n\ncommands.getActiveIMEEngine = async function getActiveIMEEngine () {\n this.log.debug('Retrieving current default IME');\n return await this.adb.defaultIME();\n};\n\ncommands.activateIMEEngine = async function activateIMEEngine (imeId) {\n this.log.debug(`Attempting to activate IME ${imeId}`);\n let availableEngines = await this.adb.availableIMEs();\n if (availableEngines.indexOf(imeId) === -1) {\n this.log.debug('IME not found, failing');\n throw new errors.IMENotAvailableError();\n }\n this.log.debug('Found installed IME, attempting to activate');\n await this.adb.enableIME(imeId);\n await this.adb.setIME(imeId);\n};\n\ncommands.deactivateIMEEngine = async function deactivateIMEEngine () {\n let currentEngine = await this.getActiveIMEEngine();\n this.log.debug(`Attempting to deactivate ${currentEngine}`);\n await this.adb.disableIME(currentEngine);\n};\n\nObject.assign(extensions, commands, helpers);\nexport { commands, helpers };\nexport default extensions;\n"],"mappings":";;;;;;;;;AAAA;;AAEA,IAAIA,QAAQ,GAAG,EAAf;AAAA,IAAmBC,OAAO,GAAG,EAA7B;AAAA,IAAiCC,UAAU,GAAG,EAA9C;;;;AAEAF,QAAQ,CAACG,cAAT,GAA0B,eAAeA,cAAf,GAAiC;EAEzD,OAAO,IAAP;AACD,CAHD;;AAKAH,QAAQ,CAACI,mBAAT,GAA+B,eAAeA,mBAAf,GAAsC;EACnE,KAAKC,GAAL,CAASC,KAAT,CAAe,2BAAf;EACA,IAAIC,OAAO,GAAG,MAAM,KAAKC,GAAL,CAASC,aAAT,EAApB;EACA,KAAKJ,GAAL,CAASC,KAAT,CAAgB,YAAWI,IAAI,CAACC,SAAL,CAAeJ,OAAf,CAAwB,EAAnD;EACA,OAAOA,OAAP;AACD,CALD;;AAOAP,QAAQ,CAACY,kBAAT,GAA8B,eAAeA,kBAAf,GAAqC;EACjE,KAAKP,GAAL,CAASC,KAAT,CAAe,gCAAf;EACA,OAAO,MAAM,KAAKE,GAAL,CAASK,UAAT,EAAb;AACD,CAHD;;AAKAb,QAAQ,CAACc,iBAAT,GAA6B,eAAeA,iBAAf,CAAkCC,KAAlC,EAAyC;EACpE,KAAKV,GAAL,CAASC,KAAT,CAAgB,8BAA6BS,KAAM,EAAnD;EACA,IAAIC,gBAAgB,GAAG,MAAM,KAAKR,GAAL,CAASC,aAAT,EAA7B;;EACA,IAAIO,gBAAgB,CAACC,OAAjB,CAAyBF,KAAzB,MAAoC,CAAC,CAAzC,EAA4C;IAC1C,KAAKV,GAAL,CAASC,KAAT,CAAe,wBAAf;IACA,MAAM,IAAIY,cAAA,CAAOC,oBAAX,EAAN;EACD;;EACD,KAAKd,GAAL,CAASC,KAAT,CAAe,6CAAf;EACA,MAAM,KAAKE,GAAL,CAASY,SAAT,CAAmBL,KAAnB,CAAN;EACA,MAAM,KAAKP,GAAL,CAASa,MAAT,CAAgBN,KAAhB,CAAN;AACD,CAVD;;AAYAf,QAAQ,CAACsB,mBAAT,GAA+B,eAAeA,mBAAf,GAAsC;EACnE,IAAIC,aAAa,GAAG,MAAM,KAAKX,kBAAL,EAA1B;EACA,KAAKP,GAAL,CAASC,KAAT,CAAgB,4BAA2BiB,aAAc,EAAzD;EACA,MAAM,KAAKf,GAAL,CAASgB,UAAT,CAAoBD,aAApB,CAAN;AACD,CAJD;;AAMAE,MAAM,CAACC,MAAP,CAAcxB,UAAd,EAA0BF,QAA1B,EAAoCC,OAApC;eAEeC,U"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["commands","Object","assign","findCmds","generalCmds","alertCmds","elementCmds","contextCmds","actionCmds","touchCmds","imeCmds","networkCmds","coverageCmds","recordscreenCmds","intentCmds","screenStreamCmds","performanceCmds","executeCmds","shellCmds","emuConsoleCmds","systemBarsCmds","appManagementCmds","fileActionsCmds","logCmds","mediaProjectionCmds"],"sources":["../../../lib/commands/index.js"],"sourcesContent":["import findCmds from './find';\nimport generalCmds from './general';\nimport alertCmds from './alert';\nimport elementCmds from './element';\nimport contextCmds from './context';\nimport actionCmds from './actions';\nimport touchCmds from './touch';\nimport imeCmds from './ime';\nimport networkCmds from './network';\nimport coverageCmds from './coverage';\nimport recordscreenCmds from './recordscreen';\nimport screenStreamCmds from './streamscreen';\nimport performanceCmds from './performance';\nimport executeCmds from './execute';\nimport shellCmds from './shell';\nimport emuConsoleCmds from './emu-console';\nimport fileActionsCmds from './file-actions';\nimport appManagementCmds from './app-management';\nimport intentCmds from './intent';\nimport systemBarsCmds from './system-bars';\nimport logCmds from './log';\nimport mediaProjectionCmds from './media-projection';\n\n\nlet commands = {};\nObject.assign(\n commands,\n findCmds,\n generalCmds,\n alertCmds,\n elementCmds,\n contextCmds,\n actionCmds,\n touchCmds,\n imeCmds,\n networkCmds,\n coverageCmds,\n recordscreenCmds,\n intentCmds,\n screenStreamCmds,\n performanceCmds,\n executeCmds,\n shellCmds,\n emuConsoleCmds,\n systemBarsCmds,\n appManagementCmds,\n fileActionsCmds,\n logCmds,\n mediaProjectionCmds,\n // add other command types here\n);\n\nexport { commands };\nexport default commands;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAGA,IAAIA,QAAQ,GAAG,EAAf;;AACAC,MAAM,CAACC,MAAP,CACEF,QADF,EAEEG,aAFF,EAGEC,gBAHF,EAIEC,cAJF,EAKEC,gBALF,EAMEC,gBANF,EAOEC,gBAPF,EAQEC,cARF,EASEC,YATF,EAUEC,gBAVF,EAWEC,iBAXF,EAYEC,qBAZF,EAaEC,eAbF,EAcEC,qBAdF,EAeEC,oBAfF,EAgBEC,gBAhBF,EAiBEC,cAjBF,EAkBEC,mBAlBF,EAmBEC,mBAnBF,EAoBEC,sBApBF,EAqBEC,oBArBF,EAsBEC,YAtBF,EAuBEC,wBAvBF;eA4BexB,Q"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"intent.js","names":["NO_VALUE_ARG_TYPE","SUPPORTED_EXTRA_TYPES","API_LEVEL_ANDROID_8","commands","parseIntentSpec","opts","intent","action","uri","mimeType","identifier","categories","component","extras","flags","resultArgs","push","_","isNil","isArray","flatMap","map","cName","package","errors","InvalidArgumentError","item","type","key","value","includes","isEmpty","isString","trim","JSON","stringify","isUndefined","mobileStartActivity","user","wait","stop","windowingMode","activityType","display","cmd","adb","getApiLevel","shell","mobileBroadcast","receiverPermission","allowBackgroundActivityStarts","mobileStartService","foreground","mobileStopService"],"sources":["../../../lib/commands/intent.js"],"sourcesContent":["import _ from 'lodash';\nimport { errors } from 'appium/driver';\n\nconst NO_VALUE_ARG_TYPE = 'sn';\nconst SUPPORTED_EXTRA_TYPES = [\n 's', NO_VALUE_ARG_TYPE, 'z', 'i', 'l', 'f', 'u', 'cn',\n 'ia', 'ial', 'la', 'lal', 'fa', 'fal', 'sa', 'sal',\n];\nconst API_LEVEL_ANDROID_8 = 26;\n\nconst commands = {};\n\nfunction parseIntentSpec (opts = {}) {\n const {\n intent,\n action,\n uri,\n mimeType,\n identifier,\n categories,\n component,\n extras,\n flags,\n } = opts;\n const resultArgs = [];\n if (intent) {\n resultArgs.push(intent);\n }\n if (action) {\n resultArgs.push('-a', action);\n }\n if (uri) {\n resultArgs.push('-d', uri);\n }\n if (mimeType) {\n resultArgs.push('-t', mimeType);\n }\n if (!_.isNil(identifier)) {\n resultArgs.push('-i', identifier);\n }\n if (categories) {\n if (_.isArray(categories)) {\n resultArgs.push(...(_.flatMap(categories.map((cName) => ['-c', cName]))));\n } else {\n resultArgs.push('-c', categories);\n }\n }\n if (component) {\n resultArgs.push('-n', component);\n }\n if (opts.package) {\n resultArgs.push('-p', opts.package);\n }\n if (extras) {\n if (!_.isArray(extras)) {\n throw new errors.InvalidArgumentError(`'extras' must be an array`);\n }\n for (const item of extras) {\n if (!_.isArray(item)) {\n throw new errors.InvalidArgumentError(`Extra argument '${item}' must be an array`);\n }\n const [type, key, value] = item;\n if (!_.includes(SUPPORTED_EXTRA_TYPES, type)) {\n throw new errors.InvalidArgumentError(\n `Extra argument type '${type}' is not known. ` +\n `Supported intent argument types are: ${SUPPORTED_EXTRA_TYPES}`\n );\n }\n if (_.isEmpty(key) || (_.isString(key) && _.trim(key) === '')) {\n throw new errors.InvalidArgumentError(\n `Extra argument's key in '${JSON.stringify(item)}' must be a valid string identifier`\n );\n }\n if (type === NO_VALUE_ARG_TYPE) {\n resultArgs.push(`--e${type}`, key);\n } else if (_.isUndefined(value)) {\n throw new errors.InvalidArgumentError(\n `Intent argument type '${type}' in '${JSON.stringify(item)}' requires a ` +\n `valid value to be provided`\n );\n } else {\n resultArgs.push(`--e${type}`, key, value);\n }\n }\n }\n if (flags) {\n resultArgs.push('-f', flags);\n }\n return resultArgs;\n}\n\n/**\n * @typedef {Object} StartActivityOptions\n * @property {?string|number} user ['current'] - The user ID for which the service is started.\n * The `current` user id is used by default\n * @property {?boolean} wait [false] - Set it to `true` if you want to block the method call\n * until the activity manager's process returns the control to the system.\n * @property {?boolean} stop [false] - Set it to `true` to force stop the target\n * app before starting the activity\n * @property {?number|string} windowingMode - The windowing mode to launch the activity into.\n * Check https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/WindowConfiguration.java\n * for more details on possible windowing modes (constants starting with `WINDOWING_MODE_`).\n * @property {?number|string} activityType - The activity type to launch the activity as.\n * Check https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/WindowConfiguration.java\n * for more details on possible activity types (constants starting with `ACTIVITY_TYPE_`).\n * @property {?number|string} display - The display identifier to launch the activity into.\n * @property {?string} intent - The name of the activity intent to start, for example\n * `com.some.package.name/.YourServiceSubClassName`\n * @property {?string} action - Action name\n * @property {?string} package - Package name\n * @property {?string} uri - Unified resource identifier\n * @property {?string} mimeType - Mime type\n * @property {?string} identifier - Optional identifier\n * @property {?string|Array<string>} categories - One or more category names\n * @property {?string} component - Component name\n * @property {Array<string|Array<string>>} extras - Optional intent arguments. Must be represented\n * as array of arrays, where each subarray item contains two or three string items:\n * value type, key name and the value itself.\n * Supported value types are:\n * - s: string. Value must be a valid string\n * - sn: null. Value is ignored for this type\n * - z: boolean. Value must be either `true` or `false`\n * - i: integer. Value must be a valid 4-byte integer number\n * - l: long. Value must be a valid 8-byte long number\n * - f: float: Value must be a valid float number\n * - u: uri. Value must be a valid uniform resource identifier string\n * - cn: component name. Value must be a valid component name string\n * - ia: Integer[]. Value must be a string of comma-separated integers\n * - ial: List<Integer>. Value must be a string of comma-separated integers\n * - la: Long[]. Value must be a string of comma-separated long numbers\n * - lal: List<Long>. Value must be a string of comma-separated long numbers\n * - fa: Float[]. Value must be a string of comma-separated float numbers\n * - fal: List<Float>. Value must be a string of comma-separated float numbers\n * - sa: String[]. Value must be comma-separated strings. To embed a comma into a string,\n * escape it using \"\\,\"\n * - sal: List<String>. Value must be comma-separated strings. To embed a comma into a string,\n * escape it using \"\\,\"\n * For example: [['s', 'varName1', 'My String1'], ['s', 'varName2', 'My String2'], ['ia', 'arrName', '1,2,3,4']]\n * @property {?string} flags - Intent startup-specific flags as a hexadecimal string.\n * See https://developer.android.com/reference/android/content/Intent.html\n * for the list of available flag values (constants starting with FLAG_ACTIVITY_).\n * Flag values could be merged using the logical 'or' operation.\n * For example, 0x10200000 is the combination of two flags:\n * 0x10000000 `FLAG_ACTIVITY_NEW_TASK` | 0x00200000 `FLAG_ACTIVITY_RESET_TASK_IF_NEEDED`\n */\n\n/**\n * Starts the given activity intent.\n *\n * @param {StartActivityOptions} opts\n * @returns {string} The command output\n * @throws {Error} If there was a failure while starting the activity\n * or required options are missing\n */\ncommands.mobileStartActivity = async function mobileStartActivity (opts = {}) {\n const {\n user,\n wait,\n stop,\n windowingMode,\n activityType,\n display,\n } = opts;\n const cmd = [\n 'am', (await this.adb.getApiLevel() < API_LEVEL_ANDROID_8) ? 'start' : 'start-activity',\n ];\n if (!_.isNil(user)) {\n cmd.push('--user', user);\n }\n if (wait) {\n cmd.push('-W');\n }\n if (stop) {\n cmd.push('-S');\n }\n if (!_.isNil(windowingMode)) {\n cmd.push('--windowingMode', windowingMode);\n }\n if (!_.isNil(activityType)) {\n cmd.push('--activityType', activityType);\n }\n if (!_.isNil(display)) {\n cmd.push('--display', display);\n }\n cmd.push(...(parseIntentSpec(opts)));\n return await this.adb.shell(cmd);\n};\n\n/**\n * @typedef {Object} BroadcastOptions\n * @property {?string|number} user ['all'] - The user ID for which the broadcast is sent.\n * The `current` alias assumes the current user ID.\n * @property {?string} receiverPermission - Require receiver to hold the given permission.\n * @property {?boolean} allowBackgroundActivityStarts [false] - Whether the receiver may\n * start activities even if in the background.\n * @property {?string} intent - The name of the intent to broadcast to, for example\n * `com.some.package.name/.YourServiceSubClassName`.\n * @property {?string} action - Action name\n * @property {?string} uri - Unified resource identifier\n * @property {?string} mimeType - Mime type\n * @property {?string} identifier - Optional identifier\n * @property {?string|Array<string>} categories - One or more category names\n * @property {?string} component - Component name\n * @property {?string} package - Package name\n * @property {Array<Array<string>>} extras - Optional intent arguments.\n * See above for the detailed description.\n * @property {?string} flags - Intent startup-specific flags as a hexadecimal string.\n * See above for the detailed description.\n */\n\n\n/**\n * Send a broadcast intent.\n *\n * @param {BroadcastOptions} opts\n * @returns {string} The command output\n * @throws {Error} If there was a failure while starting the activity\n * or required options are missing\n */\ncommands.mobileBroadcast = async function mobileBroadcast (opts = {}) {\n const {\n user,\n receiverPermission,\n allowBackgroundActivityStarts,\n } = opts;\n const cmd = ['am', 'broadcast'];\n if (!_.isNil(user)) {\n cmd.push('--user', user);\n }\n if (receiverPermission) {\n cmd.push('--receiver-permission', receiverPermission);\n }\n if (allowBackgroundActivityStarts) {\n cmd.push('--allow-background-activity-starts');\n }\n cmd.push(...(parseIntentSpec(opts)));\n return await this.adb.shell(cmd);\n};\n\n/**\n * @typedef {Object} StartServiceOptions\n * @property {?string|number} user ['current'] - The user ID for which the service is started.\n * The `current` user id is used by default\n * @property {?boolean} foreground [false] - Set it to `true` if your service must be\n * started as foreground service. This option is ignored if the API level of the\n * device under test is below 26 (Android 8).\n * @property {?string} intent - The name of the service intent to start, for example\n * `com.some.package.name/.YourServiceSubClassName`.\n * @property {?string} action - Action name\n * @property {?string} uri - Unified resource identifier\n * @property {?string} mimeType - Mime type\n * @property {?string} identifier - Optional identifier\n * @property {?string|Array<string>} categories - One or more category names\n * @property {?string} component - Component name\n * @property {?string} package - Package name\n * @property {Array<Array<string>>} extras - Optional intent arguments.\n * See above for the detailed description.\n * @property {?string} flags - Intent startup-specific flags as a hexadecimal string.\n * See above for the detailed description.\n */\n\n/**\n * Starts the given service intent.\n *\n * @param {StartServiceOptions} opts\n * @returns {string} The command output\n * @throws {Error} If there was a failure while starting the service\n * or required options are missing\n */\ncommands.mobileStartService = async function mobileStartService (opts = {}) {\n const {\n user,\n foreground,\n } = opts;\n const cmd = ['am'];\n if (await this.adb.getApiLevel() < API_LEVEL_ANDROID_8) {\n cmd.push('startservice');\n } else {\n cmd.push(foreground ? 'start-foreground-service' : 'start-service');\n }\n if (!_.isNil(user)) {\n cmd.push('--user', user);\n }\n cmd.push(...(parseIntentSpec(opts)));\n return await this.adb.shell(cmd);\n};\n\n/**\n * @typedef {Object} StopServiceOptions\n * @property {string|number} user ['current'] - The user ID for which the service is running.\n * The `current` user id is used by default\n * @property {?string} intent - The name of the service intent to stop, for example\n * `com.some.package.name/.YourServiceSubClassName`.\n * @property {?string} action - Action name\n * @property {?string} uri - Unified resource identifier\n * @property {?string} mimeType - Mime type\n * @property {?string} identifier - Optional identifier\n * @property {?string|Array<string>} categories - One or more category names\n * @property {?string} component - Component name\n * @property {?string} package - Package name\n * @property {Array<Array<string>>} extras - Optional intent arguments.\n * See above for the detailed description.\n * @property {?string} flags - See above for the detailed description.\n */\n\n/**\n * Stops the given service intent.\n *\n * @param {StopServiceOptions} opts\n * @returns {string} The command output\n * @throws {Error} If there was a failure while stopping the service\n * or required options are missing\n */\ncommands.mobileStopService = async function mobileStopService (opts = {}) {\n const {\n user,\n } = opts;\n const cmd = [\n 'am',\n (await this.adb.getApiLevel() < API_LEVEL_ANDROID_8) ? 'stopservice' : 'stop-service'\n ];\n if (!_.isNil(user)) {\n cmd.push('--user', user);\n }\n cmd.push(...(parseIntentSpec(opts)));\n return await this.adb.shell(cmd);\n};\n\n\nexport { commands };\nexport default commands;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AAEA,MAAMA,iBAAiB,GAAG,IAA1B;AACA,MAAMC,qBAAqB,GAAG,CAC5B,GAD4B,EACvBD,iBADuB,EACJ,GADI,EACC,GADD,EACM,GADN,EACW,GADX,EACgB,GADhB,EACqB,IADrB,EAE5B,IAF4B,EAEtB,KAFsB,EAEf,IAFe,EAET,KAFS,EAEF,IAFE,EAEI,KAFJ,EAEW,IAFX,EAEiB,KAFjB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R,CAAL,EAAoB;IAClBM,GAAG,CAAC5B,IAAJ,CAAS,QAAT,EAAmBsB,IAAnB;EACD;;EACDM,GAAG,CAAC5B,IAAJ,CAAS,GAAIZ,eAAe,CAACC,IAAD,CAA5B;EACA,OAAO,MAAM,KAAKwC,GAAL,CAASE,KAAT,CAAeH,GAAf,CAAb;AACD,CAhBD;;AA4CAzC,QAAQ,CAACkD,iBAAT,GAA6B,eAAeA,iBAAf,CAAkChD,IAAI,GAAG,EAAzC,EAA6C;EACxE,MAAM;IACJiC;EADI,IAEFjC,IAFJ;EAGA,MAAMuC,GAAG,GAAG,CACV,IADU,EAET,OAAM,KAAKC,GAAL,CAASC,WAAT,EAAN,IAA+B5C,mBAAhC,GAAuD,aAAvD,GAAuE,cAF7D,CAAZ;;EAIA,IAAI,CAACe,eAAA,CAAEC,KAAF,CAAQoB,IAAR,CAAL,EAAoB;IAClBM,GAAG,CAAC5B,IAAJ,CAAS,QAAT,EAAmBsB,IAAnB;EACD;;EACDM,GAAG,CAAC5B,IAAJ,CAAS,GAAIZ,eAAe,CAACC,IAAD,CAA5B;EACA,OAAO,MAAM,KAAKwC,GAAL,CAASE,KAAT,CAAeH,GAAf,CAAb;AACD,CAbD;;eAiBezC,Q"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"log.js","names":["GET_SERVER_LOGS_FEATURE","commands","helpers","extensions","WEBSOCKET_ENDPOINT","sessionId","DEFAULT_WS_PATHNAME_PREFIX","toLogRecord","timestamp","level","message","supportedLogTypes","logcat","description","getter","self","adb","getLogcatLogs","bugreport","output","Date","now","split","os","EOL","map","x","server","ensureFeatureEnabled","log","unwrap","record","_","isEmpty","prefix","mobileStartLogsBroadcast","pathname","getWebSocketHandlers","debug","info","wss","WebSocket","Server","noServer","on","ws","req","remoteIp","headers","connection","remoteAddress","_logcatWebsocketListener","logRecord","readyState","OPEN","send","setLogcatListener","code","reason","removeLogcatListener","ign","closeMsg","toString","addWebSocketHandler","mobileStopLogsBroadcast","removeWebSocketHandler","getLogTypes","nativeLogTypes","BaseDriver","prototype","call","isWebContext","webLogTypes","chromedriver","jwproxy","command","getLog","logType","keys","includes","type","Object","assign"],"sources":["../../../lib/commands/log.js"],"sourcesContent":["import log from '../logger';\nimport os from 'os';\nimport _ from 'lodash';\nimport WebSocket from 'ws';\nimport { DEFAULT_WS_PATHNAME_PREFIX, BaseDriver } from 'appium/driver';\n\nconst GET_SERVER_LOGS_FEATURE = 'get_server_logs';\n\nlet commands = {}, helpers = {}, extensions = {};\n\nconst WEBSOCKET_ENDPOINT = (sessionId) => `${DEFAULT_WS_PATHNAME_PREFIX}/session/${sessionId}/appium/device/logcat`;\n\n// https://github.com/SeleniumHQ/selenium/blob/0d425676b3c9df261dd641917f867d4d5ce7774d/java/client/src/org/openqa/selenium/logging/LogEntry.java\nfunction toLogRecord (timestamp, level, message) {\n return {\n timestamp,\n level,\n message,\n };\n}\n\nextensions.supportedLogTypes = {\n logcat: {\n description: 'Logs for Android applications on real device and emulators via ADB',\n getter: async (self) => await self.adb.getLogcatLogs(),\n },\n bugreport: {\n description: `'adb bugreport' output for advanced issues diagnostic`,\n getter: async (self) => {\n const output = await self.adb.bugreport();\n const timestamp = Date.now();\n return output.split(os.EOL)\n .map((x) => toLogRecord(timestamp, 'ALL', x));\n },\n },\n server: {\n description: 'Appium server logs',\n getter: (self) => {\n self.ensureFeatureEnabled(GET_SERVER_LOGS_FEATURE);\n const timestamp = Date.now();\n return log.unwrap().record\n .map((x) => toLogRecord(timestamp,\n 'ALL',\n _.isEmpty(x.prefix) ? x.message : `[${x.prefix}] ${x.message}`)\n );\n },\n },\n};\n\n/**\n * Starts Android logcat broadcast websocket on the same host and port\n * where Appium server is running at `/ws/session/:sessionId:/appium/logcat` endpoint. The method\n * will return immediately if the web socket is already listening.\n *\n * Each connected websocket listener will receive logcat log lines\n * as soon as they are visible to Appium.\n */\ncommands.mobileStartLogsBroadcast = async function mobileStartLogsBroadcast () {\n const pathname = WEBSOCKET_ENDPOINT(this.sessionId);\n if (!_.isEmpty(await this.server.getWebSocketHandlers(pathname))) {\n log.debug(`The logcat broadcasting web socket server is already listening at ${pathname}`);\n return;\n }\n\n log.info(`Assigning logcat broadcasting web socket server to ${pathname}`);\n // https://github.com/websockets/ws/blob/master/doc/ws.md\n const wss = new WebSocket.Server({\n noServer: true,\n });\n wss.on('connection', (ws, req) => {\n if (req) {\n const remoteIp = _.isEmpty(req.headers['x-forwarded-for'])\n ? req.connection?.remoteAddress\n : req.headers['x-forwarded-for'];\n log.debug(`Established a new logcat listener web socket connection from ${remoteIp}`);\n } else {\n log.debug('Established a new logcat listener web socket connection');\n }\n\n if (_.isEmpty(this._logcatWebsocketListener)) {\n this._logcatWebsocketListener = (logRecord) => {\n if (ws?.readyState === WebSocket.OPEN) {\n ws.send(logRecord.message);\n }\n };\n }\n this.adb.setLogcatListener(this._logcatWebsocketListener);\n\n ws.on('close', (code, reason) => {\n if (!_.isEmpty(this._logcatWebsocketListener)) {\n try {\n this.adb.removeLogcatListener(this._logcatWebsocketListener);\n } catch (ign) {}\n this._logcatWebsocketListener = null;\n }\n\n let closeMsg = 'Logcat listener web socket is closed.';\n if (!_.isEmpty(code)) {\n closeMsg += ` Code: ${code}.`;\n }\n if (!_.isEmpty(reason)) {\n closeMsg += ` Reason: ${reason.toString()}.`;\n }\n log.debug(closeMsg);\n });\n });\n await this.server.addWebSocketHandler(pathname, wss);\n};\n\n/**\n * Stops the previously started logcat broadcasting wesocket server.\n * This method will return immediately if no server is running.\n */\ncommands.mobileStopLogsBroadcast = async function mobileStopLogsBroadcast () {\n const pathname = WEBSOCKET_ENDPOINT(this.sessionId);\n if (_.isEmpty(await this.server.getWebSocketHandlers(pathname))) {\n return;\n }\n\n log.debug('Stopping the logcat broadcasting web socket server');\n await this.server.removeWebSocketHandler(pathname);\n};\n\ncommands.getLogTypes = async function getLogTypes () {\n const nativeLogTypes = await BaseDriver.prototype.getLogTypes.call(this);\n if (this.isWebContext()) {\n const webLogTypes = await this.chromedriver.jwproxy.command('/log/types', 'GET');\n return [...nativeLogTypes, ...webLogTypes];\n }\n return nativeLogTypes;\n};\n\ncommands.getLog = async function getLog (logType) {\n if (this.isWebContext() && !_.keys(this.supportedLogTypes).includes(logType)) {\n return await this.chromedriver.jwproxy.command('/log', 'POST', {type: logType});\n }\n return await BaseDriver.prototype.getLog.call(this, logType);\n};\n\nObject.assign(extensions, commands, helpers);\nexport { commands, helpers };\nexport default extensions;\n"],"mappings":";;;;;;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AAEA,MAAMA,uBAAuB,GAAG,iBAAhC;AAEA,IAAIC,QAAQ,GAAG,EAAf;AAAA,IAAmBC,OAAO,GAAG,EAA7B;AAAA,IAAiCC,UAAU,GAAG,EAA9C;;;;AAEA,MAAMC,kBAAkB,GAAIC,SAAD,IAAgB,GAAEC,kCAA2B,YAAWD,SAAU,uBAA7F;;AAGA,SAASE,WAAT,CAAsBC,SAAtB,EAAiCC,KAAjC,EAAwCC,OAAxC,EAAiD;EAC/C,OAAO;IACLF,SADK;IAELC,KAFK;IAGLC;EAHK,CAAP;AAKD;;AAEDP,UAAU,CAACQ,iBAAX,GAA+B;EAC7BC,MAAM,EAAE;IACNC,WAAW,EAAE,oEADP;IAENC,MAAM,EAAE,MAAOC,IAAP,IAAgB,MAAMA,IAAI,CAACC,GAAL,CAASC,aAAT;EAFxB,CADqB;EAK7BC,SAAS,EAAE;IACTL,WAAW,EAAG,uDADL;IAETC,MAAM,EAAE,MAAOC,IAAP,IAAgB;MACtB,MAAMI,MAAM,GAAG,MAAMJ,IAAI,CAACC,GAAL,CAASE,SAAT,EAArB;MACA,MAAMV,SAAS,GAAGY,IAAI,CAACC,GAAL,EAAlB;MACA,OAAOF,MAAM,CAACG,KAAP,CAAaC,WAAA,CAAGC,GAAhB,EACJC,GADI,CACCC,CAAD,IAAOnB,WAAW,CAACC,SAAD,EAAY,KAAZ,EAAmBkB,CAAnB,CADlB,CAAP;IAED;EAPQ,C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