svgo.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict';
  2. const {
  3. defaultPlugins,
  4. resolvePluginConfig,
  5. extendDefaultPlugins,
  6. } = require('./svgo/config.js');
  7. const { parseSvg } = require('./parser.js');
  8. const { stringifySvg } = require('./stringifier.js');
  9. const { invokePlugins } = require('./svgo/plugins.js');
  10. const JSAPI = require('./svgo/jsAPI.js');
  11. const { encodeSVGDatauri } = require('./svgo/tools.js');
  12. exports.extendDefaultPlugins = extendDefaultPlugins;
  13. const optimize = (input, config) => {
  14. if (config == null) {
  15. config = {};
  16. }
  17. if (typeof config !== 'object') {
  18. throw Error('Config should be an object');
  19. }
  20. const maxPassCount = config.multipass ? 10 : 1;
  21. let prevResultSize = Number.POSITIVE_INFINITY;
  22. let svgjs = null;
  23. const info = {};
  24. if (config.path != null) {
  25. info.path = config.path;
  26. }
  27. for (let i = 0; i < maxPassCount; i += 1) {
  28. info.multipassCount = i;
  29. // TODO throw this error in v3
  30. try {
  31. svgjs = parseSvg(input, config.path);
  32. } catch (error) {
  33. return { error: error.toString(), modernError: error };
  34. }
  35. if (svgjs.error != null) {
  36. if (config.path != null) {
  37. svgjs.path = config.path;
  38. }
  39. return svgjs;
  40. }
  41. const plugins = config.plugins || defaultPlugins;
  42. if (Array.isArray(plugins) === false) {
  43. throw Error(
  44. "Invalid plugins list. Provided 'plugins' in config should be an array."
  45. );
  46. }
  47. const resolvedPlugins = plugins.map(resolvePluginConfig);
  48. const globalOverrides = {};
  49. if (config.floatPrecision != null) {
  50. globalOverrides.floatPrecision = config.floatPrecision;
  51. }
  52. svgjs = invokePlugins(svgjs, info, resolvedPlugins, null, globalOverrides);
  53. svgjs = stringifySvg(svgjs, config.js2svg);
  54. if (svgjs.data.length < prevResultSize) {
  55. input = svgjs.data;
  56. prevResultSize = svgjs.data.length;
  57. } else {
  58. if (config.datauri) {
  59. svgjs.data = encodeSVGDatauri(svgjs.data, config.datauri);
  60. }
  61. if (config.path != null) {
  62. svgjs.path = config.path;
  63. }
  64. return svgjs;
  65. }
  66. }
  67. return svgjs;
  68. };
  69. exports.optimize = optimize;
  70. /**
  71. * The factory that creates a content item with the helper methods.
  72. *
  73. * @param {Object} data which is passed to jsAPI constructor
  74. * @returns {JSAPI} content item
  75. */
  76. const createContentItem = (data) => {
  77. return new JSAPI(data);
  78. };
  79. exports.createContentItem = createContentItem;