{"size": 1475, "ext": "js", "max_stars_repo_path": "scripts/render/processSvg.js", "max_stars_repo_name": "it-is-not/lucide", "max_stars_repo_stars_event_min_datetime": "2020-06-13T18:20:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-30T02:33:22.000Z", "max_issues_repo_path": "scripts/render/processSvg.js", "max_issues_repo_name": "it-is-not/lucide", "max_issues_repo_issues_event_min_datetime": "2020-06-13T16:39:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-06T04:02:13.000Z", "max_forks_repo_path": "scripts/render/processSvg.js", "max_forks_repo_name": "it-is-not/lucide", "max_forks_repo_forks_event_min_datetime": "2020-06-15T10:33:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T04:07:10.000Z"}
{"max_stars_count": 23, "max_issues_count": 68, "max_forks_count": 12, "avg_line_length": 23.4126984127, "max_line_length": 73, "alphanum_fraction": 0.6115254237}
/* eslint-disable import/no-extraneous-dependencies */
import { optimize } from 'svgo';
import { format } from 'prettier';
import { parseSync, stringify } from 'svgson';
import DEFAULT_ATTRS from './default-attrs.json';

/**
 * Optimize SVG with `svgo`.
 * @param {string} svg - An SVG string.
 * @returns {Promise<string>} An optimized svg
 */
async function optimizeSvg(svg) {
  const result = optimize(svg, {
    plugins: [
      {
        name: 'preset-default',
        params: {
          overrides: {
            convertShapeToPath: false,
            mergePaths: false,
            removeAttrs: {
              attrs: '(fill|stroke.*)',
            },
          },
        },
      },
    ],
  });

  return result.data;
}

/**
 * Set default attibutes on SVG.
 * @param {string} svg - An SVG string.
 * @returns {string} An SVG string, included with the default attributes.
 */
function setAttrs(svg) {
  const contents = parseSync(svg);

  contents.attributes = DEFAULT_ATTRS;

  return stringify(contents);
}

/**
 * Process SVG string.
 * @param {string} svg An SVG string.
 * @returns {Promise<string>} An optimized svg
 */
function processSvg(svg) {
  return (
    optimizeSvg(svg)
      .then(setAttrs)
      .then(optimizedSvg => format(optimizedSvg, { parser: 'babel' }))
      // remove semicolon inserted by prettier
      // because prettier thinks it's formatting JSX not HTML
      .then(svg => svg.replace(/;/g, ''))
  );
}

export default processSvg;
