code:
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

import { encodeNode } from "@webassemblyjs/wasm-gen";
import { encodeU32 } from "@webassemblyjs/wasm-gen/lib/encoder";
import { isFunc, isGlobal, assertHasLoc, orderedInsertNode, getSectionMetadata, traverse, getEndOfSection } from "@webassemblyjs/ast";
import { resizeSectionByteSize, resizeSectionVecSize, createEmptySection, removeSections } from "@webassemblyjs/helper-wasm-section";
import { overrideBytesInBuffer } from "@webassemblyjs/helper-buffer";
import { getSectionForNode } from "@webassemblyjs/helper-wasm-bytecode";

function shiftLocNodeByDelta(node, delta) {
  assertHasLoc(node); // $FlowIgnore: assertHasLoc ensures that

  node.loc.start.column += delta; // $FlowIgnore: assertHasLoc ensures that

  node.loc.end.column += delta;
}

function applyUpdate(ast, uint8Buffer, _ref) {
  var _ref2 = _slicedToArray(_ref, 2),
      oldNode = _ref2[0],
      newNode = _ref2[1];

  var deltaElements = 0;
  assertHasLoc(oldNode);
  var sectionName = getSectionForNode(newNode);
  var replacementByteArray = encodeNode(newNode);
  /**
   * Replace new node as bytes
   */

  uint8Buffer = overrideBytesInBuffer(uint8Buffer, // $FlowIgnore: assertHasLoc ensures that
  oldNode.loc.start.column, // $FlowIgnore: assertHasLoc ensures that
  oldNode.loc.end.column, replacementByteArray);
  /**
   * Update function body size if needed
   */

  if (sectionName === "code") {
    // Find the parent func
    traverse(ast, {
      Func: function Func(_ref3) {
        var node = _ref3.node;
        var funcHasThisIntr = node.body.find(function (n) {
          return n === newNode;
        }) !== undefined; // Update func's body size if needed

        if (funcHasThisIntr === true) {
          // These are the old functions locations informations
          assertHasLoc(node);
          var oldNodeSize = encodeNode(oldNode).length;
          var bodySizeDeltaBytes = replacementByteArray.length - oldNodeSize;

          if (bodySizeDeltaBytes !== 0) {
            var newValue = node.metadata.bodySize + bodySizeDeltaBytes;
            var newByteArray = encodeU32(newValue); // function body size byte
            // FIXME(sven): only handles one byte u32

            var start = node.loc.start.column;
            var end = start + 1;
            uint8Buffer = overrideBytesInBuffer(uint8Buffer, start, end, newByteArray);
          }
        }
      }
    });
  }
  /**
   * Update section size
   */

  var deltaBytes = replacementByteArray.length - (oldNode.loc.end.column - oldNode.loc.start.column); // Init location informations

  newNode.loc = {
    start: {
      line: -1,
      column: -1
    },
    end: {
      line: -1,
      column: -1
    }
  }; // Update new node end position
  // $FlowIgnore: assertHasLoc ensures that

  newNode.loc.start.column = oldNode.loc.start.column; // $FlowIgnore: assertHasLoc ensures that

  newNode.loc.end.column = // $FlowIgnore: assertHasLoc ensures that
  oldNode.loc.start.column + replacementByteArray.length;
  return {
    uint8Buffer: uint8Buffer,
    deltaBytes: deltaBytes,
    deltaElements: deltaElements
  };
}

function applyDelete(ast, uint8Buffer, node) {
  var deltaElements = -1; // since we removed an element

  assertHasLoc(node);
  var sectionName = getSectionForNode(node);

  if (sectionName === "start") {
    var sectionMetadata = getSectionMetadata(ast, "start");
    /**
     * The start section only contains one element,
     * we need to remove the whole section
     */

    uint8Buffer = removeSections(ast, uint8Buffer, "start");

    var _deltaBytes = -(sectionMetadata.size.value + 1);
    /* section id */

    return {
      uint8Buffer: uint8Buffer,
      deltaBytes: _deltaBytes,
      deltaElements: deltaElements
    };
  } // replacement is nothing

  var replacement = [];
  uint8Buffer = overrideBytesInBuffer(uint8Buffer, // $FlowIgnore: assertHasLoc ensures that
  node.loc.start.column, // $FlowIgnore: assertHasLoc ensures that
  node.loc.end.column, replacement);
  /**
   * Update section
   */
  // $FlowIgnore: assertHasLoc ensures that

  var deltaBytes = -(node.loc.end.column - node.loc.start.column);
  return {
    uint8Buffer: uint8Buffer,
    deltaBytes: deltaBytes,
    deltaElements: deltaElements
  };
}

function applyAdd(ast, uint8Buffer, node) {
  var deltaElements = +1; // since we added an element

  var sectionName = getSectionForNode(node);
  var sectionMetadata = getSectionMetadata(ast, sectionName); // Section doesn't exists, we create an empty one

  if (typeof sectionMetadata === "undefined") {
    var res = createEmptySection(ast, uint8Buffer, sectionName);
    uint8Buffer = res.uint8Buffer;
    sectionMetadata = res.sectionMetadata;
  }
  /**
   * check that the expressions were ended
   */

  if (isFunc(node)) {
    // $FlowIgnore
    var body = node.body;

    if (body.length === 0 || body[body.length - 1].id !== "end") {
      throw new Error("expressions must be ended");
    }
  }

  if (isGlobal(node)) {
    // $FlowIgnore
    var body = node.init;

    if (body.length === 0 || body[body.length - 1].id !== "end") {
      throw new Error("expressions must be ended");
    }
  }
  /**
   * Add nodes
   */

  var newByteArray = encodeNode(node); // The size of the section doesn't include the storage of the size itself
  // we need to manually add it here

  var start = getEndOfSection(sectionMetadata);
  var end = start;
  /**
   * Update section
   */

  var deltaBytes = newByteArray.length;
  uint8Buffer = overrideBytesInBuffer(uint8Buffer, start, end, newByteArray);
  node.loc = {
    start: {
      line: -1,
      column: start
    },
    end: {
      line: -1,
      column: start + deltaBytes
    }
  }; // for func add the additional metadata in the AST

  if (node.type === "Func") {
    // the size is the first byte
    // FIXME(sven): handle LEB128 correctly here
    var bodySize = newByteArray[0];
    node.metadata = {
      bodySize: bodySize
    };
  }

  if (node.type !== "IndexInFuncSection") {
    orderedInsertNode(ast.body[0], node);
  }

  return {
    uint8Buffer: uint8Buffer,
    deltaBytes: deltaBytes,
    deltaElements: deltaElements
  };
}

export function applyOperations(ast, uint8Buffer, ops) {
  ops.forEach(function (op) {
    var state;
    var sectionName;

    switch (op.kind) {
      case "update":
        state = applyUpdate(ast, uint8Buffer, [op.oldNode, op.node]);
        sectionName = getSectionForNode(op.node);
        break;

      case "delete":
        state = applyDelete(ast, uint8Buffer, op.node);
        sectionName = getSectionForNode(op.node);
        break;

      case "add":
        state = applyAdd(ast, uint8Buffer, op.node);
        sectionName = getSectionForNode(op.node);
        break;

      default:
        throw new Error("Unknown operation");
    }
    /**
     * Resize section vec size.
     * If the length of the LEB-encoded size changes, this can change
     * the byte length of the section and the offset for nodes in the
     * section. So we do this first before resizing section byte size
     * or shifting following operations' nodes.
     */

    if (state.deltaElements !== 0 && sectionName !== "start") {
      var oldBufferLength = state.uint8Buffer.length;
      state.uint8Buffer = resizeSectionVecSize(ast, state.uint8Buffer, sectionName, state.deltaElements); // Infer bytes added/removed by comparing buffer lengths

      state.deltaBytes += state.uint8Buffer.length - oldBufferLength;
    }
    /**
     * Resize section byte size.
     * If the length of the LEB-encoded size changes, this can change
     * the offset for nodes in the section. So we do this before
     * shifting following operations' nodes.
     */

    if (state.deltaBytes !== 0 && sectionName !== "start") {
      var _oldBufferLength = state.uint8Buffer.length;
      state.uint8Buffer = resizeSectionByteSize(ast, state.uint8Buffer, sectionName, state.deltaBytes); // Infer bytes added/removed by comparing buffer lengths

      state.deltaBytes += state.uint8Buffer.length - _oldBufferLength;
    }
    /**
     * Shift following operation's nodes
     */

    if (state.deltaBytes !== 0) {
      ops.forEach(function (op) {
        // We don't need to handle add ops, they are positioning independent
        switch (op.kind) {
          case "update":
            shiftLocNodeByDelta(op.oldNode, state.deltaBytes);
            break;

          case "delete":
            shiftLocNodeByDelta(op.node, state.deltaBytes);
            break;
        }
      });
    }

    uint8Buffer = state.uint8Buffer;
  });
  return uint8Buffer;
}


code:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.applyOperations = applyOperations;

var _wasmGen = require("@webassemblyjs/wasm-gen");

var _encoder = require("@webassemblyjs/wasm-gen/lib/encoder");

var _ast = require("@webassemblyjs/ast");

var _helperWasmSection = require("@webassemblyjs/helper-wasm-section");

var _helperBuffer = require("@webassemblyjs/helper-buffer");

var _helperWasmBytecode = require("@webassemblyjs/helper-wasm-bytecode");

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function shiftLocNodeByDelta(node, delta) {
  (0, _ast.assertHasLoc)(node); // $FlowIgnore: assertHasLoc ensures that

  node.loc.start.column += delta; // $FlowIgnore: assertHasLoc ensures that

  node.loc.end.column += delta;
}

function applyUpdate(ast, uint8Buffer, _ref) {
  var _ref2 = _slicedToArray(_ref, 2),
      oldNode = _ref2[0],
      newNode = _ref2[1];

  var deltaElements = 0;
  (0, _ast.assertHasLoc)(oldNode);
  var sectionName = (0, _helperWasmBytecode.getSectionForNode)(newNode);
  var replacementByteArray = (0, _wasmGen.encodeNode)(newNode);
  /**
   * Replace new node as bytes
   */

  uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, // $FlowIgnore: assertHasLoc ensures that
  oldNode.loc.start.column, // $FlowIgnore: assertHasLoc ensures that
  oldNode.loc.end.column, replacementByteArray);
  /**
   * Update function body size if needed
   */

  if (sectionName === "code") {
    // Find the parent func
    (0, _ast.traverse)(ast, {
      Func: function Func(_ref3) {
        var node = _ref3.node;
        var funcHasThisIntr = node.body.find(function (n) {
          return n === newNode;
        }) !== undefined; // Update func's body size if needed

        if (funcHasThisIntr === true) {
          // These are the old functions locations informations
          (0, _ast.assertHasLoc)(node);
          var oldNodeSize = (0, _wasmGen.encodeNode)(oldNode).length;
          var bodySizeDeltaBytes = replacementByteArray.length - oldNodeSize;

          if (bodySizeDeltaBytes !== 0) {
            var newValue = node.metadata.bodySize + bodySizeDeltaBytes;
            var newByteArray = (0, _encoder.encodeU32)(newValue); // function body size byte
            // FIXME(sven): only handles one byte u32

            var start = node.loc.start.column;
            var end = start + 1;
            uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newByteArray);
          }
        }
      }
    });
  }
  /**
   * Update section size
   */

  var deltaBytes = replacementByteArray.length - (oldNode.loc.end.column - oldNode.loc.start.column); // Init location informations

  newNode.loc = {
    start: {
      line: -1,
      column: -1
    },
    end: {
      line: -1,
      column: -1
    }
  }; // Update new node end position
  // $FlowIgnore: assertHasLoc ensures that

  newNode.loc.start.column = oldNode.loc.start.column; // $FlowIgnore: assertHasLoc ensures that

  newNode.loc.end.column = // $FlowIgnore: assertHasLoc ensures that
  oldNode.loc.start.column + replacementByteArray.length;
  return {
    uint8Buffer: uint8Buffer,
    deltaBytes: deltaBytes,
    deltaElements: deltaElements
  };
}

function applyDelete(ast, uint8Buffer, node) {
  var deltaElements = -1; // since we removed an element

  (0, _ast.assertHasLoc)(node);
  var sectionName = (0, _helperWasmBytecode.getSectionForNode)(node);

  if (sectionName === "start") {
    var sectionMetadata = (0, _ast.getSectionMetadata)(ast, "start");
    /**
     * The start section only contains one element,
     * we need to remove the whole section
     */

    uint8Buffer = (0, _helperWasmSection.removeSections)(ast, uint8Buffer, "start");

    var _deltaBytes = -(sectionMetadata.size.value + 1);
    /* section id */

    return {
      uint8Buffer: uint8Buffer,
      deltaBytes: _deltaBytes,
      deltaElements: deltaElements
    };
  } // replacement is nothing

  var replacement = [];
  uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, // $FlowIgnore: assertHasLoc ensures that
  node.loc.start.column, // $FlowIgnore: assertHasLoc ensures that
  node.loc.end.column, replacement);
  /**
   * Update section
   */
  // $FlowIgnore: assertHasLoc ensures that

  var deltaBytes = -(node.loc.end.column - node.loc.start.column);
  return {
    uint8Buffer: uint8Buffer,
    deltaBytes: deltaBytes,
    deltaElements: deltaElements
  };
}

function applyAdd(ast, uint8Buffer, node) {
  var deltaElements = +1; // since we added an element

  var sectionName = (0, _helperWasmBytecode.getSectionForNode)(node);
  var sectionMetadata = (0, _ast.getSectionMetadata)(ast, sectionName); // Section doesn't exists, we create an empty one

  if (typeof sectionMetadata === "undefined") {
    var res = (0, _helperWasmSection.createEmptySection)(ast, uint8Buffer, sectionName);
    uint8Buffer = res.uint8Buffer;
    sectionMetadata = res.sectionMetadata;
  }
  /**
   * check that the expressions were ended
   */

  if ((0, _ast.isFunc)(node)) {
    // $FlowIgnore
    var body = node.body;

    if (body.length === 0 || body[body.length - 1].id !== "end") {
      throw new Error("expressions must be ended");
    }
  }

  if ((0, _ast.isGlobal)(node)) {
    // $FlowIgnore
    var body = node.init;

    if (body.length === 0 || body[body.length - 1].id !== "end") {
      throw new Error("expressions must be ended");
    }
  }
  /**
   * Add nodes
   */

  var newByteArray = (0, _wasmGen.encodeNode)(node); // The size of the section doesn't include the storage of the size itself
  // we need to manually add it here

  var start = (0, _ast.getEndOfSection)(sectionMetadata);
  var end = start;
  /**
   * Update section
   */

  var deltaBytes = newByteArray.length;
  uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newByteArray);
  node.loc = {
    start: {
      line: -1,
      column: start
    },
    end: {
      line: -1,
      column: start + deltaBytes
    }
  }; // for func add the additional metadata in the AST

  if (node.type === "Func") {
    // the size is the first byte
    // FIXME(sven): handle LEB128 correctly here
    var bodySize = newByteArray[0];
    node.metadata = {
      bodySize: bodySize
    };
  }

  if (node.type !== "IndexInFuncSection") {
    (0, _ast.orderedInsertNode)(ast.body[0], node);
  }

  return {
    uint8Buffer: uint8Buffer,
    deltaBytes: deltaBytes,
    deltaElements: deltaElements
  };
}

function applyOperations(ast, uint8Buffer, ops) {
  ops.forEach(function (op) {
    var state;
    var sectionName;

    switch (op.kind) {
      case "update":
        state = applyUpdate(ast, uint8Buffer, [op.oldNode, op.node]);
        sectionName = (0, _helperWasmBytecode.getSectionForNode)(op.node);
        break;

      case "delete":
        state = applyDelete(ast, uint8Buffer, op.node);
        sectionName = (0, _helperWasmBytecode.getSectionForNode)(op.node);
        break;

      case "add":
        state = applyAdd(ast, uint8Buffer, op.node);
        sectionName = (0, _helperWasmBytecode.getSectionForNode)(op.node);
        break;

      default:
        throw new Error("Unknown operation");
    }
    /**
     * Resize section vec size.
     * If the length of the LEB-encoded size changes, this can change
     * the byte length of the section and the offset for nodes in the
     * section. So we do this first before resizing section byte size
     * or shifting following operations' nodes.
     */

    if (state.deltaElements !== 0 && sectionName !== "start") {
      var oldBufferLength = state.uint8Buffer.length;
      state.uint8Buffer = (0, _helperWasmSection.resizeSectionVecSize)(ast, state.uint8Buffer, sectionName, state.deltaElements); // Infer bytes added/removed by comparing buffer lengths

      state.deltaBytes += state.uint8Buffer.length - oldBufferLength;
    }
    /**
     * Resize section byte size.
     * If the length of the LEB-encoded size changes, this can change
     * the offset for nodes in the section. So we do this before
     * shifting following operations' nodes.
     */

    if (state.deltaBytes !== 0 && sectionName !== "start") {
      var _oldBufferLength = state.uint8Buffer.length;
      state.uint8Buffer = (0, _helperWasmSection.resizeSectionByteSize)(ast, state.uint8Buffer, sectionName, state.deltaBytes); // Infer bytes added/removed by comparing buffer lengths

      state.deltaBytes += state.uint8Buffer.length - _oldBufferLength;
    }
    /**
     * Shift following operation's nodes
     */

    if (state.deltaBytes !== 0) {
      ops.forEach(function (op) {
        // We don't need to handle add ops, they are positioning independent
        switch (op.kind) {
          case "update":
            shiftLocNodeByDelta(op.oldNode, state.deltaBytes);
            break;

          case "delete":
            shiftLocNodeByDelta(op.node, state.deltaBytes);
            break;
        }
      });
    }

    uint8Buffer = state.uint8Buffer;
  });
  return uint8Buffer;
}

license: mit


@webassemblyjs/wasm-edit

test: echo "Error: no test specified" && exit 1

type: git

access: public

author: Sven Sauleau

license: MIT


code:
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

import * as leb from "@webassemblyjs/leb128";
import * as ieee754 from "@webassemblyjs/ieee754";
import * as utf8 from "@webassemblyjs/utf8";
import constants from "@webassemblyjs/helper-wasm-bytecode";
import { encodeNode } from "../index";

function assertNotIdentifierNode(n) {
  if (n.type === "Identifier") {
    throw new Error("Unsupported node Identifier");
  }
}

export function encodeVersion(v) {
  var bytes = constants.moduleVersion;
  bytes[0] = v;
  return bytes;
}
export function encodeHeader() {
  return constants.magicModuleHeader;
}
export function encodeU32(v) {
  var uint8view = new Uint8Array(leb.encodeU32(v));

  var array = _toConsumableArray(uint8view);

  return array;
}
export function encodeI32(v) {
  var uint8view = new Uint8Array(leb.encodeI32(v));

  var array = _toConsumableArray(uint8view);

  return array;
}
export function encodeI64(v) {
  var uint8view = new Uint8Array(leb.encodeI64(v));

  var array = _toConsumableArray(uint8view);

  return array;
}
export function encodeVec(elements) {
  var size = encodeU32(elements.length);
  return [].concat(_toConsumableArray(size), _toConsumableArray(elements));
}
export function encodeValtype(v) {
  var _byte = constants.valtypesByString[v];

  if (typeof _byte === "undefined") {
    throw new Error("Unknown valtype: " + v);
  }

  return parseInt(_byte, 10);
}
export function encodeMutability(v) {
  var _byte2 = constants.globalTypesByString[v];

  if (typeof _byte2 === "undefined") {
    throw new Error("Unknown mutability: " + v);
  }

  return parseInt(_byte2, 10);
}
export function encodeUTF8Vec(str) {
  return encodeVec(utf8.encode(str));
}
export function encodeLimits(n) {
  var out = [];

  if (typeof n.max === "number") {
    out.push(0x01);
    out.push.apply(out, _toConsumableArray(encodeU32(n.min))); // $FlowIgnore: ensured by the typeof

    out.push.apply(out, _toConsumableArray(encodeU32(n.max)));
  } else {
    out.push(0x00);
    out.push.apply(out, _toConsumableArray(encodeU32(n.min)));
  }

  return out;
}
export function encodeModuleImport(n) {
  var out = [];
  out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.module)));
  out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.name)));

  switch (n.descr.type) {
    case "GlobalType":
      {
        out.push(0x03); // $FlowIgnore: GlobalType ensure that these props exists

        out.push(encodeValtype(n.descr.valtype)); // $FlowIgnore: GlobalType ensure that these props exists

        out.push(encodeMutability(n.descr.mutability));
        break;
      }

    case "Memory":
      {
        out.push(0x02); // $FlowIgnore

        out.push.apply(out, _toConsumableArray(encodeLimits(n.descr.limits)));
        break;
      }

    case "Table":
      {
        out.push(0x01);
        out.push(0x70); // element type
        // $FlowIgnore

        out.push.apply(out, _toConsumableArray(encodeLimits(n.descr.limits)));
        break;
      }

    case "FuncImportDescr":
      {
        out.push(0x00); // $FlowIgnore

        assertNotIdentifierNode(n.descr.id); // $FlowIgnore

        out.push.apply(out, _toConsumableArray(encodeU32(n.descr.id.value)));
        break;
      }

    default:
      throw new Error("Unsupport operation: encode module import of type: " + n.descr.type);
  }

  return out;
}
export function encodeSectionMetadata(n) {
  var out = [];
  var sectionId = constants.sections[n.section];

  if (typeof sectionId === "undefined") {
    throw new Error("Unknown section: " + n.section);
  }

  if (n.section === "start") {
    /**
     * This is not implemented yet because it's a special case which
     * doesn't have a vector in its section.
     */
    throw new Error("Unsupported section encoding of type start");
  }

  out.push(sectionId);
  out.push.apply(out, _toConsumableArray(encodeU32(n.size.value)));
  out.push.apply(out, _toConsumableArray(encodeU32(n.vectorOfSize.value)));
  return out;
}
export function encodeCallInstruction(n) {
  var out = [];
  assertNotIdentifierNode(n.index);
  out.push(0x10); // $FlowIgnore

  out.push.apply(out, _toConsumableArray(encodeU32(n.index.value)));
  return out;
}
export function encodeCallIndirectInstruction(n) {
  var out = []; // $FlowIgnore

  assertNotIdentifierNode(n.index);
  out.push(0x11); // $FlowIgnore

  out.push.apply(out, _toConsumableArray(encodeU32(n.index.value))); // add a reserved byte

  out.push(0x00);
  return out;
}
export function encodeModuleExport(n) {
  var out = [];
  assertNotIdentifierNode(n.descr.id);
  var exportTypeByteString = constants.exportTypesByName[n.descr.exportType];

  if (typeof exportTypeByteString === "undefined") {
    throw new Error("Unknown export of type: " + n.descr.exportType);
  }

  var exportTypeByte = parseInt(exportTypeByteString, 10);
  out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.name)));
  out.push(exportTypeByte); // $FlowIgnore

  out.push.apply(out, _toConsumableArray(encodeU32(n.descr.id.value)));
  return out;
}
export function encodeTypeInstruction(n) {
  var out = [0x60];
  var params = n.functype.params.map(function (x) {
    return x.valtype;
  }).map(encodeValtype);
  var results = n.functype.results.map(encodeValtype);
  out.push.apply(out, _toConsumableArray(encodeVec(params)));
  out.push.apply(out, _toConsumableArray(encodeVec(results)));
  return out;
}
export function encodeInstr(n) {
  var out = [];
  var instructionName = n.id;

  if (typeof n.object === "string") {
    instructionName = "".concat(n.object, ".").concat(String(n.id));
  }

  var byteString = constants.symbolsByName[instructionName];

  if (typeof byteString === "undefined") {
    throw new Error("encodeInstr: unknown instruction " + JSON.stringify(instructionName));
  }

  var _byte3 = parseInt(byteString, 10);

  out.push(_byte3);

  if (n.args) {
    n.args.forEach(function (arg) {
      var encoder = encodeU32; // find correct encoder

      if (n.object === "i32") {
        encoder = encodeI32;
      }

      if (n.object === "i64") {
        encoder = encodeI64;
      }

      if (n.object === "f32") {
        encoder = ieee754.encodeF32;
      }

      if (n.object === "f64") {
        encoder = ieee754.encodeF64;
      }

      if (arg.type === "NumberLiteral" || arg.type === "FloatLiteral" || arg.type === "LongNumberLiteral") {
        // $FlowIgnore
        out.push.apply(out, _toConsumableArray(encoder(arg.value)));
      } else {
        throw new Error("Unsupported instruction argument encoding " + JSON.stringify(arg.type));
      }
    });
  }

  return out;
}

function encodeExpr(instrs) {
  var out = [];
  instrs.forEach(function (instr) {
    // $FlowIgnore
    var n = encodeNode(instr);
    out.push.apply(out, _toConsumableArray(n));
  });
  return out;
}

export function encodeStringLiteral(n) {
  return encodeUTF8Vec(n.value);
}
export function encodeGlobal(n) {
  var out = [];
  var _n$globalType = n.globalType,
      valtype = _n$globalType.valtype,
      mutability = _n$globalType.mutability;
  out.push(encodeValtype(valtype));
  out.push(encodeMutability(mutability));
  out.push.apply(out, _toConsumableArray(encodeExpr(n.init)));
  return out;
}
export function encodeFuncBody(n) {
  var out = [];
  out.push(-1); // temporary function body size
  // FIXME(sven): get the func locals?

  var localBytes = encodeVec([]);
  out.push.apply(out, _toConsumableArray(localBytes));
  var funcBodyBytes = encodeExpr(n.body);
  out[0] = funcBodyBytes.length + localBytes.length;
  out.push.apply(out, _toConsumableArray(funcBodyBytes));
  return out;
}
export function encodeIndexInFuncSection(n) {
  assertNotIdentifierNode(n.index); // $FlowIgnore

  return encodeU32(n.index.value);
}
export function encodeElem(n) {
  var out = [];
  assertNotIdentifierNode(n.table); // $FlowIgnore

  out.push.apply(out, _toConsumableArray(encodeU32(n.table.value)));
  out.push.apply(out, _toConsumableArray(encodeExpr(n.offset))); // $FlowIgnore

  var funcs = n.funcs.reduce(function (acc, x) {
    return [].concat(_toConsumableArray(acc), _toConsumableArray(encodeU32(x.value)));
  }, []);
  out.push.apply(out, _toConsumableArray(encodeVec(funcs)));
  return out;
}


code:
import * as encoder from "./encoder";
export function encodeNode(n) {
  switch (n.type) {
    case "ModuleImport":
      // $FlowIgnore: ModuleImport ensure that the node is well formated
      return encoder.encodeModuleImport(n);

    case "SectionMetadata":
      // $FlowIgnore: SectionMetadata ensure that the node is well formated
      return encoder.encodeSectionMetadata(n);

    case "CallInstruction":
      // $FlowIgnore: SectionMetadata ensure that the node is well formated
      return encoder.encodeCallInstruction(n);

    case "CallIndirectInstruction":
      // $FlowIgnore: SectionMetadata ensure that the node is well formated
      return encoder.encodeCallIndirectInstruction(n);

    case "TypeInstruction":
      return encoder.encodeTypeInstruction(n);

    case "Instr":
      // $FlowIgnore
      return encoder.encodeInstr(n);

    case "ModuleExport":
      // $FlowIgnore: SectionMetadata ensure that the node is well formated
      return encoder.encodeModuleExport(n);

    case "Global":
      // $FlowIgnore
      return encoder.encodeGlobal(n);

    case "Func":
      return encoder.encodeFuncBody(n);

    case "IndexInFuncSection":
      return encoder.encodeIndexInFuncSection(n);

    case "StringLiteral":
      return encoder.encodeStringLiteral(n);

    case "Elem":
      return encoder.encodeElem(n);

    default:
      throw new Error("Unsupported encoding for node of type: " + JSON.stringify(n.type));
  }
}
export var encodeU32 = encoder.encodeU32;


code:
"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.encodeVersion = encodeVersion;
exports.encodeHeader = encodeHeader;
exports.encodeU32 = encodeU32;
exports.encodeI32 = encodeI32;
exports.encodeI64 = encodeI64;
exports.encodeVec = encodeVec;
exports.encodeValtype = encodeValtype;
exports.encodeMutability = encodeMutability;
exports.encodeUTF8Vec = encodeUTF8Vec;
exports.encodeLimits = encodeLimits;
exports.encodeModuleImport = encodeModuleImport;
exports.encodeSectionMetadata = encodeSectionMetadata;
exports.encodeCallInstruction = encodeCallInstruction;
exports.encodeCallIndirectInstruction = encodeCallIndirectInstruction;
exports.encodeModuleExport = encodeModuleExport;
exports.encodeTypeInstruction = encodeTypeInstruction;
exports.encodeInstr = encodeInstr;
exports.encodeStringLiteral = encodeStringLiteral;
exports.encodeGlobal = encodeGlobal;
exports.encodeFuncBody = encodeFuncBody;
exports.encodeIndexInFuncSection = encodeIndexInFuncSection;
exports.encodeElem = encodeElem;

var leb = _interopRequireWildcard(require("@webassemblyjs/leb128"));

var ieee754 = _interopRequireWildcard(require("@webassemblyjs/ieee754"));

var utf8 = _interopRequireWildcard(require("@webassemblyjs/utf8"));

var _helperWasmBytecode = _interopRequireDefault(require("@webassemblyjs/helper-wasm-bytecode"));

var _index = require("../index");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function assertNotIdentifierNode(n) {
  if (n.type === "Identifier") {
    throw new Error("Unsupported node Identifier");
  }
}

function encodeVersion(v) {
  var bytes = _helperWasmBytecode["default"].moduleVersion;
  bytes[0] = v;
  return bytes;
}

function encodeHeader() {
  return _helperWasmBytecode["default"].magicModuleHeader;
}

function encodeU32(v) {
  var uint8view = new Uint8Array(leb.encodeU32(v));

  var array = _toConsumableArray(uint8view);

  return array;
}

function encodeI32(v) {
  var uint8view = new Uint8Array(leb.encodeI32(v));

  var array = _toConsumableArray(uint8view);

  return array;
}

function encodeI64(v) {
  var uint8view = new Uint8Array(leb.encodeI64(v));

  var array = _toConsumableArray(uint8view);

  return array;
}

function encodeVec(elements) {
  var size = encodeU32(elements.length);
  return [].concat(_toConsumableArray(size), _toConsumableArray(elements));
}

function encodeValtype(v) {
  var _byte = _helperWasmBytecode["default"].valtypesByString[v];

  if (typeof _byte === "undefined") {
    throw new Error("Unknown valtype: " + v);
  }

  return parseInt(_byte, 10);
}

function encodeMutability(v) {
  var _byte2 = _helperWasmBytecode["default"].globalTypesByString[v];

  if (typeof _byte2 === "undefined") {
    throw new Error("Unknown mutability: " + v);
  }

  return parseInt(_byte2, 10);
}

function encodeUTF8Vec(str) {
  return encodeVec(utf8.encode(str));
}

function encodeLimits(n) {
  var out = [];

  if (typeof n.max === "number") {
    out.push(0x01);
    out.push.apply(out, _toConsumableArray(encodeU32(n.min))); // $FlowIgnore: ensured by the typeof

    out.push.apply(out, _toConsumableArray(encodeU32(n.max)));
  } else {
    out.push(0x00);
    out.push.apply(out, _toConsumableArray(encodeU32(n.min)));
  }

  return out;
}

function encodeModuleImport(n) {
  var out = [];
  out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.module)));
  out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.name)));

  switch (n.descr.type) {
    case "GlobalType":
      {
        out.push(0x03); // $FlowIgnore: GlobalType ensure that these props exists

        out.push(encodeValtype(n.descr.valtype)); // $FlowIgnore: GlobalType ensure that these props exists

        out.push(encodeMutability(n.descr.mutability));
        break;
      }

    case "Memory":
      {
        out.push(0x02); // $FlowIgnore

        out.push.apply(out, _toConsumableArray(encodeLimits(n.descr.limits)));
        break;
      }

    case "Table":
      {
        out.push(0x01);
        out.push(0x70); // element type
        // $FlowIgnore

        out.push.apply(out, _toConsumableArray(encodeLimits(n.descr.limits)));
        break;
      }

    case "FuncImportDescr":
      {
        out.push(0x00); // $FlowIgnore

        assertNotIdentifierNode(n.descr.id); // $FlowIgnore

        out.push.apply(out, _toConsumableArray(encodeU32(n.descr.id.value)));
        break;
      }

    default:
      throw new Error("Unsupport operation: encode module import of type: " + n.descr.type);
  }

  return out;
}

function encodeSectionMetadata(n) {
  var out = [];
  var sectionId = _helperWasmBytecode["default"].sections[n.section];

  if (typeof sectionId === "undefined") {
    throw new Error("Unknown section: " + n.section);
  }

  if (n.section === "start") {
    /**
     * This is not implemented yet because it's a special case which
     * doesn't have a vector in its section.
     */
    throw new Error("Unsupported section encoding of type start");
  }

  out.push(sectionId);
  out.push.apply(out, _toConsumableArray(encodeU32(n.size.value)));
  out.push.apply(out, _toConsumableArray(encodeU32(n.vectorOfSize.value)));
  return out;
}

function encodeCallInstruction(n) {
  var out = [];
  assertNotIdentifierNode(n.index);
  out.push(0x10); // $FlowIgnore

  out.push.apply(out, _toConsumableArray(encodeU32(n.index.value)));
  return out;
}

function encodeCallIndirectInstruction(n) {
  var out = []; // $FlowIgnore

  assertNotIdentifierNode(n.index);
  out.push(0x11); // $FlowIgnore

  out.push.apply(out, _toConsumableArray(encodeU32(n.index.value))); // add a reserved byte

  out.push(0x00);
  return out;
}

function encodeModuleExport(n) {
  var out = [];
  assertNotIdentifierNode(n.descr.id);
  var exportTypeByteString = _helperWasmBytecode["default"].exportTypesByName[n.descr.exportType];

  if (typeof exportTypeByteString === "undefined") {
    throw new Error("Unknown export of type: " + n.descr.exportType);
  }

  var exportTypeByte = parseInt(exportTypeByteString, 10);
  out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.name)));
  out.push(exportTypeByte); // $FlowIgnore

  out.push.apply(out, _toConsumableArray(encodeU32(n.descr.id.value)));
  return out;
}

function encodeTypeInstruction(n) {
  var out = [0x60];
  var params = n.functype.params.map(function (x) {
    return x.valtype;
  }).map(encodeValtype);
  var results = n.functype.results.map(encodeValtype);
  out.push.apply(out, _toConsumableArray(encodeVec(params)));
  out.push.apply(out, _toConsumableArray(encodeVec(results)));
  return out;
}

function encodeInstr(n) {
  var out = [];
  var instructionName = n.id;

  if (typeof n.object === "string") {
    instructionName = "".concat(n.object, ".").concat(String(n.id));
  }

  var byteString = _helperWasmBytecode["default"].symbolsByName[instructionName];

  if (typeof byteString === "undefined") {
    throw new Error("encodeInstr: unknown instruction " + JSON.stringify(instructionName));
  }

  var _byte3 = parseInt(byteString, 10);

  out.push(_byte3);

  if (n.args) {
    n.args.forEach(function (arg) {
      var encoder = encodeU32; // find correct encoder

      if (n.object === "i32") {
        encoder = encodeI32;
      }

      if (n.object === "i64") {
        encoder = encodeI64;
      }

      if (n.object === "f32") {
        encoder = ieee754.encodeF32;
      }

      if (n.object === "f64") {
        encoder = ieee754.encodeF64;
      }

      if (arg.type === "NumberLiteral" || arg.type === "FloatLiteral" || arg.type === "LongNumberLiteral") {
        // $FlowIgnore
        out.push.apply(out, _toConsumableArray(encoder(arg.value)));
      } else {
        throw new Error("Unsupported instruction argument encoding " + JSON.stringify(arg.type));
      }
    });
  }

  return out;
}

function encodeExpr(instrs) {
  var out = [];
  instrs.forEach(function (instr) {
    // $FlowIgnore
    var n = (0, _index.encodeNode)(instr);
    out.push.apply(out, _toConsumableArray(n));
  });
  return out;
}

function encodeStringLiteral(n) {
  return encodeUTF8Vec(n.value);
}

function encodeGlobal(n) {
  var out = [];
  var _n$globalType = n.globalType,
      valtype = _n$globalType.valtype,
      mutability = _n$globalType.mutability;
  out.push(encodeValtype(valtype));
  out.push(encodeMutability(mutability));
  out.push.apply(out, _toConsumableArray(encodeExpr(n.init)));
  return out;
}

function encodeFuncBody(n) {
  var out = [];
  out.push(-1); // temporary function body size
  // FIXME(sven): get the func locals?

  var localBytes = encodeVec([]);
  out.push.apply(out, _toConsumableArray(localBytes));
  var funcBodyBytes = encodeExpr(n.body);
  out[0] = funcBodyBytes.length + localBytes.length;
  out.push.apply(out, _toConsumableArray(funcBodyBytes));
  return out;
}

function encodeIndexInFuncSection(n) {
  assertNotIdentifierNode(n.index); // $FlowIgnore

  return encodeU32(n.index.value);
}

function encodeElem(n) {
  var out = [];
  assertNotIdentifierNode(n.table); // $FlowIgnore

  out.push.apply(out, _toConsumableArray(encodeU32(n.table.value)));
  out.push.apply(out, _toConsumableArray(encodeExpr(n.offset))); // $FlowIgnore

  var funcs = n.funcs.reduce(function (acc, x) {
    return [].concat(_toConsumableArray(acc), _toConsumableArray(encodeU32(x.value)));
  }, []);
  out.push.apply(out, _toConsumableArray(encodeVec(funcs)));
  return out;
}


code:
"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.encodeNode = encodeNode;
exports.encodeU32 = void 0;

var encoder = _interopRequireWildcard(require("./encoder"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function encodeNode(n) {
  switch (n.type) {
    case "ModuleImport":
      // $FlowIgnore: ModuleImport ensure that the node is well formated
      return encoder.encodeModuleImport(n);

    case "SectionMetadata":
      // $FlowIgnore: SectionMetadata ensure that the node is well formated
      return encoder.encodeSectionMetadata(n);

    case "CallInstruction":
      // $FlowIgnore: SectionMetadata ensure that the node is well formated
      return encoder.encodeCallInstruction(n);

    case "CallIndirectInstruction":
      // $FlowIgnore: SectionMetadata ensure that the node is well formated
      return encoder.encodeCallIndirectInstruction(n);

    case "TypeInstruction":
      return encoder.encodeTypeInstruction(n);

    case "Instr":
      // $FlowIgnore
      return encoder.encodeInstr(n);

    case "ModuleExport":
      // $FlowIgnore: SectionMetadata ensure that the node is well formated
      return encoder.encodeModuleExport(n);

    case "Global":
      // $FlowIgnore
      return encoder.encodeGlobal(n);

    case "Func":
      return encoder.encodeFuncBody(n);

    case "IndexInFuncSection":
      return encoder.encodeIndexInFuncSection(n);

    case "StringLiteral":
      return encoder.encodeStringLiteral(n);

    case "Elem":
      return encoder.encodeElem(n);

    default:
      throw new Error("Unsupported encoding for node of type: " + JSON.stringify(n.type));
  }
}

var encodeU32 = encoder.encodeU32;
exports.encodeU32 = encodeU32;


@webassemblyjs/wasm-gen

description: WebAssembly binary format printer


code:
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }

function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

import { decode } from "@webassemblyjs/wasm-parser";
import { shrinkPaddedLEB128 as makeShrinkPaddedLEB128 } from "./leb128.js";

var OptimizerError = /*#__PURE__*/function (_Error) {
  _inherits(OptimizerError, _Error);

  var _super = _createSuper(OptimizerError);

  function OptimizerError(name, initalError) {
    var _this;

    _classCallCheck(this, OptimizerError);

    _this = _super.call(this, "Error while optimizing: " + name + ": " + initalError.message);
    _this.stack = initalError.stack;
    return _this;
  }

  return OptimizerError;
}( /*#__PURE__*/_wrapNativeSuper(Error));

var decoderOpts = {
  ignoreCodeSection: true,
  ignoreDataSection: true
};
export function shrinkPaddedLEB128(uint8Buffer) {
  try {
    var ast = decode(uint8Buffer.buffer, decoderOpts);
    return makeShrinkPaddedLEB128(ast, uint8Buffer);
  } catch (e) {
    throw new OptimizerError("shrinkPaddedLEB128", e);
  }
}


code:
import { traverse, shiftSection } from "@webassemblyjs/ast";
import { encodeU32 } from "@webassemblyjs/wasm-gen/lib/encoder";
import { overrideBytesInBuffer } from "@webassemblyjs/helper-buffer";

function shiftFollowingSections(ast, _ref, deltaInSizeEncoding) {
  var section = _ref.section;
  // Once we hit our section every that is after needs to be shifted by the delta
  var encounteredSection = false;
  traverse(ast, {
    SectionMetadata: function SectionMetadata(path) {
      if (path.node.section === section) {
        encounteredSection = true;
        return;
      }

      if (encounteredSection === true) {
        shiftSection(ast, path.node, deltaInSizeEncoding);
      }
    }
  });
}

export function shrinkPaddedLEB128(ast, uint8Buffer) {
  traverse(ast, {
    SectionMetadata: function SectionMetadata(_ref2) {
      var node = _ref2.node;

      /**
       * Section size
       */
      {
        var newu32Encoded = encodeU32(node.size.value);
        var newu32EncodedLen = newu32Encoded.length;
        var start = node.size.loc.start.column;
        var end = node.size.loc.end.column;
        var oldu32EncodedLen = end - start;

        if (newu32EncodedLen !== oldu32EncodedLen) {
          var deltaInSizeEncoding = oldu32EncodedLen - newu32EncodedLen;
          uint8Buffer = overrideBytesInBuffer(uint8Buffer, start, end, newu32Encoded);
          shiftFollowingSections(ast, node, -deltaInSizeEncoding);
        }
      }
    }
  });
  return uint8Buffer;
}


code:
"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.shrinkPaddedLEB128 = shrinkPaddedLEB128;

var _wasmParser = require("@webassemblyjs/wasm-parser");

var _leb = require("./leb128.js");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }

function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var OptimizerError = /*#__PURE__*/function (_Error) {
  _inherits(OptimizerError, _Error);

  var _super = _createSuper(OptimizerError);

  function OptimizerError(name, initalError) {
    var _this;

    _classCallCheck(this, OptimizerError);

    _this = _super.call(this, "Error while optimizing: " + name + ": " + initalError.message);
    _this.stack = initalError.stack;
    return _this;
  }

  return OptimizerError;
}( /*#__PURE__*/_wrapNativeSuper(Error));

var decoderOpts = {
  ignoreCodeSection: true,
  ignoreDataSection: true
};

function shrinkPaddedLEB128(uint8Buffer) {
  try {
    var ast = (0, _wasmParser.decode)(uint8Buffer.buffer, decoderOpts);
    return (0, _leb.shrinkPaddedLEB128)(ast, uint8Buffer);
  } catch (e) {
    throw new OptimizerError("shrinkPaddedLEB128", e);
  }
}


code:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.shrinkPaddedLEB128 = shrinkPaddedLEB128;

var _ast = require("@webassemblyjs/ast");

var _encoder = require("@webassemblyjs/wasm-gen/lib/encoder");

var _helperBuffer = require("@webassemblyjs/helper-buffer");

function shiftFollowingSections(ast, _ref, deltaInSizeEncoding) {
  var section = _ref.section;
  // Once we hit our section every that is after needs to be shifted by the delta
  var encounteredSection = false;
  (0, _ast.traverse)(ast, {
    SectionMetadata: function SectionMetadata(path) {
      if (path.node.section === section) {
        encounteredSection = true;
        return;
      }

      if (encounteredSection === true) {
        (0, _ast.shiftSection)(ast, path.node, deltaInSizeEncoding);
      }
    }
  });
}

function shrinkPaddedLEB128(ast, uint8Buffer) {
  (0, _ast.traverse)(ast, {
    SectionMetadata: function SectionMetadata(_ref2) {
      var node = _ref2.node;

      /**
       * Section size
       */
      {
        var newu32Encoded = (0, _encoder.encodeU32)(node.size.value);
        var newu32EncodedLen = newu32Encoded.length;
        var start = node.size.loc.start.column;
        var end = node.size.loc.end.column;
        var oldu32EncodedLen = end - start;

        if (newu32EncodedLen !== oldu32EncodedLen) {
          var deltaInSizeEncoding = oldu32EncodedLen - newu32EncodedLen;
          uint8Buffer = (0, _helperBuffer.overrideBytesInBuffer)(uint8Buffer, start, end, newu32Encoded);
          shiftFollowingSections(ast, node, -deltaInSizeEncoding);
        }
      }
    }
  });
  return uint8Buffer;
}


code:
# @webassemblyjs/wasm-parser

> WebAssembly binary format parser

## Installation

```sh
yarn add @webassemblyjs/wasm-parser
```

## Usage

```js
import { decode } from "@webassemblyjs/wasm-parser";
import { readFileSync } from "fs";

const binary = readFileSync("/path/to/module.wasm");

const decoderOpts = {};
const ast = decode(binary, decoderOpts);
```

### Decoder options

- `dump`: print dump information while decoding (default `false`)
- `ignoreCodeSection`: ignore the code section (default `false`)
- `ignoreDataSection`: ignore the data section (default `false`)