72 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-01-30 00:06:17 +01:00
import * as fs from "fs";
import { assert } from "tsafe";
import type { Equals } from "tsafe";
import { z } from "zod";
2024-01-30 06:37:49 +01:00
import { join as pathJoin } from "path";
import { resolvedViteConfigJsonBasename } from "../../constants";
import type { OptionalIfCanBeUndefined } from "../../tools/OptionalIfCanBeUndefined";
2024-01-30 00:06:17 +01:00
2024-01-30 06:04:05 +01:00
export type ResolvedViteConfig = {
2024-01-30 05:54:36 +01:00
buildDir: string;
publicDir: string;
assetsDir: string;
2024-01-30 00:06:17 +01:00
urlPathname: string | undefined;
};
2024-01-30 06:04:05 +01:00
const zResolvedViteConfig = z.object({
2024-01-30 05:54:36 +01:00
"buildDir": z.string(),
"publicDir": z.string(),
"assetsDir": z.string(),
2024-01-30 00:06:17 +01:00
"urlPathname": z.string().optional()
});
{
2024-01-30 06:04:05 +01:00
type Got = ReturnType<(typeof zResolvedViteConfig)["parse"]>;
type Expected = OptionalIfCanBeUndefined<ResolvedViteConfig>;
2024-01-30 00:06:17 +01:00
assert<Equals<Got, Expected>>();
}
export function readResolvedViteConfig(params: { cacheDirPath: string }): {
resolvedViteConfig: ResolvedViteConfig | undefined;
} {
const { cacheDirPath } = params;
2024-01-30 05:54:36 +01:00
const resolvedViteConfigJsonFilePath = pathJoin(cacheDirPath, resolvedViteConfigJsonBasename);
2024-01-30 05:54:36 +01:00
if (!fs.existsSync(resolvedViteConfigJsonFilePath)) {
return { "resolvedViteConfig": undefined };
2024-01-30 00:06:17 +01:00
}
2024-01-30 06:04:05 +01:00
const resolvedViteConfig = (() => {
if (!fs.existsSync(resolvedViteConfigJsonFilePath)) {
2024-01-30 05:54:36 +01:00
throw new Error("Missing Keycloakify Vite plugin output.");
2024-01-30 00:06:17 +01:00
}
2024-01-30 06:04:05 +01:00
let out: ResolvedViteConfig;
2024-01-30 00:06:17 +01:00
try {
2024-01-30 06:04:05 +01:00
out = JSON.parse(fs.readFileSync(resolvedViteConfigJsonFilePath).toString("utf8"));
2024-01-30 00:06:17 +01:00
} catch {
throw new Error("The output of the Keycloakify Vite plugin is not a valid JSON.");
}
try {
2024-01-30 06:04:05 +01:00
const zodParseReturn = zResolvedViteConfig.parse(out);
2024-01-30 00:06:17 +01:00
// So that objectKeys from tsafe return the expected result no matter what.
Object.keys(zodParseReturn)
.filter(key => !(key in out))
.forEach(key => {
delete (out as any)[key];
});
} catch {
throw new Error("The output of the Keycloakify Vite plugin do not match the expected schema.");
}
return out;
})();
2024-01-30 06:04:05 +01:00
return { resolvedViteConfig };
2024-01-30 05:54:36 +01:00
}