webServerPlugin.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.webServerPluginsForConfig = exports.webServer = exports.WebServerPlugin = void 0;
  6. var _path = _interopRequireDefault(require("path"));
  7. var _net = _interopRequireDefault(require("net"));
  8. var _utilsBundle = require("playwright-core/lib/utilsBundle");
  9. var _utils = require("playwright-core/lib/utils");
  10. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11. /**
  12. * Copyright (c) Microsoft Corporation.
  13. *
  14. * Licensed under the Apache License, Version 2.0 (the "License");
  15. * you may not use this file except in compliance with the License.
  16. * You may obtain a copy of the License at
  17. *
  18. * http://www.apache.org/licenses/LICENSE-2.0
  19. *
  20. * Unless required by applicable law or agreed to in writing, software
  21. * distributed under the License is distributed on an "AS IS" BASIS,
  22. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. * See the License for the specific language governing permissions and
  24. * limitations under the License.
  25. */
  26. const DEFAULT_ENVIRONMENT_VARIABLES = {
  27. 'BROWSER': 'none',
  28. // Disable that create-react-app will open the page in the browser
  29. 'FORCE_COLOR': '1',
  30. 'DEBUG_COLORS': '1'
  31. };
  32. const debugWebServer = (0, _utilsBundle.debug)('pw:webserver');
  33. class WebServerPlugin {
  34. constructor(options, checkPortOnly) {
  35. this._isAvailableCallback = void 0;
  36. this._killProcess = void 0;
  37. this._processExitedPromise = void 0;
  38. this._options = void 0;
  39. this._checkPortOnly = void 0;
  40. this._reporter = void 0;
  41. this.name = 'playwright:webserver';
  42. this._options = options;
  43. this._checkPortOnly = checkPortOnly;
  44. }
  45. async setup(config, configDir, reporter) {
  46. var _this$_reporter$onStd;
  47. this._reporter = reporter;
  48. this._isAvailableCallback = this._options.url ? getIsAvailableFunction(this._options.url, this._checkPortOnly, !!this._options.ignoreHTTPSErrors, (_this$_reporter$onStd = this._reporter.onStdErr) === null || _this$_reporter$onStd === void 0 ? void 0 : _this$_reporter$onStd.bind(this._reporter)) : undefined;
  49. this._options.cwd = this._options.cwd ? _path.default.resolve(configDir, this._options.cwd) : configDir;
  50. try {
  51. await this._startProcess();
  52. await this._waitForProcess();
  53. } catch (error) {
  54. await this.teardown();
  55. throw error;
  56. }
  57. }
  58. async teardown() {
  59. var _this$_killProcess;
  60. await ((_this$_killProcess = this._killProcess) === null || _this$_killProcess === void 0 ? void 0 : _this$_killProcess.call(this));
  61. }
  62. async _startProcess() {
  63. var _this$_isAvailableCal;
  64. let processExitedReject = error => {};
  65. this._processExitedPromise = new Promise((_, reject) => processExitedReject = reject);
  66. const isAlreadyAvailable = await ((_this$_isAvailableCal = this._isAvailableCallback) === null || _this$_isAvailableCal === void 0 ? void 0 : _this$_isAvailableCal.call(this));
  67. if (isAlreadyAvailable) {
  68. var _this$_options$url;
  69. debugWebServer(`WebServer is already available`);
  70. if (this._options.reuseExistingServer) return;
  71. const port = new URL(this._options.url).port;
  72. throw new Error(`${(_this$_options$url = this._options.url) !== null && _this$_options$url !== void 0 ? _this$_options$url : `http://localhost${port ? ':' + port : ''}`} is already used, make sure that nothing is running on the port/url or set reuseExistingServer:true in config.webServer.`);
  73. }
  74. debugWebServer(`Starting WebServer process ${this._options.command}...`);
  75. const {
  76. launchedProcess,
  77. kill
  78. } = await (0, _utils.launchProcess)({
  79. command: this._options.command,
  80. env: {
  81. ...DEFAULT_ENVIRONMENT_VARIABLES,
  82. ...process.env,
  83. ...this._options.env
  84. },
  85. cwd: this._options.cwd,
  86. stdio: 'stdin',
  87. shell: true,
  88. // Reject to indicate that we cannot close the web server gracefully
  89. // and should fallback to non-graceful shutdown.
  90. attemptToGracefullyClose: () => Promise.reject(),
  91. log: () => {},
  92. onExit: code => processExitedReject(new Error(code ? `Process from config.webServer was not able to start. Exit code: ${code}` : 'Process from config.webServer exited early.')),
  93. tempDirectories: []
  94. });
  95. this._killProcess = kill;
  96. debugWebServer(`Process started`);
  97. launchedProcess.stderr.on('data', line => {
  98. var _onStdErr, _ref;
  99. if (debugWebServer.enabled || this._options.stderr === 'pipe' || !this._options.stderr) (_onStdErr = (_ref = this._reporter).onStdErr) === null || _onStdErr === void 0 ? void 0 : _onStdErr.call(_ref, _utilsBundle.colors.dim('[WebServer] ') + line.toString());
  100. });
  101. launchedProcess.stdout.on('data', line => {
  102. var _onStdOut, _ref2;
  103. if (debugWebServer.enabled || this._options.stdout === 'pipe') (_onStdOut = (_ref2 = this._reporter).onStdOut) === null || _onStdOut === void 0 ? void 0 : _onStdOut.call(_ref2, _utilsBundle.colors.dim('[WebServer] ') + line.toString());
  104. });
  105. }
  106. async _waitForProcess() {
  107. if (!this._isAvailableCallback) {
  108. this._processExitedPromise.catch(() => {});
  109. return;
  110. }
  111. debugWebServer(`Waiting for availability...`);
  112. const launchTimeout = this._options.timeout || 60 * 1000;
  113. const cancellationToken = {
  114. canceled: false
  115. };
  116. const {
  117. timedOut
  118. } = await Promise.race([(0, _utils.raceAgainstDeadline)(() => waitFor(this._isAvailableCallback, cancellationToken), (0, _utils.monotonicTime)() + launchTimeout), this._processExitedPromise]);
  119. cancellationToken.canceled = true;
  120. if (timedOut) throw new Error(`Timed out waiting ${launchTimeout}ms from config.webServer.`);
  121. debugWebServer(`WebServer available`);
  122. }
  123. }
  124. exports.WebServerPlugin = WebServerPlugin;
  125. async function isPortUsed(port) {
  126. const innerIsPortUsed = host => new Promise(resolve => {
  127. const conn = _net.default.connect(port, host).on('error', () => {
  128. resolve(false);
  129. }).on('connect', () => {
  130. conn.end();
  131. resolve(true);
  132. });
  133. });
  134. return (await innerIsPortUsed('127.0.0.1')) || (await innerIsPortUsed('::1'));
  135. }
  136. async function isURLAvailable(url, ignoreHTTPSErrors, onStdErr) {
  137. let statusCode = await httpStatusCode(url, ignoreHTTPSErrors, onStdErr);
  138. if (statusCode === 404 && url.pathname === '/') {
  139. const indexUrl = new URL(url);
  140. indexUrl.pathname = '/index.html';
  141. statusCode = await httpStatusCode(indexUrl, ignoreHTTPSErrors, onStdErr);
  142. }
  143. return statusCode >= 200 && statusCode < 404;
  144. }
  145. async function httpStatusCode(url, ignoreHTTPSErrors, onStdErr) {
  146. return new Promise(resolve => {
  147. debugWebServer(`HTTP GET: ${url}`);
  148. (0, _utils.httpRequest)({
  149. url: url.toString(),
  150. headers: {
  151. Accept: '*/*'
  152. },
  153. rejectUnauthorized: !ignoreHTTPSErrors
  154. }, res => {
  155. var _res$statusCode;
  156. res.resume();
  157. const statusCode = (_res$statusCode = res.statusCode) !== null && _res$statusCode !== void 0 ? _res$statusCode : 0;
  158. debugWebServer(`HTTP Status: ${statusCode}`);
  159. resolve(statusCode);
  160. }, error => {
  161. if (error.code === 'DEPTH_ZERO_SELF_SIGNED_CERT') onStdErr === null || onStdErr === void 0 ? void 0 : onStdErr(`[WebServer] Self-signed certificate detected. Try adding ignoreHTTPSErrors: true to config.webServer.`);
  162. debugWebServer(`Error while checking if ${url} is available: ${error.message}`);
  163. resolve(0);
  164. });
  165. });
  166. }
  167. async function waitFor(waitFn, cancellationToken) {
  168. const logScale = [100, 250, 500];
  169. while (!cancellationToken.canceled) {
  170. const connected = await waitFn();
  171. if (connected) return;
  172. const delay = logScale.shift() || 1000;
  173. debugWebServer(`Waiting ${delay}ms`);
  174. await new Promise(x => setTimeout(x, delay));
  175. }
  176. }
  177. function getIsAvailableFunction(url, checkPortOnly, ignoreHTTPSErrors, onStdErr) {
  178. const urlObject = new URL(url);
  179. if (!checkPortOnly) return () => isURLAvailable(urlObject, ignoreHTTPSErrors, onStdErr);
  180. const port = urlObject.port;
  181. return () => isPortUsed(+port);
  182. }
  183. const webServer = options => {
  184. return new WebServerPlugin(options, false);
  185. };
  186. exports.webServer = webServer;
  187. const webServerPluginsForConfig = config => {
  188. const shouldSetBaseUrl = !!config.config.webServer;
  189. const webServerPlugins = [];
  190. for (const webServerConfig of config.webServers) {
  191. if (webServerConfig.port && webServerConfig.url) throw new Error(`Either 'port' or 'url' should be specified in config.webServer.`);
  192. let url;
  193. if (webServerConfig.port || webServerConfig.url) {
  194. url = webServerConfig.url || `http://localhost:${webServerConfig.port}`;
  195. // We only set base url when only the port is given. That's a legacy mode we have regrets about.
  196. if (shouldSetBaseUrl && !webServerConfig.url) process.env.PLAYWRIGHT_TEST_BASE_URL = url;
  197. }
  198. webServerPlugins.push(new WebServerPlugin({
  199. ...webServerConfig,
  200. url
  201. }, webServerConfig.port !== undefined));
  202. }
  203. return webServerPlugins;
  204. };
  205. exports.webServerPluginsForConfig = webServerPluginsForConfig;