UNPKG

2.29 kBJavaScriptView Raw
1'use strict';
2
3const os = require('os');
4const fs = require('fs');
5const { pathToFileURL } = require('url');
6const path = require('path');
7const { optimize: optimizeAgnostic } = require('./svgo.js');
8
9const importConfig = async (configFile) => {
10 let config;
11 // at the moment dynamic import may randomly fail with segfault
12 // to workaround this for some users .cjs extension is loaded
13 // exclusively with require
14 if (configFile.endsWith('.cjs')) {
15 config = require(configFile);
16 } else {
17 // dynamic import expects file url instead of path and may fail
18 // when windows path is provided
19 const { default: imported } = await import(pathToFileURL(configFile));
20 config = imported;
21 }
22 if (config == null || typeof config !== 'object' || Array.isArray(config)) {
23 throw Error(`Invalid config file "${configFile}"`);
24 }
25 return config;
26};
27
28const isFile = async (file) => {
29 try {
30 const stats = await fs.promises.stat(file);
31 return stats.isFile();
32 } catch {
33 return false;
34 }
35};
36
37const loadConfig = async (configFile, cwd = process.cwd()) => {
38 if (configFile != null) {
39 if (path.isAbsolute(configFile)) {
40 return await importConfig(configFile);
41 } else {
42 return await importConfig(path.join(cwd, configFile));
43 }
44 }
45 let dir = cwd;
46 // eslint-disable-next-line no-constant-condition
47 while (true) {
48 const js = path.join(dir, 'svgo.config.js');
49 if (await isFile(js)) {
50 return await importConfig(js);
51 }
52 const mjs = path.join(dir, 'svgo.config.mjs');
53 if (await isFile(mjs)) {
54 return await importConfig(mjs);
55 }
56 const cjs = path.join(dir, 'svgo.config.cjs');
57 if (await isFile(cjs)) {
58 return await importConfig(cjs);
59 }
60 const parent = path.dirname(dir);
61 if (dir === parent) {
62 return null;
63 }
64 dir = parent;
65 }
66};
67exports.loadConfig = loadConfig;
68
69const optimize = (input, config) => {
70 if (config == null) {
71 config = {};
72 }
73 if (typeof config !== 'object') {
74 throw Error('Config should be an object');
75 }
76 return optimizeAgnostic(input, {
77 ...config,
78 js2svg: {
79 // platform specific default for end of line
80 eol: os.EOL === '\r\n' ? 'crlf' : 'lf',
81 ...config.js2svg,
82 },
83 });
84};
85exports.optimize = optimize;