UNPKG

2.36 kBJavaScriptView Raw
1'use strict';
2
3/**
4 * SVGO is a Nodejs-based tool for optimizing SVG vector graphics files.
5 *
6 * @see https://github.com/svg/svgo
7 *
8 * @author Kir Belevich <kir@soulshine.in> (https://github.com/deepsweet)
9 * @copyright © 2012 Kir Belevich
10 * @license MIT https://raw.githubusercontent.com/svg/svgo/master/LICENSE
11 */
12
13const {
14 defaultPlugins,
15 resolvePluginConfig,
16 extendDefaultPlugins
17} = require('./svgo/config.js');
18const svg2js = require('./svgo/svg2js.js');
19const js2svg = require('./svgo/js2svg.js');
20const invokePlugins = require('./svgo/plugins.js');
21const JSAPI = require('./svgo/jsAPI.js');
22const { encodeSVGDatauri } = require('./svgo/tools.js');
23
24exports.extendDefaultPlugins = extendDefaultPlugins;
25
26const optimize = (input, config) => {
27 if (config == null) {
28 config = {};
29 }
30 if (typeof config !== 'object') {
31 throw Error('Config should be an object')
32 }
33 const maxPassCount = config.multipass ? 10 : 1;
34 let prevResultSize = Number.POSITIVE_INFINITY;
35 let svgjs = null;
36 const info = {}
37 if (config.path != null) {
38 info.path = config.path;
39 }
40 for (let i = 0; i < maxPassCount; i += 1) {
41 info.multipassCount = i;
42 svgjs = svg2js(input);
43 if (svgjs.error == null) {
44 const plugins = config.plugins || defaultPlugins;
45 if (Array.isArray(plugins) === false) {
46 throw Error('Invalid plugins list. Provided \'plugins\' in config should be an array.');
47 }
48 const resolvedPlugins = plugins.map(plugin => resolvePluginConfig(plugin, config))
49 svgjs = invokePlugins(svgjs, info, resolvedPlugins);
50 }
51 svgjs = js2svg(svgjs, config.js2svg);
52 if (svgjs.error) {
53 throw Error(svgjs.error);
54 }
55 if (svgjs.data.length < prevResultSize) {
56 input = svgjs.data;
57 prevResultSize = svgjs.data.length
58 } else {
59 if (config.datauri) {
60 svgjs.data = encodeSVGDatauri(svgjs.data, config.datauri);
61 }
62 if (config.path != null) {
63 svgjs.path = config.path;
64 }
65 return svgjs;
66 }
67 }
68 return svgjs;
69};
70exports.optimize = optimize;
71
72/**
73 * The factory that creates a content item with the helper methods.
74 *
75 * @param {Object} data which is passed to jsAPI constructor
76 * @returns {JSAPI} content item
77 */
78const createContentItem = (data) => {
79 return new JSAPI(data);
80};
81exports.createContentItem = createContentItem;