keycloak_theme/src/bin/keycloakify/replacers/replaceImportsInCssCode.ts

55 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-06-09 09:15:16 +02:00
import type { BuildContext } from "../../shared/buildContext";
2024-06-19 22:41:25 +02:00
import { basenameOfTheKeycloakifyResourcesDir } from "../../shared/constants";
2022-08-16 14:41:06 +07:00
import { assert } from "tsafe/assert";
import { posix } from "path";
2022-08-16 14:41:06 +07:00
2024-06-09 09:15:16 +02:00
export type BuildContextLike = {
2022-08-16 14:41:06 +07:00
urlPathname: string | undefined;
};
2024-06-09 09:15:16 +02:00
assert<BuildContext extends BuildContextLike ? true : false>();
2022-08-16 14:41:06 +07:00
export function replaceImportsInCssCode(params: {
cssCode: string;
2024-06-19 22:41:25 +02:00
cssFileRelativeDirPath: string | undefined;
2024-07-07 18:45:14 +02:00
isAccountV3: boolean;
2024-06-09 09:15:16 +02:00
buildContext: BuildContextLike;
2024-05-20 15:48:51 +02:00
}): {
fixedCssCode: string;
2022-08-16 14:41:06 +07:00
} {
2024-07-07 18:45:14 +02:00
const { cssCode, cssFileRelativeDirPath, buildContext, isAccountV3 } = params;
const fixedCssCode = cssCode.replace(
/url\(["']?(\/[^/][^)"']+)["']?\)/g,
(match, assetFileAbsoluteUrlPathname) => {
if (buildContext.urlPathname !== undefined) {
if (!assetFileAbsoluteUrlPathname.startsWith(buildContext.urlPathname)) {
// NOTE: Should never happen
return match;
}
assetFileAbsoluteUrlPathname = assetFileAbsoluteUrlPathname.replace(
buildContext.urlPathname,
"/"
);
}
2024-06-19 22:41:25 +02:00
inline_style_in_html: {
if (cssFileRelativeDirPath !== undefined) {
break inline_style_in_html;
}
2024-07-07 18:45:14 +02:00
return `url(\${${!isAccountV3 ? "url.resourcesPath" : "resourceUrl"}}/${basenameOfTheKeycloakifyResourcesDir}${assetFileAbsoluteUrlPathname})`;
2024-06-19 22:41:25 +02:00
}
const assetFileRelativeUrlPathname = posix.relative(
2024-06-19 22:41:25 +02:00
cssFileRelativeDirPath.replace(/\\/g, "/"),
assetFileAbsoluteUrlPathname.replace(/^\//, "")
);
return `url(${assetFileRelativeUrlPathname})`;
}
);
2022-08-16 14:41:06 +07:00
return { fixedCssCode };
2022-08-16 14:41:06 +07:00
}