keycloak_theme/src/bin/shared/generateKcGenTs.ts

73 lines
2.5 KiB
TypeScript
Raw Normal View History

import { assert } from "tsafe/assert";
2024-06-09 09:15:16 +02:00
import type { BuildContext } from "./buildContext";
import { getThemeSrcDirPath } from "./getThemeSrcDirPath";
import * as fs from "fs/promises";
import { join as pathJoin } from "path";
2024-06-09 10:28:06 +02:00
import { existsAsync } from "../tools/fs.existsAsync";
2024-06-09 09:15:16 +02:00
export type BuildContextLike = {
projectDirPath: string;
themeNames: string[];
environmentVariables: { name: string; default: string }[];
};
2024-06-09 09:15:16 +02:00
assert<BuildContext extends BuildContextLike ? true : false>();
export async function generateKcGenTs(params: {
2024-06-09 09:15:16 +02:00
buildContext: BuildContextLike;
}): Promise<void> {
2024-06-09 09:15:16 +02:00
const { buildContext } = params;
const { themeSrcDirPath } = getThemeSrcDirPath({
2024-06-09 09:15:16 +02:00
projectDirPath: buildContext.projectDirPath
});
2024-06-09 10:28:06 +02:00
const filePath = pathJoin(themeSrcDirPath, "kc.gen.ts");
const currentContent = (await existsAsync(filePath))
? await fs.readFile(filePath)
: undefined;
const newContent = Buffer.from(
[
`/* prettier-ignore-start */`,
``,
`/* eslint-disable */`,
``,
`// @ts-nocheck`,
``,
`// noinspection JSUnusedGlobalSymbols`,
``,
`// This file is auto-generated by Keycloakify`,
``,
`export type ThemeName = ${buildContext.themeNames.map(themeName => `"${themeName}"`).join(" | ")};`,
``,
`export const themeNames: ThemeName[] = [${buildContext.themeNames.map(themeName => `"${themeName}"`).join(", ")}];`,
``,
`export type KcEnvName = ${buildContext.environmentVariables.length === 0 ? "never" : buildContext.environmentVariables.map(({ name }) => `"${name}"`).join(" | ")};`,
``,
2024-06-11 20:50:11 +02:00
`export const kcEnvNames: KcEnvName[] = [${buildContext.environmentVariables.map(({ name }) => `"${name}"`).join(", ")}];`,
2024-06-09 10:28:06 +02:00
``,
`export const kcEnvDefaults: Record<KcEnvName, string> = ${JSON.stringify(
Object.fromEntries(
buildContext.environmentVariables.map(
({ name, default: defaultValue }) => [name, defaultValue]
)
),
null,
2
)};`,
``,
2024-06-09 15:04:31 +02:00
`/* prettier-ignore-end */`,
``
2024-06-09 10:28:06 +02:00
].join("\n"),
"utf8"
);
2024-06-09 10:28:06 +02:00
if (currentContent !== undefined && currentContent.equals(newContent)) {
return;
}
await fs.writeFile(filePath, newContent);
}