mermaid/.esbuild/serve.cjs

80 lines
2.4 KiB
JavaScript
Raw Normal View History

2022-09-01 10:08:02 +02:00
const esbuild = require('esbuild');
const http = require('http');
const { iifeBuild, esmBuild } = require('./util.cjs');
2022-09-13 07:22:51 +02:00
const express = require('express');
2022-09-01 10:08:02 +02:00
2022-09-13 07:22:51 +02:00
// Start 2 esbuild servers. One for IIFE and one for ESM
// Serve 2 static directories: demo & cypress/platform
// Have 3 entry points:
// mermaid: './src/mermaid',
// e2e: './cypress/platform/viewer.js',
// 'bundle-test': './cypress/platform/bundle-test.js',
const getEntryPointsAndExtensions = (format) => {
return {
entryPoints: {
mermaid: './src/mermaid',
2022-09-13 07:22:51 +02:00
e2e: 'cypress/platform/viewer.js',
'bundle-test': 'cypress/platform/bundle-test.js',
2022-09-01 10:08:02 +02:00
},
outExtension: { '.js': format === 'iife' ? '.js' : '.esm.mjs' },
2022-09-13 07:22:51 +02:00
};
};
2022-09-01 10:08:02 +02:00
2022-09-13 07:22:51 +02:00
const generateHandler = (server) => {
return (req, res) => {
const options = {
hostname: server.host,
port: server.port,
path: req.url,
method: req.method,
headers: req.headers,
};
// Forward each incoming request to esbuild
const proxyReq = http.request(options, (proxyRes) => {
// If esbuild returns "not found", send a custom 404 page
if (proxyRes.statusCode === 404) {
if (!req.url.endsWith('.html')) {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>A custom 404 page</h1>');
return;
2022-09-01 10:08:02 +02:00
}
2022-09-13 07:22:51 +02:00
}
// Otherwise, forward the response from esbuild to the client
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});
// Forward the body of the request to esbuild
req.pipe(proxyReq, { end: true });
};
};
2022-09-01 10:08:02 +02:00
2022-09-13 07:22:51 +02:00
(async () => {
const iifeServer = await esbuild.serve(
{},
{
...iifeBuild({ minify: false, outfile: undefined, outdir: 'dist' }),
2022-09-13 07:22:51 +02:00
...getEntryPointsAndExtensions('iife'),
}
);
const esmServer = await esbuild.serve(
{},
{
...esmBuild({ minify: false, outfile: undefined, outdir: 'dist' }),
...getEntryPointsAndExtensions('esm'),
}
2022-09-13 07:22:51 +02:00
);
const app = express();
2022-09-01 10:08:02 +02:00
2022-09-13 07:22:51 +02:00
app.use(express.static('demos'));
app.use(express.static('cypress/platform'));
app.all('/mermaid.js', generateHandler(iifeServer));
app.all('/mermaid.esm.mjs', generateHandler(esmServer));
2022-09-14 11:03:38 +02:00
2022-09-20 18:43:49 +02:00
app.all('/e2e.esm.mjs', generateHandler(esmServer));
app.all('/bundle-test.esm.mjs', generateHandler(esmServer));
2022-09-14 11:03:38 +02:00
app.listen(9000, () => {
console.log(`Listening on http://localhost:9000`);
});
2022-09-13 07:22:51 +02:00
})();