import {readFile,writeFile,mkdir,readdir,unlink} from 'node:fs/promises';
import {createHash} from 'node:crypto';
import {gzipSync} from 'node:zlib';
import {transform} from 'esbuild';
import path from 'node:path';
const root=path.resolve(import.meta.dirname,'..'),pub=path.join(root,'public');
await mkdir(path.join(pub,'optimized'),{recursive:true});
for(const file of await readdir(path.join(pub,'optimized')))if(/^[a-f0-9]{16}-(?:[a-z-]+\.(?:js|css))(?:\.gz)?$/.test(file))await unlink(path.join(pub,'optimized',file));
const assets={},mapping={};let before=0,after=0,compressed=0;
async function emit(name,source,loader,mime){
const result=await transform(source,{loader,minify:true,target:'es2022',legalComments:'inline'});
const hash=createHash('sha256').update(result.code).digest('hex').slice(0,16),url=`/optimized/${hash}-${name}`;
const gz=gzipSync(result.code,{level:9});
await writeFile(path.join(pub,url),result.code);await writeFile(path.join(pub,url+'.gz'),gz);
assets[url]={gzip:url+'.gz',mime};before+=Buffer.byteLength(source);after+=Buffer.byteLength(result.code);compressed+=gz.length;
return url;
}
mapping['/hub-libraries.js']=await emit('hub-libraries.js',await readFile(path.join(pub,'hub-libraries.js'),'utf8'),'js','text/javascript; charset=utf-8');
for(const name of ['app.js','hub.js','features-client.js','accounts-client.js','account-hub-client.js','people-client.js','profile-client.js','admin-client.js','site-shell.js']){
const source=(await readFile(path.join(pub,name),'utf8')).replace(/from ['"]\.\/hub-model\.js['"]/g,'from "/hub-model.js"').replace('from "/hub-libraries.js"','from "'+mapping['/hub-libraries.js']+'"');
mapping['/'+name]=await emit(name,source,'js','text/javascript; charset=utf-8');
}
const styles=['style.css','personality.css','ui-refinement.css','navigation.css','workspace.css','feature-ui.css','design-system.css'];
const css=(await Promise.all(styles.map(name=>readFile(path.join(pub,name),'utf8')))).join('\n');
const cssUrl=await emit('hub.css',css,'css','text/css; charset=utf-8');
mapping['/design-system.css']=await emit('design-system.css',await readFile(path.join(pub,'design-system.css'),'utf8'),'css','text/css; charset=utf-8');
let html=await readFile(path.join(pub,'index.html'),'utf8');
for(const [original,url] of Object.entries(mapping))html=html.replace(`src="${original}"`,`src="${url}"`);
for(const [index,name] of styles.entries())html=html.replace(``,index===0?``:'');
await writeFile(path.join(pub,'index.optimized.html'),html);
// Content-address page bundles so a preview update cannot reuse an older module.
for(const file of await readdir(pub)){
if(!file.endsWith('.html')||file==='ZeyadsStuffV2.html')continue;
const target=path.join(pub,file);let page=await readFile(target,'utf8');
for(const [original,url] of Object.entries(mapping)){
const name=original.slice(1).replaceAll('.', '\\.');
const attr=original.endsWith('.css')?'href':'src';
page=page.replace(new RegExp(attr+'="/(?:optimized/[a-f0-9]{16}-)?'+name+'"','g'),attr+'="'+url+'"');
}
await writeFile(target,page);
}
await writeFile(path.join(root,'src/optimized-assets.ts'),'// Generated by scripts/optimize-assets.mjs.\nexport const optimizedAssets:Record='+JSON.stringify(assets)+';\n');
console.log(`Hub assets: ${before} source bytes -> ${after} minified -> ${compressed} gzip bytes.`);