import {Express, Router} from "express"; import path from "path"; import config from "config"; import ApplicationComponent from "../ApplicationComponent"; import {logger} from "../Logger"; import "svelte/register"; import ViewEngine from "../frontend/ViewEngine"; import {readdirRecursively} from "../Utils"; import FileCache from "../utils/FileCache"; export default class FrontendToolsComponent extends ApplicationComponent { private readonly publicAssetsCache: FileCache = new FileCache(); public constructor( private readonly publicAssetsDir: string, private readonly viewEngine: ViewEngine, ) { super(); } public async start(app: Express): Promise { // Cache public assets if (config.get('asset_cache')) { logger.info('Caching assets from', this.publicAssetsDir, '...'); await readdirRecursively( this.publicAssetsDir, async file => await this.publicAssetsCache.load(file), ); } else { logger.info('Asset cache disabled.'); } // Setup express view engine this.viewEngine.setup(app, true); } public async stop(): Promise { await this.viewEngine.stop(); } public async handle(router: Router): Promise { router.use((req, res, next) => { res.locals.inlineAsset = (urlPath: string) => { return this.publicAssetsCache.getOrFail(path.join(this.publicAssetsDir, urlPath)); }; next(); }); } public async preCompileViews(watch: boolean): Promise { await this.viewEngine.preCompileAll(watch); } }