webpack/lib/wasm-sync/WasmFinalizeExportsPlugin.js

94 lines
2.8 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
2018-07-30 23:08:51 +08:00
*/
"use strict";
const formatLocation = require("../formatLocation");
2018-07-09 20:48:28 +08:00
const UnsupportedWebAssemblyFeatureError = require("./UnsupportedWebAssemblyFeatureError");
/** @typedef {import("../Compiler")} Compiler */
2023-05-26 02:31:28 +08:00
/** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../Module")} Module */
2023-06-12 22:21:21 +08:00
/** @typedef {import("../Module").BuildMeta} BuildMeta */
class WasmFinalizeExportsPlugin {
/**
2020-04-23 16:48:36 +08:00
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap("WasmFinalizeExportsPlugin", compilation => {
compilation.hooks.finishModules.tap(
"WasmFinalizeExportsPlugin",
modules => {
for (const module of modules) {
2018-05-30 21:27:42 +08:00
// 1. if a WebAssembly module
if (module.type.startsWith("webassembly") === true) {
2018-06-04 22:23:41 +08:00
const jsIncompatibleExports =
2023-06-12 22:21:21 +08:00
/** @type {BuildMeta} */
(module.buildMeta).jsIncompatibleExports;
2018-06-04 22:23:41 +08:00
if (jsIncompatibleExports === undefined) {
continue;
}
for (const connection of compilation.moduleGraph.getIncomingConnections(
module
)) {
// 2. is active and referenced by a non-WebAssembly module
if (
2020-10-07 15:10:29 +08:00
connection.isTargetActive(undefined) &&
2023-05-26 02:31:28 +08:00
/** @type {Module} */
(connection.originModule).type.startsWith("webassembly") ===
false
) {
2021-05-11 15:31:46 +08:00
const referencedExports =
compilation.getDependencyReferencedExports(
2023-05-26 02:31:28 +08:00
/** @type {Dependency} */ (connection.dependency),
2021-05-11 15:31:46 +08:00
undefined
);
2018-05-30 21:27:42 +08:00
2020-06-10 19:31:01 +08:00
for (const info of referencedExports) {
const names = Array.isArray(info) ? info : info.name;
if (names.length === 0) continue;
const name = names[0];
if (typeof name === "object") continue;
// 3. and uses a func with an incompatible JS signature
if (
Object.prototype.hasOwnProperty.call(
jsIncompatibleExports,
name
)
) {
// 4. error
const error = new UnsupportedWebAssemblyFeatureError(
`Export "${name}" with ${jsIncompatibleExports[name]} can only be used for direct wasm to wasm dependencies\n` +
2023-05-26 02:31:28 +08:00
`It's used from ${
/** @type {Module} */
(connection.originModule).readableIdentifier(
compilation.requestShortener
)
} at ${formatLocation(
/** @type {Dependency} */ (connection.dependency)
.loc
)}.`
);
error.module = module;
compilation.errors.push(error);
}
2018-06-04 22:23:41 +08:00
}
}
}
}
}
}
);
});
}
}
module.exports = WasmFinalizeExportsPlugin;