grid-apps-cmms/bin/bundler.mjs
2025-10-11 22:17:42 -04:00

80 lines
2.7 KiB
JavaScript

import fs from 'fs';
import path from 'path';
import { Buffer } from 'buffer';
const cfg = JSON.parse(fs.readFileSync(process.argv[2] || './bundle.config.json', 'utf8'));
// --- recursive directory walker (follows symlinks safely) ---
function* walk(dir, seen = new Set()) {
const real = fs.realpathSync(dir);
if (seen.has(real)) {
return;
}
seen.add(real);
for (const name of fs.readdirSync(dir)) {
const p = path.join(dir, name);
let st;
try { st = fs.statSync(p); } catch { continue; }
if (st.isDirectory()) yield* walk(p, seen);
else yield p;
}
}
// --- collect all files according to config ---
let entries = [];
for (const input of cfg.inputs) {
const root = input.root;
const prefix = input.prefix || '';
for (const file of walk(root)) {
const rel = path.relative(root, file).replace(/\\/g, '/');
const virt = prefix ? `${prefix}/${rel}` : rel;
entries.push({ file, virt });
}
}
// --- build header and data ---
const dataParts = [];
const entryMeta = [];
let offset = 0;
for (const { file, virt } of entries) {
const data = fs.readFileSync(file);
entryMeta.push({ virt, offset, length: data.length });
dataParts.push(data);
offset += data.length;
}
// temporary header without offsets to measure total size
let tempHeaderParts = [];
for (const { virt, offset, length } of entryMeta) {
const name = Buffer.from(virt, 'utf8');
const nlen = Buffer.alloc(2); nlen.writeUInt16LE(name.length);
const offb = Buffer.alloc(4); offb.writeUInt32LE(0); // placeholder
const lenb = Buffer.alloc(4); lenb.writeUInt32LE(length);
tempHeaderParts.push(nlen, name, offb, lenb);
}
const count = Buffer.alloc(4); count.writeUInt32LE(entries.length);
const tempHeader = Buffer.concat([count, ...tempHeaderParts]);
const headerSize = tempHeader.length; // true data offset base
// now rebuild header with correct absolute offsets
let headerParts = [];
for (const { virt, offset, length } of entryMeta) {
const name = Buffer.from(virt, 'utf8');
const nlen = Buffer.alloc(2); nlen.writeUInt16LE(name.length);
const offb = Buffer.alloc(4); offb.writeUInt32LE(headerSize + offset);
const lenb = Buffer.alloc(4); lenb.writeUInt32LE(length);
headerParts.push(nlen, name, offb, lenb);
console.log(virt);
}
const header = Buffer.concat([count, ...headerParts]);
const full = Buffer.concat([header, ...dataParts]);
// --- write final bundle ---
const outPath = cfg.outputs.bundle || './bundle.bin';
fs.mkdirSync(path.dirname(outPath), { recursive: true });
fs.writeFileSync(outPath, full); // ⚡ write raw binary
console.log(`✅ Bundled ${entries.length} files → ${outPath} (${full.length} bytes)`);