MC/website/scripts/build.mjs

7 lines
1.6 KiB
JavaScript

import {readFileSync,writeFileSync,readdirSync,statSync,mkdirSync,existsSync,rmSync,cpSync} from 'node:fs';import path from 'node:path';import {fileURLToPath} from 'node:url';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'),web=path.join(root,'web'),dist=path.join(root,'dist');
const assets={};const types={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.webp':'image/webp','.svg':'image/svg+xml'};
function collect(directory){for(const entry of readdirSync(directory)){const p=path.join(directory,entry);if(statSync(p).isDirectory())collect(p);else{const type=types[path.extname(entry)];if(!type)throw Error('Unexpected asset: '+entry);assets['/'+path.relative(web,p).split(path.sep).join('/')]=[type,readFileSync(p).toString('base64')]}}}collect(web);
let api=readFileSync(path.join(root,'worker/feed-api.mjs'),'utf8').replace(/export /g,'');let runtime=readFileSync(path.join(root,'worker/runtime.mjs'),'utf8').replace("import {handleFeed} from './feed-api.mjs';",'');
if(existsSync(dist)){const resolved=path.resolve(dist);if(resolved!==path.join(root,'dist'))throw Error('Invalid dist directory');rmSync(resolved,{recursive:true,force:true})}
mkdirSync(path.join(dist,'server'),{recursive:true});mkdirSync(path.join(dist,'.openai'),{recursive:true});writeFileSync(path.join(dist,'server/index.js'),'const ASSET_DATA='+JSON.stringify(assets)+';\n'+api+'\n'+runtime);cpSync(path.join(root,'.openai/hosting.json'),path.join(dist,'.openai/hosting.json'));console.log('Built Worker with',Object.keys(assets).length,'embedded website assets');