-
Notifications
You must be signed in to change notification settings - Fork 306
/
config.ts
397 lines (386 loc) · 18 KB
/
config.ts
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
/* spell-checker: disable */
import webpack from 'webpack'
const { ProvidePlugin, DefinePlugin, EnvironmentPlugin } = webpack
import type { Configuration as DevServerConfiguration } from 'webpack-dev-server'
import WebExtensionPlugin from 'webpack-target-webextension'
import TerserPlugin from 'terser-webpack-plugin'
import DevtoolsIgnorePlugin from 'devtools-ignore-webpack-plugin'
import CopyPlugin from 'copy-webpack-plugin'
import HTMLPlugin from 'html-webpack-plugin'
import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin'
import { emitJSONFile } from '@nice-labs/emit-file-webpack-plugin'
import { emitManifestFile } from './plugins/manifest.js'
import { getGitInfo } from './git-info.js'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { readFile, readdir } from 'node:fs/promises'
import { createRequire } from 'node:module'
import { type EntryDescription, normalizeEntryDescription, joinEntryItem } from './utils.js'
import { type BuildFlags, normalizeBuildFlags, computedBuildFlags, computeCacheKey } from './flags.js'
import { ProfilingPlugin } from './plugins/ProfilingPlugin.js'
import './clean-hmr.js'
const __dirname = fileURLToPath(dirname(import.meta.url))
const require = createRequire(import.meta.url)
const patchesDir = join(__dirname, '../../../patches')
const templateContent = readFile(join(__dirname, './template.html'), 'utf8')
const popupTemplateContent = readFile(join(__dirname, './popups.html'), 'utf8')
export async function createConfiguration(_inputFlags: BuildFlags): Promise<webpack.Configuration> {
const VERSION = JSON.parse(await readFile(new URL('../../../package.json', import.meta.url), 'utf-8')).version
const flags = normalizeBuildFlags(_inputFlags)
const computedFlags = computedBuildFlags(flags)
const cacheKey = computeCacheKey(flags, computedFlags)
const productionLike = flags.mode === 'production' || flags.profiling
const nonWebpackJSFiles = join(flags.outputPath, './js')
const polyfillFolder = join(nonWebpackJSFiles, './polyfill')
const pnpmPatches = readdir(patchesDir).then((files) => files.map((x) => join(patchesDir, x)))
const baseConfig = {
name: 'mask',
// to set a correct base path for source map
context: join(__dirname, '../../../'),
mode: flags.mode,
devtool: computedFlags.sourceMapKind,
target: ['web', 'es2022'],
entry: {},
node: {
global: true,
__dirname: false,
__filename: false,
},
experiments: {
futureDefaults: true,
syncImportAssertion: true,
deferImport: { asyncModule: 'error' },
},
cache: {
type: 'filesystem',
buildDependencies: {
config: [fileURLToPath(import.meta.url)],
patches: await pnpmPatches,
},
version: cacheKey,
},
resolve: {
extensionAlias: {
'.js': ['.js', '.tsx', '.ts'],
'.mjs': ['.mjs', '.mts'],
},
extensions: ['.js', '.ts', '.tsx'],
alias: (() => {
const alias: Record<string, string> = {
// conflict with SES
'error-polyfill': require.resolve('./package-overrides/null.mjs'),
}
if (computedFlags.reactProductionProfiling) alias['react-dom$'] = require.resolve('react-dom/profiling')
if (flags.devtools) {
// Note: when devtools is enabled, we will install react-refresh/runtime manually to keep the correct react global hook installation order.
// https://github.com/pmmmwh/react-refresh-webpack-plugin/issues/680
alias[require.resolve('@pmmmwh/react-refresh-webpack-plugin/client/ReactRefreshEntry.js')] =
require.resolve('./package-overrides/null.mjs')
}
return alias
})(),
// Polyfill those Node built-ins
fallback: {
http: require.resolve('stream-http'),
https: require.resolve('https-browserify'),
stream: require.resolve('stream-browserify'),
crypto: require.resolve('crypto-browserify'),
zlib: require.resolve('zlib-browserify'),
'text-encoding': require.resolve('@sinonjs/text-encoding'),
},
conditionNames: ['mask-src', '...'],
},
module: {
parser: {
javascript: {
// Treat as missing export as error
strictExportPresence: true,
},
},
rules: [
// Source map for libraries
computedFlags.sourceMapKind ?
{ test: /\.js$/, enforce: 'pre', use: [require.resolve('source-map-loader')] }
: null,
// Patch old regenerator-runtime
{
test: /\..?js$/,
loader: require.resolve('./loaders/fix-regenerator-runtime.ts'),
},
// TypeScript
{
test: /\.tsx?$/,
parser: { worker: ['OnDemandWorker', '...'] },
// Compile all ts files in the workspace
include: join(__dirname, '../../'),
loader: require.resolve('swc-loader'),
options: {
sourceMaps: !!computedFlags.sourceMapKind,
// https://swc.rs/docs/configuring-swc/
jsc: {
preserveAllComments: true,
parser: {
syntax: 'typescript',
dynamicImport: true,
tsx: true,
},
target: 'es2022',
externalHelpers: true,
transform: {
react: {
runtime: 'automatic',
development: !productionLike,
refresh: flags.reactRefresh && {
refreshReg: '$RefreshReg$',
refreshSig: '$RefreshSig$',
emitFullSignatures: true,
},
},
},
experimental: {
keepImportAssertions: true,
},
},
},
},
// compress svg files
flags.mode === 'production' ?
{
test: /\.svg$/,
loader: require.resolve('svgo-loader'),
// overrides
options: {
js2svg: {
pretty: false,
},
},
dependency(data) {
if (data === '') return false
if (data !== 'url')
throw new TypeError(
'The only import mode valid for a non-JS file is via new URL(). Current import mode: ' +
data,
)
return true
},
type: 'asset/resource',
}
: null,
],
},
plugins: [
new WebExtensionPlugin({ background: { pageEntry: 'background', serviceWorkerEntry: 'backgroundWorker' } }),
flags.sourceMapHideFrameworks !== false &&
new DevtoolsIgnorePlugin({
shouldIgnorePath: (path) => {
if (path.includes('masknet') || path.includes('dimensiondev')) return false
return path.includes('/node_modules/') || path.includes('/webpack/')
},
}),
new ProvidePlugin({
// Polyfill for Node global "Buffer" variable
Buffer: [require.resolve('buffer'), 'Buffer'],
'process.nextTick': require.resolve('next-tick'),
}),
new EnvironmentPlugin({
NODE_ENV: productionLike ? 'production' : flags.mode,
NODE_DEBUG: false,
WEB3_CONSTANTS_RPC: process.env.WEB3_CONSTANTS_RPC ?? '',
MASK_SENTRY_DSN: process.env.MASK_SENTRY_DSN ?? '',
}),
new DefinePlugin({
'process.browser': 'true',
'process.version': JSON.stringify('v20.0.0'),
// MetaMaskInpageProvider => extension-port-stream => readable-stream depends on stdin and stdout
'process.stdout': '/* stdout */ null',
'process.stderr': '/* stdin */ null',
}),
flags.reactRefresh && new ReactRefreshWebpackPlugin({ overlay: false, esModule: true }),
flags.profiling && new ProfilingPlugin(),
...emitManifestFile(flags, computedFlags),
new CopyPlugin({
patterns: [
{ from: join(__dirname, '../public/'), to: flags.outputPath },
{
from: join(__dirname, '../../injected-script/dist/injected-script.js'),
to: nonWebpackJSFiles,
},
{ from: join(__dirname, '../../gun-utils/gun.js'), to: nonWebpackJSFiles },
{ from: join(__dirname, '../../mask-sdk/dist/mask-sdk.js'), to: nonWebpackJSFiles },
{
context: join(__dirname, '../../polyfills/dist/'),
from: '*.js',
to: polyfillFolder,
},
{ from: require.resolve('webextension-polyfill/dist/browser-polyfill.js'), to: polyfillFolder },
{
from:
productionLike ?
require.resolve('../../../node_modules/ses/dist/lockdown.umd.min.js')
: require.resolve('../../../node_modules/ses/dist/lockdown.umd.js'),
to: join(polyfillFolder, 'lockdown.js'),
},
{
from: join(__dirname, '../../sentry/dist/sentry.js'),
to: nonWebpackJSFiles,
},
],
}),
...(() => {
const { BRANCH_NAME, BUILD_DATE, COMMIT_DATE, COMMIT_HASH, DIRTY } = getGitInfo()
const json = {
BRANCH_NAME,
BUILD_DATE,
channel: flags.channel,
COMMIT_DATE,
COMMIT_HASH,
DIRTY,
VERSION,
REACT_DEVTOOLS_EDITOR_URL: flags.devtools ? flags.devtoolsEditorURI : undefined,
}
return [
emitJSONFile({ content: json, name: 'build-info.json' }),
emitJSONFile({ content: { ...json, channel: 'beta' }, name: 'build-info-beta.json' }),
]
})(),
],
// Focus on performance optimization. Not for download size/cache stability optimization.
optimization: {
// we don't need deterministic, and we also don't have chunk request at init we don't need "size"
chunkIds: productionLike ? 'total-size' : 'named',
concatenateModules: productionLike,
flagIncludedChunks: productionLike,
mangleExports: false,
minimize: productionLike,
minimizer: [
new TerserPlugin({
minify: TerserPlugin.swcMinify,
// https://swc.rs/docs/config-js-minify
terserOptions: {
compress: {
drop_debugger: false,
ecma: 2020,
keep_classnames: true,
keep_fnames: true,
keep_infinity: true,
passes: 3,
pure_getters: false,
sequences: false,
},
mangle: false,
},
}),
],
moduleIds: flags.channel === 'stable' && flags.mode === 'production' ? 'deterministic' : 'named',
nodeEnv: false, // provided in EnvironmentPlugin
realContentHash: false,
removeAvailableModules: productionLike,
runtimeChunk: 'single',
splitChunks:
productionLike ? undefined : (
{
maxInitialRequests: Infinity,
chunks: 'all',
cacheGroups: {
// split each npm package into a chunk to give better debug experience.
defaultVendors: {
test: /[/\\]node_modules[/\\]/,
name(module: any) {
const path = (module.context as string)
.replace(/\\/g, '/')
.match(/node_modules\/\.pnpm\/(.+)/)![1]
.split('/')
// [@org+pkgname@version, node_modules, @org, pkgname, ...inner path]
if (path[0].startsWith('@')) return `npm-ns.${path[2].replace('@', '')}.${path[3]}`
// [pkgname@version, node_modules, pkgname, ...inner path]
return `npm.${path[2]}`
},
},
},
}
),
},
output: {
environment: {
module: false,
dynamicImport: true,
},
path: flags.outputPath,
filename: 'entry/[name].js',
chunkFilename: productionLike ? 'bundled/[id].js' : 'bundled/chunk-[name].js',
assetModuleFilename: 'assets/[hash][ext][query]',
webassemblyModuleFilename: 'assets/[hash].wasm',
hotUpdateMainFilename: 'hot/[runtime].[fullhash].json',
hotUpdateChunkFilename: 'hot/[id].[fullhash].js',
devtoolModuleFilenameTemplate: 'webpack://[namespace]/[resource-path]',
globalObject: 'globalThis',
publicPath: '/',
clean: flags.mode === 'production',
trustedTypes:
String(computedFlags.sourceMapKind).includes('eval') ?
{
policyName: 'webpack',
}
: undefined,
},
ignoreWarnings: [
/Failed to parse source map/,
/Critical dependency: the request of a dependency is an expression/,
],
devServer: {
hot: flags.hmr ? 'only' : false,
liveReload: false,
client: flags.hmr ? undefined : false,
} as DevServerConfiguration,
stats: flags.mode === 'production' ? 'errors-only' : undefined,
} satisfies webpack.Configuration
const entries: Record<string, EntryDescription> = (baseConfig.entry = {
dashboard: withReactDevTools(join(__dirname, '../dashboard/initialization/index.ts')),
popups: withReactDevTools(join(__dirname, '../popups/initialization/index.ts')),
contentScript: withReactDevTools(join(__dirname, '../content-script/index.ts')),
background: normalizeEntryDescription(join(__dirname, '../background/initialization/mv2-entry.ts')),
backgroundWorker: normalizeEntryDescription(join(__dirname, '../background/initialization/mv3-entry.ts')),
})
baseConfig.plugins.push(
await addHTMLEntry({ chunks: ['dashboard'], filename: 'dashboard.html', perf: flags.profiling }),
await addHTMLEntry({ chunks: ['popups'], filename: 'popups.html', perf: flags.profiling }),
await addHTMLEntry({
chunks: ['contentScript'],
filename: 'generated__content__script.html',
perf: flags.profiling,
}),
await addHTMLEntry({ chunks: ['background'], filename: 'background.html', gun: true, perf: flags.profiling }),
)
if (flags.devtools) {
entries.devtools = normalizeEntryDescription(join(__dirname, '../devtools/panels/index.tsx'))
baseConfig.plugins.push(
await addHTMLEntry({ chunks: ['devtools'], filename: 'devtools-background.html', perf: flags.profiling }),
)
}
return baseConfig
function withReactDevTools(entry: string | string[] | EntryDescription): EntryDescription {
if (!flags.devtools) return normalizeEntryDescription(entry)
entry = normalizeEntryDescription(entry)
entry.import = joinEntryItem(join(__dirname, '../devtools/content-script/index.ts'), entry.import)
return entry
}
}
async function addHTMLEntry({
gun,
perf,
...options
}: HTMLPlugin.Options & {
gun?: boolean
perf: boolean
}) {
let template = await (options.filename === 'popups.html' && !perf ? popupTemplateContent : templateContent)
if (gun) template = template.replace(`<!-- Gun -->`, '<script src="/js/gun.js"></script>')
if (perf) template = template.replace(`<!-- Profiling -->`, '<script src="/js/perf-measure.js"></script>')
return new HTMLPlugin({
templateContent: template,
inject: 'body',
scriptLoading: 'defer',
minify: false,
...options,
})
}