ReadFileCompileAsyncWasmPlugin.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { WEBASSEMBLY_MODULE_TYPE_ASYNC } = require("../ModuleTypeConstants");
  7. const RuntimeGlobals = require("../RuntimeGlobals");
  8. const Template = require("../Template");
  9. const AsyncWasmCompileRuntimeModule = require("../wasm-async/AsyncWasmCompileRuntimeModule");
  10. const AsyncWasmLoadingRuntimeModule = require("../wasm-async/AsyncWasmLoadingRuntimeModule");
  11. /** @typedef {import("../Chunk")} Chunk */
  12. /** @typedef {import("../Compiler")} Compiler */
  13. /**
  14. * Defines the read file compile async wasm plugin options type used by this module.
  15. * @typedef {object} ReadFileCompileAsyncWasmPluginOptions
  16. * @property {boolean=} import use import?
  17. */
  18. const PLUGIN_NAME = "ReadFileCompileAsyncWasmPlugin";
  19. class ReadFileCompileAsyncWasmPlugin {
  20. /**
  21. * Creates an instance of ReadFileCompileAsyncWasmPlugin.
  22. * @param {ReadFileCompileAsyncWasmPluginOptions=} options options object
  23. */
  24. constructor({ import: useImport = false } = {}) {
  25. /** @type {boolean} */
  26. this._import = useImport;
  27. }
  28. /**
  29. * Applies the plugin by registering its hooks on the compiler.
  30. * @param {Compiler} compiler the compiler instance
  31. * @returns {void}
  32. */
  33. apply(compiler) {
  34. compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
  35. const globalWasmLoading = compilation.outputOptions.wasmLoading;
  36. /**
  37. * Checks whether this read file compile async wasm plugin is enabled for chunk.
  38. * @param {Chunk} chunk chunk
  39. * @returns {boolean} true, if wasm loading is enabled for the chunk
  40. */
  41. const isEnabledForChunk = (chunk) => {
  42. const options = chunk.getEntryOptions();
  43. const wasmLoading =
  44. options && options.wasmLoading !== undefined
  45. ? options.wasmLoading
  46. : globalWasmLoading;
  47. return wasmLoading === "async-node";
  48. };
  49. /**
  50. * @type {(path: string) => string} callback to generate code to load the wasm file
  51. */
  52. const generateLoadBinaryCode = this._import
  53. ? (path) =>
  54. Template.asString([
  55. "Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {",
  56. Template.indent([
  57. `readFile(new URL(${path}, ${compilation.outputOptions.importMetaName}.url), (err, buffer) => {`,
  58. Template.indent([
  59. "if (err) return reject(err);",
  60. "",
  61. "// Fake fetch response",
  62. "resolve({",
  63. Template.indent(["arrayBuffer() { return buffer; }"]),
  64. "});"
  65. ]),
  66. "});"
  67. ]),
  68. "}))"
  69. ])
  70. : (path) =>
  71. Template.asString([
  72. "new Promise(function (resolve, reject) {",
  73. Template.indent([
  74. "try {",
  75. Template.indent([
  76. `var { readFile } = require(${compilation.runtimeTemplate.renderNodePrefixForCoreModule("fs")});`,
  77. `var { join } = require(${compilation.runtimeTemplate.renderNodePrefixForCoreModule("path")});`,
  78. "",
  79. `readFile(join(__dirname, ${path}), function(err, buffer){`,
  80. Template.indent([
  81. "if (err) return reject(err);",
  82. "",
  83. "// Fake fetch response",
  84. "resolve({",
  85. Template.indent(["arrayBuffer() { return buffer; }"]),
  86. "});"
  87. ]),
  88. "});"
  89. ]),
  90. "} catch (err) { reject(err); }"
  91. ]),
  92. "})"
  93. ]);
  94. compilation.hooks.runtimeRequirementInTree
  95. .for(RuntimeGlobals.instantiateWasm)
  96. .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => {
  97. if (!isEnabledForChunk(chunk)) return;
  98. if (
  99. !chunkGraph.hasModuleInGraph(
  100. chunk,
  101. (m) => m.type === WEBASSEMBLY_MODULE_TYPE_ASYNC
  102. )
  103. ) {
  104. return;
  105. }
  106. compilation.addRuntimeModule(
  107. chunk,
  108. new AsyncWasmLoadingRuntimeModule({
  109. generateLoadBinaryCode,
  110. supportsStreaming: false
  111. })
  112. );
  113. });
  114. compilation.hooks.runtimeRequirementInTree
  115. .for(RuntimeGlobals.compileWasm)
  116. .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => {
  117. if (!isEnabledForChunk(chunk)) return;
  118. if (
  119. !chunkGraph.hasModuleInGraph(
  120. chunk,
  121. (m) => m.type === WEBASSEMBLY_MODULE_TYPE_ASYNC
  122. )
  123. ) {
  124. return;
  125. }
  126. compilation.addRuntimeModule(
  127. chunk,
  128. new AsyncWasmCompileRuntimeModule({
  129. generateLoadBinaryCode,
  130. supportsStreaming: false
  131. })
  132. );
  133. });
  134. });
  135. }
  136. }
  137. module.exports = ReadFileCompileAsyncWasmPlugin;