import axios from "axios";
import SHA384 from "crypto-js/sha384";
import Base64 from "crypto-js/enc-base64";
type cdnType = "css" | "js";
type algoType = "sha384";
const intergrityGen = async (url: string, type?: cdnType) => {
// TODO: support more hashing algorithm
const algo: algoType = "sha384";
if (!type) {
type = url.endsWith("css") ? "css" : url.endsWith("js") ? "js" : undefined;
}
Iif (type === undefined) throw new Error("must specify type for cdn (css/js)");
const hash = await axios.get(url).then(d => Base64.stringify(SHA384(d.data)));
return {
hash: hash,
html: template(type, url, hash, algo)
};
};
const template = (type: cdnType, url: string, hash: string, algo: algoType) => {
Iif (type !== "css" && type !== "js")
throw new Error("must specify type for cdn (css/js)");
return type === "css"
? `<link rel="stylesheet" href="${url}" integrity="${algo}-${hash}" crossorigin="anonymous">`
: `<script src="${url}" integrity="${algo}-${hash}" crossorigin="anonymous"></script>`;
};
export default intergrityGen;
|