-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathsvgo-node.js
99 lines (93 loc) · 2.47 KB
/
svgo-node.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
'use strict';
const os = require('os');
const fs = require('fs');
const { pathToFileURL } = require('url');
const path = require('path');
const {
extendDefaultPlugins,
optimize: optimizeAgnostic,
createContentItem,
} = require('./svgo.js');
exports.extendDefaultPlugins = extendDefaultPlugins;
exports.createContentItem = createContentItem;
const importConfig = async (configFile) => {
let config;
try {
// dynamic import expects file url instead of path and may fail
// when windows path is provided
const { default: imported } = await import(pathToFileURL(configFile));
config = imported;
} catch (importError) {
// TODO remove require in v3
try {
config = require(configFile);
} catch (requireError) {
// throw original error if es module is detected
if (requireError.code === 'ERR_REQUIRE_ESM') {
throw importError;
} else {
throw requireError;
}
}
}
if (config == null || typeof config !== 'object' || Array.isArray(config)) {
throw Error(`Invalid config file "${configFile}"`);
}
return config;
};
const isFile = async (file) => {
try {
const stats = await fs.promises.stat(file);
return stats.isFile();
} catch {
return false;
}
};
const loadConfig = async (configFile, cwd = process.cwd()) => {
if (configFile != null) {
if (path.isAbsolute(configFile)) {
return await importConfig(configFile);
} else {
return await importConfig(path.join(cwd, configFile));
}
}
let dir = cwd;
// eslint-disable-next-line no-constant-condition
while (true) {
const js = path.join(dir, 'svgo.config.js');
if (await isFile(js)) {
return await importConfig(js);
}
const mjs = path.join(dir, 'svgo.config.mjs');
if (await isFile(mjs)) {
return await importConfig(mjs);
}
const cjs = path.join(dir, 'svgo.config.cjs');
if (await isFile(cjs)) {
return await importConfig(cjs);
}
const parent = path.dirname(dir);
if (dir === parent) {
return null;
}
dir = parent;
}
};
exports.loadConfig = loadConfig;
const optimize = (input, config) => {
if (config == null) {
config = {};
}
if (typeof config !== 'object') {
throw Error('Config should be an object');
}
return optimizeAgnostic(input, {
...config,
js2svg: {
// platform specific default for end of line
eol: os.EOL === '\r\n' ? 'crlf' : 'lf',
...config.js2svg,
},
});
};
exports.optimize = optimize;