All files index.ts

89.47% Statements 17/19
78.57% Branches 11/14
100% Functions 3/3
93.33% Lines 14/15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 321x 1x 1x         1x   4x 4x 2x   4x 4x 4x           1x 4x     4x         1x  
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;