-
-
Notifications
You must be signed in to change notification settings - Fork 278
/
index.js
213 lines (183 loc) · 5.19 KB
/
index.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import url from 'url';
import path from 'path';
import normalize from 'normalize-url';
import typeByMime from '../config/resource-type-by-mime.js';
import typeByExt from '../config/resource-type-by-ext.js';
import logger from '../logger.js';
const MAX_FILENAME_LENGTH = 255;
const IS_URL = /^((http[s]?:)?\/\/)/;
function isUrl (path) {
return IS_URL.test(path);
}
function getUrl (currentUrl, path) {
const pathObject = url.parse(path);
if (isUrl(path) && !pathObject.protocol) {
const urlObject = url.parse(currentUrl);
pathObject.protocol = urlObject.protocol;
path = url.format(pathObject);
}
return url.resolve(currentUrl, path);
}
function getUnixPath (filepath) {
return filepath.replace(/\\/g, '/');
}
function getRelativePath (path1, path2) {
const dirname = path.dirname(path1);
const relativePath = path.relative(dirname, path2);
const escaped = relativePath
.split(path.sep)
.map(pathComponent => encodeURIComponent(pathComponent).replace(/['()]/g, c => '%' + c.charCodeAt(0).toString(16)))
.join(path.sep);
return getUnixPath(escaped);
}
/**
* Returns decoded pathname from url
* Example: https://example.co/path/logo%20(1).svg => /path/logo (1).svg
* @param u - url
* @returns {string} decoded pathname
*/
function getPathnameFromUrl (u) {
const pathname = url.parse(u).pathname;
try {
return decodeURI(pathname);
} catch (e) {
return pathname;
}
}
/**
* Returns filename from given url
* Example: http://example.com/some/path/file.js => file.js
* @param {string} u - url
* @returns {string} filename
*/
function getFilenameFromUrl (u) {
return path.basename(getPathnameFromUrl(u));
}
/**
* Returns relative path from given url
* Example: http://example.com/some/path/file.js => some/path/file.js
* @param {string} u - url
* @returns {string} path
*/
function getFilepathFromUrl (u) {
const nu = normalizeUrl(u, {removeTrailingSlash: true});
return getPathnameFromUrl(nu).substring(1);
}
function getHashFromUrl (u) {
return url.parse(u).hash || '';
}
/**
* Returns host with port from given url
* Example: http://example.com:8080/some/path/file.js => example.com:8080
* @param {string} u - url
* @returns {string} host with port
*/
function getHostFromUrl (u) {
return url.parse(u).host;
}
/**
* Returns extension for given filepath
* Example: some/path/file.js => .js
* @param {string} filepath
* @returns {string|null} - extension
*/
function getFilenameExtension (filepath) {
return (typeof filepath === 'string') ? path.extname(filepath).toLowerCase() : null;
}
function shortenFilename (filename) {
if (filename.length >= MAX_FILENAME_LENGTH) {
const shortFilename = filename.substring(0, 20) + getFilenameExtension(filename);
logger.debug(`[utils] shorten filename: ${filename} -> ${shortFilename}`);
return shortFilename;
}
return filename;
}
function normalizeUrl (u, opts) {
try {
return normalize(u, extend({removeTrailingSlash: false, stripHash: true}, opts));
} catch (e) {
return u;
}
}
function urlsEqual (url1, url2) {
return normalizeUrl(url1) === normalizeUrl(url2);
}
function isUriSchemaSupported (path) {
const protocol = url.parse(path).protocol;
return !protocol || protocol && isUrl(path);
}
function getTypeByMime (mimeType) {
return typeByMime[mimeType];
}
function getTypeByFilename (filename) {
const ext = getFilenameExtension(filename);
return typeByExt[ext];
}
function extend (first, second) {
return Object.assign({}, first, second);
}
function union (first = [], second = []) {
const merged = first.concat(second);
return merged.filter((item, index, array) => array.findIndex(el => Object.keys(el).every(k => el[k] === item[k])) === index);
}
function isPlainObject (value) {
return value instanceof Object && Object.getPrototypeOf(value) === Object.prototype;
}
function prettifyFilename (filename, {defaultFilename}) {
if (filename === defaultFilename || filename.endsWith('/' + defaultFilename)) {
return filename.slice(0, -defaultFilename.length);
}
return filename;
}
async function series (promises) {
const results = [];
for (let i = 0; i < promises.length; i++) {
const result = await promises[i]();
results.push(result);
}
return results;
}
function getCharsetFromCss (cssText) {
const CHARSET_REGEXP = /(?:@charset\s)(("(.*?)")|('(.*?)'))[\s;]/;
const hasCharset = cssText.startsWith('@charset');
if (hasCharset) {
const charsetMatch = CHARSET_REGEXP.exec(cssText);
const charset = charsetMatch?.[3] || charsetMatch?.[5];
return charset?.toLowerCase() ?? null;
} else {
return null;
}
}
function updateResourceEncoding (resource, encoding) {
logger.debug(`updating encoding of resource ${resource} to ${encoding}`);
const resourceText = resource.getText();
if (resourceText) {
const updatedText = Buffer.from(resourceText, resource.getEncoding()).toString(encoding);
resource.setText(updatedText);
}
resource.setEncoding(encoding);
}
export {
isUrl,
getUrl,
getUnixPath,
getRelativePath,
getFilenameFromUrl,
getFilepathFromUrl,
getFilenameExtension,
getHashFromUrl,
getHostFromUrl,
shortenFilename,
prettifyFilename,
normalizeUrl,
urlsEqual,
isUriSchemaSupported,
getTypeByMime,
getTypeByFilename,
extend,
union,
isPlainObject,
series,
getCharsetFromCss,
updateResourceEncoding
};