Files
Robot-Clash/build-web.mjs

78 lines
4.2 KiB
JavaScript
Raw Permalink Normal View History

2026-11-13 00:41:54 +01:00
// Builds release/robotclash.html: the whole game in ONE file. Local <script src> and
// <link rel="stylesheet"> are inlined, every file under game/assets is embedded as a data: URI
// (window.KIT_ASSETS, read by Kit.asset). Works by double-click (file://) and on any host
// (itch.io, webspace). From _Tools\Library\web\template.
// node build-web.mjs
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = path.dirname(fileURLToPath(import.meta.url));
const game = path.join(root, 'game');
const MIME = {
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif',
'.svg': 'image/svg+xml', '.mp3': 'audio/mpeg', '.ogg': 'audio/ogg', '.wav': 'audio/wav',
'.ttf': 'font/ttf', '.otf': 'font/otf', '.woff2': 'font/woff2', '.json': 'application/json',
};
function walk(dir) {
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir, { withFileTypes: true }).flatMap(e =>
e.isDirectory() ? walk(path.join(dir, e.name)) : [path.join(dir, e.name)]);
}
const assets = {};
let bytes = 0;
for (const file of walk(path.join(game, 'assets'))) {
const mime = MIME[path.extname(file).toLowerCase()];
if (!mime) continue;
const rel = path.relative(game, file).split(path.sep).join('/');
const buf = fs.readFileSync(file);
bytes += buf.length;
assets[rel] = `data:${mime};base64,${buf.toString('base64')}`;
}
let html = fs.readFileSync(path.join(game, 'index.html'), 'utf8');
const local = p => !/^(https?:)?\/\//.test(p) && !p.startsWith('data:');
// "</script" inside an inlined file would end the tag early
const safe = s => s.replace(/<\/script/gi, '<\\/script');
html = html.replace(/<link\s+rel="stylesheet"\s+href="([^"]+)"\s*\/?>/g, (m, p) =>
local(p) ? `<style>\n${fs.readFileSync(path.join(game, p), 'utf8')}\n</style>` : m);
// optional: run each own script through terser (mangle locals, compress) -> harder to read.
// Enabled with RC_OBFUSCATE=1 (build.ps1 -Obfuscate). vendor/three.min.js is already minified -> skip.
const obf = process.env.RC_OBFUSCATE === '1';
let terser = null;
if (obf) {
try { terser = await import('terser'); }
catch { console.error('RC_OBFUSCATE=1 but terser is missing - run: npm install'); process.exit(1); }
}
const minify = async (code, name) => {
if (!terser || /vendor\/three/.test(name)) return code;
const r = await terser.minify(code, { compress: true, mangle: true, format: { comments: false } });
if (r.error) { console.error(`terser failed on ${name}:`, r.error); process.exit(1); }
return r.code;
};
const scriptJobs = [];
html = html.replace(/<script\s+src="([^"]+)"\s*><\/script>/g, (m, p) => {
if (!local(p)) return m;
const token = `\u0000SCRIPT${scriptJobs.length}\u0000`;
scriptJobs.push(minify(fs.readFileSync(path.join(game, p), 'utf8'), p).then(code => [token, `<script>\n${safe(code)}\n</script>`]));
return token;
});
for (const [token, tag] of await Promise.all(scriptJobs)) html = html.replace(token, () => tag);
2026-11-13 00:41:54 +01:00
// static references in CSS / HTML attributes
html = html.replace(/url\((['"]?)(assets\/[^'")]+)\1\)/g, (m, q, p) => (assets[p] ? `url('${assets[p]}')` : m));
html = html.replace(/(src|href)="(assets\/[^"]+)"/g, (m, a, p) => (assets[p] ? `${a}="${assets[p]}"` : m));
// everything the scripts load at runtime: must come before the first other <script>
2026-11-15 20:05:02 +01:00
// build stamp: identifies this exact release, so a leaked copy can be traced back
const BUILD = new Date().toISOString().slice(0, 16).replace('T', '.').replace(/[:-]/g, '');
html = html.replace('<script>', () => `<script>window.RC_BUILD = ${JSON.stringify(BUILD)};window.KIT_ASSETS = ${JSON.stringify(assets)};</script>\n<script>`);
2026-11-13 00:41:54 +01:00
2026-11-15 20:05:02 +01:00
html = html.replace('<head>', () => '<head><!-- Robot Clash (c) 2026 Michael Media | https://michael-media.de | build ' + BUILD + ' | Alle Rechte vorbehalten. Weitergabe oder Neuveroeffentlichung dieser Datei ist nicht gestattet. -->');
2026-11-13 00:41:54 +01:00
const out = path.join(root, 'release', 'robotclash.html');
fs.mkdirSync(path.dirname(out), { recursive: true });
fs.writeFileSync(out, html);
const mb = n => (n / 1024 / 1024).toFixed(1);
2026-11-15 20:05:02 +01:00
console.log(`Fertig: ${out} (${mb(fs.statSync(out).size)} MB, ${Object.keys(assets).length} Assets, ${mb(bytes)} MB roh, Build ${BUILD})`);