encodePacket.browser.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const commons_js_1 = require("./commons.js");
  4. const withNativeBlob = typeof Blob === "function" ||
  5. (typeof Blob !== "undefined" &&
  6. Object.prototype.toString.call(Blob) === "[object BlobConstructor]");
  7. const withNativeArrayBuffer = typeof ArrayBuffer === "function";
  8. // ArrayBuffer.isView method is not defined in IE10
  9. const isView = obj => {
  10. return typeof ArrayBuffer.isView === "function"
  11. ? ArrayBuffer.isView(obj)
  12. : obj && obj.buffer instanceof ArrayBuffer;
  13. };
  14. const encodePacket = ({ type, data }, supportsBinary, callback) => {
  15. if (withNativeBlob && data instanceof Blob) {
  16. if (supportsBinary) {
  17. return callback(data);
  18. }
  19. else {
  20. return encodeBlobAsBase64(data, callback);
  21. }
  22. }
  23. else if (withNativeArrayBuffer &&
  24. (data instanceof ArrayBuffer || isView(data))) {
  25. if (supportsBinary) {
  26. return callback(data);
  27. }
  28. else {
  29. return encodeBlobAsBase64(new Blob([data]), callback);
  30. }
  31. }
  32. // plain string
  33. return callback(commons_js_1.PACKET_TYPES[type] + (data || ""));
  34. };
  35. const encodeBlobAsBase64 = (data, callback) => {
  36. const fileReader = new FileReader();
  37. fileReader.onload = function () {
  38. const content = fileReader.result.split(",")[1];
  39. callback("b" + content);
  40. };
  41. return fileReader.readAsDataURL(data);
  42. };
  43. exports.default = encodePacket;