WIP: modify dev server to use as test server, also

This commit is contained in:
Catalin Constantin Mititiuc 2025-06-16 22:41:31 -07:00
parent c424c1fef2
commit 2dfd5cdac3
4 changed files with 89 additions and 58 deletions

View File

@ -22,6 +22,7 @@ const mime = {
'.jpg': 'image/jpeg',
'.css': 'text/css; charset=utf-8',
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
};
function createServerSentEventHandler() {
@ -220,7 +221,7 @@ const externalSvgToInternal = {
}
}
const ctx = await esbuild.context({
const buildOptions = {
entryPoints: ['src/index.js', 'src/soldier_record_block.js', 'src/map.js'],
bundle: true,
outdir: 'build',
@ -233,66 +234,95 @@ const ctx = await esbuild.context({
'.svg': 'file'
},
assetNames: 'assets/images/[name]-[hash]',
});
};
await ctx.watch();
if (process.env.NODE_ENV === 'test') {
http.createServer((req, res) => {
const filename = req.url && req.url !== '/' ? req.url : 'index.html';
const filepath = ['public', 'build'].map(dir => path.join(__dirname, dir, filename)).find(fp => fs.existsSync(fp));
const { host, port } = await ctx.serve({
servedir: 'build',
port: 3000,
// onRequest: function({ remoteAddress, method, path, status, timeInMS }) {
// let statusColor = colors.red;
if (filepath) {
const readStream = fs.createReadStream(filepath, { autoClose: true });
// if (status >= 200 && status <= 299) {
// statusColor = colors.green;
// } else if (status >= 300 && status <= 399) {
// statusColor = colors.yellow;
// }
readStream.on('ready', () => {
const type = mime[path.parse(filepath).ext] || 'text/plain';
res.writeHead(200, { 'content-type': type });
readStream.pipe(res, { end: true });
});
// console.log(`${colors.dim}${remoteAddress} - "${method} ${path}" ${colors.normal}${statusColor}${status}${colors.reset}${colors.dim} [${timeInMS}ms]${colors.reset}`);
// },
});
readStream.on('error', err => {
res.writeHead(500, err.name);
res.end(JSON.stringify(err));
});
} else {
res.writeHead(404, { 'content-type': 'text/plain' });
res.end("Not found");
}
}).listen(3005, () => {
console.log('test server is online');
});
} else {
buildOptions.define = { 'window.IS_DEV': 'true' };
const ctx = await esbuild.context(buildOptions);
await ctx.watch();
http.createServer((req, res) => {
const options = {
hostname: host,
port: port,
path: req.url,
method: req.method,
headers: req.headers,
}
const { host, port } = await ctx.serve({
servedir: 'build',
port: 3000,
// onRequest: function({ remoteAddress, method, path, status, timeInMS }) {
// let statusColor = colors.red;
const filename = req.url && req.url !== '/' ? req.url : 'index.html';
const filepath = path.join(__dirname, 'public', filename);
// if (status >= 200 && status <= 299) {
// statusColor = colors.green;
// } else if (status >= 300 && status <= 399) {
// statusColor = colors.yellow;
// }
if (fs.existsSync(filepath)) {
const readStream = fs.createReadStream(filepath, { autoClose: true });
// console.log(`${colors.dim}${remoteAddress} - "${method} ${path}" ${colors.normal}${statusColor}${status}${colors.reset}${colors.dim} [${timeInMS}ms]${colors.reset}`);
// },
});
readStream.on('ready', () => {
const type = mime[path.parse(filepath).ext] || 'application/octet-stream';
console.log(`${req.method} ${req.url} => 200 ${type}`);
res.writeHead(200, { 'content-type': type });
readStream.pipe(res, { end: true });
});
http.createServer((req, res) => {
const options = {
hostname: host,
port: port,
path: req.url,
method: req.method,
headers: req.headers,
}
readStream.on('error', err => {
console.log(`${req.method} ${req.url} => 500 ${filepath} ${err.name}`);
res.writeHead(500, err.name);
res.end(JSON.stringify(err));
});
} else {
const proxyReq = http.request(options, proxyRes => {
const type = proxyRes.headers['content-type'];
console.log(`${req.method} ${req.url} => ${proxyRes.statusCode} ${type} via esbuild`);
res.writeHead(proxyRes.statusCode, { 'content-type': type });
// if (req.url === '/esbuild') buildListeners.setupConnection(req, res);
proxyRes.pipe(res);
});
const filename = req.url && req.url !== '/' ? req.url : 'index.html';
const filepath = path.join(__dirname, 'public', filename);
req.pipe(proxyReq, { end: true });
}
}).listen(8080, (e) => {
console.log('server is online', e);
});
if (fs.existsSync(filepath)) {
const readStream = fs.createReadStream(filepath, { autoClose: true });
readStream.on('ready', () => {
const type = mime[path.parse(filepath).ext] || 'application/octet-stream';
console.log(`${req.method} ${req.url} => 200 ${type}`);
res.writeHead(200, { 'content-type': type });
readStream.pipe(res, { end: true });
});
readStream.on('error', err => {
console.log(`${req.method} ${req.url} => 500 ${filepath} ${err.name}`);
res.writeHead(500, err.name);
res.end(JSON.stringify(err));
});
} else {
const proxyReq = http.request(options, proxyRes => {
const type = proxyRes.headers['content-type'];
console.log(`${req.method} ${req.url} => ${proxyRes.statusCode} ${type} via esbuild`);
res.writeHead(proxyRes.statusCode, { 'content-type': type });
// if (req.url === '/esbuild') buildListeners.setupConnection(req, res);
proxyRes.pipe(res);
});
req.pipe(proxyReq, { end: true });
}
}).listen(8080, (e) => {
console.log('server is online', e);
});
}
// console.log(`${process.env.NODE_ENV === 'test' ? 'Test' : 'Development'} server running at ${server.url}`);

View File

@ -3,11 +3,6 @@
<head>
<title>Infantry Combat Solo Basic</title>
<link rel="stylesheet" href="assets/css/style.css">
<script>
const source = new EventSource('/esbuild');
source.addEventListener('change', () => location.reload());
// source.addEventListener('message', (e) => console.log(e));
</script>
</head>
<body>
<template id="damage-block">

View File

@ -7,6 +7,12 @@ import { scenarios } from './modules/scenarios.js';
globalThis.svgns = 'http://www.w3.org/2000/svg';
if (window.IS_DEV) {
const source = new EventSource('/esbuild');
source.addEventListener('change', () => location.reload());
// source.addEventListener('message', (e) => console.log(e));
}
const mapPlaceholder = document.querySelector('.map-placeholder'),
distanceOutput = document.getElementById('status'),
proneToggle = document.getElementById('toggle-prone-counter'),

View File

@ -2,7 +2,7 @@ console.log('\nSpawning server process...');
const { spawn } = require('child_process');
module.exports = async function (globalConfig, projectConfig) {
const child = spawn('node', ['server.cjs']);
const child = spawn('node', ['esbuild-server.mjs']);
child.stdout.on('data', (data) => {
console.log(`${data}`);