generate-sri.mjs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env node
  2. 'use strict'
  3. import crypto from 'crypto'
  4. import { readFileSync, write, writeFileSync } from 'fs'
  5. import path from 'path'
  6. import { fileURLToPath } from 'node:url'
  7. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  8. const configFile = path.join(__dirname, '../_config.yml')
  9. const files = [
  10. {
  11. file: 'dist/css/tabler.min.css',
  12. configPropertyName: 'css_hash'
  13. },
  14. {
  15. file: 'dist/css/tabler.rtl.min.css',
  16. configPropertyName: 'css_rtl_hash'
  17. },
  18. {
  19. file: 'dist/css/tabler-flags.min.css',
  20. configPropertyName: 'css_flags_hash'
  21. },
  22. {
  23. file: 'dist/css/tabler-payments.min.css',
  24. configPropertyName: 'css_payments_hash'
  25. },
  26. {
  27. file: 'dist/css/tabler-social.min.css',
  28. configPropertyName: 'css_social_hash'
  29. },
  30. {
  31. file: 'dist/css/tabler-vendors.min.css',
  32. configPropertyName: 'css_vendors_hash'
  33. },
  34. {
  35. file: 'dist/js/tabler.min.js',
  36. configPropertyName: 'js_hash'
  37. },
  38. {
  39. file: 'dist/js/tabler.bundle.min.js',
  40. configPropertyName: 'js_bundle_hash'
  41. }
  42. ]
  43. files.forEach((file) => {
  44. const data = readFileSync(path.join(__dirname, '../core', file.file), 'utf8')
  45. const algo = 'sha384'
  46. const hash = crypto.createHash(algo).update(data, 'utf8').digest('base64')
  47. const integrity = `${algo}-${hash}`
  48. console.log(`${file.configPropertyName}: ${integrity}`)
  49. let config = readFileSync(configFile, 'utf8')
  50. const regex = new RegExp(`${file.configPropertyName}\\:\\s+("|')(\\S+)(\\1)`, 'gm')
  51. config = config.replace(regex, function() {
  52. return `${file.configPropertyName}: ${arguments[1]}${integrity}${arguments[3]}`
  53. })
  54. writeFileSync(configFile, config, 'utf8')
  55. })