pinafore/bin/build-inline-script.js

61 lines
1.8 KiB
JavaScript
Raw Normal View History

2018-04-15 00:50:16 +02:00
#!/usr/bin/env node
import crypto from 'crypto'
import fs from 'fs'
import pify from 'pify'
import path from 'path'
import { rollup } from 'rollup'
import { terser } from 'rollup-plugin-terser'
import replace from 'rollup-plugin-replace'
import fromPairs from 'lodash-es/fromPairs'
import { themes } from '../routes/_static/themes'
2018-04-15 00:50:16 +02:00
const readFile = pify(fs.readFile.bind(fs))
const writeFile = pify(fs.writeFile.bind(fs))
const themeColors = fromPairs(themes.map(_ => ([_.name, _.color])))
2018-04-15 00:50:16 +02:00
async function main () {
let inlineScriptPath = path.join(__dirname, '../inline-script.js')
2018-04-15 00:50:16 +02:00
let bundle = await rollup({
input: inlineScriptPath,
plugins: [
replace({
'process.browser': true,
'process.env.THEME_COLORS': JSON.stringify(themeColors)
}),
terser({
mangle: true,
compress: true
})
]
})
let { code, map } = await bundle.generate({
format: 'iife',
sourcemap: true
})
let fullCode = `${code}\n//# sourceMappingURL=inline-script.js.map`
let checksum = crypto.createHash('sha256').update(fullCode).digest('base64')
2018-04-15 00:50:16 +02:00
let checksumFilepath = path.join(__dirname, '../inline-script-checksum.json')
await writeFile(checksumFilepath, JSON.stringify({ checksum }), 'utf8')
2018-04-15 00:50:16 +02:00
let html2xxFilepath = path.join(__dirname, '../templates/2xx.html')
let html2xxFile = await readFile(html2xxFilepath, 'utf8')
html2xxFile = html2xxFile.replace(
/<!-- insert inline script here -->[\s\S]+<!-- end insert inline script here -->/,
'<!-- insert inline script here --><script>' + fullCode + '</script><!-- end insert inline script here -->'
2018-04-15 00:50:16 +02:00
)
await writeFile(html2xxFilepath, html2xxFile, 'utf8')
await writeFile(path.resolve(__dirname, '../assets/inline-script.js.map'), map.toString(), 'utf8')
2018-04-15 00:50:16 +02:00
}
main().catch(err => {
console.error(err)
process.exit(1)
})