import Element, { ElementOrElementId } from './Element'; import Server from './Server'; import findDisplayed from './lib/findDisplayed'; import { Task, CancellablePromise, partial } from '@theintern/common'; import statusCodes from './lib/statusCodes'; import Locator, { toW3cLocator, Strategy } from './lib/Locator'; import { forCommand as utilForCommand, manualFindByLinkText, sleep, toExecuteString, } from './lib/util'; import waitForDeleted from './lib/waitForDeleted'; import { Capabilities, Geolocation, LogEntry, WebDriverCookie, WebDriverResponse, } from './interfaces'; /** * A Session represents a connection to a remote environment that can be driven * programmatically. */ export default class Session extends Locator< CancellablePromise, CancellablePromise, CancellablePromise > { private _sessionId: string; private _server: Server; private _capabilities: Capabilities; private _closedWindows: any = null; // TODO: Timeouts are held so that we can fiddle with the implicit wait // timeout to add efficient `waitFor` and `waitForDeleted` convenience // methods. Technically only the implicit timeout is necessary. private _timeouts: { [key: string]: CancellablePromise } = {}; private _movedToElement = false; private _lastMousePosition: any = null; private _lastAltitude: any = null; private _nextRequest: CancellablePromise | undefined; /** * A Session represents a connection to a remote environment that can be * driven programmatically. * * @param sessionId The ID of the session, as provided by the remote. * @param server The server that the session belongs to. * @param capabilities A map of bugs and features that the remote * environment exposes. */ constructor(sessionId: string, server: Server, capabilities: Capabilities) { super(); this._sessionId = sessionId; this._server = server; this._capabilities = capabilities; this._closedWindows = {}; this._timeouts = { script: Task.resolve(0), implicit: Task.resolve(0), 'page load': Task.resolve(Infinity), }; } /** * Information about the available features and bugs in the remote * environment. */ get capabilities() { return this._capabilities; } /** * The current session ID. */ get sessionId() { return this._sessionId; } /** * The Server that the session runs on. */ get server() { return this._server; } /** * Delegates the HTTP request for a method to the underlying * [[Server.Server]] object. */ private _delegateToServer( method: 'post' | 'get' | 'delete', path: string, requestData: any, pathParts?: string[] ): CancellablePromise { path = 'session/' + this._sessionId + (path ? '/' + path : ''); if ( method === 'post' && !requestData && this.capabilities.brokenEmptyPost ) { requestData = {}; } let cancelled = false; return new Task( (resolve) => { // The promise is cleared from `_nextRequest` once it has been // resolved in order to avoid infinitely long chains of promises // retaining values that are not used any more let thisRequest: CancellablePromise | undefined; const clearNextRequest = () => { if (this._nextRequest === thisRequest) { this._nextRequest = undefined; } }; const runRequest = () => { // `runRequest` is normally called once the previous request is // finished. If this request is cancelled before the previous // request is finished, then it should simply never run. (This // Task will have been rejected already by the cancellation.) if (cancelled) { clearNextRequest(); return; } const response = this._server[method]( path, requestData, pathParts ).then((response) => response.value); // safePromise is simply a promise based on the response that // is guaranteed to resolve -- it is only used for promise // chain management const safePromise = response.catch((_error) => {}); safePromise.then(clearNextRequest); // The value of the response always needs to be taken directly // from the server call rather than from the chained // `_nextRequest` promise, since if an undefined value is // returned by the server call and that value is returned // through `finally(runRequest)`, the *previous* Task’s // resolved value will be used as the resolved value, which is // wrong resolve(response); return safePromise; }; // At least ChromeDriver 2.19 will just hard close connections if // parallel requests are made to the server, so any request sent to // the server for a given session must be serialised. Other servers // like Selendroid have been known to have issues with parallel // requests as well, so serialisation is applied universally, even // though it has negative performance implications if (this._nextRequest) { thisRequest = this._nextRequest = this._nextRequest.finally(runRequest); } else { thisRequest = this._nextRequest = runRequest(); } }, () => (cancelled = true) ); } serverGet(path: string, requestData?: any, pathParts?: string[]) { return this._delegateToServer('get', path, requestData, pathParts); } serverPost(path: string, requestData?: any, pathParts?: string[]) { return this._delegateToServer('post', path, requestData, pathParts); } serverDelete(path: string, requestData?: any, pathParts?: string[]) { return this._delegateToServer('delete', path, requestData, pathParts); } /** * Gets the current value of a timeout for the session. * * @param type The type of timeout to retrieve. One of 'script', * 'implicit', or 'page load'. * @returns The timeout, in milliseconds. */ getTimeout(type: Timeout): CancellablePromise { if (this.capabilities.supportsGetTimeouts) { return this.serverGet('timeouts').then((timeouts) => type === 'page load' ? timeouts.pageLoad : timeouts[type] ); } else { return this._timeouts[type]; } } /** * Sets the value of a timeout for the session. * * @param type The type of timeout to set. One of 'script', 'implicit', or * 'page load'. * * @param ms The length of time to use for the timeout, in milliseconds. A * value of 0 will cause operations to time out immediately. */ setTimeout(type: Timeout, ms: number): CancellablePromise { // Infinity cannot be serialised by JSON if (ms === Infinity) { // It seems that at least ChromeDriver 2.10 has a limit here that // is near the 32-bit signed integer limit, and IEDriverServer // 2.42.2 has an even lower limit; 2.33 hours should be infinite // enough for testing ms = Math.pow(2, 23) - 1; } // If the target doesn't support a timeout of 0, use 1. if (this.capabilities.brokenZeroTimeout && ms === 0) { ms = 1; } // Set both JSONWireProtocol and WebDriver properties in the data object let data = this.capabilities.usesWebDriverTimeouts ? { [type === 'page load' ? 'pageLoad' : type]: ms, } : { type, ms, }; const promise = this.serverPost('timeouts', data).catch((error) => { // Appium as of April 2014 complains that `timeouts` is // unsupported, so try the more specific endpoints if they exist if (error.name === 'UnknownCommand') { if (type === 'script') { return this.serverPost('timeouts/async_script', { ms: ms, }); } else if (type === 'implicit') { return this.serverPost('timeouts/implicit_wait', { ms: ms, }); } } else if ( !this.capabilities.usesWebDriverTimeouts && // At least Chrome 60+ (/Missing 'type' parameter/.test(error.message) || // At least Safari 10+ /Unknown timeout type/.test(error.message) || // IE11 /Invalid timeout type specified/.test(error.message)) ) { this.capabilities.usesWebDriverTimeouts = true; return this.setTimeout(type, ms); } throw error; }); this._timeouts[type] = promise.then(() => ms).catch(() => 0); return promise; } /** * Gets the identifier for the window that is currently focused. * * @returns A window handle identifier that can be used with other window * handling functions. */ getCurrentWindowHandle(): CancellablePromise { const endpoint = this.capabilities.usesWebDriverWindowHandleCommands ? 'window' : 'window_handle'; return this.serverGet(endpoint) .then((handle) => { if ( this.capabilities.brokenDeleteWindow && this._closedWindows[handle] ) { const error: SessionError = new Error(); error.status = '23'; error.name = statusCodes[error.status][0]; error.message = statusCodes[error.status][1]; throw error; } return handle; }) .catch((error) => { if ( // At least Edge 44.17763 returns an UnknownError when it doesn't // support /window_handle, whereas most drivers return an // UnknownCommand error. /^Unknown/.test(error.name) && !this.capabilities.usesWebDriverWindowHandleCommands ) { this.capabilities.usesWebDriverWindowHandleCommands = true; return this.getCurrentWindowHandle(); } throw error; }); } /** * Gets a list of identifiers for all currently open windows. */ getAllWindowHandles(): CancellablePromise { const endpoint = this.capabilities.usesWebDriverWindowHandleCommands ? 'window/handles' : 'window_handles'; return this.serverGet(endpoint) .then((handles: string[]) => { if (this.capabilities.brokenDeleteWindow) { return handles.filter((handle) => { return !this._closedWindows[handle]; }); } return handles; }) .catch((error) => { if ( error.name === 'UnknownCommand' && !this.capabilities.usesWebDriverWindowHandleCommands ) { this.capabilities.usesWebDriverWindowHandleCommands = true; return this.getAllWindowHandles(); } throw error; }); } /** * Gets the URL that is loaded in the focused window/frame. */ getCurrentUrl() { return this.serverGet('url'); } /** * Navigates the focused window/frame to a new URL. */ get(url: string) { this._movedToElement = false; if (this.capabilities.brokenMouseEvents) { this._lastMousePosition = { x: 0, y: 0 }; } return this.serverPost('url', { url: url }); } /** * Navigates the focused window/frame forward one page using the browser’s * navigation history. */ goForward() { // TODO: SPEC: Seems like this and `back` should return the newly // navigated URL. return this.serverPost('forward'); } /** * Navigates the focused window/frame back one page using the browser’s * navigation history. */ goBack() { // TODO: SPEC: Seems like this and `back` should return the newly // navigated URL. return this.serverPost('back'); } /** * Reloads the current browser window/frame. */ refresh() { if (this.capabilities.brokenRefresh) { return this.execute('location.reload();'); } return this.serverPost('refresh'); } /** * Executes JavaScript code within the focused window/frame. The code * should return a value synchronously. * * See [[Session.Session.executeAsync]] to execute code that returns values * asynchronously. * * @param script The code to execute. This function will always be * converted to a string, sent to the remote environment, and reassembled * as a new anonymous function on the remote end. This means that you * cannot access any variables through closure. If your code needs to get * data from variables on the local end, they should be passed using * `args`. * * @param args An array of arguments that will be passed to the executed * code. Only values that can be serialised to JSON, plus * [[Element.Element]] objects, can be specified as arguments. * * @returns The value returned by the remote code. Only values that can be * serialised to JSON, plus DOM elements, can be returned. */ execute(script: Function | string, args?: any[]): CancellablePromise { // At least FirefoxDriver 2.40.0 will throw a confusing // NullPointerException if args is not an array; provide a friendlier // error message to users that accidentally pass a non-array if (typeof args !== 'undefined' && !Array.isArray(args)) { throw new Error('Arguments passed to execute must be an array'); } const endpoint = this.capabilities.usesWebDriverExecuteSync ? 'execute/sync' : 'execute'; let result = this.serverPost(endpoint, { script: toExecuteString(script), args: args || [], }) .then((value) => convertToElements(this, value), fixExecuteError) .catch((error) => { if ( error.detail.error === 'unknown command' && !this.capabilities.usesWebDriverExecuteSync ) { this.capabilities.usesWebDriverExecuteSync = true; return this.execute(script, args); } throw error; }); if (this.capabilities.brokenExecuteUndefinedReturn) { result = result.then((value) => (value == null ? null : value)); } return result; } /** * Executes JavaScript code within the focused window/frame. The code must * invoke the provided callback in order to signal that it has completed * execution. * * See [[Session.Session.execute]] to execute code that returns values * synchronously. * * See [[Session.Session.setExecuteAsyncTimeout]] to set the time until an * asynchronous script is considered timed out. * * @param script The code to execute. This function will always be * converted to a string, sent to the remote environment, and reassembled * as a new anonymous function on the remote end. This means that you * cannot access any variables through closure. If your code needs to get * data from variables on the local end, they should be passed using * `args`. * * @param args An array of arguments that will be passed to the executed * code. Only values that can be serialised to JSON, plus * [[Element.Element]] objects, can be specified as arguments. In addition * to these arguments, a callback function will always be passed as the * final argument to the function specified in `script`. This callback * function must be invoked in order to signal that execution has * completed. The return value of the execution, if any, should be passed * to this callback function. * * @returns The value returned by the remote code. Only values that can be * serialised to JSON, plus DOM elements, can be returned. */ executeAsync( script: Function | string, args?: any[] ): CancellablePromise { // At least FirefoxDriver 2.40.0 will throw a confusing // NullPointerException if args is not an array; provide a friendlier // error message to users that accidentally pass a non-array if (typeof args !== 'undefined' && !Array.isArray(args)) { throw new Error('Arguments passed to executeAsync must be an array'); } const endpoint = this.capabilities.usesWebDriverExecuteAsync ? 'execute/async' : 'execute_async'; return this.serverPost(endpoint, { script: toExecuteString(script), args: args || [], }) .then(partial(convertToElements, this), fixExecuteError) .catch((error) => { if ( error.detail.error === 'unknown command' && !this.capabilities.usesWebDriverExecuteAsync ) { this.capabilities.usesWebDriverExecuteAsync = true; return this.executeAsync(script, args); } // At least Safari 11, Jan 2019 will throw Timeout errors rather than // ScriptTimeout errors for script timeouts if (error.name === 'Timeout') { error.name = 'ScriptTimeout'; } throw error; }); } /** * Gets a screenshot of the focused window and returns it in PNG format. * * @returns A buffer containing a PNG image. */ takeScreenshot() { return this.serverGet('screenshot').then((data) => Buffer.from(data, 'base64') ); } /** * Gets a list of input method editor engines available to the remote * environment. As of April 2014, no known remote environments support IME * functions. */ getAvailableImeEngines() { return this.serverGet('ime/available_engines'); } /** * Gets the currently active input method editor for the remote environment. * As of April 2014, no known remote environments support IME functions. */ getActiveImeEngine() { return this.serverGet('ime/active_engine'); } /** * Returns whether or not an input method editor is currently active in the * remote environment. As of April 2014, no known remote environments * support IME functions. */ isImeActivated() { return this.serverGet('ime/activated'); } /** * Deactivates any active input method editor in the remote environment. * As of April 2014, no known remote environments support IME functions. */ deactivateIme() { return this.serverPost('ime/deactivate'); } /** * Activates an input method editor in the remote environment. * As of April 2014, no known remote environments support IME functions. * * @param engine The type of IME to activate. */ activateIme(engine: string) { return this.serverPost('ime/activate', { engine: engine }); } /** * Switches the currently focused frame to a new frame. * * @param id The frame to switch to. In most environments, a number or * string value corresponds to a key in the `window.frames` object of the * currently active frame. If `null`, the topmost (default) frame will be * used. If an Element is provided, it must correspond to a `` or * `