-
Notifications
You must be signed in to change notification settings - Fork 853
Expand file tree
/
Copy pathbuild.mjs
More file actions
695 lines (672 loc) · 21.8 KB
/
build.mjs
File metadata and controls
695 lines (672 loc) · 21.8 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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
import archiver from 'archiver'
import fs from 'fs-extra'
import path from 'path'
import webpack from 'webpack'
import os from 'os'
import ProgressBarPlugin from 'progress-bar-webpack-plugin'
import CssMinimizerPlugin from 'css-minimizer-webpack-plugin'
import MiniCssExtractPlugin from 'mini-css-extract-plugin'
import { EsbuildPlugin } from 'esbuild-loader'
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'
const outdir = 'build'
const __dirname = path.resolve()
const isProduction = process.argv[2] !== '--development' // --production and --analyze are both production
const isAnalyzing = process.argv[2] === '--analyze'
// Env helpers
function getBooleanEnv(val, defaultValue) {
if (val == null) return defaultValue
const s = String(val).trim().toLowerCase()
if (s === '' || s === '0' || s === 'false' || s === 'no' || s === 'off') {
return false
}
if (s === '1' || s === 'true' || s === 'yes' || s === 'on') {
return true
}
console.warn(`[build] Unknown boolean env value "${val}", defaulting to ${defaultValue}`)
return defaultValue
}
// Default: parallel build ON unless explicitly disabled
const parallelBuild = getBooleanEnv(process.env.BUILD_PARALLEL, true)
const isWatchOnce = getBooleanEnv(process.env.BUILD_WATCH_ONCE, false)
// Cache compression control: default none; allow override via env
function parseCacheCompressionOption(envVal) {
if (envVal == null) return false
const v = String(envVal).trim().toLowerCase()
if (v === '' || v === '0' || v === 'false' || v === 'none') return false
if (v === 'gzip' || v === 'brotli') return v
console.warn(`[build] Unknown BUILD_CACHE_COMPRESSION="${envVal}", defaulting to no compression`)
return false
}
const cacheCompressionOption = parseCacheCompressionOption(process.env.BUILD_CACHE_COMPRESSION)
let cpuCount = 1
try {
// os.cpus() returns an array in Node.js; guard with try/catch for portability
cpuCount = Math.max(1, os.cpus().length || 1)
} catch {
cpuCount = 1
}
function parseThreadWorkerCount(envValue, cpuCount) {
const maxWorkers = Math.max(1, cpuCount)
if (envValue !== undefined && envValue !== null) {
const rawStr = String(envValue).trim()
if (/^[1-9]\d*$/.test(rawStr)) {
const raw = Number(rawStr)
if (raw > cpuCount) {
console.warn(
`[build] BUILD_THREAD_WORKERS=${raw} exceeds CPU count (${cpuCount}); capping to ${cpuCount}`,
)
}
return Math.min(raw, cpuCount)
}
console.warn(`[build] Invalid BUILD_THREAD_WORKERS="${envValue}", defaulting to ${maxWorkers}`)
}
return maxWorkers
}
const threadWorkers = parseThreadWorkerCount(process.env.BUILD_THREAD_WORKERS, cpuCount)
// Thread-loader pool timeout constants (allow override via env)
// Keep worker pool warm briefly to amortize repeated builds while still exiting quickly in CI
let PRODUCTION_POOL_TIMEOUT_MS = 2000
if (process.env.BUILD_POOL_TIMEOUT) {
const n = parseInt(process.env.BUILD_POOL_TIMEOUT, 10)
if (Number.isFinite(n) && n > 0) {
PRODUCTION_POOL_TIMEOUT_MS = n
} else {
console.warn(
`[build] Invalid BUILD_POOL_TIMEOUT="${process.env.BUILD_POOL_TIMEOUT}", keep default ${PRODUCTION_POOL_TIMEOUT_MS}ms`,
)
}
}
// Enable threads by default; allow disabling via BUILD_THREAD=0/false/no/off
const enableThread = getBooleanEnv(process.env.BUILD_THREAD, true)
// Allow opt-in symlink resolution for linked/workspace development when needed
const resolveSymlinks = getBooleanEnv(process.env.BUILD_RESOLVE_SYMLINKS, false)
// Cache and resolve Sass implementation once per process
let sassImplPromise
function resolveSassImplementation(mod) {
if (mod && typeof mod.info === 'string') return mod
if (mod?.default && typeof mod.default.info === 'string') return mod.default
return mod
}
async function getSassImplementation() {
if (!sassImplPromise) {
sassImplPromise = (async () => {
try {
const mod = await import('sass-embedded')
return resolveSassImplementation(mod)
} catch (e1) {
try {
const mod = await import('sass')
return resolveSassImplementation(mod)
} catch (e2) {
console.error('[build] Failed to load sass-embedded:', e1)
console.error('[build] Failed to load sass:', e2)
throw new Error("No Sass implementation available. Install 'sass-embedded' or 'sass'.")
}
}
})()
}
return sassImplPromise
}
async function deleteOldDir() {
await fs.rm(outdir, { recursive: true, force: true })
}
async function runWebpack(isWithoutKatex, isWithoutTiktoken, minimal, sourceBuildDir, callback) {
const shared = [
'preact',
'webextension-polyfill',
'@primer/octicons-react',
'react-bootstrap-icons',
'countries-list',
'i18next',
'react-i18next',
'react-tabs',
'./src/utils',
'./src/_locales/i18n-react',
]
if (isWithoutKatex) shared.push('./src/components')
const sassImpl = await getSassImplementation()
const dirKey = path.basename(sourceBuildDir || outdir)
const variantParts = [
isWithoutKatex ? 'no-katex' : 'with-katex',
isWithoutTiktoken ? 'no-tiktoken' : 'with-tiktoken',
minimal ? 'minimal' : 'full',
dirKey,
isProduction ? 'prod' : 'dev',
]
const variantId = variantParts.join('__')
const compiler = webpack({
entry: {
'content-script': {
import: './src/content-script/index.jsx',
dependOn: 'shared',
},
background: {
import: './src/background/index.mjs',
},
popup: {
import: './src/popup/index.jsx',
dependOn: 'shared',
},
IndependentPanel: {
import: './src/pages/IndependentPanel/index.jsx',
dependOn: 'shared',
},
shared: shared,
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, sourceBuildDir || outdir),
},
mode: isProduction ? 'production' : 'development',
devtool: isProduction ? false : 'cheap-module-source-map',
cache: {
type: 'filesystem',
name: `webpack-${variantId}`,
// Only include dimensions that affect module outputs to avoid
// unnecessary cache invalidations across machines/CI runners
version: JSON.stringify({ PROD: isProduction }),
// default none; override via BUILD_CACHE_COMPRESSION=gzip|brotli
compression: cacheCompressionOption,
buildDependencies: {
config: [
path.resolve('build.mjs'),
...['package.json', 'package-lock.json']
.map((p) => path.resolve(p))
.filter((p) => fs.existsSync(p)),
],
},
},
optimization: {
minimizer: [
// Use esbuild for JS minification (faster than Terser)
new EsbuildPlugin({
target: 'es2017',
legalComments: 'none',
}),
// Use esbuild-based CSS minify via css-minimizer plugin
new CssMinimizerPlugin({
minify: CssMinimizerPlugin.esbuildMinify,
}),
],
concatenateModules: !isAnalyzing,
},
plugins: [
minimal
? new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
})
: new webpack.ProvidePlugin({
process: 'process/browser.js',
Buffer: ['buffer', 'Buffer'],
}),
new ProgressBarPlugin({
format: ' build [:bar] :percent (:elapsed seconds)',
clear: false,
}),
new MiniCssExtractPlugin({
filename: '[name].css',
}),
new BundleAnalyzerPlugin({
analyzerMode: isAnalyzing ? 'static' : 'disable',
}),
...(isWithoutKatex
? [
new webpack.NormalModuleReplacementPlugin(/markdown\.jsx/, (result) => {
if (result.request) {
result.request = result.request.replace(
'markdown.jsx',
'markdown-without-katex.jsx',
)
}
}),
]
: []),
],
resolve: {
extensions: ['.jsx', '.mjs', '.js'],
// Disable symlink resolution for consistent behavior/perf; enable via BUILD_RESOLVE_SYMLINKS=1 when working with linked deps
symlinks: resolveSymlinks,
alias: {
parse5: path.resolve(__dirname, 'node_modules/parse5'),
...(minimal
? { buffer: path.resolve(__dirname, 'node_modules/buffer') }
: {
util: path.resolve(__dirname, 'node_modules/util'),
buffer: path.resolve(__dirname, 'node_modules/buffer'),
stream: 'stream-browserify',
crypto: 'crypto-browserify',
}),
},
},
module: {
rules: [
{
test: /\.m?jsx?$/,
exclude: /(node_modules)/,
resolve: {
fullySpecified: false,
},
use: [
...(enableThread
? [
{
loader: 'thread-loader',
options: {
workers: threadWorkers,
// Ensure one-off dev build exits quickly
poolTimeout: isProduction
? PRODUCTION_POOL_TIMEOUT_MS
: isWatchOnce
? 0
: Infinity,
},
},
]
: []),
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
cacheCompression: false,
presets: ['@babel/preset-env'],
plugins: [
['@babel/plugin-transform-runtime'],
[
'@babel/plugin-transform-react-jsx',
{
runtime: 'automatic',
importSource: 'preact',
},
],
],
},
},
],
},
{
test: /\.s[ac]ss$/,
use: [
isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
},
},
{
loader: 'sass-loader',
options: {
implementation: sassImpl,
sassOptions: {
quietDeps: true,
},
},
},
],
},
{
test: /\.less$/,
use: [
isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
},
},
{
loader: 'less-loader',
},
],
},
{
test: /\.css$/,
use: [
isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
{
loader: 'css-loader',
},
],
},
{
test: /\.(woff|ttf)$/,
type: 'asset/resource',
generator: {
emit: false,
},
},
{
test: /\.woff2$/,
type: 'asset/inline',
},
{
test: /\.(jpg|png|svg)$/,
type: 'asset/inline',
},
{
test: /\.(graphql|gql)$/,
loader: 'graphql-tag/loader',
},
isWithoutTiktoken
? {
test: /crop-text\.mjs$/,
loader: 'string-replace-loader',
options: {
multiple: [
{
search: "import { encode } from '@nem035/gpt-3-encoder'",
replace: '',
},
{
search: 'encode(',
replace: 'String(',
},
],
},
}
: {},
minimal
? {
test: /styles\.scss$/,
loader: 'string-replace-loader',
options: {
multiple: [
{
search: "@import '../fonts/styles.css';",
replace: '',
},
],
},
}
: {},
minimal
? {
test: /index\.mjs$/,
loader: 'string-replace-loader',
options: {
multiple: [
{
search: 'import { generateAnswersWithChatGLMApi }',
replace: '//',
},
{
search: 'await generateAnswersWithChatGLMApi',
replace: '//',
},
],
},
}
: {},
],
},
})
if (isProduction) {
// Ensure compiler is properly closed after production runs
compiler.run((err, stats) => {
const hasErrors = !!(err || stats?.hasErrors?.())
let callbackFailed = false
const finishClose = () =>
compiler.close((closeErr) => {
if (closeErr) {
console.error('Error closing compiler:', closeErr)
process.exitCode = 1
}
if (hasErrors || callbackFailed) {
process.exitCode = 1
}
})
try {
const ret = callback(err, stats)
if (ret && typeof ret.then === 'function') {
ret.then(finishClose, () => {
callbackFailed = true
finishClose()
})
} else {
finishClose()
}
} catch (callbackErr) {
console.error('[build] Callback error:', callbackErr)
callbackFailed = true
finishClose()
}
})
} else {
const watching = compiler.watch({}, (err, stats) => {
const hasErrors = !!(err || stats?.hasErrors?.())
// Normalize callback return into a Promise to catch synchronous throws
const ret = Promise.resolve().then(() => callback(err, stats))
if (isWatchOnce) {
const finalize = (callbackFailed = false) =>
watching.close((closeErr) => {
if (closeErr) console.error('Error closing watcher:', closeErr)
// Exit explicitly to prevent hanging processes in CI
// Use non-zero exit code when errors occurred, including callback failures
const shouldFail = hasErrors || closeErr || callbackFailed
process.exit(shouldFail ? 1 : 0)
})
ret.then(
() => finalize(false),
() => finalize(true),
)
}
})
}
}
async function zipFolder(dir) {
const zipPath = `${dir}.zip`
await fs.ensureDir(path.dirname(zipPath))
await new Promise((resolve, reject) => {
const output = fs.createWriteStream(zipPath)
const archive = archiver('zip', { zlib: { level: 9 } })
let settled = false
const fail = (err) => {
if (!settled) {
settled = true
reject(err)
}
}
const done = () => {
if (!settled) {
settled = true
resolve()
}
}
output.once('error', fail)
archive.once('error', fail)
archive.on('warning', (err) => {
// Log non-fatal archive warnings for diagnostics
console.warn('[build][zip] warning:', err)
})
// Resolve on close to ensure FD is flushed and closed
output.once('close', done)
// Ensure close is emitted after finish on some fast runners
output.once('finish', () => {
try {
if (typeof output.close === 'function') output.close()
} catch (_) {
// ignore
}
})
archive.pipe(output)
archive.directory(dir, false)
archive.finalize()
})
}
async function copyFiles(entryPoints, targetDir) {
await fs.ensureDir(targetDir)
await Promise.all(
entryPoints.map(async (entryPoint) => {
try {
await fs.copy(entryPoint.src, `${targetDir}/${entryPoint.dst}`)
} catch (e) {
const isCss = typeof entryPoint.dst === 'string' && entryPoint.dst.endsWith('.css')
if (e && e.code === 'ENOENT') {
if (!isProduction && isCss) {
console.log(
`[build] Skipping missing CSS file: ${entryPoint.src} -> ${entryPoint.dst} (placeholder will be created)`,
)
return
}
console.error('Missing build artifact:', `${entryPoint.src} -> ${entryPoint.dst}`)
} else {
console.error('Copy failed:', `${entryPoint.src} -> ${entryPoint.dst}`, e)
}
throw e
}
}),
)
}
// In development, create placeholder CSS and sourcemap files to avoid 404 noise
async function ensureDevCssPlaceholders(cssFiles) {
if (isProduction || cssFiles.length === 0) return
await Promise.all(
cssFiles.map(async (cssPath) => {
if (!(await fs.pathExists(cssPath))) {
await fs.outputFile(cssPath, '/* dev placeholder */\n')
}
const mapPath = `${cssPath}.map`
if (!(await fs.pathExists(mapPath))) {
await fs.outputFile(mapPath, '{"version":3,"sources":[],"mappings":"","names":[]}')
}
}),
)
}
async function finishOutput(outputDirSuffix, sourceBuildDir = outdir) {
const commonFiles = [
{ src: 'src/logo.png', dst: 'logo.png' },
{ src: 'src/rules.json', dst: 'rules.json' },
{ src: `${sourceBuildDir}/shared.js`, dst: 'shared.js' },
{ src: `${sourceBuildDir}/content-script.css`, dst: 'content-script.css' }, // shared
{ src: `${sourceBuildDir}/content-script.js`, dst: 'content-script.js' },
{ src: `${sourceBuildDir}/background.js`, dst: 'background.js' },
{ src: `${sourceBuildDir}/popup.js`, dst: 'popup.js' },
{ src: `${sourceBuildDir}/popup.css`, dst: 'popup.css' },
{ src: 'src/popup/index.html', dst: 'popup.html' },
{ src: `${sourceBuildDir}/IndependentPanel.js`, dst: 'IndependentPanel.js' },
{ src: 'src/pages/IndependentPanel/index.html', dst: 'IndependentPanel.html' },
// Dev-only: copy external source maps for CSP-safe debugging
...(isProduction
? []
: [
{ src: `${sourceBuildDir}/shared.js.map`, dst: 'shared.js.map' },
{ src: `${sourceBuildDir}/content-script.js.map`, dst: 'content-script.js.map' },
{ src: `${sourceBuildDir}/background.js.map`, dst: 'background.js.map' },
{ src: `${sourceBuildDir}/popup.js.map`, dst: 'popup.js.map' },
{ src: `${sourceBuildDir}/IndependentPanel.js.map`, dst: 'IndependentPanel.js.map' },
]),
]
// chromium
const chromiumOutputDir = `./${outdir}/chromium${outputDirSuffix}`
await copyFiles(
[...commonFiles, { src: 'src/manifest.json', dst: 'manifest.json' }],
chromiumOutputDir,
)
await ensureDevCssPlaceholders(
Array.from(
new Set(
commonFiles
.filter((file) => file.dst.endsWith('.css'))
.map((file) => path.join(chromiumOutputDir, file.dst)),
),
),
)
if (isProduction) await zipFolder(chromiumOutputDir)
// firefox
const firefoxOutputDir = `./${outdir}/firefox${outputDirSuffix}`
await copyFiles(
[...commonFiles, { src: 'src/manifest.v2.json', dst: 'manifest.json' }],
firefoxOutputDir,
)
await ensureDevCssPlaceholders(
Array.from(
new Set(
commonFiles
.filter((file) => file.dst.endsWith('.css'))
.map((file) => path.join(firefoxOutputDir, file.dst)),
),
),
)
if (isProduction) await zipFolder(firefoxOutputDir)
}
async function build() {
await deleteOldDir()
function createWebpackBuildPromise(isWithoutKatex, isWithoutTiktoken, minimal, tmpDir, suffix) {
return new Promise((resolve, reject) => {
const ret = runWebpack(
isWithoutKatex,
isWithoutTiktoken,
minimal,
tmpDir,
async (err, stats) => {
if (err || stats?.hasErrors?.()) {
console.error(err || stats.toString())
reject(err || new Error('webpack error'))
return
}
try {
await finishOutput(suffix, tmpDir)
resolve()
} catch (copyErr) {
reject(copyErr)
}
},
)
// runWebpack is async; catch early rejections (e.g., failed dynamic imports)
if (ret && typeof ret.then === 'function') ret.catch(reject)
})
}
if (isProduction && !isAnalyzing) {
const tmpFull = `${outdir}/.tmp-full`
const tmpMin = `${outdir}/.tmp-min`
try {
if (parallelBuild) {
const results = await Promise.allSettled([
createWebpackBuildPromise(true, true, true, tmpMin, '-without-katex-and-tiktoken'),
createWebpackBuildPromise(false, false, false, tmpFull, ''),
])
const failed = results.find((result) => result.status === 'rejected')
if (failed) {
throw failed.reason
}
} else {
await createWebpackBuildPromise(true, true, true, tmpMin, '-without-katex-and-tiktoken')
await createWebpackBuildPromise(false, false, false, tmpFull, '')
}
} finally {
await fs.rm(tmpFull, { recursive: true, force: true })
await fs.rm(tmpMin, { recursive: true, force: true })
}
return
}
await new Promise((resolve, reject) => {
const ret = runWebpack(false, false, false, outdir, async (err, stats) => {
const hasErrors = !!(err || stats?.hasErrors?.())
if (hasErrors) {
console.error(err || stats.toString())
// In normal dev watch, keep process alive on initial errors; only fail when watch-once
if (isWatchOnce) {
reject(err || new Error('webpack error'))
}
return
}
try {
await finishOutput('')
resolve()
} catch (e) {
// Packaging failure should stop even in dev to avoid silent success
reject(e)
if (isWatchOnce) {
// Re-throw to surface an error and exit non-zero even if rejection isn't awaited
throw e
}
}
})
// Early setup failures (e.g., dynamic imports) should fail fast
if (ret && typeof ret.then === 'function') ret.catch(reject)
})
}
build().catch((e) => {
console.error(e)
process.exit(1)
})