generate-sri.js 1.64 KB
Newer Older
1
2
3
4
5
6
7
#!/usr/bin/env node

/*!
 * Script to generate SRI hashes for use in our docs.
 * Remember to use the same vendor files as the CDN ones,
 * otherwise the hashes won't match!
 *
8
9
 * Copyright 2017-2022 The Bootstrap Authors
 * Copyright 2017-2022 Twitter, Inc.
10
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
11
12
 */

13
14
'use strict'

XhmikosR's avatar
XhmikosR committed
15
const crypto = require('crypto')
16
17
18
19
20
21
const fs = require('fs')
const path = require('path')
const sh = require('shelljs')

sh.config.fatal = true

XhmikosR's avatar
XhmikosR committed
22
const configFile = path.join(__dirname, '../config.yml')
23
24
25

// Array of objects which holds the files to generate SRI hashes for.
// `file` is the path from the root folder
XhmikosR's avatar
XhmikosR committed
26
// `configPropertyName` is the config.yml variable's name of the file
27
28
29
30
31
const files = [
  {
    file: 'dist/css/bootstrap.min.css',
    configPropertyName: 'css_hash'
  },
Gaël Poupard's avatar
Gaël Poupard committed
32
33
34
35
  {
    file: 'dist/css/bootstrap.rtl.min.css',
    configPropertyName: 'css_rtl_hash'
  },
36
37
38
39
40
  {
    file: 'dist/js/bootstrap.min.js',
    configPropertyName: 'js_hash'
  },
  {
XhmikosR's avatar
XhmikosR committed
41
42
    file: 'dist/js/bootstrap.bundle.min.js',
    configPropertyName: 'js_bundle_hash'
43
44
  },
  {
GeoSot's avatar
initial    
GeoSot committed
45
46
    file: 'node_modules/@floating-ui/dom/dist/floating-ui.dom.umd.js',
    configPropertyName: 'floating_ui_hash'
47
48
49
  }
]

50
for (const file of files) {
XhmikosR's avatar
XhmikosR committed
51
52
53
  fs.readFile(file.file, 'utf8', (error, data) => {
    if (error) {
      throw error
54
55
    }

XhmikosR's avatar
XhmikosR committed
56
57
58
    const algo = 'sha384'
    const hash = crypto.createHash(algo).update(data, 'utf8').digest('base64')
    const integrity = `${algo}-${hash}`
59
60
61

    console.log(`${file.configPropertyName}: ${integrity}`)

62
    sh.sed('-i', new RegExp(`^(\\s+${file.configPropertyName}:\\s+["'])\\S*(["'])`), `$1${integrity}$2`, configFile)
63
  })
64
}