UNPKG

2.91 kBJavaScriptView Raw
1'use strict';
2
3const { parseSvg } = require('./parser.js');
4const { stringifySvg } = require('./stringifier.js');
5const { builtin } = require('./builtin.js');
6const { invokePlugins } = require('./svgo/plugins.js');
7const { encodeSVGDatauri } = require('./svgo/tools.js');
8
9const pluginsMap = {};
10for (const plugin of builtin) {
11 pluginsMap[plugin.name] = plugin;
12}
13
14const resolvePluginConfig = (plugin) => {
15 if (typeof plugin === 'string') {
16 // resolve builtin plugin specified as string
17 const builtinPlugin = pluginsMap[plugin];
18 if (builtinPlugin == null) {
19 throw Error(`Unknown builtin plugin "${plugin}" specified.`);
20 }
21 return {
22 name: plugin,
23 params: {},
24 fn: builtinPlugin.fn,
25 };
26 }
27 if (typeof plugin === 'object' && plugin != null) {
28 if (plugin.name == null) {
29 throw Error(`Plugin name should be specified`);
30 }
31 // use custom plugin implementation
32 let fn = plugin.fn;
33 if (fn == null) {
34 // resolve builtin plugin implementation
35 const builtinPlugin = pluginsMap[plugin.name];
36 if (builtinPlugin == null) {
37 throw Error(`Unknown builtin plugin "${plugin.name}" specified.`);
38 }
39 fn = builtinPlugin.fn;
40 }
41 return {
42 name: plugin.name,
43 params: plugin.params,
44 fn,
45 };
46 }
47 return null;
48};
49
50const optimize = (input, config) => {
51 if (config == null) {
52 config = {};
53 }
54 if (typeof config !== 'object') {
55 throw Error('Config should be an object');
56 }
57 const maxPassCount = config.multipass ? 10 : 1;
58 let prevResultSize = Number.POSITIVE_INFINITY;
59 let output = '';
60 const info = {};
61 if (config.path != null) {
62 info.path = config.path;
63 }
64 for (let i = 0; i < maxPassCount; i += 1) {
65 info.multipassCount = i;
66 const ast = parseSvg(input, config.path);
67 const plugins = config.plugins || ['preset-default'];
68 if (!Array.isArray(plugins)) {
69 throw Error(
70 'malformed config, `plugins` property must be an array.\nSee more info here: https://github.com/svg/svgo#configuration',
71 );
72 }
73 const resolvedPlugins = plugins
74 .filter((plugin) => plugin != null)
75 .map(resolvePluginConfig);
76
77 if (resolvedPlugins.length < plugins.length) {
78 console.warn(
79 'Warning: plugins list includes null or undefined elements, these will be ignored.',
80 );
81 }
82 const globalOverrides = {};
83 if (config.floatPrecision != null) {
84 globalOverrides.floatPrecision = config.floatPrecision;
85 }
86 invokePlugins(ast, info, resolvedPlugins, null, globalOverrides);
87 output = stringifySvg(ast, config.js2svg);
88 if (output.length < prevResultSize) {
89 input = output;
90 prevResultSize = output.length;
91 } else {
92 break;
93 }
94 }
95 if (config.datauri) {
96 output = encodeSVGDatauri(output, config.datauri);
97 }
98 return {
99 data: output,
100 };
101};
102exports.optimize = optimize;