Files

119 lines
3.8 KiB
TypeScript

import { readFile } from "node:fs/promises";
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { defineConfig, type Plugin } from "vite";
import { viteModuleInventoryPlugin } from "./scripts/lib/vite-module-inventory.ts";
const RUNTIME_PROFILES = Object.freeze([
"local",
"development",
"staging",
"production",
] as const);
type RuntimeProfile = (typeof RUNTIME_PROFILES)[number];
/**
* §6.1. One sub-path, declared once.
*
* VITE_ROUTER_BASE_PATH drives Vite assets and the optional Service Worker.
* Memento's current beta shell does not need React Router, but retaining one
* deployment base contract keeps the derived application compatible with the
* frontend foundation.
*/
function routerBasePath(environment: NodeJS.ProcessEnv): string {
const declared = environment["VITE_ROUTER_BASE_PATH"];
if (declared === undefined || declared === "") return "/";
if (!declared.startsWith("/") || !declared.endsWith("/")) {
throw new Error(
`VITE_ROUTER_BASE_PATH must start and end with "/"; received ${declared}`,
);
}
return declared;
}
function runtimeProfile(environment: NodeJS.ProcessEnv): RuntimeProfile {
const declared = environment["APP_PROFILE"] ?? "local";
if ((RUNTIME_PROFILES as readonly string[]).includes(declared)) {
return declared as RuntimeProfile;
}
throw new Error(
`APP_PROFILE must be one of ${RUNTIME_PROFILES.join(", ")}; received ${declared}`,
);
}
/**
* Vite dev normally copies public/config.json, which would make every local
* dev server run the local profile. This middleware serves config/runtime
* directly so the runtime profile also works without a production build:
*
* pnpm dev -> local profile -> mock gateway
* pnpm dev:api -> development profile -> real API gateway
*
* RUNTIME_API_BASE_URL may replace only the endpoint. No secret is accepted.
*
* Vite's dev server does not build service-worker.js, so configureServer
* disables registration for the live dev server only. Profile builds keep the
* checked-in runtime capability setting and still produce the PWA worker.
*/
function mementoRuntimeProfilePlugin(
environment: NodeJS.ProcessEnv,
): Plugin {
const profile = runtimeProfile(environment);
return {
name: "memento-runtime-profile",
configureServer(server) {
server.middlewares.use(async (request, response, next) => {
const pathname = request.url?.split("?", 1)[0];
if (pathname !== "/config.json" || request.method !== "GET") {
next();
return;
}
try {
const source = JSON.parse(
await readFile(`config/runtime/${profile}.json`, "utf8"),
) as Record<string, unknown>;
const apiOverride = environment["RUNTIME_API_BASE_URL"];
if (apiOverride) source["API_BASE_URL"] = apiOverride;
const capabilityOverrides =
source["CAPABILITY_OVERRIDES"] &&
typeof source["CAPABILITY_OVERRIDES"] === "object" &&
!Array.isArray(source["CAPABILITY_OVERRIDES"])
? (source["CAPABILITY_OVERRIDES"] as Record<string, unknown>)
: {};
source["CAPABILITY_OVERRIDES"] = {
...capabilityOverrides,
SERVICE_WORKER: "DISABLED",
};
response.statusCode = 200;
response.setHeader("Content-Type", "application/json; charset=utf-8");
response.setHeader("Cache-Control", "no-store");
response.end(`${JSON.stringify(source, null, 2)}\n`);
} catch (error) {
next(error as Error);
}
});
},
};
}
export default defineConfig({
base: routerBasePath(process.env),
plugins: [
mementoRuntimeProfilePlugin(process.env),
react(),
tailwindcss(),
viteModuleInventoryPlugin(),
],
build: {
manifest: true,
sourcemap: false,
},
});