74 lines
2.5 KiB
JavaScript
74 lines
2.5 KiB
JavaScript
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.AutoReloader = void 0;
|
|
const express_1 = require("express");
|
|
const _1 = require(".");
|
|
const uuid_1 = require("uuid");
|
|
function getRouter(opts) {
|
|
const config = {
|
|
frontendDirs: Array.isArray(opts.frontendDirs) ? opts.frontendDirs : [opts.frontendDirs],
|
|
subPath: opts.subPath || '/auto-reload',
|
|
jsName: opts.jsName || 'client.js',
|
|
};
|
|
const router = express_1.Router();
|
|
if (!_1.DefaultConfig.isProduction) {
|
|
let uuid = uuid_1.v4();
|
|
let updateTimeout = undefined;
|
|
Promise.resolve().then(() => require('node-watch')).then((watch) => {
|
|
for (const frontendDir of config.frontendDirs) {
|
|
watch.default(frontendDir, { recursive: true }, () => {
|
|
if (updateTimeout !== undefined)
|
|
clearTimeout(updateTimeout);
|
|
updateTimeout = setTimeout(() => {
|
|
uuid = uuid_1.v4();
|
|
}, 200);
|
|
});
|
|
}
|
|
}).catch((err) => { _1.Logger.error(err); });
|
|
// /auto-reload/client.js
|
|
router.get(_1.urlJoin(config.subPath, config.jsName), (req, res) => {
|
|
_1.Logger.debug(req.url, req.originalUrl, req.baseUrl);
|
|
res.setHeader('Content-Type', 'application/javascript');
|
|
// language=JavaScript
|
|
res.send(`
|
|
const loc = window.location;
|
|
const url = loc.protocol+'//'+loc.host+'${_1.urlJoin(req.baseUrl, config.subPath)}';
|
|
// const parse = async res => (await res.json()).uuid;
|
|
const parse = function(res) {
|
|
return res.json()
|
|
.then(function(json) {return json.uuid;}) }
|
|
let hash = undefined;
|
|
let hadError = false;
|
|
setInterval(function() {
|
|
try {
|
|
fetch(url)
|
|
.then(function(res) { return parse(res) })
|
|
.then(function(data) {
|
|
if (data) {
|
|
hash = hash === undefined ? data : hash;
|
|
if (hash !== data) {
|
|
window.location.reload();
|
|
}
|
|
}
|
|
});
|
|
} catch (e) {
|
|
if (hadError === false) {
|
|
console.log(e);
|
|
hadError = true;
|
|
}
|
|
}
|
|
}, 3000);
|
|
`.replace(/\t/g, ''));
|
|
});
|
|
// /auto-reload
|
|
router.get(_1.urlJoin(config.subPath), (req, res) => {
|
|
req.noHttpLogging = true;
|
|
res.json({ uuid });
|
|
});
|
|
}
|
|
return router;
|
|
}
|
|
exports.AutoReloader = {
|
|
getRouter,
|
|
};
|