From a824a8d0a3783b6cbd1e9db8b9b7c06a083dd5c1 Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Sun, 26 Apr 2026 13:06:37 -0500 Subject: [PATCH 1/4] refactor: migrate to ES module syntax --- babel.config.js | 6 +- bin/webpack-dev-server.js | 61 +- client-src/webpack.config.js | 11 +- commitlint.config.js | 4 +- eslint.config.mjs | 5 + jest.config.js | 4 +- lib/Server.js | 165 +++-- lib/getPort.js | 8 +- lib/servers/BaseServer.js | 12 +- lib/servers/WebsocketServer.js | 18 +- lint-staged.config.js | 4 +- package-lock.json | 499 +++++++------- package.json | 3 +- scripts/extend-webpack-types.js | 20 +- tsconfig.json | 10 +- types/lib/Server.d.ts | 915 ++++++++++++------------- types/lib/getPort.d.ts | 2 +- types/lib/servers/BaseServer.d.ts | 17 +- types/lib/servers/WebsocketServer.d.ts | 21 +- 19 files changed, 864 insertions(+), 921 deletions(-) diff --git a/babel.config.js b/babel.config.js index a34db39f39..960f6b5739 100644 --- a/babel.config.js +++ b/babel.config.js @@ -1,6 +1,4 @@ -"use strict"; - -module.exports = (api) => { +export default (api) => { api.cache(true); return { @@ -24,7 +22,7 @@ module.exports = (api) => { "@babel/preset-env", { targets: { - node: "20.9.0", + node: "22.12.0", }, }, ], diff --git a/bin/webpack-dev-server.js b/bin/webpack-dev-server.js index de0cfd3b32..16e76b136b 100755 --- a/bin/webpack-dev-server.js +++ b/bin/webpack-dev-server.js @@ -2,17 +2,20 @@ /* Based on webpack/bin/webpack.js */ /* eslint-disable no-console */ -"use strict"; +import cp from "node:child_process"; +import nodeModule from "node:module"; +import path from "node:path"; +import readLine from "node:readline"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import fs from "graceful-fs"; /** * @param {string} command process to run * @param {string[]} args command line arguments * @returns {Promise} promise */ -const runCommand = (command, args) => { - const cp = require("node:child_process"); - - return new Promise((resolve, reject) => { +const runCommand = (command, args) => + new Promise((resolve, reject) => { const executedCommand = cp.spawn(command, args, { stdio: "inherit", shell: true, @@ -30,7 +33,6 @@ const runCommand = (command, args) => { } }); }); -}; /** * @param {string} packageName name of the package @@ -41,10 +43,7 @@ const isInstalled = (packageName) => { return true; } - const path = require("node:path"); - const fs = require("graceful-fs"); - - let dir = __dirname; + let dir = path.dirname(fileURLToPath(import.meta.url)); do { try { @@ -58,9 +57,9 @@ const isInstalled = (packageName) => { } } while (dir !== (dir = path.dirname(dir))); - // https://github.com/nodejs/node/blob/v18.9.1/lib/internal/modules/cjs/loader.js#L1274 + // https://github.com/nodejs/node/blob/v22.12.0/lib/internal/modules/cjs/loader.js#L1818 // @ts-expect-error - for (const internalPath of require("node:module").globalPaths) { + for (const internalPath of nodeModule.globalPaths) { try { if (fs.statSync(path.join(internalPath, packageName)).isDirectory()) { return true; @@ -75,29 +74,20 @@ const isInstalled = (packageName) => { /** * @param {CliOption} cli options - * @returns {void} + * @returns {Promise} */ -const runCli = (cli) => { +const runCli = async (cli) => { if (cli.preprocess) { cli.preprocess(); } - const path = require("node:path"); + const pkgUrl = import.meta.resolve(`${cli.package}/package.json`); + const pkgPath = fileURLToPath(pkgUrl); + const pkg = (await import(pkgUrl, { with: { type: "json" } })).default; - const pkgPath = require.resolve(`${cli.package}/package.json`); + const binPath = path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]); - const pkg = require(pkgPath); - - if (pkg.type === "module" || /\.mjs/i.test(pkg.bin[cli.binName])) { - import(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName])).catch( - (error) => { - console.error(error); - process.exitCode = 1; - }, - ); - } else { - require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName])); - } + await import(pathToFileURL(binPath).href); }; /** @@ -123,10 +113,6 @@ const cli = { }; if (!cli.installed) { - const path = require("node:path"); - const fs = require("graceful-fs"); - const readLine = require("node:readline"); - const notify = `CLI for webpack must be installed.\n ${cli.name} (${cli.url})\n`; console.error(notify); @@ -187,14 +173,17 @@ if (!cli.installed) { ); runCommand(packageManager, [...installOptions, cli.package]) - .then(() => { - runCli(cli); - }) + .then(() => runCli(cli)) .catch((error) => { console.error(error); process.exitCode = 1; }); }); } else { - runCli(cli); + try { + await runCli(cli); + } catch (error) { + console.error(error); + process.exitCode = 1; + } } diff --git a/client-src/webpack.config.js b/client-src/webpack.config.js index 7037f9406f..5aa430209b 100644 --- a/client-src/webpack.config.js +++ b/client-src/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import webpack from "webpack"; +import { merge } from "webpack-merge"; -const path = require("node:path"); -const webpack = require("webpack"); -const { merge } = require("webpack-merge"); +const __dirname = path.dirname(fileURLToPath(import.meta.url)); const library = { library: { @@ -37,7 +38,7 @@ const baseForModules = { }, }; -module.exports = [ +export default [ merge(baseForModules, { entry: path.join(__dirname, "modules/logger/index.js"), output: { diff --git a/commitlint.config.js b/commitlint.config.js index 1698d22ed8..f0f7617e9e 100644 --- a/commitlint.config.js +++ b/commitlint.config.js @@ -1,6 +1,4 @@ -"use strict"; - -module.exports = { +export default { extends: ["@commitlint/config-conventional"], rules: { "header-max-length": [0], diff --git a/eslint.config.mjs b/eslint.config.mjs index 52ac3be3ee..f63dcef69a 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -7,6 +7,11 @@ export default defineConfig([ { extends: [config], ignores: ["client-src/**/*", "!client-src/webpack.config.js"], + languageOptions: { + // ES2025 needed for import attributes (`import(x, { with: ... })`). + // eslint-config-webpack pins ecmaVersion to 2024 for Node 22. + ecmaVersion: "latest", + }, rules: { // TODO fix me "prefer-destructuring": "off", diff --git a/jest.config.js b/jest.config.js index 7bd7b0bb03..3747b2d2b4 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,6 +1,4 @@ -"use strict"; - -module.exports = { +export default { testEnvironmentOptions: { url: "http://localhost/", }, diff --git a/lib/Server.js b/lib/Server.js index 093e03ab62..40b01db2ef 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -1,14 +1,21 @@ -"use strict"; - -const os = require("node:os"); -const path = require("node:path"); -const url = require("node:url"); -const fs = require("graceful-fs"); -const ipaddr = require("ipaddr.js"); -const { validate } = require("schema-utils"); -const schema = require("./options.json"); +import net from "node:net"; +import os from "node:os"; +import path from "node:path"; +import url, { fileURLToPath } from "node:url"; +import fs from "graceful-fs"; +import ipaddr from "ipaddr.js"; +import { validate } from "schema-utils"; +import schema from "./options.json" with { type: "json" }; + +/** @type {typeof import("webpack") | undefined} */ +let webpackPeer; +try { + webpackPeer = (await import("webpack")).default; +} catch { + // webpack is an optional peer dependency +} -/** @typedef {import("schema-utils/declarations/validate").Schema} Schema */ +/** @typedef {import("schema-utils").Schema} Schema */ /** @typedef {import("webpack").Compiler} Compiler */ /** @typedef {import("webpack").MultiCompiler} MultiCompiler */ /** @typedef {import("webpack").Configuration} WebpackConfiguration */ @@ -266,7 +273,7 @@ const memoize = (fn) => { }; }; -const getExpress = memoize(() => require("express")); +const getExpress = memoize(async () => (await import("express")).default); /** * @param {OverlayMessageOptions=} setting overlay settings @@ -495,9 +502,8 @@ class Server { return port; } - const pRetry = (await import("p-retry")).default; - - const getPort = require("./getPort"); + const { default: pRetry } = await import("p-retry"); + const { default: getPort } = await import("./getPort.js"); const basePort = typeof process.env.WEBPACK_DEV_SERVER_BASE_PORT !== "undefined" @@ -738,7 +744,9 @@ class Server { additionalEntries.push(clientHotEntry); } - const webpack = compiler.webpack || require("webpack"); + const webpack = + compiler.webpack || + /** @type {NonNullable} */ (webpackPeer); // use a hook to add entries if available for (const additionalEntry of additionalEntries) { @@ -1139,7 +1147,7 @@ class Server { if (!certificateExists) { this.logger.info("Generating SSL certificate..."); - const selfsigned = require("selfsigned"); + const { default: selfsigned } = await import("selfsigned"); const attributes = [{ name: "commonName", value: "localhost" }]; const notBeforeDate = new Date(); @@ -1477,14 +1485,16 @@ class Server { switch (typeof clientTransport) { case "string": - // could be 'ws', or a path that should be required + // could be 'ws', or a path that should be resolved if (clientTransport === "ws") { - clientImplementation = require.resolve( - "../client/clients/WebSocketClient", + clientImplementation = fileURLToPath( + import.meta.resolve("../client/clients/WebSocketClient.js"), ); } else { try { - clientImplementation = require.resolve(clientTransport); + clientImplementation = fileURLToPath( + import.meta.resolve(clientTransport), + ); } catch { clientImplementationFound = false; } @@ -1500,7 +1510,7 @@ class Server { !isKnownWebSocketServerImplementation ? "When you use custom web socket implementation you must explicitly specify client.webSocketTransport. " : "" - }client.webSocketTransport must be a string denoting a default implementation (e.g. 'ws') or a full path to a JS file via require.resolve(...) which exports a class `, + }client.webSocketTransport must be a string denoting a default implementation (e.g. 'ws') or a resolvable module specifier or absolute file path which exports a class `, ); } @@ -1510,9 +1520,9 @@ class Server { /** * @template T * @private - * @returns {T} server transport + * @returns {Promise} server transport */ - getServerTransport() { + async getServerTransport() { let implementation; let implementationFound = true; @@ -1529,13 +1539,17 @@ class Server { this.options.webSocketServer ).type === "ws" ) { - implementation = require("./servers/WebsocketServer"); + implementation = (await import("./servers/WebsocketServer.js")) + .default; } else { try { - implementation = require( - /** @type {WebSocketServerConfiguration} */ - (this.options.webSocketServer).type, + const mod = await import( + /** @type {string} */ ( + /** @type {WebSocketServerConfiguration} */ + (this.options.webSocketServer).type + ) ); + implementation = mod.default || mod; } catch { implementationFound = false; } @@ -1552,9 +1566,9 @@ class Server { if (!implementationFound) { throw new Error( - "webSocketServer (webSocketServer.type) must be a string denoting a default implementation (e.g. 'ws'), a full path to " + - "a JS file which exports a class extending BaseServer (webpack-dev-server/lib/servers/BaseServer.js) " + - "via require.resolve(...), or the class itself which extends BaseServer", + "webSocketServer (webSocketServer.type) must be a string denoting a default implementation (e.g. 'ws'), a resolvable module specifier or absolute file path " + + "which exports a class extending BaseServer (webpack-dev-server/lib/servers/BaseServer.js), " + + "or the class itself which extends BaseServer", ); } @@ -1566,7 +1580,7 @@ class Server { */ getClientEntry() { - return require.resolve("../client/index.js"); + return fileURLToPath(import.meta.resolve("../client/index.js")); } /** @@ -1574,9 +1588,9 @@ class Server { */ getClientHotEntry() { if (this.options.hot === "only") { - return require.resolve("webpack/hot/only-dev-server"); + return fileURLToPath(import.meta.resolve("webpack/hot/only-dev-server")); } else if (this.options.hot) { - return require.resolve("webpack/hot/dev-server"); + return fileURLToPath(import.meta.resolve("webpack/hot/dev-server")); } } @@ -1646,7 +1660,9 @@ class Server { this.addAdditionalEntries(compiler); - const webpack = compiler.webpack || require("webpack"); + const webpack = + compiler.webpack || + /** @type {NonNullable} */ (webpackPeer); new webpack.ProvidePlugin({ __webpack_dev_server_client__: this.getClientTransport(), @@ -1680,9 +1696,9 @@ class Server { } } - this.setupWatchFiles(); - this.setupWatchStaticFiles(); - this.setupMiddlewares(); + await this.setupWatchFiles(); + await this.setupWatchStaticFiles(); + await this.setupMiddlewares(); if (this.options.setupExitSignals) { const signals = ["SIGINT", "SIGTERM"]; @@ -1749,7 +1765,7 @@ class Server { ( typeof this.options.app === "function" ? await this.options.app() - : getExpress()() + : (await getExpress())() ); } @@ -1805,15 +1821,15 @@ class Server { /** * @private - * @returns {void} + * @returns {Promise} */ - setupWatchStaticFiles() { + async setupWatchStaticFiles() { const watchFiles = /** @type {NormalizedStatic[]} */ (this.options.static); if (watchFiles.length > 0) { for (const item of watchFiles) { if (item.watch) { - this.watchFiles(item.directory, item.watch); + await this.watchFiles(item.directory, item.watch); } } } @@ -1821,23 +1837,23 @@ class Server { /** * @private - * @returns {void} + * @returns {Promise} */ - setupWatchFiles() { + async setupWatchFiles() { const watchFiles = /** @type {WatchFiles[]} */ (this.options.watchFiles); if (watchFiles.length > 0) { for (const item of watchFiles) { - this.watchFiles(item.paths, item.options); + await this.watchFiles(item.paths, item.options); } } } /** * @private - * @returns {void} + * @returns {Promise} */ - setupMiddlewares() { + async setupMiddlewares() { /** * @type {Array} */ @@ -1926,7 +1942,7 @@ class Server { // compress is placed last and uses unshift so that it will be the first middleware used if (this.options.compress) { - const compression = require("compression"); + const { default: compression } = await import("compression"); middlewares.push({ name: "compression", middleware: compression() }); } @@ -1971,9 +1987,9 @@ class Server { * @param {Request} req request * @param {Response} res response * @param {NextFunction} next next function - * @returns {void} + * @returns {Promise} */ - middleware: (req, res, next) => { + middleware: async (req, res, next) => { if (req.method !== "GET" && req.method !== "HEAD") { next(); return; @@ -1989,7 +2005,7 @@ class Server { const fileName = params.get("fileName"); if (typeof fileName === "string") { - const launchEditor = require("launch-editor"); + const { default: launchEditor } = await import("launch-editor"); launchEditor(fileName); } @@ -2082,7 +2098,7 @@ class Server { }); if (this.options.proxy) { - const { createProxyMiddleware } = require("http-proxy-middleware"); + const { createProxyMiddleware } = await import("http-proxy-middleware"); /** * @param {ProxyConfigArrayItem} proxyConfig proxy config @@ -2200,7 +2216,7 @@ class Server { middlewares.push({ name: "express-static", path: publicPath, - middleware: getExpress().static( + middleware: (await getExpress()).static( staticOption.directory, staticOption.staticOptions, ), @@ -2210,7 +2226,9 @@ class Server { } if (this.options.historyApiFallback) { - const connectHistoryApiFallback = require("connect-history-api-fallback"); + const { default: connectHistoryApiFallback } = await import( + "connect-history-api-fallback" + ); const { historyApiFallback } = this.options; @@ -2253,7 +2271,7 @@ class Server { middlewares.push({ name: "express-static", path: publicPath, - middleware: getExpress().static( + middleware: (await getExpress()).static( staticOption.directory, staticOption.staticOptions, ), @@ -2264,7 +2282,7 @@ class Server { } if (staticOptions.length > 0) { - const serveIndex = require("serve-index"); + const { default: serveIndex } = await import("serve-index"); for (const staticOption of staticOptions) { for (const publicPath of staticOption.publicPath) { @@ -2321,11 +2339,13 @@ class Server { middlewares = this.options.setupMiddlewares(middlewares, this); } + const { default: webpackDevMiddleware } = await import( + "webpack-dev-middleware" + ); + // Lazy init webpack dev middleware const lazyInitDevMiddleware = () => { if (!this.middleware) { - const webpackDevMiddleware = require("webpack-dev-middleware"); - // middleware for serving webpack bundle /** @type {import("webpack-dev-middleware").API} */ this.middleware = webpackDevMiddleware( @@ -2389,7 +2409,8 @@ class Server { (this.app), ); } else { - const serverType = require(/** @type {string} */ (type)); + const mod = await import(/** @type {string} */ (type)); + const serverType = mod.default || mod; /** @type {S | undefined} */ this.server = @@ -2437,11 +2458,11 @@ class Server { /** * @private - * @returns {void} + * @returns {Promise} */ - createWebSocketServer() { + async createWebSocketServer() { /** @type {WebSocketServerImplementation | undefined | null} */ - this.webSocketServer = new (this.getServerTransport())(this); + this.webSocketServer = new (await this.getServerTransport())(this); /** @type {WebSocketServerImplementation} */ (this.webSocketServer).implementation.on( @@ -2601,10 +2622,10 @@ class Server { /** * @private - * @returns {void} + * @returns {Promise} */ - runBonjour() { - const { Bonjour } = require("bonjour-service"); + async runBonjour() { + const { Bonjour } = await import("bonjour-service"); const type = this.isTlsServer ? "https" : "http"; @@ -3170,11 +3191,11 @@ class Server { /** * @param {string | string[]} watchPath watch path * @param {WatchOptions=} watchOptions watch options + * @returns {Promise} */ - watchFiles(watchPath, watchOptions = {}) { - const chokidar = require("chokidar"); - const path = require("node:path"); - const { globSync, isDynamicPattern } = require("tinyglobby"); + async watchFiles(watchPath, watchOptions = {}) { + const { default: chokidar } = await import("chokidar"); + const { globSync, isDynamicPattern } = await import("tinyglobby"); const isWin = path.sep === "\\"; const toPosix = (/** @type {string} */ filePath) => @@ -3242,8 +3263,6 @@ class Server { if (this.options.ipc) { await /** @type {Promise} */ ( new Promise((resolve, reject) => { - const net = require("node:net"); - const socket = new net.Socket(); socket.on( @@ -3313,11 +3332,11 @@ class Server { } if (this.options.webSocketServer) { - this.createWebSocketServer(); + await this.createWebSocketServer(); } if (this.options.bonjour) { - this.runBonjour(); + await this.runBonjour(); } await this.logStatus(); @@ -3431,4 +3450,4 @@ class Server { } } -module.exports = Server; +export default Server; diff --git a/lib/getPort.js b/lib/getPort.js index 23bc4e348a..032e41f31b 100644 --- a/lib/getPort.js +++ b/lib/getPort.js @@ -1,13 +1,11 @@ -"use strict"; - /* * Based on the packages get-port https://www.npmjs.com/package/get-port * and portfinder https://www.npmjs.com/package/portfinder * The code structure is similar to get-port, but it searches * ports deterministically like portfinder */ -const net = require("node:net"); -const os = require("node:os"); +import net from "node:net"; +import os from "node:os"; const minPort = 1024; const maxPort = 65_535; @@ -129,4 +127,4 @@ async function getPorts(basePort, host) { throw new Error("No available ports found"); } -module.exports = getPorts; +export default getPorts; diff --git a/lib/servers/BaseServer.js b/lib/servers/BaseServer.js index 9f5a18f4e0..13079303b8 100644 --- a/lib/servers/BaseServer.js +++ b/lib/servers/BaseServer.js @@ -1,18 +1,16 @@ -"use strict"; - -/** @typedef {import("../Server").ClientConnection} ClientConnection */ +/** @typedef {import("../Server.js").ClientConnection} ClientConnection */ // base class that users should extend if they are making their own // server implementation -module.exports = class BaseServer { +export default class BaseServer { /** - * @param {import("../Server")} server server + * @param {import("../Server.js").default} server server */ constructor(server) { - /** @type {import("../Server")} */ + /** @type {import("../Server.js").default} */ this.server = server; /** @type {ClientConnection[]} */ this.clients = []; } -}; +} diff --git a/lib/servers/WebsocketServer.js b/lib/servers/WebsocketServer.js index b9071f4bd3..cc3f7b635b 100644 --- a/lib/servers/WebsocketServer.js +++ b/lib/servers/WebsocketServer.js @@ -1,16 +1,14 @@ -"use strict"; +import { WebSocketServer as WsServer } from "ws"; +import BaseServer from "./BaseServer.js"; -const WebSocket = require("ws"); -const BaseServer = require("./BaseServer"); +/** @typedef {import("../Server.js").WebSocketServerConfiguration} WebSocketServerConfiguration */ +/** @typedef {import("../Server.js").ClientConnection} ClientConnection */ -/** @typedef {import("../Server").WebSocketServerConfiguration} WebSocketServerConfiguration */ -/** @typedef {import("../Server").ClientConnection} ClientConnection */ - -module.exports = class WebsocketServer extends BaseServer { +export default class WebsocketServer extends BaseServer { static heartbeatInterval = 1000; /** - * @param {import("../Server")} server server + * @param {import("../Server.js").default} server server */ constructor(server) { super(server); @@ -29,7 +27,7 @@ module.exports = class WebsocketServer extends BaseServer { options.noServer = true; } - this.implementation = new WebSocket.Server(options); + this.implementation = new WsServer(options); /** @type {import("http").Server} */ (this.server.server).on( @@ -108,4 +106,4 @@ module.exports = class WebsocketServer extends BaseServer { clearInterval(interval); }); } -}; +} diff --git a/lint-staged.config.js b/lint-staged.config.js index 2d40a32b75..50d30973d9 100644 --- a/lint-staged.config.js +++ b/lint-staged.config.js @@ -1,6 +1,4 @@ -"use strict"; - -module.exports = { +export default { "*": [ "prettier --cache --write --ignore-unknown", "cspell --cache --no-must-find-files", diff --git a/package-lock.json b/package-lock.json index 217a4cd486..78cd5f63e5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,7 +44,7 @@ "@babel/eslint-parser": "^7.28.6", "@babel/plugin-transform-object-assign": "^7.27.1", "@babel/plugin-transform-runtime": "^7.29.0", - "@babel/preset-env": "^7.25.9", + "@babel/preset-env": "^7.29.2", "@babel/runtime": "^7.29.2", "@commitlint/cli": "^19.5.0", "@commitlint/config-conventional": "^19.5.0", @@ -341,18 +341,18 @@ } }, "node_modules/@babel/helper-create-class-features-plugin": { - "version": "7.28.3", - "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.28.3.tgz", - "integrity": "sha512-V9f6ZFIYSLNEbuGA/92uOvYsGCJNsuA8ESZ4ldc09bWk/j8H8TKiPw8Mk1eG6olpnO0ALHJmYfZvF4MEE4gajg==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.28.6.tgz", + "integrity": "sha512-dTOdvsjnG3xNT9Y0AUg1wAl38y+4Rl4sf9caSQZOXdNqVn+H+HbbJ4IyyHaIqNR6SW9oJpA/RuRjsjCw2IdIow==", "dev": true, "license": "MIT", "dependencies": { "@babel/helper-annotate-as-pure": "^7.27.3", - "@babel/helper-member-expression-to-functions": "^7.27.1", + "@babel/helper-member-expression-to-functions": "^7.28.5", "@babel/helper-optimise-call-expression": "^7.27.1", - "@babel/helper-replace-supers": "^7.27.1", + "@babel/helper-replace-supers": "^7.28.6", "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1", - "@babel/traverse": "^7.28.3", + "@babel/traverse": "^7.28.6", "semver": "^6.3.1" }, "engines": { @@ -363,14 +363,14 @@ } }, "node_modules/@babel/helper-create-regexp-features-plugin": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.27.1.tgz", - "integrity": "sha512-uVDC72XVf8UbrH5qQTc18Agb8emwjTiZrQE11Nv3CuBEZmVvTwwE9CBUEvHku06gQCAyYf8Nv6ja1IN+6LMbxQ==", + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.28.5.tgz", + "integrity": "sha512-N1EhvLtHzOvj7QQOUCCS3NrPJP8c5W6ZXCHDn7Yialuy1iu4r5EmIYkXlKNqT99Ciw+W0mDqWoR6HWMZlFP3hw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-annotate-as-pure": "^7.27.1", - "regexpu-core": "^6.2.0", + "@babel/helper-annotate-as-pure": "^7.27.3", + "regexpu-core": "^6.3.1", "semver": "^6.3.1" }, "engines": { @@ -381,17 +381,17 @@ } }, "node_modules/@babel/helper-define-polyfill-provider": { - "version": "0.6.5", - "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.6.5.tgz", - "integrity": "sha512-uJnGFcPsWQK8fvjgGP5LZUZZsYGIoPeRjSF5PGwrelYgq7Q15/Ft9NGFp1zglwgIv//W0uG4BevRuSJRyylZPg==", + "version": "0.6.8", + "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.6.8.tgz", + "integrity": "sha512-47UwBLPpQi1NoWzLuHNjRoHlYXMwIJoBf7MFou6viC/sIHWYygpvr0B6IAyh5sBdA2nr2LPIRww8lfaUVQINBA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-compilation-targets": "^7.27.2", - "@babel/helper-plugin-utils": "^7.27.1", - "debug": "^4.4.1", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", + "debug": "^4.4.3", "lodash.debounce": "^4.0.8", - "resolve": "^1.22.10" + "resolve": "^1.22.11" }, "peerDependencies": { "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" @@ -408,14 +408,14 @@ } }, "node_modules/@babel/helper-member-expression-to-functions": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.27.1.tgz", - "integrity": "sha512-E5chM8eWjTp/aNoVpcbfM7mLxu9XGLWYise2eBKGQomAk/Mb4XoxyqXTZbuTohbsl8EKqdlMhnDI2CCLfcs9wA==", + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.28.5.tgz", + "integrity": "sha512-cwM7SBRZcPCLgl8a7cY0soT1SptSzAlMH39vwiRpOQkJlh53r5hdHwLSCZpQdVLT39sZt+CRpNwYG4Y2v77atg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/traverse": "^7.27.1", - "@babel/types": "^7.27.1" + "@babel/traverse": "^7.28.5", + "@babel/types": "^7.28.5" }, "engines": { "node": ">=6.9.0" @@ -495,15 +495,15 @@ } }, "node_modules/@babel/helper-replace-supers": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.27.1.tgz", - "integrity": "sha512-7EHz6qDZc8RYS5ElPoShMheWvEgERonFCs7IAonWLLUTXW59DP14bCZt89/GKyreYn8g3S83m21FelHKbeDCKA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.28.6.tgz", + "integrity": "sha512-mq8e+laIk94/yFec3DxSjCRD2Z0TAjhVbEJY3UQrlwVo15Lmt7C2wAUbK4bjnTs4APkwsYLTahXRraQXhb1WCg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-member-expression-to-functions": "^7.27.1", + "@babel/helper-member-expression-to-functions": "^7.28.5", "@babel/helper-optimise-call-expression": "^7.27.1", - "@babel/traverse": "^7.27.1" + "@babel/traverse": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -557,15 +557,15 @@ } }, "node_modules/@babel/helper-wrap-function": { - "version": "7.28.3", - "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.28.3.tgz", - "integrity": "sha512-zdf983tNfLZFletc0RRXYrHrucBEg95NIFMkn6K9dbeMYnsgHaSBGcQqdsCSStG2PYwRre0Qc2NNSCXbG+xc6g==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.28.6.tgz", + "integrity": "sha512-z+PwLziMNBeSQJonizz2AGnndLsP2DeGHIxDAn+wdHOGuo4Fo1x1HBPPXeE9TAOPHNNWQKCSlA2VZyYyyibDnQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/template": "^7.27.2", - "@babel/traverse": "^7.28.3", - "@babel/types": "^7.28.2" + "@babel/template": "^7.28.6", + "@babel/traverse": "^7.28.6", + "@babel/types": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -669,14 +669,14 @@ } }, "node_modules/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": { - "version": "7.28.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly/-/plugin-bugfix-v8-static-class-fields-redefine-readonly-7.28.3.tgz", - "integrity": "sha512-b6YTX108evsvE4YgWyQ921ZAFFQm3Bn+CA3+ZXlNVnPhx+UfsVURoPjfGAPCjBgrqo30yX/C2nZGX96DxvR9Iw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly/-/plugin-bugfix-v8-static-class-fields-redefine-readonly-7.28.6.tgz", + "integrity": "sha512-a0aBScVTlNaiUe35UtfxAN7A/tehvvG4/ByO6+46VPKTRSlfnAFsgKy0FUh+qAkQrDTmhDkT+IBOKlOoMUxQ0g==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1", - "@babel/traverse": "^7.28.3" + "@babel/helper-plugin-utils": "^7.28.6", + "@babel/traverse": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -754,13 +754,13 @@ } }, "node_modules/@babel/plugin-syntax-import-assertions": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-assertions/-/plugin-syntax-import-assertions-7.27.1.tgz", - "integrity": "sha512-UT/Jrhw57xg4ILHLFnzFpPDlMbcdEicaAtjPQpbj9wa8T4r5KVWCimHcL/460g8Ht0DMxDyjsLgiWSkVjnwPFg==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-assertions/-/plugin-syntax-import-assertions-7.28.6.tgz", + "integrity": "sha512-pSJUpFHdx9z5nqTSirOCMtYVP2wFgoWhP0p3g8ONK/4IHhLIBd0B9NYqAvIUAhq+OkhO4VM1tENCt0cjlsNShw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -770,13 +770,13 @@ } }, "node_modules/@babel/plugin-syntax-import-attributes": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.27.1.tgz", - "integrity": "sha512-oFT0FrKHgF53f4vOsZGi2Hh3I35PfSmVs4IBFLFj4dnafP+hIWDLg3VyKmUHfLoLHlyxY4C7DGtmHuJgn+IGww==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.28.6.tgz", + "integrity": "sha512-jiLC0ma9XkQT3TKJ9uYvlakm66Pamywo+qwL+oL8HJOvc6TWdZXVfhqJr8CCzbSGUAbDOzlGHJC1U+vRfLQDvw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -987,15 +987,15 @@ } }, "node_modules/@babel/plugin-transform-async-generator-functions": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-7.28.0.tgz", - "integrity": "sha512-BEOdvX4+M765icNPZeidyADIvQ1m1gmunXufXxvRESy/jNNyfovIqUyE7MVgGBjWktCoJlzvFA1To2O4ymIO3Q==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-7.29.0.tgz", + "integrity": "sha512-va0VdWro4zlBr2JsXC+ofCPB2iG12wPtVGTWFx2WLDOM3nYQZZIGP82qku2eW/JR83sD+k2k+CsNtyEbUqhU6w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-plugin-utils": "^7.28.6", "@babel/helper-remap-async-to-generator": "^7.27.1", - "@babel/traverse": "^7.28.0" + "@babel/traverse": "^7.29.0" }, "engines": { "node": ">=6.9.0" @@ -1005,14 +1005,14 @@ } }, "node_modules/@babel/plugin-transform-async-to-generator": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.27.1.tgz", - "integrity": "sha512-NREkZsZVJS4xmTr8qzE5y8AfIPqsdQfRuUiLRTEzb7Qii8iFWCyDKaUV2c0rCuh4ljDZ98ALHP/PetiBV2nddA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.28.6.tgz", + "integrity": "sha512-ilTRcmbuXjsMmcZ3HASTe4caH5Tpo93PkTxF9oG2VZsSWsahydmcEHhix9Ik122RcTnZnUzPbmux4wh1swfv7g==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-module-imports": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-module-imports": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", "@babel/helper-remap-async-to-generator": "^7.27.1" }, "engines": { @@ -1039,13 +1039,13 @@ } }, "node_modules/@babel/plugin-transform-block-scoping": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.28.5.tgz", - "integrity": "sha512-45DmULpySVvmq9Pj3X9B+62Xe+DJGov27QravQJU1LLcapR6/10i+gYVAucGGJpHBp5mYxIMK4nDAT/QDLr47g==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.28.6.tgz", + "integrity": "sha512-tt/7wOtBmwHPNMPu7ax4pdPz6shjFrmHDghvNC+FG9Qvj7D6mJcoRQIF5dy4njmxR941l6rgtvfSB2zX3VlUIw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1055,14 +1055,14 @@ } }, "node_modules/@babel/plugin-transform-class-properties": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-7.27.1.tgz", - "integrity": "sha512-D0VcalChDMtuRvJIu3U/fwWjf8ZMykz5iZsg77Nuj821vCKI3zCyRLwRdWbsuJ/uRwZhZ002QtCqIkwC/ZkvbA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-7.28.6.tgz", + "integrity": "sha512-dY2wS3I2G7D697VHndN91TJr8/AAfXQNt5ynCTI/MpxMsSzHp+52uNivYT5wCPax3whc47DR8Ba7cmlQMg24bw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-class-features-plugin": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1072,14 +1072,14 @@ } }, "node_modules/@babel/plugin-transform-class-static-block": { - "version": "7.28.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-static-block/-/plugin-transform-class-static-block-7.28.3.tgz", - "integrity": "sha512-LtPXlBbRoc4Njl/oh1CeD/3jC+atytbnf/UqLoqTDcEYGUPj022+rvfkbDYieUrSj3CaV4yHDByPE+T2HwfsJg==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-static-block/-/plugin-transform-class-static-block-7.28.6.tgz", + "integrity": "sha512-rfQ++ghVwTWTqQ7w8qyDxL1XGihjBss4CmTgGRCTAC9RIbhVpyp4fOeZtta0Lbf+dTNIVJer6ych2ibHwkZqsQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.28.3", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-class-features-plugin": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1089,18 +1089,18 @@ } }, "node_modules/@babel/plugin-transform-classes": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.28.4.tgz", - "integrity": "sha512-cFOlhIYPBv/iBoc+KS3M6et2XPtbT2HiCRfBXWtfpc9OAyostldxIf9YAYB6ypURBBbx+Qv6nyrLzASfJe+hBA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.28.6.tgz", + "integrity": "sha512-EF5KONAqC5zAqT783iMGuM2ZtmEBy+mJMOKl2BCvPZ2lVrwvXnB6o+OBWCS+CoeCCpVRF2sA2RBKUxvT8tQT5Q==", "dev": true, "license": "MIT", "dependencies": { "@babel/helper-annotate-as-pure": "^7.27.3", - "@babel/helper-compilation-targets": "^7.27.2", + "@babel/helper-compilation-targets": "^7.28.6", "@babel/helper-globals": "^7.28.0", - "@babel/helper-plugin-utils": "^7.27.1", - "@babel/helper-replace-supers": "^7.27.1", - "@babel/traverse": "^7.28.4" + "@babel/helper-plugin-utils": "^7.28.6", + "@babel/helper-replace-supers": "^7.28.6", + "@babel/traverse": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1110,14 +1110,14 @@ } }, "node_modules/@babel/plugin-transform-computed-properties": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.27.1.tgz", - "integrity": "sha512-lj9PGWvMTVksbWiDT2tW68zGS/cyo4AkZ/QTp0sQT0mjPopCmrSkzxeXkznjqBxzDI6TclZhOJbBmbBLjuOZUw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.28.6.tgz", + "integrity": "sha512-bcc3k0ijhHbc2lEfpFHgx7eYw9KNXqOerKWfzbxEHUGKnS3sz9C4CNL9OiFN1297bDNfUiSO7DaLzbvHQQQ1BQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1", - "@babel/template": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6", + "@babel/template": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1144,14 +1144,14 @@ } }, "node_modules/@babel/plugin-transform-dotall-regex": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.27.1.tgz", - "integrity": "sha512-gEbkDVGRvjj7+T1ivxrfgygpT7GUd4vmODtYpbs0gZATdkX8/iSnOtZSxiZnsgm1YjTgjI6VKBGSJJevkrclzw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.28.6.tgz", + "integrity": "sha512-SljjowuNKB7q5Oayv4FoPzeB74g3QgLt8IVJw9ADvWy3QnUb/01aw8I4AVv8wYnPvQz2GDDZ/g3GhcNyDBI4Bg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-regexp-features-plugin": "^7.28.5", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1177,14 +1177,14 @@ } }, "node_modules/@babel/plugin-transform-duplicate-named-capturing-groups-regex": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-named-capturing-groups-regex/-/plugin-transform-duplicate-named-capturing-groups-regex-7.27.1.tgz", - "integrity": "sha512-hkGcueTEzuhB30B3eJCbCYeCaaEQOmQR0AdvzpD4LoN0GXMWzzGSuRrxR2xTnCrvNbVwK9N6/jQ92GSLfiZWoQ==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-named-capturing-groups-regex/-/plugin-transform-duplicate-named-capturing-groups-regex-7.29.0.tgz", + "integrity": "sha512-zBPcW2lFGxdiD8PUnPwJjag2J9otbcLQzvbiOzDxpYXyCuYX9agOwMPGn1prVH0a4qzhCKu24rlH4c1f7yA8rw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-regexp-features-plugin": "^7.28.5", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1210,14 +1210,14 @@ } }, "node_modules/@babel/plugin-transform-explicit-resource-management": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-explicit-resource-management/-/plugin-transform-explicit-resource-management-7.28.0.tgz", - "integrity": "sha512-K8nhUcn3f6iB+P3gwCv/no7OdzOZQcKchW6N389V6PD8NUWKZHzndOd9sPDVbMoBsbmjMqlB4L9fm+fEFNVlwQ==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-explicit-resource-management/-/plugin-transform-explicit-resource-management-7.28.6.tgz", + "integrity": "sha512-Iao5Konzx2b6g7EPqTy40UZbcdXE126tTxVFr/nAIj+WItNxjKSYTEw3RC+A2/ZetmdJsgueL1KhaMCQHkLPIg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1", - "@babel/plugin-transform-destructuring": "^7.28.0" + "@babel/helper-plugin-utils": "^7.28.6", + "@babel/plugin-transform-destructuring": "^7.28.5" }, "engines": { "node": ">=6.9.0" @@ -1227,13 +1227,13 @@ } }, "node_modules/@babel/plugin-transform-exponentiation-operator": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.28.5.tgz", - "integrity": "sha512-D4WIMaFtwa2NizOp+dnoFjRez/ClKiC2BqqImwKd1X28nqBtZEyCYJ2ozQrrzlxAFrcrjxo39S6khe9RNDlGzw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.28.6.tgz", + "integrity": "sha512-WitabqiGjV/vJ0aPOLSFfNY1u9U3R7W36B03r5I2KoNix+a3sOhJ3pKFB3R5It9/UiK78NiO0KE9P21cMhlPkw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1294,13 +1294,13 @@ } }, "node_modules/@babel/plugin-transform-json-strings": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-json-strings/-/plugin-transform-json-strings-7.27.1.tgz", - "integrity": "sha512-6WVLVJiTjqcQauBhn1LkICsR2H+zm62I3h9faTDKt1qP4jn2o72tSvqMwtGFKGTpojce0gJs+76eZ2uCHRZh0Q==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-json-strings/-/plugin-transform-json-strings-7.28.6.tgz", + "integrity": "sha512-Nr+hEN+0geQkzhbdgQVPoqr47lZbm+5fCUmO70722xJZd0Mvb59+33QLImGj6F+DkK3xgDi1YVysP8whD6FQAw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1326,13 +1326,13 @@ } }, "node_modules/@babel/plugin-transform-logical-assignment-operators": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-logical-assignment-operators/-/plugin-transform-logical-assignment-operators-7.28.5.tgz", - "integrity": "sha512-axUuqnUTBuXyHGcJEVVh9pORaN6wC5bYfE7FGzPiaWa3syib9m7g+/IT/4VgCOe2Upef43PHzeAvcrVek6QuuA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-logical-assignment-operators/-/plugin-transform-logical-assignment-operators-7.28.6.tgz", + "integrity": "sha512-+anKKair6gpi8VsM/95kmomGNMD0eLz1NQ8+Pfw5sAwWH9fGYXT50E55ZpV0pHUHWf6IUTWPM+f/7AAff+wr9A==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1375,14 +1375,14 @@ } }, "node_modules/@babel/plugin-transform-modules-commonjs": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.27.1.tgz", - "integrity": "sha512-OJguuwlTYlN0gBZFRPqwOGNWssZjfIUdS7HMYtN8c1KmwpwHFBwTeFZrg9XZa+DFTitWOW5iTAG7tyCUPsCCyw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.28.6.tgz", + "integrity": "sha512-jppVbf8IV9iWWwWTQIxJMAJCWBuuKx71475wHwYytrRGQ2CWiDvYlADQno3tcYpS/T2UUWFQp3nVtYfK/YBQrA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-module-transforms": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1392,16 +1392,16 @@ } }, "node_modules/@babel/plugin-transform-modules-systemjs": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.28.5.tgz", - "integrity": "sha512-vn5Jma98LCOeBy/KpeQhXcV2WZgaRUtjwQmjoBuLNlOmkg0fB5pdvYVeWRYI69wWKwK2cD1QbMiUQnoujWvrew==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.29.0.tgz", + "integrity": "sha512-PrujnVFbOdUpw4UHiVwKvKRLMMic8+eC0CuNlxjsyZUiBjhFdPsewdXCkveh2KqBA9/waD0W1b4hXSOBQJezpQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-module-transforms": "^7.28.3", - "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", "@babel/helper-validator-identifier": "^7.28.5", - "@babel/traverse": "^7.28.5" + "@babel/traverse": "^7.29.0" }, "engines": { "node": ">=6.9.0" @@ -1428,14 +1428,14 @@ } }, "node_modules/@babel/plugin-transform-named-capturing-groups-regex": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.27.1.tgz", - "integrity": "sha512-SstR5JYy8ddZvD6MhV0tM/j16Qds4mIpJTOd1Yu9J9pJjH93bxHECF7pgtc28XvkzTD6Pxcm/0Z73Hvk7kb3Ng==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.29.0.tgz", + "integrity": "sha512-1CZQA5KNAD6ZYQLPw7oi5ewtDNxH/2vuCh+6SmvgDfhumForvs8a1o9n0UrEoBD8HU4djO2yWngTQlXl1NDVEQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-regexp-features-plugin": "^7.28.5", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1461,13 +1461,13 @@ } }, "node_modules/@babel/plugin-transform-nullish-coalescing-operator": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-7.27.1.tgz", - "integrity": "sha512-aGZh6xMo6q9vq1JGcw58lZ1Z0+i0xB2x0XaauNIUXd6O1xXc3RwoWEBlsTQrY4KQ9Jf0s5rgD6SiNkaUdJegTA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-7.28.6.tgz", + "integrity": "sha512-3wKbRgmzYbw24mDJXT7N+ADXw8BC/imU9yo9c9X9NKaLF1fW+e5H1U5QjMUBe4Qo4Ox/o++IyUkl1sVCLgevKg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1477,13 +1477,13 @@ } }, "node_modules/@babel/plugin-transform-numeric-separator": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-numeric-separator/-/plugin-transform-numeric-separator-7.27.1.tgz", - "integrity": "sha512-fdPKAcujuvEChxDBJ5c+0BTaS6revLV7CJL08e4m3de8qJfNIuCc2nc7XJYOjBoTMJeqSmwXJ0ypE14RCjLwaw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-numeric-separator/-/plugin-transform-numeric-separator-7.28.6.tgz", + "integrity": "sha512-SJR8hPynj8outz+SlStQSwvziMN4+Bq99it4tMIf5/Caq+3iOc0JtKyse8puvyXkk3eFRIA5ID/XfunGgO5i6w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1509,17 +1509,17 @@ } }, "node_modules/@babel/plugin-transform-object-rest-spread": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-rest-spread/-/plugin-transform-object-rest-spread-7.28.4.tgz", - "integrity": "sha512-373KA2HQzKhQCYiRVIRr+3MjpCObqzDlyrM6u4I201wL8Mp2wHf7uB8GhDwis03k2ti8Zr65Zyyqs1xOxUF/Ew==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-rest-spread/-/plugin-transform-object-rest-spread-7.28.6.tgz", + "integrity": "sha512-5rh+JR4JBC4pGkXLAcYdLHZjXudVxWMXbB6u6+E9lRL5TrGVbHt1TjxGbZ8CkmYw9zjkB7jutzOROArsqtncEA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-compilation-targets": "^7.27.2", - "@babel/helper-plugin-utils": "^7.27.1", - "@babel/plugin-transform-destructuring": "^7.28.0", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", + "@babel/plugin-transform-destructuring": "^7.28.5", "@babel/plugin-transform-parameters": "^7.27.7", - "@babel/traverse": "^7.28.4" + "@babel/traverse": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1546,13 +1546,13 @@ } }, "node_modules/@babel/plugin-transform-optional-catch-binding": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-catch-binding/-/plugin-transform-optional-catch-binding-7.27.1.tgz", - "integrity": "sha512-txEAEKzYrHEX4xSZN4kJ+OfKXFVSWKB2ZxM9dpcE3wT7smwkNmXo5ORRlVzMVdJbD+Q8ILTgSD7959uj+3Dm3Q==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-catch-binding/-/plugin-transform-optional-catch-binding-7.28.6.tgz", + "integrity": "sha512-R8ja/Pyrv0OGAvAXQhSTmWyPJPml+0TMqXlO5w+AsMEiwb2fg3WkOvob7UxFSL3OIttFSGSRFKQsOhJ/X6HQdQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1562,13 +1562,13 @@ } }, "node_modules/@babel/plugin-transform-optional-chaining": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-7.28.5.tgz", - "integrity": "sha512-N6fut9IZlPnjPwgiQkXNhb+cT8wQKFlJNqcZkWlcTqkcqx6/kU4ynGmLFoa4LViBSirn05YAwk+sQBbPfxtYzQ==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-7.28.6.tgz", + "integrity": "sha512-A4zobikRGJTsX9uqVFdafzGkqD30t26ck2LmOzAuLL8b2x6k3TIqRiT2xVvA9fNmFeTX484VpsdgmKNA0bS23w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-plugin-utils": "^7.28.6", "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1" }, "engines": { @@ -1595,14 +1595,14 @@ } }, "node_modules/@babel/plugin-transform-private-methods": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-7.27.1.tgz", - "integrity": "sha512-10FVt+X55AjRAYI9BrdISN9/AQWHqldOeZDUoLyif1Kn05a56xVBXb8ZouL8pZ9jem8QpXaOt8TS7RHUIS+GPA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-7.28.6.tgz", + "integrity": "sha512-piiuapX9CRv7+0st8lmuUlRSmX6mBcVeNQ1b4AYzJxfCMuBfB0vBXDiGSmm03pKJw1v6cZ8KSeM+oUnM6yAExg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-class-features-plugin": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1612,15 +1612,15 @@ } }, "node_modules/@babel/plugin-transform-private-property-in-object": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-7.27.1.tgz", - "integrity": "sha512-5J+IhqTi1XPa0DXF83jYOaARrX+41gOewWbkPyjMNRDqgOCqdffGh8L3f/Ek5utaEBZExjSAzcyjmV9SSAWObQ==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-7.28.6.tgz", + "integrity": "sha512-b97jvNSOb5+ehyQmBpmhOCiUC5oVK4PMnpRvO7+ymFBoqYjeDHIU9jnrNUuwHOiL9RpGDoKBpSViarV+BU+eVA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-annotate-as-pure": "^7.27.1", - "@babel/helper-create-class-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-annotate-as-pure": "^7.27.3", + "@babel/helper-create-class-features-plugin": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1646,13 +1646,13 @@ } }, "node_modules/@babel/plugin-transform-regenerator": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.28.4.tgz", - "integrity": "sha512-+ZEdQlBoRg9m2NnzvEeLgtvBMO4tkFBw5SQIUgLICgTrumLoU7lr+Oghi6km2PFj+dbUt2u1oby2w3BDO9YQnA==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.29.0.tgz", + "integrity": "sha512-FijqlqMA7DmRdg/aINBSs04y8XNTYw/lr1gJ2WsmBnnaNw1iS43EPkJW+zK7z65auG3AWRFXWj+NcTQwYptUog==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1662,14 +1662,14 @@ } }, "node_modules/@babel/plugin-transform-regexp-modifiers": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regexp-modifiers/-/plugin-transform-regexp-modifiers-7.27.1.tgz", - "integrity": "sha512-TtEciroaiODtXvLZv4rmfMhkCv8jx3wgKpL68PuiPh2M4fvz5jhsA7697N1gMvkvr/JTF13DrFYyEbY9U7cVPA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regexp-modifiers/-/plugin-transform-regexp-modifiers-7.28.6.tgz", + "integrity": "sha512-QGWAepm9qxpaIs7UM9FvUSnCGlb8Ua1RhyM4/veAxLwt3gMat/LSGrZixyuj4I6+Kn9iwvqCyPTtbdxanYoWYg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-regexp-features-plugin": "^7.28.5", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1732,13 +1732,13 @@ } }, "node_modules/@babel/plugin-transform-spread": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.27.1.tgz", - "integrity": "sha512-kpb3HUqaILBJcRFVhFUs6Trdd4mkrzcGXss+6/mxUd273PfbWqSDHRzMT2234gIg2QYfAjvXLSquP1xECSg09Q==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.28.6.tgz", + "integrity": "sha512-9U4QObUC0FtJl05AsUcodau/RWDytrU6uKgkxu09mLR9HLDAtUMoPuuskm5huQsoktmsYpI+bGmq+iapDcriKA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-plugin-utils": "^7.28.6", "@babel/helper-skip-transparent-expression-wrappers": "^7.27.1" }, "engines": { @@ -1813,14 +1813,14 @@ } }, "node_modules/@babel/plugin-transform-unicode-property-regex": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-property-regex/-/plugin-transform-unicode-property-regex-7.27.1.tgz", - "integrity": "sha512-uW20S39PnaTImxp39O5qFlHLS9LJEmANjMG7SxIhap8rCHqu0Ik+tLEPX5DKmHn6CsWQ7j3lix2tFOa5YtL12Q==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-property-regex/-/plugin-transform-unicode-property-regex-7.28.6.tgz", + "integrity": "sha512-4Wlbdl/sIZjzi/8St0evF0gEZrgOswVO6aOzqxh1kDZOl9WmLrHq2HtGhnOJZmHZYKP8WZ1MDLCt5DAWwRo57A==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-regexp-features-plugin": "^7.28.5", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1847,14 +1847,14 @@ } }, "node_modules/@babel/plugin-transform-unicode-sets-regex": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-7.27.1.tgz", - "integrity": "sha512-EtkOujbc4cgvb0mlpQefi4NTPBzhSIevblFevACNLUspmrALgmEBdL/XfnyyITfd8fKBZrZys92zOWcik7j9Tw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-7.28.6.tgz", + "integrity": "sha512-/wHc/paTUmsDYN7SZkpWxogTOBNnlx7nBQYfy6JJlCT7G3mVhltk3e++N7zV0XfgGsrqBxd4rJQt9H16I21Y1Q==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.27.1", - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-create-regexp-features-plugin": "^7.28.5", + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -1864,81 +1864,81 @@ } }, "node_modules/@babel/preset-env": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.28.5.tgz", - "integrity": "sha512-S36mOoi1Sb6Fz98fBfE+UZSpYw5mJm0NUHtIKrOuNcqeFauy1J6dIvXm2KRVKobOSaGq4t/hBXdN4HGU3wL9Wg==", + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.29.2.tgz", + "integrity": "sha512-DYD23veRYGvBFhcTY1iUvJnDNpuqNd/BzBwCvzOTKUnJjKg5kpUBh3/u9585Agdkgj+QuygG7jLfOPWMa2KVNw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/compat-data": "^7.28.5", - "@babel/helper-compilation-targets": "^7.27.2", - "@babel/helper-plugin-utils": "^7.27.1", + "@babel/compat-data": "^7.29.0", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", "@babel/helper-validator-option": "^7.27.1", "@babel/plugin-bugfix-firefox-class-in-computed-class-key": "^7.28.5", "@babel/plugin-bugfix-safari-class-field-initializer-scope": "^7.27.1", "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^7.27.1", "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^7.27.1", - "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": "^7.28.3", + "@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly": "^7.28.6", "@babel/plugin-proposal-private-property-in-object": "7.21.0-placeholder-for-preset-env.2", - "@babel/plugin-syntax-import-assertions": "^7.27.1", - "@babel/plugin-syntax-import-attributes": "^7.27.1", + "@babel/plugin-syntax-import-assertions": "^7.28.6", + "@babel/plugin-syntax-import-attributes": "^7.28.6", "@babel/plugin-syntax-unicode-sets-regex": "^7.18.6", "@babel/plugin-transform-arrow-functions": "^7.27.1", - "@babel/plugin-transform-async-generator-functions": "^7.28.0", - "@babel/plugin-transform-async-to-generator": "^7.27.1", + "@babel/plugin-transform-async-generator-functions": "^7.29.0", + "@babel/plugin-transform-async-to-generator": "^7.28.6", "@babel/plugin-transform-block-scoped-functions": "^7.27.1", - "@babel/plugin-transform-block-scoping": "^7.28.5", - "@babel/plugin-transform-class-properties": "^7.27.1", - "@babel/plugin-transform-class-static-block": "^7.28.3", - "@babel/plugin-transform-classes": "^7.28.4", - "@babel/plugin-transform-computed-properties": "^7.27.1", + "@babel/plugin-transform-block-scoping": "^7.28.6", + "@babel/plugin-transform-class-properties": "^7.28.6", + "@babel/plugin-transform-class-static-block": "^7.28.6", + "@babel/plugin-transform-classes": "^7.28.6", + "@babel/plugin-transform-computed-properties": "^7.28.6", "@babel/plugin-transform-destructuring": "^7.28.5", - "@babel/plugin-transform-dotall-regex": "^7.27.1", + "@babel/plugin-transform-dotall-regex": "^7.28.6", "@babel/plugin-transform-duplicate-keys": "^7.27.1", - "@babel/plugin-transform-duplicate-named-capturing-groups-regex": "^7.27.1", + "@babel/plugin-transform-duplicate-named-capturing-groups-regex": "^7.29.0", "@babel/plugin-transform-dynamic-import": "^7.27.1", - "@babel/plugin-transform-explicit-resource-management": "^7.28.0", - "@babel/plugin-transform-exponentiation-operator": "^7.28.5", + "@babel/plugin-transform-explicit-resource-management": "^7.28.6", + "@babel/plugin-transform-exponentiation-operator": "^7.28.6", "@babel/plugin-transform-export-namespace-from": "^7.27.1", "@babel/plugin-transform-for-of": "^7.27.1", "@babel/plugin-transform-function-name": "^7.27.1", - "@babel/plugin-transform-json-strings": "^7.27.1", + "@babel/plugin-transform-json-strings": "^7.28.6", "@babel/plugin-transform-literals": "^7.27.1", - "@babel/plugin-transform-logical-assignment-operators": "^7.28.5", + "@babel/plugin-transform-logical-assignment-operators": "^7.28.6", "@babel/plugin-transform-member-expression-literals": "^7.27.1", "@babel/plugin-transform-modules-amd": "^7.27.1", - "@babel/plugin-transform-modules-commonjs": "^7.27.1", - "@babel/plugin-transform-modules-systemjs": "^7.28.5", + "@babel/plugin-transform-modules-commonjs": "^7.28.6", + "@babel/plugin-transform-modules-systemjs": "^7.29.0", "@babel/plugin-transform-modules-umd": "^7.27.1", - "@babel/plugin-transform-named-capturing-groups-regex": "^7.27.1", + "@babel/plugin-transform-named-capturing-groups-regex": "^7.29.0", "@babel/plugin-transform-new-target": "^7.27.1", - "@babel/plugin-transform-nullish-coalescing-operator": "^7.27.1", - "@babel/plugin-transform-numeric-separator": "^7.27.1", - "@babel/plugin-transform-object-rest-spread": "^7.28.4", + "@babel/plugin-transform-nullish-coalescing-operator": "^7.28.6", + "@babel/plugin-transform-numeric-separator": "^7.28.6", + "@babel/plugin-transform-object-rest-spread": "^7.28.6", "@babel/plugin-transform-object-super": "^7.27.1", - "@babel/plugin-transform-optional-catch-binding": "^7.27.1", - "@babel/plugin-transform-optional-chaining": "^7.28.5", + "@babel/plugin-transform-optional-catch-binding": "^7.28.6", + "@babel/plugin-transform-optional-chaining": "^7.28.6", "@babel/plugin-transform-parameters": "^7.27.7", - "@babel/plugin-transform-private-methods": "^7.27.1", - "@babel/plugin-transform-private-property-in-object": "^7.27.1", + "@babel/plugin-transform-private-methods": "^7.28.6", + "@babel/plugin-transform-private-property-in-object": "^7.28.6", "@babel/plugin-transform-property-literals": "^7.27.1", - "@babel/plugin-transform-regenerator": "^7.28.4", - "@babel/plugin-transform-regexp-modifiers": "^7.27.1", + "@babel/plugin-transform-regenerator": "^7.29.0", + "@babel/plugin-transform-regexp-modifiers": "^7.28.6", "@babel/plugin-transform-reserved-words": "^7.27.1", "@babel/plugin-transform-shorthand-properties": "^7.27.1", - "@babel/plugin-transform-spread": "^7.27.1", + "@babel/plugin-transform-spread": "^7.28.6", "@babel/plugin-transform-sticky-regex": "^7.27.1", "@babel/plugin-transform-template-literals": "^7.27.1", "@babel/plugin-transform-typeof-symbol": "^7.27.1", "@babel/plugin-transform-unicode-escapes": "^7.27.1", - "@babel/plugin-transform-unicode-property-regex": "^7.27.1", + "@babel/plugin-transform-unicode-property-regex": "^7.28.6", "@babel/plugin-transform-unicode-regex": "^7.27.1", - "@babel/plugin-transform-unicode-sets-regex": "^7.27.1", + "@babel/plugin-transform-unicode-sets-regex": "^7.28.6", "@babel/preset-modules": "0.1.6-no-external-plugins", - "babel-plugin-polyfill-corejs2": "^0.4.14", - "babel-plugin-polyfill-corejs3": "^0.13.0", - "babel-plugin-polyfill-regenerator": "^0.6.5", - "core-js-compat": "^3.43.0", + "babel-plugin-polyfill-corejs2": "^0.4.15", + "babel-plugin-polyfill-corejs3": "^0.14.0", + "babel-plugin-polyfill-regenerator": "^0.6.6", + "core-js-compat": "^3.48.0", "semver": "^6.3.1" }, "engines": { @@ -1948,6 +1948,20 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/preset-env/node_modules/babel-plugin-polyfill-corejs3": { + "version": "0.14.2", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.14.2.tgz", + "integrity": "sha512-coWpDLJ410R781Npmn/SIBZEsAetR4xVi0SxLMXPaMO4lSf1MwnkGYMtkFxew0Dn8B3/CpbpYxN0JCgg8mn67g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-define-polyfill-provider": "^0.6.8", + "core-js-compat": "^3.48.0" + }, + "peerDependencies": { + "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" + } + }, "node_modules/@babel/preset-modules": { "version": "0.1.6-no-external-plugins", "resolved": "https://registry.npmjs.org/@babel/preset-modules/-/preset-modules-0.1.6-no-external-plugins.tgz", @@ -6883,14 +6897,14 @@ } }, "node_modules/babel-plugin-polyfill-corejs2": { - "version": "0.4.14", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.14.tgz", - "integrity": "sha512-Co2Y9wX854ts6U8gAAPXfn0GmAyctHuK8n0Yhfjd6t30g7yvKjspvvOo9yG+z52PZRgFErt7Ka2pYnXCjLKEpg==", + "version": "0.4.17", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.17.tgz", + "integrity": "sha512-aTyf30K/rqAsNwN76zYrdtx8obu0E4KoUME29B1xj+B3WxgvWkp943vYQ+z8Mv3lw9xHXMHpvSPOBxzAkIa94w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/compat-data": "^7.27.7", - "@babel/helper-define-polyfill-provider": "^0.6.5", + "@babel/compat-data": "^7.28.6", + "@babel/helper-define-polyfill-provider": "^0.6.8", "semver": "^6.3.1" }, "peerDependencies": { @@ -6912,13 +6926,13 @@ } }, "node_modules/babel-plugin-polyfill-regenerator": { - "version": "0.6.5", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.6.5.tgz", - "integrity": "sha512-ISqQ2frbiNU9vIJkzg7dlPpznPZ4jOiUQ1uSmB0fEHeowtN3COYRsXr/xexn64NpU13P06jc/L5TgiJXOgrbEg==", + "version": "0.6.8", + "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.6.8.tgz", + "integrity": "sha512-M762rNHfSF1EV3SLtnCJXFoQbbIIz0OyRwnCmV0KPC7qosSfCO0QLTSuJX3ayAebubhE6oYBAYPrBA5ljowaZg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-define-polyfill-provider": "^0.6.5" + "@babel/helper-define-polyfill-provider": "^0.6.8" }, "peerDependencies": { "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" @@ -9395,13 +9409,13 @@ } }, "node_modules/core-js-compat": { - "version": "3.45.1", - "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.45.1.tgz", - "integrity": "sha512-tqTt5T4PzsMIZ430XGviK4vzYSoeNJ6CXODi6c/voxOT6IZqBht5/EKaSNnYiEjjRYxjVz7DQIsOsY0XNi8PIA==", + "version": "3.49.0", + "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.49.0.tgz", + "integrity": "sha512-VQXt1jr9cBz03b331DFDCCP90b3fanciLkgiOoy8SBHy06gNf+vQ1A3WFLqG7I8TipYIKeYK9wxd0tUrvHcOZA==", "dev": true, "license": "MIT", "dependencies": { - "browserslist": "^4.25.3" + "browserslist": "^4.28.1" }, "funding": { "type": "opencollective", @@ -20562,13 +20576,14 @@ "license": "MIT" }, "node_modules/resolve": { - "version": "1.22.10", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz", - "integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", + "version": "1.22.12", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", + "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", "dev": true, "license": "MIT", "dependencies": { - "is-core-module": "^2.16.0", + "es-errors": "^1.3.0", + "is-core-module": "^2.16.1", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, diff --git a/package.json b/package.json index 6f71d9a0ca..a87a988b46 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ }, "license": "MIT", "author": "Tobias Koppers @sokra", + "type": "module", "main": "lib/Server.js", "types": "types/lib/Server.d.ts", "bin": "bin/webpack-dev-server.js", @@ -76,7 +77,7 @@ "@babel/eslint-parser": "^7.28.6", "@babel/plugin-transform-object-assign": "^7.27.1", "@babel/plugin-transform-runtime": "^7.29.0", - "@babel/preset-env": "^7.25.9", + "@babel/preset-env": "^7.29.2", "@babel/runtime": "^7.29.2", "@commitlint/cli": "^19.5.0", "@commitlint/config-conventional": "^19.5.0", diff --git a/scripts/extend-webpack-types.js b/scripts/extend-webpack-types.js index 36a811a933..5125aa55ed 100644 --- a/scripts/extend-webpack-types.js +++ b/scripts/extend-webpack-types.js @@ -1,13 +1,15 @@ -"use strict"; - -const path = require("node:path"); -const fs = require("graceful-fs"); +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import fs from "graceful-fs"; /** * @returns {Promise} */ async function extendTypes() { - const typesPath = path.resolve(__dirname, "../types/lib/Server.d.ts"); + const typesPath = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + "../types/lib/Server.d.ts", + ); const content = await fs.promises.readFile(typesPath, "utf8"); const newContent = `${content} // DO NOT REMOVE THIS! @@ -26,10 +28,4 @@ declare module "webpack" { await fs.promises.writeFile(typesPath, newContent); } -// eslint-disable-next-line unicorn/prefer-top-level-await -Promise.resolve().then( - () => extendTypes(), - (error) => { - throw error; - }, -); +await extendTypes(); diff --git a/tsconfig.json b/tsconfig.json index a28baacbf5..f8f19ec5cb 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,14 +1,16 @@ { "compilerOptions": { - "target": "ES2017", - "module": "commonjs", - "lib": ["es2017", "dom"], + "target": "ES2022", + "module": "nodenext", + "moduleResolution": "nodenext", + "lib": ["es2022", "dom"], "allowJs": true, "checkJs": true, "strict": true, "types": ["node"], "resolveJsonModule": true, - "allowSyntheticDefaultImports": true + "allowSyntheticDefaultImports": true, + "esModuleInterop": true }, "include": ["./bin/**/*", "./lib/**/*"] } diff --git a/types/lib/Server.d.ts b/types/lib/Server.d.ts index 80a7fbe2df..678da2b5b1 100644 --- a/types/lib/Server.d.ts +++ b/types/lib/Server.d.ts @@ -1,4 +1,340 @@ -export = Server; +export default Server; +export type Schema = import("schema-utils").Schema; +export type Compiler = import("webpack").Compiler; +export type MultiCompiler = import("webpack").MultiCompiler; +export type WebpackConfiguration = import("webpack").Configuration; +export type StatsOptions = import("webpack").StatsOptions; +export type StatsCompilation = import("webpack").StatsCompilation; +export type Stats = import("webpack").Stats; +export type MultiStats = import("webpack").MultiStats; +export type NetworkInterfaceInfo = import("os").NetworkInterfaceInfo; +export type WatchOptions = import("chokidar").ChokidarOptions; +export type FSWatcher = import("chokidar").FSWatcher; +export type ConnectHistoryApiFallbackOptions = + import("connect-history-api-fallback").Options; +export type Bonjour = import("bonjour-service").Bonjour; +export type BonjourOptions = import("bonjour-service").Service; +export type RequestHandler = import("http-proxy-middleware").RequestHandler; +export type HttpProxyMiddlewareOptions = + import("http-proxy-middleware").Options; +export type HttpProxyMiddlewareOptionsFilter = + import("http-proxy-middleware").Filter; +export type ServeIndexOptions = import("serve-index").Options; +export type ServeStaticOptions = import("serve-static").ServeStaticOptions; +export type IPv4 = import("ipaddr.js").IPv4; +export type IPv6 = import("ipaddr.js").IPv6; +export type Socket = import("net").Socket; +export type HTTPServer = import("http").Server; +export type IncomingMessage = import("http").IncomingMessage; +export type ServerResponse = import("http").ServerResponse; +export type OpenOptions = import("open").Options; +export type ExpressApplication = import("express").Application; +export type ExpressRequestHandler = import("express").RequestHandler; +export type ExpressErrorRequestHandler = import("express").ErrorRequestHandler; +export type ExpressRequest = import("express").Request; +export type ExpressResponse = import("express").Response; +export type EXPECTED_ANY = any; +export type NextFunction = (err?: EXPECTED_ANY) => void; +export type SimpleHandleFunction = ( + req: IncomingMessage, + res: ServerResponse, +) => void; +export type NextHandleFunction = ( + req: IncomingMessage, + res: ServerResponse, + next: NextFunction, +) => void; +export type ErrorHandleFunction = ( + err: EXPECTED_ANY, + req: IncomingMessage, + res: ServerResponse, + next: NextFunction, +) => void; +export type HandleFunction = + | SimpleHandleFunction + | NextHandleFunction + | ErrorHandleFunction; +export type ServerOptions = import("https").ServerOptions; +export type Request< + T extends BasicApplication = import("express").Application, +> = T extends ExpressApplication ? ExpressRequest : IncomingMessage; +export type Response< + T extends BasicApplication = import("express").Application, +> = T extends ExpressApplication ? ExpressResponse : ServerResponse; +export type DevMiddlewareOptions< + T extends Request, + U extends Response, +> = import("webpack-dev-middleware").Options; +export type DevMiddlewareContext< + T extends Request, + U extends Response, +> = import("webpack-dev-middleware").Context; +export type Host = "local-ip" | "local-ipv4" | "local-ipv6" | string; +export type Port = number | string | "auto"; +export type WatchFiles = { + /** + * paths + */ + paths: string | string[]; + /** + * options + */ + options?: + | (WatchOptions & { + aggregateTimeout?: number; + ignored?: WatchOptions["ignored"]; + poll?: number | boolean; + }) + | undefined; +}; +export type Static = { + /** + * directory + */ + directory?: string | undefined; + /** + * public path + */ + publicPath?: (string | string[]) | undefined; + /** + * serve index + */ + serveIndex?: (boolean | ServeIndexOptions) | undefined; + /** + * static options + */ + staticOptions?: ServeStaticOptions | undefined; + /** + * watch and watch options + */ + watch?: + | ( + | boolean + | (WatchOptions & { + aggregateTimeout?: number; + ignored?: WatchOptions["ignored"]; + poll?: number | boolean; + }) + ) + | undefined; +}; +export type NormalizedStatic = { + directory: string; + publicPath: string[]; + serveIndex: false | ServeIndexOptions; + staticOptions: ServeStaticOptions; + watch: false | WatchOptions; +}; +export type ServerType< + A extends BasicApplication = import("express").Application, + S extends BasicServer = import("http").Server< + typeof import("http").IncomingMessage, + typeof import("http").ServerResponse + >, +> = + | "http" + | "https" + | "http2" + | string + | ((serverOptions: ServerOptions, application: A) => S); +export type ServerConfiguration< + A extends BasicApplication = import("express").Application, + S extends BasicServer = import("http").Server< + typeof import("http").IncomingMessage, + typeof import("http").ServerResponse + >, +> = { + /** + * type + */ + type?: ServerType | undefined; + /** + * options + */ + options?: ServerOptions | undefined; +}; +export type WebSocketServerConfiguration = { + /** + * type + */ + type?: ("ws" | string | (() => WebSocketServerConfiguration)) | undefined; + /** + * options + */ + options?: Record | undefined; +}; +export type ClientConnection = (import("ws").WebSocket & { + send: import("ws").WebSocket["send"]; + terminate: import("ws").WebSocket["terminate"]; + ping: import("ws").WebSocket["ping"]; +}) & { + isAlive?: boolean; +}; +export type WebSocketServer = import("ws").WebSocketServer & { + close: import("ws").WebSocketServer["close"]; +}; +export type WebSocketServerImplementation = { + implementation: WebSocketServer; + clients: ClientConnection[]; +}; +export type ProxyConfigArrayItem = { + path?: HttpProxyMiddlewareOptionsFilter | undefined; + context?: HttpProxyMiddlewareOptionsFilter | undefined; +} & HttpProxyMiddlewareOptions; +export type ProxyConfigArray = ( + | ProxyConfigArrayItem + | (( + req?: Request | undefined, + res?: Response | undefined, + next?: NextFunction | undefined, + ) => ProxyConfigArrayItem) +)[]; +export type OpenApp = { + name?: string | undefined; + arguments?: string[] | undefined; +}; +export type Open = { + app?: (string | string[] | OpenApp) | undefined; + /** + * target + */ + target?: (string | string[]) | undefined; +}; +export type NormalizedOpen = { + target: string; + options: import("open").Options; +}; +export type WebSocketURL = { + /** + * hostname + */ + hostname?: string | undefined; + /** + * password + */ + password?: string | undefined; + /** + * pathname + */ + pathname?: string | undefined; + /** + * port + */ + port?: (number | string) | undefined; + /** + * protocol + */ + protocol?: string | undefined; + /** + * username + */ + username?: string | undefined; +}; +export type OverlayMessageOptions = boolean | ((error: Error) => void); +export type ClientConfiguration = { + /** + * logging + */ + logging?: + | ("log" | "info" | "warn" | "error" | "none" | "verbose") + | undefined; + /** + * overlay + */ + overlay?: + | ( + | boolean + | { + warnings?: OverlayMessageOptions; + errors?: OverlayMessageOptions; + runtimeErrors?: OverlayMessageOptions; + } + ) + | undefined; + /** + * progress + */ + progress?: boolean | undefined; + /** + * reconnect + */ + reconnect?: (boolean | number) | undefined; + /** + * web socket transport + */ + webSocketTransport?: ("ws" | string) | undefined; + /** + * web socket URL + */ + webSocketURL?: (string | WebSocketURL) | undefined; +}; +export type Headers = + | Array<{ + key: string; + value: string; + }> + | Record; +export type MiddlewareHandler< + T extends BasicApplication = import("express").Application, +> = T extends ExpressApplication + ? ExpressRequestHandler | ExpressErrorRequestHandler + : HandleFunction; +export type MiddlewareObject = { + name?: string; + path?: string; + middleware: MiddlewareHandler; +}; +export type Middleware = MiddlewareObject | MiddlewareHandler; +export type BasicServer = import("net").Server | import("tls").Server; +export type Configuration< + A extends BasicApplication = import("express").Application, + S extends BasicServer = import("http").Server< + typeof import("http").IncomingMessage, + typeof import("http").ServerResponse + >, +> = { + ipc?: (boolean | string) | undefined; + host?: Host | undefined; + port?: Port | undefined; + hot?: (boolean | "only") | undefined; + liveReload?: boolean | undefined; + devMiddleware?: DevMiddlewareOptions | undefined; + compress?: boolean | undefined; + allowedHosts?: ("auto" | "all" | string | string[]) | undefined; + historyApiFallback?: (boolean | ConnectHistoryApiFallbackOptions) | undefined; + bonjour?: (boolean | Record | BonjourOptions) | undefined; + watchFiles?: + | (string | string[] | WatchFiles | Array) + | undefined; + static?: (boolean | string | Static | Array) | undefined; + server?: (ServerType | ServerConfiguration) | undefined; + app?: (() => Promise) | undefined; + webSocketServer?: + | (boolean | "ws" | string | WebSocketServerConfiguration) + | undefined; + proxy?: ProxyConfigArray | undefined; + open?: (boolean | string | Open | Array) | undefined; + setupExitSignals?: boolean | undefined; + client?: (boolean | ClientConfiguration) | undefined; + headers?: + | ( + | Headers + | (( + req: Request, + res: Response, + context: DevMiddlewareContext | undefined, + ) => Headers) + ) + | undefined; + onListening?: ((devServer: Server) => void) | undefined; + setupMiddlewares?: + | ((middlewares: Middleware[], devServer: Server) => Middleware[]) + | undefined; +}; +export type FunctionReturning = () => T; +export type BasicApplication = { + use: typeof useFn; +}; /** * @typedef {object} BasicApplication * @property {typeof useFn} use @@ -1219,7 +1555,7 @@ declare class Server< /** * @template T * @private - * @returns {T} server transport + * @returns {Promise} server transport */ private getServerTransport; /** @@ -1265,17 +1601,17 @@ declare class Server< private stats; /** * @private - * @returns {void} + * @returns {Promise} */ private setupWatchStaticFiles; /** * @private - * @returns {void} + * @returns {Promise} */ private setupWatchFiles; /** * @private - * @returns {void} + * @returns {Promise} */ private setupMiddlewares; /** @type {import("webpack-dev-middleware").API} */ @@ -1285,534 +1621,133 @@ declare class Server< import("express-serve-static-core").ParamsDictionary, any, any, - qs.ParsedQs, + import("qs").ParsedQs, Record >, import("express").Response> > | undefined; /** - * @private - * @returns {Promise} - */ - private createServer; - /** @type {S | undefined} */ - server: S | undefined; - isTlsServer: boolean | undefined; - /** - * @private - * @returns {void} - */ - private createWebSocketServer; - /** @type {WebSocketServerImplementation | undefined | null} */ - webSocketServer: WebSocketServerImplementation | undefined | null; - /** - * @private - * @param {string} defaultOpenTarget default open target - * @returns {Promise} - */ - private openBrowser; - /** - * @private - * @returns {void} - */ - private runBonjour; - /** - * @private - * @type {Bonjour | undefined} - */ - private bonjour; - /** - * @private - * @param {() => void} callback callback - * @returns {void} - */ - private stopBonjour; - /** - * @private - * @returns {Promise} - */ - private logStatus; - /** - * @private - * @param {Request} req request - * @param {Response} res response - * @param {NextFunction} next next function - */ - private setHeaders; - /** - * @private - * @param {string} value value - * @returns {boolean} true when host allowed, otherwise false - */ - private isHostAllowed; - /** - * @private - * @param {{ [key: string]: string | undefined }} headers headers - * @param {string} headerToCheck header to check - * @param {boolean} validateHost need to validate host - * @returns {boolean} true when host is valid, otherwise false - */ - private isValidHost; - /** - * @private - * @param {{ [key: string]: string | undefined }} headers headers - * @returns {boolean} true when is same origin, otherwise false - */ - private isSameOrigin; - /** - * @param {ClientConnection[]} clients clients - * @param {string} type type - * @param {EXPECTED_ANY=} data data - * @param {EXPECTED_ANY=} params params - */ - sendMessage( - clients: ClientConnection[], - type: string, - data?: EXPECTED_ANY | undefined, - params?: EXPECTED_ANY | undefined, - ): void; - /** - * @private - * @param {ClientConnection[]} clients clients - * @param {StatsCompilation} stats stats - * @param {boolean=} force force - */ - private sendStats; - /** - * @param {string | string[]} watchPath watch path - * @param {WatchOptions=} watchOptions watch options - */ - watchFiles( - watchPath: string | string[], - watchOptions?: WatchOptions | undefined, - ): void; - /** - * @param {import("webpack-dev-middleware").Callback=} callback callback - */ - invalidate( - callback?: import("webpack-dev-middleware").Callback | undefined, - ): void; - /** - * @returns {Promise} - */ - start(): Promise; - /** - * @param {((err?: Error) => void)=} callback callback - */ - startCallback(callback?: ((err?: Error) => void) | undefined): void; - /** - * @returns {Promise} - */ - stop(): Promise; - /** - * @param {((err?: Error) => void)=} callback callback - */ - stopCallback(callback?: ((err?: Error) => void) | undefined): void; - #private; -} -declare namespace Server { - export { - Schema, - Compiler, - MultiCompiler, - WebpackConfiguration, - StatsOptions, - StatsCompilation, - Stats, - MultiStats, - NetworkInterfaceInfo, - WatchOptions, - FSWatcher, - ConnectHistoryApiFallbackOptions, - Bonjour, - BonjourOptions, - RequestHandler, - HttpProxyMiddlewareOptions, - HttpProxyMiddlewareOptionsFilter, - ServeIndexOptions, - ServeStaticOptions, - IPv4, - IPv6, - Socket, - HTTPServer, - IncomingMessage, - ServerResponse, - OpenOptions, - ExpressApplication, - ExpressRequestHandler, - ExpressErrorRequestHandler, - ExpressRequest, - ExpressResponse, - EXPECTED_ANY, - NextFunction, - SimpleHandleFunction, - NextHandleFunction, - ErrorHandleFunction, - HandleFunction, - ServerOptions, - Request, - Response, - DevMiddlewareOptions, - DevMiddlewareContext, - Host, - Port, - WatchFiles, - Static, - NormalizedStatic, - ServerType, - ServerConfiguration, - WebSocketServerConfiguration, - ClientConnection, - WebSocketServer, - WebSocketServerImplementation, - ProxyConfigArrayItem, - ProxyConfigArray, - OpenApp, - Open, - NormalizedOpen, - WebSocketURL, - OverlayMessageOptions, - ClientConfiguration, - Headers, - MiddlewareHandler, - MiddlewareObject, - Middleware, - BasicServer, - Configuration, - FunctionReturning, - BasicApplication, - }; -} -type Schema = import("schema-utils/declarations/validate").Schema; -type Compiler = import("webpack").Compiler; -type MultiCompiler = import("webpack").MultiCompiler; -type WebpackConfiguration = import("webpack").Configuration; -type StatsOptions = import("webpack").StatsOptions; -type StatsCompilation = import("webpack").StatsCompilation; -type Stats = import("webpack").Stats; -type MultiStats = import("webpack").MultiStats; -type NetworkInterfaceInfo = import("os").NetworkInterfaceInfo; -type WatchOptions = import("chokidar").ChokidarOptions; -type FSWatcher = import("chokidar").FSWatcher; -type ConnectHistoryApiFallbackOptions = - import("connect-history-api-fallback").Options; -type Bonjour = import("bonjour-service").Bonjour; -type BonjourOptions = import("bonjour-service").Service; -type RequestHandler = import("http-proxy-middleware").RequestHandler; -type HttpProxyMiddlewareOptions = import("http-proxy-middleware").Options; -type HttpProxyMiddlewareOptionsFilter = import("http-proxy-middleware").Filter; -type ServeIndexOptions = import("serve-index").Options; -type ServeStaticOptions = import("serve-static").ServeStaticOptions; -type IPv4 = import("ipaddr.js").IPv4; -type IPv6 = import("ipaddr.js").IPv6; -type Socket = import("net").Socket; -type HTTPServer = import("http").Server; -type IncomingMessage = import("http").IncomingMessage; -type ServerResponse = import("http").ServerResponse; -type OpenOptions = import("open").Options; -type ExpressApplication = import("express").Application; -type ExpressRequestHandler = import("express").RequestHandler; -type ExpressErrorRequestHandler = import("express").ErrorRequestHandler; -type ExpressRequest = import("express").Request; -type ExpressResponse = import("express").Response; -type EXPECTED_ANY = any; -type NextFunction = (err?: EXPECTED_ANY) => void; -type SimpleHandleFunction = (req: IncomingMessage, res: ServerResponse) => void; -type NextHandleFunction = ( - req: IncomingMessage, - res: ServerResponse, - next: NextFunction, -) => void; -type ErrorHandleFunction = ( - err: EXPECTED_ANY, - req: IncomingMessage, - res: ServerResponse, - next: NextFunction, -) => void; -type HandleFunction = - | SimpleHandleFunction - | NextHandleFunction - | ErrorHandleFunction; -type ServerOptions = import("https").ServerOptions; -type Request = - T extends ExpressApplication ? ExpressRequest : IncomingMessage; -type Response = - T extends ExpressApplication ? ExpressResponse : ServerResponse; -type DevMiddlewareOptions< - T extends Request, - U extends Response, -> = import("webpack-dev-middleware").Options; -type DevMiddlewareContext< - T extends Request, - U extends Response, -> = import("webpack-dev-middleware").Context; -type Host = "local-ip" | "local-ipv4" | "local-ipv6" | string; -type Port = number | string | "auto"; -type WatchFiles = { - /** - * paths - */ - paths: string | string[]; - /** - * options - */ - options?: - | (WatchOptions & { - aggregateTimeout?: number; - ignored?: WatchOptions["ignored"]; - poll?: number | boolean; - }) - | undefined; -}; -type Static = { - /** - * directory - */ - directory?: string | undefined; - /** - * public path - */ - publicPath?: (string | string[]) | undefined; - /** - * serve index - */ - serveIndex?: (boolean | ServeIndexOptions) | undefined; - /** - * static options + * @private + * @returns {Promise} */ - staticOptions?: ServeStaticOptions | undefined; + private createServer; + /** @type {S | undefined} */ + server: S | undefined; + isTlsServer: boolean | undefined; /** - * watch and watch options + * @private + * @returns {Promise} */ - watch?: - | ( - | boolean - | (WatchOptions & { - aggregateTimeout?: number; - ignored?: WatchOptions["ignored"]; - poll?: number | boolean; - }) - ) - | undefined; -}; -type NormalizedStatic = { - directory: string; - publicPath: string[]; - serveIndex: false | ServeIndexOptions; - staticOptions: ServeStaticOptions; - watch: false | WatchOptions; -}; -type ServerType< - A extends BasicApplication = import("express").Application, - S extends BasicServer = import("http").Server< - typeof import("http").IncomingMessage, - typeof import("http").ServerResponse - >, -> = - | "http" - | "https" - | "http2" - | string - | ((serverOptions: ServerOptions, application: A) => S); -type ServerConfiguration< - A extends BasicApplication = import("express").Application, - S extends BasicServer = import("http").Server< - typeof import("http").IncomingMessage, - typeof import("http").ServerResponse - >, -> = { + private createWebSocketServer; + /** @type {WebSocketServerImplementation | undefined | null} */ + webSocketServer: WebSocketServerImplementation | undefined | null; /** - * type + * @private + * @param {string} defaultOpenTarget default open target + * @returns {Promise} */ - type?: ServerType | undefined; + private openBrowser; /** - * options + * @private + * @returns {Promise} */ - options?: ServerOptions | undefined; -}; -type WebSocketServerConfiguration = { + private runBonjour; /** - * type + * @private + * @type {Bonjour | undefined} */ - type?: ("ws" | string | (() => WebSocketServerConfiguration)) | undefined; + private bonjour; /** - * options + * @private + * @param {() => void} callback callback + * @returns {void} */ - options?: Record | undefined; -}; -type ClientConnection = (import("ws").WebSocket & { - send: import("ws").WebSocket["send"]; - terminate: import("ws").WebSocket["terminate"]; - ping: import("ws").WebSocket["ping"]; -}) & { - isAlive?: boolean; -}; -type WebSocketServer = import("ws").WebSocketServer & { - close: import("ws").WebSocketServer["close"]; -}; -type WebSocketServerImplementation = { - implementation: WebSocketServer; - clients: ClientConnection[]; -}; -type ProxyConfigArrayItem = { - path?: HttpProxyMiddlewareOptionsFilter | undefined; - context?: HttpProxyMiddlewareOptionsFilter | undefined; -} & HttpProxyMiddlewareOptions; -type ProxyConfigArray = ( - | ProxyConfigArrayItem - | (( - req?: Request | undefined, - res?: Response | undefined, - next?: NextFunction | undefined, - ) => ProxyConfigArrayItem) -)[]; -type OpenApp = { - name?: string | undefined; - arguments?: string[] | undefined; -}; -type Open = { - app?: (string | string[] | OpenApp) | undefined; + private stopBonjour; /** - * target + * @private + * @returns {Promise} */ - target?: (string | string[]) | undefined; -}; -type NormalizedOpen = { - target: string; - options: import("open").Options; -}; -type WebSocketURL = { + private logStatus; /** - * hostname + * @private + * @param {Request} req request + * @param {Response} res response + * @param {NextFunction} next next function */ - hostname?: string | undefined; + private setHeaders; /** - * password + * @private + * @param {string} value value + * @returns {boolean} true when host allowed, otherwise false */ - password?: string | undefined; + private isHostAllowed; /** - * pathname + * @private + * @param {{ [key: string]: string | undefined }} headers headers + * @param {string} headerToCheck header to check + * @param {boolean} validateHost need to validate host + * @returns {boolean} true when host is valid, otherwise false */ - pathname?: string | undefined; + private isValidHost; /** - * port + * @private + * @param {{ [key: string]: string | undefined }} headers headers + * @returns {boolean} true when is same origin, otherwise false */ - port?: (number | string) | undefined; + private isSameOrigin; /** - * protocol + * @param {ClientConnection[]} clients clients + * @param {string} type type + * @param {EXPECTED_ANY=} data data + * @param {EXPECTED_ANY=} params params */ - protocol?: string | undefined; + sendMessage( + clients: ClientConnection[], + type: string, + data?: EXPECTED_ANY | undefined, + params?: EXPECTED_ANY | undefined, + ): void; /** - * username + * @private + * @param {ClientConnection[]} clients clients + * @param {StatsCompilation} stats stats + * @param {boolean=} force force */ - username?: string | undefined; -}; -type OverlayMessageOptions = boolean | ((error: Error) => void); -type ClientConfiguration = { + private sendStats; /** - * logging + * @param {string | string[]} watchPath watch path + * @param {WatchOptions=} watchOptions watch options + * @returns {Promise} */ - logging?: - | ("log" | "info" | "warn" | "error" | "none" | "verbose") - | undefined; + watchFiles( + watchPath: string | string[], + watchOptions?: WatchOptions | undefined, + ): Promise; /** - * overlay + * @param {import("webpack-dev-middleware").Callback=} callback callback */ - overlay?: - | ( - | boolean - | { - warnings?: OverlayMessageOptions; - errors?: OverlayMessageOptions; - runtimeErrors?: OverlayMessageOptions; - } - ) - | undefined; + invalidate( + callback?: import("webpack-dev-middleware").Callback | undefined, + ): void; /** - * progress + * @returns {Promise} */ - progress?: boolean | undefined; + start(): Promise; /** - * reconnect + * @param {((err?: Error) => void)=} callback callback */ - reconnect?: (boolean | number) | undefined; + startCallback(callback?: ((err?: Error) => void) | undefined): void; /** - * web socket transport + * @returns {Promise} */ - webSocketTransport?: ("ws" | string) | undefined; + stop(): Promise; /** - * web socket URL + * @param {((err?: Error) => void)=} callback callback */ - webSocketURL?: (string | WebSocketURL) | undefined; -}; -type Headers = - | Array<{ - key: string; - value: string; - }> - | Record; -type MiddlewareHandler< - T extends BasicApplication = import("express").Application, -> = T extends ExpressApplication - ? ExpressRequestHandler | ExpressErrorRequestHandler - : HandleFunction; -type MiddlewareObject = { - name?: string; - path?: string; - middleware: MiddlewareHandler; -}; -type Middleware = MiddlewareObject | MiddlewareHandler; -type BasicServer = import("net").Server | import("tls").Server; -type Configuration< - A extends BasicApplication = import("express").Application, - S extends BasicServer = import("http").Server< - typeof import("http").IncomingMessage, - typeof import("http").ServerResponse - >, -> = { - ipc?: (boolean | string) | undefined; - host?: Host | undefined; - port?: Port | undefined; - hot?: (boolean | "only") | undefined; - liveReload?: boolean | undefined; - devMiddleware?: DevMiddlewareOptions | undefined; - compress?: boolean | undefined; - allowedHosts?: ("auto" | "all" | string | string[]) | undefined; - historyApiFallback?: (boolean | ConnectHistoryApiFallbackOptions) | undefined; - bonjour?: (boolean | Record | BonjourOptions) | undefined; - watchFiles?: - | (string | string[] | WatchFiles | Array) - | undefined; - static?: (boolean | string | Static | Array) | undefined; - server?: (ServerType | ServerConfiguration) | undefined; - app?: (() => Promise) | undefined; - webSocketServer?: - | (boolean | "ws" | string | WebSocketServerConfiguration) - | undefined; - proxy?: ProxyConfigArray | undefined; - open?: (boolean | string | Open | Array) | undefined; - setupExitSignals?: boolean | undefined; - client?: (boolean | ClientConfiguration) | undefined; - headers?: - | ( - | Headers - | (( - req: Request, - res: Response, - context: DevMiddlewareContext | undefined, - ) => Headers) - ) - | undefined; - onListening?: ((devServer: Server) => void) | undefined; - setupMiddlewares?: - | ((middlewares: Middleware[], devServer: Server) => Middleware[]) - | undefined; -}; -type FunctionReturning = () => T; -type BasicApplication = { - use: typeof useFn; -}; + stopCallback(callback?: ((err?: Error) => void) | undefined): void; + #private; +} /** * @overload * @param {NextHandleFunction} fn function diff --git a/types/lib/getPort.d.ts b/types/lib/getPort.d.ts index 677eb97671..d6eec701a3 100644 --- a/types/lib/getPort.d.ts +++ b/types/lib/getPort.d.ts @@ -1,4 +1,4 @@ -export = getPorts; +export default getPorts; /** * @param {number} basePort base port * @param {string=} host host diff --git a/types/lib/servers/BaseServer.d.ts b/types/lib/servers/BaseServer.d.ts index 07d29fb4b5..4094129b1a 100644 --- a/types/lib/servers/BaseServer.d.ts +++ b/types/lib/servers/BaseServer.d.ts @@ -1,15 +1,12 @@ -export = BaseServer; -declare class BaseServer { +/** @typedef {import("../Server.js").ClientConnection} ClientConnection */ +export default class BaseServer { /** - * @param {import("../Server")} server server + * @param {import("../Server.js").default} server server */ - constructor(server: import("../Server")); - /** @type {import("../Server")} */ - server: import("../Server"); + constructor(server: import("../Server.js").default); + /** @type {import("../Server.js").default} */ + server: import("../Server.js").default; /** @type {ClientConnection[]} */ clients: ClientConnection[]; } -declare namespace BaseServer { - export { ClientConnection }; -} -type ClientConnection = import("../Server").ClientConnection; +export type ClientConnection = import("../Server.js").ClientConnection; diff --git a/types/lib/servers/WebsocketServer.d.ts b/types/lib/servers/WebsocketServer.d.ts index ce8c693789..19e7acbcd8 100644 --- a/types/lib/servers/WebsocketServer.d.ts +++ b/types/lib/servers/WebsocketServer.d.ts @@ -1,16 +1,13 @@ -export = WebsocketServer; -declare class WebsocketServer extends BaseServer { +/** @typedef {import("../Server.js").WebSocketServerConfiguration} WebSocketServerConfiguration */ +/** @typedef {import("../Server.js").ClientConnection} ClientConnection */ +export default class WebsocketServer extends BaseServer { static heartbeatInterval: number; - implementation: WebSocket.Server< - typeof WebSocket, + implementation: import("ws").Server< + typeof import("ws").default, typeof import("http").IncomingMessage >; } -declare namespace WebsocketServer { - export { WebSocketServerConfiguration, ClientConnection }; -} -import BaseServer = require("./BaseServer"); -import WebSocket = require("ws"); -type WebSocketServerConfiguration = - import("../Server").WebSocketServerConfiguration; -type ClientConnection = import("../Server").ClientConnection; +export type WebSocketServerConfiguration = + import("../Server.js").WebSocketServerConfiguration; +export type ClientConnection = import("../Server.js").ClientConnection; +import BaseServer from "./BaseServer.js"; From 8a96bfc6d7b2edfb091b2c8eacc5ba93e6304c82 Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Fri, 1 May 2026 17:47:54 -0500 Subject: [PATCH 2/4] chore: add Jest configuration files for testing setup --- jest.config.js | 6 +++--- scripts/{globalSetupTest.js => globalSetupTest.cjs} | 0 scripts/{setupTest.js => setupTest.cjs} | 0 test/helpers/{snapshotResolver.js => snapshotResolver.cjs} | 0 4 files changed, 3 insertions(+), 3 deletions(-) rename scripts/{globalSetupTest.js => globalSetupTest.cjs} (100%) rename scripts/{setupTest.js => setupTest.cjs} (100%) rename test/helpers/{snapshotResolver.js => snapshotResolver.cjs} (100%) diff --git a/jest.config.js b/jest.config.js index 3747b2d2b4..407a76e9fd 100644 --- a/jest.config.js +++ b/jest.config.js @@ -9,9 +9,9 @@ export default { "/client/", ], testPathIgnorePatterns: ["/bin/this/process-arguments.js"], - snapshotResolver: "/test/helpers/snapshotResolver.js", - setupFilesAfterEnv: ["/scripts/setupTest.js"], - globalSetup: "/scripts/globalSetupTest.js", + snapshotResolver: "/test/helpers/snapshotResolver.cjs", + setupFilesAfterEnv: ["/scripts/setupTest.cjs"], + globalSetup: "/scripts/globalSetupTest.cjs", moduleNameMapper: { // This forces Jest/jest-environment-jsdom to use a Node+CommonJS version of uuid, not a Browser+ESM one // See https://github.com/uuidjs/uuid/pull/616 diff --git a/scripts/globalSetupTest.js b/scripts/globalSetupTest.cjs similarity index 100% rename from scripts/globalSetupTest.js rename to scripts/globalSetupTest.cjs diff --git a/scripts/setupTest.js b/scripts/setupTest.cjs similarity index 100% rename from scripts/setupTest.js rename to scripts/setupTest.cjs diff --git a/test/helpers/snapshotResolver.js b/test/helpers/snapshotResolver.cjs similarity index 100% rename from test/helpers/snapshotResolver.js rename to test/helpers/snapshotResolver.cjs From 2a3e191f93e79e2175120ce973fcb0a5974ad844 Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Sat, 2 May 2026 12:05:44 -0500 Subject: [PATCH 3/4] feat: more change to test --- babel.config.js | 1 + eslint.config.mjs | 39 +- scripts/globalSetupTest.cjs | 2 +- scripts/setupTest.cjs | 10 +- test/cli/allowedHosts-option.test.js | 10 +- test/cli/basic.test.js | 99 ++-- test/cli/bonjour-option.test.js | 36 +- test/cli/client-option.test.js | 24 +- test/cli/colors.test.js | 44 +- test/cli/compress-option.test.js | 8 +- test/cli/historyApiFallback-option.test.js | 20 +- test/cli/host-option.test.js | 33 +- test/cli/hot-option.test.js | 9 +- test/cli/ipc-option.test.js | 11 +- test/cli/liveReload-option.test.js | 8 +- test/cli/open-option.test.js | 19 +- test/cli/port-option.test.js | 20 +- test/cli/server-option.test.js | 64 ++- test/cli/static-option.test.js | 90 +++- test/cli/watchFiles-option.test.js | 35 +- test/cli/webSocketServer-option.test.js | 8 +- test/client/ReactErrorBoundary.test.js | 2 - test/client/bundle.test.js | 2 - test/client/clients/WebsocketClient.test.js | 2 - test/client/index.test.js | 2 - test/client/package.json | 3 + test/client/socket-helper.test.js | 2 - test/client/utils/createSocketURL.test.js | 2 - .../utils/getCurrentScriptSource.test.js | 2 - test/client/utils/log.test.js | 2 - test/client/utils/sendMessage.test.js | 2 - test/e2e/allowed-hosts.test.js | 337 +------------ test/e2e/api.test.js | 256 +++------- test/e2e/app.test.js | 70 ++- test/e2e/bonjour.test.js | 80 +-- test/e2e/built-in-routes.test.js | 75 +-- test/e2e/client-reconnect.test.js | 69 ++- test/e2e/client.test.js | 70 +-- test/e2e/compress.test.js | 46 +- test/e2e/cross-origin-request.test.js | 69 +-- test/e2e/entry.test.js | 121 ++--- test/e2e/headers.test.js | 103 +--- test/e2e/history-api-fallback.test.js | 141 +----- test/e2e/host.test.js | 92 +--- test/e2e/hot-and-live-reload.test.js | 199 +++----- test/e2e/ipc.test.js | 102 +--- test/e2e/lazy-compilation.test.js | 44 +- test/e2e/logging.test.js | 46 +- test/e2e/mime-types.test.js | 30 +- test/e2e/module-federation.test.js | 104 ++-- test/e2e/multi-compiler.test.js | 239 +++------ test/e2e/on-listening.test.js | 38 +- test/e2e/options-middleware.test.js | 32 +- test/e2e/overlay.test.js | 465 +++--------------- test/e2e/port.test.js | 30 +- test/e2e/progress.test.js | 36 +- test/e2e/range-header.test.js | 33 +- test/e2e/server-and-client-transport.test.js | 87 +--- test/e2e/server.test.js | 162 +----- test/e2e/setup-exit-signals.test.js | 31 +- test/e2e/setup-middlewares.test.js | 37 +- test/e2e/static-directory.test.js | 122 +---- test/e2e/static-public-path.test.js | 206 +------- test/e2e/stats.test.js | 32 +- test/e2e/target.test.js | 66 ++- test/e2e/watch-files.test.js | 243 +++------ test/e2e/web-socket-communication.test.js | 55 +-- test/e2e/web-socket-server-url.test.js | 442 +---------------- test/e2e/web-socket-server.test.js | 25 +- test/fixtures/cli-colors-default-stats/foo.js | 2 - .../webpack.config.js | 8 +- test/fixtures/cli-colors-disabled/foo.js | 2 - .../cli-colors-disabled/webpack.config.js | 8 +- test/fixtures/cli-colors-enabled/foo.js | 2 - .../cli-colors-enabled/webpack.config.js | 8 +- .../cli-empty-entry/webpack.config.js | 9 +- test/fixtures/cli-entry-as-descriptor/foo.js | 2 - .../cli-entry-as-descriptor/webpack.config.js | 8 +- test/fixtures/cli-multi-entry/bar.js | 2 - test/fixtures/cli-multi-entry/foo.js | 2 - .../cli-multi-entry/webpack.config.js | 11 +- test/fixtures/cli-promise-config/foo.js | 2 - .../cli-promise-config/webpack.config.js | 11 +- test/fixtures/cli-single-entry/foo.js | 2 - .../cli-single-entry/webpack.config.js | 11 +- test/fixtures/cli-target-config/foo.js | 2 - .../cli-target-config/webpack.config.js | 11 +- .../cli-universal-compiler-config/client.js | 2 - .../cli-universal-compiler-config/server.js | 2 - .../webpack.config.js | 8 +- test/fixtures/cli/foo.js | 2 - test/fixtures/cli/webpack.config.js | 8 +- test/fixtures/client-config/bar.js | 2 - test/fixtures/client-config/foo.js | 2 - test/fixtures/client-config/webpack.config.js | 11 +- .../custom-client/CustomClientEntry.js | 2 - .../custom-client/CustomClientHotEntry.js | 2 - .../custom-client/CustomWebSocketClient.js | 8 +- test/fixtures/dev-public-path/foo.js | 2 - .../dev-public-path/webpack.config.js | 11 +- test/fixtures/dev-server/bar.js | 2 - .../dev-server/client-custom-path-config.js | 11 +- .../dev-server/client-default-path-config.js | 11 +- test/fixtures/dev-server/foo.js | 2 - test/fixtures/entry-as-function/foo.js | 2 - .../entry-as-function/webpack.config.js | 8 +- .../historyapifallback-2-config/foo.js | 2 - .../webpack.config.js | 8 +- .../historyapifallback-3-config/foo.js | 4 +- .../webpack.config.js | 9 +- .../fixtures/historyapifallback-config/foo.js | 6 +- .../webpack.config.js | 9 +- .../lazy-compilation-multiple-entries/one.js | 2 - .../lazy-compilation-multiple-entries/two.js | 2 - .../webpack.config.js | 14 +- .../lazy-compilation-single-entry/entry.js | 2 - .../webpack.config.js | 12 +- test/fixtures/mime-types-config/foo.js | 4 +- .../mime-types-config/webpack.config.js | 9 +- .../module-federation-config/entry1.js | 4 +- .../module-federation-config/entry2.js | 4 +- .../webpack.config.js | 8 +- .../webpack.multi.config.js | 8 +- .../webpack.object-entry.config.js | 8 +- .../webpack.plugin.js | 18 +- .../multi-compiler-one-configuration/foo.js | 2 - .../webpack.config.js | 11 +- .../multi-compiler-two-configurations/one.js | 2 - .../multi-compiler-two-configurations/two.js | 2 - .../webpack.config.js | 11 +- test/fixtures/multi-public-path-config/bar.js | 2 - test/fixtures/multi-public-path-config/baz.js | 2 - test/fixtures/multi-public-path-config/foo.js | 4 +- .../webpack.config.js | 12 +- .../trusted-types.webpack.config.js | 15 +- .../fixtures/overlay-config/webpack.config.js | 11 +- test/fixtures/provide-plugin-custom/foo.js | 6 +- .../provide-plugin-custom/webpack.config.js | 11 +- test/fixtures/provide-plugin-default/foo.js | 7 +- .../provide-plugin-default/webpack.config.js | 11 +- test/fixtures/provide-plugin-ws-config/foo.js | 7 +- .../webpack.config.js | 11 +- test/fixtures/proxy-config/foo.js | 2 - test/fixtures/proxy-config/webpack.config.js | 8 +- test/fixtures/reload-config-2/foo.js | 4 +- .../reload-config-2/webpack.config.js | 20 +- test/fixtures/reload-config/foo.js | 4 +- test/fixtures/reload-config/webpack.config.js | 20 +- test/fixtures/schema/webpack.config.simple.js | 8 +- test/fixtures/simple-config-other/foo.js | 2 - .../simple-config-other/webpack.config.js | 8 +- test/fixtures/simple-config/foo.js | 2 - test/fixtures/simple-config/webpack.config.js | 11 +- test/fixtures/static-config/foo.js | 2 - test/fixtures/static-config/webpack.config.js | 8 +- test/fixtures/static/foo.js | 2 - test/fixtures/static/webpack.config.js | 11 +- .../universal-compiler-config/browser.js | 2 - .../universal-compiler-config/server.js | 2 - .../webpack.config.js | 11 +- test/fixtures/watch-files-config/foo.js | 2 - .../watch-files-config/webpack.config.js | 11 +- .../worker-config-dev-server-false/index.js | 4 - .../webpack.config.js | 13 +- .../worker-config-dev-server-false/worker.js | 3 - test/fixtures/worker-config/index.js | 4 - test/fixtures/worker-config/webpack.config.js | 11 +- test/fixtures/worker-config/worker.js | 3 - test/helpers/ExitOnDonePlugin.js | 8 +- test/helpers/conditional-test.js | 5 +- test/helpers/custom-http.js | 6 +- test/helpers/html-generator-plugin.js | 13 +- test/helpers/normalize-options.js | 9 +- test/helpers/puppeteer-constants.js | 102 ++-- test/helpers/run-browser.js | 38 +- test/helpers/session-subscribe.js | 6 +- test/helpers/test-bin.js | 49 +- test/helpers/test-server.js | 20 +- .../trusted-types-html-generator-plugin.js | 10 +- test/normalize-options.test.js | 40 +- test/ports-map.js | 18 +- test/server/open-option.test.js | 193 +++----- test/server/proxy-option.test.js | 180 ++----- test/validate-options.test.js | 227 +++++++-- 184 files changed, 1961 insertions(+), 4648 deletions(-) create mode 100644 test/client/package.json diff --git a/babel.config.js b/babel.config.js index 960f6b5739..27d3cb7e53 100644 --- a/babel.config.js +++ b/babel.config.js @@ -21,6 +21,7 @@ export default (api) => { [ "@babel/preset-env", { + modules: false, targets: { node: "22.12.0", }, diff --git a/eslint.config.mjs b/eslint.config.mjs index f63dcef69a..8173c28d01 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -8,9 +8,19 @@ export default defineConfig([ extends: [config], ignores: ["client-src/**/*", "!client-src/webpack.config.js"], languageOptions: { - // ES2025 needed for import attributes (`import(x, { with: ... })`). + // ES2025 needed for import attributes (`import x from "y" with { ... }`). // eslint-config-webpack pins ecmaVersion to 2024 for Node 22. ecmaVersion: "latest", + sourceType: "module", + }, + settings: { + // eslint-plugin-import re-parses imported modules with espree, which on + // its bundled version doesn't understand import attributes. Delegate to + // @babel/eslint-parser so files importing JSON via `with { type: "json" }` + // (e.g. lib/Server.js) parse correctly. + "import/parsers": { + "@babel/eslint-parser": [".js", ".cjs", ".mjs"], + }, }, rules: { // TODO fix me @@ -27,4 +37,31 @@ export default defineConfig([ files: ["test/**/*"], extends: [configs["universal-recommended"]], }, + { + // test/client/* still uses CJS (jest.mock + require for module reload). + // It is scoped to commonjs via test/client/package.json. + files: ["test/client/**/*"], + languageOptions: { + sourceType: "commonjs", + globals: { + require: "readonly", + module: "readonly", + __dirname: "readonly", + __filename: "readonly", + exports: "readonly", + process: "readonly", + }, + }, + rules: { + "import/extensions": "off", + "no-undef": "off", + strict: "off", + // test/client/package.json scopes these files to commonjs but does not + // re-declare devDependencies; resolve from the project root instead. + "import/no-extraneous-dependencies": [ + "error", + { packageDir: import.meta.dirname }, + ], + }, + }, ]); diff --git a/scripts/globalSetupTest.cjs b/scripts/globalSetupTest.cjs index e8ee1c86b3..c2694d9886 100644 --- a/scripts/globalSetupTest.cjs +++ b/scripts/globalSetupTest.cjs @@ -2,7 +2,7 @@ const tcpPortUsed = require("tcp-port-used"); const { version } = require("webpack"); -const ports = require("../test/ports-map"); +const { default: ports } = require("../test/ports-map"); // eslint-disable-next-line no-console console.log(`\n Running tests for webpack @${version} \n`); diff --git a/scripts/setupTest.cjs b/scripts/setupTest.cjs index 5e0aaeb46d..5b8b324532 100644 --- a/scripts/setupTest.cjs +++ b/scripts/setupTest.cjs @@ -1,7 +1,13 @@ "use strict"; -/* global jest */ +const jestGlobals = require("@jest/globals"); + +// In Jest's ESM runtime, `jest` is not auto-injected as a global into ESM +// test modules — only the test runner's automatic CJS binding gets it. +// Expose it on globalThis so ESM tests can use `jest.fn`, `jest.spyOn`, etc. +// without an explicit `import { jest } from "@jest/globals"` in every file. +globalThis.jest = jestGlobals.jest; process.env.CHOKIDAR_USEPOLLING = true; -jest.setTimeout(400000); +jestGlobals.jest.setTimeout(400000); diff --git a/test/cli/allowedHosts-option.test.js b/test/cli/allowedHosts-option.test.js index 548314d148..946805a1e3 100644 --- a/test/cli/allowedHosts-option.test.js +++ b/test/cli/allowedHosts-option.test.js @@ -1,7 +1,7 @@ -"use strict"; +import { testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; -const { testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-allowed-hosts"]; +const port = _ports_map["cli-allowed-hosts"]; describe('"allowedHosts" CLI option', () => { it('should work using "--allowed-hosts auto"', async () => { @@ -11,7 +11,6 @@ describe('"allowedHosts" CLI option', () => { "--allowed-hosts", "auto", ]); - expect(exitCode).toBe(0); }); @@ -22,7 +21,6 @@ describe('"allowedHosts" CLI option', () => { "--allowed-hosts", "all", ]); - expect(exitCode).toBe(0); }); @@ -33,7 +31,6 @@ describe('"allowedHosts" CLI option', () => { "--allowed-hosts", "testhouse.com", ]); - expect(exitCode).toBe(0); }); @@ -46,7 +43,6 @@ describe('"allowedHosts" CLI option', () => { "--allowed-hosts", "testhost1.com", ]); - expect(exitCode).toBe(0); }); }); diff --git a/test/cli/basic.test.js b/test/cli/basic.test.js index cf5b4a4964..9edd2fc0fa 100644 --- a/test/cli/basic.test.js +++ b/test/cli/basic.test.js @@ -1,11 +1,13 @@ -"use strict"; - -const path = require("node:path"); -const util = require("node:util"); -const execa = require("execa"); -const { normalizeStderr, testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-basic"]; - +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import util from "node:util"; +import execa from "execa"; +import { normalizeStderr, testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map["cli-basic"]; const isMacOS = process.platform === "darwin"; describe("basic", () => { @@ -27,9 +29,12 @@ describe("basic", () => { "--port", port, ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--host localhost --port "', async () => { @@ -39,7 +44,6 @@ describe("basic", () => { "--host", "localhost", ]); - expect(exitCode).toBe(0); expect(normalizeStderr(stderr)).toMatchSnapshot("stderr"); }); @@ -54,9 +58,12 @@ describe("basic", () => { "--port", port, ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it("should work using multi compiler mode", async () => { @@ -69,9 +76,12 @@ describe("basic", () => { "--port", port, ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it("should exit the process when SIGINT is detected", (done) => { @@ -83,18 +93,16 @@ describe("basic", () => { __dirname, "../../examples/client/web-socket-url", ); - const cp = execa("node", ["--port", port, cliPath], { cwd: examplePath }); - + const cp = execa("node", ["--port", port, cliPath], { + cwd: examplePath, + }); cp.stdout.on("data", (data) => { const bits = data.toString(); - if (/main.js/.test(bits)) { expect(cp.pid).not.toBe(0); - cp.kill("SIGINT"); } }); - cp.on("exit", () => { done(); }); @@ -106,20 +114,17 @@ describe("basic", () => { "../../bin/webpack-dev-server.js", ); const cwd = path.resolve(__dirname, "../fixtures/cli"); - const cp = execa("node", ["--port", port, cliPath], { cwd }); - + const cp = execa("node", ["--port", port, cliPath], { + cwd, + }); let killed = false; - cp.stdout.on("data", () => { if (!killed) { expect(cp.pid).not.toBe(0); - cp.kill("SIGINT"); } - killed = true; }); - cp.on("exit", () => { done(); }); @@ -141,18 +146,14 @@ describe("basic", () => { cwd: examplePath, }, ); - cp.stdout.on("data", (data) => { const bits = data.toString(); - if (/main.js/.test(bits)) { expect(cp.pid).not.toBe(0); - cp.stdin.write("hello"); cp.stdin.end("world"); } }); - cp.on("exit", () => { done(); }); @@ -167,30 +168,25 @@ describe("basic", () => { const cp = execa( "node", [cliPath, "--port", port, "--watch-options-stdin"], - { cwd }, + { + cwd, + }, ); - let killed = false; - cp.on("error", (error) => { done(error); }); - cp.stdin.on("error", (error) => { done(error); }); - cp.stdout.on("data", () => { if (!killed) { expect(cp.pid).not.toBe(0); - cp.stdin.write("hello"); cp.stdin.end("world"); } - killed = true; }); - cp.on("exit", () => { done(); }); @@ -208,7 +204,6 @@ describe("basic", () => { outputKillStr: /client\/index\.js\?/, }, ); - expect(exitCode).toBe(0); expect(stdout).toContain("client/index.js?"); }); @@ -227,7 +222,6 @@ describe("basic", () => { outputKillStr: /foo\.js/, }, ); - expect(exitCode).toBe(0); expect(stdout).toContain("client/index.js?"); expect(stdout).toContain("foo.js"); @@ -245,7 +239,6 @@ describe("basic", () => { outputKillStr: /client\/index\.js\?/, }, ); - expect(exitCode).toBe(0); expect(stdout).toContain("client/index.js?"); }); @@ -264,7 +257,6 @@ describe("basic", () => { outputKillStr: /foo\.js/, }, ); - expect(exitCode).toBe(0); expect(stdout).toContain("foo.js"); }); @@ -276,7 +268,6 @@ describe("basic", () => { outputKillStr: /foo\.js/, }, ); - expect(exitCode).toBe(0); expect(stdout).toContain("client/index.js?"); expect(stdout).toContain("foo.js"); @@ -289,7 +280,6 @@ describe("basic", () => { outputKillStr: /foo\.js/, }, ); - expect(exitCode).toBe(0); expect(stdout).not.toContain("client/index.js?"); expect(stdout).toContain("foo.js"); @@ -302,7 +292,6 @@ describe("basic", () => { outputKillStr: /webpack\/hot\/dev-server/, }, ); - expect(exitCode).toBe(0); expect(stdout).toContain("webpack/hot/dev-server"); }); @@ -319,7 +308,6 @@ describe("basic", () => { outputKillStr: /client\/index\.js/, }, ); - expect(exitCode).toBe(0); expect(stdout).toContain("client/index.js"); }); @@ -331,10 +319,12 @@ describe("basic", () => { "../../bin/webpack-dev-server.js", ); const cwd = path.resolve(__dirname, "../fixtures/cli"); - - const cp = execa("node", [cliPath, "--colors=false"], { cwd }); - const cp2 = execa("node", [cliPath, "--colors=false"], { cwd }); - + const cp = execa("node", [cliPath, "--colors=false"], { + cwd, + }); + const cp2 = execa("node", [cliPath, "--colors=false"], { + cwd, + }); const runtime = { cp: { port: null, @@ -345,47 +335,38 @@ describe("basic", () => { done: false, }, }; - cp.stderr.on("data", (data) => { const bits = data.toString(); const portMatch = /Project is running at http:\/\/localhost:(\d*)\//.exec(bits); - if (portMatch) { [, runtime.cp.port] = portMatch; } - if (/Compiled successfully/.test(bits)) { expect(cp.pid).not.toBe(0); cp.kill("SIGINT"); } }); - cp2.stderr.on("data", (data) => { const bits = data.toString(); const portMatch = /Project is running at http:\/\/localhost:(\d*)\//.exec(bits); - if (portMatch) { [, runtime.cp2.port] = portMatch; } - if (/Compiled successfully/.test(bits)) { expect(cp.pid).not.toBe(0); cp2.kill("SIGINT"); } }); - cp.on("exit", () => { runtime.cp.done = true; if (runtime.cp2.done) { expect(runtime.cp.port).not.toBe(runtime.cp2.port); } }); - cp2.on("exit", () => { runtime.cp2.done = true; - if (runtime.cp.done) { expect(runtime.cp.port).not.toBe(runtime.cp2.port); } diff --git a/test/cli/bonjour-option.test.js b/test/cli/bonjour-option.test.js index 77d1df223b..522d634a10 100644 --- a/test/cli/bonjour-option.test.js +++ b/test/cli/bonjour-option.test.js @@ -1,24 +1,29 @@ -"use strict"; - -const fs = require("node:fs"); -const Server = require("../../lib/Server"); -const { normalizeStderr, testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-bonjour"]; +import fs from "node:fs"; +import Server from "../../lib/Server.js"; +import { normalizeStderr, testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; +const port = _ports_map["cli-bonjour"]; const defaultCertificateDir = Server.findCacheDir(); describe('"bonjour" CLI option', () => { beforeEach(async () => { - fs.rmSync(defaultCertificateDir, { recursive: true, force: true }); + fs.rmSync(defaultCertificateDir, { + recursive: true, + force: true, + }); }); it('should work using "--bonjour"', async () => { const { exitCode, stderr } = await testBin(["--port", port, "--bonjour"], { outputKillStr: /Broadcasting/, }); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot(); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot(); }); it('should work using "--bonjour and --server-type=https"', async () => { @@ -28,10 +33,12 @@ describe('"bonjour" CLI option', () => { outputKillStr: /Broadcasting/, }, ); - expect(exitCode).toBe(0); expect( - normalizeStderr(stderr, { ipv6: true, https: true }), + normalizeStderr(stderr, { + ipv6: true, + https: true, + }), ).toMatchSnapshot(); }); @@ -41,8 +48,11 @@ describe('"bonjour" CLI option', () => { port, "--no-bonjour", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot(); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot(); }); }); diff --git a/test/cli/client-option.test.js b/test/cli/client-option.test.js index 0fd38d6af8..a307a7a4b4 100644 --- a/test/cli/client-option.test.js +++ b/test/cli/client-option.test.js @@ -1,7 +1,7 @@ -"use strict"; +import { testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; -const { testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-client"]; +const port = _ports_map["cli-client"]; describe('"client" CLI option', () => { it('should work using "--client-web-socket-transport ws"', async () => { @@ -11,19 +11,16 @@ describe('"client" CLI option', () => { "--client-web-socket-transport", "ws", ]); - expect(exitCode).toBe(0); }); it('should work using "--client-overlay"', async () => { const { exitCode } = await testBin(["--port", port, "--client-overlay"]); - expect(exitCode).toBe(0); }); it('should work using "--no-client-overlay"', async () => { const { exitCode } = await testBin(["--port", port, "--no-client-overlay"]); - expect(exitCode).toBe(0); }); @@ -33,7 +30,6 @@ describe('"client" CLI option', () => { port, "--client-overlay-errors", ]); - expect(exitCode).toBe(0); }); @@ -43,7 +39,6 @@ describe('"client" CLI option', () => { port, "--no-client-overlay-errors", ]); - expect(exitCode).toBe(0); }); @@ -53,7 +48,6 @@ describe('"client" CLI option', () => { port, "--client-overlay-warnings", ]); - expect(exitCode).toBe(0); }); @@ -63,7 +57,6 @@ describe('"client" CLI option', () => { port, "--no-client-overlay-warnings", ]); - expect(exitCode).toBe(0); }); @@ -74,13 +67,11 @@ describe('"client" CLI option', () => { "--client-logging", "verbose", ]); - expect(exitCode).toBe(0); }); it('should work using "--client-progress"', async () => { const { exitCode } = await testBin(["--port", port, "--client-progress"]); - expect(exitCode).toBe(0); }); @@ -90,13 +81,11 @@ describe('"client" CLI option', () => { port, "--no-client-progress", ]); - expect(exitCode).toBe(0); }); it('should work using "--client-reconnect"', async () => { const { exitCode } = await testBin(["--port", port, "--client-reconnect"]); - expect(exitCode).toBe(0); }); @@ -107,7 +96,6 @@ describe('"client" CLI option', () => { "--client-reconnect", 5, ]); - expect(exitCode).toBe(0); }); @@ -117,7 +105,6 @@ describe('"client" CLI option', () => { port, "--no-client-reconnect", ]); - expect(exitCode).toBe(0); }); @@ -128,7 +115,6 @@ describe('"client" CLI option', () => { "--client-web-socket-url", "ws://myhost.com:8080/foo/test", ]); - expect(exitCode).toBe(0); }); @@ -139,7 +125,6 @@ describe('"client" CLI option', () => { "--client-web-socket-url-protocol", "ws:", ]); - expect(exitCode).toBe(0); }); @@ -150,7 +135,6 @@ describe('"client" CLI option', () => { "--client-web-socket-url-hostname", "0.0.0.0", ]); - expect(exitCode).toBe(0); }); @@ -161,7 +145,6 @@ describe('"client" CLI option', () => { "--client-web-socket-url-pathname", "/ws", ]); - expect(exitCode).toBe(0); }); @@ -172,7 +155,6 @@ describe('"client" CLI option', () => { "--client-web-socket-url-port", 8080, ]); - expect(exitCode).toBe(0); }); }); diff --git a/test/cli/colors.test.js b/test/cli/colors.test.js index a19143439e..6771e84e52 100644 --- a/test/cli/colors.test.js +++ b/test/cli/colors.test.js @@ -1,8 +1,9 @@ -"use strict"; - -const { normalizeStderr, testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-colors"]; +import { createRequire } from "node:module"; +import { normalizeStderr, testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; +const require = createRequire(import.meta.url); +const port = _ports_map["cli-colors"]; const colorsDefaultStats = require.resolve( "../fixtures/cli-colors-default-stats/webpack.config", ); @@ -21,25 +22,34 @@ describe("colors", () => { "--color", colorsDefaultStats, ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); expect(stderr).toContain("\u001B["); }); it('should work use colors using "--color"', async () => { const { exitCode, stderr } = await testBin(["--port", port, "--color"]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); expect(stderr).toContain("\u001B["); }); it('should work do not use colors using "--no-color"', async () => { const { exitCode, stderr } = await testBin(["--port", port, "--no-color"]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); expect(stderr).not.toContain("\u001B["); }); @@ -50,9 +60,12 @@ describe("colors", () => { "--config", colorsEnabled, ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); expect(stderr).toContain("\u001B["); }); @@ -63,9 +76,12 @@ describe("colors", () => { "--config", colorsDisabled, ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); expect(stderr).not.toContain("\u001B["); }); }); diff --git a/test/cli/compress-option.test.js b/test/cli/compress-option.test.js index ccd3884350..fda51dd1e2 100644 --- a/test/cli/compress-option.test.js +++ b/test/cli/compress-option.test.js @@ -1,18 +1,16 @@ -"use strict"; +import { testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; -const { testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-compress"]; +const port = _ports_map["cli-compress"]; describe('"compress" CLI option', () => { it('should work using "--compress"', async () => { const { exitCode } = await testBin(["--port", port, "--compress"]); - expect(exitCode).toBe(0); }); it('should work using "--no-compress"', async () => { const { exitCode } = await testBin(["--port", port, "--no-compress"]); - expect(exitCode).toBe(0); }); }); diff --git a/test/cli/historyApiFallback-option.test.js b/test/cli/historyApiFallback-option.test.js index 018db0e5b3..33a965af36 100644 --- a/test/cli/historyApiFallback-option.test.js +++ b/test/cli/historyApiFallback-option.test.js @@ -1,7 +1,7 @@ -"use strict"; +import { normalizeStderr, testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; -const { normalizeStderr, testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-history-api-fallback"]; +const port = _ports_map["cli-history-api-fallback"]; describe('"historyApiFallback" CLI option', () => { it('should work using "--history-api-fallback"', async () => { @@ -11,9 +11,12 @@ describe('"historyApiFallback" CLI option', () => { outputKillStr: /404s will fallback/, }, ); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot(); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot(); }); it('should work using "--no-history-api-fallback"', async () => { @@ -22,8 +25,11 @@ describe('"historyApiFallback" CLI option', () => { port, "--no-history-api-fallback", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot(); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot(); }); }); diff --git a/test/cli/host-option.test.js b/test/cli/host-option.test.js index dfa65ee92b..c6dd44ba4b 100644 --- a/test/cli/host-option.test.js +++ b/test/cli/host-option.test.js @@ -1,10 +1,9 @@ -"use strict"; - -const os = require("node:os"); -const Server = require("../../lib/Server"); -const { normalizeStderr, testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-host"]; +import os from "node:os"; +import Server from "../../lib/Server.js"; +import { normalizeStderr, testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; +const port = _ports_map["cli-host"]; const localIPv4 = Server.findIp("v4", false); const localIPv6 = Server.findIp("v6", false); @@ -16,9 +15,12 @@ describe('"host" CLI option', () => { "--host", "0.0.0.0", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--host ::" (IPv6)', async () => { @@ -28,9 +30,12 @@ describe('"host" CLI option', () => { "--host", "::", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--host ::1" (IPv6)', async () => { @@ -40,7 +45,6 @@ describe('"host" CLI option', () => { "--host", "::1", ]); - expect(exitCode).toBe(0); expect(normalizeStderr(stderr)).toMatchSnapshot("stderr"); }); @@ -52,7 +56,6 @@ describe('"host" CLI option', () => { "--host", "localhost", ]); - expect(exitCode).toBe(0); expect(normalizeStderr(stderr)).toMatchSnapshot("stderr"); }); @@ -64,7 +67,6 @@ describe('"host" CLI option', () => { "--host", "127.0.0.1", ]); - expect(exitCode).toBe(0); expect(normalizeStderr(stderr)).toMatchSnapshot("stderr"); }); @@ -76,7 +78,6 @@ describe('"host" CLI option', () => { "--host", localIPv4, ]); - expect(exitCode).toBe(0); expect(normalizeStderr(stderr)).toMatchSnapshot("stderr"); }); @@ -89,7 +90,6 @@ describe('"host" CLI option', () => { "--host", localIPv6, ]); - expect(exitCode).toBe(0); expect(normalizeStderr(stderr)).toMatchSnapshot("stderr"); }); @@ -101,7 +101,6 @@ describe('"host" CLI option', () => { "--host", "local-ip", ]); - expect(exitCode).toBe(0); expect(normalizeStderr(stderr)).toMatchSnapshot("stderr"); }); @@ -114,7 +113,6 @@ describe('"host" CLI option', () => { "--host", "local-ip", ]); - expect(exitCode).toBe(0); jest.spyOn(os, "networkInterfaces").mockImplementation(() => ({ lo: [ @@ -233,7 +231,6 @@ describe('"host" CLI option', () => { "--host", "local-ipv4", ]); - expect(exitCode).toBe(0); expect(normalizeStderr(stderr)).toMatchSnapshot("stderr"); }); diff --git a/test/cli/hot-option.test.js b/test/cli/hot-option.test.js index 6b525d885a..a6b869a985 100644 --- a/test/cli/hot-option.test.js +++ b/test/cli/hot-option.test.js @@ -1,7 +1,7 @@ -"use strict"; +import { testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; -const { testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-hot"]; +const port = _ports_map["cli-hot"]; describe('"hot" CLI option', () => { it('should work using "--hot"', async () => { @@ -11,7 +11,6 @@ describe('"hot" CLI option', () => { outputKillStr: /compiled successfully/, }, ); - expect(exitCode).toBe(0); expect(stdout).toContain("webpack/hot/dev-server.js"); }); @@ -23,7 +22,6 @@ describe('"hot" CLI option', () => { outputKillStr: /compiled successfully/, }, ); - expect(exitCode).toBe(0); expect(stdout).not.toContain("webpack/hot/dev-server.js"); }); @@ -35,7 +33,6 @@ describe('"hot" CLI option', () => { outputKillStr: /compiled successfully/, }, ); - expect(exitCode).toBe(0); expect(stdout).toContain("/hot/only-dev-server.js"); }); diff --git a/test/cli/ipc-option.test.js b/test/cli/ipc-option.test.js index 304c05f38d..dc8d2653c6 100644 --- a/test/cli/ipc-option.test.js +++ b/test/cli/ipc-option.test.js @@ -1,13 +1,10 @@ -"use strict"; - -const os = require("node:os"); -const path = require("node:path"); -const { normalizeStderr, testBin } = require("../helpers/test-bin"); +import os from "node:os"; +import path from "node:path"; +import { normalizeStderr, testBin } from "../helpers/test-bin.js"; describe('"ipc" CLI option', () => { it('should work using "--ipc"', async () => { const { exitCode, stderr } = await testBin(["--ipc"]); - expect(exitCode).toBe(0); expect(normalizeStderr(stderr)).toMatchSnapshot("stderr"); }); @@ -17,9 +14,7 @@ describe('"ipc" CLI option', () => { const pipePrefix = isWindows ? "\\\\.\\pipe\\" : os.tmpdir(); const pipeName = "webpack-dev-server.cli.sock"; const ipc = path.join(pipePrefix, pipeName); - const { exitCode, stderr } = await testBin(["--ipc", ipc]); - expect(exitCode).toBe(0); expect(normalizeStderr(stderr)).toMatchSnapshot("stderr"); }); diff --git a/test/cli/liveReload-option.test.js b/test/cli/liveReload-option.test.js index 53e2b198e8..c9ec35549e 100644 --- a/test/cli/liveReload-option.test.js +++ b/test/cli/liveReload-option.test.js @@ -1,18 +1,16 @@ -"use strict"; +import { testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; -const { testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-live-reload"]; +const port = _ports_map["cli-live-reload"]; describe('"liveReload" CLI option', () => { it('should work using "--live-reload"', async () => { const { exitCode } = await testBin(["--port", port, "--live-reload"]); - expect(exitCode).toBe(0); }); it('should work using "--no-live-reload"', async () => { const { exitCode } = await testBin(["--port", port, "--no-live-reload"]); - expect(exitCode).toBe(0); }); }); diff --git a/test/cli/open-option.test.js b/test/cli/open-option.test.js index 9cc9b9cd41..5c6c7c9cce 100644 --- a/test/cli/open-option.test.js +++ b/test/cli/open-option.test.js @@ -1,12 +1,11 @@ -"use strict"; +import { testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; -const { testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-open"]; +const port = _ports_map["cli-open"]; describe('"open" CLI option', () => { it('should work using "--open"', async () => { const { exitCode } = await testBin(["--port", port, "--open"]); - expect(exitCode).toBe(0); }); @@ -17,7 +16,6 @@ describe('"open" CLI option', () => { "--open", "/index.html", ]); - expect(exitCode).toBe(0); }); @@ -29,13 +27,11 @@ describe('"open" CLI option', () => { "/first.html", "second.html", ]); - expect(exitCode).toBe(0); }); it('should work using "--no-open"', async () => { const { exitCode } = await testBin(["--no-open", "--port", port]); - expect(exitCode).toBe(0); }); @@ -47,7 +43,6 @@ describe('"open" CLI option', () => { "--open", "/third.html", ]); - expect(exitCode).toBe(0); }); @@ -59,7 +54,6 @@ describe('"open" CLI option', () => { "--open-target", "", ]); - expect(exitCode).toBe(0); }); @@ -71,7 +65,6 @@ describe('"open" CLI option', () => { "--open-target", "/third.html", ]); - expect(exitCode).toBe(0); }); @@ -82,7 +75,6 @@ describe('"open" CLI option', () => { "--open-app-name", "google-chrome", ]); - expect(exitCode).toBe(0); }); @@ -94,7 +86,6 @@ describe('"open" CLI option', () => { "--open-app-name", "firefox", ]); - expect(exitCode).toBe(0); }); @@ -105,7 +96,6 @@ describe('"open" CLI option', () => { "--open-target", "index.html", ]); - expect(exitCode).toBe(0); }); @@ -117,7 +107,6 @@ describe('"open" CLI option', () => { "--open-target", "first.html", ]); - expect(exitCode).toBe(0); }); @@ -129,7 +118,6 @@ describe('"open" CLI option', () => { "/first.html", "second.html", ]); - expect(exitCode).toBe(0); }); @@ -142,7 +130,6 @@ describe('"open" CLI option', () => { "--open-app-name", "google-chrome", ]); - expect(exitCode).toBe(0); }); }); diff --git a/test/cli/port-option.test.js b/test/cli/port-option.test.js index b771e7f280..d3ec7ea4b2 100644 --- a/test/cli/port-option.test.js +++ b/test/cli/port-option.test.js @@ -1,20 +1,26 @@ -"use strict"; +import { normalizeStderr, testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; -const { normalizeStderr, testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-port-option"]; +const port = _ports_map["cli-port-option"]; describe('"port" CLI option', () => { it('should work using "--port "', async () => { const { exitCode, stderr } = await testBin(["--port", port]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--port auto"', async () => { const { exitCode, stderr } = await testBin(["--port", "auto"]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); }); diff --git a/test/cli/server-option.test.js b/test/cli/server-option.test.js index 7b9e77256b..ebea912961 100644 --- a/test/cli/server-option.test.js +++ b/test/cli/server-option.test.js @@ -1,16 +1,17 @@ -"use strict"; - -const path = require("node:path"); -const { rimraf } = require("rimraf"); -const Server = require("../../lib/Server"); -const { normalizeStderr, testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-server"]; - +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { rimraf } from "rimraf"; +import Server from "../../lib/Server.js"; +import { normalizeStderr, testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map["cli-server"]; const httpsCertificateDirectory = path.resolve( __dirname, "../fixtures/https-certificate", ); - const defaultCertificateDir = Server.findCacheDir(); describe('"server" CLI options', () => { @@ -25,10 +26,12 @@ describe('"server" CLI options', () => { "--server-type", "http", ]); - expect(exitCode).toBe(0); expect( - normalizeStderr(stderr, { ipv6: true, https: false }), + normalizeStderr(stderr, { + ipv6: true, + https: false, + }), ).toMatchSnapshot(); }); @@ -39,10 +42,12 @@ describe('"server" CLI options', () => { "--server-type", "https", ]); - expect(exitCode).toBe(0); expect( - normalizeStderr(stderr, { ipv6: true, https: true }), + normalizeStderr(stderr, { + ipv6: true, + https: true, + }), ).toMatchSnapshot(); }); @@ -52,7 +57,6 @@ describe('"server" CLI options', () => { const cert = path.join(httpsCertificateDirectory, "server.crt"); const ca = path.join(httpsCertificateDirectory, "ca.pem"); const passphrase = "webpack-dev-server"; - const { exitCode, stderr } = await testBin([ "--port", port, @@ -69,10 +73,12 @@ describe('"server" CLI options', () => { "--server-options-ca", ca, ]); - expect(exitCode).toBe(0); expect( - normalizeStderr(stderr, { ipv6: true, https: true }), + normalizeStderr(stderr, { + ipv6: true, + https: true, + }), ).toMatchSnapshot(); }); @@ -82,7 +88,6 @@ describe('"server" CLI options', () => { const cert = path.join(httpsCertificateDirectory, "server.crt"); const ca = path.join(httpsCertificateDirectory, "ca.pem"); const passphrase = "webpack-dev-server"; - const { exitCode, stderr } = await testBin([ "--port", port, @@ -103,10 +108,12 @@ describe('"server" CLI options', () => { "--server-options-ca", ca, ]); - expect(exitCode).toBe(0); expect( - normalizeStderr(stderr, { ipv6: true, https: true }), + normalizeStderr(stderr, { + ipv6: true, + https: true, + }), ).toMatchSnapshot(); }); @@ -116,7 +123,6 @@ describe('"server" CLI options', () => { const key = path.join(httpsCertificateDirectory, "server.key"); const cert = path.join(httpsCertificateDirectory, "server.crt"); const passphrase = "webpack-dev-server"; - const { exitCode, stderr } = await testBin([ "--port", port, @@ -131,10 +137,12 @@ describe('"server" CLI options', () => { "--server-options-cert", cert, ]); - expect(exitCode).toBe(0); expect( - normalizeStderr(stderr, { ipv6: true, https: true }), + normalizeStderr(stderr, { + ipv6: true, + https: true, + }), ).toMatchSnapshot(); }); @@ -146,10 +154,12 @@ describe('"server" CLI options', () => { "https", "--server-options-request-cert", ]); - expect(exitCode).toBe(0); expect( - normalizeStderr(stderr, { ipv6: true, https: true }), + normalizeStderr(stderr, { + ipv6: true, + https: true, + }), ).toMatchSnapshot(); }); @@ -161,10 +171,12 @@ describe('"server" CLI options', () => { "https", "--no-server-options-request-cert", ]); - expect(exitCode).toBe(0); expect( - normalizeStderr(stderr, { ipv6: true, https: true }), + normalizeStderr(stderr, { + ipv6: true, + https: true, + }), ).toMatchSnapshot(); }); }); diff --git a/test/cli/static-option.test.js b/test/cli/static-option.test.js index 66ccd5ec67..16946bfef3 100644 --- a/test/cli/static-option.test.js +++ b/test/cli/static-option.test.js @@ -1,14 +1,17 @@ -"use strict"; +import { normalizeStderr, testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; -const { normalizeStderr, testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-static"]; +const port = _ports_map["cli-static"]; describe('"static" CLI option', () => { it('should work using "--static"', async () => { const { exitCode, stderr } = await testBin(["--port", port, "--static"]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--static new-static"', async () => { @@ -18,9 +21,12 @@ describe('"static" CLI option', () => { "--static", "new-static", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--static new-static --static other-static"', async () => { @@ -32,9 +38,12 @@ describe('"static" CLI option', () => { "--static", "other-static", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--static-reset"', async () => { @@ -45,9 +54,12 @@ describe('"static" CLI option', () => { "--static", "new-static-after-reset", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--static-reset --static-directory new-static-directory"', async () => { @@ -58,9 +70,12 @@ describe('"static" CLI option', () => { "--static-directory", "new-static-directory", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--static-directory static-dir"', async () => { @@ -70,9 +85,12 @@ describe('"static" CLI option', () => { "--static-directory", "static-dir", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--static-public-path /public"', async () => { @@ -82,9 +100,12 @@ describe('"static" CLI option', () => { "--static-public-path", "/public", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--static-public-path-reset"', async () => { @@ -95,9 +116,12 @@ describe('"static" CLI option', () => { "--static-public-path", "/new-public", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--static-serve-index"', async () => { @@ -106,9 +130,12 @@ describe('"static" CLI option', () => { port, "--static-serve-index", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--no-static-serve-index"', async () => { @@ -117,9 +144,12 @@ describe('"static" CLI option', () => { port, "--no-static-serve-index", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--static-watch"', async () => { @@ -128,9 +158,12 @@ describe('"static" CLI option', () => { port, "--static-watch", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--no-static-watch"', async () => { @@ -139,8 +172,11 @@ describe('"static" CLI option', () => { port, "--no-static-watch", ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); }); diff --git a/test/cli/watchFiles-option.test.js b/test/cli/watchFiles-option.test.js index 93eeebfe78..df5c54b519 100644 --- a/test/cli/watchFiles-option.test.js +++ b/test/cli/watchFiles-option.test.js @@ -1,22 +1,27 @@ -"use strict"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { normalizeStderr, testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; -const path = require("node:path"); -const { normalizeStderr, testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-watch-files"]; +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map["cli-watch-files"]; describe('"watchFiles" CLI option', () => { it('should work using "--watch-files "', async () => { const watchDirectory = path.resolve(__dirname, "../fixtures/static/static"); - const { exitCode, stderr } = await testBin([ "--port", port, "--watch-files", watchDirectory, ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--watch-files --watch-files "', async () => { @@ -25,7 +30,6 @@ describe('"watchFiles" CLI option', () => { __dirname, "../fixtures/static/simple-config", ); - const { exitCode, stderr } = await testBin([ "--port", port, @@ -34,14 +38,16 @@ describe('"watchFiles" CLI option', () => { "--watch-files", watchOtherDirectory, ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); it('should work using "--watch-files-reset --watch-files "', async () => { const watchDirectory = path.resolve(__dirname, "../fixtures/static/static"); - const { exitCode, stderr } = await testBin([ "--port", port, @@ -49,8 +55,11 @@ describe('"watchFiles" CLI option', () => { "--watch-files", watchDirectory, ]); - expect(exitCode).toBe(0); - expect(normalizeStderr(stderr, { ipv6: true })).toMatchSnapshot("stderr"); + expect( + normalizeStderr(stderr, { + ipv6: true, + }), + ).toMatchSnapshot("stderr"); }); }); diff --git a/test/cli/webSocketServer-option.test.js b/test/cli/webSocketServer-option.test.js index e7394c8933..59d465f5b7 100644 --- a/test/cli/webSocketServer-option.test.js +++ b/test/cli/webSocketServer-option.test.js @@ -1,7 +1,7 @@ -"use strict"; +import { testBin } from "../helpers/test-bin.js"; +import _ports_map from "../ports-map.js"; -const { testBin } = require("../helpers/test-bin"); -const port = require("../ports-map")["cli-web-socket-server"]; +const port = _ports_map["cli-web-socket-server"]; describe('"webSocketServer" CLI option', () => { it('should work using "--web-socket-server-type ws"', async () => { @@ -11,7 +11,6 @@ describe('"webSocketServer" CLI option', () => { "--web-socket-server-type", "ws", ]); - expect(exitCode).toBe(0); }); @@ -21,7 +20,6 @@ describe('"webSocketServer" CLI option', () => { port, "--no-web-socket-server", ]); - expect(exitCode).toBe(0); }); }); diff --git a/test/client/ReactErrorBoundary.test.js b/test/client/ReactErrorBoundary.test.js index 8932de9a2c..095f59defc 100644 --- a/test/client/ReactErrorBoundary.test.js +++ b/test/client/ReactErrorBoundary.test.js @@ -2,8 +2,6 @@ * @jest-environment jsdom */ -"use strict"; - const { createOverlay } = require("../../client-src/overlay"); describe("createOverlay", () => { diff --git a/test/client/bundle.test.js b/test/client/bundle.test.js index c392196be9..0ce29d6147 100644 --- a/test/client/bundle.test.js +++ b/test/client/bundle.test.js @@ -1,5 +1,3 @@ -"use strict"; - const acorn = require("acorn"); const request = require("supertest"); const webpack = require("webpack"); diff --git a/test/client/clients/WebsocketClient.test.js b/test/client/clients/WebsocketClient.test.js index de113abb2c..95f11f8a2b 100644 --- a/test/client/clients/WebsocketClient.test.js +++ b/test/client/clients/WebsocketClient.test.js @@ -3,8 +3,6 @@ * @jest-environment-options { "customExportConditions": ["main"] } */ -"use strict"; - const http = require("node:http"); const express = require("express"); const ws = require("ws"); diff --git a/test/client/index.test.js b/test/client/index.test.js index aaa1c9f0f5..f763f18ff9 100644 --- a/test/client/index.test.js +++ b/test/client/index.test.js @@ -2,8 +2,6 @@ * @jest-environment jsdom */ -"use strict"; - describe("index", () => { let log; let socket; diff --git a/test/client/package.json b/test/client/package.json new file mode 100644 index 0000000000..5bbefffbab --- /dev/null +++ b/test/client/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/test/client/socket-helper.test.js b/test/client/socket-helper.test.js index 2ebcf25c98..035f64385d 100644 --- a/test/client/socket-helper.test.js +++ b/test/client/socket-helper.test.js @@ -2,8 +2,6 @@ * @jest-environment jsdom */ -"use strict"; - describe("socket", () => { beforeEach(() => { jest.resetAllMocks(); diff --git a/test/client/utils/createSocketURL.test.js b/test/client/utils/createSocketURL.test.js index 3170d8fa62..0385441c78 100644 --- a/test/client/utils/createSocketURL.test.js +++ b/test/client/utils/createSocketURL.test.js @@ -2,8 +2,6 @@ * @jest-environment jsdom */ -"use strict"; - describe("'createSocketURL' function", () => { globalThis.__webpack_hash__ = "hash"; diff --git a/test/client/utils/getCurrentScriptSource.test.js b/test/client/utils/getCurrentScriptSource.test.js index 8eca65c0bd..70764b764b 100644 --- a/test/client/utils/getCurrentScriptSource.test.js +++ b/test/client/utils/getCurrentScriptSource.test.js @@ -2,8 +2,6 @@ * @jest-environment jsdom */ -"use strict"; - describe("'getCurrentScriptSource' function", () => { let getCurrentScriptSource; diff --git a/test/client/utils/log.test.js b/test/client/utils/log.test.js index 53c0fb64a5..8e9a061e4c 100644 --- a/test/client/utils/log.test.js +++ b/test/client/utils/log.test.js @@ -2,8 +2,6 @@ * @jest-environment jsdom */ -"use strict"; - describe("'log' function", () => { let logMock; let setLogLevel; diff --git a/test/client/utils/sendMessage.test.js b/test/client/utils/sendMessage.test.js index 3bfdb588d5..a7fad5463f 100644 --- a/test/client/utils/sendMessage.test.js +++ b/test/client/utils/sendMessage.test.js @@ -2,8 +2,6 @@ * @jest-environment jsdom */ -"use strict"; - const sendMessage = require("../../../client-src/utils/sendMessage").default; describe("'sendMessage' function", () => { diff --git a/test/e2e/allowed-hosts.test.js b/test/e2e/allowed-hosts.test.js index 7f7f9b492d..6868349245 100644 --- a/test/e2e/allowed-hosts.test.js +++ b/test/e2e/allowed-hosts.test.js @@ -1,13 +1,12 @@ -"use strict"; - -const express = require("express"); -const { createProxyMiddleware } = require("http-proxy-middleware"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const [port1, port2] = require("../ports-map")["allowed-hosts"]; - +import express from "express"; +import { createProxyMiddleware } from "http-proxy-middleware"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const [port1, port2] = _ports_map["allowed-hosts"]; const webSocketServers = ["ws"]; describe("allowed hosts", () => { @@ -17,7 +16,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -31,12 +29,9 @@ describe("allowed hosts", () => { allowedHosts: "auto", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -46,21 +41,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -68,18 +59,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -90,7 +78,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -103,12 +90,9 @@ describe("allowed hosts", () => { host: devServerHost, }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -118,22 +102,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -141,18 +120,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -163,7 +139,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -176,12 +151,9 @@ describe("allowed hosts", () => { host: devServerHost, }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -191,22 +163,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -214,18 +181,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -236,7 +200,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -250,12 +213,9 @@ describe("allowed hosts", () => { allowedHosts: "auto", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -265,22 +225,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -288,18 +243,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -310,7 +262,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -324,12 +275,9 @@ describe("allowed hosts", () => { allowedHosts: "auto", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -339,22 +287,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -362,18 +305,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://[${proxyHost}]:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -385,7 +325,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = IPv4; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -399,12 +338,9 @@ describe("allowed hosts", () => { allowedHosts: "auto", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -414,22 +350,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -437,18 +368,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -459,7 +387,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -473,12 +400,9 @@ describe("allowed hosts", () => { allowedHosts: "auto", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -493,22 +417,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -516,18 +435,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -538,7 +454,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -552,12 +467,9 @@ describe("allowed hosts", () => { allowedHosts: "auto", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -572,22 +484,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -595,18 +502,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -617,7 +521,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -631,12 +534,9 @@ describe("allowed hosts", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -652,22 +552,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -675,18 +570,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -697,7 +589,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -711,12 +602,9 @@ describe("allowed hosts", () => { allowedHosts: ["all"], }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -732,22 +620,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -755,18 +638,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -777,7 +657,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -791,12 +670,9 @@ describe("allowed hosts", () => { allowedHosts: "my-test-origin.com", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -812,22 +688,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -835,18 +706,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -857,7 +725,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -871,12 +738,9 @@ describe("allowed hosts", () => { allowedHosts: ".my-test-origin.com", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -892,22 +756,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -915,18 +774,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -937,7 +793,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -951,12 +806,9 @@ describe("allowed hosts", () => { allowedHosts: ".my-test-origin.com", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -975,22 +827,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -998,18 +845,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -1020,7 +864,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -1034,12 +877,9 @@ describe("allowed hosts", () => { allowedHosts: ["my-test-origin.com"], }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -1055,22 +895,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1078,18 +913,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -1100,7 +932,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -1114,12 +945,9 @@ describe("allowed hosts", () => { allowedHosts: ["192.168.1.1"], }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -1135,22 +963,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1158,18 +981,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("(work) console messages"); expect(pageErrors).toMatchSnapshot("(work) page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -1180,7 +1000,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -1194,12 +1013,9 @@ describe("allowed hosts", () => { allowedHosts: "auto", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -1215,22 +1031,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1238,18 +1049,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -1260,7 +1068,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -1276,12 +1083,9 @@ describe("allowed hosts", () => { server: "https", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -1298,22 +1102,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1321,18 +1120,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -1343,7 +1139,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -1357,12 +1152,9 @@ describe("allowed hosts", () => { allowedHosts: "auto", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -1378,22 +1170,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1401,18 +1188,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -1423,7 +1207,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -1437,12 +1220,9 @@ describe("allowed hosts", () => { allowedHosts: "auto", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -1459,22 +1239,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1482,13 +1257,10 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - const html = await page.content(); - expect(html).toMatchSnapshot("html"); expect( consoleMessages.map((message) => message.text()), @@ -1496,7 +1268,6 @@ describe("allowed hosts", () => { expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -1507,7 +1278,6 @@ describe("allowed hosts", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -1521,12 +1291,9 @@ describe("allowed hosts", () => { allowedHosts: ["192.168.1.1"], }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -1542,22 +1309,17 @@ describe("allowed hosts", () => { logger: server.logger, }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1565,18 +1327,15 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("(work) console messages"); expect(pageErrors).toMatchSnapshot("(work) page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -1607,17 +1366,12 @@ describe("allowed hosts", () => { allowedHosts: "auto", port: port1, }; - const headers = { host: "localhost", }; - server = new Server(options, compiler); - await server.start(); - ({ page, browser } = await runBrowser()); - page .on("console", (message) => { consoleMessages.push(message); @@ -1625,21 +1379,16 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://127.0.0.1:${port1}/main.js`, { waitUntil: "networkidle0", }); - if (!server.isValidHost(headers, "host")) { throw new Error("Validation didn't fail"); } - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -1648,17 +1397,12 @@ describe("allowed hosts", () => { allowedHosts: "auto", port: port1, }; - const headers = { host: "app.localhost", }; - server = new Server(options, compiler); - await server.start(); - ({ page, browser } = await runBrowser()); - page .on("console", (message) => { consoleMessages.push(message); @@ -1666,21 +1410,16 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://127.0.0.1:${port1}/main.js`, { waitUntil: "networkidle0", }); - if (!server.isValidHost(headers, "host")) { throw new Error("Validation didn't fail"); } - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -1691,17 +1430,12 @@ describe("allowed hosts", () => { allowedHosts: "auto", port: port1, }; - const headers = { host: networkIP, }; - server = new Server(options, compiler); - await server.start(); - ({ page, browser } = await runBrowser()); - page .on("console", (message) => { consoleMessages.push(message); @@ -1709,21 +1443,16 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://${networkIP}:${port1}/main.js`, { waitUntil: "networkidle0", }); - if (!server.isValidHost(headers, "host")) { throw new Error("Validation didn't fail"); } - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -1735,17 +1464,12 @@ describe("allowed hosts", () => { webSocketURL: "ws://test.host:80", }, }; - const headers = { host: "test.host", }; - server = new Server(options, compiler); - await server.start(); - ({ page, browser } = await runBrowser()); - page .on("console", (message) => { consoleMessages.push(message); @@ -1753,21 +1477,16 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://127.0.0.1:${port1}/main.js`, { waitUntil: "networkidle0", }); - if (!server.isValidHost(headers, "host")) { throw new Error("Validation didn't fail"); } - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -1779,13 +1498,9 @@ describe("allowed hosts", () => { const headers = { host: "bad.host", }; - server = new Server(options, compiler); - await server.start(); - ({ page, browser } = await runBrowser()); - page .on("console", (message) => { consoleMessages.push(message); @@ -1793,21 +1508,16 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://127.0.0.1:${port1}/main.js`, { waitUntil: "networkidle0", }); - if (!server.isValidHost(headers, "host")) { throw new Error("Validation didn't fail"); } - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -1817,13 +1527,9 @@ describe("allowed hosts", () => { allowedHosts: tests, port: port1, }; - server = new Server(options, compiler); - await server.start(); - ({ page, browser } = await runBrowser()); - page .on("console", (message) => { consoleMessages.push(message); @@ -1831,25 +1537,21 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://127.0.0.1:${port1}/main.js`, { waitUntil: "networkidle0", }); - for (const test of tests) { - const headers = { host: test }; - + const headers = { + host: test, + }; if (!server.isValidHost(headers, "host")) { throw new Error("Validation didn't fail"); } } - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -1858,13 +1560,9 @@ describe("allowed hosts", () => { allowedHosts: [".example.com"], port: port1, }; - server = new Server(options, compiler); - await server.start(); - ({ page, browser } = await runBrowser()); - page .on("console", (message) => { consoleMessages.push(message); @@ -1872,11 +1570,9 @@ describe("allowed hosts", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://127.0.0.1:${port1}/main.js`, { waitUntil: "networkidle0", }); - const tests = [ "www.example.com", "subdomain.example.com", @@ -1885,21 +1581,18 @@ describe("allowed hosts", () => { "example.com:80", "subdomain.example.com:80", ]; - for (const test of tests) { - const headers = { host: test }; - + const headers = { + host: test, + }; if (!server.isValidHost(headers, "host")) { throw new Error("Validation didn't fail"); } } - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); diff --git a/test/e2e/api.test.js b/test/e2e/api.test.js index ee09842d04..af80653d11 100644 --- a/test/e2e/api.test.js +++ b/test/e2e/api.test.js @@ -1,12 +1,15 @@ -"use strict"; - -const path = require("node:path"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const sessionSubscribe = require("../helpers/session-subscribe"); -const port = require("../ports-map").api; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser, { runPage } from "../helpers/run-browser.js"; +import sessionSubscribe from "../helpers/session-subscribe.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map.api; describe("API", () => { describe("WEBPACK_SERVE environment variable", () => { @@ -20,13 +23,11 @@ describe("API", () => { beforeEach(async () => { // this is important - it clears the cache jest.resetModules(); - - process.env = { ...OLD_ENV }; - + process.env = { + ...OLD_ENV, + }; delete process.env.WEBPACK_SERVE; - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -39,7 +40,6 @@ describe("API", () => { it("should be present", async () => { expect(process.env.WEBPACK_SERVE).toBeUndefined(); - page .on("console", (message) => { consoleMessages.push(message); @@ -47,26 +47,23 @@ describe("API", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - - const WebpackDevServer = require("../../lib/Server"); - + const WebpackDevServer = Server; const compiler = webpack(config); - server = new WebpackDevServer({ port }, compiler); - + server = new WebpackDevServer( + { + port, + }, + compiler, + ); await server.start(); - expect(process.env.WEBPACK_SERVE).toBe("true"); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -74,16 +71,17 @@ describe("API", () => { describe("latest async API", () => { it("should work with async API", async () => { const compiler = webpack(config); - const server = new Server({ port }, compiler); - + const server = new Server( + { + port, + }, + compiler, + ); await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -91,11 +89,9 @@ describe("API", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); @@ -108,20 +104,21 @@ describe("API", () => { it("should work with callback API", async () => { const compiler = webpack(config); - const server = new Server({ port }, compiler); - + const server = new Server( + { + port, + }, + compiler, + ); await new Promise((resolve) => { server.startCallback(() => { resolve(); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -129,11 +126,9 @@ describe("API", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); @@ -151,10 +146,12 @@ describe("API", () => { it("should catch errors within startCallback", async () => { const compiler = webpack(config); const server = new Server( - { port, static: "https://absolute-url.com/somewhere" }, + { + port, + static: "https://absolute-url.com/somewhere", + }, compiler, ); - await new Promise((resolve) => { server.startCallback((err) => { expect(err.message).toBe( @@ -163,7 +160,6 @@ describe("API", () => { resolve(); }); }); - await new Promise((resolve) => { server.stopCallback(() => { resolve(); @@ -176,23 +172,24 @@ describe("API", () => { ...config, entry: [ "webpack/hot/dev-server.js", - `${path.resolve( - __dirname, - "../../client/index.js", - )}?hot=true&live-reload=true"`, + `${path.resolve(__dirname, "../../client/index.js")}?hot=true&live-reload=true"`, path.resolve(__dirname, "../fixtures/client-config/foo.js"), ], plugins: [...config.plugins, new webpack.HotModuleReplacementPlugin()], }); - const server = new Server({ port, hot: false, client: false }, compiler); - + const server = new Server( + { + port, + hot: false, + client: false, + }, + compiler, + ); await server.start(); - const { page, browser } = await runBrowser(); try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -200,11 +197,9 @@ describe("API", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); @@ -217,16 +212,17 @@ describe("API", () => { it("should work and allow to rerun dev server multiple times", async () => { const compiler = webpack(config); - const server = new Server({ port }, compiler); - + const server = new Server( + { + port, + }, + compiler, + ); await server.start(); - const { page: firstPage, browser } = await runBrowser(); - try { const firstPageErrors = []; const firstConsoleMessages = []; - firstPage .on("console", (message) => { firstConsoleMessages.push(message); @@ -234,11 +230,9 @@ describe("API", () => { .on("pageerror", (error) => { firstPageErrors.push(error); }); - await firstPage.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( firstConsoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); @@ -246,15 +240,11 @@ describe("API", () => { } finally { await server.stop(); } - await server.start(); - - const secondPage = await runBrowser.runPage(browser); - + const secondPage = await runPage(browser); try { const secondPageErrors = []; const secondConsoleMessages = []; - secondPage .on("console", (message) => { secondConsoleMessages.push(message); @@ -262,11 +252,9 @@ describe("API", () => { .on("pageerror", (error) => { secondPageErrors.push(error); }); - await secondPage.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( secondConsoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); @@ -288,12 +276,9 @@ describe("API", () => { beforeEach(async () => { compiler = webpack(config); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -301,9 +286,13 @@ describe("API", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - - server = new Server({ port, static: false }, compiler); - + server = new Server( + { + port, + static: false, + }, + compiler, + ); await server.start(); }); @@ -314,17 +303,13 @@ describe("API", () => { it("should use the default `noop` callback when invalidate is called without any callback", async () => { const callback = jest.fn(); - server.invalidate(); server.middleware.context.callbacks[0] = callback; - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(callback).toHaveBeenCalledTimes(1); expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); @@ -333,20 +318,15 @@ describe("API", () => { it("should use the provided `callback` function", async () => { const callback = jest.fn(); - server.invalidate(callback); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(callback).toHaveBeenCalledTimes(1); expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -358,7 +338,6 @@ describe("API", () => { afterEach(() => { delete process.env.WEBPACK_DEV_SERVER_BASE_PORT; delete process.env.WEBPACK_DEV_SERVER_PORT_RETRY; - return dummyServers .reduce( (p, server) => @@ -380,8 +359,13 @@ describe("API", () => { function createDummyServers(n) { const basePort = process.env.WEBPACK_DEV_SERVER_TEST_BASE_PORT || 30000; process.env.WEBPACK_DEV_SERVER_BASE_PORT = basePort; - - return (Array.isArray(n) ? n : Array.from({ length: n })).reduce( + return ( + Array.isArray(n) + ? n + : Array.from({ + length: n, + }) + ).reduce( (p, _, i) => p.then( () => @@ -389,12 +373,13 @@ describe("API", () => { devServerPort = basePort + i; const compiler = webpack(config); const server = new Server( - { port: devServerPort, host: "0.0.0.0" }, + { + port: devServerPort, + host: "0.0.0.0", + }, compiler, ); - dummyServers.push(server); - server.startCallback((err) => { if (err) { // If we get EACCES, try again with a higher port range @@ -421,17 +406,13 @@ describe("API", () => { it("should return the port when the port is specified", async () => { const retryCount = 1; - process.env.WEBPACK_DEV_SERVER_PORT_RETRY = retryCount; - const freePort = await Server.getFreePort(9082); - expect(freePort).toBe(9082); }); it("should return the port when the port is `null`", async () => { const retryCount = 2; - process.env.WEBPACK_DEV_SERVER_PORT_RETRY = retryCount; try { await createDummyServers(retryCount); @@ -440,15 +421,11 @@ describe("API", () => { 10, ); const freePort = await Server.getFreePort(null); - expect(freePort).toEqual(basePort + retryCount); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -456,20 +433,16 @@ describe("API", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${devServerPort}/`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); } catch (error) { if (error.code === "EACCES") { @@ -480,7 +453,6 @@ describe("API", () => { // Get current retry count or initialize to 0 global[retryKey] ||= 0; global[retryKey] += 1; - if (global[retryKey] < maxRetries) { console.warn( `EACCES error encountered (attempt ${global[retryKey]}/${maxRetries}): ${error.message}. Retrying...`, @@ -506,7 +478,6 @@ describe("API", () => { it("should return the port when the port is undefined", async () => { const retryCount = 3; - process.env.WEBPACK_DEV_SERVER_PORT_RETRY = retryCount; try { await createDummyServers(retryCount); @@ -514,17 +485,12 @@ describe("API", () => { process.env.WEBPACK_DEV_SERVER_BASE_PORT, 10, ); - const freePort = await Server.getFreePort(undefined); - expect(freePort).toEqual(basePort + retryCount); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -532,20 +498,16 @@ describe("API", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${devServerPort}/`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); } catch (error) { if (error.code === "EACCES") { @@ -556,7 +518,6 @@ describe("API", () => { // Get current retry count or initialize to 0 global[retryKey] ||= 0; global[retryKey] += 1; - if (global[retryKey] < maxRetries) { console.warn( `EACCES error encountered (attempt ${global[retryKey]}/${maxRetries}): ${error.message}. Retrying...`, @@ -582,9 +543,7 @@ describe("API", () => { it("should retry finding the port for up to defaultPortRetry times (number)", async () => { const retryCount = 4; - process.env.WEBPACK_DEV_SERVER_PORT_RETRY = retryCount; - try { await createDummyServers(retryCount); const basePort = Number.parseInt( @@ -592,15 +551,11 @@ describe("API", () => { 10, ); const freePort = await Server.getFreePort(); - expect(freePort).toEqual(basePort + retryCount); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -608,20 +563,16 @@ describe("API", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${devServerPort}/`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); } catch (error) { if (error.code === "EACCES") { @@ -632,7 +583,6 @@ describe("API", () => { // Get current retry count or initialize to 0 global[retryKey] ||= 0; global[retryKey] += 1; - if (global[retryKey] < maxRetries) { console.warn( `EACCES error encountered (attempt ${global[retryKey]}/${maxRetries}): ${error.message}. Retrying...`, @@ -659,9 +609,7 @@ describe("API", () => { it("should retry finding the port for up to defaultPortRetry times (string)", async () => { const retryCount = 5; - process.env.WEBPACK_DEV_SERVER_PORT_RETRY = retryCount; - try { await createDummyServers(retryCount); const basePort = Number.parseInt( @@ -669,15 +617,11 @@ describe("API", () => { 10, ); const freePort = await Server.getFreePort(); - expect(freePort).toEqual(basePort + retryCount); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -685,20 +629,16 @@ describe("API", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${devServerPort}/`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); } catch (error) { if (error.code === "EACCES") { @@ -709,7 +649,6 @@ describe("API", () => { // Get current retry count or initialize to 0 global[retryKey] ||= 0; global[retryKey] += 1; - if (global[retryKey] < maxRetries) { console.warn( `EACCES error encountered (attempt ${global[retryKey]}/${maxRetries}): ${error.message}. Retrying...`, @@ -739,23 +678,22 @@ describe("API", () => { process.env.WEBPACK_DEV_SERVER_TEST_BASE_PORT || 30000, 10, ); - const busyPorts = Array.from({ length: 6 }, (_, i) => basePort + i); - + const busyPorts = Array.from( + { + length: 6, + }, + (_, i) => basePort + i, + ); process.env.WEBPACK_DEV_SERVER_PORT_RETRY = 1000; - await createDummyServers(busyPorts); - const freePort = await Server.getFreePort(); // to use the last port in the busyPorts array const lastBusyPort = busyPorts[busyPorts.length - 1]; expect(freePort).toBeGreaterThan(lastBusyPort); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -763,7 +701,6 @@ describe("API", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - try { const response = await page.goto( `http://localhost:${devServerPort}/`, @@ -771,13 +708,10 @@ describe("API", () => { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); } catch (error) { if (error.code === "EACCES") { @@ -788,7 +722,6 @@ describe("API", () => { // Get current retry count or initialize to 0 global[retryKey] ||= 0; global[retryKey] += 1; - if (global[retryKey] < maxRetries) { console.warn( `EACCES error encountered (attempt ${global[retryKey]}/${maxRetries}): ${error.message}. Retrying...`, @@ -808,7 +741,6 @@ describe("API", () => { // Get current retry count or initialize to 0 global[retryKey] ||= 0; global[retryKey] += 1; - if (global[retryKey] < maxRetries) { console.warn( `EACCES error encountered (attempt ${global[retryKey]}/${maxRetries}): ${error.message}. Retrying...`, @@ -825,14 +757,11 @@ describe("API", () => { it("should throw the error when the port isn't found", async () => { expect.assertions(1); - jest.mock( "../../lib/getPort", () => () => Promise.reject(new Error("busy")), ); - process.env.WEBPACK_DEV_SERVER_PORT_RETRY = 1; - try { await Server.getFreePort(); } catch (error) { @@ -846,7 +775,6 @@ describe("API", () => { const options = { allowedHosts: "all", }; - const tests = [ "192.168.1.123", "192.168.1.2:8080", @@ -855,20 +783,17 @@ describe("API", () => { "[ad42::1de2:54c2:c2fa:1234]", "[ad42::1de2:54c2:c2fa:1234]:8080", ]; - const compiler = webpack(config); const server = new Server(options, compiler); - let isValidHost = true; - for (const test of tests) { - const headers = { host: test }; - + const headers = { + host: test, + }; if (!server.isValidHost(headers, "host")) { isValidHost = false; } } - expect(isValidHost).toBe(true); }); @@ -886,18 +811,13 @@ describe("API", () => { const headers = { origin: "https://test.host", }; - const compiler = webpack(config); const server = new Server(options, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -905,53 +825,41 @@ describe("API", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - try { const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - if (!server.isValidHost(headers, "origin")) { throw new Error("Validation didn't fail"); } - await new Promise((resolve) => { const interval = setInterval(() => { const needFinish = consoleMessages.filter((message) => /Trying to reconnect/.test(message.text()), ); - if (needFinish.length > 0) { clearInterval(interval); resolve(); } }, 100); }); - expect(webSocketRequests[0].url).toMatchSnapshot("web socket URL"); - expect(response.status()).toMatchSnapshot("response status"); - expect( // net::ERR_NAME_NOT_RESOLVED can be multiple times consoleMessages.map((message) => message.text()).slice(0, 7), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); } catch (error) { if (error.code === "EACCES") { @@ -962,7 +870,6 @@ describe("API", () => { // Get current retry count or initialize to 0 global[retryKey] ||= 0; global[retryKey] += 1; - if (global[retryKey] < maxRetries) { console.warn( `EACCES error encountered (attempt ${global[retryKey]}/${maxRetries}): ${error.message}. Retrying...`, @@ -982,7 +889,6 @@ describe("API", () => { // Get current retry count or initialize to 0 global[retryKey] ||= 0; global[retryKey] += 1; - if (global[retryKey] < maxRetries) { console.warn( `EACCES error encountered (attempt ${global[retryKey]}/${maxRetries}): ${error.message}. Retrying...`, diff --git a/test/e2e/app.test.js b/test/e2e/app.test.js index b98b9f65e9..72d4e1b755 100644 --- a/test/e2e/app.test.js +++ b/test/e2e/app.test.js @@ -1,31 +1,38 @@ -"use strict"; - -const fs = require("node:fs"); -const path = require("node:path"); -const webpack = require("webpack"); -const wdm = require("webpack-dev-middleware"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map").app; - +import fs from "node:fs"; +import http2 from "node:http2"; +import https from "node:https"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { createAdaptorServer } from "@hono/node-server"; +import connect from "connect"; +import express from "express"; +import { Hono } from "hono"; +import webpack from "webpack"; +import wdm from "webpack-dev-middleware"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map.app; const staticDirectory = path.resolve( __dirname, "../fixtures/static-config/public", ); - const apps = [ - ["express", () => require("express")(), "http"], - ["express", () => require("express")(), "https"], - ["connect", () => require("connect")(), "http"], - ["connect", () => require("connect")(), "https"], - ["connect", () => require("connect")(), "http2"], - ["connect (async)", () => require("connect")(), "http"], + ["express", () => express(), "http"], + ["express", () => express(), "https"], + ["connect", () => connect(), "http"], + ["connect", () => connect(), "https"], + ["connect", () => connect(), "http2"], + ["connect (async)", () => connect(), "http"], [ "hono", - () => new (require("hono").Hono)(), + () => new Hono(), (options, app) => - require("@hono/node-server").createAdaptorServer({ + createAdaptorServer({ fetch: app.fetch, }), (_, devServer) => [ @@ -37,11 +44,11 @@ const apps = [ ], [ "hono", - () => new (require("hono").Hono)(), + () => new Hono(), (_, app) => - require("@hono/node-server").createAdaptorServer({ + createAdaptorServer({ fetch: app.fetch, - createServer: require("node:https").createServer, + createServer: https.createServer, serverOptions: { key: fs.readFileSync( path.resolve(__dirname, "../fixtures/ssl/localhost-privkey.pem"), @@ -60,12 +67,12 @@ const apps = [ ], [ "hono", - () => new (require("hono").Hono)(), + () => new Hono(), { type: (options, app) => - require("@hono/node-server").createAdaptorServer({ + createAdaptorServer({ fetch: app.fetch, - createServer: require("node:http2").createSecureServer, + createServer: http2.createSecureServer, serverOptions: options, }), options: { @@ -99,7 +106,6 @@ describe("app option", () => { describe(`should work using "${appName}" application and "${typeof server === "function" ? "custom server" : server}" server`, () => { beforeEach(async () => { compiler = webpack(config); - devServer = new Server( { static: { @@ -116,11 +122,8 @@ describe("app option", () => { }, compiler, ); - await devServer.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -143,19 +146,15 @@ describe("app option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const pageUrl = devServer.isTlsServer ? `https://localhost:${port}/` : `http://localhost:${port}/`; - const response = await page.goto(pageUrl, { waitUntil: "networkidle0", }); - const HTTPVersion = await page.evaluate( () => performance.getEntries()[0].nextHopProtocol, ); - if ( server === "http2" || (server.options && server.options.allowHTTP1) @@ -164,11 +163,8 @@ describe("app option", () => { } else { expect(HTTPVersion).toBe("http/1.1"); } - expect(response.status()).toBe(200); - const text = await response.text(); - expect(text).toContain( '', ); diff --git a/test/e2e/bonjour.test.js b/test/e2e/bonjour.test.js index 5f2bc90aab..297865299c 100644 --- a/test/e2e/bonjour.test.js +++ b/test/e2e/bonjour.test.js @@ -1,11 +1,11 @@ -"use strict"; +import os from "node:os"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/simple-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; -const os = require("node:os"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/simple-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map").bonjour; +const port = _ports_map.bonjour; describe("bonjour option", () => { let mockPublish; @@ -36,15 +36,16 @@ describe("bonjour option", () => { destroy: mockDestroy, })), })); - compiler = webpack(config); - - server = new Server({ port, bonjour: true }, compiler); - + server = new Server( + { + port, + bonjour: true, + }, + compiler, + ); await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -52,7 +53,6 @@ describe("bonjour option", () => { afterEach(async () => { await browser.close(); await server.stop(); - mockPublish.mockReset(); mockUnpublishAll.mockReset(); mockDestroy.mockReset(); @@ -66,29 +66,22 @@ describe("bonjour option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(mockPublish).toHaveBeenCalledTimes(1); - expect(mockPublish).toHaveBeenCalledWith({ name: `Webpack Dev Server ${os.hostname()}:${port}`, port, type: "http", subtypes: ["webpack"], }); - expect(mockUnpublishAll).toHaveBeenCalledTimes(0); expect(mockDestroy).toHaveBeenCalledTimes(0); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -109,15 +102,17 @@ describe("bonjour option", () => { destroy: mockDestroy, })), })); - compiler = webpack(config); - - server = new Server({ bonjour: true, port, server: "https" }, compiler); - + server = new Server( + { + bonjour: true, + port, + server: "https", + }, + compiler, + ); await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -135,29 +130,22 @@ describe("bonjour option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`https://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(mockPublish).toHaveBeenCalledTimes(1); - expect(mockPublish).toHaveBeenCalledWith({ name: `Webpack Dev Server ${os.hostname()}:${port}`, port, type: "https", subtypes: ["webpack"], }); - expect(mockUnpublishAll).toHaveBeenCalledTimes(0); expect(mockDestroy).toHaveBeenCalledTimes(0); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -178,9 +166,7 @@ describe("bonjour option", () => { destroy: mockDestroy, })), })); - compiler = webpack(config); - server = new Server( { port, @@ -191,11 +177,8 @@ describe("bonjour option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -213,13 +196,10 @@ describe("bonjour option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(mockPublish).toHaveBeenCalledTimes(1); - expect(mockPublish).toHaveBeenCalledWith({ name: `Webpack Dev Server ${os.hostname()}:${port}`, port, @@ -227,16 +207,12 @@ describe("bonjour option", () => { protocol: "udp", subtypes: ["webpack"], }); - expect(mockUnpublishAll).toHaveBeenCalledTimes(0); expect(mockDestroy).toHaveBeenCalledTimes(0); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -257,9 +233,7 @@ describe("bonjour option", () => { destroy: mockDestroy, })), })); - compiler = webpack(config); - server = new Server( { port, @@ -273,11 +247,8 @@ describe("bonjour option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -295,13 +266,10 @@ describe("bonjour option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`https://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(mockPublish).toHaveBeenCalledTimes(1); - expect(mockPublish).toHaveBeenCalledWith({ name: `Webpack Dev Server ${os.hostname()}:${port}`, port, @@ -309,16 +277,12 @@ describe("bonjour option", () => { protocol: "udp", subtypes: ["webpack"], }); - expect(mockUnpublishAll).toHaveBeenCalledTimes(0); expect(mockDestroy).toHaveBeenCalledTimes(0); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); diff --git a/test/e2e/built-in-routes.test.js b/test/e2e/built-in-routes.test.js index a0af821a2a..9618b51f90 100644 --- a/test/e2e/built-in-routes.test.js +++ b/test/e2e/built-in-routes.test.js @@ -1,11 +1,11 @@ -"use strict"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import multiConfig from "../fixtures/multi-public-path-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const multiConfig = require("../fixtures/multi-public-path-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map").routes; +const port = _ports_map.routes; describe("Built in routes", () => { describe("with simple config", () => { @@ -18,12 +18,14 @@ describe("Built in routes", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server({ port }, compiler); - + server = new Server( + { + port, + }, + compiler, + ); await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -41,22 +43,17 @@ describe("Built in routes", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}/webpack-dev-server/invalidate`, { waitUntil: "networkidle0", }, ); - expect(response.headers()["content-type"]).not.toBe("text/html"); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -68,26 +65,20 @@ describe("Built in routes", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}/webpack-dev-server/`, { waitUntil: "networkidle0", }, ); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("directory list"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -101,29 +92,24 @@ describe("Built in routes", () => { }) .on("request", (interceptedRequest) => { if (interceptedRequest.isInterceptResolutionHandled()) return; - - interceptedRequest.continue({ method: "HEAD" }); + interceptedRequest.continue({ + method: "HEAD", + }); }); - const response = await page.goto( `http://localhost:${port}/webpack-dev-server/`, { waitUntil: "networkidle0", }, ); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("directory list"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -135,17 +121,13 @@ describe("Built in routes", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/main.js`, { waitUntil: "networkidle0", }); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); @@ -161,20 +143,17 @@ describe("Built in routes", () => { }) .on("request", (interceptedRequest) => { if (interceptedRequest.isInterceptResolutionHandled()) return; - - interceptedRequest.continue({ method: "HEAD" }); + interceptedRequest.continue({ + method: "HEAD", + }); }); - const response = await page.goto(`http://localhost:${port}/main.js`, { waitUntil: "networkidle0", }); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); @@ -191,12 +170,14 @@ describe("Built in routes", () => { beforeEach(async () => { compiler = webpack(multiConfig); - server = new Server({ port }, compiler); - + server = new Server( + { + port, + }, + compiler, + ); await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -214,26 +195,20 @@ describe("Built in routes", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}/webpack-dev-server/`, { waitUntil: "networkidle0", }, ); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("directory list"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); diff --git a/test/e2e/client-reconnect.test.js b/test/e2e/client-reconnect.test.js index eff831783d..4f1c8b2bc4 100644 --- a/test/e2e/client-reconnect.test.js +++ b/test/e2e/client-reconnect.test.js @@ -1,10 +1,10 @@ -"use strict"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/simple-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/simple-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["client-reconnect-option"]; +const port = _ports_map["client-reconnect-option"]; describe("client.reconnect option", () => { describe("specified as true", () => { @@ -17,13 +17,17 @@ describe("client.reconnect option", () => { beforeEach(async () => { compiler = webpack(config); - - server = new Server({ port, client: { reconnect: true } }, compiler); - + server = new Server( + { + port, + client: { + reconnect: true, + }, + }, + compiler, + ); await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -40,33 +44,26 @@ describe("client.reconnect option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - try { expect(response.status()).toMatchSnapshot("response status"); } finally { await server.stop(); } - let interval; - await new Promise((resolve) => { interval = setInterval(() => { const retryingMessages = consoleMessages.filter((message) => message.text().includes("Trying to reconnect..."), ); - if (retryingMessages.length >= 5) { clearInterval(interval); - resolve(); } }, 1000); }); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -81,13 +78,17 @@ describe("client.reconnect option", () => { beforeEach(async () => { compiler = webpack(config); - - server = new Server({ port, client: { reconnect: false } }, compiler); - + server = new Server( + { + port, + client: { + reconnect: false, + }, + }, + compiler, + ); await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -104,11 +105,9 @@ describe("client.reconnect option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - try { expect(response.status()).toMatchSnapshot("response status"); } finally { @@ -124,11 +123,9 @@ describe("client.reconnect option", () => { 1000 * 2 ** 3, ); }); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -143,13 +140,17 @@ describe("client.reconnect option", () => { beforeEach(async () => { compiler = webpack(config); - - server = new Server({ port, client: { reconnect: 2 } }, compiler); - + server = new Server( + { + port, + client: { + reconnect: 2, + }, + }, + compiler, + ); await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -166,11 +167,9 @@ describe("client.reconnect option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - try { expect(response.status()).toMatchSnapshot("response status"); } finally { @@ -186,11 +185,9 @@ describe("client.reconnect option", () => { 1000 * 2 ** 3, ); }); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); diff --git a/test/e2e/client.test.js b/test/e2e/client.test.js index 5c779a2cbd..8369c5c3b6 100644 --- a/test/e2e/client.test.js +++ b/test/e2e/client.test.js @@ -1,11 +1,13 @@ -"use strict"; +import { createRequire } from "node:module"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import sessionSubscribe from "../helpers/session-subscribe.js"; +import _ports_map from "../ports-map.js"; -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const sessionSubscribe = require("../helpers/session-subscribe"); -const port = require("../ports-map")["client-option"]; +const require = createRequire(import.meta.url); +const port = _ports_map["client-option"]; describe("client option", () => { describe("default behaviour", () => { @@ -18,7 +20,6 @@ describe("client option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { client: { @@ -29,11 +30,8 @@ describe("client option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -51,39 +49,30 @@ describe("client option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); // overlay should be true by default expect(server.options.client.overlay).toBe(true); - expect(response.status()).toMatchSnapshot("response status"); - expect(webSocketRequests.map((request) => request.url)).toMatchSnapshot( "webSockets", ); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -98,7 +87,6 @@ describe("client option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { client: { @@ -118,11 +106,8 @@ describe("client option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -140,34 +125,26 @@ describe("client option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(webSocketRequests.map((request) => request.url)).toMatchSnapshot( "webSockets", ); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -182,7 +159,6 @@ describe("client option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { client: false, @@ -190,11 +166,8 @@ describe("client option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -212,36 +185,26 @@ describe("client option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - const response = await page.goto(`http://localhost:${port}/main.js`, { waitUntil: "networkidle0", }); - expect(webSocketRequests).toMatchSnapshot("webSockets"); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).not.toMatch(/client\/index\.js/); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -251,7 +214,6 @@ describe("client option", () => { let server; let page; let browser; - class OverrideServer extends Server { getClientEntry() { return require.resolve( @@ -268,16 +230,13 @@ describe("client option", () => { beforeEach(async () => { compiler = webpack(config); - server = new OverrideServer( { port, }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); }); @@ -290,9 +249,7 @@ describe("client option", () => { const response = await page.goto(`http://localhost:${port}/main.js`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - const content = await response.text(); expect(content).toContain("CustomClientEntry.js"); expect(content).toContain("CustomClientHotEntry.js"); @@ -331,11 +288,8 @@ describe("client option", () => { describe("passed to server", () => { for (const data of clientModes) { - it(`${data.title} ${ - data.shouldThrow ? "should throw" : "should not throw" - }`, async () => { + it(`${data.title} ${data.shouldThrow ? "should throw" : "should not throw"}`, async () => { const compiler = webpack(config); - const server = new Server( { client: data.client, @@ -343,21 +297,17 @@ describe("client option", () => { }, compiler, ); - let thrownError; - try { await server.start(); } catch (error) { thrownError = error; } - if (data.shouldThrow) { expect(thrownError.message).toMatch( /client\.webSocketTransport must be a string/, ); } - await server.stop(); }); } diff --git a/test/e2e/compress.test.js b/test/e2e/compress.test.js index 4436292e8f..5c8c38838f 100644 --- a/test/e2e/compress.test.js +++ b/test/e2e/compress.test.js @@ -1,10 +1,10 @@ -"use strict"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/simple-config-other/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/simple-config-other/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["compress-option"]; +const port = _ports_map["compress-option"]; describe("compress option", () => { describe("enabled by default when not specified", () => { @@ -17,13 +17,14 @@ describe("compress option", () => { beforeEach(async () => { compiler = webpack(config); - - server = new Server({ port }, compiler); - + server = new Server( + { + port, + }, + compiler, + ); await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -41,21 +42,16 @@ describe("compress option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/main.js`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(response.headers()["content-encoding"]).toMatchSnapshot( "response headers content-encoding", ); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -70,7 +66,6 @@ describe("compress option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { compress: true, @@ -78,11 +73,8 @@ describe("compress option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -100,21 +92,16 @@ describe("compress option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/main.js`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(response.headers()["content-encoding"]).toMatchSnapshot( "response headers content-encoding", ); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -129,7 +116,6 @@ describe("compress option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { compress: false, @@ -137,11 +123,8 @@ describe("compress option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -159,21 +142,16 @@ describe("compress option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/main.js`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(response.headers()["content-encoding"]).toMatchSnapshot( "response headers content-encoding", ); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); diff --git a/test/e2e/cross-origin-request.test.js b/test/e2e/cross-origin-request.test.js index d003024928..538b23e7c1 100644 --- a/test/e2e/cross-origin-request.test.js +++ b/test/e2e/cross-origin-request.test.js @@ -1,10 +1,11 @@ -"use strict"; +import http from "node:http"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const [port1, port2] = require("../ports-map")["cross-origin-request"]; +const [port1, port2] = _ports_map["cross-origin-request"]; describe("cross-origin requests", () => { const devServerPort = port1; @@ -18,14 +19,13 @@ describe("cross-origin requests", () => { allowedHosts: "auto", }; const server = new Server(devServerOptions, compiler); - await server.start(); // Start a separate server for serving the HTML file - const http = require("node:http"); - const htmlServer = http.createServer((req, res) => { - res.writeHead(200, { "Content-Type": "text/html" }); + res.writeHead(200, { + "Content-Type": "text/html", + }); res.end(` @@ -36,24 +36,17 @@ describe("cross-origin requests", () => { `); }); htmlServer.listen(htmlServerPort, htmlServerHost); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; - page.on("pageerror", (error) => { pageErrors.push(error); }); - const scriptTagRequest = page.waitForResponse( `http://localhost:${devServerPort}/main.js`, ); - await page.goto(`http://${htmlServerHost}:${htmlServerPort}`); - const response = await scriptTagRequest; - expect(response.status()).toBe(403); } finally { await browser.close(); @@ -72,14 +65,13 @@ describe("cross-origin requests", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); // Start a separate server for serving the HTML file - const http = require("node:http"); - const htmlServer = http.createServer((req, res) => { - res.writeHead(200, { "Content-Type": "text/html" }); + res.writeHead(200, { + "Content-Type": "text/html", + }); res.end(` @@ -90,24 +82,17 @@ describe("cross-origin requests", () => { `); }); htmlServer.listen(htmlServerPort, htmlServerHost); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; - page.on("pageerror", (error) => { pageErrors.push(error); }); - const scriptTagRequest = page.waitForResponse( `http://localhost:${devServerPort}/main.js`, ); - await page.goto(`http://${htmlServerHost}:${htmlServerPort}`); - const response = await scriptTagRequest; - expect(response.status()).toBe(200); } finally { await browser.close(); @@ -123,14 +108,13 @@ describe("cross-origin requests", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); // Start a separate server for serving the HTML file - const http = require("node:http"); - const htmlServer = http.createServer((req, res) => { - res.writeHead(200, { "Content-Type": "text/html" }); + res.writeHead(200, { + "Content-Type": "text/html", + }); res.end(` @@ -141,24 +125,17 @@ describe("cross-origin requests", () => { `); }); htmlServer.listen(htmlServerPort, htmlServerHost); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; - page.on("pageerror", (error) => { pageErrors.push(error); }); - const scriptTagRequest = page.waitForResponse( `http://localhost:${devServerPort}/main.js`, ); - await page.goto(`http://${htmlServerHost}:${htmlServerPort}`); - const response = await scriptTagRequest; - expect(response.status()).toBe(200); } finally { await browser.close(); @@ -174,14 +151,13 @@ describe("cross-origin requests", () => { allowedHosts: ["localhost"], }; const server = new Server(devServerOptions, compiler); - await server.start(); // Start a separate server for serving the HTML file - const http = require("node:http"); - const htmlServer = http.createServer((req, res) => { - res.writeHead(200, { "Content-Type": "text/html" }); + res.writeHead(200, { + "Content-Type": "text/html", + }); res.end(` @@ -192,24 +168,17 @@ describe("cross-origin requests", () => { `); }); htmlServer.listen(htmlServerPort, htmlServerHost); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; - page.on("pageerror", (error) => { pageErrors.push(error); }); - const scriptTagRequest = page.waitForResponse( `http://localhost:${devServerPort}/main.js`, ); - await page.goto(`http://${htmlServerHost}:${htmlServerPort}`); - const response = await scriptTagRequest; - expect(response.status()).toBe(200); } finally { await browser.close(); diff --git a/test/e2e/entry.test.js b/test/e2e/entry.test.js index 311d87c333..1579ab55b9 100644 --- a/test/e2e/entry.test.js +++ b/test/e2e/entry.test.js @@ -1,21 +1,21 @@ -"use strict"; - -const path = require("node:path"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map").entry; - +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map.entry; const HOT_ENABLED_MESSAGE = "[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled."; - const waitForConsoleLogFinished = async (consoleLogs) => { await new Promise((resolve) => { const interval = setInterval(() => { if (consoleLogs.includes(HOT_ENABLED_MESSAGE)) { clearInterval(interval); - resolve(); } }, 100); @@ -33,20 +33,19 @@ describe("entry", () => { ); it("should work with single entry", async () => { - const compiler = webpack({ ...config, entry: entryFirst }); + const compiler = webpack({ + ...config, + entry: entryFirst, + }); const devServerOptions = { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -54,11 +53,9 @@ describe("entry", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); @@ -70,20 +67,19 @@ describe("entry", () => { }); it("should work with single array entry", async () => { - const compiler = webpack({ ...config, entry: [entryFirst, entrySecond] }); + const compiler = webpack({ + ...config, + entry: [entryFirst, entrySecond], + }); const devServerOptions = { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -91,11 +87,9 @@ describe("entry", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); @@ -110,22 +104,20 @@ describe("entry", () => { const compiler = webpack({ ...config, entry: { - main: { import: entryFirst }, + main: { + import: entryFirst, + }, }, }); const devServerOptions = { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -133,11 +125,9 @@ describe("entry", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); @@ -149,20 +139,19 @@ describe("entry", () => { }); it("should work with dynamic entry", async () => { - const compiler = webpack({ ...config, entry: () => entryFirst }); + const compiler = webpack({ + ...config, + entry: () => entryFirst, + }); const devServerOptions = { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -170,11 +159,9 @@ describe("entry", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); @@ -197,15 +184,11 @@ describe("entry", () => { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -213,11 +196,9 @@ describe("entry", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); @@ -245,15 +226,11 @@ describe("entry", () => { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message.text()); @@ -261,14 +238,16 @@ describe("entry", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/test.html`, { waitUntil: "networkidle0", }); - await page.addScriptTag({ url: `http://localhost:${port}/runtime.js` }); - await page.addScriptTag({ url: `http://localhost:${port}/foo.js` }); + await page.addScriptTag({ + url: `http://localhost:${port}/runtime.js`, + }); + await page.addScriptTag({ + url: `http://localhost:${port}/foo.js`, + }); await waitForConsoleLogFinished(consoleMessages); - expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { @@ -294,15 +273,11 @@ describe("entry", () => { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message.text()); @@ -310,14 +285,16 @@ describe("entry", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/test.html`, { waitUntil: "networkidle0", }); - await page.addScriptTag({ url: `http://localhost:${port}/runtime.js` }); - await page.addScriptTag({ url: `http://localhost:${port}/bar.js` }); + await page.addScriptTag({ + url: `http://localhost:${port}/runtime.js`, + }); + await page.addScriptTag({ + url: `http://localhost:${port}/bar.js`, + }); await waitForConsoleLogFinished(consoleMessages); - expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { @@ -341,15 +318,11 @@ describe("entry", () => { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message.text()); @@ -357,14 +330,16 @@ describe("entry", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/test.html`, { waitUntil: "networkidle0", }); - await page.addScriptTag({ url: `http://localhost:${port}/bar.js` }); - await page.addScriptTag({ url: `http://localhost:${port}/foo.js` }); + await page.addScriptTag({ + url: `http://localhost:${port}/bar.js`, + }); + await page.addScriptTag({ + url: `http://localhost:${port}/foo.js`, + }); await waitForConsoleLogFinished(consoleMessages); - expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { @@ -378,24 +353,18 @@ describe("entry", () => { ...config, entry: {}, }); - new webpack.EntryPlugin(compiler.context, entryFirst, { name: "main", }).apply(compiler); - const devServerOptions = { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -403,11 +372,9 @@ describe("entry", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); diff --git a/test/e2e/headers.test.js b/test/e2e/headers.test.js index efaddab452..5c2f906990 100644 --- a/test/e2e/headers.test.js +++ b/test/e2e/headers.test.js @@ -1,11 +1,11 @@ -"use strict"; +import request from "supertest"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/simple-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; -const request = require("supertest"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/simple-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["headers-option"]; +const port = _ports_map["headers-option"]; describe("headers option", () => { describe("as a string", () => { @@ -18,19 +18,17 @@ describe("headers option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { - headers: { "X-Foo": "dev-server headers" }, + headers: { + "X-Foo": "dev-server headers", + }, port, }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -48,21 +46,16 @@ describe("headers option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.headers()["x-foo"]).toMatchSnapshot( "response headers x-foo", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -77,7 +70,6 @@ describe("headers option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { headers: [ @@ -94,11 +86,8 @@ describe("headers option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -116,25 +105,19 @@ describe("headers option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.headers()["x-foo"]).toMatchSnapshot( "response headers x-foo", ); - expect(response.headers()["x-bar"]).toMatchSnapshot( "response headers x-bar", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -149,19 +132,17 @@ describe("headers option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { - headers: { "X-Bar": ["key1=value1", "key2=value2"] }, + headers: { + "X-Bar": ["key1=value1", "key2=value2"], + }, port, }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -179,21 +160,16 @@ describe("headers option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.headers()["x-bar"]).toMatchSnapshot( "response headers x-bar", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -208,19 +184,17 @@ describe("headers option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { - headers: () => ({ "X-Bar": ["key1=value1", "key2=value2"] }), + headers: () => ({ + "X-Bar": ["key1=value1", "key2=value2"], + }), port, }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -238,21 +212,16 @@ describe("headers option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.headers()["x-bar"]).toMatchSnapshot( "response headers x-bar", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -267,7 +236,6 @@ describe("headers option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { headers: () => [ @@ -284,11 +252,8 @@ describe("headers option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -306,25 +271,19 @@ describe("headers option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.headers()["x-foo"]).toMatchSnapshot( "response headers x-foo", ); - expect(response.headers()["x-bar"]).toMatchSnapshot( "response headers x-bar", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -339,22 +298,22 @@ describe("headers option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { - headers: { "X-Foo": "dev-server-headers" }, + headers: { + "X-Foo": "dev-server-headers", + }, devMiddleware: { - headers: { "X-Foo": "dev-middleware-headers" }, + headers: { + "X-Foo": "dev-middleware-headers", + }, }, port, }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -372,21 +331,16 @@ describe("headers option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.headers()["x-foo"]).toMatchSnapshot( "response headers x-foo", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -402,21 +356,18 @@ describe("headers option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { - headers: { "X-Foo": "dev-server headers" }, + headers: { + "X-Foo": "dev-server headers", + }, port, }, compiler, ); - await server.start(); - req = request(server.app); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -434,11 +385,9 @@ describe("headers option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.headers()["x-foo"]).toMatchSnapshot( "response headers x-foo", ); @@ -447,9 +396,7 @@ describe("headers option", () => { "console messages", ); expect(pageErrors).toMatchSnapshot("page errors"); - const responseForHead = await req.get("/"); - expect(responseForHead.headers["x-foo"]).toBe("dev-server headers"); }); }); diff --git a/test/e2e/history-api-fallback.test.js b/test/e2e/history-api-fallback.test.js index b6506e85af..2986552c9f 100644 --- a/test/e2e/history-api-fallback.test.js +++ b/test/e2e/history-api-fallback.test.js @@ -1,13 +1,16 @@ -"use strict"; - -const path = require("node:path"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config2 = require("../fixtures/historyapifallback-2-config/webpack.config"); -const config3 = require("../fixtures/historyapifallback-3-config/webpack.config"); -const config = require("../fixtures/historyapifallback-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["history-api-fallback-option"]; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config2 from "../fixtures/historyapifallback-2-config/webpack.config.js"; +import config3 from "../fixtures/historyapifallback-3-config/webpack.config.js"; +import config from "../fixtures/historyapifallback-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map["history-api-fallback-option"]; describe("historyApiFallback option", () => { describe("as boolean", () => { @@ -20,7 +23,6 @@ describe("historyApiFallback option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { historyApiFallback: true, @@ -28,11 +30,8 @@ describe("historyApiFallback option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -50,23 +49,17 @@ describe("historyApiFallback option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/foo`, { waitUntil: "networkidle0", }); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -81,7 +74,6 @@ describe("historyApiFallback option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { historyApiFallback: { @@ -91,11 +83,8 @@ describe("historyApiFallback option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -113,23 +102,17 @@ describe("historyApiFallback option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/foo`, { waitUntil: "networkidle0", }); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -144,7 +127,6 @@ describe("historyApiFallback option", () => { beforeEach(async () => { compiler = webpack(config2); - server = new Server( { static: path.resolve( @@ -158,11 +140,8 @@ describe("historyApiFallback option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -180,23 +159,17 @@ describe("historyApiFallback option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/foo`, { waitUntil: "networkidle0", }); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -208,26 +181,20 @@ describe("historyApiFallback option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}/random-file.txt`, { waitUntil: "networkidle2", }, ); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -242,7 +209,6 @@ describe("historyApiFallback option", () => { beforeEach(async () => { compiler = webpack(config3); - server = new Server( { static: false, @@ -253,11 +219,8 @@ describe("historyApiFallback option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -275,23 +238,17 @@ describe("historyApiFallback option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/index.html`, { waitUntil: "networkidle0", }); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -306,7 +263,6 @@ describe("historyApiFallback option", () => { beforeEach(async () => { compiler = webpack(config2); - server = new Server( { port, @@ -329,11 +285,8 @@ describe("historyApiFallback option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -351,23 +304,17 @@ describe("historyApiFallback option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -379,23 +326,17 @@ describe("historyApiFallback option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/acme`, { waitUntil: "networkidle0", }); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -407,23 +348,17 @@ describe("historyApiFallback option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/other`, { waitUntil: "networkidle0", }); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -439,9 +374,7 @@ describe("historyApiFallback option", () => { beforeEach(async () => { consoleSpy = jest.spyOn(globalThis.console, "log"); - compiler = webpack(config); - server = new Server( { historyApiFallback: { @@ -452,11 +385,8 @@ describe("historyApiFallback option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -475,19 +405,14 @@ describe("historyApiFallback option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/foo`, { waitUntil: "networkidle0", }); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleSpy).toHaveBeenCalledWith( "Rewriting", "GET", @@ -495,11 +420,9 @@ describe("historyApiFallback option", () => { "to", "/bar.html", ); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -515,9 +438,7 @@ describe("historyApiFallback option", () => { beforeEach(async () => { consoleSpy = jest.spyOn(globalThis.console, "log"); - compiler = webpack(config); - server = new Server( { historyApiFallback: { @@ -528,11 +449,8 @@ describe("historyApiFallback option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -551,19 +469,14 @@ describe("historyApiFallback option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/foo`, { waitUntil: "networkidle0", }); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleSpy).toHaveBeenCalledWith( "Rewriting", "GET", @@ -571,11 +484,9 @@ describe("historyApiFallback option", () => { "to", "/bar.html", ); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -590,7 +501,6 @@ describe("historyApiFallback option", () => { beforeEach(async () => { compiler = webpack(config3); - server = new Server( { static: path.resolve( @@ -602,11 +512,8 @@ describe("historyApiFallback option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -624,23 +531,17 @@ describe("historyApiFallback option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/foo`, { waitUntil: "networkidle0", }); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -648,35 +549,31 @@ describe("historyApiFallback option", () => { await page.goto(`http://localhost:${port}/foo`, { waitUntil: "networkidle0", }); - const responseGet = await page.evaluate(async () => { - const response = await fetch("/foo", { method: "GET" }); - + const response = await fetch("/foo", { + method: "GET", + }); return { contentType: response.headers.get("content-type"), statusText: response.statusText, text: await response.text(), }; }); - expect(responseGet.contentType).toMatchSnapshot( "response headers content-type", ); - expect(responseGet.statusText).toMatchSnapshot("response status"); - expect(responseGet.text).toMatchSnapshot("response text"); - const responseHead = await page.evaluate(async () => { - const response = await fetch("/foo", { method: "HEAD" }); - + const response = await fetch("/foo", { + method: "HEAD", + }); return { contentType: response.headers.get("content-type"), statusText: response.statusText, text: await response.text(), }; }); - expect(responseHead).toMatchObject({ ...responseGet, // HEAD response has an empty body diff --git a/test/e2e/host.test.js b/test/e2e/host.test.js index fe79392ca4..be127bc085 100644 --- a/test/e2e/host.test.js +++ b/test/e2e/host.test.js @@ -1,18 +1,15 @@ -"use strict"; - -const http = require("node:http"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map").host; - +import http from "node:http"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const port = _ports_map.host; const ipv4 = Server.findIp("v4", false); const ipv6 = Server.findIp("v6", false); - async function getAddress(host, hostname) { let address; - if ( typeof host === "undefined" || (typeof host === "string" && (host === "" || host === "::")) @@ -29,20 +26,22 @@ async function getAddress(host, hostname) { res.setHeader("Content-Type", "text/plain"); res.end("Hello World\n"); }); - await new Promise((resolve) => { - server.listen({ host: "localhost", port: 23100 }, resolve); + server.listen( + { + host: "localhost", + port: 23100, + }, + resolve, + ); }); - address = server.address().address; - await new Promise((resolve, reject) => { server.close((err) => { if (err) { reject(err); return; } - resolve(); }); }); @@ -51,14 +50,14 @@ async function getAddress(host, hostname) { } else { address = hostname; } - - return { address }; + return { + address, + }; } describe("host", () => { const hosts = [ "", - undefined, "0.0.0.0", "::", @@ -69,16 +68,15 @@ describe("host", () => { "local-ipv4", "local-ipv6", ]; - for (const host of hosts) { it(`should work using "${host}" host and port as number`, async () => { const compiler = webpack(config); - const devServerOptions = { port }; - + const devServerOptions = { + port, + }; if (host !== "") { devServerOptions.host = host; } - if ( host === "" || typeof host === "undefined" || @@ -88,11 +86,8 @@ describe("host", () => { ) { devServerOptions.allowedHosts = "all"; } - const server = new Server(devServerOptions, compiler); - let hostname = host; - if (hostname === "" || typeof hostname === "undefined") { // If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise. hostname = ipv6 ? `[${ipv6}]` : ipv4; @@ -109,19 +104,14 @@ describe("host", () => { // For test env where network ipv6 doesn't work hostname = ipv6 ? `[${ipv6}]` : "[::1]"; } - await server.start(); - expect(server.server.address()).toMatchObject( await getAddress(host, hostname), ); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -129,15 +119,12 @@ describe("host", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${hostname}:${port}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); } finally { await browser.close(); @@ -147,12 +134,12 @@ describe("host", () => { it(`should work using "${host}" host and port as string`, async () => { const compiler = webpack(config); - const devServerOptions = { port: `${port}` }; - + const devServerOptions = { + port: `${port}`, + }; if (host !== "") { devServerOptions.host = host; } - if ( host === "" || typeof host === "undefined" || @@ -162,11 +149,8 @@ describe("host", () => { ) { devServerOptions.allowedHosts = "all"; } - const server = new Server(devServerOptions, compiler); - let hostname = host; - if (hostname === "" || typeof hostname === "undefined") { // If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise. hostname = ipv6 ? `[${ipv6}]` : ipv4; @@ -183,19 +167,14 @@ describe("host", () => { // For test env where network ipv6 doesn't work hostname = ipv6 ? `[${ipv6}]` : "[::1]"; } - await server.start(); - expect(server.server.address()).toMatchObject( await getAddress(host, hostname), ); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -203,15 +182,12 @@ describe("host", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${hostname}:${port}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); } finally { await browser.close(); @@ -221,15 +197,13 @@ describe("host", () => { it(`should work using "${host}" host and "auto" port`, async () => { const compiler = webpack(config); - process.env.WEBPACK_DEV_SERVER_BASE_PORT = port; - - const devServerOptions = { port: "auto" }; - + const devServerOptions = { + port: "auto", + }; if (host !== "") { devServerOptions.host = host; } - if ( host === "" || typeof host === "undefined" || @@ -239,11 +213,8 @@ describe("host", () => { ) { devServerOptions.allowedHosts = "all"; } - const server = new Server(devServerOptions, compiler); - let hostname = host; - if (hostname === "" || typeof hostname === "undefined") { // If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise. hostname = ipv6 ? `[${ipv6}]` : ipv4; @@ -260,20 +231,15 @@ describe("host", () => { // For test env where network ipv6 doesn't work hostname = ipv6 ? `[${ipv6}]` : "[::1]"; } - await server.start(); - expect(server.server.address()).toMatchObject( await getAddress(host, hostname), ); - const address = server.server.address(); const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -281,19 +247,15 @@ describe("host", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://${hostname}:${address.port}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); } finally { delete process.env.WEBPACK_DEV_SERVER_BASE_PORT; - await browser.close(); await server.stop(); } diff --git a/test/e2e/hot-and-live-reload.test.js b/test/e2e/hot-and-live-reload.test.js index 9778b2cd5f..d06ccbd8ac 100644 --- a/test/e2e/hot-and-live-reload.test.js +++ b/test/e2e/hot-and-live-reload.test.js @@ -2,25 +2,28 @@ * @jest-environment node */ -"use strict"; - -const path = require("node:path"); -const fs = require("graceful-fs"); -const webpack = require("webpack"); -const WebSocket = require("ws"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const multiCompilerConfig = require("../fixtures/multi-compiler-one-configuration/webpack.config"); -const reloadConfig = require("../fixtures/reload-config/webpack.config"); -const HTMLGeneratorPlugin = require("../helpers/html-generator-plugin"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["hot-and-live-reload"]; - +import { createRequire } from "node:module"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import fs from "graceful-fs"; +import webpack from "webpack"; +import WebSocket from "ws"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import multiCompilerConfig from "../fixtures/multi-compiler-one-configuration/webpack.config.js"; +import reloadConfig from "../fixtures/reload-config/webpack.config.js"; +import HTMLGeneratorPlugin from "../helpers/html-generator-plugin.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const require = createRequire(import.meta.url); +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map["hot-and-live-reload"]; const cssFilePath = path.resolve( __dirname, "../fixtures/reload-config/main.css", ); - const INVALID_MESSAGE = "[webpack-dev-server] App updated. Recompiling..."; describe("hot and live reload", () => { @@ -240,7 +243,6 @@ describe("hot and live reload", () => { }, }, ]; - let browser; let server; @@ -252,11 +254,9 @@ describe("hot and live reload", () => { if (browser) { await browser.close(); } - if (server) { await server.stop(); } - fs.unlinkSync(cssFilePath); }); @@ -268,18 +268,20 @@ describe("hot and live reload", () => { // eslint-disable-next-line no-loop-func it(`${mode.title} (${webSocketServerTitle})`, async () => { - const webpackOptions = { ...reloadConfig, ...mode.webpackOptions }; + const webpackOptions = { + ...reloadConfig, + ...mode.webpackOptions, + }; const compiler = webpack(webpackOptions); const testDevServerOptions = mode.options || {}; - const devServerOptions = { port, ...testDevServerOptions }; - + const devServerOptions = { + port, + ...testDevServerOptions, + }; server = new Server(devServerOptions, compiler); - await server.start(); - const webSocketServerLaunched = testDevServerOptions.webSocketServer !== false; - await new Promise((resolve) => { const ws = new WebSocket(`ws://localhost:${devServerOptions.port}/ws`, { headers: { @@ -287,31 +289,23 @@ describe("hot and live reload", () => { origin: `http://localhost:${devServerOptions.port}`, }, }); - let opened = false; let received = false; let errored = false; - ws.on("error", (_error) => { errored = true; - ws.close(); }); - ws.on("open", () => { opened = true; }); - ws.on("message", (data) => { const message = JSON.parse(data); - if (message.type === "ok") { received = true; - ws.close(); } }); - ws.on("close", () => { if (opened && received && !errored) { resolve(); @@ -320,24 +314,17 @@ describe("hot and live reload", () => { } }); }); - const launched = await runBrowser(); - ({ browser } = launched); - const { page } = launched; - const consoleMessages = []; const pageErrors = []; - let doneHotUpdate = false; let hasDisconnectedMessage = false; - page .on("console", (message) => { if (!hasDisconnectedMessage) { const text = message.text(); - hasDisconnectedMessage = /Disconnected!/.test(text); consoleMessages.push(text); } @@ -350,24 +337,18 @@ describe("hot and live reload", () => { doneHotUpdate = true; } }); - await page.goto(`http://localhost:${port}/${mode.query || ""}`, { waitUntil: "networkidle0", }); - const backgroundColorBefore = await page.evaluate(() => { const { body } = document; - return getComputedStyle(body)["background-color"]; }); - expect(backgroundColorBefore).toBe("rgb(0, 0, 255)"); - fs.writeFileSync( cssFilePath, "body { background-color: rgb(255, 0, 0); }", ); - let waitHot = typeof testDevServerOptions.hot !== "undefined" ? testDevServerOptions.hot @@ -376,12 +357,10 @@ describe("hot and live reload", () => { typeof testDevServerOptions.liveReload !== "undefined" ? testDevServerOptions.liveReload : true; - if (webSocketServerLaunched === false) { waitHot = false; waitLiveReload = false; } - if (Array.isArray(webpackOptions.entry)) { if (webpackOptions.entry.some((item) => item.includes("hot=true"))) { waitHot = true; @@ -391,7 +370,6 @@ describe("hot and live reload", () => { waitHot = false; } } - if (Array.isArray(webpackOptions.entry)) { if ( webpackOptions.entry.some((item) => item.includes("live-reload=true")) @@ -405,24 +383,19 @@ describe("hot and live reload", () => { waitLiveReload = false; } } - const query = mode.query || ""; - if (query.includes("webpack-dev-server-hot=false")) { waitHot = false; } - if (query.includes("webpack-dev-server-live-reload=false")) { waitLiveReload = false; } - if (waitHot) { await page.waitForFunction( () => getComputedStyle(document.body)["background-color"] === "rgb(255, 0, 0)", ); - expect(doneHotUpdate).toBe(true); } else if (waitLiveReload) { await page.waitForNavigation({ @@ -433,25 +406,20 @@ describe("hot and live reload", () => { const interval = setInterval(() => { if (consoleMessages.includes(INVALID_MESSAGE)) { clearInterval(interval); - resolve(); } }, 100); }); } - const backgroundColorAfter = await page.evaluate(() => { const { body } = document; - return getComputedStyle(body)["background-color"]; }); - if (!waitHot && !waitLiveReload) { expect(backgroundColorAfter).toBe("rgb(0, 0, 255)"); } else { expect(backgroundColorAfter).toBe("rgb(255, 0, 0)"); } - expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -471,9 +439,7 @@ describe("simple hot config HMR plugin", () => { beforeEach(async () => { compiler = webpack(config); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -485,23 +451,22 @@ describe("simple hot config HMR plugin", () => { it("should register the HMR plugin before compilation is complete", async () => { let pluginFound = false; - compiler.hooks.compilation.intercept({ register: (tapInfo) => { if (tapInfo.name === "HotModuleReplacementPlugin") { pluginFound = true; } - return tapInfo; }, }); - - server = new Server({ port }, compiler); - + server = new Server( + { + port, + }, + compiler, + ); await server.start(); - expect(pluginFound).toBe(true); - page .on("console", (message) => { consoleMessages.push(message); @@ -509,17 +474,13 @@ describe("simple hot config HMR plugin", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -537,9 +498,7 @@ describe("simple hot config HMR plugin with already added HMR plugin", () => { ...config, plugins: [...config.plugins, new webpack.HotModuleReplacementPlugin()], }); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -551,24 +510,23 @@ describe("simple hot config HMR plugin with already added HMR plugin", () => { it("should register the HMR plugin before compilation is complete", async () => { let pluginFound = false; - compiler.hooks.compilation.intercept({ register: (tapInfo) => { if (tapInfo.name === "HotModuleReplacementPlugin") { pluginFound = true; } - return tapInfo; }, }); - - server = new Server({ port }, compiler); - + server = new Server( + { + port, + }, + compiler, + ); await server.start(); - expect(compiler.options.plugins).toHaveLength(2); expect(pluginFound).toBe(true); - page .on("console", (message) => { consoleMessages.push(message); @@ -576,17 +534,13 @@ describe("simple hot config HMR plugin with already added HMR plugin", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -600,12 +554,12 @@ describe("simple config with already added HMR plugin", () => { beforeEach(() => { compiler = webpack({ ...config, - devServer: { hot: false }, + devServer: { + hot: false, + }, plugins: [...config.plugins, new webpack.HotModuleReplacementPlugin()], }); - loggerWarnSpy = jest.fn(); - getInfrastructureLoggerSpy = jest .spyOn(compiler, "getInfrastructureLogger") .mockImplementation(() => ({ @@ -621,38 +575,46 @@ describe("simple config with already added HMR plugin", () => { }); it("should show warning with hot normalized as true", async () => { - server = new Server({ port }, compiler); - + server = new Server( + { + port, + }, + compiler, + ); await server.start(); - expect(loggerWarnSpy).toHaveBeenCalledWith( '"hot: true" automatically applies HMR plugin, you don\'t have to add it manually to your webpack configuration.', ); - await server.stop(); }); it('should show warning with "hot: true"', async () => { - server = new Server({ port, hot: true }, compiler); - + server = new Server( + { + port, + hot: true, + }, + compiler, + ); await server.start(); - expect(loggerWarnSpy).toHaveBeenCalledWith( '"hot: true" automatically applies HMR plugin, you don\'t have to add it manually to your webpack configuration.', ); - await server.stop(); }); it('should not show warning with "hot: false"', async () => { - server = new Server({ port, hot: false }, compiler); - + server = new Server( + { + port, + hot: false, + }, + compiler, + ); await server.start(); - expect(loggerWarnSpy).not.toHaveBeenCalledWith( '"hot: true" automatically applies HMR plugin, you don\'t have to add it manually to your webpack configuration.', ); - await server.stop(); }); }); @@ -667,9 +629,7 @@ describe("multi compiler hot config HMR plugin", () => { beforeEach(async () => { compiler = webpack(multiCompilerConfig); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -681,23 +641,22 @@ describe("multi compiler hot config HMR plugin", () => { it("should register the HMR plugin before compilation is complete", async () => { let pluginFound = false; - compiler.compilers[0].hooks.compilation.intercept({ register: (tapInfo) => { if (tapInfo.name === "HotModuleReplacementPlugin") { pluginFound = true; } - return tapInfo; }, }); - - server = new Server({ port }, compiler); - + server = new Server( + { + port, + }, + compiler, + ); await server.start(); - expect(pluginFound).toBe(true); - page .on("console", (message) => { consoleMessages.push(message); @@ -705,17 +664,13 @@ describe("multi compiler hot config HMR plugin", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -730,9 +685,7 @@ describe("hot disabled HMR plugin", () => { beforeEach(async () => { compiler = webpack(config); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -744,23 +697,23 @@ describe("hot disabled HMR plugin", () => { it("should NOT register the HMR plugin before compilation is complete", async () => { let pluginFound = false; - compiler.hooks.compilation.intercept({ register: (tapInfo) => { if (tapInfo.name === "HotModuleReplacementPlugin") { pluginFound = true; } - return tapInfo; }, }); - - server = new Server({ port, hot: false }, compiler); - + server = new Server( + { + port, + hot: false, + }, + compiler, + ); await server.start(); - expect(pluginFound).toBe(false); - page .on("console", (message) => { consoleMessages.push(message); @@ -768,17 +721,13 @@ describe("hot disabled HMR plugin", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); diff --git a/test/e2e/ipc.test.js b/test/e2e/ipc.test.js index 519c9e1ea4..ff85b573f8 100644 --- a/test/e2e/ipc.test.js +++ b/test/e2e/ipc.test.js @@ -1,17 +1,16 @@ -"use strict"; - -const http = require("node:http"); -const net = require("node:net"); -const os = require("node:os"); -const path = require("node:path"); -const httpProxy = require("http-proxy"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const sessionSubscribe = require("../helpers/session-subscribe"); -const port1 = require("../ports-map").ipc; - +import http from "node:http"; +import net from "node:net"; +import os from "node:os"; +import path from "node:path"; +import httpProxy from "http-proxy"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import sessionSubscribe from "../helpers/session-subscribe.js"; +import _ports_map from "../ports-map.js"; + +const port1 = _ports_map.ipc; const webSocketServers = ["ws"]; describe("web socket server URL", () => { @@ -22,46 +21,38 @@ describe("web socket server URL", () => { const devServerHost = "localhost"; const proxyHost = devServerHost; const proxyPort = port1; - const compiler = webpack(config); const devServerOptions = { webSocketServer, ipc: true, }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const proxy = httpProxy.createProxyServer({ - target: { socketPath: server.options.ipc }, + target: { + socketPath: server.options.ipc, + }, }); - const proxyServer = http.createServer((request, response) => { // You can define here your custom logic to handle the request // and then proxy the request. proxy.web(request, response); }); - proxyServer.on("upgrade", (request, socket, head) => { proxy.ws(request, socket, head); }); - return proxyServer.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -69,29 +60,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://${devServerHost}:${proxyPort}/ws`, ); @@ -101,7 +84,6 @@ describe("web socket server URL", () => { expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -112,50 +94,41 @@ describe("web socket server URL", () => { const pipePrefix = isWindows ? "\\\\.\\pipe\\" : os.tmpdir(); const pipeName = `webpack-dev-server.${process.pid}-1.sock`; const ipc = path.join(pipePrefix, pipeName); - const devServerHost = "localhost"; const proxyHost = devServerHost; const proxyPort = port1; - const compiler = webpack(config); const devServerOptions = { webSocketServer, ipc, }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const proxy = httpProxy.createProxyServer({ - target: { socketPath: ipc }, + target: { + socketPath: ipc, + }, }); - const proxyServer = http.createServer((request, response) => { // You can define here your custom logic to handle the request // and then proxy the request. proxy.web(request, response); }); - proxyServer.on("upgrade", (request, socket, head) => { proxy.ws(request, socket, head); }); - return proxyServer.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -163,29 +136,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://${devServerHost}:${proxyPort}/ws`, ); @@ -195,7 +160,6 @@ describe("web socket server URL", () => { expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -209,11 +173,9 @@ describe("web socket server URL", () => { const pipePrefix = isWindows ? "\\\\.\\pipe\\" : localRelative; const pipeName = `webpack-dev-server.${process.pid}-2.sock`; const ipc = path.join(pipePrefix, pipeName); - const ipcServer = await new Promise((resolve, reject) => { // eslint-disable-next-line new-cap const server = net.Server(); - server.on("error", (error) => { reject(error); }); @@ -223,11 +185,9 @@ describe("web socket server URL", () => { resolve(); }); }); - const devServerHost = "localhost"; const proxyHost = devServerHost; const proxyPort = port1; - const compiler = webpack(config); const devServerOptions = { webSocketServer, @@ -235,39 +195,32 @@ describe("web socket server URL", () => { ipc, }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const proxy = httpProxy.createProxyServer({ - target: { socketPath: ipc }, + target: { + socketPath: ipc, + }, }); - const proxyServer = http.createServer((request, response) => { // You can define here your custom logic to handle the request // and then proxy the request. proxy.web(request, response); }); - proxyServer.on("upgrade", (request, socket, head) => { proxy.ws(request, socket, head); }); - return proxyServer.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -275,29 +228,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://${devServerHost}:${proxyPort}/ws`, ); @@ -307,15 +252,12 @@ describe("web socket server URL", () => { expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await new Promise((resolve, reject) => { ipcServer.close((error) => { if (error) { reject(error); - return; } - resolve(); }); }); diff --git a/test/e2e/lazy-compilation.test.js b/test/e2e/lazy-compilation.test.js index 8bb5390fa5..330ac3829b 100644 --- a/test/e2e/lazy-compilation.test.js +++ b/test/e2e/lazy-compilation.test.js @@ -1,27 +1,28 @@ -"use strict"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import lazyCompilationMultipleEntriesConfig from "../fixtures/lazy-compilation-multiple-entries/webpack.config.js"; +import lazyCompilationSingleEntryConfig from "../fixtures/lazy-compilation-single-entry/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const lazyCompilationMultipleEntriesConfig = require("../fixtures/lazy-compilation-multiple-entries/webpack.config"); -const lazyCompilationSingleEntryConfig = require("../fixtures/lazy-compilation-single-entry/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["lazy-compilation"]; +const port = _ports_map["lazy-compilation"]; /* eslint-disable jest/no-disabled-tests */ describe("lazy compilation", () => { // TODO jest freeze due webpack do not close `eventsource`, we should uncomment this after fix it on webpack side it.skip("should work with single entry", async () => { const compiler = webpack(lazyCompilationSingleEntryConfig); - const server = new Server({ port }, compiler); - + const server = new Server( + { + port, + }, + compiler, + ); await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message.text()); @@ -29,7 +30,6 @@ describe("lazy compilation", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/test.html`, { waitUntil: "domcontentloaded", }); @@ -37,12 +37,10 @@ describe("lazy compilation", () => { const interval = setInterval(() => { if (consoleMessages.includes("Hey.")) { clearInterval(interval); - resolve(); } }, 100); }); - expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { @@ -53,16 +51,17 @@ describe("lazy compilation", () => { it.skip("should work with multiple entries", async () => { const compiler = webpack(lazyCompilationMultipleEntriesConfig); - const server = new Server({ port }, compiler); - + const server = new Server( + { + port, + }, + compiler, + ); await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message.text()); @@ -70,7 +69,6 @@ describe("lazy compilation", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/test-one.html`, { waitUntil: "domcontentloaded", }); @@ -79,12 +77,10 @@ describe("lazy compilation", () => { console.log(consoleMessages); if (consoleMessages.includes("One.")) { clearInterval(interval); - resolve(); } }, 100); }); - await page.goto(`http://localhost:${port}/test-two.html`, { waitUntil: "domcontentloaded", }); @@ -93,12 +89,10 @@ describe("lazy compilation", () => { console.log(consoleMessages); if (consoleMessages.includes("Two.")) { clearInterval(interval); - resolve(); } }, 100); }); - expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { diff --git a/test/e2e/logging.test.js b/test/e2e/logging.test.js index 9ba530ba3d..80a06ab2b0 100644 --- a/test/e2e/logging.test.js +++ b/test/e2e/logging.test.js @@ -1,17 +1,23 @@ -"use strict"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import fs from "graceful-fs"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import HTMLGeneratorPlugin from "../helpers/html-generator-plugin.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; -const path = require("node:path"); -const fs = require("graceful-fs"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const HTMLGeneratorPlugin = require("../helpers/html-generator-plugin"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map").logging; +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map.logging; describe("logging", () => { - const webSocketServers = [{ webSocketServer: "ws" }]; - + const webSocketServers = [ + { + webSocketServer: "ws", + }, + ]; const cases = [ { title: "should work and log message about live reloading is enabled", @@ -184,45 +190,37 @@ describe("logging", () => { }, }, ]; - for (const webSocketServer of webSocketServers) { for (const testCase of cases) { - it(`${testCase.title} (${ - webSocketServer.webSocketServer || "default" - })`, async () => { - const compiler = webpack({ ...config, ...testCase.webpackOptions }); + it(`${testCase.title} (${webSocketServer.webSocketServer || "default"})`, async () => { + const compiler = webpack({ + ...config, + ...testCase.webpackOptions, + }); const devServerOptions = { port, ...testCase.devServerOptions, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - if (testCase.devServerOptions && testCase.devServerOptions.static) { fs.writeFileSync( path.join(testCase.devServerOptions.static, "./foo.txt"), "Text", ); - await page.waitForNavigation({ waitUntil: "networkidle0", }); } - expect( consoleMessages.map((message) => message diff --git a/test/e2e/mime-types.test.js b/test/e2e/mime-types.test.js index ee71894d70..bc930fa337 100644 --- a/test/e2e/mime-types.test.js +++ b/test/e2e/mime-types.test.js @@ -1,10 +1,10 @@ -"use strict"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/mime-types-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/mime-types-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["mime-types-option"]; +const port = _ports_map["mime-types-option"]; describe("mimeTypes option", () => { describe("as an object with a remapped type", () => { @@ -17,7 +17,6 @@ describe("mimeTypes option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { devMiddleware: { @@ -29,11 +28,8 @@ describe("mimeTypes option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -51,21 +47,16 @@ describe("mimeTypes option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/main.js`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -80,7 +71,6 @@ describe("mimeTypes option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { devMiddleware: { @@ -92,11 +82,8 @@ describe("mimeTypes option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -114,21 +101,16 @@ describe("mimeTypes option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/file.custom`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); diff --git a/test/e2e/module-federation.test.js b/test/e2e/module-federation.test.js index f1fa63144f..0823385e32 100644 --- a/test/e2e/module-federation.test.js +++ b/test/e2e/module-federation.test.js @@ -1,14 +1,14 @@ -"use strict"; - -const requireFromString = require("require-from-string"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const simpleConfig = require("../fixtures/module-federation-config/webpack.config"); -const multiConfig = require("../fixtures/module-federation-config/webpack.multi.config"); -const objectEntryConfig = require("../fixtures/module-federation-config/webpack.object-entry.config"); -const pluginConfig = require("../fixtures/module-federation-config/webpack.plugin"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["module-federation"]; +import requireFromString from "require-from-string"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import simpleConfig from "../fixtures/module-federation-config/webpack.config.js"; +import multiConfig from "../fixtures/module-federation-config/webpack.multi.config.js"; +import objectEntryConfig from "../fixtures/module-federation-config/webpack.object-entry.config.js"; +import pluginConfig from "../fixtures/module-federation-config/webpack.plugin.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const port = _ports_map["module-federation"]; describe("Module federation", () => { describe("should work with simple multi-entry config", () => { @@ -21,12 +21,14 @@ describe("Module federation", () => { beforeEach(async () => { compiler = webpack(simpleConfig); - server = new Server({ port }, compiler); - + server = new Server( + { + port, + }, + compiler, + ); await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -44,27 +46,19 @@ describe("Module federation", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/main.js`, { waitUntil: "networkidle0", }); - const textContent = await response.text(); - expect(textContent).toContain("entry1"); - let exports; - expect(() => { exports = requireFromString(textContent); }).not.toThrow(); - expect(exports).toBe("entry2"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -79,12 +73,14 @@ describe("Module federation", () => { beforeEach(async () => { compiler = webpack(objectEntryConfig); - server = new Server({ port }, compiler); - + server = new Server( + { + port, + }, + compiler, + ); await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -102,27 +98,19 @@ describe("Module federation", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/main.js`, { waitUntil: "networkidle0", }); - const textContent = await response.text(); - expect(textContent).toContain("entry1"); - let exports; - expect(() => { exports = requireFromString(textContent); }).not.toThrow(); - expect(exports).toBe("entry2"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -134,27 +122,19 @@ describe("Module federation", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/foo.js`, { waitUntil: "networkidle0", }); - const textContent = await response.text(); - expect(textContent).not.toContain("entry2"); - let exports; - expect(() => { exports = requireFromString(textContent); }).not.toThrow(); - expect(exports).toBe("entry1"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -169,12 +149,14 @@ describe("Module federation", () => { beforeEach(async () => { compiler = webpack(multiConfig); - server = new Server({ port }, compiler); - + server = new Server( + { + port, + }, + compiler, + ); await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -192,27 +174,19 @@ describe("Module federation", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/main.js`, { waitUntil: "networkidle0", }); - const textContent = await response.text(); - expect(textContent).toContain("entry1"); - let exports; - expect(() => { exports = requireFromString(textContent); }).not.toThrow(); - expect(exports).toBe("entry2"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -227,12 +201,14 @@ describe("Module federation", () => { beforeEach(async () => { compiler = webpack(pluginConfig); - server = new Server({ port }, compiler); - + server = new Server( + { + port, + }, + compiler, + ); await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -250,22 +226,17 @@ describe("Module federation", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}/remoteEntry.js`, { waitUntil: "networkidle0", }, ); - const remoteEntryTextContent = await response.text(); - expect(remoteEntryTextContent).toMatch(/webpack\/hot\/dev-server\.js/); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -277,19 +248,14 @@ describe("Module federation", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/main.js`, { waitUntil: "networkidle0", }); - const mainEntryTextContent = await response.text(); - expect(mainEntryTextContent).toMatch(/webpack\/hot\/dev-server\.js/); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); diff --git a/test/e2e/multi-compiler.test.js b/test/e2e/multi-compiler.test.js index 73879d5323..2bba41f69e 100644 --- a/test/e2e/multi-compiler.test.js +++ b/test/e2e/multi-compiler.test.js @@ -1,14 +1,17 @@ -"use strict"; - -const path = require("node:path"); -const fs = require("graceful-fs"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const oneWebTargetConfiguration = require("../fixtures/multi-compiler-one-configuration/webpack.config"); -const twoWebTargetConfiguration = require("../fixtures/multi-compiler-two-configurations/webpack.config"); -const universalConfiguration = require("../fixtures/universal-compiler-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["multi-compiler"]; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import fs from "graceful-fs"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import oneWebTargetConfiguration from "../fixtures/multi-compiler-one-configuration/webpack.config.js"; +import twoWebTargetConfiguration from "../fixtures/multi-compiler-two-configurations/webpack.config.js"; +import universalConfiguration from "../fixtures/universal-compiler-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map["multi-compiler"]; describe("multi compiler", () => { it("should work with one web target configuration and do nothing", async () => { @@ -17,15 +20,11 @@ describe("multi compiler", () => { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message.text()); @@ -33,11 +32,9 @@ describe("multi compiler", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { @@ -51,17 +48,12 @@ describe("multi compiler", () => { const devServerOptions = { port, }; - const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { let pageErrors = []; let consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message.text()); @@ -69,21 +61,16 @@ describe("multi compiler", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/one-main.html`, { waitUntil: "networkidle0", }); - expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); - pageErrors = []; consoleMessages = []; - await page.goto(`http://localhost:${port}/two-main.html`, { waitUntil: "networkidle0", }); - expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { @@ -109,61 +96,47 @@ describe("multi compiler", () => { "../fixtures/multi-compiler-two-configurations/two.js", ); const originalTwoEntryContent = fs.readFileSync(pathToTwoEntry); - const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { let pageErrors = []; let consoleMessages = []; - page .on("console", (message) => { let text = message.text(); - if (/Error: Aborted because/.test(text)) { const splittedText = text.split("\n"); - text = `${splittedText[0]}\n${splittedText[1]}\n `; } - consoleMessages.push(text); }) .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/one-main.html`, { waitUntil: "networkidle0", }); - fs.writeFileSync(pathToOneEntry, `${originalOneEntryContent}// comment`); - - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); - pageErrors = []; consoleMessages = []; - await page.goto(`http://localhost:${port}/two-main.html`, { waitUntil: "networkidle0", }); - fs.writeFileSync(pathToTwoEntry, `${originalTwoEntryContent}// comment`); - - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { await browser.close(); await server.stop(); - fs.writeFileSync(pathToOneEntry, originalOneEntryContent); fs.writeFileSync(pathToTwoEntry, originalTwoEntryContent); } @@ -186,61 +159,47 @@ describe("multi compiler", () => { "../fixtures/multi-compiler-two-configurations/two.js", ); const originalTwoEntryContent = fs.readFileSync(pathToTwoEntry); - const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { let pageErrors = []; let consoleMessages = []; - page .on("console", (message) => { let text = message.text(); - if (/Error: Aborted because/.test(text)) { const splittedText = text.split("\n"); - text = `${splittedText[0]}\n${splittedText[1]}\n `; } - consoleMessages.push(text); }) .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/one-main.html`, { waitUntil: "networkidle0", }); - fs.writeFileSync(pathToOneEntry, `${originalOneEntryContent}// comment`); - - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); - pageErrors = []; consoleMessages = []; - await page.goto(`http://localhost:${port}/two-main.html`, { waitUntil: "networkidle0", }); - fs.writeFileSync(pathToTwoEntry, `${originalTwoEntryContent}// comment`); - - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { await browser.close(); await server.stop(); - fs.writeFileSync(pathToOneEntry, originalOneEntryContent); fs.writeFileSync(pathToTwoEntry, originalTwoEntryContent); } @@ -263,17 +222,12 @@ describe("multi compiler", () => { "../fixtures/multi-compiler-two-configurations/two.js", ); const originalTwoEntryContent = fs.readFileSync(pathToTwoEntry); - const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { let pageErrors = []; let consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message.text()); @@ -281,35 +235,29 @@ describe("multi compiler", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/one-main.html`, { waitUntil: "networkidle0", }); - fs.writeFileSync(pathToOneEntry, `${originalOneEntryContent}// comment`); - - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); - pageErrors = []; consoleMessages = []; - await page.goto(`http://localhost:${port}/two-main.html`, { waitUntil: "networkidle0", }); - fs.writeFileSync(pathToTwoEntry, `${originalTwoEntryContent}// comment`); - - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { await browser.close(); await server.stop(); - fs.writeFileSync(pathToOneEntry, originalOneEntryContent); fs.writeFileSync(pathToTwoEntry, originalTwoEntryContent); } @@ -332,17 +280,12 @@ describe("multi compiler", () => { "../fixtures/multi-compiler-two-configurations/two.js", ); const originalTwoEntryContent = fs.readFileSync(pathToTwoEntry); - const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { let pageErrors = []; let consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message.text()); @@ -350,35 +293,29 @@ describe("multi compiler", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/one-main.html`, { waitUntil: "networkidle0", }); - fs.writeFileSync(pathToTwoEntry, `${originalTwoEntryContent}// comment`); - - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); - pageErrors = []; consoleMessages = []; - await page.goto(`http://localhost:${port}/two-main.html`, { waitUntil: "networkidle0", }); - fs.writeFileSync(pathToOneEntry, `${originalOneEntryContent}// comment`); - - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { await browser.close(); await server.stop(); - fs.writeFileSync(pathToOneEntry, originalOneEntryContent); fs.writeFileSync(pathToTwoEntry, originalTwoEntryContent); } @@ -390,11 +327,8 @@ describe("multi compiler", () => { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - const pageErrors = []; const consoleMessages = []; try { @@ -404,12 +338,9 @@ describe("multi compiler", () => { waitUntil: "networkidle0", }, ); - const serverResponseText = await serverResponse.text(); - expect(serverResponseText).toContain("Hello from the server"); expect(serverResponseText).not.toContain("WebsocketServer"); - page .on("console", (message) => { consoleMessages.push(message.text()); @@ -417,7 +348,6 @@ describe("multi compiler", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/browser.html`, { waitUntil: "networkidle0", }); @@ -425,7 +355,6 @@ describe("multi compiler", () => { await browser.close(); await server.stop(); } - expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -447,13 +376,9 @@ describe("multi compiler", () => { "../fixtures/universal-compiler-config/server.js", ); const originalServerEntryContent = fs.readFileSync(pathToServerEntry); - const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const serverResponse = await page.goto( `http://localhost:${port}/server.js`, @@ -461,48 +386,38 @@ describe("multi compiler", () => { waitUntil: "networkidle0", }, ); - const serverResponseText = await serverResponse.text(); - expect(serverResponseText).toContain("Hello from the server"); expect(serverResponseText).not.toContain("WebsocketServer"); - const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { let text = message.text(); - if (/Error: Aborted because/.test(text)) { const splittedText = text.split("\n"); - text = `${splittedText[0]}\n${splittedText[1]}\n `; } - consoleMessages.push(text); }) .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/browser.html`, { waitUntil: "networkidle0", }); - fs.writeFileSync( pathToBrowserEntry, `${originalBrowserEntryContent}// comment`, ); - - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { await browser.close(); await server.stop(); - fs.writeFileSync(pathToBrowserEntry, originalBrowserEntryContent); fs.writeFileSync(pathToServerEntry, originalServerEntryContent); } @@ -520,13 +435,9 @@ describe("multi compiler", () => { "../fixtures/universal-compiler-config/browser.js", ); const originalBrowserEntryContent = fs.readFileSync(pathToBrowserEntry); - const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const serverResponse = await page.goto( `http://localhost:${port}/server.js`, @@ -534,48 +445,38 @@ describe("multi compiler", () => { waitUntil: "networkidle0", }, ); - const serverResponseText = await serverResponse.text(); - expect(serverResponseText).toContain("Hello from the server"); expect(serverResponseText).not.toContain("WebsocketServer"); - const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { let text = message.text(); - if (/Error: Aborted because/.test(text)) { const splittedText = text.split("\n"); - text = `${splittedText[0]}\n${splittedText[1]}\n `; } - consoleMessages.push(text); }) .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/browser.html`, { waitUntil: "networkidle0", }); - fs.writeFileSync( pathToBrowserEntry, `${originalBrowserEntryContent}// comment`, ); - - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { await browser.close(); await server.stop(); - fs.writeFileSync(pathToBrowserEntry, originalBrowserEntryContent); } }); @@ -597,13 +498,9 @@ describe("multi compiler", () => { "../fixtures/universal-compiler-config/server.js", ); const originalServerEntryContent = fs.readFileSync(pathToServerEntry); - const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const serverResponse = await page.goto( `http://localhost:${port}/server.js`, @@ -611,15 +508,11 @@ describe("multi compiler", () => { waitUntil: "networkidle0", }, ); - const serverResponseText = await serverResponse.text(); - expect(serverResponseText).toContain("Hello from the server"); expect(serverResponseText).not.toContain("WebsocketServer"); - let pageErrors = []; let consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message.text()); @@ -627,41 +520,35 @@ describe("multi compiler", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/browser.html`, { waitUntil: "networkidle0", }); - fs.writeFileSync( pathToBrowserEntry, `${originalBrowserEntryContent}// comment`, ); - - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); - pageErrors = []; consoleMessages = []; - await page.goto(`http://localhost:${port}/browser.html`, { waitUntil: "networkidle0", }); - fs.writeFileSync( pathToServerEntry, `${originalServerEntryContent}// comment`, ); - - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { await browser.close(); await server.stop(); - fs.writeFileSync(pathToBrowserEntry, originalBrowserEntryContent); fs.writeFileSync(pathToServerEntry, originalServerEntryContent); } @@ -684,13 +571,9 @@ describe("multi compiler", () => { "../fixtures/universal-compiler-config/server.js", ); const originalServerEntryContent = fs.readFileSync(pathToServerEntry); - const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const serverResponse = await page.goto( `http://localhost:${port}/server.js`, @@ -698,15 +581,11 @@ describe("multi compiler", () => { waitUntil: "networkidle0", }, ); - const serverResponseText = await serverResponse.text(); - expect(serverResponseText).toContain("Hello from the server"); expect(serverResponseText).not.toContain("WebsocketServer"); - let pageErrors = []; let consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message.text()); @@ -714,41 +593,35 @@ describe("multi compiler", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/browser.html`, { waitUntil: "networkidle0", }); - fs.writeFileSync( pathToServerEntry, `${originalServerEntryContent}// comment`, ); - - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); - pageErrors = []; consoleMessages = []; - await page.goto(`http://localhost:${port}/browser.html`, { waitUntil: "networkidle0", }); - fs.writeFileSync( pathToBrowserEntry, `${originalBrowserEntryContent}// comment`, ); - - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { await browser.close(); await server.stop(); - fs.writeFileSync(pathToBrowserEntry, originalBrowserEntryContent); fs.writeFileSync(pathToServerEntry, originalServerEntryContent); } diff --git a/test/e2e/on-listening.test.js b/test/e2e/on-listening.test.js index 1e2be08a9d..d7bbb2c0de 100644 --- a/test/e2e/on-listening.test.js +++ b/test/e2e/on-listening.test.js @@ -1,10 +1,10 @@ -"use strict"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["on-listening-option"]; +const port = _ports_map["on-listening-option"]; describe("onListening option", () => { let compiler; @@ -23,9 +23,7 @@ describe("onListening option", () => { if (!devServer) { throw new Error("webpack-dev-server is not defined"); } - onListeningIsRunning = true; - devServer.app.use("/listening/some/path", (req, res, next) => { if (req.method === "GET") { res.setHeader("Content-Type", "text/html; charset=utf-8"); @@ -36,7 +34,6 @@ describe("onListening option", () => { res.end("listening POST"); return; } - return next(); }); }, @@ -44,11 +41,8 @@ describe("onListening option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -66,34 +60,26 @@ describe("onListening option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}/listening/some/path`, { waitUntil: "networkidle0", }, ); - expect(onListeningIsRunning).toBe(true); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); it("should handle POST request to /listening/some/path route", async () => { await page.setRequestInterception(true); - page .on("console", (message) => { consoleMessages.push(message); @@ -103,31 +89,25 @@ describe("onListening option", () => { }) .on("request", (interceptedRequest) => { if (interceptedRequest.isInterceptResolutionHandled()) return; - - interceptedRequest.continue({ method: "POST" }); + interceptedRequest.continue({ + method: "POST", + }); }); - const response = await page.goto( `http://localhost:${port}/listening/some/path`, { waitUntil: "networkidle0", }, ); - expect(onListeningIsRunning).toBe(true); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); diff --git a/test/e2e/options-middleware.test.js b/test/e2e/options-middleware.test.js index 1bc05cd64b..1b71ea3e17 100644 --- a/test/e2e/options-middleware.test.js +++ b/test/e2e/options-middleware.test.js @@ -1,21 +1,18 @@ -"use strict"; - -const Express = require("express"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["options-request-response"]; - +import Express from "express"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const port = _ports_map["options-request-response"]; const createWaiting = () => { let resolve; let reject; - const waiting = new Promise((resolve$, reject$) => { resolve = resolve$; reject = reject$; }); - return { resolve, reject, @@ -30,24 +27,18 @@ describe("handle options-request correctly", () => { const closeApp = await (async () => { const { resolve, waiting } = createWaiting(); const app = new Express(); - app.get("/", (req, res) => { res.sendStatus(200); }); - const server = app.listen(portForApp, () => { resolve(); }); - await waiting; - return async () => { const { resolve: resolve2, waiting: waiting2 } = createWaiting(); - server.close(() => { resolve2(); }); - await waiting2; }; })(); @@ -61,27 +52,21 @@ describe("handle options-request correctly", () => { }, compiler, ); - await server.start(); - const { page, browser } = await runBrowser(); const prefixUrl = "http://localhost"; const htmlUrl = `${prefixUrl}:${portForServer}/test.html`; const appUrl = `${prefixUrl}:${portForApp}`; - try { const responseStatus = []; - page.on("response", (res) => { if (/test\.html$/.test(res.url())) { responseStatus.push(res.status()); } }); - await page.goto(appUrl, { waitUntil: "networkidle0", }); - await page.evaluate( (url) => globalThis.fetch(url, { @@ -91,7 +76,6 @@ describe("handle options-request correctly", () => { }), htmlUrl, ); - expect(responseStatus.sort()).toEqual([200, 204]); } finally { await browser.close(); diff --git a/test/e2e/overlay.test.js b/test/e2e/overlay.test.js index 5ccb678bdd..b8b8a1e468 100644 --- a/test/e2e/overlay.test.js +++ b/test/e2e/overlay.test.js @@ -1,16 +1,18 @@ -"use strict"; - -const path = require("node:path"); -const fs = require("graceful-fs"); -const prettier = require("prettier"); -const waitForExpect = require("wait-for-expect"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const trustedTypesConfig = require("../fixtures/overlay-config/trusted-types.webpack.config"); -const config = require("../fixtures/overlay-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map").overlay; - +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import fs from "graceful-fs"; +import { format as prettierFormat } from "prettier"; +import waitForExpect from "wait-for-expect"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import trustedTypesConfig from "../fixtures/overlay-config/trusted-types.webpack.config.js"; +import config from "../fixtures/overlay-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map.overlay; class ErrorPlugin { constructor(message, skipCounter) { this.message = @@ -28,16 +30,13 @@ class ErrorPlugin { this.counter !== this.skipCounter ) { this.counter += 1; - return; } - compilation.errors.push(new Error(this.message)); }, ); } } - class WarningPlugin { constructor(message, skipCounter) { this.message = message || "Warning from compilation"; @@ -54,16 +53,13 @@ class WarningPlugin { this.counter !== this.skipCounter ) { this.counter += 1; - return; } - compilation.warnings.push(new Error(this.message)); }, ); } } - const delay = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); @@ -72,18 +68,13 @@ const delay = (ms) => describe("overlay", () => { it("should show a warning for initial compilation", async () => { const compiler = webpack(config); - new WarningPlugin().apply(compiler); - const devServerOptions = { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -91,21 +82,19 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -117,18 +106,13 @@ describe("overlay", () => { it("should show an error for initial compilation", async () => { const compiler = webpack(config); - new ErrorPlugin().apply(compiler); - const devServerOptions = { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -136,21 +120,19 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -162,22 +144,17 @@ describe("overlay", () => { it("should show a warning and error for initial compilation", async () => { const compiler = webpack(config); - new WarningPlugin().apply(compiler); new WarningPlugin().apply(compiler); new ErrorPlugin().apply(compiler); new ErrorPlugin().apply(compiler); new ErrorPlugin().apply(compiler); - const devServerOptions = { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -185,21 +162,19 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -211,20 +186,15 @@ describe("overlay", () => { it("should show an ansi formatted error for initial compilation", async () => { const compiler = webpack(config); - new ErrorPlugin( "  18 | Render ansi formatted text", ).apply(compiler); - const devServerOptions = { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -232,21 +202,19 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -258,19 +226,14 @@ describe("overlay", () => { it("should show a warning and error for initial compilation and protects against xss", async () => { const compiler = webpack(config); - new WarningPlugin("strong").apply(compiler); new ErrorPlugin("strong").apply(compiler); - const devServerOptions = { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -278,21 +241,19 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -308,67 +269,52 @@ describe("overlay", () => { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - let pageHtml = await page.evaluate(() => document.body.outerHTML); let overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html initial"); - const pathToFile = path.resolve( __dirname, "../fixtures/overlay-config/foo.js", ); const originalCode = fs.readFileSync(pathToFile); - fs.writeFileSync(pathToFile, "`;"); - await page.waitForSelector("#webpack-dev-server-client-overlay"); - overlayHandle = await page.$("#webpack-dev-server-client-overlay"); pageHtml = await page.evaluate(() => document.body.outerHTML); - const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html with error"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); - fs.writeFileSync(pathToFile, originalCode); - await page.waitForSelector("#webpack-dev-server-client-overlay", { hidden: true, }); - pageHtml = await page.evaluate(() => document.body.outerHTML); overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html after fix error"); @@ -384,91 +330,71 @@ describe("overlay", () => { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - let pageHtml = await page.evaluate(() => document.body.outerHTML); let overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html initial"); - const pathToFile = path.resolve( __dirname, "../fixtures/overlay-config/foo.js", ); const originalCode = fs.readFileSync(pathToFile); - fs.writeFileSync(pathToFile, "`;"); - await page.waitForSelector("#webpack-dev-server-client-overlay"); - overlayHandle = await page.$("#webpack-dev-server-client-overlay"); pageHtml = await page.evaluate(() => document.body.outerHTML); - let overlayFrame = await overlayHandle.contentFrame(); let overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html with error"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); - fs.writeFileSync(pathToFile, "`;a"); - await page.waitForSelector("#webpack-dev-server-client-overlay", { hidden: true, }); await page.waitForSelector("#webpack-dev-server-client-overlay"); - overlayHandle = await page.$("#webpack-dev-server-client-overlay"); pageHtml = await page.evaluate(() => document.body.outerHTML); - overlayFrame = await overlayHandle.contentFrame(); overlayHtml = await overlayFrame.evaluate(() => document.body.outerHTML); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html with other error"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); - fs.writeFileSync(pathToFile, originalCode); - await page.waitForSelector("#webpack-dev-server-client-overlay", { hidden: true, }); - pageHtml = await page.evaluate(() => document.body.outerHTML); overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html after fix error"); @@ -484,77 +410,59 @@ describe("overlay", () => { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - let pageHtml = await page.evaluate(() => document.body.outerHTML); let overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html initial"); - const pathToFile = path.resolve( __dirname, "../fixtures/overlay-config/foo.js", ); const originalCode = fs.readFileSync(pathToFile); - fs.writeFileSync(pathToFile, "`;"); - await page.waitForSelector("#webpack-dev-server-client-overlay"); - overlayHandle = await page.$("#webpack-dev-server-client-overlay"); pageHtml = await page.evaluate(() => document.body.outerHTML); - const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html with error"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); - const frame = await page .frames() .find((item) => item.name() === "webpack-dev-server-client-overlay"); - const buttonHandle = await frame.$("button"); - await buttonHandle.click(); - await page.waitForSelector("#webpack-dev-server-client-overlay", { hidden: true, }); - pageHtml = await page.evaluate(() => document.body.outerHTML); overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html after close"); - fs.writeFileSync(pathToFile, originalCode); } finally { await browser.close(); @@ -565,44 +473,32 @@ describe("overlay", () => { it("should open editor when error with file info is clicked", async () => { const mockLaunchEditorCb = jest.fn(); jest.mock("launch-editor", () => mockLaunchEditorCb); - const compiler = webpack(config); const devServerOptions = { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - const pathToFile = path.resolve( __dirname, "../fixtures/overlay-config/foo.js", ); const originalCode = fs.readFileSync(pathToFile); - fs.writeFileSync(pathToFile, "`;"); - await page.waitForSelector("#webpack-dev-server-client-overlay"); - const frame = page .frames() .find((item) => item.name() === "webpack-dev-server-client-overlay"); - const errorHandle = await frame.$("[data-can-open]"); - await errorHandle.click(); - await waitForExpect(() => { expect(mockLaunchEditorCb).toHaveBeenCalledTimes(1); }); - fs.writeFileSync(pathToFile, originalCode); } finally { await browser.close(); @@ -612,9 +508,7 @@ describe("overlay", () => { it('should not show a warning when "client.overlay" is "false"', async () => { const compiler = webpack(config); - new WarningPlugin().apply(compiler); - const devServerOptions = { port, client: { @@ -622,11 +516,8 @@ describe("overlay", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -634,13 +525,11 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); @@ -652,9 +541,7 @@ describe("overlay", () => { it('should not show a warning when "client.overlay.warnings" is "false"', async () => { const compiler = webpack(config); - new WarningPlugin().apply(compiler); - const devServerOptions = { port, client: { @@ -664,11 +551,8 @@ describe("overlay", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -676,13 +560,11 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); @@ -694,9 +576,7 @@ describe("overlay", () => { it("should not show warning when it is filtered", async () => { const compiler = webpack(config); - new WarningPlugin("My special warning").apply(compiler); - const server = new Server( { port, @@ -712,11 +592,8 @@ describe("overlay", () => { }, compiler, ); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -724,9 +601,7 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); } finally { await browser.close(); @@ -736,9 +611,7 @@ describe("overlay", () => { it("should show warning when it is not filtered", async () => { const compiler = webpack(config); - new WarningPlugin("Unfiltered warning").apply(compiler); - const server = new Server( { port, @@ -750,11 +623,8 @@ describe("overlay", () => { }, compiler, ); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -762,21 +632,19 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -788,9 +656,7 @@ describe("overlay", () => { it('should show a warning when "client.overlay" is "true"', async () => { const compiler = webpack(config); - new WarningPlugin().apply(compiler); - const devServerOptions = { port, client: { @@ -798,11 +664,8 @@ describe("overlay", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -810,21 +673,19 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -836,9 +697,7 @@ describe("overlay", () => { it('should show a warning when "client.overlay.warnings" is "true"', async () => { const compiler = webpack(config); - new WarningPlugin().apply(compiler); - const devServerOptions = { port, client: { @@ -848,11 +707,8 @@ describe("overlay", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -860,21 +716,19 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -886,9 +740,7 @@ describe("overlay", () => { it('should show a warning when "client.overlay.errors" is "true"', async () => { const compiler = webpack(config); - new WarningPlugin().apply(compiler); - const devServerOptions = { port, client: { @@ -898,11 +750,8 @@ describe("overlay", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -910,21 +759,19 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -936,9 +783,7 @@ describe("overlay", () => { it('should not show an error when "client.overlay" is "false"', async () => { const compiler = webpack(config); - new ErrorPlugin().apply(compiler); - const devServerOptions = { port, client: { @@ -946,11 +791,8 @@ describe("overlay", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -958,13 +800,11 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); @@ -976,9 +816,7 @@ describe("overlay", () => { it('should not show an error when "client.overlay.errors" is "false"', async () => { const compiler = webpack(config); - new ErrorPlugin().apply(compiler); - const devServerOptions = { port, client: { @@ -988,11 +826,8 @@ describe("overlay", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -1000,13 +835,11 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); @@ -1018,9 +851,7 @@ describe("overlay", () => { it("should not show error when it is filtered", async () => { const compiler = webpack(config); - new ErrorPlugin("My special error").apply(compiler); - const server = new Server( { port, @@ -1029,7 +860,6 @@ describe("overlay", () => { errors: (error) => { // error is string in webpack 4 const message = typeof error === "string" ? error : error.message; - return message !== "My special error"; }, }, @@ -1037,11 +867,8 @@ describe("overlay", () => { }, compiler, ); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -1049,9 +876,7 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); } finally { await browser.close(); @@ -1061,9 +886,7 @@ describe("overlay", () => { it("should show error when it is not filtered", async () => { const compiler = webpack(config); - new ErrorPlugin("Unfiltered error").apply(compiler); - const server = new Server( { port, @@ -1075,11 +898,8 @@ describe("overlay", () => { }, compiler, ); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -1087,21 +907,19 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -1113,9 +931,7 @@ describe("overlay", () => { it('should show an error when "client.overlay" is "true"', async () => { const compiler = webpack(config); - new ErrorPlugin().apply(compiler); - const devServerOptions = { port, client: { @@ -1123,11 +939,8 @@ describe("overlay", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -1135,21 +948,19 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -1161,9 +972,7 @@ describe("overlay", () => { it("should show overlay when Trusted Types are enabled", async () => { const compiler = webpack(trustedTypesConfig); - new ErrorPlugin().apply(compiler); - const devServerOptions = { port, client: { @@ -1173,44 +982,37 @@ describe("overlay", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message.text()); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( consoleMessages.filter((item) => /requires 'TrustedHTML' assignment/.test(item), ), ).toHaveLength(0); expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -1222,9 +1024,7 @@ describe("overlay", () => { it("should show overlay when Trusted Types are enabled and the \"require-trusted-types-for 'script'\" header was used", async () => { const compiler = webpack(trustedTypesConfig); - new ErrorPlugin().apply(compiler); - const devServerOptions = { port, headers: [ @@ -1240,48 +1040,40 @@ describe("overlay", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message.text()); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.filter((item) => /requires 'TrustedHTML' assignment/.test(item), ), ).toHaveLength(0); expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -1293,9 +1085,7 @@ describe("overlay", () => { it("should not show overlay when Trusted Types are enabled, but policy is not allowed", async () => { const compiler = webpack(trustedTypesConfig); - new ErrorPlugin().apply(compiler); - const devServerOptions = { port, client: { @@ -1305,11 +1095,8 @@ describe("overlay", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -1317,12 +1104,11 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); expect(overlayHandle).toBeNull(); expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); @@ -1334,9 +1120,7 @@ describe("overlay", () => { it('should show an error when "client.overlay.errors" is "true"', async () => { const compiler = webpack(config); - new ErrorPlugin().apply(compiler); - const devServerOptions = { port, client: { @@ -1346,11 +1130,8 @@ describe("overlay", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -1358,21 +1139,19 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -1384,9 +1163,7 @@ describe("overlay", () => { it('should show an error when "client.overlay.warnings" is "true"', async () => { const compiler = webpack(config); - new WarningPlugin().apply(compiler); - const devServerOptions = { port, client: { @@ -1396,11 +1173,8 @@ describe("overlay", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", @@ -1408,21 +1182,19 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -1434,66 +1206,54 @@ describe("overlay", () => { it("should show a warning and hide them after closing connection", async () => { const compiler = webpack(config); - new WarningPlugin().apply(compiler); - - const devServerOptions = { port }; + const devServerOptions = { + port, + }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message.text()); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); - await server.stop(); - await new Promise((resolve) => { const interval = setInterval(() => { if (consoleMessages.includes("[webpack-dev-server] Disconnected!")) { clearInterval(interval); - resolve(); } }, 100); }); - const pageHtmlAfterClose = await page.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtmlAfterClose, { + await prettierFormat(pageHtmlAfterClose, { parser: "html", }), ).toMatchSnapshot("page html"); @@ -1504,29 +1264,22 @@ describe("overlay", () => { it("should show an error after invalidation", async () => { const compiler = webpack(config); - new ErrorPlugin("Error from compilation", 1).apply(compiler); - const devServerOptions = { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - await new Promise((resolve) => { server.middleware.invalidate(() => { resolve(); }); }); - await new Promise((resolve) => { server.middleware.waitUntilValid(() => { resolve(); @@ -1535,23 +1288,20 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - await page.waitForSelector("#webpack-dev-server-client-overlay"); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -1563,29 +1313,22 @@ describe("overlay", () => { it("should show a warning after invalidation", async () => { const compiler = webpack(config); - new WarningPlugin("Warning from compilation", 1).apply(compiler); - const devServerOptions = { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - await new Promise((resolve) => { server.middleware.invalidate(() => { resolve(); }); }); - await new Promise((resolve) => { server.middleware.waitUntilValid(() => { resolve(); @@ -1594,23 +1337,20 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - await page.waitForSelector("#webpack-dev-server-client-overlay"); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -1622,23 +1362,18 @@ describe("overlay", () => { it("should show error for uncaught runtime error", async () => { const compiler = webpack(config); - const server = new Server( { port, }, compiler, ); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - await page.addScriptTag({ content: `(function throwError() { throw new Error('Injected error'); @@ -1647,15 +1382,13 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -1667,7 +1400,6 @@ describe("overlay", () => { it("should not show filtered runtime error", async () => { const compiler = webpack(config); - const server = new Server( { port, @@ -1679,16 +1411,12 @@ describe("overlay", () => { }, compiler, ); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - await page.addScriptTag({ content: `(function throwError() { throw new Error('Injected error'); @@ -1697,9 +1425,7 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); } finally { await browser.close(); @@ -1709,23 +1435,18 @@ describe("overlay", () => { it("should show error for uncaught promise rejection", async () => { const compiler = webpack(config); - const server = new Server( { port, }, compiler, ); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - await page.addScriptTag({ content: `(function throwError() { setTimeout(function () { @@ -1736,15 +1457,13 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(overlayHtml, { + await prettierFormat(overlayHtml, { parser: "html", }), ).toMatchSnapshot("overlay html"); @@ -1756,7 +1475,6 @@ describe("overlay", () => { it("should not show filtered promise rejection", async () => { const compiler = webpack(config); - const server = new Server( { port, @@ -1768,16 +1486,12 @@ describe("overlay", () => { }, compiler, ); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - await page.addScriptTag({ content: `(function throwError() { setTimeout(function () { @@ -1788,9 +1502,7 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); } finally { await browser.close(); @@ -1800,7 +1512,6 @@ describe("overlay", () => { it("should not show filtered promise rejection with specific error cause", async () => { const compiler = webpack(config); - const server = new Server( { port, @@ -1813,16 +1524,12 @@ describe("overlay", () => { }, compiler, ); - await server.start(); - const { page, browser } = await runBrowser(); - try { await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - await page.addScriptTag({ content: `(function throwError() { setTimeout(function () { @@ -1833,9 +1540,7 @@ describe("overlay", () => { // Delay for the overlay to appear await delay(1000); - const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); - expect(overlayHandle).toBeNull(); } finally { await browser.close(); @@ -1844,10 +1549,11 @@ describe("overlay", () => { }); it('should show overlay when "Content-Security-Policy" is "default-src \'self\'" was used', async () => { - const compiler = webpack({ ...config, devtool: false }); - + const compiler = webpack({ + ...config, + devtool: false, + }); new ErrorPlugin().apply(compiler); - const devServerOptions = { port, headers: [ @@ -1858,39 +1564,32 @@ describe("overlay", () => { ], }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message.text()); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); // Delay for the overlay to appear await delay(1000); - const pageHtml = await page.evaluate(() => document.body.outerHTML); const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); const overlayFrame = await overlayHandle.contentFrame(); const overlayHtml = await overlayFrame.evaluate( () => document.body.outerHTML, ); - expect( - await prettier.format(pageHtml, { + await prettierFormat(pageHtml, { parser: "html", }), ).toMatchSnapshot("page html"); expect( - await prettier.format( + await prettierFormat( overlayHtml.replace( /", diff --git a/test/e2e/port.test.js b/test/e2e/port.test.js index b7824a49e9..eb7e4428e0 100644 --- a/test/e2e/port.test.js +++ b/test/e2e/port.test.js @@ -1,15 +1,14 @@ -"use strict"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const { port } = require("../ports-map"); +const { port } = _ports_map; describe("port", () => { const ports = [ "", - undefined, "auto", port, @@ -18,14 +17,11 @@ describe("port", () => { "-1", "99999", ]; - for (const testedPort of ports) { it(`should work using "${testedPort}" port `, async () => { const compiler = webpack(config); const devServerOptions = {}; - let usedPort; - if ( testedPort === "" || typeof testedPort === "undefined" @@ -40,43 +36,32 @@ describe("port", () => { devServerOptions.port = testedPort; usedPort = testedPort; } - const server = new Server(devServerOptions, compiler); - let errored; - try { await server.start(); } catch (error) { errored = error; } - if (testedPort === "-1" || testedPort === "99999") { const errorMessageRegExp = /options.port should be >= 0 and < 65536/; - try { expect(errored.message).toMatch(errorMessageRegExp); } finally { await server.stop(); } - return; } - const address = server.server.address(); - if (testedPort === 0) { expect(typeof address.port).toBe("number"); } else { expect(address.port).toBe(Number(usedPort)); } - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -84,11 +69,9 @@ describe("port", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${address.port}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); @@ -97,7 +80,6 @@ describe("port", () => { await browser.close(); await server.stop(); } - if ( testedPort === "" || typeof testedPort === "undefined" diff --git a/test/e2e/progress.test.js b/test/e2e/progress.test.js index 3f922d98c0..80b4f40f28 100644 --- a/test/e2e/progress.test.js +++ b/test/e2e/progress.test.js @@ -1,13 +1,15 @@ -"use strict"; - -const path = require("node:path"); -const fs = require("graceful-fs"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const reloadConfig = require("../fixtures/reload-config-2/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map").progress; - +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import fs from "graceful-fs"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import reloadConfig from "../fixtures/reload-config-2/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map.progress; const cssFilePath = path.resolve( __dirname, "../fixtures/reload-config-2/main.css", @@ -16,7 +18,6 @@ const cssFilePath = path.resolve( describe("progress", () => { it("should work and log progress in a browser console", async () => { fs.writeFileSync(cssFilePath, "body { background-color: rgb(0, 0, 255); }"); - const compiler = webpack(reloadConfig); const devServerOptions = { port, @@ -25,43 +26,33 @@ describe("progress", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - try { const { page, browser } = await runBrowser(); - const consoleMessages = []; - try { let doHotUpdate = false; - page .on("console", (message) => { consoleMessages.push(message); }) .on("request", (interceptedRequest) => { if (interceptedRequest.isInterceptResolutionHandled()) return; - if (/\.hot-update\.(json|js)$/.test(interceptedRequest.url())) { doHotUpdate = true; } }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - fs.writeFileSync( cssFilePath, "body { background-color: rgb(255, 0, 0); }", ); - await new Promise((resolve) => { const timer = setInterval(() => { if (doHotUpdate) { clearInterval(timer); - resolve(); } }, 100); @@ -69,17 +60,14 @@ describe("progress", () => { } finally { await browser.close(); } - const progressConsoleMessage = consoleMessages.filter((message) => /^\[webpack-dev-server\] (\[[a-zA-Z]+\] )?[0-9]{1,3}% - /.test( message.text(), ), ); - expect(progressConsoleMessage.length).toBeGreaterThan(0); } finally { fs.unlinkSync(cssFilePath); - await server.stop(); } }); diff --git a/test/e2e/range-header.test.js b/test/e2e/range-header.test.js index a1237b583b..3fc7602e4d 100644 --- a/test/e2e/range-header.test.js +++ b/test/e2e/range-header.test.js @@ -1,10 +1,10 @@ -"use strict"; +import request from "supertest"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/static-config/webpack.config.js"; +import _ports_map from "../ports-map.js"; -const request = require("supertest"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/static-config/webpack.config"); -const port = require("../ports-map")["range-header"]; +const port = _ports_map["range-header"]; describe("'Range' header", () => { let compiler; @@ -12,9 +12,12 @@ describe("'Range' header", () => { beforeAll(async () => { compiler = webpack(config); - - server = new Server({ port }, compiler); - + server = new Server( + { + port, + }, + compiler, + ); await server.start(); }); @@ -24,18 +27,15 @@ describe("'Range' header", () => { it('should work with "Range" header using "GET" method', async () => { const response = await request(server.app).get("/main.js"); - expect(response.status).toBe(200); expect(response.headers["content-type"]).toBe( "text/javascript; charset=utf-8", ); expect(response.headers["accept-ranges"]).toBe("bytes"); - const responseContent = response.text; const responseRange = await request(server.app) .get("/main.js") .set("Range", "bytes=0-499"); - expect(responseRange.status).toBe(206); expect(responseRange.headers["content-type"]).toBe( "text/javascript; charset=utf-8", @@ -48,17 +48,14 @@ describe("'Range' header", () => { it('should work with "Range" header using "HEAD" method', async () => { const response = await request(server.app).head("/main.js"); - expect(response.status).toBe(200); expect(response.headers["content-type"]).toBe( "text/javascript; charset=utf-8", ); expect(response.headers["accept-ranges"]).toBe("bytes"); - const responseRange = await request(server.app) .head("/main.js") .set("Range", "bytes=0-499"); - expect(responseRange.status).toBe(206); expect(responseRange.headers["content-type"]).toBe( "text/javascript; charset=utf-8", @@ -69,17 +66,14 @@ describe("'Range' header", () => { it('should work with unsatisfiable "Range" header using "GET" method', async () => { const response = await request(server.app).get("/main.js"); - expect(response.status).toBe(200); expect(response.headers["content-type"]).toBe( "text/javascript; charset=utf-8", ); expect(response.headers["accept-ranges"]).toBe("bytes"); - const responseRange = await request(server.app) .get("/main.js") .set("Range", "bytes=99999999999-"); - expect(responseRange.status).toBe(416); expect(responseRange.headers["content-type"]).toBe( "text/html; charset=utf-8", @@ -89,18 +83,15 @@ describe("'Range' header", () => { it('should work with malformed "Range" header using "GET" method', async () => { const response = await request(server.app).get("/main.js"); - expect(response.status).toBe(200); expect(response.headers["content-type"]).toBe( "text/javascript; charset=utf-8", ); expect(response.headers["accept-ranges"]).toBe("bytes"); - const responseContent = response.text; const responseRange = await request(server.app) .get("/main.js") .set("Range", "bytes"); - expect(responseRange.status).toBe(200); expect(responseRange.headers["content-type"]).toBe( "text/javascript; charset=utf-8", diff --git a/test/e2e/server-and-client-transport.test.js b/test/e2e/server-and-client-transport.test.js index b8dc4ad79d..9eca3035ba 100644 --- a/test/e2e/server-and-client-transport.test.js +++ b/test/e2e/server-and-client-transport.test.js @@ -1,12 +1,14 @@ -"use strict"; - -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const WebsocketServer = require("../../lib/servers/WebsocketServer"); -const defaultConfig = require("../fixtures/provide-plugin-default/webpack.config"); -const wsConfig = require("../fixtures/provide-plugin-ws-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["server-and-client-transport"]; +import { createRequire } from "node:module"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import WebsocketServer from "../../lib/servers/WebsocketServer.js"; +import defaultConfig from "../fixtures/provide-plugin-default/webpack.config.js"; +import wsConfig from "../fixtures/provide-plugin-ws-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const require = createRequire(import.meta.url); +const port = _ports_map["server-and-client-transport"]; describe("server and client transport", () => { it('should use default web socket server ("ws")', async () => { @@ -15,26 +17,19 @@ describe("server and client transport", () => { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - const isCorrectTransport = await page.evaluate( () => globalThis.injectedClient === globalThis.expectedClient, ); - expect(isCorrectTransport).toBe(true); expect( consoleMessages.map((message) => message.text()), @@ -52,26 +47,19 @@ describe("server and client transport", () => { webSocketServer: "ws", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - const isCorrectTransport = await page.evaluate( () => globalThis.injectedClient === globalThis.expectedClient, ); - expect(isCorrectTransport).toBe(true); expect( consoleMessages.map((message) => message.text()), @@ -91,26 +79,19 @@ describe("server and client transport", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - const isCorrectTransport = await page.evaluate( () => globalThis.injectedClient === globalThis.expectedClient, ); - expect(isCorrectTransport).toBe(true); expect( consoleMessages.map((message) => message.text()), @@ -131,26 +112,19 @@ describe("server and client transport", () => { webSocketServer: WebsocketServer, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - const isCorrectTransport = await page.evaluate( () => globalThis.injectedClient === globalThis.expectedClient, ); - expect(isCorrectTransport).toBe(true); expect( consoleMessages.map((message) => message.text()), @@ -173,26 +147,19 @@ describe("server and client transport", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - const isCorrectTransport = await page.evaluate( () => globalThis.injectedClient === globalThis.expectedClient, ); - expect(isCorrectTransport).toBe(true); expect( consoleMessages.map((message) => message.text()), @@ -213,26 +180,19 @@ describe("server and client transport", () => { webSocketServer: require.resolve("../../lib/servers/WebsocketServer"), }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - const isCorrectTransport = await page.evaluate( () => globalThis.injectedClient === globalThis.expectedClient, ); - expect(isCorrectTransport).toBe(true); expect( consoleMessages.map((message) => message.text()), @@ -255,26 +215,19 @@ describe("server and client transport", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - const isCorrectTransport = await page.evaluate( () => globalThis.injectedClient === globalThis.expectedClient, ); - expect(isCorrectTransport).toBe(true); expect( consoleMessages.map((message) => message.text()), @@ -287,7 +240,6 @@ describe("server and client transport", () => { it("should throw an error on wrong path", async () => { expect.assertions(1); - const compiler = webpack(defaultConfig); const devServerOptions = { port, @@ -296,7 +248,6 @@ describe("server and client transport", () => { }, }; const server = new Server(devServerOptions, compiler); - try { await server.start(); } catch (error) { @@ -315,26 +266,19 @@ describe("server and client transport", () => { }, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - const isCorrectTransport = await page.evaluate( () => globalThis.injectedClient === globalThis.expectedClient, ); - expect(isCorrectTransport).toBe(true); expect( consoleMessages.map((message) => message.text()), @@ -355,26 +299,19 @@ describe("server and client transport", () => { webSocketServer: "ws", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - const isCorrectTransport = await page.evaluate( () => globalThis.injectedClient === globalThis.expectedClient, ); - expect(isCorrectTransport).toBe(true); expect( consoleMessages.map((message) => message.text()), @@ -397,7 +334,6 @@ describe("server and client transport", () => { await expect(async () => { await server.start(); }).rejects.toThrowErrorMatchingSnapshot(); - await server.stop(); }); @@ -413,7 +349,6 @@ describe("server and client transport", () => { await expect(async () => { await server.start(); }).rejects.toThrowErrorMatchingSnapshot(); - await server.stop(); }); }); diff --git a/test/e2e/server.test.js b/test/e2e/server.test.js index 3a41e99bdd..da1641491a 100644 --- a/test/e2e/server.test.js +++ b/test/e2e/server.test.js @@ -1,23 +1,24 @@ -"use strict"; - -const https = require("node:https"); -const path = require("node:path"); -const fs = require("graceful-fs"); -const request = require("supertest"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/static-config/webpack.config"); -const { skipTestOnWindows } = require("../helpers/conditional-test"); -const customHTTP = require("../helpers/custom-http"); -const normalizeOptions = require("../helpers/normalize-options"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["server-option"]; - +import https from "node:https"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import fs from "graceful-fs"; +import request from "supertest"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/static-config/webpack.config.js"; +import { skipTestOnWindows } from "../helpers/conditional-test.js"; +import customHTTP from "../helpers/custom-http.js"; +import normalizeOptions from "../helpers/normalize-options.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map["server-option"]; const httpsCertificateDirectory = path.resolve( __dirname, "../fixtures/https-certificate", ); - const staticDirectory = path.resolve( __dirname, "../fixtures/static-config/public", @@ -35,7 +36,6 @@ describe("server option", () => { describe("http", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: { @@ -47,11 +47,8 @@ describe("server option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -69,25 +66,18 @@ describe("server option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - const HTTPVersion = await page.evaluate( () => performance.getEntries()[0].nextHopProtocol, ); - expect(HTTPVersion).not.toBe("h2"); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -95,7 +85,6 @@ describe("server option", () => { describe("custom-http", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: { @@ -107,11 +96,8 @@ describe("server option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -129,25 +115,18 @@ describe("server option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - const HTTPVersion = await page.evaluate( () => performance.getEntries()[0].nextHopProtocol, ); - expect(HTTPVersion).not.toBe("h2"); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -155,7 +134,6 @@ describe("server option", () => { describe("https", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: { @@ -167,11 +145,8 @@ describe("server option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -189,25 +164,18 @@ describe("server option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`https://localhost:${port}/`, { waitUntil: "networkidle0", }); - const HTTPVersion = await page.evaluate( () => performance.getEntries()[0].nextHopProtocol, ); - expect(HTTPVersion).not.toBe("h2"); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -225,9 +193,7 @@ describe("server option", () => { beforeEach(async () => { compiler = webpack(config); - createServerSpy = jest.spyOn(https, "createServer"); - server = new Server( { static: { @@ -256,18 +222,14 @@ describe("server option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); afterEach(async () => { createServerSpy.mockRestore(); - await browser.close(); await server.stop(); }); @@ -280,11 +242,9 @@ describe("server option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`https://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( normalizeOptions(createServerSpy.mock.calls[0][0]), ).toMatchSnapshot("https options"); @@ -308,9 +268,7 @@ describe("server option", () => { beforeEach(async () => { compiler = webpack(config); - createServerSpy = jest.spyOn(https, "createServer"); - server = new Server( { static: { @@ -347,18 +305,14 @@ describe("server option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); afterEach(async () => { createServerSpy.mockRestore(); - await browser.close(); await server.stop(); }); @@ -371,11 +325,9 @@ describe("server option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`https://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( normalizeOptions(createServerSpy.mock.calls[0][0]), ).toMatchSnapshot("https options"); @@ -399,9 +351,7 @@ describe("server option", () => { beforeEach(async () => { compiler = webpack(config); - createServerSpy = jest.spyOn(https, "createServer"); - server = new Server( { static: { @@ -436,18 +386,14 @@ describe("server option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); afterEach(async () => { createServerSpy.mockRestore(); - await browser.close(); await server.stop(); }); @@ -460,11 +406,9 @@ describe("server option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`https://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( normalizeOptions(createServerSpy.mock.calls[0][0]), ).toMatchSnapshot("https options"); @@ -488,9 +432,7 @@ describe("server option", () => { beforeEach(async () => { compiler = webpack(config); - createServerSpy = jest.spyOn(https, "createServer"); - server = new Server( { static: { @@ -534,18 +476,14 @@ describe("server option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); afterEach(async () => { createServerSpy.mockRestore(); - await browser.close(); await server.stop(); }); @@ -558,11 +496,9 @@ describe("server option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`https://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( normalizeOptions(createServerSpy.mock.calls[0][0]), ).toMatchSnapshot("https options"); @@ -586,9 +522,7 @@ describe("server option", () => { beforeEach(async () => { compiler = webpack(config); - createServerSpy = jest.spyOn(https, "createServer"); - server = new Server( { static: { @@ -609,18 +543,14 @@ describe("server option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); afterEach(async () => { createServerSpy.mockRestore(); - await browser.close(); await server.stop(); }); @@ -633,11 +563,9 @@ describe("server option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`https://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( normalizeOptions(createServerSpy.mock.calls[0][0]), ).toMatchSnapshot("https options"); @@ -661,9 +589,7 @@ describe("server option", () => { beforeEach(async () => { compiler = webpack(config); - createServerSpy = jest.spyOn(https, "createServer"); - server = new Server( { static: { @@ -684,18 +610,14 @@ describe("server option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); afterEach(async () => { createServerSpy.mockRestore(); - await browser.close(); await server.stop(); }); @@ -708,11 +630,9 @@ describe("server option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`https://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( normalizeOptions(createServerSpy.mock.calls[0][0]), ).toMatchSnapshot("https options"); @@ -729,7 +649,6 @@ describe("server option", () => { if (skipTestOnWindows("Symlinks are not supported on Windows")) { return; } - let compiler; let server; let createServerSpy; @@ -740,9 +659,7 @@ describe("server option", () => { beforeEach(async () => { compiler = webpack(config); - createServerSpy = jest.spyOn(https, "createServer"); - server = new Server( { static: { @@ -766,18 +683,14 @@ describe("server option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); afterEach(async () => { createServerSpy.mockRestore(); - await browser.close(); await server.stop(); }); @@ -790,11 +703,9 @@ describe("server option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`https://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toBe(200); expect(await response.text()).toContain("Heyo"); expect(consoleMessages.map((message) => message.text())).toEqual([]); @@ -813,9 +724,7 @@ describe("server option", () => { beforeEach(async () => { compiler = webpack(config); - createServerSpy = jest.spyOn(https, "createServer"); - server = new Server( { static: { @@ -852,18 +761,14 @@ describe("server option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); afterEach(async () => { createServerSpy.mockRestore(); - await browser.close(); await server.stop(); }); @@ -876,11 +781,9 @@ describe("server option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`https://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( normalizeOptions(createServerSpy.mock.calls[0][0]), ).toMatchSnapshot("https options"); @@ -904,9 +807,7 @@ describe("server option", () => { beforeEach(async () => { compiler = webpack(config); - createServerSpy = jest.spyOn(https, "createServer"); - server = new Server( { static: { @@ -948,18 +849,14 @@ describe("server option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); afterEach(async () => { createServerSpy.mockRestore(); - await browser.close(); await server.stop(); }); @@ -972,11 +869,9 @@ describe("server option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`https://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( normalizeOptions(createServerSpy.mock.calls[0][0]), ).toMatchSnapshot("https options"); @@ -1000,9 +895,7 @@ describe("server option", () => { beforeEach(async () => { compiler = webpack(config); - createServerSpy = jest.spyOn(https, "createServer"); - server = new Server( { static: { @@ -1032,18 +925,14 @@ describe("server option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); afterEach(async () => { createServerSpy.mockRestore(); - await browser.close(); await server.stop(); }); @@ -1056,11 +945,9 @@ describe("server option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`https://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( normalizeOptions(createServerSpy.mock.calls[0][0]), ).toMatchSnapshot("https options"); @@ -1082,9 +969,7 @@ describe("server option", () => { beforeEach(async () => { compiler = webpack(config); - createServerSpy = jest.spyOn(https, "createServer"); - server = new Server( { static: { @@ -1111,15 +996,12 @@ describe("server option", () => { }, compiler, ); - await server.start(); - req = request(server.app); }); afterEach(async () => { createServerSpy.mockRestore(); - await server.stop(); }); @@ -1131,7 +1013,6 @@ describe("server option", () => { it("should handle GET request to index route (/)", async () => { const response = await req.get("/"); - expect(response.status).toMatchSnapshot("response status"); expect(response.text).toMatchSnapshot("response text"); }); @@ -1148,9 +1029,7 @@ describe("server option", () => { beforeEach(async () => { compiler = webpack(config); - createServerSpy = jest.spyOn(customHTTP, "createServer"); - server = new Server( { static: { @@ -1167,18 +1046,14 @@ describe("server option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); afterEach(async () => { createServerSpy.mockRestore(); - await browser.close(); await server.stop(); }); @@ -1191,15 +1066,12 @@ describe("server option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - const HTTPVersion = await page.evaluate( () => performance.getEntries()[0].nextHopProtocol, ); - expect(HTTPVersion).toBe("http/1.1"); expect( normalizeOptions(createServerSpy.mock.calls[0][0]), diff --git a/test/e2e/setup-exit-signals.test.js b/test/e2e/setup-exit-signals.test.js index 8b8de09674..14f706efb5 100644 --- a/test/e2e/setup-exit-signals.test.js +++ b/test/e2e/setup-exit-signals.test.js @@ -1,10 +1,10 @@ -"use strict"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/simple-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/simple-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["setup-exit-signals-option"]; +const port = _ports_map["setup-exit-signals-option"]; describe("setupExitSignals option", () => { describe("should handle 'SIGINT' and 'SIGTERM' signals", () => { @@ -19,12 +19,10 @@ describe("setupExitSignals option", () => { let stopCallbackSpy; let stdinResumeSpy; let closeCallbackSpy; - const signals = ["SIGINT", "SIGTERM"]; beforeEach(async () => { compiler = webpack(config); - server = new Server( { setupExitSignals: true, @@ -32,25 +30,18 @@ describe("setupExitSignals option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; doExit = false; - exitSpy = jest.spyOn(process, "exit").mockImplementation(() => { doExit = true; }); - stdinResumeSpy = jest .spyOn(process.stdin, "resume") .mockImplementation(() => {}); - stopCallbackSpy = jest.spyOn(server, "stopCallback"); - if (server.compiler.close) { closeCallbackSpy = jest.spyOn(server.compiler, "close"); } @@ -75,31 +66,23 @@ describe("setupExitSignals option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - process.emit(signal); - await new Promise((resolve) => { const interval = setInterval(() => { if (doExit) { expect(stopCallbackSpy.mock.calls).toHaveLength(1); - if (server.compiler.close) { expect(closeCallbackSpy.mock.calls).toHaveLength(1); } - clearInterval(interval); - resolve(); } }, 100); }); - consoleMessages = consoleMessages.filter( (message) => !( @@ -107,11 +90,9 @@ describe("setupExitSignals option", () => { message.text().includes("Disconnected") ), ); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); diff --git a/test/e2e/setup-middlewares.test.js b/test/e2e/setup-middlewares.test.js index e33b2256bd..282598414d 100644 --- a/test/e2e/setup-middlewares.test.js +++ b/test/e2e/setup-middlewares.test.js @@ -1,10 +1,10 @@ -"use strict"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["setup-middlewares-option"]; +const port = _ports_map["setup-middlewares-option"]; describe("setupMiddlewares option", () => { let compiler; @@ -22,7 +22,6 @@ describe("setupMiddlewares option", () => { if (!devServer) { throw new Error("webpack-dev-server is not defined"); } - devServer.app.use("/setup-middleware/some/path", (req, res, next) => { if (req.method === "GET") { res.setHeader("Content-Type", "text/html; charset=utf-8"); @@ -33,10 +32,8 @@ describe("setupMiddlewares option", () => { res.end("setup-middlewares option POST"); return; } - return next(); }); - middlewares.push({ name: "hello-world-test-two", middleware: (req, res, next) => { @@ -44,7 +41,6 @@ describe("setupMiddlewares option", () => { next(); return; } - res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end("Hello World without path!"); }, @@ -61,18 +57,14 @@ describe("setupMiddlewares option", () => { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end("Hello World as function!"); }); - return middlewares; }, port, }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -90,53 +82,44 @@ describe("setupMiddlewares option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}/setup-middleware/some/path`, { waitUntil: "networkidle0", }, ); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); expect(response.status()).toMatchSnapshot("response status"); expect(await response.text()).toMatchSnapshot("response text"); - const response1 = await page.goto(`http://localhost:${port}/foo/bar`, { waitUntil: "networkidle0", }); - expect(response1.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); expect(response1.status()).toMatchSnapshot("response status"); expect(await response1.text()).toMatchSnapshot("response text"); - const response2 = await page.goto(`http://localhost:${port}/foo/bar/baz`, { waitUntil: "networkidle0", }); - expect(response2.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); expect(response2.status()).toMatchSnapshot("response status"); expect(await response2.text()).toMatchSnapshot("response text"); - const response3 = await page.goto( `http://localhost:${port}/setup-middleware/unknown`, { waitUntil: "networkidle0", }, ); - expect(response3.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); expect(response3.status()).toMatchSnapshot("response status"); expect(await response3.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); @@ -145,7 +128,6 @@ describe("setupMiddlewares option", () => { it("should handle POST request to /setup-middleware/some/path route", async () => { await page.setRequestInterception(true); - page .on("console", (message) => { consoleMessages.push(message); @@ -155,17 +137,16 @@ describe("setupMiddlewares option", () => { }) .on("request", (interceptedRequest) => { if (interceptedRequest.isInterceptResolutionHandled()) return; - - interceptedRequest.continue({ method: "POST" }); + interceptedRequest.continue({ + method: "POST", + }); }); - const response = await page.goto( `http://localhost:${port}/setup-middleware/some/path`, { waitUntil: "networkidle0", }, ); - expect(response.headers()["content-type"]).toMatchSnapshot( "response headers content-type", ); diff --git a/test/e2e/static-directory.test.js b/test/e2e/static-directory.test.js index a4f2b02002..73ff6f2370 100644 --- a/test/e2e/static-directory.test.js +++ b/test/e2e/static-directory.test.js @@ -1,14 +1,16 @@ -"use strict"; - -const path = require("node:path"); -const fs = require("graceful-fs"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/static-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const testServer = require("../helpers/test-server"); -const port = require("../ports-map")["static-directory-option"]; - +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import fs from "graceful-fs"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/static-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import testServer from "../helpers/test-server.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map["static-directory-option"]; const staticDirectory = path.resolve(__dirname, "../fixtures/static-config"); const publicDirectory = path.resolve(staticDirectory, "public"); const otherPublicDirectory = path.resolve(staticDirectory, "other"); @@ -16,7 +18,6 @@ const otherPublicDirectory = path.resolve(staticDirectory, "other"); describe("static.directory option", () => { describe("to directory", () => { const nestedFile = path.resolve(publicDirectory, "assets/example.txt"); - let compiler; let server; let page; @@ -26,7 +27,6 @@ describe("static.directory option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: { @@ -37,11 +37,8 @@ describe("static.directory option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -60,19 +57,14 @@ describe("static.directory option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -84,19 +76,14 @@ describe("static.directory option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/other.html`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -116,16 +103,13 @@ describe("static.directory option", () => { it("watches node_modules", (done) => { const filePath = path.join(publicDirectory, "node_modules", "index.html"); - fs.writeFileSync(filePath, "foo", "utf8"); // chokidar emitted a change, // meaning it watched the file correctly server.staticWatchers[0].on("change", (filepath) => { expect(typeof filepath).toBe("string"); - fs.unlinkSync(filePath); - done(); }); @@ -146,7 +130,6 @@ describe("static.directory option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: { @@ -158,11 +141,8 @@ describe("static.directory option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -180,19 +160,14 @@ describe("static.directory option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/assets`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -204,19 +179,14 @@ describe("static.directory option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/bar`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -231,7 +201,6 @@ describe("static.directory option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: { @@ -243,11 +212,8 @@ describe("static.directory option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -265,22 +231,16 @@ describe("static.directory option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/assets/`, { waitUntil: "networkidle0", }); - const text = await response.text(); - expect(response.status()).toMatchSnapshot("response status"); - expect(text).toContain("example.txt"); expect(text).toContain("other.txt"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -292,19 +252,14 @@ describe("static.directory option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/bar/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -319,7 +274,6 @@ describe("static.directory option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: { @@ -330,11 +284,8 @@ describe("static.directory option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -352,22 +303,16 @@ describe("static.directory option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/assets`, { waitUntil: "networkidle0", }); - const text = await response.text(); - expect(response.status()).toMatchSnapshot("response status"); - expect(text).toContain("example.txt"); expect(text).toContain("other.txt"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -379,19 +324,14 @@ describe("static.directory option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/bar`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -406,7 +346,6 @@ describe("static.directory option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: [publicDirectory, otherPublicDirectory], @@ -414,11 +353,8 @@ describe("static.directory option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -436,19 +372,14 @@ describe("static.directory option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -460,19 +391,14 @@ describe("static.directory option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/foo.html`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -488,7 +414,6 @@ describe("static.directory option", () => { it("should throw exception (external url)", (done) => { expect.assertions(1); - server = testServer.start( config, { @@ -498,7 +423,6 @@ describe("static.directory option", () => { expect(error.message).toBe( "Using a URL as static.directory is not supported", ); - server.stopCallback(done); }, ); @@ -567,7 +491,6 @@ describe("static.directory option", () => { expect(error.message).toBe( "Using a URL as static.directory is not supported", ); - server.stopCallback(done); }, ); @@ -587,7 +510,6 @@ describe("static.directory option", () => { .spyOn(process, "cwd") .mockImplementation(() => path.resolve(staticDirectory)); compiler = webpack(config); - server = new Server( { static: undefined, @@ -595,11 +517,8 @@ describe("static.directory option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -617,19 +536,14 @@ describe("static.directory option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/index.html`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -646,9 +560,7 @@ describe("static.directory option", () => { // This is a somewhat weird test, but it is important that we mock // the PWD here, and test if /other.html in our "fake" PWD really is not requested. jest.spyOn(process, "cwd").mockImplementation(() => publicDirectory); - compiler = webpack(config); - server = new Server( { static: false, @@ -656,11 +568,8 @@ describe("static.directory option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -678,19 +587,14 @@ describe("static.directory option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/index.html`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); diff --git a/test/e2e/static-public-path.test.js b/test/e2e/static-public-path.test.js index 8af9cf0e58..11fdbad2d5 100644 --- a/test/e2e/static-public-path.test.js +++ b/test/e2e/static-public-path.test.js @@ -1,12 +1,14 @@ -"use strict"; - -const path = require("node:path"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/static-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["static-public-path-option"]; - +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/static-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map["static-public-path-option"]; const staticDirectory = path.resolve(__dirname, "../fixtures/static-config"); const publicDirectory = path.resolve(staticDirectory, "public"); const otherPublicDirectory = path.resolve(staticDirectory, "other"); @@ -24,7 +26,6 @@ describe("static.publicPath option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: { @@ -36,11 +37,8 @@ describe("static.publicPath option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -58,22 +56,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -85,22 +78,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/other.html`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -115,7 +103,6 @@ describe("static.publicPath option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: { @@ -128,11 +115,8 @@ describe("static.publicPath option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -150,22 +134,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/assets`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -177,22 +156,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/bar`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -207,7 +181,6 @@ describe("static.publicPath option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: { @@ -220,11 +193,8 @@ describe("static.publicPath option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -242,22 +212,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/assets`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toContain("other.txt"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -269,22 +234,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/bar`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -299,7 +259,6 @@ describe("static.publicPath option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: { @@ -312,11 +271,8 @@ describe("static.publicPath option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -334,22 +290,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/assets`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toContain("other.txt"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -361,22 +312,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/bar`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -391,7 +337,6 @@ describe("static.publicPath option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: [ @@ -408,11 +353,8 @@ describe("static.publicPath option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -430,22 +372,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -457,22 +394,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/foo.html`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -490,9 +422,7 @@ describe("static.publicPath option", () => { cwdSpy = jest .spyOn(process, "cwd") .mockImplementation(() => staticDirectory); - compiler = webpack(config); - server = new Server( { static: { @@ -502,18 +432,14 @@ describe("static.publicPath option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); afterEach(async () => { cwdSpy.mockRestore(); - await browser.close(); await server.stop(); }); @@ -526,22 +452,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/index.html`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -556,7 +477,6 @@ describe("static.publicPath option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: { @@ -567,11 +487,8 @@ describe("static.publicPath option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -589,24 +506,19 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/assets/example.txt`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(response.headers()["content-type"]).toMatchSnapshot( "response header content-type", ); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -621,7 +533,6 @@ describe("static.publicPath option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: { @@ -632,11 +543,8 @@ describe("static.publicPath option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -654,20 +562,16 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -681,29 +585,25 @@ describe("static.publicPath option", () => { }) .on("request", (interceptedRequest) => { if (interceptedRequest.isInterceptResolutionHandled()) return; - - interceptedRequest.continue({ method: "HEAD" }); + interceptedRequest.continue({ + method: "HEAD", + }); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); it("should not handle POST request", async () => { await page.setRequestInterception(true); - page .on("console", (message) => { consoleMessages.push(message); @@ -712,28 +612,25 @@ describe("static.publicPath option", () => { pageErrors.push(error); }) .on("request", (interceptedRequest) => { - interceptedRequest.continue({ method: "POST" }); + interceptedRequest.continue({ + method: "POST", + }); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); it("should not handle PUT request", async () => { await page.setRequestInterception(true); - page .on("console", (message) => { consoleMessages.push(message); @@ -742,28 +639,25 @@ describe("static.publicPath option", () => { pageErrors.push(error); }) .on("request", (interceptedRequest) => { - interceptedRequest.continue({ method: "PUT" }); + interceptedRequest.continue({ + method: "PUT", + }); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); it("should not handle DELETE request", async () => { await page.setRequestInterception(true); - page .on("console", (message) => { consoleMessages.push(message); @@ -772,28 +666,25 @@ describe("static.publicPath option", () => { pageErrors.push(error); }) .on("request", (interceptedRequest) => { - interceptedRequest.continue({ method: "DELETE" }); + interceptedRequest.continue({ + method: "DELETE", + }); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); it("should not handle PATCH request", async () => { await page.setRequestInterception(true); - page .on("console", (message) => { consoleMessages.push(message); @@ -802,22 +693,20 @@ describe("static.publicPath option", () => { pageErrors.push(error); }) .on("request", (interceptedRequest) => { - interceptedRequest.continue({ method: "PATCH" }); + interceptedRequest.continue({ + method: "PATCH", + }); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -832,7 +721,6 @@ describe("static.publicPath option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: [ @@ -851,11 +739,8 @@ describe("static.publicPath option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -873,22 +758,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -900,22 +780,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/other.html`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -927,22 +802,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${otherStaticPublicPath}/foo.html`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); @@ -957,7 +827,6 @@ describe("static.publicPath option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { static: [ @@ -976,11 +845,8 @@ describe("static.publicPath option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -998,22 +864,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -1025,22 +886,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/other.html`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -1052,22 +908,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${staticPublicPath}/foo.html`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); @@ -1079,22 +930,17 @@ describe("static.publicPath option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto( `http://localhost:${port}${otherStaticPublicPath}/foo.html`, { waitUntil: "networkidle0", }, ); - expect(response.status()).toMatchSnapshot("response status"); - expect(await response.text()).toMatchSnapshot("response text"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); }); }); diff --git a/test/e2e/stats.test.js b/test/e2e/stats.test.js index 70f3017b12..b5d9a82cfb 100644 --- a/test/e2e/stats.test.js +++ b/test/e2e/stats.test.js @@ -1,12 +1,11 @@ -"use strict"; - -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const HTMLGeneratorPlugin = require("../helpers/html-generator-plugin"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map").stats; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import HTMLGeneratorPlugin from "../helpers/html-generator-plugin.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; +const port = _ports_map.stats; jest.spyOn(globalThis.console, "log").mockImplementation(); describe("stats", () => { @@ -78,11 +77,12 @@ describe("stats", () => { }, new HTMLGeneratorPlugin(), ], - stats: { warningsFilter: /Warning from compilation/ }, + stats: { + warningsFilter: /Warning from compilation/, + }, }, }, ]; - if (webpack.version.startsWith("5")) { cases.push({ title: 'should work and respect the "ignoreWarnings" option', @@ -106,30 +106,26 @@ describe("stats", () => { }, }); } - for (const testCase of cases) { it(testCase.title, async () => { - const compiler = webpack({ ...config, ...testCase.webpackOptions }); + const compiler = webpack({ + ...config, + ...testCase.webpackOptions, + }); const devServerOptions = { port, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const consoleMessages = []; - page.on("console", (message) => { consoleMessages.push(message); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot(); diff --git a/test/e2e/target.test.js b/test/e2e/target.test.js index 32f9a5aaef..dd25cf76c2 100644 --- a/test/e2e/target.test.js +++ b/test/e2e/target.test.js @@ -1,14 +1,16 @@ -"use strict"; - -const path = require("node:path"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const workerConfig = require("../fixtures/worker-config/webpack.config"); -const workerConfigDevServerFalse = require("../fixtures/worker-config-dev-server-false/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map").target; - +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import workerConfig from "../fixtures/worker-config/webpack.config.js"; +import workerConfigDevServerFalse from "../fixtures/worker-config-dev-server-false/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map.target; const sortByTerm = (data, term) => data.sort((a, b) => (a.indexOf(term) < b.indexOf(term) ? -1 : 1)); @@ -28,7 +30,6 @@ describe("target", () => { "es5", ["web", "es5"], ]; - for (const target of targets) { it(`should work using "${target}" target`, async () => { const compiler = webpack({ @@ -36,20 +37,24 @@ describe("target", () => { target, ...(target === false || target === "es5" ? { - output: { chunkFormat: "array-push", path: "/" }, + output: { + chunkFormat: "array-push", + path: "/", + }, } : {}), }); - const server = new Server({ port }, compiler); - + const server = new Server( + { + port, + }, + compiler, + ); await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -57,15 +62,12 @@ describe("target", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); - if ( target === "node" || target === "async-node" || @@ -79,7 +81,6 @@ describe("target", () => { pageErrors.filter((pageError) => /require is not defined|global is not defined/.test(pageError), ).length === 1; - expect(hasRequireOrGlobalError).toBe(true); } else { expect(pageErrors).toMatchSnapshot("page errors"); @@ -93,16 +94,17 @@ describe("target", () => { it("should work using multi compiler mode with `web` and `webworker` targets", async () => { const compiler = webpack(workerConfig); - const server = new Server({ port }, compiler); - + const server = new Server( + { + port, + }, + compiler, + ); await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -110,18 +112,15 @@ describe("target", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( sortByTerm( consoleMessages.map((message) => message.text()), "Worker said:", ), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); } finally { await browser.close(); @@ -143,15 +142,11 @@ describe("target", () => { }, compiler, ); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -159,18 +154,15 @@ describe("target", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect( sortByTerm( consoleMessages.map((message) => message.text()), "Worker said:", ), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); } finally { await browser.close(); diff --git a/test/e2e/watch-files.test.js b/test/e2e/watch-files.test.js index e06126ef92..26011d99ea 100644 --- a/test/e2e/watch-files.test.js +++ b/test/e2e/watch-files.test.js @@ -1,13 +1,15 @@ -"use strict"; - -const path = require("node:path"); -const fs = require("graceful-fs"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/watch-files-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["watch-files-option"]; - +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import fs from "graceful-fs"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/watch-files-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const port = _ports_map["watch-files-option"]; const watchDir = path.resolve( __dirname, "../fixtures/watch-files-config/public", @@ -25,7 +27,6 @@ describe("watchFiles option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { watchFiles: file, @@ -33,11 +34,8 @@ describe("watchFiles option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -56,29 +54,24 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); // change file content fs.writeFileSync(file, "Kurosaki Ichigo", "utf8"); - await new Promise((resolve) => { server.staticWatchers[0].on("change", async (changedPath) => { // page reload - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(changedPath).toBe(file); - resolve(); }); }); @@ -96,7 +89,6 @@ describe("watchFiles option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { watchFiles: watchDir, @@ -104,11 +96,8 @@ describe("watchFiles option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -127,29 +116,24 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); // change file content fs.writeFileSync(file, "Kurosaki Ichigo", "utf8"); - await new Promise((resolve) => { server.staticWatchers[0].on("change", async (changedPath) => { // page reload - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(changedPath).toBe(file); - resolve(); }); }); @@ -167,7 +151,6 @@ describe("watchFiles option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { watchFiles: `${watchDir}/**/*`, @@ -175,11 +158,8 @@ describe("watchFiles option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -198,29 +178,24 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); // change file content fs.writeFileSync(file, "Kurosaki Ichigo", "utf8"); - await new Promise((resolve) => { server.staticWatchers[0].on("change", async (changedPath) => { // page reload - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(changedPath).toBe(file); - resolve(); }); }); @@ -239,7 +214,6 @@ describe("watchFiles option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { watchFiles: [`${watchDir}/**/*.txt`, `${watchDir}/**/*.js`], @@ -247,11 +221,8 @@ describe("watchFiles option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -271,29 +242,24 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); // change file content fs.writeFileSync(file, "Kurosaki Ichigo", "utf8"); - await new Promise((resolve) => { server.staticWatchers[0].on("change", async (changedPath) => { // page reload - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(changedPath).toBe(file); - resolve(); }); }); @@ -311,7 +277,6 @@ describe("watchFiles option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { watchFiles: { @@ -325,11 +290,8 @@ describe("watchFiles option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -348,29 +310,24 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); // change file content fs.writeFileSync(file, "Kurosaki Ichigo", "utf8"); - await new Promise((resolve) => { server.staticWatchers[0].on("change", async (changedPath) => { // page reload - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(changedPath).toBe(file); - resolve(); }); }); @@ -378,7 +335,6 @@ describe("watchFiles option", () => { it("should not reload when a non-matching file is changed", async () => { const ignoredFile = path.join(watchDir, "assets/example.js"); - page .on("console", (message) => { consoleMessages.push(message); @@ -386,11 +342,9 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); // change ignored file content @@ -399,11 +353,9 @@ describe("watchFiles option", () => { // wait a bit to ensure no reload happens await new Promise((resolve) => { let changed = false; - server.staticWatchers[0].on("change", () => { changed = true; }); - setTimeout(() => { expect(changed).toBe(false); resolve(); @@ -427,7 +379,6 @@ describe("watchFiles option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { watchFiles: { @@ -440,11 +391,8 @@ describe("watchFiles option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -463,29 +411,24 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); // change file content fs.writeFileSync(file, "Kurosaki Ichigo", "utf8"); - await new Promise((resolve) => { server.staticWatchers[0].on("change", async (changedPath) => { // page reload - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(changedPath).toBe(file); - resolve(); }); }); @@ -499,11 +442,9 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); // change ignored file content @@ -512,11 +453,9 @@ describe("watchFiles option", () => { // wait a bit to ensure no reload happens await new Promise((resolve) => { let changed = false; - server.staticWatchers[0].on("change", () => { changed = true; }); - setTimeout(() => { expect(changed).toBe(false); resolve(); @@ -540,7 +479,6 @@ describe("watchFiles option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { watchFiles: { @@ -553,11 +491,8 @@ describe("watchFiles option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -576,29 +511,24 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); // change file content fs.writeFileSync(file, "Kurosaki Ichigo", "utf8"); - await new Promise((resolve) => { server.staticWatchers[0].on("change", async (changedPath) => { // page reload - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(changedPath).toBe(file); - resolve(); }); }); @@ -612,11 +542,9 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); // change ignored file content @@ -625,11 +553,9 @@ describe("watchFiles option", () => { // wait a bit to ensure no reload happens await new Promise((resolve) => { let changed = false; - server.staticWatchers[0].on("change", () => { changed = true; }); - setTimeout(() => { expect(changed).toBe(false); resolve(); @@ -656,9 +582,7 @@ describe("watchFiles option", () => { } catch { // ignore } - compiler = webpack(config); - server = new Server( { watchFiles: nonExistFile, @@ -666,11 +590,8 @@ describe("watchFiles option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -688,24 +609,20 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); - await new Promise((resolve) => { server.staticWatchers[0].on("change", async (changedPath) => { // page reload - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(changedPath).toBe(nonExistFile); resolve(); }); @@ -733,19 +650,17 @@ describe("watchFiles option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { - watchFiles: { paths: file }, + watchFiles: { + paths: file, + }, port, }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -764,29 +679,24 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); // change file content fs.writeFileSync(file, "Kurosaki Ichigo", "utf8"); - await new Promise((resolve) => { server.staticWatchers[0].on("change", async (changedPath) => { // page reload - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(changedPath).toBe(file); - resolve(); }); }); @@ -805,19 +715,17 @@ describe("watchFiles option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { - watchFiles: { paths: [file, other] }, + watchFiles: { + paths: [file, other], + }, port, }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -837,35 +745,28 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); // change file content fs.writeFileSync(file, "foo", "utf8"); fs.writeFileSync(other, "bar", "utf8"); - await new Promise((resolve) => { const expected = [file, other]; let changed = 0; - server.staticWatchers[0].on("change", async (changedPath) => { // page reload - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(expected.includes(changedPath)).toBeTruthy(); - changed += 1; - if (changed === 2) { resolve(); } @@ -886,19 +787,20 @@ describe("watchFiles option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { - watchFiles: [{ paths: [file] }, other], + watchFiles: [ + { + paths: [file], + }, + other, + ], port, }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -918,46 +820,38 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(response.status()).toMatchSnapshot("response status"); - expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", ); - expect(pageErrors).toMatchSnapshot("page errors"); // change file content fs.writeFileSync(file, "foo", "utf8"); fs.writeFileSync(other, "bar", "utf8"); - await new Promise((resolve) => { let changed = 0; - server.staticWatchers[0].on("change", async (changedPath) => { // page reload - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(changedPath).toBe(file); - changed += 1; - if (changed === 2) { resolve(); } }); server.staticWatchers[1].on("change", async (changedPath) => { // page reload - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(changedPath).toBe(other); - changed += 1; - if (changed === 2) { resolve(); } @@ -968,7 +862,6 @@ describe("watchFiles option", () => { describe("should work with options", () => { const file = path.join(watchDir, "assets/example.txt"); - const optionCases = [ { interval: undefined, @@ -1033,7 +926,6 @@ describe("watchFiles option", () => { poll: 400, }, ]; - for (const optionCase of optionCases) { describe(JSON.stringify(optionCase), () => { let compiler; @@ -1045,7 +937,6 @@ describe("watchFiles option", () => { beforeEach(async () => { compiler = webpack(config); - server = new Server( { watchFiles: { @@ -1056,11 +947,8 @@ describe("watchFiles option", () => { }, compiler, ); - await server.start(); - ({ page, browser } = await runBrowser()); - pageErrors = []; consoleMessages = []; }); @@ -1079,32 +967,27 @@ describe("watchFiles option", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const response = await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); // should pass correct options to chokidar config expect(server.staticWatchers[0].options).toMatchSnapshot(); - expect(response.status()).toMatchSnapshot("response status"); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); - expect(pageErrors).toMatchSnapshot("page errors"); // change file content fs.writeFileSync(file, "Kurosaki Ichigo", "utf8"); - await new Promise((resolve) => { server.staticWatchers[0].on("change", async (changedPath) => { // page reload - await page.waitForNavigation({ waitUntil: "networkidle0" }); - + await page.waitForNavigation({ + waitUntil: "networkidle0", + }); expect(changedPath).toBe(file); - resolve(); }); }); diff --git a/test/e2e/web-socket-communication.test.js b/test/e2e/web-socket-communication.test.js index d071576eff..7d8b55f8a7 100644 --- a/test/e2e/web-socket-communication.test.js +++ b/test/e2e/web-socket-communication.test.js @@ -1,35 +1,29 @@ -"use strict"; +import webpack from "webpack"; +import WebSocket from "ws"; +import Server from "../../lib/Server.js"; +import WebsocketServer from "../../lib/servers/WebsocketServer.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import _ports_map from "../ports-map.js"; -const webpack = require("webpack"); -const WebSocket = require("ws"); -const Server = require("../../lib/Server"); -const WebsocketServer = require("../../lib/servers/WebsocketServer"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const port = require("../ports-map")["web-socket-communication"]; +const port = _ports_map["web-socket-communication"]; describe("web socket communication", () => { const webSocketServers = ["ws"]; - for (const websocketServer of webSocketServers) { it(`should work and close web socket client connection when web socket server closed ("${websocketServer}")`, async () => { WebsocketServer.heartbeatInterval = 100; - const compiler = webpack(config); const devServerOptions = { port, webSocketServer: websocketServer, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message.text()); @@ -37,11 +31,9 @@ describe("web socket communication", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - await server.stop(); await new Promise((resolve) => { const interval = setInterval(() => { @@ -49,12 +41,10 @@ describe("web socket communication", () => { consoleMessages.includes("[webpack-dev-server] Disconnected!") ) { clearInterval(interval); - resolve(); } }, 100); }); - expect(consoleMessages).toMatchSnapshot("console messages"); expect(pageErrors).toMatchSnapshot("page errors"); } finally { @@ -64,22 +54,17 @@ describe("web socket communication", () => { it(`should work and terminate client that is not alive ("${websocketServer}")`, async () => { WebsocketServer.heartbeatInterval = 100; - const compiler = webpack(config); const devServerOptions = { port, webSocketServer: websocketServer, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -87,7 +72,6 @@ describe("web socket communication", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); @@ -99,7 +83,6 @@ describe("web socket communication", () => { resolve(); }, 200); }); - expect(server.webSocketServer.clients).toHaveLength(0); expect( consoleMessages.map((message) => message.text()), @@ -112,22 +95,17 @@ describe("web socket communication", () => { it(`should work and reconnect when the connection is lost ("${websocketServer}")`, async () => { WebsocketServer.heartbeatInterval = 100; - const compiler = webpack(config); const devServerOptions = { port, webSocketServer: websocketServer, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -135,18 +113,14 @@ describe("web socket communication", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - await server.stop(); await server.start(); - await page.waitForNavigation({ waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); @@ -160,21 +134,16 @@ describe("web socket communication", () => { it('should work and do heartbeat using ("ws" web socket server)', async () => { WebsocketServer.heartbeatInterval = 100; - const compiler = webpack(config); const devServerOptions = { port, webSocketServer: "ws", }; const server = new Server(devServerOptions, compiler); - await server.start(); - server.webSocketServer.heartbeatInterval = 100; - let opened = false; let received = false; - await new Promise((resolve, reject) => { const ws = new WebSocket(`ws://localhost:${devServerOptions.port}/ws`, { headers: { @@ -182,37 +151,29 @@ describe("web socket communication", () => { origin: `http://localhost:${devServerOptions.port}`, }, }); - ws.on("open", () => { opened = true; }); - ws.on("error", (error) => { reject(error); }); - ws.on("ping", () => { if (opened && received) { ws.close(); } }); - ws.on("message", (data) => { const message = JSON.parse(data); - if (message.type === "ok") { received = true; } }); - ws.on("close", () => { resolve(); }); }); - expect(opened).toBe(true); expect(received).toBe(true); - await server.stop(); }); }); diff --git a/test/e2e/web-socket-server-url.test.js b/test/e2e/web-socket-server-url.test.js index b8fdba83cf..823ef2762f 100644 --- a/test/e2e/web-socket-server-url.test.js +++ b/test/e2e/web-socket-server-url.test.js @@ -1,14 +1,13 @@ -"use strict"; - -const express = require("express"); -const { createProxyMiddleware } = require("http-proxy-middleware"); -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const sessionSubscribe = require("../helpers/session-subscribe"); -const [port1, port2] = require("../ports-map")["web-socket-server-url"]; - +import express from "express"; +import { createProxyMiddleware } from "http-proxy-middleware"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import sessionSubscribe from "../helpers/session-subscribe.js"; +import _ports_map from "../ports-map.js"; + +const [port1, port2] = _ports_map["web-socket-server-url"]; const webSocketServers = ["ws"]; describe("web socket server URL", () => { @@ -20,7 +19,6 @@ describe("web socket server URL", () => { const devServerPort = port1; const proxyHost = devServerHost; const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { webSocketServer, @@ -29,9 +27,7 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); app.use( @@ -43,22 +39,17 @@ describe("web socket server URL", () => { logLevel: "warn", }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -66,28 +57,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://${devServerHost}:${devServerPort}/ws`, ); @@ -107,7 +91,6 @@ describe("web socket server URL", () => { const devServerPort = port1; const proxyHost = Server.findIp("v4", false); const proxyPort = port1; - const compiler = webpack(config); const devServerOptions = { webSocketServer, @@ -116,9 +99,7 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); app.use( @@ -130,22 +111,17 @@ describe("web socket server URL", () => { logLevel: "warn", }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -153,29 +129,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://${devServerHost}:${devServerPort}/ws`, ); @@ -195,7 +163,6 @@ describe("web socket server URL", () => { const devServerPort = port1; const proxyHost = Server.findIp("v4", false); const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { client: { @@ -209,9 +176,7 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - function startProxy(callback) { const app = express(); app.use( @@ -223,22 +188,17 @@ describe("web socket server URL", () => { logLevel: "warn", }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -246,28 +206,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://${devServerHost}:${devServerPort}/ws`, ); @@ -277,7 +230,6 @@ describe("web socket server URL", () => { expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); } @@ -285,10 +237,8 @@ describe("web socket server URL", () => { it(`should work behind proxy, when the "host" option is "local-ip" and the "port" option is "auto" ("${webSocketServer}")`, async () => { process.env.WEBPACK_DEV_SERVER_BASE_PORT = 40000; - const proxyHost = Server.findIp("v4", false); const proxyPort = port2; - const compiler = webpack(config); const devServerOptions = { webSocketServer, @@ -297,15 +247,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const resolvedHost = server.options.host; const resolvedPort = server.options.port; - function startProxy(callback) { const app = express(); - app.use( "/", createProxyMiddleware({ @@ -315,22 +261,17 @@ describe("web socket server URL", () => { logLevel: "warn", }), ); - return app.listen(proxyPort, proxyHost, callback); } - const proxy = await new Promise((resolve) => { const proxyCreated = startProxy(() => { resolve(proxyCreated); }); }); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -338,29 +279,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://${proxyHost}:${proxyPort}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://${resolvedHost}:${resolvedPort}/ws`, ); @@ -370,10 +303,8 @@ describe("web socket server URL", () => { expect(pageErrors).toMatchSnapshot("page errors"); } finally { proxy.close(); - await browser.close(); await server.stop(); - delete process.env.WEBPACK_DEV_SERVER_BASE_PORT; } }); @@ -392,15 +323,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -408,29 +335,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://localhost:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://localhost:${port1}/ws`, ); @@ -458,15 +377,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -474,29 +389,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://localhost:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://localhost:${port1}/ws`, ); @@ -524,15 +431,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -540,29 +443,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://localhost:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://localhost:${port1}/ws`, ); @@ -590,15 +485,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -606,29 +497,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}/ws`, ); @@ -656,15 +539,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -672,28 +551,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}/ws`, ); @@ -721,15 +593,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -737,29 +605,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}/ws`, ); @@ -787,15 +647,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -803,29 +659,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}/ws`, ); @@ -859,15 +707,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -875,29 +719,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port2}/ws`, ); @@ -925,15 +761,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -941,28 +773,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}/ws`, ); @@ -990,15 +815,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1006,28 +827,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}/ws`, ); @@ -1050,15 +864,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1066,29 +876,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}/ws`, ); @@ -1116,15 +918,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1132,28 +930,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://zenitsu@127.0.0.1:${port1}/ws`, ); @@ -1182,15 +973,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1198,28 +985,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://foo:chuntaro@127.0.0.1:${port1}/ws`, ); @@ -1248,15 +1028,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1264,29 +1040,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://zenitsu:chuntaro@127.0.0.1:${port1}/ws`, ); @@ -1314,15 +1082,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1330,29 +1094,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}/custom-ws/foo/bar`, ); @@ -1381,15 +1137,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1397,29 +1149,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}`, ); @@ -1452,15 +1196,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1468,29 +1208,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}/custom-ws/foo/bar`, ); @@ -1523,15 +1255,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1539,29 +1267,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}/custom-ws`, ); @@ -1594,15 +1314,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1610,29 +1326,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}/custom-ws/`, ); @@ -1666,15 +1374,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1682,29 +1386,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}`, ); @@ -1728,22 +1424,20 @@ describe("web socket server URL", () => { }, webSocketServer: { type: webSocketServer, - options: { path: "/custom-ws" }, + options: { + path: "/custom-ws", + }, }, port: port1, host: "0.0.0.0", allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1751,29 +1445,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}/custom-ws`, ); @@ -1796,15 +1482,11 @@ describe("web socket server URL", () => { host: hostname, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1812,28 +1494,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); await page.goto(`http://${hostname}:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://${hostname}:${port1}/ws`, ); @@ -1856,15 +1531,11 @@ describe("web socket server URL", () => { host: "local-ip", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1872,29 +1543,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://${hostname}:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://${hostname}:${port1}/ws`, ); @@ -1917,15 +1580,11 @@ describe("web socket server URL", () => { host: "local-ipv4", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1933,28 +1592,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); await page.goto(`http://${hostname}:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://${hostname}:${port1}/ws`, ); @@ -1977,15 +1629,11 @@ describe("web socket server URL", () => { server: "https", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -1993,31 +1641,22 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`https://${hostname}:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain(`wss://${hostname}:${port1}/ws`); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); @@ -2030,7 +1669,6 @@ describe("web socket server URL", () => { it(`should work when "port" option is "auto" ("${webSocketServer}")`, async () => { process.env.WEBPACK_DEV_SERVER_BASE_PORT = 50000; - const compiler = webpack(config); const devServerOptions = { webSocketServer, @@ -2039,17 +1677,12 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const resolvedFreePort = server.options.port; - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -2057,29 +1690,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${resolvedFreePort}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${resolvedFreePort}/ws`, ); @@ -2090,7 +1715,6 @@ describe("web socket server URL", () => { } finally { await browser.close(); await server.stop(); - delete process.env.WEBPACK_DEV_SERVER_BASE_PORT; } }); @@ -2112,15 +1736,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -2128,29 +1748,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}/ws`, ); @@ -2176,15 +1788,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -2192,29 +1800,21 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; - const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://127.0.0.1:${port1}/`, { waitUntil: "networkidle0", }); - const [webSocketRequest] = webSocketRequests; - expect(webSocketRequest.url).toContain( `${websocketURLProtocol}://127.0.0.1:${port1}/ws`, ); @@ -2240,15 +1840,11 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -2256,11 +1852,9 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port1}/`, { waitUntil: "networkidle0", }); - expect( consoleMessages.map((message) => message.text()), ).toMatchSnapshot("console messages"); @@ -2287,21 +1881,15 @@ describe("web socket server URL", () => { allowedHosts: "all", }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - let isDisconnected = false; - page .on("console", (message) => { const text = message.text(); - if (!isDisconnected) { isDisconnected = /Disconnected!/.test(text); consoleMessages.push(text.replaceAll(/:[\d]+/g, ":")); @@ -2310,23 +1898,19 @@ describe("web socket server URL", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - await page.goto(`http://localhost:${port1}/`, { waitUntil: "networkidle0", }); - await new Promise((resolve) => { const interval = setInterval(() => { if ( consoleMessages.includes("[webpack-dev-server] Disconnected!") ) { clearInterval(interval); - resolve(); } }, 100); }); - expect(consoleMessages).toMatchSnapshot("console messages"); expect( pageErrors.map((pageError) => pageError.message.split("\n")[0]), diff --git a/test/e2e/web-socket-server.test.js b/test/e2e/web-socket-server.test.js index ea50d4aa24..616e3b903d 100644 --- a/test/e2e/web-socket-server.test.js +++ b/test/e2e/web-socket-server.test.js @@ -1,31 +1,26 @@ -"use strict"; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/client-config/webpack.config.js"; +import runBrowser from "../helpers/run-browser.js"; +import sessionSubscribe from "../helpers/session-subscribe.js"; +import _ports_map from "../ports-map.js"; -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/client-config/webpack.config"); -const runBrowser = require("../helpers/run-browser"); -const sessionSubscribe = require("../helpers/session-subscribe"); -const port = require("../ports-map")["web-socket-server-test"]; +const port = _ports_map["web-socket-server-test"]; describe("web socket server", () => { it("should work allow to disable", async () => { const devServerPort = port; - const compiler = webpack(config); const devServerOptions = { webSocketServer: false, port: devServerPort, }; const server = new Server(devServerOptions, compiler); - await server.start(); - const { page, browser } = await runBrowser(); - try { const pageErrors = []; const consoleMessages = []; - page .on("console", (message) => { consoleMessages.push(message); @@ -33,26 +28,20 @@ describe("web socket server", () => { .on("pageerror", (error) => { pageErrors.push(error); }); - const webSocketRequests = []; const session = await page.createCDPSession(); - await session.send("Target.setAutoAttach", { autoAttach: true, flatten: true, waitForDebuggerOnStart: true, }); - await sessionSubscribe(session); - session.on("Network.webSocketCreated", (test) => { webSocketRequests.push(test); }); - await page.goto(`http://localhost:${port}/`, { waitUntil: "networkidle0", }); - expect(webSocketRequests).toHaveLength(0); expect(consoleMessages.map((message) => message.text())).toMatchSnapshot( "console messages", diff --git a/test/fixtures/cli-colors-default-stats/foo.js b/test/fixtures/cli-colors-default-stats/foo.js index 5940e9197c..e19c947786 100644 --- a/test/fixtures/cli-colors-default-stats/foo.js +++ b/test/fixtures/cli-colors-default-stats/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("i am foo!"); diff --git a/test/fixtures/cli-colors-default-stats/webpack.config.js b/test/fixtures/cli-colors-default-stats/webpack.config.js index 856a6d18a2..9d74b688a6 100644 --- a/test/fixtures/cli-colors-default-stats/webpack.config.js +++ b/test/fixtures/cli-colors-default-stats/webpack.config.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = { +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, entry: "./foo.js", diff --git a/test/fixtures/cli-colors-disabled/foo.js b/test/fixtures/cli-colors-disabled/foo.js index 5940e9197c..e19c947786 100644 --- a/test/fixtures/cli-colors-disabled/foo.js +++ b/test/fixtures/cli-colors-disabled/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("i am foo!"); diff --git a/test/fixtures/cli-colors-disabled/webpack.config.js b/test/fixtures/cli-colors-disabled/webpack.config.js index e0c751cb9e..1a06e78cd7 100644 --- a/test/fixtures/cli-colors-disabled/webpack.config.js +++ b/test/fixtures/cli-colors-disabled/webpack.config.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = { +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", stats: { colors: false, diff --git a/test/fixtures/cli-colors-enabled/foo.js b/test/fixtures/cli-colors-enabled/foo.js index 5940e9197c..e19c947786 100644 --- a/test/fixtures/cli-colors-enabled/foo.js +++ b/test/fixtures/cli-colors-enabled/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("i am foo!"); diff --git a/test/fixtures/cli-colors-enabled/webpack.config.js b/test/fixtures/cli-colors-enabled/webpack.config.js index 9cdfeb4a69..4374e4258f 100644 --- a/test/fixtures/cli-colors-enabled/webpack.config.js +++ b/test/fixtures/cli-colors-enabled/webpack.config.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = { +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", stats: { colors: true, diff --git a/test/fixtures/cli-empty-entry/webpack.config.js b/test/fixtures/cli-empty-entry/webpack.config.js index 82d77e536f..89708835e6 100644 --- a/test/fixtures/cli-empty-entry/webpack.config.js +++ b/test/fixtures/cli-empty-entry/webpack.config.js @@ -1,7 +1,8 @@ -"use strict"; - -module.exports = { +export default { mode: "development", - stats: { orphanModules: true, preset: "detailed" }, + stats: { + orphanModules: true, + preset: "detailed", + }, entry: {}, }; diff --git a/test/fixtures/cli-entry-as-descriptor/foo.js b/test/fixtures/cli-entry-as-descriptor/foo.js index 5940e9197c..e19c947786 100644 --- a/test/fixtures/cli-entry-as-descriptor/foo.js +++ b/test/fixtures/cli-entry-as-descriptor/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("i am foo!"); diff --git a/test/fixtures/cli-entry-as-descriptor/webpack.config.js b/test/fixtures/cli-entry-as-descriptor/webpack.config.js index d7649d4b3c..f6c15e0b13 100644 --- a/test/fixtures/cli-entry-as-descriptor/webpack.config.js +++ b/test/fixtures/cli-entry-as-descriptor/webpack.config.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = { +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, entry: { diff --git a/test/fixtures/cli-multi-entry/bar.js b/test/fixtures/cli-multi-entry/bar.js index fcd4a4e9a0..4f46053856 100644 --- a/test/fixtures/cli-multi-entry/bar.js +++ b/test/fixtures/cli-multi-entry/bar.js @@ -1,3 +1 @@ -"use strict"; - console.log("I am bar"); diff --git a/test/fixtures/cli-multi-entry/foo.js b/test/fixtures/cli-multi-entry/foo.js index f9e4e59568..bfe689e6fd 100644 --- a/test/fixtures/cli-multi-entry/foo.js +++ b/test/fixtures/cli-multi-entry/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("I am foo"); diff --git a/test/fixtures/cli-multi-entry/webpack.config.js b/test/fixtures/cli-multi-entry/webpack.config.js index c171eb78c8..38375efc6c 100644 --- a/test/fixtures/cli-multi-entry/webpack.config.js +++ b/test/fixtures/cli-multi-entry/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const { resolve } = require("path"); - -module.exports = { +import { resolve } from "path"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", stats: "detailed", context: __dirname, diff --git a/test/fixtures/cli-promise-config/foo.js b/test/fixtures/cli-promise-config/foo.js index 5940e9197c..e19c947786 100644 --- a/test/fixtures/cli-promise-config/foo.js +++ b/test/fixtures/cli-promise-config/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("i am foo!"); diff --git a/test/fixtures/cli-promise-config/webpack.config.js b/test/fixtures/cli-promise-config/webpack.config.js index a75b90a920..7e5dc1c7e0 100644 --- a/test/fixtures/cli-promise-config/webpack.config.js +++ b/test/fixtures/cli-promise-config/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const { join } = require("path"); - -module.exports = () => +import { join } from "path"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default () => new Promise((resolve) => { resolve({ mode: "development", diff --git a/test/fixtures/cli-single-entry/foo.js b/test/fixtures/cli-single-entry/foo.js index f9e4e59568..bfe689e6fd 100644 --- a/test/fixtures/cli-single-entry/foo.js +++ b/test/fixtures/cli-single-entry/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("I am foo"); diff --git a/test/fixtures/cli-single-entry/webpack.config.js b/test/fixtures/cli-single-entry/webpack.config.js index 2106279701..e41643c373 100644 --- a/test/fixtures/cli-single-entry/webpack.config.js +++ b/test/fixtures/cli-single-entry/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const { resolve } = require("path"); - -module.exports = { +import { resolve } from "path"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", stats: "detailed", entry: resolve(__dirname, "./foo.js"), diff --git a/test/fixtures/cli-target-config/foo.js b/test/fixtures/cli-target-config/foo.js index f9e4e59568..bfe689e6fd 100644 --- a/test/fixtures/cli-target-config/foo.js +++ b/test/fixtures/cli-target-config/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("I am foo"); diff --git a/test/fixtures/cli-target-config/webpack.config.js b/test/fixtures/cli-target-config/webpack.config.js index 6b6380e474..f55bb49cb7 100644 --- a/test/fixtures/cli-target-config/webpack.config.js +++ b/test/fixtures/cli-target-config/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const { resolve } = require("path"); - -module.exports = { +import { resolve } from "path"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", stats: "detailed", entry: resolve(__dirname, "./foo.js"), diff --git a/test/fixtures/cli-universal-compiler-config/client.js b/test/fixtures/cli-universal-compiler-config/client.js index 3cc4ed1dcb..d4c687d5d1 100644 --- a/test/fixtures/cli-universal-compiler-config/client.js +++ b/test/fixtures/cli-universal-compiler-config/client.js @@ -1,3 +1 @@ -"use strict"; - console.log("Hello from the client"); diff --git a/test/fixtures/cli-universal-compiler-config/server.js b/test/fixtures/cli-universal-compiler-config/server.js index 3dfb585f6d..f02fa029ad 100644 --- a/test/fixtures/cli-universal-compiler-config/server.js +++ b/test/fixtures/cli-universal-compiler-config/server.js @@ -1,3 +1 @@ -"use strict"; - console.log("Hello from the server"); diff --git a/test/fixtures/cli-universal-compiler-config/webpack.config.js b/test/fixtures/cli-universal-compiler-config/webpack.config.js index 7562d54206..81c45cee90 100644 --- a/test/fixtures/cli-universal-compiler-config/webpack.config.js +++ b/test/fixtures/cli-universal-compiler-config/webpack.config.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = [ +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default [ { name: "client", mode: "development", diff --git a/test/fixtures/cli/foo.js b/test/fixtures/cli/foo.js index 5940e9197c..e19c947786 100644 --- a/test/fixtures/cli/foo.js +++ b/test/fixtures/cli/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("i am foo!"); diff --git a/test/fixtures/cli/webpack.config.js b/test/fixtures/cli/webpack.config.js index 20a13bb93d..1afd6d4e43 100644 --- a/test/fixtures/cli/webpack.config.js +++ b/test/fixtures/cli/webpack.config.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = { +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", stats: "detailed", context: __dirname, diff --git a/test/fixtures/client-config/bar.js b/test/fixtures/client-config/bar.js index 1ae523febc..b8881f03de 100644 --- a/test/fixtures/client-config/bar.js +++ b/test/fixtures/client-config/bar.js @@ -1,3 +1 @@ -"use strict"; - console.log("Bar."); diff --git a/test/fixtures/client-config/foo.js b/test/fixtures/client-config/foo.js index 3c915dbcb8..3dea82f991 100644 --- a/test/fixtures/client-config/foo.js +++ b/test/fixtures/client-config/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("Hey."); diff --git a/test/fixtures/client-config/webpack.config.js b/test/fixtures/client-config/webpack.config.js index 41cfbc5928..d422e3661e 100644 --- a/test/fixtures/client-config/webpack.config.js +++ b/test/fixtures/client-config/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const HTMLGeneratorPlugin = require("../../helpers/html-generator-plugin"); - -module.exports = { +import HTMLGeneratorPlugin from "../../helpers/html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { devtool: false, mode: "development", context: __dirname, diff --git a/test/fixtures/custom-client/CustomClientEntry.js b/test/fixtures/custom-client/CustomClientEntry.js index ee237e53f6..daf1cfff68 100644 --- a/test/fixtures/custom-client/CustomClientEntry.js +++ b/test/fixtures/custom-client/CustomClientEntry.js @@ -1,3 +1 @@ -"use strict"; - console.log("custom client entry"); diff --git a/test/fixtures/custom-client/CustomClientHotEntry.js b/test/fixtures/custom-client/CustomClientHotEntry.js index 6a574ef5c5..4432633b15 100644 --- a/test/fixtures/custom-client/CustomClientHotEntry.js +++ b/test/fixtures/custom-client/CustomClientHotEntry.js @@ -1,3 +1 @@ -"use strict"; - console.log("custom client hot entry"); diff --git a/test/fixtures/custom-client/CustomWebSocketClient.js b/test/fixtures/custom-client/CustomWebSocketClient.js index 58ec6c2136..66ee9cc66a 100644 --- a/test/fixtures/custom-client/CustomWebSocketClient.js +++ b/test/fixtures/custom-client/CustomWebSocketClient.js @@ -1,20 +1,16 @@ -"use strict"; - -module.exports = class WebSocketClient { +export default (class WebSocketClient { constructor(url) { this.client = new WebSocket(url); this.client.onerror = (error) => { console.error(error); }; } - onOpen(f) { this.client.onopen = () => { console.log("open"); f(); }; } - onClose(f) { this.client.onclose = () => { console.log("close"); @@ -30,4 +26,4 @@ module.exports = class WebSocketClient { f(e.data); }; } -}; +}); diff --git a/test/fixtures/dev-public-path/foo.js b/test/fixtures/dev-public-path/foo.js index 5940e9197c..e19c947786 100644 --- a/test/fixtures/dev-public-path/foo.js +++ b/test/fixtures/dev-public-path/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("i am foo!"); diff --git a/test/fixtures/dev-public-path/webpack.config.js b/test/fixtures/dev-public-path/webpack.config.js index 2faa9805d1..ee19cb2304 100644 --- a/test/fixtures/dev-public-path/webpack.config.js +++ b/test/fixtures/dev-public-path/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const { join } = require("path"); - -module.exports = { +import { join } from "path"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", entry: join(__dirname, "foo.js"), devServer: { diff --git a/test/fixtures/dev-server/bar.js b/test/fixtures/dev-server/bar.js index fcd4a4e9a0..4f46053856 100644 --- a/test/fixtures/dev-server/bar.js +++ b/test/fixtures/dev-server/bar.js @@ -1,3 +1 @@ -"use strict"; - console.log("I am bar"); diff --git a/test/fixtures/dev-server/client-custom-path-config.js b/test/fixtures/dev-server/client-custom-path-config.js index 8c9d377854..07aabfac59 100644 --- a/test/fixtures/dev-server/client-custom-path-config.js +++ b/test/fixtures/dev-server/client-custom-path-config.js @@ -1,8 +1,9 @@ -"use strict"; - -const { resolve } = require("path"); - -module.exports = { +import { resolve } from "path"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", stats: "detailed", entry: resolve(__dirname, "./foo.js"), diff --git a/test/fixtures/dev-server/client-default-path-config.js b/test/fixtures/dev-server/client-default-path-config.js index f208a49af4..6d004d3af5 100644 --- a/test/fixtures/dev-server/client-default-path-config.js +++ b/test/fixtures/dev-server/client-default-path-config.js @@ -1,8 +1,9 @@ -"use strict"; - -const { resolve } = require("path"); - -module.exports = { +import { resolve } from "path"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", stats: "detailed", entry: resolve(__dirname, "./foo.js"), diff --git a/test/fixtures/dev-server/foo.js b/test/fixtures/dev-server/foo.js index f9e4e59568..bfe689e6fd 100644 --- a/test/fixtures/dev-server/foo.js +++ b/test/fixtures/dev-server/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("I am foo"); diff --git a/test/fixtures/entry-as-function/foo.js b/test/fixtures/entry-as-function/foo.js index 5940e9197c..e19c947786 100644 --- a/test/fixtures/entry-as-function/foo.js +++ b/test/fixtures/entry-as-function/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("i am foo!"); diff --git a/test/fixtures/entry-as-function/webpack.config.js b/test/fixtures/entry-as-function/webpack.config.js index cf48f0b924..760698d88a 100644 --- a/test/fixtures/entry-as-function/webpack.config.js +++ b/test/fixtures/entry-as-function/webpack.config.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = { +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, entry: () => "./foo.js", diff --git a/test/fixtures/historyapifallback-2-config/foo.js b/test/fixtures/historyapifallback-2-config/foo.js index 3c915dbcb8..3dea82f991 100644 --- a/test/fixtures/historyapifallback-2-config/foo.js +++ b/test/fixtures/historyapifallback-2-config/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("Hey."); diff --git a/test/fixtures/historyapifallback-2-config/webpack.config.js b/test/fixtures/historyapifallback-2-config/webpack.config.js index f03898aa61..65ce243635 100644 --- a/test/fixtures/historyapifallback-2-config/webpack.config.js +++ b/test/fixtures/historyapifallback-2-config/webpack.config.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = { +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, stats: "none", diff --git a/test/fixtures/historyapifallback-3-config/foo.js b/test/fixtures/historyapifallback-3-config/foo.js index aae7eee3a7..ff0128eab4 100644 --- a/test/fixtures/historyapifallback-3-config/foo.js +++ b/test/fixtures/historyapifallback-3-config/foo.js @@ -1,5 +1,3 @@ -"use strict"; - -require("./bar.html"); +import "./bar.html"; console.log("Hey."); diff --git a/test/fixtures/historyapifallback-3-config/webpack.config.js b/test/fixtures/historyapifallback-3-config/webpack.config.js index 792be36f9c..8560d8adaa 100644 --- a/test/fixtures/historyapifallback-3-config/webpack.config.js +++ b/test/fixtures/historyapifallback-3-config/webpack.config.js @@ -1,5 +1,7 @@ -"use strict"; - +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); const moduleRuleForHTML = { test: /\.html$/, type: "asset/resource", @@ -7,8 +9,7 @@ const moduleRuleForHTML = { filename: "index.html", }, }; - -module.exports = { +export default { mode: "development", context: __dirname, stats: "none", diff --git a/test/fixtures/historyapifallback-config/foo.js b/test/fixtures/historyapifallback-config/foo.js index fa06808d30..49d08468b9 100644 --- a/test/fixtures/historyapifallback-config/foo.js +++ b/test/fixtures/historyapifallback-config/foo.js @@ -1,6 +1,4 @@ -"use strict"; - -require("./index.html"); -require("./bar.html"); +import "./index.html"; +import "./bar.html"; console.log("Hey."); diff --git a/test/fixtures/historyapifallback-config/webpack.config.js b/test/fixtures/historyapifallback-config/webpack.config.js index bf2a52ba91..7d39db39fe 100644 --- a/test/fixtures/historyapifallback-config/webpack.config.js +++ b/test/fixtures/historyapifallback-config/webpack.config.js @@ -1,5 +1,7 @@ -"use strict"; - +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); const moduleRuleForHTML = { test: /\.html$/, type: "asset/resource", @@ -7,8 +9,7 @@ const moduleRuleForHTML = { filename: "[name][ext]", }, }; - -module.exports = { +export default { mode: "development", context: __dirname, stats: "none", diff --git a/test/fixtures/lazy-compilation-multiple-entries/one.js b/test/fixtures/lazy-compilation-multiple-entries/one.js index 3141da7ce0..7e899f5fed 100644 --- a/test/fixtures/lazy-compilation-multiple-entries/one.js +++ b/test/fixtures/lazy-compilation-multiple-entries/one.js @@ -1,3 +1 @@ -"use strict"; - console.log("One."); diff --git a/test/fixtures/lazy-compilation-multiple-entries/two.js b/test/fixtures/lazy-compilation-multiple-entries/two.js index 0f719c9099..90bf6742b5 100644 --- a/test/fixtures/lazy-compilation-multiple-entries/two.js +++ b/test/fixtures/lazy-compilation-multiple-entries/two.js @@ -1,3 +1 @@ -"use strict"; - console.log("Two."); diff --git a/test/fixtures/lazy-compilation-multiple-entries/webpack.config.js b/test/fixtures/lazy-compilation-multiple-entries/webpack.config.js index 74f65f722b..7962482bf8 100644 --- a/test/fixtures/lazy-compilation-multiple-entries/webpack.config.js +++ b/test/fixtures/lazy-compilation-multiple-entries/webpack.config.js @@ -1,5 +1,7 @@ -"use strict"; - +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); const oneHTMLContent = ` @@ -22,8 +24,7 @@ const twoHTMLContent = ` `; - -module.exports = { +export default { devtool: false, mode: "development", context: __dirname, @@ -50,10 +51,8 @@ module.exports = { const pluginName = "html-generator-plugin-test"; const oneFilename = "test-one.html"; const twoFilename = "test-two.html"; - compiler.hooks.thisCompilation.tap(pluginName, (compilation) => { const { RawSource } = compiler.webpack.sources; - compilation.hooks.processAssets.tap( { name: pluginName, @@ -62,11 +61,8 @@ module.exports = { }, () => { const oneSource = new RawSource(oneHTMLContent); - compilation.emitAsset(oneFilename, oneSource); - const twoSource = new RawSource(twoHTMLContent); - compilation.emitAsset(twoFilename, twoSource); }, ); diff --git a/test/fixtures/lazy-compilation-single-entry/entry.js b/test/fixtures/lazy-compilation-single-entry/entry.js index 3c915dbcb8..3dea82f991 100644 --- a/test/fixtures/lazy-compilation-single-entry/entry.js +++ b/test/fixtures/lazy-compilation-single-entry/entry.js @@ -1,3 +1 @@ -"use strict"; - console.log("Hey."); diff --git a/test/fixtures/lazy-compilation-single-entry/webpack.config.js b/test/fixtures/lazy-compilation-single-entry/webpack.config.js index c3223f029a..9ca5193db9 100644 --- a/test/fixtures/lazy-compilation-single-entry/webpack.config.js +++ b/test/fixtures/lazy-compilation-single-entry/webpack.config.js @@ -1,5 +1,7 @@ -"use strict"; - +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); const HTMLContent = ` @@ -11,8 +13,7 @@ const HTMLContent = ` `; - -module.exports = { +export default { devtool: false, mode: "development", context: __dirname, @@ -35,10 +36,8 @@ module.exports = { apply(compiler) { const pluginName = "html-generator-plugin-test"; const filename = "test.html"; - compiler.hooks.thisCompilation.tap(pluginName, (compilation) => { const { RawSource } = compiler.webpack.sources; - compilation.hooks.processAssets.tap( { name: pluginName, @@ -47,7 +46,6 @@ module.exports = { }, () => { const source = new RawSource(HTMLContent); - compilation.emitAsset(filename, source); }, ); diff --git a/test/fixtures/mime-types-config/foo.js b/test/fixtures/mime-types-config/foo.js index 739d9bd638..af7b2d3f91 100644 --- a/test/fixtures/mime-types-config/foo.js +++ b/test/fixtures/mime-types-config/foo.js @@ -1,5 +1,3 @@ -"use strict"; - -require("./file.custom"); +import "./file.custom"; console.log("Hey."); diff --git a/test/fixtures/mime-types-config/webpack.config.js b/test/fixtures/mime-types-config/webpack.config.js index 5e59b2d444..8414de6512 100644 --- a/test/fixtures/mime-types-config/webpack.config.js +++ b/test/fixtures/mime-types-config/webpack.config.js @@ -1,5 +1,7 @@ -"use strict"; - +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); const moduleRuleForCustom = { test: /\.custom$/, type: "asset/resource", @@ -7,8 +9,7 @@ const moduleRuleForCustom = { filename: "[name][ext]", }, }; - -module.exports = { +export default { mode: "development", context: __dirname, stats: "none", diff --git a/test/fixtures/module-federation-config/entry1.js b/test/fixtures/module-federation-config/entry1.js index dbd0f49a83..ae45df7780 100644 --- a/test/fixtures/module-federation-config/entry1.js +++ b/test/fixtures/module-federation-config/entry1.js @@ -1,3 +1 @@ -"use strict"; - -module.exports = "entry1"; +export default "entry1"; diff --git a/test/fixtures/module-federation-config/entry2.js b/test/fixtures/module-federation-config/entry2.js index 74f9bc577f..bbfcd5c63c 100644 --- a/test/fixtures/module-federation-config/entry2.js +++ b/test/fixtures/module-federation-config/entry2.js @@ -1,3 +1 @@ -"use strict"; - -module.exports = "entry2"; +export default "entry2"; diff --git a/test/fixtures/module-federation-config/webpack.config.js b/test/fixtures/module-federation-config/webpack.config.js index 269e4cab41..d81146ef57 100644 --- a/test/fixtures/module-federation-config/webpack.config.js +++ b/test/fixtures/module-federation-config/webpack.config.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = { +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", target: "node", stats: "none", diff --git a/test/fixtures/module-federation-config/webpack.multi.config.js b/test/fixtures/module-federation-config/webpack.multi.config.js index 5863c8e14a..b257765f5b 100644 --- a/test/fixtures/module-federation-config/webpack.multi.config.js +++ b/test/fixtures/module-federation-config/webpack.multi.config.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = [ +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default [ { mode: "development", target: "node", diff --git a/test/fixtures/module-federation-config/webpack.object-entry.config.js b/test/fixtures/module-federation-config/webpack.object-entry.config.js index 43c47a4183..0ed91016c5 100644 --- a/test/fixtures/module-federation-config/webpack.object-entry.config.js +++ b/test/fixtures/module-federation-config/webpack.object-entry.config.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = { +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", target: "node", stats: "none", diff --git a/test/fixtures/module-federation-config/webpack.plugin.js b/test/fixtures/module-federation-config/webpack.plugin.js index 9178e3c600..5ef0e72f15 100644 --- a/test/fixtures/module-federation-config/webpack.plugin.js +++ b/test/fixtures/module-federation-config/webpack.plugin.js @@ -1,9 +1,10 @@ -"use strict"; - -const ModuleFederationPlugin = - require("webpack").container.ModuleFederationPlugin; - -module.exports = { +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +import webpack from "webpack"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +const { ModuleFederationPlugin } = webpack.container; +export default { mode: "development", target: "node", stats: "none", @@ -12,7 +13,10 @@ module.exports = { plugins: [ new ModuleFederationPlugin({ name: "app1", - library: { type: "var", name: "app1" }, + library: { + type: "var", + name: "app1", + }, filename: "remoteEntry.js", exposes: { "./entry1": "./entry1", diff --git a/test/fixtures/multi-compiler-one-configuration/foo.js b/test/fixtures/multi-compiler-one-configuration/foo.js index 3c915dbcb8..3dea82f991 100644 --- a/test/fixtures/multi-compiler-one-configuration/foo.js +++ b/test/fixtures/multi-compiler-one-configuration/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("Hey."); diff --git a/test/fixtures/multi-compiler-one-configuration/webpack.config.js b/test/fixtures/multi-compiler-one-configuration/webpack.config.js index d00d2b4c86..e93ddfd80d 100644 --- a/test/fixtures/multi-compiler-one-configuration/webpack.config.js +++ b/test/fixtures/multi-compiler-one-configuration/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const HTMLGeneratorPlugin = require("../../helpers/html-generator-plugin"); - -module.exports = [ +import HTMLGeneratorPlugin from "../../helpers/html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default [ { target: "web", mode: "development", diff --git a/test/fixtures/multi-compiler-two-configurations/one.js b/test/fixtures/multi-compiler-two-configurations/one.js index e767ff32f1..0dab8b6bcb 100644 --- a/test/fixtures/multi-compiler-two-configurations/one.js +++ b/test/fixtures/multi-compiler-two-configurations/one.js @@ -1,3 +1 @@ -"use strict"; - console.log("one"); diff --git a/test/fixtures/multi-compiler-two-configurations/two.js b/test/fixtures/multi-compiler-two-configurations/two.js index 83bf26e4bb..ef0e38f5b5 100644 --- a/test/fixtures/multi-compiler-two-configurations/two.js +++ b/test/fixtures/multi-compiler-two-configurations/two.js @@ -1,3 +1 @@ -"use strict"; - console.log("two"); diff --git a/test/fixtures/multi-compiler-two-configurations/webpack.config.js b/test/fixtures/multi-compiler-two-configurations/webpack.config.js index eaeba3006d..6253254344 100644 --- a/test/fixtures/multi-compiler-two-configurations/webpack.config.js +++ b/test/fixtures/multi-compiler-two-configurations/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const HTMLGeneratorPlugin = require("../../helpers/html-generator-plugin"); - -module.exports = [ +import HTMLGeneratorPlugin from "../../helpers/html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default [ { target: "web", name: "one", diff --git a/test/fixtures/multi-public-path-config/bar.js b/test/fixtures/multi-public-path-config/bar.js index 3c915dbcb8..3dea82f991 100644 --- a/test/fixtures/multi-public-path-config/bar.js +++ b/test/fixtures/multi-public-path-config/bar.js @@ -1,3 +1 @@ -"use strict"; - console.log("Hey."); diff --git a/test/fixtures/multi-public-path-config/baz.js b/test/fixtures/multi-public-path-config/baz.js index 3c915dbcb8..3dea82f991 100644 --- a/test/fixtures/multi-public-path-config/baz.js +++ b/test/fixtures/multi-public-path-config/baz.js @@ -1,3 +1 @@ -"use strict"; - console.log("Hey."); diff --git a/test/fixtures/multi-public-path-config/foo.js b/test/fixtures/multi-public-path-config/foo.js index d2f0aa53dd..287ee67d45 100644 --- a/test/fixtures/multi-public-path-config/foo.js +++ b/test/fixtures/multi-public-path-config/foo.js @@ -1,3 +1 @@ -"use strict"; - -require("./test.html"); +import "./test.html"; diff --git a/test/fixtures/multi-public-path-config/webpack.config.js b/test/fixtures/multi-public-path-config/webpack.config.js index 71e82d2309..4d46617789 100644 --- a/test/fixtures/multi-public-path-config/webpack.config.js +++ b/test/fixtures/multi-public-path-config/webpack.config.js @@ -1,7 +1,8 @@ -"use strict"; - -const path = require("path"); - +import path from "path"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); const moduleRuleForHTML = { test: /\.html$/, type: "asset/resource", @@ -9,8 +10,7 @@ const moduleRuleForHTML = { filename: "path/to/file.html", }, }; - -module.exports = [ +export default [ { mode: "development", context: __dirname, diff --git a/test/fixtures/overlay-config/trusted-types.webpack.config.js b/test/fixtures/overlay-config/trusted-types.webpack.config.js index 94c2921269..6c002c9fcf 100644 --- a/test/fixtures/overlay-config/trusted-types.webpack.config.js +++ b/test/fixtures/overlay-config/trusted-types.webpack.config.js @@ -1,15 +1,18 @@ -"use strict"; - -const HTMLGeneratorPlugin = require("../../helpers/trusted-types-html-generator-plugin"); - -module.exports = { +import HTMLGeneratorPlugin from "../../helpers/trusted-types-html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, stats: "none", entry: "./foo.js", output: { path: "/", - trustedTypes: { policyName: "webpack" }, + trustedTypes: { + policyName: "webpack", + }, }, infrastructureLogging: { level: "info", diff --git a/test/fixtures/overlay-config/webpack.config.js b/test/fixtures/overlay-config/webpack.config.js index c1e0b481b1..deb93af17d 100644 --- a/test/fixtures/overlay-config/webpack.config.js +++ b/test/fixtures/overlay-config/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const HTMLGeneratorPlugin = require("../../helpers/html-generator-plugin"); - -module.exports = { +import HTMLGeneratorPlugin from "../../helpers/html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, stats: "none", diff --git a/test/fixtures/provide-plugin-custom/foo.js b/test/fixtures/provide-plugin-custom/foo.js index c1faff1c20..9eebdb9e2d 100644 --- a/test/fixtures/provide-plugin-custom/foo.js +++ b/test/fixtures/provide-plugin-custom/foo.js @@ -1,8 +1,4 @@ -"use strict"; - -// 'npm run prepare' must be run for this to work during testing -const CustomClient = require("../custom-client/CustomWebSocketClient"); - +import CustomClient from "../custom-client/CustomWebSocketClient.js"; window.expectedClient = CustomClient; // eslint-disable-next-line camelcase, no-undef window.injectedClient = __webpack_dev_server_client__; diff --git a/test/fixtures/provide-plugin-custom/webpack.config.js b/test/fixtures/provide-plugin-custom/webpack.config.js index 6006074030..888b9dc040 100644 --- a/test/fixtures/provide-plugin-custom/webpack.config.js +++ b/test/fixtures/provide-plugin-custom/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const HTMLGeneratorPlugin = require("../../helpers/html-generator-plugin"); - -module.exports = { +import HTMLGeneratorPlugin from "../../helpers/html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, stats: "none", diff --git a/test/fixtures/provide-plugin-default/foo.js b/test/fixtures/provide-plugin-default/foo.js index bd4904444f..8d7bf33392 100644 --- a/test/fixtures/provide-plugin-default/foo.js +++ b/test/fixtures/provide-plugin-default/foo.js @@ -1,9 +1,4 @@ -"use strict"; - -// 'npm run prepare' must be run for this to work during testing -const WebsocketClient = - require("../../../client/clients/WebSocketClient").default; - +import WebsocketClient from "../../../client/clients/WebSocketClient.js"; window.expectedClient = WebsocketClient; // eslint-disable-next-line camelcase, no-undef window.injectedClient = __webpack_dev_server_client__.default; diff --git a/test/fixtures/provide-plugin-default/webpack.config.js b/test/fixtures/provide-plugin-default/webpack.config.js index 6006074030..888b9dc040 100644 --- a/test/fixtures/provide-plugin-default/webpack.config.js +++ b/test/fixtures/provide-plugin-default/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const HTMLGeneratorPlugin = require("../../helpers/html-generator-plugin"); - -module.exports = { +import HTMLGeneratorPlugin from "../../helpers/html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, stats: "none", diff --git a/test/fixtures/provide-plugin-ws-config/foo.js b/test/fixtures/provide-plugin-ws-config/foo.js index bd4904444f..8d7bf33392 100644 --- a/test/fixtures/provide-plugin-ws-config/foo.js +++ b/test/fixtures/provide-plugin-ws-config/foo.js @@ -1,9 +1,4 @@ -"use strict"; - -// 'npm run prepare' must be run for this to work during testing -const WebsocketClient = - require("../../../client/clients/WebSocketClient").default; - +import WebsocketClient from "../../../client/clients/WebSocketClient.js"; window.expectedClient = WebsocketClient; // eslint-disable-next-line camelcase, no-undef window.injectedClient = __webpack_dev_server_client__.default; diff --git a/test/fixtures/provide-plugin-ws-config/webpack.config.js b/test/fixtures/provide-plugin-ws-config/webpack.config.js index 6006074030..888b9dc040 100644 --- a/test/fixtures/provide-plugin-ws-config/webpack.config.js +++ b/test/fixtures/provide-plugin-ws-config/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const HTMLGeneratorPlugin = require("../../helpers/html-generator-plugin"); - -module.exports = { +import HTMLGeneratorPlugin from "../../helpers/html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, stats: "none", diff --git a/test/fixtures/proxy-config/foo.js b/test/fixtures/proxy-config/foo.js index 3c915dbcb8..3dea82f991 100644 --- a/test/fixtures/proxy-config/foo.js +++ b/test/fixtures/proxy-config/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("Hey."); diff --git a/test/fixtures/proxy-config/webpack.config.js b/test/fixtures/proxy-config/webpack.config.js index f03898aa61..65ce243635 100644 --- a/test/fixtures/proxy-config/webpack.config.js +++ b/test/fixtures/proxy-config/webpack.config.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = { +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, stats: "none", diff --git a/test/fixtures/reload-config-2/foo.js b/test/fixtures/reload-config-2/foo.js index 37887d2535..361bfb33ae 100644 --- a/test/fixtures/reload-config-2/foo.js +++ b/test/fixtures/reload-config-2/foo.js @@ -1,4 +1,2 @@ -"use strict"; - // eslint-disable-next-line import/no-unresolved -require("./main.css"); +import "./main.css"; diff --git a/test/fixtures/reload-config-2/webpack.config.js b/test/fixtures/reload-config-2/webpack.config.js index b8d11148bb..776be420f0 100644 --- a/test/fixtures/reload-config-2/webpack.config.js +++ b/test/fixtures/reload-config-2/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const HTMLGeneratorPlugin = require("../../helpers/html-generator-plugin"); - -module.exports = { +import HTMLGeneratorPlugin from "../../helpers/html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, stats: "none", @@ -14,7 +15,14 @@ module.exports = { rules: [ { test: /\.css$/, - use: [{ loader: "style-loader" }, { loader: "css-loader" }], + use: [ + { + loader: "style-loader", + }, + { + loader: "css-loader", + }, + ], }, ], }, diff --git a/test/fixtures/reload-config/foo.js b/test/fixtures/reload-config/foo.js index 68ad7bddf6..1bebc0ca7a 100644 --- a/test/fixtures/reload-config/foo.js +++ b/test/fixtures/reload-config/foo.js @@ -1,3 +1 @@ -"use strict"; - -require("./main.css"); +import "./main.css"; diff --git a/test/fixtures/reload-config/webpack.config.js b/test/fixtures/reload-config/webpack.config.js index 9801ab7ac2..92d77b4620 100644 --- a/test/fixtures/reload-config/webpack.config.js +++ b/test/fixtures/reload-config/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const HTMLGeneratorPlugin = require("../../helpers/html-generator-plugin"); - -module.exports = { +import HTMLGeneratorPlugin from "../../helpers/html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, entry: "./foo.js", @@ -14,7 +15,14 @@ module.exports = { rules: [ { test: /\.css$/, - use: [{ loader: "style-loader" }, { loader: "css-loader" }], + use: [ + { + loader: "style-loader", + }, + { + loader: "css-loader", + }, + ], }, ], }, diff --git a/test/fixtures/schema/webpack.config.simple.js b/test/fixtures/schema/webpack.config.simple.js index ad290af1fb..b430af6a9f 100644 --- a/test/fixtures/schema/webpack.config.simple.js +++ b/test/fixtures/schema/webpack.config.simple.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = { +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, entry: "./foo.js", diff --git a/test/fixtures/simple-config-other/foo.js b/test/fixtures/simple-config-other/foo.js index 64284aa09e..c6df86ba3f 100644 --- a/test/fixtures/simple-config-other/foo.js +++ b/test/fixtures/simple-config-other/foo.js @@ -1,5 +1,3 @@ -"use strict"; - console.log( "Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Long Line.", ); diff --git a/test/fixtures/simple-config-other/webpack.config.js b/test/fixtures/simple-config-other/webpack.config.js index 624dc8a648..d2e5ae5648 100644 --- a/test/fixtures/simple-config-other/webpack.config.js +++ b/test/fixtures/simple-config-other/webpack.config.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = { +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, stats: "none", diff --git a/test/fixtures/simple-config/foo.js b/test/fixtures/simple-config/foo.js index 3c915dbcb8..3dea82f991 100644 --- a/test/fixtures/simple-config/foo.js +++ b/test/fixtures/simple-config/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("Hey."); diff --git a/test/fixtures/simple-config/webpack.config.js b/test/fixtures/simple-config/webpack.config.js index 6006074030..888b9dc040 100644 --- a/test/fixtures/simple-config/webpack.config.js +++ b/test/fixtures/simple-config/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const HTMLGeneratorPlugin = require("../../helpers/html-generator-plugin"); - -module.exports = { +import HTMLGeneratorPlugin from "../../helpers/html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, stats: "none", diff --git a/test/fixtures/static-config/foo.js b/test/fixtures/static-config/foo.js index 3c915dbcb8..3dea82f991 100644 --- a/test/fixtures/static-config/foo.js +++ b/test/fixtures/static-config/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("Hey."); diff --git a/test/fixtures/static-config/webpack.config.js b/test/fixtures/static-config/webpack.config.js index e0a2dfdbd5..28d132c646 100644 --- a/test/fixtures/static-config/webpack.config.js +++ b/test/fixtures/static-config/webpack.config.js @@ -1,6 +1,8 @@ -"use strict"; - -module.exports = { +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", context: __dirname, stats: "none", diff --git a/test/fixtures/static/foo.js b/test/fixtures/static/foo.js index 5940e9197c..e19c947786 100644 --- a/test/fixtures/static/foo.js +++ b/test/fixtures/static/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("i am foo!"); diff --git a/test/fixtures/static/webpack.config.js b/test/fixtures/static/webpack.config.js index a710816d46..715e67c14f 100644 --- a/test/fixtures/static/webpack.config.js +++ b/test/fixtures/static/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const path = require("path"); - -module.exports = { +import path from "path"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", entry: path.resolve(__dirname, "foo.js"), devServer: { diff --git a/test/fixtures/universal-compiler-config/browser.js b/test/fixtures/universal-compiler-config/browser.js index ddcebf29c7..801b8ff0c5 100644 --- a/test/fixtures/universal-compiler-config/browser.js +++ b/test/fixtures/universal-compiler-config/browser.js @@ -1,3 +1 @@ -"use strict"; - console.log("Hello from the browser"); diff --git a/test/fixtures/universal-compiler-config/server.js b/test/fixtures/universal-compiler-config/server.js index 3dfb585f6d..f02fa029ad 100644 --- a/test/fixtures/universal-compiler-config/server.js +++ b/test/fixtures/universal-compiler-config/server.js @@ -1,3 +1 @@ -"use strict"; - console.log("Hello from the server"); diff --git a/test/fixtures/universal-compiler-config/webpack.config.js b/test/fixtures/universal-compiler-config/webpack.config.js index 368e5606f4..dcc1cf5451 100644 --- a/test/fixtures/universal-compiler-config/webpack.config.js +++ b/test/fixtures/universal-compiler-config/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const HTMLGeneratorPlugin = require("../../helpers/html-generator-plugin"); - -module.exports = [ +import HTMLGeneratorPlugin from "../../helpers/html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default [ { name: "browser", mode: "development", diff --git a/test/fixtures/watch-files-config/foo.js b/test/fixtures/watch-files-config/foo.js index 3c915dbcb8..3dea82f991 100644 --- a/test/fixtures/watch-files-config/foo.js +++ b/test/fixtures/watch-files-config/foo.js @@ -1,3 +1 @@ -"use strict"; - console.log("Hey."); diff --git a/test/fixtures/watch-files-config/webpack.config.js b/test/fixtures/watch-files-config/webpack.config.js index 2f64765a90..3602319984 100644 --- a/test/fixtures/watch-files-config/webpack.config.js +++ b/test/fixtures/watch-files-config/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const HTMLGeneratorPlugin = require("../../helpers/html-generator-plugin"); - -module.exports = { +import HTMLGeneratorPlugin from "../../helpers/html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default { mode: "development", devtool: false, context: __dirname, diff --git a/test/fixtures/worker-config-dev-server-false/index.js b/test/fixtures/worker-config-dev-server-false/index.js index a7cbdfdd80..b55b42ac9d 100644 --- a/test/fixtures/worker-config-dev-server-false/index.js +++ b/test/fixtures/worker-config-dev-server-false/index.js @@ -1,9 +1,5 @@ -"use strict"; - const myWorker = new Worker("./worker-bundle.js"); - myWorker.onmessage = (event) => { console.log(`Worker said: ${event.data}`); }; - myWorker.postMessage("message"); diff --git a/test/fixtures/worker-config-dev-server-false/webpack.config.js b/test/fixtures/worker-config-dev-server-false/webpack.config.js index a53fe51d31..18b4e01256 100644 --- a/test/fixtures/worker-config-dev-server-false/webpack.config.js +++ b/test/fixtures/worker-config-dev-server-false/webpack.config.js @@ -1,9 +1,10 @@ -"use strict"; - -const path = require("path"); -const HTMLGeneratorPlugin = require("../../helpers/html-generator-plugin"); - -module.exports = [ +import path from "path"; +import HTMLGeneratorPlugin from "../../helpers/html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default [ { name: "app", // dependencies: ["worker"], diff --git a/test/fixtures/worker-config-dev-server-false/worker.js b/test/fixtures/worker-config-dev-server-false/worker.js index 37bab96133..124ce81f64 100644 --- a/test/fixtures/worker-config-dev-server-false/worker.js +++ b/test/fixtures/worker-config-dev-server-false/worker.js @@ -1,7 +1,4 @@ -"use strict"; - postMessage("I'm working before postMessage"); - onmessage = (event) => { postMessage(`Message sent: ${event.data}`); }; diff --git a/test/fixtures/worker-config/index.js b/test/fixtures/worker-config/index.js index e14970b9ec..2c87e80371 100644 --- a/test/fixtures/worker-config/index.js +++ b/test/fixtures/worker-config/index.js @@ -1,9 +1,5 @@ -"use strict"; - const myWorker = new Worker("./worker.js"); - myWorker.onmessage = (event) => { console.log(`Worker said: ${event.data}`); }; - myWorker.postMessage("message"); diff --git a/test/fixtures/worker-config/webpack.config.js b/test/fixtures/worker-config/webpack.config.js index a4b8cc5940..1a2a43e23c 100644 --- a/test/fixtures/worker-config/webpack.config.js +++ b/test/fixtures/worker-config/webpack.config.js @@ -1,8 +1,9 @@ -"use strict"; - -const HTMLGeneratorPlugin = require("../../helpers/html-generator-plugin"); - -module.exports = [ +import HTMLGeneratorPlugin from "../../helpers/html-generator-plugin.js"; +import { fileURLToPath } from "node:url"; +import { dirname } from "node:path"; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +export default [ { name: "app", dependencies: ["worker"], diff --git a/test/fixtures/worker-config/worker.js b/test/fixtures/worker-config/worker.js index 37bab96133..124ce81f64 100644 --- a/test/fixtures/worker-config/worker.js +++ b/test/fixtures/worker-config/worker.js @@ -1,7 +1,4 @@ -"use strict"; - postMessage("I'm working before postMessage"); - onmessage = (event) => { postMessage(`Message sent: ${event.data}`); }; diff --git a/test/helpers/ExitOnDonePlugin.js b/test/helpers/ExitOnDonePlugin.js index 656b58579a..982c85be2f 100644 --- a/test/helpers/ExitOnDonePlugin.js +++ b/test/helpers/ExitOnDonePlugin.js @@ -1,18 +1,14 @@ -"use strict"; - -module.exports = class ExitOnDonePlugin { +export default (class ExitOnDonePlugin { apply(compiler) { compiler.hooks.afterDone.tap("webpack-dev-server", (stats) => { let exitCode = 0; - if (stats.hasErrors()) { exitCode = 1; } - setImmediate(() => { // eslint-disable-next-line n/no-process-exit process.exit(exitCode); }); }); } -}; +}); diff --git a/test/helpers/conditional-test.js b/test/helpers/conditional-test.js index 9a05682c72..00ce78025d 100644 --- a/test/helpers/conditional-test.js +++ b/test/helpers/conditional-test.js @@ -1,5 +1,3 @@ -"use strict"; - /* global test */ const isWindows = process.platform === "win32"; @@ -12,8 +10,7 @@ function skipTestOnWindows(reason) { if (isWindows) { test.skip(reason, () => {}); } - return isWindows; } -module.exports.skipTestOnWindows = skipTestOnWindows; +export { skipTestOnWindows }; diff --git a/test/helpers/custom-http.js b/test/helpers/custom-http.js index 29046c9bc3..9b4866f1b2 100644 --- a/test/helpers/custom-http.js +++ b/test/helpers/custom-http.js @@ -1,5 +1 @@ -"use strict"; - -const customHTTP = require("node:http"); - -module.exports = customHTTP; +export { default } from "node:http"; diff --git a/test/helpers/html-generator-plugin.js b/test/helpers/html-generator-plugin.js index 261d16e592..7d5472c590 100644 --- a/test/helpers/html-generator-plugin.js +++ b/test/helpers/html-generator-plugin.js @@ -1,5 +1,3 @@ -"use strict"; - const HTMLContentForIndex = ` @@ -13,7 +11,6 @@ const HTMLContentForIndex = ` `; - const HTMLContentForAssets = (assetName) => ` @@ -27,7 +24,6 @@ const HTMLContentForAssets = (assetName) => ` `; - const HTMLContentForTest = ` @@ -41,13 +37,11 @@ const HTMLContentForTest = ` `; -module.exports = class HTMLGeneratorPlugin { +export default (class HTMLGeneratorPlugin { apply(compiler) { const pluginName = "html-generator-plugin"; - compiler.hooks.thisCompilation.tap(pluginName, (compilation) => { const { RawSource } = compiler.webpack.sources; - compilation.hooks.processAssets.tap( { name: pluginName, @@ -57,13 +51,10 @@ module.exports = class HTMLGeneratorPlugin { const indexSource = new RawSource(HTMLContentForIndex); const testSource = new RawSource(HTMLContentForTest); const assets = compilation.getAssets(); - compilation.emitAsset("index.html", indexSource); compilation.emitAsset("test.html", testSource); - for (const asset of assets) { const assetName = asset.name; - if (assetName !== "main.js") { const assetSource = new RawSource( // eslint-disable-next-line new-cap @@ -79,4 +70,4 @@ module.exports = class HTMLGeneratorPlugin { ); }); } -}; +}); diff --git a/test/helpers/normalize-options.js b/test/helpers/normalize-options.js index 923b8146e1..1bad381358 100644 --- a/test/helpers/normalize-options.js +++ b/test/helpers/normalize-options.js @@ -1,15 +1,11 @@ -"use strict"; - /** * @param {import("https").ServerOptions} options server options * @returns {Record} normalized server options */ function normalizeOptions(options) { const normalizedOptions = {}; - for (const propertyName in options) { let value = options[propertyName]; - if (Array.isArray(value)) { value = value.map((item) => { if (Buffer.isBuffer(item)) { @@ -25,17 +21,14 @@ function normalizeOptions(options) { ) { item.buf = ""; } - return item; }); } else if (Buffer.isBuffer(value)) { value = ""; } - normalizedOptions[propertyName] = value; } - return normalizedOptions; } -module.exports = normalizeOptions; +export default normalizeOptions; diff --git a/test/helpers/puppeteer-constants.js b/test/helpers/puppeteer-constants.js index 23bce93c45..346298d823 100644 --- a/test/helpers/puppeteer-constants.js +++ b/test/helpers/puppeteer-constants.js @@ -1,53 +1,49 @@ -"use strict"; - -module.exports = { - reloadReadyDelay: 5000, - completeReloadDelay: 10000, - initConsoleDelay: 3000, - awaitServerCloseDelay: 1000, - beforeBrowserCloseDelay: 3000, - puppeteerArgs: [ - "--disable-background-timer-throttling", - "--disable-breakpad", - "--disable-client-side-phishing-detection", - "--disable-cloud-import", - "--disable-default-apps", - "--disable-dev-shm-usage", - "--disable-extensions", - "--disable-gesture-typing", - "--disable-hang-monitor", - "--disable-infobars", - "--disable-notifications", - "--disable-offer-store-unmasked-wallet-cards", - "--disable-offer-upload-credit-cards", - "--disable-popup-blocking", - "--disable-print-preview", - "--disable-prompt-on-repost", - "--disable-setuid-sandbox", - "--disable-speech-api", - "--disable-sync", - "--disable-tab-for-desktop-share", - "--disable-translate", - "--disable-voice-input", - "--disable-wake-on-wifi", - "--enable-async-dns", - "--enable-simple-cache-backend", - "--enable-tcp-fast-open", - "--enable-webgl", - "--hide-scrollbars", - "--ignore-gpu-blacklist", - "--media-cache-size=33554432", - "--metrics-recording-only", - "--mute-audio", - "--no-default-browser-check", - "--no-first-run", - "--no-pings", - "--no-sandbox", - "--no-zygote", - "--password-store=basic", - "--prerender-from-omnibox=disabled", - "--use-gl=swiftshader", - "--use-mock-keychain", - "--disable-field-trial-config", - ], -}; +export const reloadReadyDelay = 5000; +export const completeReloadDelay = 10000; +export const initConsoleDelay = 3000; +export const awaitServerCloseDelay = 1000; +export const beforeBrowserCloseDelay = 3000; +export const puppeteerArgs = [ + "--disable-background-timer-throttling", + "--disable-breakpad", + "--disable-client-side-phishing-detection", + "--disable-cloud-import", + "--disable-default-apps", + "--disable-dev-shm-usage", + "--disable-extensions", + "--disable-gesture-typing", + "--disable-hang-monitor", + "--disable-infobars", + "--disable-notifications", + "--disable-offer-store-unmasked-wallet-cards", + "--disable-offer-upload-credit-cards", + "--disable-popup-blocking", + "--disable-print-preview", + "--disable-prompt-on-repost", + "--disable-setuid-sandbox", + "--disable-speech-api", + "--disable-sync", + "--disable-tab-for-desktop-share", + "--disable-translate", + "--disable-voice-input", + "--disable-wake-on-wifi", + "--enable-async-dns", + "--enable-simple-cache-backend", + "--enable-tcp-fast-open", + "--enable-webgl", + "--hide-scrollbars", + "--ignore-gpu-blacklist", + "--media-cache-size=33554432", + "--metrics-recording-only", + "--mute-audio", + "--no-default-browser-check", + "--no-first-run", + "--no-pings", + "--no-sandbox", + "--no-zygote", + "--password-store=basic", + "--prerender-from-omnibox=disabled", + "--use-gl=swiftshader", + "--use-mock-keychain", + "--disable-field-trial-config", +]; diff --git a/test/helpers/run-browser.js b/test/helpers/run-browser.js index e4d00b9ba9..e107286c32 100644 --- a/test/helpers/run-browser.js +++ b/test/helpers/run-browser.js @@ -1,8 +1,5 @@ -"use strict"; - -const puppeteer = require("puppeteer"); -const { puppeteerArgs } = require("./puppeteer-constants"); - +import { launch } from "puppeteer"; +import { puppeteerArgs } from "./puppeteer-constants.js"; /** @typedef {import('puppeteer').Browser} Browser */ /** @typedef {import('puppeteer').Page} Page */ /** @typedef {import('puppeteer').Device} Device */ @@ -23,7 +20,6 @@ function runPage(browser, device) { * @type {Page} */ let page; - const options = { viewport: { width: 500, @@ -32,13 +28,11 @@ function runPage(browser, device) { userAgent: "", ...device, }; - return Promise.resolve() .then(() => browser.newPage()) .then((newPage) => { page = newPage; page.emulate(options); - return page.setRequestInterception(true); }) .then(() => { @@ -57,7 +51,6 @@ function runPage(browser, device) { ); } }); - return page; }); } @@ -76,28 +69,27 @@ function runBrowser(device) { * @type {import('puppeteer').Browser} */ let browser; - - puppeteer - .launch({ - headless: "new", - // because of invalid localhost certificate - acceptInsecureCerts: true, - // args come from: https://github.com/alixaxel/chrome-aws-lambda/blob/master/source/index.js - args: puppeteerArgs, - }) + launch({ + headless: "new", + // because of invalid localhost certificate + acceptInsecureCerts: true, + // args come from: https://github.com/alixaxel/chrome-aws-lambda/blob/master/source/index.js + args: puppeteerArgs, + }) .then((launchedBrowser) => { browser = launchedBrowser; - return runPage(launchedBrowser, device); }) .then((newPage) => { page = newPage; - - resolve({ page, browser }); + resolve({ + page, + browser, + }); }) .catch(reject); }); } -module.exports = runBrowser; -module.exports.runPage = runPage; +export default runBrowser; +export { runPage }; diff --git a/test/helpers/session-subscribe.js b/test/helpers/session-subscribe.js index 9287e2646a..02c92b13ef 100644 --- a/test/helpers/session-subscribe.js +++ b/test/helpers/session-subscribe.js @@ -1,9 +1,7 @@ -"use strict"; - -module.exports = async function sessionSubscribe(session) { +export default (async function sessionSubscribe(session) { session.on("sessionattached", (attachedSession) => { sessionSubscribe(attachedSession); }); await session.send("Network.enable"); await session.send("Runtime.runIfWaitingForDebugger"); -}; +}); diff --git a/test/helpers/test-bin.js b/test/helpers/test-bin.js index 15667fe59e..2ffb33faee 100644 --- a/test/helpers/test-bin.js +++ b/test/helpers/test-bin.js @@ -1,11 +1,12 @@ -"use strict"; - -const os = require("node:os"); -const path = require("node:path"); -const util = require("node:util"); -const execa = require("execa"); -const { Writable } = require("readable-stream"); - +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import util from "node:util"; +import execa from "execa"; +import { Writable } from "readable-stream"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); const webpackDevServerPath = path.resolve( __dirname, "../../bin/webpack-dev-server.js", @@ -26,30 +27,24 @@ const processKill = (process) => { // process.kill(); // } }; - const testBin = (testArgs = [], options = {}) => { const cwd = process.cwd(); const env = { WEBPACK_CLI_HELP_WIDTH: 2048, NODE_ENV: process.env.NODE_ENV, }; - if (typeof testArgs === "string") { testArgs = testArgs.split(" "); } - let args; - if (testArgs.includes("--help")) { args = [webpackDevServerPath, ...testArgs]; } else { const configOptions = testArgs.includes("--config") ? [] : ["--config", basicConfigPath]; - args = [webpackDevServerPath, ...configOptions, ...testArgs]; } - return new Promise((resolve, reject) => { const outputKillStr = options.outputKillStr || @@ -62,44 +57,36 @@ const testBin = (testArgs = [], options = {}) => { reject: false, ...options, }); - subprocess.stdout.pipe( new Writable({ write(chunk, encoding, callback) { const str = chunk.toString(); const output = util.stripVTControlCharacters(str); - if (outputKillStr.test(output)) { processKill(subprocess); } - callback(); }, }), ); - subprocess.stderr.pipe( new Writable({ write(chunk, encoding, callback) { const str = chunk.toString(); const output = util.stripVTControlCharacters(str); - if (outputKillStr.test(output)) { processKill(subprocess); } - callback(); }, }), ); - subprocess .then((result) => { // Sometimes we will kill our process early, so there is no exit code if (!result.exitCode) { result.exitCode = 0; } - resolve(result); }) .catch((error) => { @@ -107,7 +94,6 @@ const testBin = (testArgs = [], options = {}) => { }); }); }; - const ipV4 = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}"; const ipV6Seg = "[a-fA-F\\d]{1,4}"; @@ -126,10 +112,8 @@ const ipV6 = ` .replaceAll(/\s*\/\/.*$/gm, "") .replaceAll("\n", "") .trim(); - const normalizeStderr = (stderr, options = {}) => { let normalizedStderr = util.stripVTControlCharacters(stderr); - normalizedStderr = normalizedStderr .replaceAll("\\", "/") .replaceAll(new RegExp(process.cwd().replaceAll("\\", "/"), "g"), "") @@ -147,14 +131,12 @@ const normalizeStderr = (stderr, options = {}) => { /.*Use `node --trace-deprecation ...` to show where the warning was created.*(\n)*/gm, "", ); - normalizedStderr = normalizedStderr.split("\n"); normalizedStderr = normalizedStderr.filter( (item) => !/.+wait until bundle finished.*(\n)?/g.test(item), ); normalizedStderr = normalizedStderr.join("\n"); normalizedStderr = normalizedStderr.replaceAll(/:[0-9]+\//g, ":/"); - if (options.https) { // We have deprecation warning on windows in some cases normalizedStderr = normalizedStderr.split("\n"); @@ -167,45 +149,34 @@ const normalizeStderr = (stderr, options = {}) => { ); normalizedStderr = normalizedStderr.join("\n"); } - if (normalizedStderr.includes("Loopback:")) { normalizedStderr = normalizedStderr.split("\n"); - const loopbackIndex = normalizedStderr.findIndex((item) => /Loopback:/.test(item), ); - const protocol = options.https ? "https" : "http"; - normalizedStderr[loopbackIndex] = ` Loopback: ${protocol}://localhost:/, ${protocol}://:/, ${protocol}://[]:/`; normalizedStderr = normalizedStderr.join("\n"); } - if (options.ipv6 && !normalizedStderr.includes("On Your Network (IPv6):")) { // Github Actions doesn't support IPv6 on ubuntu in some cases normalizedStderr = normalizedStderr.split("\n"); - const ipv4MessageIndex = normalizedStderr.findIndex((item) => /On Your Network \(IPv4\)/.test(item), ); - const protocol = options.https ? "https" : "http"; - normalizedStderr.splice( ipv4MessageIndex + 1, 0, ` [webpack-dev-server] On Your Network (IPv6): ${protocol}://[]:/`, ); - normalizedStderr = normalizedStderr.join("\n"); } - if (/Gracefully shutting down/.test(normalizedStderr)) { normalizedStderr = normalizedStderr.split("\n").slice(0, -1).join("\n"); } - return normalizedStderr; }; -module.exports = { normalizeStderr, testBin }; +export { normalizeStderr, testBin }; diff --git a/test/helpers/test-server.js b/test/helpers/test-server.js index 9333c64601..94a094611d 100644 --- a/test/helpers/test-server.js +++ b/test/helpers/test-server.js @@ -1,8 +1,5 @@ -"use strict"; - -const webpack = require("webpack"); -const Server = require("../../lib/Server"); - +import webpack from "webpack"; +import Server from "../../lib/Server.js"; /** @typedef {import("webpack").Configuration} Configuration */ /** @typedef {import("../../lib/Server").Configuration} DevServerConfiguration */ /** @typedef {import("webpack").Compiler} Compiler */ @@ -27,21 +24,16 @@ function startFullSetup(config, devServerConfig, done) { // this provides a way of using the default static value delete devServerConfig.static; } - const compiler = webpack(config); - server = new Server(devServerConfig, compiler); - server.startCallback((error) => { if (error && done) { return done(error); } - if (done) { done(); } }); - return { server, compiler, @@ -56,21 +48,16 @@ function startFullSetup(config, devServerConfig, done) { */ function start(config, devServerConfig, done) { let readyCount = 0; - const ready = (error) => { if (error && done) { done(error); - return; } - readyCount += 1; - if (readyCount === 2) { done(); } }; - const result = startFullSetup(config, devServerConfig, ready); // wait for compilation, since dev server can start before this @@ -78,7 +65,6 @@ function start(config, devServerConfig, done) { result.compiler.hooks.done.tap("done", () => { ready(); }); - return result.server; } @@ -96,7 +82,7 @@ function close(done) { } } -module.exports = { +export default { close, start, }; diff --git a/test/helpers/trusted-types-html-generator-plugin.js b/test/helpers/trusted-types-html-generator-plugin.js index 6d023305db..57459f7a9a 100644 --- a/test/helpers/trusted-types-html-generator-plugin.js +++ b/test/helpers/trusted-types-html-generator-plugin.js @@ -1,5 +1,3 @@ -"use strict"; - const HTMLContentForIndex = ` @@ -17,7 +15,6 @@ const HTMLContentForIndex = ` `; - const HTMLContentForTest = ` @@ -35,14 +32,12 @@ const HTMLContentForTest = ` `; -module.exports = class HTMLGeneratorPlugin { +export default (class HTMLGeneratorPlugin { apply(compiler) { const pluginName = "html-generator-plugin"; - compiler.hooks.thisCompilation.tap(pluginName, (compilation) => { if (compiler.webpack) { const { RawSource } = compiler.webpack.sources; - compilation.hooks.processAssets.tap( { name: pluginName, @@ -51,7 +46,6 @@ module.exports = class HTMLGeneratorPlugin { () => { const indexSource = new RawSource(HTMLContentForIndex); const testSource = new RawSource(HTMLContentForTest); - compilation.emitAsset("index.html", indexSource); compilation.emitAsset("test.html", testSource); }, @@ -78,4 +72,4 @@ module.exports = class HTMLGeneratorPlugin { } }); } -}; +}); diff --git a/test/normalize-options.test.js b/test/normalize-options.test.js index b80d418ed0..b0d781b804 100644 --- a/test/normalize-options.test.js +++ b/test/normalize-options.test.js @@ -1,9 +1,9 @@ -"use strict"; +import { klona } from "klona/full"; +import webpack from "webpack"; +import Server from "../lib/Server.js"; +import _ports_map from "./ports-map.js"; -const { klona } = require("klona/full"); -const webpack = require("webpack"); -const Server = require("../lib/Server"); -const port = require("./ports-map")["normalize-option"]; +const port = _ports_map["normalize-option"]; describe("normalize options", () => { const cases = [ @@ -483,7 +483,6 @@ describe("normalize options", () => { }, }, }, - { title: "single compiler watchOptions is object", multiCompiler: false, @@ -569,14 +568,15 @@ describe("normalize options", () => { }, }, ]; - for (const item of cases) { it(item.title, async () => { let webpackConfig; - if (item.multiCompiler) { - webpackConfig = require("./fixtures/multi-compiler-one-configuration/webpack.config"); - + webpackConfig = ( + await import( + "./fixtures/multi-compiler-one-configuration/webpack.config.js" + ) + ).default; if (Array.isArray(item.webpackConfig)) { webpackConfig = item.webpackConfig.map((config, index) => ({ ...webpackConfig[index], @@ -584,8 +584,9 @@ describe("normalize options", () => { })); } } else { - webpackConfig = require("./fixtures/simple-config/webpack.config"); - + webpackConfig = ( + await import("./fixtures/simple-config/webpack.config.js") + ).default; if (item.webpackConfig) { webpackConfig = { ...webpackConfig, @@ -593,26 +594,26 @@ describe("normalize options", () => { }; } } - const compiler = webpack(webpackConfig); - const server = new Server({ ...item.options, port }, compiler); - + const server = new Server( + { + ...item.options, + port, + }, + compiler, + ); let errored; - try { await server.start(); } catch (error) { errored = error; } - try { if (item.throws) { expect(errored.message).toMatch(item.throws); } else { const optionsForSnapshot = klona(server.options); - optionsForSnapshot.port = ""; - if (optionsForSnapshot.static.length > 0) { for (const i of optionsForSnapshot.static) { i.directory = i.directory @@ -623,7 +624,6 @@ describe("normalize options", () => { ); } } - expect(optionsForSnapshot).toMatchSnapshot(); } } finally { diff --git a/test/ports-map.js b/test/ports-map.js index d898970fdf..d3fd16127a 100644 --- a/test/ports-map.js +++ b/test/ports-map.js @@ -1,5 +1,3 @@ -"use strict"; - // important: new port mappings must be added to the bottom of this list const listOfTests = { // CLI tests @@ -81,39 +79,33 @@ const listOfTests = { app: 1, "cross-origin-request": 2, }; - let startPort = 8089; - const ports = {}; - for (const key of Object.keys(listOfTests)) { const value = listOfTests[key]; - ports[key] = value === 1 ? (startPort += 1) - : // eslint-disable-next-line no-loop-func - Array.from({ length: value }).map(() => (startPort += 1)); + : Array.from({ + length: value, + // eslint-disable-next-line no-loop-func + }).map(() => (startPort += 1)); } - const busy = {}; -module.exports = new Proxy(ports, { +export default new Proxy(ports, { get(target, name) { if (!target[name]) { throw new Error( `Requested "${name}" port(s) for tests not found, please update "test/ports-map.js".`, ); } - if (busy[name]) { throw new Error( `The "${name}" port is already in use in another test, please add a new one.`, ); } - busy[name] = true; - return target[name]; }, }); diff --git a/test/server/open-option.test.js b/test/server/open-option.test.js index ddd100186c..aad22040e1 100644 --- a/test/server/open-option.test.js +++ b/test/server/open-option.test.js @@ -1,10 +1,9 @@ -"use strict"; - -const webpack = require("webpack"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/simple-config/webpack.config"); -const port = require("../ports-map")["open-option"]; +import webpack from "webpack"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/simple-config/webpack.config.js"; +import _ports_map from "../ports-map.js"; +const port = _ports_map["open-option"]; const internalIPv4 = Server.findIp("v4", false); describe('"open" option', () => { @@ -13,11 +12,9 @@ describe('"open" option', () => { beforeEach(async () => { compiler = webpack(config); - jest.unstable_mockModule("open", () => ({ default: jest.fn(() => Promise.resolve()), })); - open = (await import("open")).default; }); @@ -34,10 +31,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://localhost:${port}/`, { wait: false, }); @@ -52,10 +47,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`https://localhost:${port}/`, { wait: false, }); @@ -63,7 +56,6 @@ describe('"open" option', () => { it("should work with '0.0.0.0' host but open localhost", async () => { const host = "0.0.0.0"; - const server = new Server( { host, @@ -72,10 +64,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://localhost:${port}/`, { wait: false, }); @@ -83,7 +73,6 @@ describe('"open" option', () => { it("should work with '::' host", async () => { const host = "::"; - const server = new Server( { host, @@ -92,10 +81,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://localhost:${port}/`, { wait: false, }); @@ -103,7 +90,6 @@ describe('"open" option', () => { it("should work with 'localhost' host", async () => { const host = "localhost"; - const server = new Server( { host, @@ -112,10 +98,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/`, { wait: false, }); @@ -123,7 +107,6 @@ describe('"open" option', () => { it("should work with '127.0.0.1' host", async () => { const host = "127.0.0.1"; - const server = new Server( { host, @@ -132,10 +115,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/`, { wait: false, }); @@ -143,7 +124,6 @@ describe('"open" option', () => { it("should work with '::1' host", async () => { const host = "::1"; - const server = new Server( { host, @@ -152,10 +132,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://[${host}]:${port}/`, { wait: false, }); @@ -170,10 +148,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${internalIPv4}:${port}/`, { wait: false, }); @@ -181,7 +157,6 @@ describe('"open" option', () => { it("should work with boolean", async () => { const host = "localhost"; - const server = new Server( { host, @@ -190,10 +165,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/`, { wait: false, }); @@ -201,7 +174,6 @@ describe('"open" option', () => { it("should work with boolean but don't close with 'false' value", async () => { const host = "localhost"; - const server = new Server( { host, @@ -210,16 +182,13 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).not.toHaveBeenCalled(); }); it("should work with relative string", async () => { const host = "localhost"; - const server = new Server( { host, @@ -228,10 +197,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/index.html`, { wait: false, }); @@ -239,7 +206,6 @@ describe('"open" option', () => { it('should work with "" pattern', async () => { const host = "localhost"; - const server = new Server( { host, @@ -248,10 +214,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/`, { wait: false, }); @@ -259,7 +223,6 @@ describe('"open" option', () => { it('should work with relative string starting with "/"', async () => { const host = "localhost"; - const server = new Server( { host, @@ -268,10 +231,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/index.html`, { wait: false, }); @@ -279,7 +240,6 @@ describe('"open" option', () => { it("should work with absolute string", async () => { const host = "localhost"; - const server = new Server( { open: `http://${host}:${port}/index.html`, @@ -288,10 +248,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/index.html`, { wait: false, }); @@ -299,7 +257,6 @@ describe('"open" option', () => { it("should work with multiple relative strings", async () => { const host = "localhost"; - const server = new Server( { host: "localhost", @@ -308,10 +265,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenNthCalledWith( 1, `http://${host}:${port}/first.html`, @@ -330,7 +285,6 @@ describe('"open" option', () => { it("should work with multiple absolute strings", async () => { const host = "localhost"; - const server = new Server( { host: "localhost", @@ -342,10 +296,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenNthCalledWith( 1, `http://${host}:${port}/first.html`, @@ -364,7 +316,6 @@ describe('"open" option', () => { it('should work with "" pattern in multiple strings', async () => { const host = "localhost"; - const server = new Server( { host: "localhost", @@ -373,10 +324,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenNthCalledWith(1, `http://${host}:${port}/`, { wait: false, }); @@ -391,7 +340,6 @@ describe('"open" option', () => { it("should work with empty object", async () => { const host = "localhost"; - const server = new Server( { host, @@ -400,10 +348,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/`, { wait: false, }); @@ -411,7 +357,6 @@ describe('"open" option', () => { it("should work with object and with the 'target' option", async () => { const host = "localhost"; - const server = new Server( { host, @@ -422,10 +367,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/index.html`, { wait: false, }); @@ -433,7 +376,6 @@ describe('"open" option', () => { it("should work with object and with multiple values of the 'target' option", async () => { const host = "localhost"; - const server = new Server( { host, @@ -444,10 +386,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenNthCalledWith( 1, `http://${host}:${port}/first.html`, @@ -466,7 +406,6 @@ describe('"open" option', () => { it("should work with object and with the 'app' option", async () => { const host = "localhost"; - const server = new Server( { host, @@ -477,42 +416,44 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/`, { - app: { name: "google-chrome" }, + app: { + name: "google-chrome", + }, wait: false, }); }); it("should work with object and with the 'app' and 'arguments' options", async () => { const host = "localhost"; - const server = new Server( { host, port, open: { - app: { name: "google-chrome", arguments: ["--incognito"] }, + app: { + name: "google-chrome", + arguments: ["--incognito"], + }, }, }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/`, { - app: { name: "google-chrome", arguments: ["--incognito"] }, + app: { + name: "google-chrome", + arguments: ["--incognito"], + }, wait: false, }); }); it('should work with object with "target" and "app" options', async () => { const host = "localhost"; - const server = new Server( { host, @@ -524,19 +465,18 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/index.html`, { - app: { name: "google-chrome" }, + app: { + name: "google-chrome", + }, wait: false, }); }); it('should work with pattern in "target" and "app" options', async () => { const host = "localhost"; - const server = new Server( { host, @@ -548,40 +488,43 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/`, { - app: { name: "google-chrome" }, + app: { + name: "google-chrome", + }, wait: false, }); }); it("should work with object, with multiple value of the 'target' option and with the 'app' and 'arguments' options", async () => { const host = "localhost"; - const server = new Server( { host, port, open: { target: ["first.html", "second.html"], - app: { name: "google-chrome", arguments: ["--incognito"] }, + app: { + name: "google-chrome", + arguments: ["--incognito"], + }, }, }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenNthCalledWith( 1, `http://${host}:${port}/first.html`, { wait: false, - app: { name: "google-chrome", arguments: ["--incognito"] }, + app: { + name: "google-chrome", + arguments: ["--incognito"], + }, }, ); expect(open).toHaveBeenNthCalledWith( @@ -589,35 +532,41 @@ describe('"open" option', () => { `http://${host}:${port}/second.html`, { wait: false, - app: { name: "google-chrome", arguments: ["--incognito"] }, + app: { + name: "google-chrome", + arguments: ["--incognito"], + }, }, ); }); it("should work with object, with multiple value of the 'target' option (relative and absolute URLs) and with the 'app' option with arguments", async () => { const host = "localhost"; - const server = new Server( { host, port, open: { target: ["first.html", `http://${host}:${port}/second.html`], - app: { name: "google-chrome", arguments: ["--incognito"] }, + app: { + name: "google-chrome", + arguments: ["--incognito"], + }, }, }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenNthCalledWith( 1, `http://${host}:${port}/first.html`, { wait: false, - app: { name: "google-chrome", arguments: ["--incognito"] }, + app: { + name: "google-chrome", + arguments: ["--incognito"], + }, }, ); expect(open).toHaveBeenNthCalledWith( @@ -625,14 +574,16 @@ describe('"open" option', () => { `http://${host}:${port}/second.html`, { wait: false, - app: { name: "google-chrome", arguments: ["--incognito"] }, + app: { + name: "google-chrome", + arguments: ["--incognito"], + }, }, ); }); it("should work with pattern in multiple open options", async () => { const host = "localhost"; - const server = new Server( { host, @@ -650,24 +601,24 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/`, { - app: { name: "google-chrome" }, + app: { + name: "google-chrome", + }, wait: false, }); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/`, { - app: { name: "firefox" }, + app: { + name: "firefox", + }, wait: false, }); }); it("should work with multiple open options without target", async () => { const host = "localhost"; - const server = new Server( { host, @@ -683,24 +634,24 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/`, { - app: { name: "google-chrome" }, + app: { + name: "google-chrome", + }, wait: false, }); - expect(open).toHaveBeenCalledWith(`http://${host}:${port}/`, { - app: { name: "firefox" }, + app: { + name: "firefox", + }, wait: false, }); }); it("should log warning when can't open", async () => { open.mockRejectedValue(undefined); - const loggerWarnSpy = jest.fn(); const getInfrastructureLoggerSpy = jest .spyOn(compiler, "getInfrastructureLogger") @@ -709,7 +660,6 @@ describe('"open" option', () => { info: () => {}, log: () => {}, })); - const server = new Server( { port, @@ -717,24 +667,20 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://localhost:${port}/`, { wait: false, }); expect(loggerWarnSpy).toHaveBeenCalledWith( `Unable to open "http://localhost:${port}/" page. If you are running in a headless environment, please do not use the "open" option or related flags like "--open", "--open-target", and "--open-app-name".`, ); - getInfrastructureLoggerSpy.mockRestore(); loggerWarnSpy.mockRestore(); }); it("should log warning when can't open with string", async () => { open.mockRejectedValue(undefined); - const loggerWarnSpy = jest.fn(); const getInfrastructureLoggerSpy = jest .spyOn(compiler, "getInfrastructureLogger") @@ -743,7 +689,6 @@ describe('"open" option', () => { info: () => {}, log: () => {}, })); - const server = new Server( { open: "index.html", @@ -751,24 +696,20 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://localhost:${port}/index.html`, { wait: false, }); expect(loggerWarnSpy).toHaveBeenCalledWith( `Unable to open "http://localhost:${port}/index.html" page. If you are running in a headless environment, please do not use the "open" option or related flags like "--open", "--open-target", and "--open-app-name".`, ); - getInfrastructureLoggerSpy.mockRestore(); loggerWarnSpy.mockRestore(); }); it("should log warning when can't open with object", async () => { open.mockRejectedValue(undefined); - const loggerWarnSpy = jest.fn(); const getInfrastructureLoggerSpy = jest .spyOn(compiler, "getInfrastructureLogger") @@ -777,7 +718,6 @@ describe('"open" option', () => { info: () => {}, log: () => {}, })); - const server = new Server( { open: { @@ -788,25 +728,23 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://localhost:${port}/index.html`, { - app: { name: "google-chrome" }, + app: { + name: "google-chrome", + }, wait: false, }); expect(loggerWarnSpy).toHaveBeenCalledWith( `Unable to open "http://localhost:${port}/index.html" page in "google-chrome" app. If you are running in a headless environment, please do not use the "open" option or related flags like "--open", "--open-target", and "--open-app-name".`, ); - loggerWarnSpy.mockRestore(); getInfrastructureLoggerSpy.mockRestore(); }); it("should log warning when can't open with object with the 'app' option with arguments", async () => { open.mockRejectedValue(undefined); - const loggerWarnSpy = jest.fn(); const getInfrastructureLoggerSpy = jest .spyOn(compiler, "getInfrastructureLogger") @@ -815,7 +753,6 @@ describe('"open" option', () => { info: () => {}, log: () => {}, })); - const server = new Server( { open: { @@ -829,10 +766,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenCalledWith(`http://localhost:${port}/index.html`, { app: { name: "google-chrome", @@ -843,14 +778,12 @@ describe('"open" option', () => { expect(loggerWarnSpy).toHaveBeenCalledWith( `Unable to open "http://localhost:${port}/index.html" page in "google-chrome" app with "--incognito --new-window" arguments. If you are running in a headless environment, please do not use the "open" option or related flags like "--open", "--open-target", and "--open-app-name".`, ); - getInfrastructureLoggerSpy.mockRestore(); loggerWarnSpy.mockRestore(); }); it("should log warning when can't open with object with the 'app' option with arguments #2", async () => { open.mockRejectedValue(undefined); - const loggerWarnSpy = jest.fn(); const getInfrastructureLoggerSpy = jest .spyOn(compiler, "getInfrastructureLogger") @@ -859,7 +792,6 @@ describe('"open" option', () => { info: () => {}, log: () => {}, })); - const server = new Server( { open: { @@ -873,10 +805,8 @@ describe('"open" option', () => { }, compiler, ); - await server.start(); await server.stop(); - expect(open).toHaveBeenNthCalledWith( 1, `http://localhost:${port}/first.html`, @@ -907,7 +837,6 @@ describe('"open" option', () => { 2, `Unable to open "http://localhost:${port}/second.html" page in "google-chrome" app with "--incognito --new-window" arguments. If you are running in a headless environment, please do not use the "open" option or related flags like "--open", "--open-target", and "--open-app-name".`, ); - getInfrastructureLoggerSpy.mockRestore(); loggerWarnSpy.mockRestore(); }); diff --git a/test/server/proxy-option.test.js b/test/server/proxy-option.test.js index 76865bc1e9..3cf6faa3b9 100644 --- a/test/server/proxy-option.test.js +++ b/test/server/proxy-option.test.js @@ -1,17 +1,18 @@ -"use strict"; - -const path = require("node:path"); -const express = require("express"); -const request = require("supertest"); -const webpack = require("webpack"); -const WebSocket = require("ws"); -const Server = require("../../lib/Server"); -const config = require("../fixtures/proxy-config/webpack.config"); -const [port1, port2, port3, port4] = require("../ports-map")["proxy-option"]; - +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import express from "express"; +import request from "supertest"; +import webpack from "webpack"; +import WebSocket from "ws"; +import Server from "../../lib/Server.js"; +import config from "../fixtures/proxy-config/webpack.config.js"; +import _ports_map from "../ports-map.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const [port1, port2, port3, port4] = _ports_map["proxy-option"]; const WebSocketServer = WebSocket.Server; const staticDirectory = path.resolve(__dirname, "../fixtures/proxy-config"); - const proxyOptionPathsAsProperties = [ { context: "/proxy1", @@ -20,7 +21,9 @@ const proxyOptionPathsAsProperties = [ { path: "/api/proxy2", target: `http://localhost:${port2}`, - pathRewrite: { "^/api": "" }, + pathRewrite: { + "^/api": "", + }, }, { pathFilter: ["/foo/*.html", "/baz/*.html", "/bypass-with-target/*.html"], @@ -28,17 +31,18 @@ const proxyOptionPathsAsProperties = [ router: () => `http://localhost:${port3}`, }, ]; - const proxyOption = [ { context: () => true, target: `http://localhost:${port1}`, }, ]; - let maxServerListeners = 0; const proxyOptionOfArray = [ - { context: "/proxy1", target: `http://localhost:${port1}` }, + { + context: "/proxy1", + target: `http://localhost:${port1}`, + }, function proxy(req) { if (req) { const socket = req.socket || req.connection; @@ -53,17 +57,17 @@ const proxyOptionOfArray = [ return { context: "/api/proxy2", target: `http://localhost:${port2}`, - pathRewrite: { "^/api": "" }, + pathRewrite: { + "^/api": "", + }, }; }, ]; - const proxyOptionOfArrayWithoutTarget = [ { router: () => `http://localhost:${port1}`, }, ]; - const proxyWithPath = [ { context: "/proxy1", @@ -71,14 +75,12 @@ const proxyWithPath = [ target: `http://localhost:${port1}`, }, ]; - const proxyWithString = [ { context: "/proxy1", target: `http://localhost:${port1}`, }, ]; - const proxyWithRouterAsObject = [ { router: () => `http://localhost:${port1}`, @@ -88,7 +90,6 @@ const proxyWithRouterAsObject = [ describe("proxy option", () => { let proxyServer1; let proxyServer2; - function getStderrOutput(stderrSpy) { return stderrSpy.mock.calls .map((call) => call[0]) @@ -97,7 +98,6 @@ describe("proxy option", () => { .replaceAll(/127\.0\.0\.1:\d+/g, "127.0.0.1:") .replaceAll(/\[ENOTFOUND\]|\[EAI_AGAIN\]/g, "[]"); } - function getConsoleErrorOutput(consoleSpy) { return consoleSpy.mock.calls .map((call) => call[0]) @@ -105,11 +105,9 @@ describe("proxy option", () => { .replaceAll(/127\.0\.0\.1:\d+/g, "127.0.0.1:") .replaceAll(/\[ENOTFOUND\]|\[EAI_AGAIN\]/g, "[]"); } - async function listenProxyServers() { const proxyApp1 = express(); const proxyApp2 = express(); - proxyApp1.get("/proxy1", (req, res) => { res.send("from proxy1"); }); @@ -122,27 +120,23 @@ describe("proxy option", () => { proxyApp2.get("/proxy2", (req, res) => { res.send("from proxy2"); }); - await new Promise((resolve) => { proxyServer1 = proxyApp1.listen(port1, () => { resolve(); }); }); - await new Promise((resolve) => { proxyServer2 = proxyApp2.listen(port2, () => { resolve(); }); }); } - async function closeProxyServers() { await new Promise((resolve) => { proxyServer1.close(() => { resolve(); }); }); - await new Promise((resolve) => { proxyServer2.close(() => { resolve(); @@ -156,7 +150,6 @@ describe("proxy option", () => { beforeAll(async () => { const compiler = webpack(config); - server = new Server( { static: { @@ -168,11 +161,8 @@ describe("proxy option", () => { }, compiler, ); - await server.start(); - await listenProxyServers(); - req = request(server.app); }); @@ -184,7 +174,6 @@ describe("proxy option", () => { describe("target", () => { it("respects a proxy option when a request path is matched", async () => { const response = await req.get("/proxy1"); - expect(response.status).toBe(200); expect(response.text).toContain("from proxy1"); }); @@ -193,7 +182,6 @@ describe("proxy option", () => { describe("pathRewrite", () => { it("respects a pathRewrite option", async () => { const response = await req.get("/api/proxy2"); - expect(response.status).toBe(200); expect(response.text).toContain("from proxy2"); }); @@ -202,47 +190,40 @@ describe("proxy option", () => { describe("pathFilter and pathRewrite", () => { it("should rewrite matching paths using pathFilter", async () => { const response = await req.get("/foo/bar.html"); - expect(response.status).toBe(200); expect(response.text).toContain("Hello"); }); it("should rewrite paths using pathRewrite function", async () => { const response = await req.get("/baz/hoge.html"); - expect(response.status).toBe(200); expect(response.text).toContain("Hello"); }); it("should proxy requests that don't match pathFilter", async () => { const response = await req.get("/foo.js"); - expect(response.status).toBe(200); expect(response.text).toContain("Hey"); }); it("should serve static files when not matching proxy rules", async () => { const response = await req.get("/index.html"); - expect(response.status).toBe(200); expect(response.text).toContain("Hello"); }); it("should return 404 for unmatched paths", async () => { const response = await req.get("/proxyfalse"); - expect(response.status).toBe(404); }); it("should handle pathFilter with router option", async () => { const response = await req.get("/bypass-with-target/foo.js"); - expect(response.status).toBe(404); }); it("should rewrite matching pathFilter patterns with router", async () => { const response = await req.get("/bypass-with-target/index.html"); - expect(response.status).toBe(200); expect(response.text).toContain("Hello"); }); @@ -255,7 +236,6 @@ describe("proxy option", () => { beforeAll(async () => { const compiler = webpack(config); - server = new Server( { proxy: proxyOption, @@ -263,11 +243,8 @@ describe("proxy option", () => { }, compiler, ); - await server.start(); - await listenProxyServers(); - req = request(server.app); }); @@ -278,7 +255,6 @@ describe("proxy option", () => { it("respects a proxy option", async () => { const response = await req.get("/proxy1"); - expect(response.status).toBe(200); expect(response.text).toContain("from proxy1"); }); @@ -290,7 +266,6 @@ describe("proxy option", () => { beforeAll(async () => { const compiler = webpack(config); - server = new Server( { proxy: proxyWithString, @@ -298,11 +273,8 @@ describe("proxy option", () => { }, compiler, ); - await server.start(); - await listenProxyServers(); - req = request(server.app); }); @@ -313,7 +285,6 @@ describe("proxy option", () => { it("respects a proxy option", async () => { const response = await req.get("/proxy1"); - expect(response.status).toBe(200); expect(response.text).toContain("from proxy1"); }); @@ -325,7 +296,6 @@ describe("proxy option", () => { beforeAll(async () => { const compiler = webpack(config); - server = new Server( { proxy: proxyWithPath, @@ -333,11 +303,8 @@ describe("proxy option", () => { }, compiler, ); - await server.start(); - await listenProxyServers(); - req = request(server.app); }); @@ -348,7 +315,6 @@ describe("proxy option", () => { it("respects a proxy option", async () => { const response = await req.get("/proxy1"); - expect(response.status).toBe(200); expect(response.text).toContain("from proxy1"); }); @@ -360,7 +326,6 @@ describe("proxy option", () => { beforeAll(async () => { const compiler = webpack(config); - server = new Server( { proxy: proxyWithRouterAsObject, @@ -368,11 +333,8 @@ describe("proxy option", () => { }, compiler, ); - await server.start(); - await listenProxyServers(); - req = request(server.app); }); @@ -383,7 +345,6 @@ describe("proxy option", () => { it("respects a proxy option", async () => { const response = await req.get("/proxy1"); - expect(response.status).toBe(200); expect(response.text).toContain("from proxy1"); }); @@ -395,7 +356,6 @@ describe("proxy option", () => { beforeAll(async () => { const compiler = webpack(config); - server = new Server( { proxy: proxyOptionOfArray, @@ -403,11 +363,8 @@ describe("proxy option", () => { }, compiler, ); - await server.start(); - await listenProxyServers(); - req = request(server.app); }); @@ -418,14 +375,12 @@ describe("proxy option", () => { it("respects a proxy option", async () => { const response = await req.get("/proxy1"); - expect(response.status).toBe(200); expect(response.text).toContain("from proxy1"); }); it("respects a proxy option of function", async () => { const response = await req.get("/api/proxy2"); - expect(response.status).toBe(200); expect(response.text).toContain("from proxy2"); }); @@ -441,7 +396,6 @@ describe("proxy option", () => { beforeAll(async () => { const compiler = webpack(config); - server = new Server( { proxy: proxyOptionOfArrayWithoutTarget, @@ -449,11 +403,8 @@ describe("proxy option", () => { }, compiler, ); - await server.start(); - await listenProxyServers(); - req = request(server.app); }); @@ -464,7 +415,6 @@ describe("proxy option", () => { it("respects a proxy option", async () => { const response = await req.get("/proxy1"); - expect(response.status).toBe(200); expect(response.text).toContain("from proxy1"); }); @@ -477,7 +427,6 @@ describe("proxy option", () => { beforeAll(async () => { const compiler = webpack(config); - server = new Server( { proxy: [ @@ -494,17 +443,12 @@ describe("proxy option", () => { }, compiler, ); - await server.start(); - const proxy = express(); - proxy.get("*slug", (proxyReq, res) => { res.send("from proxy"); }); - listener = proxy.listen(port1); - req = request(server.app); }); @@ -519,14 +463,12 @@ describe("proxy option", () => { it("respects proxy1 option", async () => { const response = await req.get("/proxy1"); - expect(response.status).toBe(200); expect(response.text).toContain("from proxy"); }); it("respects proxy2 option", async () => { const response = await req.get("/proxy2"); - expect(response.status).toBe(200); expect(response.text).toContain("from proxy"); }); @@ -537,15 +479,12 @@ describe("proxy option", () => { let server; let webSocketServer; let responseMessage; - const webSocketServerTypes = ["ws"]; - for (const webSocketServerType of webSocketServerTypes) { // eslint-disable-next-line no-loop-func describe(`with webSocketServerType: ${webSocketServerType}`, () => { beforeAll(async () => { const compiler = webpack(config); - server = new Server( { webSocketServer: webSocketServerType, @@ -560,10 +499,10 @@ describe("proxy option", () => { }, compiler, ); - await server.start(); - - webSocketServer = new WebSocketServer({ port: port4 }); + webSocketServer = new WebSocketServer({ + port: port4, + }); webSocketServer.on("connection", (connection) => { connection.on("message", (message) => { connection.send(message); @@ -573,12 +512,10 @@ describe("proxy option", () => { beforeEach((done) => { ws = new WebSocket(`ws://localhost:${port3}/proxy3/socket`); - ws.on("message", (message) => { responseMessage = message.toString(); done(); }); - ws.on("open", () => { ws.send("foo"); }); @@ -586,11 +523,9 @@ describe("proxy option", () => { afterAll(async () => { webSocketServer.close(); - for (const client of webSocketServer.clients) { client.terminate(); } - await server.stop(); }); @@ -608,7 +543,6 @@ describe("proxy option", () => { beforeAll(async () => { const compiler = webpack(config); - server = new Server( { proxy: [ @@ -621,13 +555,15 @@ describe("proxy option", () => { }, compiler, ); - await server.start(); - const proxy = express(); // Parse application/x-www-form-urlencoded - proxy.use(express.urlencoded({ extended: false })); + proxy.use( + express.urlencoded({ + extended: false, + }), + ); // Parse application/json proxy.use(express.json()); @@ -644,38 +580,31 @@ describe("proxy option", () => { res.status(500); res.send("error from proxy"); }); - proxy.get("/get", (proxyReq, res) => { res.send("GET method from proxy"); }); - proxy.head("/head", (proxyReq, res) => { res.send("HEAD method from proxy"); }); - proxy.post("/post-x-www-form-urlencoded", (proxyReq, res) => { const { id } = proxyReq.body; - res.status(200).send(`POST method from proxy (id: ${id})`); }); - proxy.post("/post-application-json", (proxyReq, res) => { const { id } = proxyReq.body; - - res.status(200).send({ answer: `POST method from proxy (id: ${id})` }); + res.status(200).send({ + answer: `POST method from proxy (id: ${id})`, + }); }); - proxy.delete("/delete", (proxyReq, res) => { res.send("DELETE method from proxy"); }); - listener = proxy.listen(port1); req = request(server.app); }); afterAll(async () => { await server.stop(); - await new Promise((resolve) => { listener.close(() => { resolve(); @@ -685,21 +614,18 @@ describe("proxy option", () => { it("errors", async () => { const response = await req.get("/%"); - expect(response.status).toBe(500); expect(response.text).toContain("error from proxy"); }); it("gET method", async () => { const response = await req.get("/get"); - expect(response.status).toBe(200); expect(response.text).toContain("GET method from proxy"); }); it("hEAD method", async () => { const response = await req.head("/head"); - expect(response.status).toBe(200); }); @@ -707,7 +633,6 @@ describe("proxy option", () => { const response = await req .post("/post-x-www-form-urlencoded") .send("id=1"); - expect(response.status).toBe(200); expect(response.text).toContain("POST method from proxy (id: 1)"); }); @@ -715,9 +640,10 @@ describe("proxy option", () => { it("pOST method (application/json)", async () => { const response = await req .post("/post-application-json") - .send({ id: "1" }) + .send({ + id: "1", + }) .set("Accept", "application/json"); - expect(response.status).toBe(200); expect(response.headers["content-type"]).toBe( "application/json; charset=utf-8", @@ -727,7 +653,6 @@ describe("proxy option", () => { it("dELETE method", async () => { const response = await req.delete("/delete"); - expect(response.status).toBe(200); expect(response.text).toContain("DELETE method from proxy"); }); @@ -739,7 +664,6 @@ describe("proxy option", () => { beforeAll(async () => { const compiler = webpack([config, config]); - server = new Server( { proxy: [ @@ -752,11 +676,8 @@ describe("proxy option", () => { }, compiler, ); - await server.start(); - await listenProxyServers(); - req = request(server.app); }); @@ -767,7 +688,6 @@ describe("proxy option", () => { it("respects a proxy option", async () => { const response = await req.get("/proxy1"); - expect(response.status).toBe(200); expect(response.text).toContain("from proxy1"); }); @@ -780,9 +700,7 @@ describe("proxy option", () => { beforeAll(async () => { consoleSpy = jest.spyOn(console, "error").mockImplementation(() => {}); - const compiler = webpack([config, config]); - server = new Server( { proxy: [ @@ -796,11 +714,8 @@ describe("proxy option", () => { }, compiler, ); - await server.start(); - await listenProxyServers(); - req = request(server.app); }); @@ -813,7 +728,6 @@ describe("proxy option", () => { describe("target", () => { it("respects a proxy option when a request path is matched", async () => { await req.get("/my-path"); - expect(getConsoleErrorOutput(consoleSpy)).toMatchSnapshot(); }); }); @@ -828,12 +742,13 @@ describe("proxy option", () => { stderrSpy = jest .spyOn(process.stderr, "write") .mockImplementation(() => true); - const compiler = webpack({ ...config, - infrastructureLogging: { colors: false, level: "error" }, + infrastructureLogging: { + colors: false, + level: "error", + }, }); - server = new Server( { proxy: [ @@ -846,11 +761,8 @@ describe("proxy option", () => { }, compiler, ); - await server.start(); - await listenProxyServers(); - req = request(server.app); }); @@ -863,7 +775,6 @@ describe("proxy option", () => { describe("target", () => { it("respects a proxy option when a request path is matched", async () => { await req.get("/my-path"); - expect(getStderrOutput(stderrSpy)).toMatchSnapshot(); }); }); @@ -878,12 +789,12 @@ describe("proxy option", () => { stderrSpy = jest .spyOn(process.stderr, "write") .mockImplementation(() => true); - const compiler = webpack({ ...config, - infrastructureLogging: { level: "none" }, + infrastructureLogging: { + level: "none", + }, }); - server = new Server( { proxy: [ @@ -896,9 +807,7 @@ describe("proxy option", () => { }, compiler, ); - await server.start(); - req = request(server.app); }); @@ -910,7 +819,6 @@ describe("proxy option", () => { describe("target", () => { it("respects a proxy option when a request path is matched", async () => { await req.get("/my-path"); - expect(getStderrOutput(stderrSpy)).toMatchSnapshot(); }); }); diff --git a/test/validate-options.test.js b/test/validate-options.test.js index da416cee23..fa45e04c14 100644 --- a/test/validate-options.test.js +++ b/test/validate-options.test.js @@ -1,21 +1,31 @@ -"use strict"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import connect from "connect"; +import gracefulFs from "graceful-fs"; -const os = require("node:os"); -const path = require("node:path"); -const { readFileSync } = require("graceful-fs"); -const { Volume, createFsFromVolume } = require("memfs"); -const webpack = require("webpack"); -const Server = require("../lib/Server"); -const config = require("./fixtures/simple-config/webpack.config"); +import { Volume, createFsFromVolume } from "memfs"; +import webpack from "webpack"; +import Server from "../lib/Server.js"; +import config from "./fixtures/simple-config/webpack.config.js"; +const { readFileSync } = gracefulFs; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); const httpsCertificateDirectory = path.join( __dirname, "./fixtures/https-certificate", ); - const tests = { bonjour: { - success: [false, true, { type: "https" }], + success: [ + false, + true, + { + type: "https", + }, + ], failure: [""], }, client: { @@ -74,19 +84,29 @@ const tests = { webSocketURL: "ws://localhost:8080", }, { - webSocketURL: { hostname: "localhost" }, + webSocketURL: { + hostname: "localhost", + }, }, { - webSocketURL: { port: 8080 }, + webSocketURL: { + port: 8080, + }, }, { - webSocketURL: { port: "8080" }, + webSocketURL: { + port: "8080", + }, }, { - webSocketURL: { pathname: "" }, + webSocketURL: { + pathname: "", + }, }, { - webSocketURL: { pathname: "/my-path/" }, + webSocketURL: { + pathname: "/my-path/", + }, }, { webSocketURL: { @@ -96,7 +116,10 @@ const tests = { }, }, { - webSocketURL: { username: "username", password: "password" }, + webSocketURL: { + username: "username", + password: "password", + }, }, ], failure: [ @@ -138,22 +161,37 @@ const tests = { webSocketTransport: true, }, { - webSocketURL: { hostname: true, pathname: "", port: 8080 }, + webSocketURL: { + hostname: true, + pathname: "", + port: 8080, + }, }, { - webSocketURL: { pathname: true }, + webSocketURL: { + pathname: true, + }, }, { - webSocketURL: { port: true }, + webSocketURL: { + port: true, + }, }, { - webSocketURL: { hostname: "" }, + webSocketURL: { + hostname: "", + }, }, { - webSocketURL: { port: "" }, + webSocketURL: { + port: "", + }, }, { - webSocketURL: { username: 123, password: 976 }, + webSocketURL: { + username: 123, + password: 976, + }, }, ], }, @@ -170,8 +208,29 @@ const tests = { failure: [true, false, 123, [], [""]], }, headers: { - success: [{}, { foo: "bar" }, () => {}, [{ key: "foo", value: "bar" }]], - failure: [false, 1, [], [{ foo: "bar" }]], + success: [ + {}, + { + foo: "bar", + }, + () => {}, + [ + { + key: "foo", + value: "bar", + }, + ], + ], + failure: [ + false, + 1, + [], + [ + { + foo: "bar", + }, + ], + ], }, historyApiFallback: { success: [{}, true], @@ -203,22 +262,77 @@ const tests = { "foo", [], ["foo", "bar"], - [{ app: "google-chrome" }], - [{ app: "google-chrome" }, { app: "firefox" }], - [{ target: "foo", app: "google-chrome" }, { app: "firefox" }], - [{ target: ["foo", "bar"], app: "google-chrome" }, { app: "firefox" }], - { target: "foo" }, - { target: ["foo", "bar"] }, - { app: "google-chrome" }, - { app: { name: "google-chrome", arguments: ["--incognito"] } }, - { target: "foo", app: "google-chrome" }, + [ + { + app: "google-chrome", + }, + ], + [ + { + app: "google-chrome", + }, + { + app: "firefox", + }, + ], + [ + { + target: "foo", + app: "google-chrome", + }, + { + app: "firefox", + }, + ], + [ + { + target: ["foo", "bar"], + app: "google-chrome", + }, + { + app: "firefox", + }, + ], + { + target: "foo", + }, { target: ["foo", "bar"], - app: { name: "google-chrome", arguments: ["--incognito"] }, + }, + { + app: "google-chrome", + }, + { + app: { + name: "google-chrome", + arguments: ["--incognito"], + }, + }, + { + target: "foo", + app: "google-chrome", + }, + { + target: ["foo", "bar"], + app: { + name: "google-chrome", + arguments: ["--incognito"], + }, }, {}, ], - failure: ["", { foo: "bar" }, { target: 90 }, { app: true }], + failure: [ + "", + { + foo: "bar", + }, + { + target: 90, + }, + { + app: true, + }, + ], }, port: { success: ["20000", 20001, "auto", 0, 1, 65535], @@ -432,10 +546,10 @@ const tests = { }, app: { success: [ - () => require("connect")(), + () => connect(), async () => new Promise((resolve) => { - resolve(require("connect")()); + resolve(connect()); }), ], failure: ["test", false], @@ -530,9 +644,21 @@ const tests = { success: [ "dir", ["one-dir", "two-dir"], - { paths: ["dir"] }, - { paths: ["dir"], options: { usePolling: true } }, - [{ paths: ["one-dir"] }, "two-dir"], + { + paths: ["dir"], + }, + { + paths: ["dir"], + options: { + usePolling: true, + }, + }, + [ + { + paths: ["one-dir"], + }, + "two-dir", + ], ], failure: [ false, @@ -572,7 +698,6 @@ describe("options", () => { ) { return ""; } - if (typeof replacedValue === "string") { replacedValue = replacedValue .replaceAll("\\", "/") @@ -581,30 +706,26 @@ describe("options", () => { "", ); } - return replacedValue; }); } - return value; } - function createTestCase(type, key, value) { - it(`should ${ - type === "success" ? "successfully validate" : "throw an error on" - } the "${key}" option with '${stringifyValue( - value, - )}' value`, async () => { + it(`should ${type === "success" ? "successfully validate" : "throw an error on"} the "${key}" option with '${stringifyValue(value)}' value`, async () => { const compiler = webpack(config); let thrownError; - try { // eslint-disable-next-line no-new - new Server({ [key]: value }, compiler); + new Server( + { + [key]: value, + }, + compiler, + ); } catch (error) { thrownError = error; } - if (type === "success") { expect(thrownError).toBeUndefined(); } else { @@ -613,13 +734,11 @@ describe("options", () => { } }); } - const memfs = createFsFromVolume(new Volume()); // We need to patch memfs // https://github.com/webpack/webpack-dev-middleware#fs memfs.join = path.join; - for (const [key, values] of Object.entries(tests)) { for (const type of Object.keys(values)) { for (const value of values[type]) { From 425008b2eb7c73f9f9a0cee7e33467843fd8b1ce Mon Sep 17 00:00:00 2001 From: Sebastian Beltran Date: Sat, 2 May 2026 12:39:03 -0500 Subject: [PATCH 4/4] fixup! --- test/e2e/bonjour.test.js | 57 ++++++++++++++-------------------------- 1 file changed, 19 insertions(+), 38 deletions(-) diff --git a/test/e2e/bonjour.test.js b/test/e2e/bonjour.test.js index 297865299c..38059e10e2 100644 --- a/test/e2e/bonjour.test.js +++ b/test/e2e/bonjour.test.js @@ -1,23 +1,32 @@ import os from "node:os"; import webpack from "webpack"; -import Server from "../../lib/Server.js"; import config from "../fixtures/simple-config/webpack.config.js"; import runBrowser from "../helpers/run-browser.js"; import _ports_map from "../ports-map.js"; const port = _ports_map.bonjour; -describe("bonjour option", () => { - let mockPublish; - let mockUnpublishAll; - let mockDestroy; +const mockPublish = jest.fn(); +const mockUnpublishAll = jest.fn((callback) => { + callback(); +}); +const mockDestroy = jest.fn(); + +jest.unstable_mockModule("bonjour-service", () => ({ + Bonjour: jest.fn().mockImplementation(() => ({ + publish: mockPublish, + unpublishAll: mockUnpublishAll, + destroy: mockDestroy, + })), +})); +const { default: Server } = await import("../../lib/Server.js"); + +describe("bonjour option", () => { beforeEach(() => { - mockPublish = jest.fn(); - mockUnpublishAll = jest.fn((callback) => { - callback(); - }); - mockDestroy = jest.fn(); + mockPublish.mockClear(); + mockUnpublishAll.mockClear(); + mockDestroy.mockClear(); }); describe("as true", () => { @@ -29,13 +38,6 @@ describe("bonjour option", () => { let consoleMessages; beforeEach(async () => { - jest.mock("bonjour-service", () => ({ - Bonjour: jest.fn().mockImplementation(() => ({ - publish: mockPublish, - unpublishAll: mockUnpublishAll, - destroy: mockDestroy, - })), - })); compiler = webpack(config); server = new Server( { @@ -95,13 +97,6 @@ describe("bonjour option", () => { let consoleMessages; beforeEach(async () => { - jest.mock("bonjour-service", () => ({ - Bonjour: jest.fn().mockImplementation(() => ({ - publish: mockPublish, - unpublishAll: mockUnpublishAll, - destroy: mockDestroy, - })), - })); compiler = webpack(config); server = new Server( { @@ -159,13 +154,6 @@ describe("bonjour option", () => { let consoleMessages; beforeEach(async () => { - jest.mock("bonjour-service", () => ({ - Bonjour: jest.fn().mockImplementation(() => ({ - publish: mockPublish, - unpublishAll: mockUnpublishAll, - destroy: mockDestroy, - })), - })); compiler = webpack(config); server = new Server( { @@ -226,13 +214,6 @@ describe("bonjour option", () => { let consoleMessages; beforeEach(async () => { - jest.mock("bonjour-service", () => ({ - Bonjour: jest.fn().mockImplementation(() => ({ - publish: mockPublish, - unpublishAll: mockUnpublishAll, - destroy: mockDestroy, - })), - })); compiler = webpack(config); server = new Server( {