webServerPlugin.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __export = (target, all) => {
  9. for (var name in all)
  10. __defProp(target, name, { get: all[name], enumerable: true });
  11. };
  12. var __copyProps = (to, from, except, desc) => {
  13. if (from && typeof from === "object" || typeof from === "function") {
  14. for (let key of __getOwnPropNames(from))
  15. if (!__hasOwnProp.call(to, key) && key !== except)
  16. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  17. }
  18. return to;
  19. };
  20. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  21. // If the importer is in node compatibility mode or this is not an ESM
  22. // file that has been converted to a CommonJS file using a Babel-
  23. // compatible transform (i.e. "__esModule" has not been set), then set
  24. // "default" to the CommonJS "module.exports" for node compatibility.
  25. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  26. mod
  27. ));
  28. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  29. var webServerPlugin_exports = {};
  30. __export(webServerPlugin_exports, {
  31. WebServerPlugin: () => WebServerPlugin,
  32. webServer: () => webServer,
  33. webServerPluginsForConfig: () => webServerPluginsForConfig
  34. });
  35. module.exports = __toCommonJS(webServerPlugin_exports);
  36. var import_net = __toESM(require("net"));
  37. var import_path = __toESM(require("path"));
  38. var import_utils = require("playwright-core/lib/utils");
  39. var import_utils2 = require("playwright-core/lib/utils");
  40. var import_utilsBundle = require("playwright-core/lib/utilsBundle");
  41. const DEFAULT_ENVIRONMENT_VARIABLES = {
  42. "BROWSER": "none",
  43. // Disable that create-react-app will open the page in the browser
  44. "FORCE_COLOR": "1",
  45. "DEBUG_COLORS": "1"
  46. };
  47. const debugWebServer = (0, import_utilsBundle.debug)("pw:webserver");
  48. class WebServerPlugin {
  49. constructor(options, checkPortOnly) {
  50. this.name = "playwright:webserver";
  51. this._options = options;
  52. this._checkPortOnly = checkPortOnly;
  53. }
  54. async setup(config, configDir, reporter) {
  55. this._reporter = reporter;
  56. this._isAvailableCallback = this._options.url ? getIsAvailableFunction(this._options.url, this._checkPortOnly, !!this._options.ignoreHTTPSErrors, this._reporter.onStdErr?.bind(this._reporter)) : void 0;
  57. this._options.cwd = this._options.cwd ? import_path.default.resolve(configDir, this._options.cwd) : configDir;
  58. try {
  59. await this._startProcess();
  60. await this._waitForProcess();
  61. } catch (error) {
  62. await this.teardown();
  63. throw error;
  64. }
  65. }
  66. async teardown() {
  67. debugWebServer(`Terminating the WebServer`);
  68. await this._killProcess?.();
  69. debugWebServer(`Terminated the WebServer`);
  70. }
  71. async _startProcess() {
  72. let processExitedReject = (error) => {
  73. };
  74. this._processExitedPromise = new Promise((_, reject) => processExitedReject = reject);
  75. const isAlreadyAvailable = await this._isAvailableCallback?.();
  76. if (isAlreadyAvailable) {
  77. debugWebServer(`WebServer is already available`);
  78. if (this._options.reuseExistingServer)
  79. return;
  80. const port = new URL(this._options.url).port;
  81. throw new Error(`${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.`);
  82. }
  83. if (!this._options.command)
  84. throw new Error("config.webServer.command cannot be empty");
  85. debugWebServer(`Starting WebServer process ${this._options.command}...`);
  86. const { launchedProcess, gracefullyClose } = await (0, import_utils.launchProcess)({
  87. command: this._options.command,
  88. env: {
  89. ...DEFAULT_ENVIRONMENT_VARIABLES,
  90. ...process.env,
  91. ...this._options.env
  92. },
  93. cwd: this._options.cwd,
  94. stdio: "stdin",
  95. shell: true,
  96. attemptToGracefullyClose: async () => {
  97. if (process.platform === "win32")
  98. throw new Error("Graceful shutdown is not supported on Windows");
  99. if (!this._options.gracefulShutdown)
  100. throw new Error("skip graceful shutdown");
  101. const { signal, timeout = 0 } = this._options.gracefulShutdown;
  102. process.kill(-launchedProcess.pid, signal);
  103. return new Promise((resolve, reject) => {
  104. const timer = timeout !== 0 ? setTimeout(() => reject(new Error(`process didn't close gracefully within timeout`)), timeout) : void 0;
  105. launchedProcess.once("close", (...args) => {
  106. clearTimeout(timer);
  107. resolve();
  108. });
  109. });
  110. },
  111. log: () => {
  112. },
  113. onExit: (code) => processExitedReject(new Error(code ? `Process from config.webServer was not able to start. Exit code: ${code}` : "Process from config.webServer exited early.")),
  114. tempDirectories: []
  115. });
  116. this._killProcess = gracefullyClose;
  117. debugWebServer(`Process started`);
  118. if (this._options.wait?.stdout || this._options.wait?.stderr)
  119. this._waitForStdioPromise = new import_utils.ManualPromise();
  120. const stdioWaitCollectors = {
  121. stdout: this._options.wait?.stdout ? "" : void 0,
  122. stderr: this._options.wait?.stderr ? "" : void 0
  123. };
  124. launchedProcess.stdout.on("data", (data) => {
  125. if (debugWebServer.enabled || this._options.stdout === "pipe")
  126. this._reporter.onStdOut?.(prefixOutputLines(data.toString(), this._options.name));
  127. });
  128. launchedProcess.stderr.on("data", (data) => {
  129. if (debugWebServer.enabled || (this._options.stderr === "pipe" || !this._options.stderr))
  130. this._reporter.onStdErr?.(prefixOutputLines(data.toString(), this._options.name));
  131. });
  132. const resolveStdioPromise = () => {
  133. stdioWaitCollectors.stdout = void 0;
  134. stdioWaitCollectors.stderr = void 0;
  135. this._waitForStdioPromise?.resolve();
  136. };
  137. for (const stdio of ["stdout", "stderr"]) {
  138. launchedProcess[stdio].on("data", (data) => {
  139. if (!this._options.wait?.[stdio] || stdioWaitCollectors[stdio] === void 0)
  140. return;
  141. stdioWaitCollectors[stdio] += data.toString();
  142. this._options.wait[stdio].lastIndex = 0;
  143. const result = this._options.wait[stdio].exec(stdioWaitCollectors[stdio]);
  144. if (result) {
  145. for (const [key, value] of Object.entries(result.groups || {}))
  146. process.env[key.toUpperCase()] = value;
  147. resolveStdioPromise();
  148. }
  149. });
  150. }
  151. }
  152. async _waitForProcess() {
  153. if (!this._isAvailableCallback && !this._waitForStdioPromise) {
  154. this._processExitedPromise.catch(() => {
  155. });
  156. return;
  157. }
  158. debugWebServer(`Waiting for availability...`);
  159. const launchTimeout = this._options.timeout || 60 * 1e3;
  160. const cancellationToken = { canceled: false };
  161. const deadline = (0, import_utils.monotonicTime)() + launchTimeout;
  162. const racingPromises = [this._processExitedPromise];
  163. if (this._isAvailableCallback)
  164. racingPromises.push((0, import_utils.raceAgainstDeadline)(() => waitFor(this._isAvailableCallback, cancellationToken), deadline));
  165. if (this._waitForStdioPromise)
  166. racingPromises.push((0, import_utils.raceAgainstDeadline)(() => this._waitForStdioPromise, deadline));
  167. const { timedOut } = await Promise.race(racingPromises);
  168. cancellationToken.canceled = true;
  169. if (timedOut)
  170. throw new Error(`Timed out waiting ${launchTimeout}ms from config.webServer.`);
  171. debugWebServer(`WebServer available`);
  172. }
  173. }
  174. async function isPortUsed(port) {
  175. const innerIsPortUsed = (host) => new Promise((resolve) => {
  176. const conn = import_net.default.connect(port, host).on("error", () => {
  177. resolve(false);
  178. }).on("connect", () => {
  179. conn.end();
  180. resolve(true);
  181. });
  182. });
  183. return await innerIsPortUsed("127.0.0.1") || await innerIsPortUsed("::1");
  184. }
  185. async function waitFor(waitFn, cancellationToken) {
  186. const logScale = [100, 250, 500];
  187. while (!cancellationToken.canceled) {
  188. const connected = await waitFn();
  189. if (connected)
  190. return;
  191. const delay = logScale.shift() || 1e3;
  192. debugWebServer(`Waiting ${delay}ms`);
  193. await new Promise((x) => setTimeout(x, delay));
  194. }
  195. }
  196. function getIsAvailableFunction(url, checkPortOnly, ignoreHTTPSErrors, onStdErr) {
  197. const urlObject = new URL(url);
  198. if (!checkPortOnly)
  199. return () => (0, import_utils.isURLAvailable)(urlObject, ignoreHTTPSErrors, debugWebServer, onStdErr);
  200. const port = urlObject.port;
  201. return () => isPortUsed(+port);
  202. }
  203. const webServer = (options) => {
  204. return new WebServerPlugin(options, false);
  205. };
  206. const webServerPluginsForConfig = (config) => {
  207. const shouldSetBaseUrl = !!config.config.webServer;
  208. const webServerPlugins = [];
  209. for (const webServerConfig of config.webServers) {
  210. if (webServerConfig.port && webServerConfig.url)
  211. throw new Error(`Either 'port' or 'url' should be specified in config.webServer.`);
  212. let url;
  213. if (webServerConfig.port || webServerConfig.url) {
  214. url = webServerConfig.url || `http://localhost:${webServerConfig.port}`;
  215. if (shouldSetBaseUrl && !webServerConfig.url)
  216. process.env.PLAYWRIGHT_TEST_BASE_URL = url;
  217. }
  218. webServerPlugins.push(new WebServerPlugin({ ...webServerConfig, url }, webServerConfig.port !== void 0));
  219. }
  220. return webServerPlugins;
  221. };
  222. function prefixOutputLines(output, prefixName = "WebServer") {
  223. const lastIsNewLine = output[output.length - 1] === "\n";
  224. let lines = output.split("\n");
  225. if (lastIsNewLine)
  226. lines.pop();
  227. lines = lines.map((line) => import_utils2.colors.dim(`[${prefixName}] `) + line);
  228. if (lastIsNewLine)
  229. lines.push("");
  230. return lines.join("\n");
  231. }
  232. // Annotate the CommonJS export names for ESM import in node:
  233. 0 && (module.exports = {
  234. WebServerPlugin,
  235. webServer,
  236. webServerPluginsForConfig
  237. });