jmtp.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * Copyright (c) 2015-present, Waysact Pty Ltd
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. var Template = require('webpack/lib/Template');
  8. var util = require('./util');
  9. function WebIntegrityJsonpMainTemplatePlugin(sriPlugin, compilation) {
  10. this.sriPlugin = sriPlugin;
  11. this.compilation = compilation;
  12. }
  13. function addSriHashes(plugin, chunk, source) {
  14. var allChunks = util.findChunks(chunk);
  15. if (allChunks.size > 0) {
  16. return (Template.asString || plugin.asString)([
  17. source,
  18. 'var sriHashes = ' +
  19. JSON.stringify(
  20. Array.from(allChunks).reduce(function chunkIdReducer(
  21. sriHashes,
  22. depChunk
  23. ) {
  24. if (chunk !== depChunk) {
  25. // eslint-disable-next-line no-param-reassign
  26. sriHashes[depChunk.id] = util.makePlaceholder(depChunk.id);
  27. }
  28. return sriHashes;
  29. },
  30. {})
  31. ) +
  32. ';'
  33. ]);
  34. }
  35. return source;
  36. }
  37. WebIntegrityJsonpMainTemplatePlugin.prototype.apply = function apply(
  38. mainTemplate
  39. ) {
  40. var self = this;
  41. /*
  42. * Patch jsonp-script code to add the integrity attribute.
  43. */
  44. function jsonpScriptPlugin(source) {
  45. if (!mainTemplate.outputOptions.crossOriginLoading) {
  46. self.sriPlugin.error(
  47. self.compilation,
  48. 'webpack option output.crossOriginLoading not set, code splitting will not work!'
  49. );
  50. }
  51. return (Template.asString || this.asString)([
  52. source,
  53. 'script.integrity = sriHashes[chunkId];',
  54. 'script.crossOrigin = ' + JSON.stringify(mainTemplate.outputOptions.crossOriginLoading) + ';',
  55. ]);
  56. }
  57. /*
  58. * Patch local-vars code to add a mapping from chunk ID to SRIs.
  59. * Since SRIs haven't been computed at this point, we're using
  60. * magic placeholders for SRI values and going to replace them
  61. * later.
  62. */
  63. function localVarsPlugin(source, chunk) {
  64. return addSriHashes(this, chunk, source);
  65. }
  66. if (mainTemplate.hooks) {
  67. mainTemplate.hooks.jsonpScript.tap('SriPlugin', jsonpScriptPlugin);
  68. mainTemplate.hooks.localVars.tap('SriPlugin', localVarsPlugin);
  69. } else {
  70. mainTemplate.plugin('jsonp-script', jsonpScriptPlugin);
  71. mainTemplate.plugin('local-vars', localVarsPlugin);
  72. }
  73. };
  74. module.exports = WebIntegrityJsonpMainTemplatePlugin;