diff --git a/web/src/index.html b/web/src/index.html index adefba0696..ea6f1c99d2 100644 --- a/web/src/index.html +++ b/web/src/index.html @@ -13,7 +13,7 @@ diff --git a/web/src/lib/webpack-po-handler.js b/web/src/lib/webpack-po-handler.js new file mode 100644 index 0000000000..e14a1b59f6 --- /dev/null +++ b/web/src/lib/webpack-po-handler.js @@ -0,0 +1,33 @@ +const fs = require("fs"); +const path = require("path"); + +// Cockpit internally returns the "po..js" file content for the +// "po.js" request, reimplement it with a simple redirection (the JS file +// only exists in the webpack memory, we cannot read it from disk) +// +// This function processes the webpack HTTP request. +// +// @param req HTTP request +// @param res HTTP response +module.exports = function (req, res) { + // the regexp was taken from the original Cockpit code :-) + const language = req.headers.cookie.replace(/(?:(?:^|.*;\s*)CockpitLang\s*=\s*([^;]*).*$)|^.*$/, "$1") || ""; + // the cookie uses "pt-br" format while the PO file is "pt_BR" :-/ + let [lang, country] = language.split("-"); + country = country.toUpperCase(); + + // first check the full locale ("pt_BR") PO file + if (fs.existsSync(path.join(__dirname, "..", "..", "po", `${lang}_${country}.po`))) { + res.redirect(`/po.${lang}_${country}.js`); + } else { + // then check the language part only ("pt") PO file + if (fs.existsSync(path.join(__dirname, "..", "..", "po", `${lang}.po`))) { + res.redirect(`/po.${lang}.js`); + } else { + if (lang !== "en") console.log(`translation "${language}" not found`); + // Cockpit returns an empty script if the translation file is missing + res.set("Content-Type", "application/javascript"); + res.send(""); + } + } +}; diff --git a/web/webpack.config.js b/web/webpack.config.js index 249192383d..ae3c3271e0 100644 --- a/web/webpack.config.js +++ b/web/webpack.config.js @@ -13,6 +13,7 @@ const StylelintPlugin = require('stylelint-webpack-plugin'); const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin'); const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin'); const webpack = require('webpack'); +const po_handler = require("./src/lib/webpack-po-handler"); /* A standard nodejs and webpack pattern */ const production = process.env.NODE_ENV === 'production'; @@ -114,6 +115,12 @@ module.exports = { // hot replacement does not support wss:// transport when running over https://, // as a workaround use sockjs (which uses standard https:// protocol) webSocketServer: "sockjs", + + // Cockpit handles "po.js" requests specially + setupMiddlewares: (middlewares, devServer) => { + devServer.app.get("/po.js", (req, res) => po_handler(req, res)); + return middlewares; + } }, devtool: "source-map", stats: "errors-warnings",