2018-09-23 19:26:01 +00:00
|
|
|
import crypto from 'crypto'
|
|
|
|
import fs from 'fs'
|
2019-01-19 23:06:25 +00:00
|
|
|
import { promisify } from 'util'
|
2018-09-23 19:26:01 +00:00
|
|
|
import path from 'path'
|
2018-12-08 19:21:54 +00:00
|
|
|
import { rollup } from 'rollup'
|
|
|
|
import { terser } from 'rollup-plugin-terser'
|
2020-01-12 18:32:40 +00:00
|
|
|
import replace from '@rollup/plugin-replace'
|
2021-07-05 03:19:04 +00:00
|
|
|
import { themes } from '../src/routes/_static/themes.js'
|
|
|
|
import terserOptions from './terserOptions.js'
|
2018-09-23 19:26:01 +00:00
|
|
|
|
2021-07-05 03:19:04 +00:00
|
|
|
const __dirname = path.dirname(new URL(import.meta.url).pathname)
|
2019-01-19 23:06:25 +00:00
|
|
|
const writeFile = promisify(fs.writeFile)
|
2021-07-05 03:19:04 +00:00
|
|
|
const themeColors = Object.fromEntries(themes.map(_ => ([_.name, _.color])))
|
2018-12-08 19:21:54 +00:00
|
|
|
|
2018-12-18 01:21:29 +00:00
|
|
|
export async function buildInlineScript () {
|
2019-08-03 20:49:37 +00:00
|
|
|
const inlineScriptPath = path.join(__dirname, '../src/inline-script/inline-script.js')
|
2018-04-14 22:50:16 +00:00
|
|
|
|
2019-08-03 20:49:37 +00:00
|
|
|
const bundle = await rollup({
|
2018-12-08 19:21:54 +00:00
|
|
|
input: inlineScriptPath,
|
|
|
|
plugins: [
|
|
|
|
replace({
|
2021-05-15 20:28:31 +00:00
|
|
|
values: {
|
|
|
|
'process.browser': true,
|
|
|
|
'process.env.THEME_COLORS': JSON.stringify(themeColors)
|
|
|
|
},
|
|
|
|
preventAssignment: true
|
2018-12-08 19:21:54 +00:00
|
|
|
}),
|
2021-03-06 17:06:53 +00:00
|
|
|
// TODO: can't disable terser at all, it causes the CSP checksum to stop working
|
|
|
|
// because the HTML gets minified as some point so the checksums don't match.
|
|
|
|
terser({ ...terserOptions, mangle: !process.env.DEBUG })
|
2018-12-08 19:21:54 +00:00
|
|
|
]
|
|
|
|
})
|
2019-08-03 20:49:37 +00:00
|
|
|
const { output } = await bundle.generate({
|
2018-12-08 19:21:54 +00:00
|
|
|
format: 'iife',
|
|
|
|
sourcemap: true
|
|
|
|
})
|
|
|
|
|
2019-08-03 20:49:37 +00:00
|
|
|
const { code, map } = output[0]
|
2019-01-01 18:42:50 +00:00
|
|
|
|
2019-08-03 20:49:37 +00:00
|
|
|
const fullCode = `${code}//# sourceMappingURL=/inline-script.js.map`
|
2021-03-07 16:21:20 +00:00
|
|
|
const checksum = crypto.createHash('sha256').update(fullCode, 'utf8').digest('base64')
|
2018-04-14 22:50:16 +00:00
|
|
|
|
2019-01-26 18:14:15 +00:00
|
|
|
await writeFile(path.resolve(__dirname, '../src/inline-script/checksum.js'),
|
2021-07-05 03:19:04 +00:00
|
|
|
`export default ${JSON.stringify(checksum)}`, 'utf8')
|
2018-12-18 01:21:29 +00:00
|
|
|
await writeFile(path.resolve(__dirname, '../static/inline-script.js.map'),
|
|
|
|
map.toString(), 'utf8')
|
2018-12-08 19:21:54 +00:00
|
|
|
|
2018-12-18 01:21:29 +00:00
|
|
|
return '<script>' + fullCode + '</script>'
|
2018-04-14 22:50:16 +00:00
|
|
|
}
|