webpack.conf.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. const { modifyWebpackConfig, shallowMerge, defaultOptions } = require('@gera2ld/plaid');
  2. const { isProd } = require('@gera2ld/plaid/util');
  3. const webpack = require('webpack');
  4. const TerserPlugin = isProd && require('terser-webpack-plugin');
  5. const deepmerge = isProd && require('deepmerge');
  6. const { ListBackgroundScriptsPlugin } = require('./manifest-helper');
  7. const { addWrapperWithGlobals, getUniqIdB64 } = require('./webpack-util');
  8. const ProtectWebpackBootstrapPlugin = require('./webpack-protect-bootstrap-plugin');
  9. const projectConfig = require('./plaid.conf');
  10. const mergedConfig = shallowMerge(defaultOptions, projectConfig);
  11. // Avoiding collisions with globals of a content-mode userscript
  12. const INIT_FUNC_NAME = `Violentmonkey:${getUniqIdB64()}`;
  13. const VAULT_ID = '__VAULT_ID__';
  14. const HANDSHAKE_ID = '__HANDSHAKE_ID__';
  15. // eslint-disable-next-line import/no-dynamic-require
  16. const VM_VER = require(`${defaultOptions.distDir}/manifest.json`).version;
  17. const WEBPACK_OPTS = {
  18. node: {
  19. global: false,
  20. process: false,
  21. setImmediate: false,
  22. },
  23. performance: {
  24. maxEntrypointSize: 1e6,
  25. maxAssetSize: 0.5e6,
  26. },
  27. };
  28. const MIN_OPTS = {
  29. cache: true,
  30. parallel: true,
  31. sourceMap: true,
  32. terserOptions: {
  33. compress: {
  34. // `terser` often inlines big one-time functions inside a small "hot" function
  35. reduce_funcs: false,
  36. reduce_vars: false,
  37. },
  38. output: {
  39. ascii_only: true,
  40. },
  41. },
  42. };
  43. const MIN_OPTS_PUBLIC = isProd && {
  44. chunkFilter: ({ name }) => name.startsWith('public/'),
  45. ...MIN_OPTS,
  46. };
  47. const MIN_OPTS_MAIN = isProd && deepmerge.all([{}, MIN_OPTS, {
  48. chunkFilter: ({ name }) => !name.startsWith('public/'),
  49. terserOptions: {
  50. compress: {
  51. ecma: 8, // ES2017 Object.entries and so on
  52. passes: 2, // necessary now since we removed plaid's minimizer
  53. unsafe_arrows: true, // it's 'safe' since we don't rely on function prototypes
  54. },
  55. },
  56. }]);
  57. const pickEnvs = (items) => {
  58. return Object.assign({}, ...items.map(x => ({
  59. [`process.env.${x.key}`]: JSON.stringify(
  60. 'val' in x ? x.val
  61. : process.env[x.key] ?? x.def,
  62. ),
  63. })));
  64. };
  65. const defsObj = {
  66. ...pickEnvs([
  67. { key: 'DEBUG', def: false },
  68. { key: 'VM_VER', val: VM_VER },
  69. { key: 'SYNC_GOOGLE_CLIENT_ID' },
  70. { key: 'SYNC_GOOGLE_CLIENT_SECRET' },
  71. { key: 'SYNC_ONEDRIVE_CLIENT_ID' },
  72. { key: 'SYNC_ONEDRIVE_CLIENT_SECRET' },
  73. ]),
  74. 'process.env.INIT_FUNC_NAME': JSON.stringify(INIT_FUNC_NAME),
  75. 'process.env.VAULT_ID': VAULT_ID,
  76. 'process.env.HANDSHAKE_ID': HANDSHAKE_ID,
  77. 'process.env.HANDSHAKE_ACK': '1',
  78. };
  79. // avoid running webpack bootstrap in a potentially hacked environment
  80. // after documentElement was replaced which triggered reinjection of content scripts
  81. const skipReinjectionHeader = `if (window['${INIT_FUNC_NAME}'] !== 1)`;
  82. const modify = (page, entry, init) => modifyWebpackConfig(
  83. (config) => {
  84. Object.assign(config, WEBPACK_OPTS);
  85. config.plugins.push(new webpack.DefinePlugin({
  86. ...defsObj,
  87. // Conditional compilation to remove unsafe and unused stuff from `injected`
  88. 'process.env.IS_INJECTED': JSON.stringify(/injected/.test(page) && page),
  89. }));
  90. config.optimization.minimizer.find((m, i, arr) => (
  91. m.constructor.name === 'TerserPlugin' && arr.splice(i, 1)
  92. ));
  93. config.optimization.minimizer.push(...!isProd ? [] : [
  94. new TerserPlugin(MIN_OPTS_PUBLIC),
  95. new TerserPlugin(MIN_OPTS_MAIN),
  96. ]);
  97. if (!entry) init = page;
  98. if (init) init(config);
  99. return config;
  100. }, {
  101. projectConfig: {
  102. ...mergedConfig,
  103. ...entry && { pages: { [page]: { entry } } },
  104. },
  105. },
  106. );
  107. module.exports = Promise.all([
  108. modify((config) => {
  109. addWrapperWithGlobals('common', config, defsObj, getGlobals => ({
  110. header: () => `{ ${getGlobals()}`,
  111. footer: '}',
  112. test: /^(?!injected|public).*\.js$/,
  113. }));
  114. config.plugins.push(new ListBackgroundScriptsPlugin({
  115. minify: false, // keeping readable
  116. }));
  117. }),
  118. modify('injected', './src/injected', (config) => {
  119. config.plugins.push(new ProtectWebpackBootstrapPlugin());
  120. addWrapperWithGlobals('injected/content', config, defsObj, getGlobals => ({
  121. header: () => `${skipReinjectionHeader} { ${getGlobals()}`,
  122. footer: '}',
  123. }));
  124. }),
  125. modify('injected-web', './src/injected/web', (config) => {
  126. // TODO: replace WebPack's Object.*, .call(), .apply() with safe calls
  127. config.output.libraryTarget = 'commonjs2';
  128. config.plugins.push(new ProtectWebpackBootstrapPlugin());
  129. addWrapperWithGlobals('injected/web', config, defsObj, getGlobals => ({
  130. header: () => `${skipReinjectionHeader}
  131. window['${INIT_FUNC_NAME}'] = function (IS_FIREFOX,${HANDSHAKE_ID},${VAULT_ID}) {
  132. const module = { __proto__: null };
  133. ${getGlobals()}`,
  134. footer: `
  135. const { exports } = module;
  136. return exports.__esModule ? exports.default : exports;
  137. };0;`,
  138. }));
  139. }),
  140. ]);