forked from vercel/next.js
/
index.js
345 lines (294 loc) · 9.52 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
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
// @ts-nocheck
import * as path from 'path'
import {
webpack,
ModuleFilenameHelpers,
sources,
} from 'next/dist/compiled/webpack/webpack'
import pLimit from 'next/dist/compiled/p-limit'
import { Worker } from 'next/dist/compiled/jest-worker'
import { spans } from '../../profiling-plugin'
function getEcmaVersion(environment) {
// ES 6th
if (
environment.arrowFunction ||
environment.const ||
environment.destructuring ||
environment.forOf ||
environment.module
) {
return 2015
}
// ES 11th
if (environment.bigIntLiteral || environment.dynamicImport) {
return 2020
}
return 5
}
function buildError(error, file) {
if (error.line) {
return new Error(
`${file} from Terser\n${error.message} [${file}:${error.line},${
error.col
}]${
error.stack ? `\n${error.stack.split('\n').slice(1).join('\n')}` : ''
}`
)
}
if (error.stack) {
return new Error(`${file} from Terser\n${error.message}\n${error.stack}`)
}
return new Error(`${file} from Terser\n${error.message}`)
}
const debugMinify = process.env.NEXT_DEBUG_MINIFY
export class TerserPlugin {
constructor(options = {}) {
const { terserOptions = {}, parallel, swcMinify } = options
this.options = {
swcMinify,
parallel,
terserOptions,
}
}
async optimize(
compiler,
compilation,
assets,
optimizeOptions,
cache,
{ SourceMapSource, RawSource }
) {
const compilationSpan = spans.get(compilation) || spans.get(compiler)
const terserSpan = compilationSpan.traceChild(
'terser-webpack-plugin-optimize'
)
terserSpan.setAttribute('compilationName', compilation.name)
return terserSpan.traceAsyncFn(async () => {
let numberOfAssetsForMinify = 0
const assetsList = Object.keys(assets)
const assetsForMinify = await Promise.all(
assetsList
.filter((name) => {
if (
!ModuleFilenameHelpers.matchObject.bind(
// eslint-disable-next-line no-undefined
undefined,
{ test: /\.[cm]?js(\?.*)?$/i }
)(name)
) {
return false
}
const res = compilation.getAsset(name)
if (!res) {
console.log(name)
return false
}
// don't minify _middleware as it can break in some cases
// and doesn't provide too much of a benefit as it's server-side
if (
name.match(
/(middleware-runtime\.js|middleware-chunks|_middleware\.js$)/
)
) {
return false
}
const { info } = res
// Skip double minimize assets from child compilation
if (info.minimized) {
return false
}
return true
})
.map(async (name) => {
const { info, source } = compilation.getAsset(name)
const eTag = cache.getLazyHashedEtag(source)
const output = await cache.getPromise(name, eTag)
if (!output) {
numberOfAssetsForMinify += 1
}
if (debugMinify && debugMinify === '1') {
console.dir(
{
name,
source: source.source().toString(),
},
{
breakLength: Infinity,
maxStringLength: Infinity,
}
)
}
return { name, info, inputSource: source, output, eTag }
})
)
const numberOfWorkers = Math.min(
numberOfAssetsForMinify,
optimizeOptions.availableNumberOfCores
)
let initializedWorker
// eslint-disable-next-line consistent-return
const getWorker = () => {
if (this.options.swcMinify) {
return {
minify: async (options) => {
const result = await require('../../../../swc').minify(
options.input,
{
...(options.inputSourceMap
? {
sourceMap: {
content: JSON.stringify(options.inputSourceMap),
},
}
: {}),
compress: true,
mangle: true,
}
)
return result
},
}
}
if (initializedWorker) {
return initializedWorker
}
initializedWorker = new Worker(path.join(__dirname, './minify.js'), {
numWorkers: numberOfWorkers,
enableWorkerThreads: true,
})
initializedWorker.getStdout().pipe(process.stdout)
initializedWorker.getStderr().pipe(process.stderr)
return initializedWorker
}
const limit = pLimit(
// When using the SWC minifier the limit will be handled by Node.js
this.options.swcMinify
? Infinity
: numberOfAssetsForMinify > 0
? numberOfWorkers
: Infinity
)
const scheduledTasks = []
for (const asset of assetsForMinify) {
scheduledTasks.push(
limit(async () => {
const { name, inputSource, info, eTag } = asset
let { output } = asset
const minifySpan = terserSpan.traceChild('minify-js')
minifySpan.setAttribute('name', name)
minifySpan.setAttribute(
'cache',
typeof output === 'undefined' ? 'MISS' : 'HIT'
)
return minifySpan.traceAsyncFn(async () => {
if (!output) {
const { source: sourceFromInputSource, map: inputSourceMap } =
inputSource.sourceAndMap()
const input = Buffer.isBuffer(sourceFromInputSource)
? sourceFromInputSource.toString()
: sourceFromInputSource
const options = {
name,
input,
inputSourceMap,
terserOptions: { ...this.options.terserOptions },
}
if (typeof options.terserOptions.module === 'undefined') {
if (typeof info.javascriptModule !== 'undefined') {
options.terserOptions.module = info.javascriptModule
} else if (/\.mjs(\?.*)?$/i.test(name)) {
options.terserOptions.module = true
} else if (/\.cjs(\?.*)?$/i.test(name)) {
options.terserOptions.module = false
}
}
try {
output = await getWorker().minify(options)
} catch (error) {
compilation.errors.push(buildError(error, name))
return
}
if (output.map) {
output.source = new SourceMapSource(
output.code,
name,
output.map,
input,
/** @type {SourceMapRawSourceMap} */ (inputSourceMap),
true
)
} else {
output.source = new RawSource(output.code)
}
await cache.storePromise(name, eTag, {
source: output.source,
})
}
/** @type {AssetInfo} */
const newInfo = { minimized: true }
const { source } = output
compilation.updateAsset(name, source, newInfo)
})
})
)
}
await Promise.all(scheduledTasks)
if (initializedWorker) {
await initializedWorker.end()
}
})
}
/**
* @param {Compiler} compiler
* @returns {void}
*/
apply(compiler) {
const { SourceMapSource, RawSource } = compiler?.webpack?.sources || sources
const { output } = compiler.options
if (typeof this.options.terserOptions.ecma === 'undefined') {
this.options.terserOptions.ecma = getEcmaVersion(output.environment || {})
}
const pluginName = this.constructor.name
const availableNumberOfCores = this.options.parallel
compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
const cache = compilation.getCache('TerserWebpackPlugin')
const handleHashForChunk = (hash, chunk) => {
// increment 'c' to invalidate cache
hash.update('c')
}
const JSModulesHooks =
webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(
compilation
)
JSModulesHooks.chunkHash.tap(pluginName, (chunk, hash) => {
if (!chunk.hasRuntime()) return
return handleHashForChunk(hash, chunk)
})
compilation.hooks.processAssets.tapPromise(
{
name: pluginName,
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
},
(assets) =>
this.optimize(
compiler,
compilation,
assets,
{
availableNumberOfCores,
},
cache,
{ SourceMapSource, RawSource }
)
)
compilation.hooks.statsPrinter.tap(pluginName, (stats) => {
stats.hooks.print
.for('asset.info.minimized')
.tap('terser-webpack-plugin', (minimized, { green, formatFlag }) =>
// eslint-disable-next-line no-undefined
minimized ? green(formatFlag('minimized')) : undefined
)
})
})
}
}