source: frontend/node_modules/webpack/lib/wasm-async/UniversalCompileAsyncWasmPlugin.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 4.4 KB
RevLine 
[9af201e]1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Alexander Akait @alexander-akait
4*/
5
6"use strict";
7
8const { WEBASSEMBLY_MODULE_TYPE_ASYNC } = require("../ModuleTypeConstants");
9const RuntimeGlobals = require("../RuntimeGlobals");
10const Template = require("../Template");
11const AsyncWasmCompileRuntimeModule = require("../wasm-async/AsyncWasmCompileRuntimeModule");
12const AsyncWasmLoadingRuntimeModule = require("../wasm-async/AsyncWasmLoadingRuntimeModule");
13
14/** @typedef {import("../Chunk")} Chunk */
15/** @typedef {import("../Compiler")} Compiler */
16
17const PLUGIN_NAME = "UniversalCompileAsyncWasmPlugin";
18
19/**
20 * Enables async WebAssembly loading that works in both browser-like and Node.js
21 * environments by selecting the appropriate binary-loading strategy at runtime.
22 */
23class UniversalCompileAsyncWasmPlugin {
24 /**
25 * Registers compilation hooks that attach the universal async wasm runtime
26 * to chunks using `wasmLoading: "universal"`.
27 * @param {Compiler} compiler the compiler instance
28 * @returns {void}
29 */
30 apply(compiler) {
31 compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
32 const globalWasmLoading = compilation.outputOptions.wasmLoading;
33 /**
34 * Determines whether the chunk should use the universal async wasm
35 * loading backend.
36 * @param {Chunk} chunk chunk
37 * @returns {boolean} true, if wasm loading is enabled for the chunk
38 */
39 const isEnabledForChunk = (chunk) => {
40 const options = chunk.getEntryOptions();
41 const wasmLoading =
42 options && options.wasmLoading !== undefined
43 ? options.wasmLoading
44 : globalWasmLoading;
45 return wasmLoading === "universal";
46 };
47 const generateBeforeStreaming = () =>
48 Template.asString([
49 "if (!useFetch) {",
50 Template.indent(["return fallback();"]),
51 "}"
52 ]);
53 /**
54 * Generates setup code that decides whether the current environment can
55 * use `fetch` and captures the wasm module URL.
56 * @param {string} path path
57 * @returns {string} code
58 */
59 const generateBeforeLoadBinaryCode = (path) =>
60 Template.asString([
61 "var useFetch = typeof document !== 'undefined' || typeof self !== 'undefined';",
62 `var wasmUrl = ${path};`
63 ]);
64 /**
65 * Generates the runtime expression that fetches the binary in browsers
66 * or reads it from the filesystem in Node.js.
67 * @type {(path: string) => string}
68 */
69 const generateLoadBinaryCode = () =>
70 Template.asString([
71 "(useFetch",
72 Template.indent([
73 `? fetch(new URL(wasmUrl, ${compilation.outputOptions.importMetaName}.url))`
74 ]),
75 Template.indent([
76 ": Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {",
77 Template.indent([
78 `readFile(new URL(wasmUrl, ${compilation.outputOptions.importMetaName}.url), (err, buffer) => {`,
79 Template.indent([
80 "if (err) return reject(err);",
81 "",
82 "// Fake fetch response",
83 "resolve({",
84 Template.indent(["arrayBuffer() { return buffer; }"]),
85 "});"
86 ]),
87 "});"
88 ]),
89 "})))"
90 ])
91 ]);
92
93 compilation.hooks.runtimeRequirementInTree
94 .for(RuntimeGlobals.instantiateWasm)
95 .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => {
96 if (!isEnabledForChunk(chunk)) return;
97 if (
98 !chunkGraph.hasModuleInGraph(
99 chunk,
100 (m) => m.type === WEBASSEMBLY_MODULE_TYPE_ASYNC
101 )
102 ) {
103 return;
104 }
105 compilation.addRuntimeModule(
106 chunk,
107 new AsyncWasmLoadingRuntimeModule({
108 generateBeforeLoadBinaryCode,
109 generateLoadBinaryCode,
110 generateBeforeInstantiateStreaming: generateBeforeStreaming,
111 supportsStreaming: true
112 })
113 );
114 });
115
116 compilation.hooks.runtimeRequirementInTree
117 .for(RuntimeGlobals.compileWasm)
118 .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => {
119 if (!isEnabledForChunk(chunk)) return;
120 if (
121 !chunkGraph.hasModuleInGraph(
122 chunk,
123 (m) => m.type === WEBASSEMBLY_MODULE_TYPE_ASYNC
124 )
125 ) {
126 return;
127 }
128 compilation.addRuntimeModule(
129 chunk,
130 new AsyncWasmCompileRuntimeModule({
131 generateBeforeLoadBinaryCode,
132 generateLoadBinaryCode,
133 generateBeforeCompileStreaming: generateBeforeStreaming,
134 supportsStreaming: true
135 })
136 );
137 });
138 });
139 }
140}
141
142module.exports = UniversalCompileAsyncWasmPlugin;
Note: See TracBrowser for help on using the repository browser.