@@ -9,13 +9,29 @@ const Template = require("../Template");
99const WebAssemblyUtils = require ( "./WebAssemblyUtils" ) ;
1010const { RawSource } = require ( "webpack-sources" ) ;
1111
12+ const { shrinkPaddedLEB128 } = require ( "@webassemblyjs/wasm-opt" ) ;
1213const { editWithAST, addWithAST } = require ( "@webassemblyjs/wasm-edit" ) ;
1314const { decode } = require ( "@webassemblyjs/wasm-parser" ) ;
1415const t = require ( "@webassemblyjs/ast" ) ;
1516
1617/** @typedef {import("../Module") } Module */
1718/** @typedef {import("./WebAssemblyUtils").UsedWasmDependency } UsedWasmDependency */
1819
20+ /**
21+ * @typedef {(ArrayBuffer) => ArrayBuffer } ArrayBufferTransform
22+ */
23+
24+ /**
25+ * Run some preprocessing on the binary before wasm-edit
26+ *
27+ * @param {ArrayBuffer } ab - original binary
28+ * @returns {ArrayBufferTransform } transform
29+ */
30+ function preprocess ( ab ) {
31+ const optBin = shrinkPaddedLEB128 ( new Uint8Array ( ab ) ) ;
32+ return optBin . buffer ;
33+ }
34+
1935/**
2036 * @template T
2137 * @param {Function[] } fns transforms
@@ -42,9 +58,6 @@ const isGlobalImport = n => n.descr.type === "GlobalType";
4258const isFuncImport = n => n . descr . type === "FuncImportDescr" ;
4359
4460// TODO replace with @callback
45- /**
46- * @typedef {(ArrayBuffer) => ArrayBuffer } ArrayBufferTransform
47- */
4861
4962/**
5063 * Removes the start instruction
@@ -176,7 +189,7 @@ const rewriteImportedGlobals = state => bin => {
176189
177190 newGlobals . push (
178191 t . global ( globalType , [
179- t . objectInstruction ( "const" , "i32" , [ t . numberLiteral ( 0 ) ] )
192+ t . objectInstruction ( "const" , "i32" , [ t . numberLiteralFromRaw ( 0 ) ] )
180193 ] )
181194 ) ;
182195
@@ -315,7 +328,8 @@ const getUsedDependencyMap = module => {
315328
316329class WebAssemblyGenerator extends Generator {
317330 generate ( module ) {
318- const bin = module . originalSource ( ) . source ( ) ;
331+ let bin = module . originalSource ( ) . source ( ) ;
332+ bin = preprocess ( bin ) ;
319333
320334 const initFuncId = t . identifier (
321335 Array . isArray ( module . usedExports )
0 commit comments