mirror of
https://github.com/MagicMirrorOrg/MagicMirror.git
synced 2026-03-12 17:51:41 +08:00
Thanks to: @Blackspirits, @Crazylegstoo, @jarnoml, @jboucly, @JHWelch, @khassel, @KristjanESPERANTO, @rejas, @sdetweil, @xsorifc28 ⚠️ This release needs nodejs version >=22.21.1 <23 || >=24 [Compare to previous Release v2.33.0](https://github.com/MagicMirrorOrg/MagicMirror/compare/v2.33.0...develop) [core] Prepare Release 2.34.0 (https://github.com/MagicMirrorOrg/MagicMirror/pull/3998) dependency update + adjust Playwright setup + fix linter issue (https://github.com/MagicMirrorOrg/MagicMirror/pull/3994) demo with gif (https://github.com/MagicMirrorOrg/MagicMirror/pull/3995) [core] fix: allow browser globals in config files (https://github.com/MagicMirrorOrg/MagicMirror/pull/3992) [core] fix: restore --ozone-platform=wayland flag for reliable Wayland support (https://github.com/MagicMirrorOrg/MagicMirror/pull/3989) [core] auto create release notes with every push on develop (https://github.com/MagicMirrorOrg/MagicMirror/pull/3985) [core] chore: simplify Wayland start script (https://github.com/MagicMirrorOrg/MagicMirror/pull/3974) [gitignore] restore the old Git behavior for the default modules (https://github.com/MagicMirrorOrg/MagicMirror/pull/3968) [core] configure cspell to check default modules only and fix typos (https://github.com/MagicMirrorOrg/MagicMirror/pull/3955) [gitignore] restoring the old Git behavior for the CSS directory (https://github.com/MagicMirrorOrg/MagicMirror/pull/3954) feat(core): add server:watch script with automatic restart on file changes (https://github.com/MagicMirrorOrg/MagicMirror/pull/3920) [check_config] refactor: improve error handling (https://github.com/MagicMirrorOrg/MagicMirror/pull/3927) refactor: replace express-ipfilter with lightweight custom middleware (https://github.com/MagicMirrorOrg/MagicMirror/pull/3917) refactor: replace module-alias dependency with internal alias resolver (https://github.com/MagicMirrorOrg/MagicMirror/pull/3893) [dependencies] [chore] update dependencies and min. node version (https://github.com/MagicMirrorOrg/MagicMirror/pull/3986) [core] bump dependencies into december (https://github.com/MagicMirrorOrg/MagicMirror/pull/3982) Bump actions/checkout from 5 to 6 (https://github.com/MagicMirrorOrg/MagicMirror/pull/3972) Update deps, unpin parse5 (https://github.com/MagicMirrorOrg/MagicMirror/pull/3934) [core] Update deps and pin jsdom to v27.0.0 (https://github.com/MagicMirrorOrg/MagicMirror/pull/3925) chore: update dependencies (https://github.com/MagicMirrorOrg/MagicMirror/pull/3921) update deps, exclude node v23 (https://github.com/MagicMirrorOrg/MagicMirror/pull/3916) remove eslint warnings, add npm publish process to Collaboration.md (https://github.com/MagicMirrorOrg/MagicMirror/pull/3913) feat: add ESlint rule no-sparse-arrays for config check (https://github.com/MagicMirrorOrg/MagicMirror/pull/3911) chore: bump dependencies into october (https://github.com/MagicMirrorOrg/MagicMirror/pull/3909) [logging] logger: add calling filename as prefix on server side (https://github.com/MagicMirrorOrg/MagicMirror/pull/3926) [logger] Add prefixes to most Log messages (https://github.com/MagicMirrorOrg/MagicMirror/pull/3923) [modules/alert] Add new pt and pt-BR translations for Alert module and update global PT strings (https://github.com/MagicMirrorOrg/MagicMirror/pull/3965) [modules/calendar] add checksum to test whether calendar event list changed (https://github.com/MagicMirrorOrg/MagicMirror/pull/3988) [calendar] fix: prevent excessive fetching on client reload and refactor calendarfetcherutils.js (https://github.com/MagicMirrorOrg/MagicMirror/pull/3976) [calendar] refactor: migrate CalendarFetcher to ES6 class and improve error handling (https://github.com/MagicMirrorOrg/MagicMirror/pull/3959) [calendar] Show repeatingCountTitle only if yearDiff > 0 (https://github.com/MagicMirrorOrg/MagicMirror/pull/3949) [tests] suppress debug logs in CI environment + improve calendar symbol test stability (https://github.com/MagicMirrorOrg/MagicMirror/pull/3941) [calendar] chore: remove requiresVersion: "2.1.0" (https://github.com/MagicMirrorOrg/MagicMirror/pull/3932) [calendar] test: remove "Recurring event per timezone" test (https://github.com/MagicMirrorOrg/MagicMirror/pull/3929) [modules/compliments] [compliments] refactor: optimize loadComplimentFile method and add unit tests (https://github.com/MagicMirrorOrg/MagicMirror/pull/3969) fix: set compliments remote file minimum delay to 15 minutes (https://github.com/MagicMirrorOrg/MagicMirror/pull/3970) [compliments] fix: duplicate query param "?" in compliments module refresh url (https://github.com/MagicMirrorOrg/MagicMirror/pull/3967) [modules/newsfeed] [newsfeed] fix header layout issue (https://github.com/MagicMirrorOrg/MagicMirror/pull/3946) [modules/weather] [weatherprovider] update subclass language use override (https://github.com/MagicMirrorOrg/MagicMirror/pull/3914) [weather] fix wind-icon not showing in pirateweather (https://github.com/MagicMirrorOrg/MagicMirror/pull/3957) [weather] add error handling to weather fetch functions, including cors (https://github.com/MagicMirrorOrg/MagicMirror/pull/3791) remove deprecated ukmetoffice datapoint provider, cleanup .gitignore (https://github.com/MagicMirrorOrg/MagicMirror/pull/3952) fixes problems with daylight-saving-time in weather provider openmeteo (https://github.com/MagicMirrorOrg/MagicMirror/pull/3931) Fix for envcanada Provider to use updated Env Canada URL (https://github.com/MagicMirrorOrg/MagicMirror/pull/3919) [weather] feat: add configurable forecast date format option (https://github.com/MagicMirrorOrg/MagicMirror/pull/3918) [testing] testing: update "Enforce Pull-Request Rules" workflow (https://github.com/MagicMirrorOrg/MagicMirror/pull/3987) [core] refactor: replace XMLHttpRequest with fetch and migrate e2e tests to Playwright (https://github.com/MagicMirrorOrg/MagicMirror/pull/3950) [test] replace node-libgpiod with serialport in electron-rebuild workflow (https://github.com/MagicMirrorOrg/MagicMirror/pull/3945) [ci] Add concurrency to automated tests workflow to cancel outdated runs (https://github.com/MagicMirrorOrg/MagicMirror/pull/3943) [tests] migrate from jest to vitest (https://github.com/MagicMirrorOrg/MagicMirror/pull/3940) --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Karsten Hassel <hassel@gmx.de> Co-authored-by: Kristjan ESPERANTO <35647502+KristjanESPERANTO@users.noreply.github.com> Co-authored-by: Ryan Williams <65094007+ryan-d-williams@users.noreply.github.com> Co-authored-by: Veeck <github@veeck.de> Co-authored-by: Bugsounet - Cédric <github@bugsounet.fr> Co-authored-by: Marc Landis <dirk.rettschlag@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: HeikoGr <20295490+HeikoGr@users.noreply.github.com> Co-authored-by: Pedro Lamas <pedrolamas@gmail.com> Co-authored-by: veeck <gitkraken@veeck.de> Co-authored-by: Magnus <34011212+MagMar94@users.noreply.github.com> Co-authored-by: Ikko Eltociear Ashimine <eltociear@gmail.com> Co-authored-by: DevIncomin <56730075+Developer-Incoming@users.noreply.github.com> Co-authored-by: Nathan <n8nyoung@gmail.com> Co-authored-by: mixasgr <mixasgr@users.noreply.github.com> Co-authored-by: Savvas Adamtziloglou <savvas-gr@greeklug.gr> Co-authored-by: Konstantinos <geraki@gmail.com> Co-authored-by: OWL4C <124401812+OWL4C@users.noreply.github.com> Co-authored-by: BugHaver <43462320+bughaver@users.noreply.github.com> Co-authored-by: BugHaver <43462320+lsaadeh@users.noreply.github.com> Co-authored-by: Koen Konst <koenspero@gmail.com> Co-authored-by: Koen Konst <c.h.konst@avisi.nl> Co-authored-by: dathbe <github@beffa.us> Co-authored-by: Marcel <m-idler@users.noreply.github.com> Co-authored-by: Kevin G. <crazylegstoo@gmail.com> Co-authored-by: Jboucly <33218155+jboucly@users.noreply.github.com> Co-authored-by: Jboucly <contact@jboucly.fr> Co-authored-by: Jarno <54169345+jarnoml@users.noreply.github.com> Co-authored-by: Jordan Welch <JordanHWelch@gmail.com> Co-authored-by: Blackspirits <blackspirits@gmail.com> Co-authored-by: Samed Ozdemir <samed@xsor.io>
262 lines
6.7 KiB
JavaScript
262 lines
6.7 KiB
JavaScript
// Load lightweight internal alias resolver to enable require("logger")
|
|
require("../js/alias-resolver");
|
|
|
|
const { spawn } = require("child_process");
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
const net = require("net");
|
|
const http = require("http");
|
|
const Log = require("logger");
|
|
const { getConfigFilePath } = require("#server_functions");
|
|
|
|
const RESTART_DELAY_MS = 500;
|
|
const PORT_CHECK_MAX_ATTEMPTS = 20;
|
|
const PORT_CHECK_INTERVAL_MS = 500;
|
|
|
|
let child = null;
|
|
let restartTimer = null;
|
|
let isShuttingDown = false;
|
|
let isRestarting = false;
|
|
let serverConfig = null;
|
|
const rootDir = path.join(__dirname, "..");
|
|
|
|
/**
|
|
* Get the server configuration (port and address)
|
|
* @returns {{port: number, address: string}} The server config
|
|
*/
|
|
function getServerConfig () {
|
|
if (serverConfig) return serverConfig;
|
|
|
|
try {
|
|
const configPath = getConfigFilePath();
|
|
delete require.cache[require.resolve(configPath)];
|
|
const config = require(configPath);
|
|
serverConfig = {
|
|
port: global.mmPort || config.port || 8080,
|
|
address: config.address || "localhost"
|
|
};
|
|
} catch (err) {
|
|
serverConfig = { port: 8080, address: "localhost" };
|
|
}
|
|
|
|
return serverConfig;
|
|
}
|
|
|
|
/**
|
|
* Check if a port is available on the configured address
|
|
* @param {number} port The port to check
|
|
* @returns {Promise<boolean>} True if port is available
|
|
*/
|
|
function isPortAvailable (port) {
|
|
return new Promise((resolve) => {
|
|
const server = net.createServer();
|
|
|
|
server.once("error", () => {
|
|
resolve(false);
|
|
});
|
|
|
|
server.once("listening", () => {
|
|
server.close();
|
|
resolve(true);
|
|
});
|
|
|
|
// Use the same address as the actual server will bind to
|
|
const { address } = getServerConfig();
|
|
server.listen(port, address);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Wait until port is available
|
|
* @param {number} port The port to wait for
|
|
* @param {number} maxAttempts Maximum number of attempts
|
|
* @returns {Promise<void>}
|
|
*/
|
|
async function waitForPort (port, maxAttempts = PORT_CHECK_MAX_ATTEMPTS) {
|
|
for (let i = 0; i < maxAttempts; i++) {
|
|
if (await isPortAvailable(port)) {
|
|
Log.info(`Port ${port} is now available`);
|
|
return;
|
|
}
|
|
await new Promise((resolve) => setTimeout(resolve, PORT_CHECK_INTERVAL_MS));
|
|
}
|
|
Log.warn(`Port ${port} still not available after ${maxAttempts} attempts`);
|
|
}
|
|
|
|
/**
|
|
* Start the server process
|
|
*/
|
|
function startServer () {
|
|
// Start node directly instead of via npm to avoid process tree issues
|
|
child = spawn("node", ["./serveronly"], {
|
|
stdio: "inherit",
|
|
cwd: path.join(__dirname, "..")
|
|
});
|
|
|
|
child.on("error", (error) => {
|
|
Log.error("Failed to start server process:", error.message);
|
|
child = null;
|
|
});
|
|
|
|
child.on("exit", (code, signal) => {
|
|
child = null;
|
|
|
|
if (isShuttingDown) {
|
|
return;
|
|
}
|
|
|
|
if (isRestarting) {
|
|
// Expected restart - don't log as error
|
|
isRestarting = false;
|
|
} else {
|
|
// Unexpected exit
|
|
Log.error(`Server exited unexpectedly with code ${code} and signal ${signal}`);
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Send reload notification to all connected clients
|
|
*/
|
|
function notifyClientsToReload () {
|
|
const { port, address } = getServerConfig();
|
|
const options = {
|
|
hostname: address,
|
|
port: port,
|
|
path: "/reload",
|
|
method: "GET"
|
|
};
|
|
|
|
const req = http.request(options, (res) => {
|
|
if (res.statusCode === 200) {
|
|
Log.info("Reload notification sent to clients");
|
|
}
|
|
});
|
|
|
|
req.on("error", (err) => {
|
|
// Server might not be running yet, ignore
|
|
Log.debug(`Could not send reload notification: ${err.message}`);
|
|
});
|
|
|
|
req.end();
|
|
}
|
|
|
|
/**
|
|
* Restart the server process
|
|
* @param {string} reason The reason for the restart
|
|
*/
|
|
async function restartServer (reason) {
|
|
if (restartTimer) clearTimeout(restartTimer);
|
|
|
|
restartTimer = setTimeout(async () => {
|
|
Log.info(reason);
|
|
|
|
if (child) {
|
|
isRestarting = true;
|
|
|
|
// Get the actual port being used
|
|
const { port } = getServerConfig();
|
|
|
|
// Notify clients to reload before restart
|
|
notifyClientsToReload();
|
|
|
|
// Set up one-time listener for the exit event
|
|
child.once("exit", async () => {
|
|
// Wait until port is actually available
|
|
await waitForPort(port);
|
|
// Reset config cache in case it changed
|
|
serverConfig = null;
|
|
startServer();
|
|
});
|
|
|
|
child.kill("SIGTERM");
|
|
} else {
|
|
startServer();
|
|
}
|
|
}, RESTART_DELAY_MS);
|
|
}
|
|
|
|
/**
|
|
* Watch a specific file for changes and restart the server on change
|
|
* Watches the parent directory to handle editors that use atomic writes
|
|
* @param {string} file The file path to watch
|
|
*/
|
|
function watchFile (file) {
|
|
try {
|
|
const fileName = path.basename(file);
|
|
const dirName = path.dirname(file);
|
|
|
|
const watcher = fs.watch(dirName, (_eventType, changedFile) => {
|
|
// Only trigger for the specific file we're interested in
|
|
if (changedFile !== fileName) return;
|
|
|
|
Log.info(`[watchFile] Change detected in: ${file}`);
|
|
if (restartTimer) clearTimeout(restartTimer);
|
|
|
|
restartTimer = setTimeout(() => {
|
|
Log.info(`[watchFile] Triggering restart due to change in: ${file}`);
|
|
restartServer(`File changed: ${path.basename(file)} — restarting...`);
|
|
}, RESTART_DELAY_MS);
|
|
});
|
|
|
|
watcher.on("error", (error) => {
|
|
Log.error(`Watcher error for ${file}:`, error.message);
|
|
});
|
|
|
|
Log.log(`Watching file: ${file}`);
|
|
} catch (error) {
|
|
Log.error(`Failed to watch file ${file}:`, error.message);
|
|
}
|
|
}
|
|
|
|
startServer();
|
|
|
|
// Setup file watching based on config
|
|
try {
|
|
const configPath = getConfigFilePath();
|
|
delete require.cache[require.resolve(configPath)];
|
|
const config = require(configPath);
|
|
|
|
let watchTargets = [];
|
|
if (Array.isArray(config.watchTargets) && config.watchTargets.length > 0) {
|
|
watchTargets = config.watchTargets.filter((target) => typeof target === "string" && target.trim() !== "");
|
|
}
|
|
|
|
if (watchTargets.length === 0) {
|
|
Log.warn("Watch mode is enabled but no watchTargets are configured. No files will be monitored. Set the watchTargets array in your config.js to enable file watching.");
|
|
}
|
|
|
|
Log.log(`Watch mode enabled. Watching ${watchTargets.length} file(s)`);
|
|
|
|
// Watch each target file
|
|
for (const target of watchTargets) {
|
|
const targetPath = path.isAbsolute(target)
|
|
? target
|
|
: path.join(rootDir, target);
|
|
|
|
// Check if file exists
|
|
if (!fs.existsSync(targetPath)) {
|
|
Log.warn(`Watch target does not exist: ${targetPath}`);
|
|
continue;
|
|
}
|
|
|
|
// Check if it's a file (directories are not supported)
|
|
const stats = fs.statSync(targetPath);
|
|
if (stats.isFile()) {
|
|
watchFile(targetPath);
|
|
} else {
|
|
Log.warn(`Watch target is not a file (directories not supported): ${targetPath}`);
|
|
}
|
|
}
|
|
} catch (err) {
|
|
// Config file might not exist or be invalid, use fallback targets
|
|
Log.warn("Could not load watchTargets from config.");
|
|
}
|
|
|
|
process.on("SIGINT", () => {
|
|
isShuttingDown = true;
|
|
if (restartTimer) clearTimeout(restartTimer);
|
|
if (child) child.kill("SIGTERM");
|
|
process.exit(0);
|
|
});
|