common.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.makeDataUriToBuffer = void 0;
  4. /**
  5. * Returns a `Buffer` instance from the given data URI `uri`.
  6. *
  7. * @param {String} uri Data URI to turn into a Buffer instance
  8. */
  9. const makeDataUriToBuffer = (convert) => (uri) => {
  10. uri = String(uri);
  11. if (!/^data:/i.test(uri)) {
  12. throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
  13. }
  14. // strip newlines
  15. uri = uri.replace(/\r?\n/g, '');
  16. // split the URI up into the "metadata" and the "data" portions
  17. const firstComma = uri.indexOf(',');
  18. if (firstComma === -1 || firstComma <= 4) {
  19. throw new TypeError('malformed data: URI');
  20. }
  21. // remove the "data:" scheme and parse the metadata
  22. const meta = uri.substring(5, firstComma).split(';');
  23. let charset = '';
  24. let base64 = false;
  25. const type = meta[0] || 'text/plain';
  26. let typeFull = type;
  27. for (let i = 1; i < meta.length; i++) {
  28. if (meta[i] === 'base64') {
  29. base64 = true;
  30. }
  31. else if (meta[i]) {
  32. typeFull += `;${meta[i]}`;
  33. if (meta[i].indexOf('charset=') === 0) {
  34. charset = meta[i].substring(8);
  35. }
  36. }
  37. }
  38. // defaults to US-ASCII only if type is not provided
  39. if (!meta[0] && !charset.length) {
  40. typeFull += ';charset=US-ASCII';
  41. charset = 'US-ASCII';
  42. }
  43. // get the encoded data portion and decode URI-encoded chars
  44. const data = unescape(uri.substring(firstComma + 1));
  45. const buffer = base64 ? convert.base64ToArrayBuffer(data) : convert.stringToBuffer(data);
  46. return {
  47. type,
  48. typeFull,
  49. charset,
  50. buffer,
  51. };
  52. };
  53. exports.makeDataUriToBuffer = makeDataUriToBuffer;
  54. //# sourceMappingURL=common.js.map