-
-
Notifications
You must be signed in to change notification settings - Fork 166
Expand file tree
/
Copy pathminify.js
More file actions
412 lines (355 loc) · 11.6 KB
/
minify.js
File metadata and controls
412 lines (355 loc) · 11.6 KB
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/** @typedef {import("./index.js").MinimizedResult} MinimizedResult */
/** @typedef {import("./index.js").CustomOptions} CustomOptions */
/** @typedef {import("./index.js").RawSourceMap} RawSourceMap */
/**
* @template T
* @typedef {import("./index.js").MinimizerOptions<T>} MinimizerOptions
*/
const VLQ_BASE64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* Encode a single integer as Base64 VLQ as used by the source-map spec.
* @param {number} value integer to encode
* @returns {string} encoded VLQ characters
*/
/* eslint-disable prefer-destructuring, no-eq-null, eqeqeq */
/**
* @param {number} value integer to encode
* @returns {string} encoded VLQ characters
*/
function encodeVlq(value) {
let vlq = value < 0 ? (-value << 1) | 1 : value << 1;
let out = "";
do {
let digit = vlq & 0b11111;
vlq >>>= 5;
if (vlq > 0) {
digit |= 0b100000;
}
out += VLQ_BASE64[digit];
} while (vlq > 0);
return out;
}
/**
* Encode decoded source-map mappings (per-line arrays of segments) back into
* the spec's `mappings` string.
* @param {number[][][]} decoded mappings as nested arrays of segments
* @returns {string} encoded `mappings` field
*/
function encodeMappings(decoded) {
let result = "";
let prevSourceIdx = 0;
let prevOriginalLine = 0;
let prevOriginalColumn = 0;
let prevNameIdx = 0;
for (let line = 0; line < decoded.length; line++) {
if (line > 0) {
result += ";";
}
let prevGeneratedColumn = 0;
const segments = decoded[line];
for (let i = 0; i < segments.length; i++) {
if (i > 0) {
result += ",";
}
const seg = segments[i];
result += encodeVlq(seg[0] - prevGeneratedColumn);
prevGeneratedColumn = seg[0];
if (seg.length >= 4) {
result += encodeVlq(seg[1] - prevSourceIdx);
prevSourceIdx = seg[1];
result += encodeVlq(seg[2] - prevOriginalLine);
prevOriginalLine = seg[2];
result += encodeVlq(seg[3] - prevOriginalColumn);
prevOriginalColumn = seg[3];
if (seg.length >= 5) {
result += encodeVlq(seg[4] - prevNameIdx);
prevNameIdx = seg[4];
}
}
}
}
return result;
}
/**
* Compose a freshly-produced source map with the input source map fed to
* the minimizer. `currentMap` represents `name → step-output` and
* `prevMap` represents `original → name`; the result represents
* `original → step-output`.
*
* TODO: replace with a webpack-sources helper once one is exposed —
* `SourceMapSource` already composes one level via `innerSourceMap`,
* see https://github.com/webpack/webpack-sources for the proposal to
* expose it as a public `composeSourceMaps` (or n-step `SourceMapSource`).
* @param {RawSourceMap | undefined} currentMap map produced by the minimizer
* @param {RawSourceMap | undefined} prevMap input source map fed to the minimizer
* @param {string} name name of the asset that the current map points to
* @returns {RawSourceMap | undefined} composed map
*/
function composeSourceMaps(currentMap, prevMap, name) {
if (!currentMap || !prevMap) {
return currentMap;
}
// Custom minimizers may return the map as a JSON string (e.g. terser's
// default output). `TraceMap` accepts both shapes, but we still hand
// back the original `currentMap` (string preserved) when the previous
// map can't be combined.
const {
TraceMap,
decodedMappings,
originalPositionFor,
sourceContentFor,
} = require("@jridgewell/trace-mapping");
const current = new TraceMap(
/** @type {import("@jridgewell/trace-mapping").SourceMapInput} */ (
/** @type {unknown} */ (currentMap)
),
);
const previous = new TraceMap(
/** @type {import("@jridgewell/trace-mapping").SourceMapInput} */ (
/** @type {unknown} */ (prevMap)
),
);
/** @type {string[]} */
const sources = [];
/** @type {(string | null)[]} */
const sourcesContent = [];
/** @type {string[]} */
const names = [];
/** @type {Map<string, number>} */
const sourceIdx = new Map();
/** @type {Map<string, number>} */
const nameIdx = new Map();
/**
* @param {string | null | undefined} source source identifier
* @param {string | undefined} content source content (when available)
* @returns {number} index assigned in the composed map
*/
const getSourceIdx = (source, content) => {
const key = source || "";
let idx = sourceIdx.get(key);
if (typeof idx === "undefined") {
idx = sources.length;
sources.push(key);
sourcesContent.push(typeof content === "string" ? content : null);
sourceIdx.set(key, idx);
} else if (typeof content === "string" && sourcesContent[idx] === null) {
sourcesContent[idx] = content;
}
return idx;
};
/**
* @param {string | null | undefined} value name
* @returns {number} index assigned in the composed map
*/
const getNameIdx = (value) => {
if (typeof value !== "string") {
return -1;
}
let idx = nameIdx.get(value);
if (typeof idx === "undefined") {
idx = names.length;
names.push(value);
nameIdx.set(value, idx);
}
return idx;
};
const decoded = decodedMappings(current);
const currentSources = current.sources.map(
/**
* @param {string | null} source source from current map
* @returns {string} normalized source string
*/
(source) => source || "",
);
const currentNames = current.names;
/** @type {number[][][]} */
const composed = [];
for (let line = 0; line < decoded.length; line++) {
/** @type {number[][]} */
const newSegments = [];
for (const rawSeg of decoded[line]) {
const seg = /** @type {number[]} */ (rawSeg);
// Single-element segment is just a generated column with no source info
if (seg.length < 4) {
newSegments.push([seg[0]]);
continue;
}
const sourceName = currentSources[seg[1]];
const origLine = /** @type {number} */ (seg[2]);
const origCol = /** @type {number} */ (seg[3]);
const segName =
seg.length >= 5
? currentNames[seg[4]]
: /** @type {string | null} */ (null);
// When the segment points back at our intermediate `name`, look up
// the original position in the previous map and emit a mapping that
// points all the way back. Otherwise keep the segment as-is.
if (sourceName === name) {
const orig = originalPositionFor(previous, {
line: origLine + 1,
column: origCol,
});
if (
typeof orig.source !== "string" ||
orig.line == null ||
orig.column == null
) {
continue;
}
const content = sourceContentFor(previous, orig.source) || undefined;
const newSrcIdx = getSourceIdx(orig.source, content);
const finalName =
typeof orig.name === "string" && orig.name ? orig.name : segName;
if (typeof finalName === "string") {
newSegments.push([
seg[0],
newSrcIdx,
orig.line - 1,
orig.column,
getNameIdx(finalName),
]);
} else {
newSegments.push([seg[0], newSrcIdx, orig.line - 1, orig.column]);
}
} else {
const content = sourceContentFor(current, sourceName) || undefined;
const newSrcIdx = getSourceIdx(sourceName, content);
if (typeof segName === "string") {
newSegments.push([
seg[0],
newSrcIdx,
origLine,
origCol,
getNameIdx(segName),
]);
} else {
newSegments.push([seg[0], newSrcIdx, origLine, origCol]);
}
}
}
composed.push(newSegments);
}
const result =
/** @type {RawSourceMap} */
(
/** @type {unknown} */ ({
version: 3,
sources,
names,
mappings: encodeMappings(composed),
})
);
if (currentMap.file) {
result.file = currentMap.file;
}
if (sourcesContent.some((value) => typeof value === "string")) {
result.sourcesContent =
/** @type {string[]} */
(/** @type {unknown} */ (sourcesContent));
}
return result;
}
/* eslint-enable prefer-destructuring, no-eq-null, eqeqeq */
/**
* @template T
* @param {import("./index.js").InternalOptions<T>} options options
* @returns {Promise<MinimizedResult>} minified result
*/
async function minify(options) {
const { name, input, inputSourceMap, extractComments, module, ecma } =
options;
const { implementation, options: minimizerOptions } = options.minimizer;
const implementations = Array.isArray(implementation)
? implementation
: [implementation];
/** @type {string | undefined} */
let lastCode;
/** @type {RawSourceMap | undefined} */
let lastMap;
/** @type {(Error | string)[]} */
const warnings = [];
/** @type {(Error | string)[]} */
const errors = [];
/** @type {string[]} */
const extractedComments = [];
for (let i = 0; i < implementations.length; i++) {
const currentImplementation =
/** @type {import("./index.js").BasicMinimizerImplementation<T> & import("./index.js").MinimizeFunctionHelpers} */
(implementations[i]);
const baseOptions =
/** @type {import("./index.js").MinimizerOptions<T> & { module?: boolean, ecma?: number | string }} */
(
Array.isArray(minimizerOptions)
? minimizerOptions[i] || {}
: minimizerOptions || {}
);
const currentInput = typeof lastCode === "string" ? lastCode : input;
const currentMap = typeof lastCode === "string" ? lastMap : inputSourceMap;
// Overlay `module` and `ecma` without mutating the caller's options so
// a single options object can be reused safely across assets.
const currentOptions =
/** @type {import("./index.js").MinimizerOptions<T>} */
({
...baseOptions,
module: baseOptions.module || module,
ecma: baseOptions.ecma || ecma,
});
const result = await currentImplementation(
{ [name]: currentInput },
currentMap,
currentOptions,
extractComments,
);
if (result.warnings && result.warnings.length > 0) {
warnings.push(...result.warnings);
}
if (result.errors && result.errors.length > 0) {
errors.push(...result.errors);
}
if (result.extractedComments && result.extractedComments.length > 0) {
extractedComments.push(...result.extractedComments);
}
if (typeof result.code === "string") {
lastCode = result.code;
// The minimizer's output map is `name → step-output`. Chain it with
// the previous accumulated map so that across an array of minimizers
// the final map points back to the original sources.
lastMap = composeSourceMaps(result.map, currentMap, name);
}
}
return {
code: lastCode,
map: lastMap,
warnings,
errors,
extractedComments,
};
}
/**
* @param {string} options options
* @returns {Promise<MinimizedResult>} minified result
*/
async function transform(options) {
// 'use strict' => this === undefined (Clean Scope)
// Safer for possible security issues, albeit not critical at all here
const evaluatedOptions =
/**
* @template T
* @type {import("./index.js").InternalOptions<T>}
*/
(
// eslint-disable-next-line no-new-func
new Function(
"exports",
"require",
"module",
"__filename",
"__dirname",
`'use strict'\nreturn ${options}`,
// eslint-disable-next-line n/exports-style
)(exports, require, module, __filename, __dirname)
);
return minify(evaluatedOptions);
}
module.exports = { minify, transform };