Files
Trilium/apps/server/src/routes/assets.ts

53 lines
2.3 KiB
TypeScript
Raw Normal View History

import { assetUrlFragment } from "../services/asset_path.js";
import path from "path";
import express from "express";
import { getResourceDir, isDev } from "../services/utils.js";
import type serveStatic from "serve-static";
2025-05-17 10:50:52 +03:00
import proxy from "express-http-proxy";
import { existsSync } from "fs";
const persistentCacheStatic = (root: string, options?: serveStatic.ServeStaticOptions<express.Response<unknown, Record<string, unknown>>>) => {
if (!isDev) {
2023-05-07 15:23:46 +02:00
options = {
2025-01-09 18:07:02 +02:00
maxAge: "1y",
2023-05-07 15:23:46 +02:00
...options
};
}
return express.static(root, options);
};
async function register(app: express.Application) {
const srcRoot = path.join(__dirname, "..");
const resourceDir = getResourceDir();
if (isDev) {
const publicUrl = process.env.TRILIUM_PUBLIC_SERVER;
if (!publicUrl) {
throw new Error("Missing TRILIUM_PUBLIC_SERVER");
}
app.use("/" + assetUrlFragment + `/@fs`, proxy(publicUrl, {
proxyReqPathResolver: (req) => "/" + assetUrlFragment + `/@fs` + req.url
}));
2024-12-14 10:10:10 +02:00
} else {
const publicDir = path.join(resourceDir, "public");
if (!existsSync(publicDir)) {
throw new Error("Public directory is missing at: " + path.resolve(publicDir));
}
app.use(`/${assetUrlFragment}/src`, persistentCacheStatic(path.join(publicDir, "src")));
app.use(`/${assetUrlFragment}/stylesheets`, persistentCacheStatic(path.join(publicDir, "stylesheets")));
app.use(`/${assetUrlFragment}/fonts`, persistentCacheStatic(path.join(publicDir, "fonts")));
app.use(`/${assetUrlFragment}/translations/`, persistentCacheStatic(path.join(publicDir, "translations")));
app.use(`/node_modules/`, persistentCacheStatic(path.join(publicDir, "node_modules")));
2024-12-14 10:10:10 +02:00
}
app.use(`/${assetUrlFragment}/images`, persistentCacheStatic(path.join(resourceDir, "assets", "images")));
app.use(`/${assetUrlFragment}/doc_notes`, persistentCacheStatic(path.join(resourceDir, "assets", "doc_notes")));
2025-01-09 18:07:02 +02:00
app.use(`/assets/vX/fonts`, express.static(path.join(srcRoot, "public/fonts")));
app.use(`/assets/vX/images`, express.static(path.join(srcRoot, "..", "images")));
2025-01-09 18:07:02 +02:00
app.use(`/assets/vX/stylesheets`, express.static(path.join(srcRoot, "public/stylesheets")));
2023-11-22 19:58:54 +01:00
}
2023-05-07 15:23:46 +02:00
export default {
2023-05-07 15:23:46 +02:00
register
};