client.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. const browserify = require('browserify')
  2. const watchify = require('watchify')
  3. const { createWriteStream } = require('fs')
  4. const { readFile } = require('fs').promises
  5. const bundleResourceToFile = (inPath, outPath) => {
  6. return new Promise((resolve, reject) => {
  7. browserify(inPath).bundle()
  8. .once('error', (e) => reject(e))
  9. .pipe(createWriteStream(outPath))
  10. .once('finish', () => resolve())
  11. })
  12. }
  13. const bundleResource = (inPath) => {
  14. return new Promise((resolve, reject) => {
  15. browserify(inPath).bundle((err, buffer) => {
  16. if (err != null) {
  17. reject(err)
  18. return
  19. }
  20. resolve(buffer)
  21. })
  22. })
  23. }
  24. const watchResourceToFile = (inPath, outPath) => {
  25. const b = browserify({
  26. entries: [inPath],
  27. cache: {},
  28. packageCache: {},
  29. plugin: [watchify]
  30. })
  31. const bundle = () => {
  32. b.bundle()
  33. .once('error', (e) => {
  34. console.error(`Failed to bundle ${inPath} into ${outPath}.`)
  35. console.error(e)
  36. })
  37. .pipe(createWriteStream(outPath))
  38. .once('finish', () => console.log(`Bundled ${inPath} into ${outPath}.`))
  39. }
  40. b.on('update', bundle)
  41. bundle()
  42. }
  43. const main = async () => {
  44. if (process.argv[2] === 'build') {
  45. await bundleResourceToFile('client/main.js', 'static/karma.js')
  46. await bundleResourceToFile('context/main.js', 'static/context.js')
  47. } else if (process.argv[2] === 'check') {
  48. const expectedClient = await bundleResource('client/main.js')
  49. const expectedContext = await bundleResource('context/main.js')
  50. const actualClient = await readFile('static/karma.js')
  51. const actualContext = await readFile('static/context.js')
  52. if (Buffer.compare(expectedClient, actualClient) !== 0 || Buffer.compare(expectedContext, actualContext) !== 0) {
  53. // eslint-disable-next-line no-throw-literal
  54. throw 'Bundled client assets are outdated. Forgot to run "npm run build"?'
  55. }
  56. } else if (process.argv[2] === 'watch') {
  57. watchResourceToFile('client/main.js', 'static/karma.js')
  58. watchResourceToFile('context/main.js', 'static/context.js')
  59. } else {
  60. // eslint-disable-next-line no-throw-literal
  61. throw `Unknown command: ${process.argv[2]}`
  62. }
  63. }
  64. main().catch((err) => {
  65. console.error(err)
  66. process.exit(1)
  67. })