update-sri.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Update badge and CDN urls and subresource integrity hashes
  2. // Usage: node update-sri.js <VERSION> FILES...
  3. // To check SRI hashes, pass `check` as VERSION
  4. const fs = require("fs-extra");
  5. const sriToolbox = require("sri-toolbox");
  6. const version = process.argv[2];
  7. Promise.all(process.argv.slice(3).map(file =>
  8. fs.readFile(file, "utf8")
  9. .then(body => {
  10. // Replace size badge url
  11. // eslint-disable-next-line max-len
  12. body = body.replace(/(https:\/\/img\.badgesize\.io\/KaTeX\/KaTeX\/v)(?:.+)(\/dist\/katex\.min\.js\?compression=gzip)/g, `$1${version}$2`);
  13. // Replace CDN urls
  14. // 1 - url prefix: "http…/KaTeX/
  15. // 2 - opening quote: "
  16. // 3 - preserved suffix: /katex.min.js" integrity="…"
  17. // 4 - file name: katex.min.js
  18. // 5 - integrity opening quote: "
  19. // 6 - old hash: sha384-…
  20. // 7 - integrity hash algorithm: sha384
  21. // eslint-disable-next-line max-len
  22. const cdnRe = /((["'])https?:\/\/cdn\.jsdelivr\.net\/npm\/katex@)[^/"']+(\/([^"']+)\2(?:\s+integrity=(["'])(([^-]+)-[^"']+)\5)?)/g;
  23. const hashes = {};
  24. body = body.replace(cdnRe, (m, pre, oq1, post, file, oq2, old, algo) => {
  25. if (old) {
  26. hashes[old] = {file, algo};
  27. }
  28. return pre + version + post;
  29. });
  30. const promise = Promise.all(Object.keys(hashes).map(hash =>
  31. fs.readFile(hashes[hash].file, null)
  32. .then(data => {
  33. const newHash = sriToolbox.generate({
  34. algorithms: [hashes[hash].algo],
  35. }, data);
  36. body = body.replace(
  37. new RegExp(hash.replace(/\+/g, '\\+'), 'g'), newHash);
  38. if (version === "check" && hash !== newHash) {
  39. throw new Error("SRI mismatch! " +
  40. "Please run the release script again.");
  41. }
  42. })
  43. ));
  44. return version === "check" ? promise
  45. : promise.then(() => fs.writeFile(file, body));
  46. })
  47. )).then(() => process.exit(0), err => {
  48. // eslint-disable-next-line no-console
  49. console.error(err.stack);
  50. process.exit(1);
  51. });