keycloak_theme/src/bin/build-keycloak-theme/replaceImportFromStatic.ts

89 lines
2.1 KiB
TypeScript
Raw Normal View History

2021-02-21 17:38:59 +01:00
import * as crypto from "crypto";
export function replaceImportFromStaticInJsCode(
params: {
ftlValuesGlobalName: string;
jsCode: string;
}
): { fixedJsCode: string; } {
const { jsCode, ftlValuesGlobalName } = params;
const fixedJsCode = jsCode!.replace(
2021-03-22 19:40:38 +01:00
/ [^ ]+"static\//g,
` window.${ftlValuesGlobalName}.url.resourcesPath + "/build/static/`
2021-02-21 17:38:59 +01:00
);
return { fixedJsCode };
}
export function replaceImportFromStaticInCssCode(
params: {
cssCode: string;
}
): {
fixedCssCode: string;
cssGlobalsToDefine: Record<string, string>;
} {
const { cssCode } = params;
const cssGlobalsToDefine: Record<string, string> = {};
2021-03-22 07:21:31 +01:00
new Set(cssCode.match(/url\(\/[^)]+\)[^;}]*/g) ?? [])
2021-02-21 17:38:59 +01:00
.forEach(match =>
cssGlobalsToDefine[
"url" + crypto
.createHash("sha256")
.update(match)
.digest("hex")
.substring(0, 15)
] = match
);
let fixedCssCode = cssCode;
Object.keys(cssGlobalsToDefine).forEach(
cssVariableName =>
//NOTE: split/join pattern ~ replace all
fixedCssCode =
fixedCssCode.split(cssGlobalsToDefine[cssVariableName])
.join(`var(--${cssVariableName})`)
);
return { fixedCssCode, cssGlobalsToDefine };
}
export function generateCssCodeToDefineGlobals(
params: {
cssGlobalsToDefine: Record<string, string>;
2021-03-22 19:40:38 +01:00
urlPathname: string;
2021-02-21 17:38:59 +01:00
}
): {
cssCodeToPrependInHead: string;
} {
2021-03-22 19:40:38 +01:00
const { cssGlobalsToDefine, urlPathname } = params;
2021-02-21 17:38:59 +01:00
return {
"cssCodeToPrependInHead": [
":root {",
...Object.keys(cssGlobalsToDefine)
.map(cssVariableName => [
`--${cssVariableName}:`,
2021-03-22 07:21:31 +01:00
cssGlobalsToDefine[cssVariableName]
2021-03-22 19:40:38 +01:00
.replace(new RegExp(`url\\(${urlPathname.replace(/\//g,"\\/")}`, "g"),"url(${url.resourcesPath}/build/")
2021-02-21 17:38:59 +01:00
].join(" "))
2021-02-21 18:05:26 +01:00
.map(line => ` ${line};`),
2021-02-21 17:38:59 +01:00
"}"
].join("\n")
};
}