Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.js 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.patchDebug = exports.findByWhich = exports.uniq = exports.sort = exports.getPages = exports.getStaleElementError = exports.transformExecuteResult = exports.transformExecuteArgs = exports.sanitizeError = exports.findElements = exports.findElement = exports.getPrototype = exports.validate = void 0;
  7. const fs_1 = __importDefault(require("fs"));
  8. const path_1 = __importDefault(require("path"));
  9. const child_process_1 = require("child_process");
  10. const logger_1 = __importDefault(require("@wdio/logger"));
  11. const utils_1 = require("@wdio/utils");
  12. const protocols_1 = require("@wdio/protocols");
  13. const cleanUpSerializationSelector_1 = __importDefault(require("./scripts/cleanUpSerializationSelector"));
  14. const constants_1 = require("./constants");
  15. const log = logger_1.default('devtools');
  16. exports.validate = function (command, parameters, variables, ref, args) {
  17. const commandParams = [...variables.map((v) => Object.assign(v, {
  18. required: true,
  19. type: 'string'
  20. })), ...parameters];
  21. const commandUsage = `${command}(${commandParams.map((p) => p.name).join(', ')})`;
  22. const moreInfo = `\n\nFor more info see ${ref}\n`;
  23. const body = {};
  24. const minAllowedParams = commandParams.filter((param) => param.required).length;
  25. if (args.length < minAllowedParams || args.length > commandParams.length) {
  26. const parameterDescription = commandParams.length
  27. ? `\n\nProperty Description:\n${commandParams.map((p) => ` "${p.name}" (${p.type}): ${p.description}`).join('\n')}`
  28. : '';
  29. throw new Error(`Wrong parameters applied for ${command}\n` +
  30. `Usage: ${commandUsage}` +
  31. parameterDescription +
  32. moreInfo);
  33. }
  34. for (const [i, arg] of Object.entries(args)) {
  35. const commandParam = commandParams[parseInt(i, 10)];
  36. if (!utils_1.isValidParameter(arg, commandParam.type)) {
  37. if (typeof arg === 'undefined' && !commandParam.required) {
  38. continue;
  39. }
  40. throw new Error(`Malformed type for "${commandParam.name}" parameter of command ${command}\n` +
  41. `Expected: ${commandParam.type}\n` +
  42. `Actual: ${utils_1.getArgumentType(arg)}` +
  43. moreInfo);
  44. }
  45. body[commandParams[parseInt(i, 10)].name] = arg;
  46. }
  47. log.info('COMMAND', utils_1.commandCallStructure(command, args));
  48. return body;
  49. };
  50. function getPrototype(commandWrapper) {
  51. const prototype = {};
  52. for (const [endpoint, methods] of Object.entries(protocols_1.WebDriverProtocol)) {
  53. for (const [method, commandData] of Object.entries(methods)) {
  54. prototype[commandData.command] = { value: commandWrapper(method, endpoint, commandData) };
  55. }
  56. }
  57. return prototype;
  58. }
  59. exports.getPrototype = getPrototype;
  60. async function findElement(context, using, value) {
  61. const implicitTimeout = this.timeouts.get('implicit');
  62. const waitForFn = using === 'xpath' ? context.waitForXPath : context.waitForSelector;
  63. if (implicitTimeout && waitForFn) {
  64. await waitForFn.call(context, value, { timeout: implicitTimeout });
  65. }
  66. let element;
  67. try {
  68. element = using === 'xpath'
  69. ? (await context.$x(value))[0]
  70. : await context.$(value);
  71. }
  72. catch (err) {
  73. if (!err.message.includes('failed to find element')) {
  74. throw err;
  75. }
  76. }
  77. if (!element) {
  78. return new Error(`Element with selector "${value}" not found`);
  79. }
  80. const elementId = this.elementStore.set(element);
  81. return { [constants_1.ELEMENT_KEY]: elementId };
  82. }
  83. exports.findElement = findElement;
  84. async function findElements(context, using, value) {
  85. const implicitTimeout = this.timeouts.get('implicit');
  86. const waitForFn = using === 'xpath' ? context.waitForXPath : context.waitForSelector;
  87. if (implicitTimeout && waitForFn) {
  88. await waitForFn.call(context, value, { timeout: implicitTimeout });
  89. }
  90. const elements = using === 'xpath'
  91. ? await context.$x(value)
  92. : await context.$$(value);
  93. if (elements.length === 0) {
  94. return [];
  95. }
  96. return elements.map((element) => ({
  97. [constants_1.ELEMENT_KEY]: this.elementStore.set(element)
  98. }));
  99. }
  100. exports.findElements = findElements;
  101. function sanitizeError(err) {
  102. let errorMessage = err.message;
  103. if (err.message.includes('Node is detached from document')) {
  104. err.name = constants_1.ERROR_MESSAGES.staleElement.name;
  105. errorMessage = constants_1.ERROR_MESSAGES.staleElement.message;
  106. }
  107. const stack = err.stack ? err.stack.split('\n') : [];
  108. const asyncStack = stack.lastIndexOf(' -- ASYNC --');
  109. err.stack = errorMessage + '\n' + stack.slice(asyncStack + 1)
  110. .filter((line) => !line.includes('devtools/node_modules/puppeteer-core'))
  111. .join('\n');
  112. return err;
  113. }
  114. exports.sanitizeError = sanitizeError;
  115. async function transformExecuteArgs(args = []) {
  116. return Promise.all(args.map(async (arg) => {
  117. if (arg[constants_1.ELEMENT_KEY]) {
  118. const elementHandle = await this.elementStore.get(arg[constants_1.ELEMENT_KEY]);
  119. if (!elementHandle) {
  120. throw getStaleElementError(arg[constants_1.ELEMENT_KEY]);
  121. }
  122. arg = elementHandle;
  123. }
  124. return arg;
  125. }));
  126. }
  127. exports.transformExecuteArgs = transformExecuteArgs;
  128. async function transformExecuteResult(page, result) {
  129. const isResultArray = Array.isArray(result);
  130. let tmpResult = isResultArray ? result : [result];
  131. if (tmpResult.find((r) => typeof r === 'string' && r.startsWith(constants_1.SERIALIZE_FLAG))) {
  132. tmpResult = await Promise.all(tmpResult.map(async (r) => {
  133. if (typeof r === 'string' && r.startsWith(constants_1.SERIALIZE_FLAG)) {
  134. return findElement.call(this, page, 'css selector', `[${constants_1.SERIALIZE_PROPERTY}="${r}"]`);
  135. }
  136. return result;
  137. }));
  138. await page.$$eval(`[${constants_1.SERIALIZE_PROPERTY}]`, cleanUpSerializationSelector_1.default, constants_1.SERIALIZE_PROPERTY);
  139. }
  140. return isResultArray ? tmpResult : tmpResult[0];
  141. }
  142. exports.transformExecuteResult = transformExecuteResult;
  143. function getStaleElementError(elementId) {
  144. const error = new Error(`stale element reference: The element with reference ${elementId} is stale; either the ` +
  145. 'element is no longer attached to the DOM, it is not in the current frame context, or the ' +
  146. 'document has been refreshed');
  147. error.name = 'stale element reference';
  148. return error;
  149. }
  150. exports.getStaleElementError = getStaleElementError;
  151. async function getPages(browser, retryInterval = 100) {
  152. const pages = await browser.pages();
  153. if (pages.length === 0) {
  154. log.info('no browser pages found, retrying...');
  155. await new Promise((resolve) => setTimeout(resolve, retryInterval));
  156. return getPages(browser);
  157. }
  158. return pages;
  159. }
  160. exports.getPages = getPages;
  161. function sort(installations, priorities) {
  162. const defaultPriority = 10;
  163. return installations
  164. .map((inst) => {
  165. for (const pair of priorities) {
  166. if (pair.regex.test(inst)) {
  167. return { path: inst, weight: pair.weight };
  168. }
  169. }
  170. return { path: inst, weight: defaultPriority };
  171. })
  172. .sort((a, b) => (b.weight - a.weight))
  173. .map(pair => pair.path);
  174. }
  175. exports.sort = sort;
  176. function uniq(arr) {
  177. return Array.from(new Set(arr));
  178. }
  179. exports.uniq = uniq;
  180. function findByWhich(executables, priorities) {
  181. const installations = [];
  182. executables.forEach((executable) => {
  183. try {
  184. const browserPath = child_process_1.execFileSync('which', [executable], { stdio: 'pipe' }).toString().split(/\r?\n/)[0];
  185. if (utils_1.canAccess(browserPath)) {
  186. installations.push(browserPath);
  187. }
  188. }
  189. catch (e) {
  190. }
  191. });
  192. return sort(uniq(installations.filter(Boolean)), priorities);
  193. }
  194. exports.findByWhich = findByWhich;
  195. function patchDebug(scoppedLogger) {
  196. let puppeteerDebugPkg = path_1.default.resolve(path_1.default.dirname(require.resolve('puppeteer-core')), 'node_modules', 'debug');
  197. if (!fs_1.default.existsSync(puppeteerDebugPkg)) {
  198. const pkgName = 'debug';
  199. puppeteerDebugPkg = require.resolve(pkgName);
  200. }
  201. require(puppeteerDebugPkg).log = (msg) => {
  202. if (msg.includes('puppeteer:protocol')) {
  203. msg = msg.slice(msg.indexOf(constants_1.PPTR_LOG_PREFIX) + constants_1.PPTR_LOG_PREFIX.length).trim();
  204. }
  205. scoppedLogger.debug(msg);
  206. };
  207. }
  208. exports.patchDebug = patchDebug;