From 4658fde69731538bf9a822363777a05aac4c347c Mon Sep 17 00:00:00 2001 From: Malcolm Kee Date: Fri, 5 May 2023 22:51:39 +1000 Subject: [PATCH 1/6] feat: allow filter overlay message with function --- client-src/index.js | 69 +++- client-src/overlay.js | 44 ++- client-src/overlay/state-machine.js | 5 + examples/client/overlay/app.js | 10 +- examples/client/overlay/error-button.js | 22 +- examples/client/overlay/webpack.config.js | 21 +- lib/Server.js | 30 +- lib/options.json | 54 ++- .../validate-options.test.js.snap.webpack5 | 28 +- types/lib/Server.d.ts | 335 +++++++++++------- 10 files changed, 432 insertions(+), 186 deletions(-) diff --git a/client-src/index.js b/client-src/index.js index 4689552d9e..3a948884b5 100644 --- a/client-src/index.js +++ b/client-src/index.js @@ -10,12 +10,20 @@ import sendMessage from "./utils/sendMessage.js"; import reloadApp from "./utils/reloadApp.js"; import createSocketURL from "./utils/createSocketURL.js"; +/** + * @typedef {Object} OverlayOptions + * @property {boolean | (error: Error) => boolean} [warnings] + * @property {boolean | (error: Error) => boolean} [errors] + * @property {boolean | (error: Error) => boolean} [runtimeErrors] + * @property {string} [trustedTypesPolicyName] + */ + /** * @typedef {Object} Options * @property {boolean} hot * @property {boolean} liveReload * @property {boolean} progress - * @property {boolean | { warnings?: boolean, errors?: boolean, runtimeErrors?: boolean, trustedTypesPolicyName?: string }} overlay + * @property {boolean | OverlayOptions} overlay * @property {string} [logging] * @property {number} [reconnect] */ @@ -83,6 +91,23 @@ if (parsedResourceQuery.overlay) { runtimeErrors: true, ...options.overlay, }; + + ["errors", "warnings", "runtimeErrors"].forEach((property) => { + if (typeof options.overlay[property] === "string") { + const overlayFilterFunctionString = decodeURIComponent( + options.overlay[property] + ); + + // eslint-disable-next-line no-new-func + const overlayFilterFunction = new Function( + "message", + `var callback = ${overlayFilterFunctionString} + return callback(message)` + ); + + options.overlay[property] = overlayFilterFunction; + } + }); } enabledFeatures.Overlay = true; } @@ -266,17 +291,24 @@ const onSocketMessage = { log.warn(printableWarnings[i]); } - const needShowOverlayForWarnings = + const overlayWarningsSetting = typeof options.overlay === "boolean" ? options.overlay : options.overlay && options.overlay.warnings; - if (needShowOverlayForWarnings) { - overlay.send({ - type: "BUILD_ERROR", - level: "warning", - messages: warnings, - }); + if (overlayWarningsSetting) { + const warningsToDisplay = + typeof overlayWarningsSetting === "function" + ? warnings.filter(overlayWarningsSetting) + : warnings; + + if (warningsToDisplay.length) { + overlay.send({ + type: "BUILD_ERROR", + level: "warning", + messages: warnings, + }); + } } if (params && params.preventReloading) { @@ -303,17 +335,24 @@ const onSocketMessage = { log.error(printableErrors[i]); } - const needShowOverlayForErrors = + const overlayErrorsSettings = typeof options.overlay === "boolean" ? options.overlay : options.overlay && options.overlay.errors; - if (needShowOverlayForErrors) { - overlay.send({ - type: "BUILD_ERROR", - level: "error", - messages: errors, - }); + if (overlayErrorsSettings) { + const errorsToDisplay = + typeof overlayErrorsSettings === "function" + ? errors.filter(overlayErrorsSettings) + : errors; + + if (errorsToDisplay.length) { + overlay.send({ + type: "BUILD_ERROR", + level: "error", + messages: errors, + }); + } } }, /** diff --git a/client-src/overlay.js b/client-src/overlay.js index 2887c28ad3..210b4996d1 100644 --- a/client-src/overlay.js +++ b/client-src/overlay.js @@ -78,7 +78,7 @@ function formatProblem(type, item) { /** * @typedef {Object} CreateOverlayOptions * @property {string | null} trustedTypesPolicyName - * @property {boolean} [catchRuntimeError] + * @property {boolean | (error: Error) => void} [catchRuntimeError] */ /** @@ -90,6 +90,8 @@ const createOverlay = (options) => { let iframeContainerElement; /** @type {HTMLDivElement | null | undefined} */ let containerElement; + /** @type {HTMLDivElement | null | undefined} */ + let headerElement; /** @type {Array<(element: HTMLDivElement) => void>} */ let onLoadQueue = []; /** @type {TrustedTypePolicy | undefined} */ @@ -124,6 +126,7 @@ const createOverlay = (options) => { iframeContainerElement.id = "webpack-dev-server-client-overlay"; iframeContainerElement.src = "about:blank"; applyStyle(iframeContainerElement, iframeStyle); + iframeContainerElement.onload = () => { const contentElement = /** @type {Document} */ @@ -141,7 +144,7 @@ const createOverlay = (options) => { contentElement.id = "webpack-dev-server-client-overlay-div"; applyStyle(contentElement, containerStyle); - const headerElement = document.createElement("div"); + headerElement = document.createElement("div"); headerElement.innerText = "Compiled with problems:"; applyStyle(headerElement, headerStyle); @@ -219,9 +222,15 @@ const createOverlay = (options) => { * @param {string} type * @param {Array} messages * @param {string | null} trustedTypesPolicyName + * @param {'build' | 'runtime'} messageSource */ - function show(type, messages, trustedTypesPolicyName) { + function show(type, messages, trustedTypesPolicyName, messageSource) { ensureOverlayExists(() => { + headerElement.innerText = + messageSource === "runtime" + ? "Uncaught runtime errors:" + : "Compiled with problems:"; + messages.forEach((message) => { const entryElement = document.createElement("div"); const msgStyle = @@ -267,8 +276,8 @@ const createOverlay = (options) => { } const overlayService = createOverlayMachine({ - showOverlay: ({ level = "error", messages }) => - show(level, messages, options.trustedTypesPolicyName), + showOverlay: ({ level = "error", messages, messageSource }) => + show(level, messages, options.trustedTypesPolicyName, messageSource), hideOverlay: hide, }); @@ -284,15 +293,22 @@ const createOverlay = (options) => { const errorObject = error instanceof Error ? error : new Error(error || message); - overlayService.send({ - type: "RUNTIME_ERROR", - messages: [ - { - message: errorObject.message, - stack: parseErrorToStacks(errorObject), - }, - ], - }); + const shouldDisplay = + typeof options.catchRuntimeError === "function" + ? options.catchRuntimeError(errorObject) + : true; + + if (shouldDisplay) { + overlayService.send({ + type: "RUNTIME_ERROR", + messages: [ + { + message: errorObject.message, + stack: parseErrorToStacks(errorObject), + }, + ], + }); + } }); } diff --git a/client-src/overlay/state-machine.js b/client-src/overlay/state-machine.js index d9ed764198..4c0444383c 100644 --- a/client-src/overlay/state-machine.js +++ b/client-src/overlay/state-machine.js @@ -4,6 +4,7 @@ import createMachine from "./fsm.js"; * @typedef {Object} ShowOverlayData * @property {'warning' | 'error'} level * @property {Array} messages + * @property {'build' | 'runtime'} messageSource */ /** @@ -23,6 +24,7 @@ const createOverlayMachine = (options) => { context: { level: "error", messages: [], + messageSource: "build", }, states: { hidden: { @@ -73,18 +75,21 @@ const createOverlayMachine = (options) => { return { messages: [], level: "error", + messageSource: "build", }; }, appendMessages: (context, event) => { return { messages: context.messages.concat(event.messages), level: event.level || context.level, + messageSource: event.type === "RUNTIME_ERROR" ? "runtime" : "build", }; }, setMessages: (context, event) => { return { messages: event.messages, level: event.level || context.level, + messageSource: event.type === "RUNTIME_ERROR" ? "runtime" : "build", }; }, hideOverlay, diff --git a/examples/client/overlay/app.js b/examples/client/overlay/app.js index a4344aa340..5885cfaf68 100644 --- a/examples/client/overlay/app.js +++ b/examples/client/overlay/app.js @@ -5,7 +5,15 @@ const createErrorBtn = require("./error-button"); const target = document.querySelector("#target"); -target.insertAdjacentElement("afterend", createErrorBtn()); +target.insertAdjacentElement( + "afterend", + createErrorBtn("Click to throw error", "Error message thrown from JS") +); + +target.insertAdjacentElement( + "afterend", + createErrorBtn("Click to throw ignored error", "something something") +); // eslint-disable-next-line import/no-unresolved, import/extensions const invalid = require("./invalid.js"); diff --git a/examples/client/overlay/error-button.js b/examples/client/overlay/error-button.js index 11fe606af0..2f0b87351e 100644 --- a/examples/client/overlay/error-button.js +++ b/examples/client/overlay/error-button.js @@ -1,18 +1,24 @@ "use strict"; -function unsafeOperation() { - throw new Error("Error message thrown from JS"); -} +/** + * + * @param {string} label + * @param {string} errorMessage + * @returns HTMLButtonElement + */ +module.exports = function createErrorButton(label, errorMessage) { + function unsafeOperation() { + throw new Error(errorMessage); + } -function handleButtonClick() { - unsafeOperation(); -} + function handleButtonClick() { + unsafeOperation(); + } -module.exports = function createErrorButton() { const errorBtn = document.createElement("button"); errorBtn.addEventListener("click", handleButtonClick); - errorBtn.innerHTML = "Click to throw error"; + errorBtn.innerHTML = label; return errorBtn; }; diff --git a/examples/client/overlay/webpack.config.js b/examples/client/overlay/webpack.config.js index 41d8ad543b..a2413a2434 100644 --- a/examples/client/overlay/webpack.config.js +++ b/examples/client/overlay/webpack.config.js @@ -10,7 +10,26 @@ module.exports = setup({ entry: "./app.js", devServer: { client: { - overlay: true, + overlay: { + warnings: false, + runtimeErrors: (msg) => { + if (msg) { + let msgString; + + if (msg instanceof Error) { + msgString = msg.message; + } else if (typeof msg === "string") { + msgString = msg; + } + + if (msgString) { + return !/something/i.test(msgString); + } + } + + return true; + }, + }, }, }, // uncomment to test for IE diff --git a/lib/Server.js b/lib/Server.js index ec3453b6f2..03deff124e 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -154,10 +154,14 @@ const schema = require("./options.json"); * @property {string} [username] */ +/** + * @typedef {boolean | ((error: Error) => void)} OverlayMessageOptions + */ + /** * @typedef {Object} ClientConfiguration * @property {"log" | "info" | "warn" | "error" | "none" | "verbose"} [logging] - * @property {boolean | { warnings?: boolean, errors?: boolean, runtimeErrors?: boolean }} [overlay] + * @property {boolean | { warnings?: OverlayMessageOptions, errors?: OverlayMessageOptions, runtimeErrors?: OverlayMessageOptions }} [overlay] * @property {boolean} [progress] * @property {boolean | number} [reconnect] * @property {"ws" | "sockjs" | string} [webSocketTransport] @@ -654,12 +658,28 @@ class Server { } if (typeof client.overlay !== "undefined") { - searchParams.set( - "overlay", + /** + * + * @param {OverlayMessageOptions} [setting] + * @returns + */ + const encodeOverlaySettings = (setting) => + typeof setting === "function" + ? encodeURIComponent(setting.toString()) + : setting; + + const overlayString = typeof client.overlay === "boolean" ? String(client.overlay) - : JSON.stringify(client.overlay) - ); + : JSON.stringify({ + errors: encodeOverlaySettings(client.overlay.errors), + warnings: encodeOverlaySettings(client.overlay.warnings), + runtimeErrors: encodeOverlaySettings( + client.overlay.runtimeErrors + ), + }); + + searchParams.set("overlay", overlayString); } if (typeof client.reconnect !== "undefined") { diff --git a/lib/options.json b/lib/options.json index 87ac7e1fb3..654a68a580 100644 --- a/lib/options.json +++ b/lib/options.json @@ -98,25 +98,49 @@ "additionalProperties": false, "properties": { "errors": { - "description": "Enables a full-screen overlay in the browser when there are compiler errors.", - "type": "boolean", - "cli": { - "negatedDescription": "Disables the full-screen overlay in the browser when there are compiler errors." - } + "anyOf": [ + { + "description": "Enables a full-screen overlay in the browser when there are compiler errors.", + "type": "boolean", + "cli": { + "negatedDescription": "Disables the full-screen overlay in the browser when there are compiler errors." + } + }, + { + "instanceof": "Function", + "description": "Filter compiler errors. Return true to include and return false to exclude." + } + ] }, "warnings": { - "description": "Enables a full-screen overlay in the browser when there are compiler warnings.", - "type": "boolean", - "cli": { - "negatedDescription": "Disables the full-screen overlay in the browser when there are compiler warnings." - } + "anyOf": [ + { + "description": "Enables a full-screen overlay in the browser when there are compiler warnings.", + "type": "boolean", + "cli": { + "negatedDescription": "Disables the full-screen overlay in the browser when there are compiler warnings." + } + }, + { + "instanceof": "Function", + "description": "Filter compiler warnings. Return true to include and return false to exclude." + } + ] }, "runtimeErrors": { - "description": "Enables a full-screen overlay in the browser when there are uncaught runtime errors.", - "type": "boolean", - "cli": { - "negatedDescription": "Disables the full-screen overlay in the browser when there are uncaught runtime errors." - } + "anyOf": [ + { + "description": "Enables a full-screen overlay in the browser when there are uncaught runtime errors.", + "type": "boolean", + "cli": { + "negatedDescription": "Disables the full-screen overlay in the browser when there are uncaught runtime errors." + } + }, + { + "instanceof": "Function", + "description": "Filter uncaught runtime errors. Return true to include and return false to exclude." + } + ] }, "trustedTypesPolicyName": { "description": "The name of a Trusted Types policy for the overlay. Defaults to 'webpack-dev-server#overlay'.", diff --git a/test/__snapshots__/validate-options.test.js.snap.webpack5 b/test/__snapshots__/validate-options.test.js.snap.webpack5 index 2a5ed5e47d..887634ff91 100644 --- a/test/__snapshots__/validate-options.test.js.snap.webpack5 +++ b/test/__snapshots__/validate-options.test.js.snap.webpack5 @@ -107,14 +107,34 @@ exports[`options validate should throw an error on the "client" option with '{"o exports[`options validate should throw an error on the "client" option with '{"overlay":{"errors":""}}' value 1`] = ` "ValidationError: Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. - - options.client.overlay.errors should be a boolean. - -> Enables a full-screen overlay in the browser when there are compiler errors." + - options.client should be one of these: + false | object { logging?, overlay?, progress?, reconnect?, webSocketTransport?, webSocketURL? } + -> Allows to specify options for client script in the browser or disable client script. + -> Read more at https://webpack.js.org/configuration/dev-server/#devserverclient + Details: + * options.client.overlay.errors should be one of these: + boolean | function + Details: + * options.client.overlay.errors should be a boolean. + -> Enables a full-screen overlay in the browser when there are compiler errors. + * options.client.overlay.errors should be an instance of function. + -> Filter compiler errors. Return true to include and return false to exclude." `; exports[`options validate should throw an error on the "client" option with '{"overlay":{"warnings":""}}' value 1`] = ` "ValidationError: Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. - - options.client.overlay.warnings should be a boolean. - -> Enables a full-screen overlay in the browser when there are compiler warnings." + - options.client should be one of these: + false | object { logging?, overlay?, progress?, reconnect?, webSocketTransport?, webSocketURL? } + -> Allows to specify options for client script in the browser or disable client script. + -> Read more at https://webpack.js.org/configuration/dev-server/#devserverclient + Details: + * options.client.overlay.warnings should be one of these: + boolean | function + Details: + * options.client.overlay.warnings should be a boolean. + -> Enables a full-screen overlay in the browser when there are compiler warnings. + * options.client.overlay.warnings should be an instance of function. + -> Filter compiler warnings. Return true to include and return false to exclude." `; exports[`options validate should throw an error on the "client" option with '{"progress":""}' value 1`] = ` diff --git a/types/lib/Server.d.ts b/types/lib/Server.d.ts index e5ed287917..7361906c51 100644 --- a/types/lib/Server.d.ts +++ b/types/lib/Server.d.ts @@ -139,10 +139,13 @@ declare class Server { * @property {string} [protocol] * @property {string} [username] */ + /** + * @typedef {boolean | ((error: Error) => void)} OverlayMessageOptions + */ /** * @typedef {Object} ClientConfiguration * @property {"log" | "info" | "warn" | "error" | "none" | "verbose"} [logging] - * @property {boolean | { warnings?: boolean, errors?: boolean, runtimeErrors?: boolean }} [overlay] + * @property {boolean | { warnings?: OverlayMessageOptions, errors?: OverlayMessageOptions, runtimeErrors?: OverlayMessageOptions }} [overlay] * @property {boolean} [progress] * @property {boolean | number} [reconnect] * @property {"ws" | "sockjs" | string} [webSocketTransport] @@ -294,10 +297,13 @@ declare class Server { * @property {string} [protocol] * @property {string} [username] */ + /** + * @typedef {boolean | ((error: Error) => void)} OverlayMessageOptions + */ /** * @typedef {Object} ClientConfiguration * @property {"log" | "info" | "warn" | "error" | "none" | "verbose"} [logging] - * @property {boolean | { warnings?: boolean, errors?: boolean, runtimeErrors?: boolean }} [overlay] + * @property {boolean | { warnings?: OverlayMessageOptions, errors?: OverlayMessageOptions, runtimeErrors?: OverlayMessageOptions }} [overlay] * @property {boolean} [progress] * @property {boolean | number} [reconnect] * @property {"ws" | "sockjs" | string} [webSocketTransport] @@ -454,10 +460,13 @@ declare class Server { * @property {string} [protocol] * @property {string} [username] */ + /** + * @typedef {boolean | ((error: Error) => void)} OverlayMessageOptions + */ /** * @typedef {Object} ClientConfiguration * @property {"log" | "info" | "warn" | "error" | "none" | "verbose"} [logging] - * @property {boolean | { warnings?: boolean, errors?: boolean, runtimeErrors?: boolean }} [overlay] + * @property {boolean | { warnings?: OverlayMessageOptions, errors?: OverlayMessageOptions, runtimeErrors?: OverlayMessageOptions }} [overlay] * @property {boolean} [progress] * @property {boolean | number} [reconnect] * @property {"ws" | "sockjs" | string} [webSocketTransport] @@ -550,9 +559,6 @@ declare class Server { simpleType: string; multiple: boolean; }; - /** - * @typedef {Array<{ key: string; value: string }> | Record} Headers - */ "client-reconnect": { configs: ( | { @@ -613,7 +619,7 @@ declare class Server { }[]; description: string; simpleType: string; - multiple: boolean; + /** @type {T} */ multiple: boolean; }; "client-web-socket-url-password": { configs: { @@ -648,20 +654,12 @@ declare class Server { simpleType: string; multiple: boolean; }; - /** - * @private - * @type {RequestHandler[]} - */ "client-web-socket-url-protocol": { configs: ( | { description: string; multiple: boolean; path: string; - /** - * @private - * @type {string | undefined} - */ type: string; values: string[]; } @@ -809,15 +807,16 @@ declare class Server { simpleType: string; multiple: boolean; }; - /** - * @type {string[]} - */ "https-cacert-reset": { + /** + * @private + * @param {Compiler} compiler + */ configs: { description: string; multiple: boolean; path: string; - /** @type {WebSocketURL} */ type: string; + type: string; }[]; description: string; multiple: boolean; @@ -898,7 +897,7 @@ declare class Server { }[]; description: string; simpleType: string; - multiple: boolean; + /** @type {ClientConfiguration} */ multiple: boolean; }; "https-pfx": { configs: { @@ -947,12 +946,6 @@ declare class Server { values: boolean[]; multiple: boolean; description: string; - /** - * prependEntry Method for webpack 4 - * @param {any} originalEntry - * @param {any} newAdditionalEntries - * @returns {any} - */ path: string; } )[]; @@ -995,6 +988,7 @@ declare class Server { | { type: string; multiple: boolean; + /** @type {any} */ description: string; negatedDescription: string; path: string; @@ -1012,7 +1006,7 @@ declare class Server { path: string; }[]; description: string; - simpleType: string; + /** @type {MultiCompiler} */ simpleType: string; multiple: boolean; }; "open-app-name": { @@ -1253,7 +1247,7 @@ declare class Server { type: string; values: string[]; }[]; - /** @type {ServerConfiguration} */ description: string; + description: string; multiple: boolean; simpleType: string; }; @@ -1267,7 +1261,7 @@ declare class Server { } | { type: string; - multiple: boolean; + /** @type {ServerConfiguration} */ multiple: boolean; description: string; negatedDescription: string; path: string; @@ -1286,14 +1280,14 @@ declare class Server { }[]; description: string; simpleType: string; - multiple: boolean; + multiple: boolean /** @type {ServerOptions} */; }; "static-public-path": { configs: { type: string; multiple: boolean; - description: string; - path: string /** @type {any} */; + /** @type {ServerOptions} */ description: string; + path: string; }[]; description: string; simpleType: string; @@ -1610,10 +1604,13 @@ declare class Server { * @property {string} [protocol] * @property {string} [username] */ + /** + * @typedef {boolean | ((error: Error) => void)} OverlayMessageOptions + */ /** * @typedef {Object} ClientConfiguration * @property {"log" | "info" | "warn" | "error" | "none" | "verbose"} [logging] - * @property {boolean | { warnings?: boolean, errors?: boolean, runtimeErrors?: boolean }} [overlay] + * @property {boolean | { warnings?: OverlayMessageOptions, errors?: OverlayMessageOptions, runtimeErrors?: OverlayMessageOptions }} [overlay] * @property {boolean} [progress] * @property {boolean | number} [reconnect] * @property {"ws" | "sockjs" | string} [webSocketTransport] @@ -1759,10 +1756,13 @@ declare class Server { * @property {string} [protocol] * @property {string} [username] */ + /** + * @typedef {boolean | ((error: Error) => void)} OverlayMessageOptions + */ /** * @typedef {Object} ClientConfiguration * @property {"log" | "info" | "warn" | "error" | "none" | "verbose"} [logging] - * @property {boolean | { warnings?: boolean, errors?: boolean, runtimeErrors?: boolean }} [overlay] + * @property {boolean | { warnings?: OverlayMessageOptions, errors?: OverlayMessageOptions, runtimeErrors?: OverlayMessageOptions }} [overlay] * @property {boolean} [progress] * @property {boolean | number} [reconnect] * @property {"ws" | "sockjs" | string} [webSocketTransport] @@ -1824,25 +1824,158 @@ declare class Server { additionalProperties: boolean; properties: { errors: { - description: string; - type: string; - cli: { - negatedDescription: string; - }; + anyOf: ( + | { + description: string; + type: string; + cli: { + negatedDescription: string; + }; + instanceof?: undefined; + } + | { + instanceof: string; + /** + * @typedef {Object} WebSocketServerConfiguration + * @property {"sockjs" | "ws" | string | Function} [type] + * @property {Record} [options] + */ + /** + * @typedef {(import("ws").WebSocket | import("sockjs").Connection & { send: import("ws").WebSocket["send"], terminate: import("ws").WebSocket["terminate"], ping: import("ws").WebSocket["ping"] }) & { isAlive?: boolean }} ClientConnection + */ + /** + * @typedef {import("ws").WebSocketServer | import("sockjs").Server & { close: import("ws").WebSocketServer["close"] }} WebSocketServer + */ + /** + * @typedef {{ implementation: WebSocketServer, clients: ClientConnection[] }} WebSocketServerImplementation + */ + /** + * @callback ByPass + * @param {Request} req + * @param {Response} res + * @param {ProxyConfigArrayItem} proxyConfig + */ + /** + * @typedef {{ path?: HttpProxyMiddlewareOptionsFilter | undefined, context?: HttpProxyMiddlewareOptionsFilter | undefined } & { bypass?: ByPass } & HttpProxyMiddlewareOptions } ProxyConfigArrayItem + */ + /** + * @typedef {(ProxyConfigArrayItem | ((req?: Request | undefined, res?: Response | undefined, next?: NextFunction | undefined) => ProxyConfigArrayItem))[]} ProxyConfigArray + */ + /** + * @typedef {{ [url: string]: string | ProxyConfigArrayItem }} ProxyConfigMap + */ + /** + * @typedef {Object} OpenApp + * @property {string} [name] + * @property {string[]} [arguments] + */ + /** + * @typedef {Object} Open + * @property {string | string[] | OpenApp} [app] + * @property {string | string[]} [target] + */ + /** + * @typedef {Object} NormalizedOpen + * @property {string} target + * @property {import("open").Options} options + */ + /** + * @typedef {Object} WebSocketURL + * @property {string} [hostname] + * @property {string} [password] + * @property {string} [pathname] + * @property {number | string} [port] + * @property {string} [protocol] + * @property {string} [username] + */ + /** + * @typedef {boolean | ((error: Error) => void)} OverlayMessageOptions + */ + /** + * @typedef {Object} ClientConfiguration + * @property {"log" | "info" | "warn" | "error" | "none" | "verbose"} [logging] + * @property {boolean | { warnings?: OverlayMessageOptions, errors?: OverlayMessageOptions, runtimeErrors?: OverlayMessageOptions }} [overlay] + * @property {boolean} [progress] + * @property {boolean | number} [reconnect] + * @property {"ws" | "sockjs" | string} [webSocketTransport] + * @property {string | WebSocketURL} [webSocketURL] + */ + /** + * @typedef {Array<{ key: string; value: string }> | Record} Headers + */ + /** + * @typedef {{ name?: string, path?: string, middleware: ExpressRequestHandler | ExpressErrorRequestHandler } | ExpressRequestHandler | ExpressErrorRequestHandler} Middleware + */ + /** + * @typedef {Object} Configuration + * @property {boolean | string} [ipc] + * @property {Host} [host] + * @property {Port} [port] + * @property {boolean | "only"} [hot] + * @property {boolean} [liveReload] + * @property {DevMiddlewareOptions} [devMiddleware] + * @property {boolean} [compress] + * @property {boolean} [magicHtml] + * @property {"auto" | "all" | string | string[]} [allowedHosts] + * @property {boolean | ConnectHistoryApiFallbackOptions} [historyApiFallback] + * @property {boolean | Record | BonjourOptions} [bonjour] + * @property {string | string[] | WatchFiles | Array} [watchFiles] + * @property {boolean | string | Static | Array} [static] + * @property {boolean | ServerOptions} [https] + * @property {boolean} [http2] + * @property {"http" | "https" | "spdy" | string | ServerConfiguration} [server] + * @property {boolean | "sockjs" | "ws" | string | WebSocketServerConfiguration} [webSocketServer] + * @property {ProxyConfigMap | ProxyConfigArrayItem | ProxyConfigArray} [proxy] + * @property {boolean | string | Open | Array} [open] + * @property {boolean} [setupExitSignals] + * @property {boolean | ClientConfiguration} [client] + * @property {Headers | ((req: Request, res: Response, context: DevMiddlewareContext) => Headers)} [headers] + * @property {(devServer: Server) => void} [onAfterSetupMiddleware] + * @property {(devServer: Server) => void} [onBeforeSetupMiddleware] + * @property {(devServer: Server) => void} [onListening] + * @property {(middlewares: Middleware[], devServer: Server) => Middleware[]} [setupMiddlewares] + */ + description: string; + type?: undefined; + cli?: undefined; + } + )[]; }; warnings: { - description: string; - type: string; - cli: { - negatedDescription: string; - }; + anyOf: ( + | { + description: string; + type: string; + cli: { + negatedDescription: string; + }; + instanceof?: undefined; + } + | { + instanceof: string; + description: string; + type?: undefined; + cli?: undefined; + } + )[]; }; runtimeErrors: { - description: string; - type: string; - cli: { - negatedDescription: string; - }; + anyOf: ( + | { + description: string; + type: string; + cli: { + negatedDescription: string; + }; + instanceof?: undefined; + } + | { + instanceof: string; + description: string; + type?: undefined; + cli?: undefined; + } + )[]; }; trustedTypesPolicyName: { description: string; @@ -1869,69 +2002,6 @@ declare class Server { anyOf: ( | { type: string; - /** - * @typedef {Object} Open - * @property {string | string[] | OpenApp} [app] - * @property {string | string[]} [target] - */ - /** - * @typedef {Object} NormalizedOpen - * @property {string} target - * @property {import("open").Options} options - */ - /** - * @typedef {Object} WebSocketURL - * @property {string} [hostname] - * @property {string} [password] - * @property {string} [pathname] - * @property {number | string} [port] - * @property {string} [protocol] - * @property {string} [username] - */ - /** - * @typedef {Object} ClientConfiguration - * @property {"log" | "info" | "warn" | "error" | "none" | "verbose"} [logging] - * @property {boolean | { warnings?: boolean, errors?: boolean, runtimeErrors?: boolean }} [overlay] - * @property {boolean} [progress] - * @property {boolean | number} [reconnect] - * @property {"ws" | "sockjs" | string} [webSocketTransport] - * @property {string | WebSocketURL} [webSocketURL] - */ - /** - * @typedef {Array<{ key: string; value: string }> | Record} Headers - */ - /** - * @typedef {{ name?: string, path?: string, middleware: ExpressRequestHandler | ExpressErrorRequestHandler } | ExpressRequestHandler | ExpressErrorRequestHandler} Middleware - */ - /** - * @typedef {Object} Configuration - * @property {boolean | string} [ipc] - * @property {Host} [host] - * @property {Port} [port] - * @property {boolean | "only"} [hot] - * @property {boolean} [liveReload] - * @property {DevMiddlewareOptions} [devMiddleware] - * @property {boolean} [compress] - * @property {boolean} [magicHtml] - * @property {"auto" | "all" | string | string[]} [allowedHosts] - * @property {boolean | ConnectHistoryApiFallbackOptions} [historyApiFallback] - * @property {boolean | Record | BonjourOptions} [bonjour] - * @property {string | string[] | WatchFiles | Array} [watchFiles] - * @property {boolean | string | Static | Array} [static] - * @property {boolean | ServerOptions} [https] - * @property {boolean} [http2] - * @property {"http" | "https" | "spdy" | string | ServerConfiguration} [server] - * @property {boolean | "sockjs" | "ws" | string | WebSocketServerConfiguration} [webSocketServer] - * @property {ProxyConfigMap | ProxyConfigArrayItem | ProxyConfigArray} [proxy] - * @property {boolean | string | Open | Array} [open] - * @property {boolean} [setupExitSignals] - * @property {boolean | ClientConfiguration} [client] - * @property {Headers | ((req: Request, res: Response, context: DevMiddlewareContext) => Headers)} [headers] - * @property {(devServer: Server) => void} [onAfterSetupMiddleware] - * @property {(devServer: Server) => void} [onBeforeSetupMiddleware] - * @property {(devServer: Server) => void} [onListening] - * @property {(middlewares: Middleware[], devServer: Server) => Middleware[]} [setupMiddlewares] - */ cli: { negatedDescription: string; }; @@ -2056,6 +2126,10 @@ declare class Server { } | { type: string; + /** + * @private + * @type {{ name: string | symbol, listener: (...args: any[]) => void}[] }} + */ additionalProperties: boolean; properties: { passphrase: { @@ -2395,7 +2469,7 @@ declare class Server { cli: { negatedDescription: string; }; - link: string; + link: string /** @type {number | string} */; }; MagicHTML: { type: string; @@ -2433,7 +2507,7 @@ declare class Server { } | { $ref: string; - /** @type {string} */ type?: undefined; + type?: undefined; items?: undefined; } )[]; @@ -2532,6 +2606,12 @@ declare class Server { | { type: string; minLength: number; + /** + * prependEntry Method for webpack 4 + * @param {any} originalEntry + * @param {any} newAdditionalEntries + * @returns {any} + */ minimum?: undefined; maximum?: undefined; enum?: undefined; @@ -2570,7 +2650,7 @@ declare class Server { } )[]; description: string; - /** @type {Object} */ link: string; + link: string; }; Server: { anyOf: { @@ -2603,11 +2683,12 @@ declare class Server { $ref: string; }[]; }; + /** @type {MultiCompiler} */ options: { $ref: string; }; }; - additionalProperties: boolean; + /** @type {MultiCompiler} */ additionalProperties: boolean; }; ServerOptions: { type: string; @@ -2615,7 +2696,7 @@ declare class Server { properties: { passphrase: { type: string; - description: string; + /** @type {MultiCompiler} */ description: string; }; requestCert: { type: string; @@ -2663,6 +2744,10 @@ declare class Server { anyOf: ( | { type: string; + /** + * @private + * @returns {Promise} + */ instanceof?: undefined; } | { @@ -2684,6 +2769,10 @@ declare class Server { items?: undefined; } )[]; + /** + * @param {WatchOptions & { aggregateTimeout?: number, ignored?: WatchOptions["ignored"], poll?: number | boolean }} watchOptions + * @returns {WatchOptions} + */ description: string; }; cert: { @@ -3051,7 +3140,7 @@ declare class Server { }; }; }; - additionalProperties: boolean; + /** @type {ServerOptions} */ additionalProperties: boolean; }; WebSocketServerString: { type: string; @@ -3059,7 +3148,6 @@ declare class Server { }; }; additionalProperties: boolean; - /** @type {ServerOptions} */ properties: { allowedHosts: { $ref: string; @@ -3121,7 +3209,6 @@ declare class Server { proxy: { $ref: string; }; - /** @type {any} */ server: { $ref: string; }; @@ -3502,6 +3589,7 @@ declare namespace Server { Open, NormalizedOpen, WebSocketURL, + OverlayMessageOptions, ClientConfiguration, Headers, Middleware, @@ -3720,14 +3808,15 @@ type WebSocketURL = { protocol?: string | undefined; username?: string | undefined; }; +type OverlayMessageOptions = boolean | ((error: Error) => void); type ClientConfiguration = { logging?: "none" | "error" | "warn" | "info" | "log" | "verbose" | undefined; overlay?: | boolean | { - warnings?: boolean | undefined; - errors?: boolean | undefined; - runtimeErrors?: boolean | undefined; + warnings?: OverlayMessageOptions | undefined; + errors?: OverlayMessageOptions | undefined; + runtimeErrors?: OverlayMessageOptions | undefined; } | undefined; progress?: boolean | undefined; From 9e634224a5b5a7738ca5cc24bcb63b89fbcf548f Mon Sep 17 00:00:00 2001 From: Malcolm Kee Date: Fri, 5 May 2023 23:13:44 +1000 Subject: [PATCH 2/6] fix: update snapshot --- .../validate-options.test.js.snap.webpack4 | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/test/__snapshots__/validate-options.test.js.snap.webpack4 b/test/__snapshots__/validate-options.test.js.snap.webpack4 index 2a5ed5e47d..887634ff91 100644 --- a/test/__snapshots__/validate-options.test.js.snap.webpack4 +++ b/test/__snapshots__/validate-options.test.js.snap.webpack4 @@ -107,14 +107,34 @@ exports[`options validate should throw an error on the "client" option with '{"o exports[`options validate should throw an error on the "client" option with '{"overlay":{"errors":""}}' value 1`] = ` "ValidationError: Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. - - options.client.overlay.errors should be a boolean. - -> Enables a full-screen overlay in the browser when there are compiler errors." + - options.client should be one of these: + false | object { logging?, overlay?, progress?, reconnect?, webSocketTransport?, webSocketURL? } + -> Allows to specify options for client script in the browser or disable client script. + -> Read more at https://webpack.js.org/configuration/dev-server/#devserverclient + Details: + * options.client.overlay.errors should be one of these: + boolean | function + Details: + * options.client.overlay.errors should be a boolean. + -> Enables a full-screen overlay in the browser when there are compiler errors. + * options.client.overlay.errors should be an instance of function. + -> Filter compiler errors. Return true to include and return false to exclude." `; exports[`options validate should throw an error on the "client" option with '{"overlay":{"warnings":""}}' value 1`] = ` "ValidationError: Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. - - options.client.overlay.warnings should be a boolean. - -> Enables a full-screen overlay in the browser when there are compiler warnings." + - options.client should be one of these: + false | object { logging?, overlay?, progress?, reconnect?, webSocketTransport?, webSocketURL? } + -> Allows to specify options for client script in the browser or disable client script. + -> Read more at https://webpack.js.org/configuration/dev-server/#devserverclient + Details: + * options.client.overlay.warnings should be one of these: + boolean | function + Details: + * options.client.overlay.warnings should be a boolean. + -> Enables a full-screen overlay in the browser when there are compiler warnings. + * options.client.overlay.warnings should be an instance of function. + -> Filter compiler warnings. Return true to include and return false to exclude." `; exports[`options validate should throw an error on the "client" option with '{"progress":""}' value 1`] = ` From 9c6e408344614e3a721be667c4866f74897654e3 Mon Sep 17 00:00:00 2001 From: Malcolm Kee Date: Sat, 6 May 2023 00:45:22 +1000 Subject: [PATCH 3/6] test: add test for overlay runtimeErrors --- .../overlay.test.js.snap.webpack4 | 86 +++++++++++++++++++ .../overlay.test.js.snap.webpack5 | 86 +++++++++++++++++++ test/e2e/overlay.test.js | 75 ++++++++++++++++ 3 files changed, 247 insertions(+) diff --git a/test/e2e/__snapshots__/overlay.test.js.snap.webpack4 b/test/e2e/__snapshots__/overlay.test.js.snap.webpack4 index f989b527bb..eca0d83aba 100644 --- a/test/e2e/__snapshots__/overlay.test.js.snap.webpack4 +++ b/test/e2e/__snapshots__/overlay.test.js.snap.webpack4 @@ -2135,3 +2135,89 @@ exports[`overlay should show an error when "client.overlay.warnings" is "true": " `; + +exports[`overlay should show error for uncaught runtime error: overlay html 1`] = ` +" +
+
+ Uncaught runtime errors: +
+ +
+
+
+ ERROR +
+
+ Injected error at throwError (<anonymous>:2:15) at + <anonymous>:3:9 at addScriptContent + (__puppeteer_evaluation_script__:9:27) +
+
+
+
+ +" +`; diff --git a/test/e2e/__snapshots__/overlay.test.js.snap.webpack5 b/test/e2e/__snapshots__/overlay.test.js.snap.webpack5 index 33fc1dbc70..39555dfd65 100644 --- a/test/e2e/__snapshots__/overlay.test.js.snap.webpack5 +++ b/test/e2e/__snapshots__/overlay.test.js.snap.webpack5 @@ -2152,6 +2152,92 @@ exports[`overlay should show an error when "client.overlay.warnings" is "true": " `; +exports[`overlay should show error for uncaught runtime error: overlay html 1`] = ` +" +
+
+ Uncaught runtime errors: +
+ +
+
+
+ ERROR +
+
+ Injected error at throwError (<anonymous>:2:15) at + <anonymous>:3:9 at addScriptContent + (__puppeteer_evaluation_script__:9:27) +
+
+
+
+ +" +`; + exports[`overlay should show overlay when Trusted Types are enabled: overlay html 1`] = ` "
{ await browser.close(); await server.stop(); }); + + 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(); + + await page.goto(`http://localhost:${port}/`, { + waitUntil: "networkidle0", + }); + + await page.addScriptTag({ + content: `(function throwError() { + throw new Error('Injected error'); + })();`, + }); + + const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); + const overlayFrame = await overlayHandle.contentFrame(); + const overlayHtml = await overlayFrame.evaluate( + () => document.body.outerHTML + ); + + expect(prettier.format(overlayHtml, { parser: "html" })).toMatchSnapshot( + "overlay html" + ); + + await browser.close(); + await server.stop(); + }); + + it("show not show filtered runtime error", async () => { + const compiler = webpack(config); + + const server = new Server( + { + port, + client: { + overlay: { + runtimeErrors: (error) => error && !/Injected/.test(error.message), + }, + }, + }, + compiler + ); + + await server.start(); + + const { page, browser } = await runBrowser(); + + await page.goto(`http://localhost:${port}/`, { + waitUntil: "networkidle0", + }); + + await page.addScriptTag({ + content: `(function throwError() { + throw new Error('Injected error'); + })();`, + }); + + const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); + + expect(overlayHandle).toBe(null); + + await browser.close(); + await server.stop(); + }); }); From 6c017ebc30b94c5ef7b2a98f0ba07714caf33a8d Mon Sep 17 00:00:00 2001 From: Malcolm Kee Date: Sat, 6 May 2023 02:23:47 +1000 Subject: [PATCH 4/6] test: test overlay errors and warnings filter function --- client-src/index.js | 42 ++-- lib/Server.js | 39 +++- .../overlay.test.js.snap.webpack4 | 210 ++++++++++++++++++ .../overlay.test.js.snap.webpack5 | 210 ++++++++++++++++++ test/e2e/overlay.test.js | 175 ++++++++++++++- types/lib/Server.d.ts | 75 ++++--- 6 files changed, 685 insertions(+), 66 deletions(-) diff --git a/client-src/index.js b/client-src/index.js index 3a948884b5..7cd441bf4b 100644 --- a/client-src/index.js +++ b/client-src/index.js @@ -35,6 +35,30 @@ import createSocketURL from "./utils/createSocketURL.js"; * @property {string} [previousHash] */ +/** + * @param {boolean | { warnings?: boolean | string; errors?: boolean | string; runtimeErrors?: boolean | string; }} overlayOptions + */ +const decodeOverlayOptions = (overlayOptions) => { + if (typeof overlayOptions === "object") { + ["warnings", "errors", "runtimeErrors"].forEach((property) => { + if (typeof overlayOptions[property] === "string") { + const overlayFilterFunctionString = decodeURIComponent( + overlayOptions[property] + ); + + // eslint-disable-next-line no-new-func + const overlayFilterFunction = new Function( + "message", + `var callback = ${overlayFilterFunctionString} + return callback(message)` + ); + + overlayOptions[property] = overlayFilterFunction; + } + }); + } +}; + /** * @type {Status} */ @@ -92,22 +116,7 @@ if (parsedResourceQuery.overlay) { ...options.overlay, }; - ["errors", "warnings", "runtimeErrors"].forEach((property) => { - if (typeof options.overlay[property] === "string") { - const overlayFilterFunctionString = decodeURIComponent( - options.overlay[property] - ); - - // eslint-disable-next-line no-new-func - const overlayFilterFunction = new Function( - "message", - `var callback = ${overlayFilterFunctionString} - return callback(message)` - ); - - options.overlay[property] = overlayFilterFunction; - } - }); + decodeOverlayOptions(options.overlay); } enabledFeatures.Overlay = true; } @@ -198,6 +207,7 @@ const onSocketMessage = { } options.overlay = value; + decodeOverlayOptions(options.overlay); }, /** * @param {number} value diff --git a/lib/Server.js b/lib/Server.js index 03deff124e..2d67d2b72a 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -240,6 +240,16 @@ const memoize = (fn) => { const getExpress = memoize(() => require("express")); +/** + * + * @param {OverlayMessageOptions} [setting] + * @returns + */ +const encodeOverlaySettings = (setting) => + typeof setting === "function" + ? encodeURIComponent(setting.toString()) + : setting; + class Server { /** * @param {Configuration | Compiler | MultiCompiler} options @@ -658,16 +668,6 @@ class Server { } if (typeof client.overlay !== "undefined") { - /** - * - * @param {OverlayMessageOptions} [setting] - * @returns - */ - const encodeOverlaySettings = (setting) => - typeof setting === "function" - ? encodeURIComponent(setting.toString()) - : setting; - const overlayString = typeof client.overlay === "boolean" ? String(client.overlay) @@ -2647,11 +2647,26 @@ class Server { /** @type {ClientConfiguration} */ (this.options.client).overlay ) { + const overlayConfig = /** @type {ClientConfiguration} */ ( + this.options.client + ).overlay; + this.sendMessage( [client], "overlay", - /** @type {ClientConfiguration} */ - (this.options.client).overlay + typeof overlayConfig === "object" + ? { + errors: + overlayConfig.errors && + encodeOverlaySettings(overlayConfig.errors), + warnings: + overlayConfig.warnings && + encodeOverlaySettings(overlayConfig.warnings), + runtimeErrors: + overlayConfig.runtimeErrors && + encodeOverlaySettings(overlayConfig.runtimeErrors), + } + : overlayConfig ); } diff --git a/test/e2e/__snapshots__/overlay.test.js.snap.webpack4 b/test/e2e/__snapshots__/overlay.test.js.snap.webpack4 index eca0d83aba..44a1317cf9 100644 --- a/test/e2e/__snapshots__/overlay.test.js.snap.webpack4 +++ b/test/e2e/__snapshots__/overlay.test.js.snap.webpack4 @@ -2221,3 +2221,213 @@ exports[`overlay should show error for uncaught runtime error: overlay html 1`] " `; + +exports[`overlay should show error when it is not filtered: overlay html 1`] = ` +" +
+
+ Compiled with problems: +
+ +
+
+
+ ERROR +
+
+ Unfiltered error +
+
+
+
+ +" +`; + +exports[`overlay should show error when it is not filtered: page html 1`] = ` +" +

webpack-dev-server is running...

+ + + + +" +`; + +exports[`overlay should show warning when it is not filtered: overlay html 1`] = ` +" +
+
+ Compiled with problems: +
+ +
+
+
+ WARNING +
+
+ Unfiltered warning +
+
+
+
+ +" +`; + +exports[`overlay should show warning when it is not filtered: page html 1`] = ` +" +

webpack-dev-server is running...

+ + + + +" +`; diff --git a/test/e2e/__snapshots__/overlay.test.js.snap.webpack5 b/test/e2e/__snapshots__/overlay.test.js.snap.webpack5 index 39555dfd65..49990c3d43 100644 --- a/test/e2e/__snapshots__/overlay.test.js.snap.webpack5 +++ b/test/e2e/__snapshots__/overlay.test.js.snap.webpack5 @@ -2238,6 +2238,111 @@ exports[`overlay should show error for uncaught runtime error: overlay html 1`] " `; +exports[`overlay should show error when it is not filtered: overlay html 1`] = ` +" +
+
+ Compiled with problems: +
+ +
+
+
+ ERROR +
+
+ Unfiltered error +
+
+
+
+ +" +`; + +exports[`overlay should show error when it is not filtered: page html 1`] = ` +" +

webpack-dev-server is running...

+ + + + +" +`; + exports[`overlay should show overlay when Trusted Types are enabled: overlay html 1`] = ` "
" `; + +exports[`overlay should show warning when it is not filtered: overlay html 1`] = ` +" +
+
+ Compiled with problems: +
+ +
+
+
+ WARNING +
+
+ Unfiltered warning +
+
+
+
+ +" +`; + +exports[`overlay should show warning when it is not filtered: page html 1`] = ` +" +

webpack-dev-server is running...

+ + + + +" +`; diff --git a/test/e2e/overlay.test.js b/test/e2e/overlay.test.js index 11f9d3bd4a..6ea8cb60c5 100644 --- a/test/e2e/overlay.test.js +++ b/test/e2e/overlay.test.js @@ -596,6 +596,90 @@ describe("overlay", () => { await server.stop(); }); + 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, + client: { + overlay: { + warnings: (error) => { + // error is string in webpack 4 + const message = typeof error === "string" ? error : error.message; + return message !== "My special warning"; + }, + }, + }, + }, + compiler + ); + + await server.start(); + + const { page, browser } = await runBrowser(); + + await page.goto(`http://localhost:${port}/`, { + waitUntil: "networkidle0", + }); + + const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); + + expect(overlayHandle).toBe(null); + + await browser.close(); + await server.stop(); + }); + + 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, + client: { + overlay: { + warnings: () => true, + }, + }, + }, + compiler + ); + + await server.start(); + + const { page, browser } = await runBrowser(); + + try { + await page.goto(`http://localhost:${port}/`, { + waitUntil: "networkidle0", + }); + + 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(prettier.format(pageHtml, { parser: "html" })).toMatchSnapshot( + "page html" + ); + expect(prettier.format(overlayHtml, { parser: "html" })).toMatchSnapshot( + "overlay html" + ); + } catch (error) { + console.error(error); + } + + await browser.close(); + await server.stop(); + }); + it('should show a warning when "client.overlay" is "true"', async () => { const compiler = webpack(config); @@ -785,6 +869,95 @@ describe("overlay", () => { await server.stop(); }); + 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, + client: { + overlay: { + errors: (error) => { + // error is string in webpack 4 + const message = typeof error === "string" ? error : error.message; + + return message !== "My special error"; + }, + }, + }, + }, + compiler + ); + + await server.start(); + + const { page, browser } = await runBrowser(); + + try { + await page.goto(`http://localhost:${port}/`, { + waitUntil: "networkidle0", + }); + + const overlayHandle = await page.$("#webpack-dev-server-client-overlay"); + + expect(overlayHandle).toBe(null); + } catch (error) { + console.error(error); + } + + await browser.close(); + await server.stop(); + }); + + 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, + client: { + overlay: { + errors: () => true, + }, + }, + }, + compiler + ); + + await server.start(); + + const { page, browser } = await runBrowser(); + + try { + await page.goto(`http://localhost:${port}/`, { + waitUntil: "networkidle0", + }); + + 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(prettier.format(pageHtml, { parser: "html" })).toMatchSnapshot( + "page html" + ); + expect(prettier.format(overlayHtml, { parser: "html" })).toMatchSnapshot( + "overlay html" + ); + } catch (error) { + console.error(error); + } + + await browser.close(); + await server.stop(); + }); + it('should show an error when "client.overlay" is "true"', async () => { const compiler = webpack(config); @@ -1184,7 +1357,7 @@ describe("overlay", () => { await server.stop(); }); - it("show not show filtered runtime error", async () => { + it("should not show filtered runtime error", async () => { const compiler = webpack(config); const server = new Server( diff --git a/types/lib/Server.d.ts b/types/lib/Server.d.ts index 7361906c51..ab8c6e3d08 100644 --- a/types/lib/Server.d.ts +++ b/types/lib/Server.d.ts @@ -665,9 +665,16 @@ declare class Server { } | { description: string; + /** + * @private + * @type {RequestHandler[]} + */ multiple: boolean; path: string; type: string; + /** + * @type {Socket[]} + */ } )[]; description: string; @@ -774,6 +781,9 @@ declare class Server { simpleType: string; multiple: boolean; }; + /** + * @type {string | undefined} + */ "https-ca": { configs: { type: string; @@ -808,10 +818,6 @@ declare class Server { multiple: boolean; }; "https-cacert-reset": { - /** - * @private - * @param {Compiler} compiler - */ configs: { description: string; multiple: boolean; @@ -826,7 +832,7 @@ declare class Server { configs: { type: string; multiple: boolean; - description: string; + /** @type {ClientConfiguration} */ description: string; path: string; }[]; description: string; @@ -886,7 +892,7 @@ declare class Server { }[]; description: string; multiple: boolean; - simpleType: string; + /** @type {string} */ simpleType: string; }; "https-passphrase": { configs: { @@ -897,7 +903,7 @@ declare class Server { }[]; description: string; simpleType: string; - /** @type {ClientConfiguration} */ multiple: boolean; + multiple: boolean; }; "https-pfx": { configs: { @@ -983,12 +989,12 @@ declare class Server { type: string; multiple: boolean; description: string; + /** @type {any} */ path: string; } | { type: string; multiple: boolean; - /** @type {any} */ description: string; negatedDescription: string; path: string; @@ -1018,8 +1024,9 @@ declare class Server { }[]; description: string; simpleType: string; - multiple: boolean; + multiple: boolean /** @type {MultiCompiler} */; }; + /** @type {MultiCompiler} */ "open-app-name-reset": { configs: { type: string; @@ -1091,6 +1098,10 @@ declare class Server { path: string; type: string; }[]; + /** + * @param {string | Static | undefined} [optionsForStatic] + * @returns {NormalizedStatic} + */ description: string; multiple: boolean; simpleType: string; @@ -1261,7 +1272,7 @@ declare class Server { } | { type: string; - /** @type {ServerConfiguration} */ multiple: boolean; + multiple: boolean; description: string; negatedDescription: string; path: string; @@ -1278,15 +1289,15 @@ declare class Server { description: string; path: string; }[]; - description: string; + /** @type {ServerOptions} */ description: string; simpleType: string; - multiple: boolean /** @type {ServerOptions} */; + multiple: boolean; }; "static-public-path": { configs: { type: string; multiple: boolean; - /** @type {ServerOptions} */ description: string; + description: string; path: string; }[]; description: string; @@ -2126,10 +2137,6 @@ declare class Server { } | { type: string; - /** - * @private - * @type {{ name: string | symbol, listener: (...args: any[]) => void}[] }} - */ additionalProperties: boolean; properties: { passphrase: { @@ -2143,6 +2150,10 @@ declare class Server { negatedDescription: string; }; }; + /** + * @private + * @type {string | undefined} + */ ca: { anyOf: ( | { @@ -2406,6 +2417,7 @@ declare class Server { | { type: string; description: string; + /** @type {{ type: WebSocketServerConfiguration["type"], options: NonNullable }} */ link: string; cli?: undefined; } @@ -2440,7 +2452,7 @@ declare class Server { } | { enum: string[]; - type?: undefined; + /** @type {string} */ type?: undefined; cli?: undefined; } )[]; @@ -2469,7 +2481,7 @@ declare class Server { cli: { negatedDescription: string; }; - link: string /** @type {number | string} */; + link: string; }; MagicHTML: { type: string; @@ -2606,12 +2618,6 @@ declare class Server { | { type: string; minLength: number; - /** - * prependEntry Method for webpack 4 - * @param {any} originalEntry - * @param {any} newAdditionalEntries - * @returns {any} - */ minimum?: undefined; maximum?: undefined; enum?: undefined; @@ -2688,7 +2694,7 @@ declare class Server { $ref: string; }; }; - /** @type {MultiCompiler} */ additionalProperties: boolean; + additionalProperties: boolean; }; ServerOptions: { type: string; @@ -2696,7 +2702,7 @@ declare class Server { properties: { passphrase: { type: string; - /** @type {MultiCompiler} */ description: string; + description: string; }; requestCert: { type: string; @@ -2744,10 +2750,6 @@ declare class Server { anyOf: ( | { type: string; - /** - * @private - * @returns {Promise} - */ instanceof?: undefined; } | { @@ -2769,10 +2771,6 @@ declare class Server { items?: undefined; } )[]; - /** - * @param {WatchOptions & { aggregateTimeout?: number, ignored?: WatchOptions["ignored"], poll?: number | boolean }} watchOptions - * @returns {WatchOptions} - */ description: string; }; cert: { @@ -3126,6 +3124,7 @@ declare class Server { }; WebSocketServerObject: { type: string; + /** @type {ServerOptions} */ properties: { type: { anyOf: { @@ -3135,12 +3134,13 @@ declare class Server { options: { type: string; additionalProperties: boolean; + /** @type {ServerOptions} */ cli: { exclude: boolean; }; }; }; - /** @type {ServerOptions} */ additionalProperties: boolean; + additionalProperties: boolean; }; WebSocketServerString: { type: string; @@ -3195,8 +3195,9 @@ declare class Server { $ref: string; }; onBeforeSetupMiddleware: { - $ref: string; + $ref: string /** @type {any} */; }; + /** @type {any} */ onListening: { $ref: string; }; From 2132c30de3a78bcb0d53a0347d30d227d5bbedea Mon Sep 17 00:00:00 2001 From: Malcolm Kee Date: Sat, 6 May 2023 11:35:43 +1000 Subject: [PATCH 5/6] fix: encode overlay options correctly --- lib/Server.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/Server.js b/lib/Server.js index 2d67d2b72a..0c093b2415 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -672,6 +672,7 @@ class Server { typeof client.overlay === "boolean" ? String(client.overlay) : JSON.stringify({ + ...client.overlay, errors: encodeOverlaySettings(client.overlay.errors), warnings: encodeOverlaySettings(client.overlay.warnings), runtimeErrors: encodeOverlaySettings( @@ -2656,6 +2657,7 @@ class Server { "overlay", typeof overlayConfig === "object" ? { + ...overlayConfig, errors: overlayConfig.errors && encodeOverlaySettings(overlayConfig.errors), From f7386f60da170b158d13a2c41cc668f0b83d9679 Mon Sep 17 00:00:00 2001 From: Malcolm Kee Date: Sat, 6 May 2023 11:43:05 +1000 Subject: [PATCH 6/6] fix: update types --- types/lib/Server.d.ts | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/types/lib/Server.d.ts b/types/lib/Server.d.ts index ab8c6e3d08..f8aa0d06bb 100644 --- a/types/lib/Server.d.ts +++ b/types/lib/Server.d.ts @@ -969,6 +969,12 @@ declare class Server { }[]; description: string; simpleType: string; + /** + * prependEntry Method for webpack 4 + * @param {any} originalEntry + * @param {any} newAdditionalEntries + * @returns {any} + */ multiple: boolean; }; "magic-html": { @@ -989,13 +995,13 @@ declare class Server { type: string; multiple: boolean; description: string; - /** @type {any} */ path: string; } | { + /** @type {any} */ type: string; multiple: boolean; - description: string; + /** @type {any} */ description: string; negatedDescription: string; path: string; } @@ -1012,7 +1018,7 @@ declare class Server { path: string; }[]; description: string; - /** @type {MultiCompiler} */ simpleType: string; + simpleType: string; multiple: boolean; }; "open-app-name": { @@ -1024,9 +1030,8 @@ declare class Server { }[]; description: string; simpleType: string; - multiple: boolean /** @type {MultiCompiler} */; + multiple: boolean; }; - /** @type {MultiCompiler} */ "open-app-name-reset": { configs: { type: string; @@ -1098,10 +1103,6 @@ declare class Server { path: string; type: string; }[]; - /** - * @param {string | Static | undefined} [optionsForStatic] - * @returns {NormalizedStatic} - */ description: string; multiple: boolean; simpleType: string; @@ -1289,7 +1290,7 @@ declare class Server { description: string; path: string; }[]; - /** @type {ServerOptions} */ description: string; + description: string; simpleType: string; multiple: boolean; }; @@ -1324,8 +1325,9 @@ declare class Server { }[]; description: string; simpleType: string; - multiple: boolean; + multiple: boolean /** @type {any} */; }; + /** @type {any} */ "static-serve-index": { configs: { type: string; @@ -2676,7 +2678,7 @@ declare class Server { }; ServerString: { type: string; - minLength: number; + /** @type {string} */ minLength: number; cli: { exclude: boolean; }; @@ -2689,7 +2691,6 @@ declare class Server { $ref: string; }[]; }; - /** @type {MultiCompiler} */ options: { $ref: string; }; @@ -2873,6 +2874,7 @@ declare class Server { )[]; description: string; }; + /** @type {NormalizedStatic} */ pfx: { anyOf: ( | { @@ -3124,7 +3126,6 @@ declare class Server { }; WebSocketServerObject: { type: string; - /** @type {ServerOptions} */ properties: { type: { anyOf: { @@ -3134,7 +3135,6 @@ declare class Server { options: { type: string; additionalProperties: boolean; - /** @type {ServerOptions} */ cli: { exclude: boolean; }; @@ -3195,9 +3195,8 @@ declare class Server { $ref: string; }; onBeforeSetupMiddleware: { - $ref: string /** @type {any} */; + $ref: string; }; - /** @type {any} */ onListening: { $ref: string; };