-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathwebpack.config.js
More file actions
353 lines (318 loc) · 12.7 KB
/
webpack.config.js
File metadata and controls
353 lines (318 loc) · 12.7 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
const { resolve, join } = require('path');
const nodeExternals = require('webpack-node-externals');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const webpack = require('webpack');
const fs = require('fs');
const { execSync } = require('child_process');
const path = require('path');
const BUNDLE_NAME = 'cfn-lsp-server-standalone';
const Package = JSON.parse(fs.readFileSync('package.json', 'utf8'));
const PackageLock = JSON.parse(fs.readFileSync('package-lock.json', 'utf8'));
const ExternalsDeps = Package.externalDependencies;
const NativePrebuilds = Package.nativePrebuilds;
const UnusedDeps = Package.unusedDependencies;
const COPY_FILES = ['LICENSE', 'NOTICE', 'THIRD-PARTY-LICENSES.txt', 'README.md'];
const KEEP_FILES = [
'.cjs',
'.gyp',
'.js',
'.js.map',
'.mjs',
'.node',
'.wasm',
'mappingTable.json',
'package.json',
'pyodide-lock.json',
'python_stdlib.zip',
];
const IGNORE_PATHS = ['/bin/', '/test/', '/benchmarks/', '/examples/'];
function generateExternals() {
const externals = [...ExternalsDeps, ...UnusedDeps];
const collected = new Set(externals);
const queue = [...externals];
while (queue.length > 0) {
const dep = queue.shift();
const pkgInfo = PackageLock.packages?.[`node_modules/${dep}`];
if (pkgInfo?.dependencies) {
for (const subDep of Object.keys(pkgInfo.dependencies)) {
if (!collected.has(subDep) && !subDep.startsWith('@types/') && !pkgInfo.dev && !pkgInfo.optional) {
collected.add(subDep);
queue.push(subDep);
}
}
}
}
for (const dep of NativePrebuilds) {
collected.add(dep);
}
return Array.from(collected).sort();
}
const EXTERNALS = generateExternals();
function createPlugins(isDevelopment, outputPath, mode, env, rebuild = false, buildTarget = '') {
const plugins = [];
plugins.push(
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
reportFilename: resolve(outputPath, `../${mode}-analysis.html`),
}),
);
// Download Python wheels at build time so they don't need to be committed to git
plugins.push({
apply: (compiler) => {
compiler.hooks.beforeRun.tapAsync('DownloadWheels', (_compilation, callback) => {
try {
console.log('[DownloadWheels] Downloading Python wheels...');
execSync('npm run download-wheels', { cwd: __dirname, stdio: 'inherit' });
console.log('[DownloadWheels] Done');
callback();
} catch (error) {
console.error('[DownloadWheels] Error:', error);
callback(error);
}
});
},
});
// Copy relationship schemas for both development and production
plugins.push(
new CopyWebpackPlugin({
patterns: [
{
from: 'assets',
to: 'assets',
},
{
from: 'vendor/cfn-guard/guard_bg.wasm',
to: 'guard_bg.wasm',
},
{
from: 'vendor/cfn-guard/guard.js',
to: 'vendor/cfn-guard/guard.js',
},
{
from: 'vendor/cfn-guard/index.js',
to: 'vendor/cfn-guard/index.js',
},
{
from: 'vendor/cfn-guard/package.json',
to: 'vendor/cfn-guard/package.json',
},
{
from: 'vendor/cfn-guard/guard_bg.wasm',
to: 'vendor/cfn-guard/guard_bg.wasm',
},
],
}),
);
if (!isDevelopment) {
const tmpDir = path.join(__dirname, 'tmp-node-modules');
console.debug('Working in tmpDir:', tmpDir);
plugins.push({
apply: (compiler) => {
compiler.hooks.beforeRun.tapAsync('InstallDependencies', (compilation, callback) => {
try {
console.log('[InstallDependencies] Starting dependency installation...');
const tmpPkg = {
...Package,
main: `./${BUNDLE_NAME}.js`,
};
delete tmpPkg['scripts'];
delete tmpPkg['devDependencies'];
delete tmpPkg['externalDependencies'];
delete tmpPkg['nativePrebuilds'];
console.log('[InstallDependencies] Cleaning temp directory...');
if (fs.existsSync(tmpDir)) {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
fs.mkdirSync(tmpDir, { recursive: true });
fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify(tmpPkg, null, 2));
fs.copyFileSync('package-lock.json', `${tmpDir}/package-lock.json`);
console.log('[InstallDependencies] Running npm ci --omit=dev');
execSync('npm ci --omit=dev', { cwd: tmpDir, stdio: 'inherit' });
const externals = ExternalsDeps.map((dep) => {
return `${dep}@${PackageLock.packages[`node_modules/${dep}`].version}`;
});
console.log(
`[InstallDependencies] Installing externals: npm install --save-exact ${externals.join(' ')}`,
);
execSync(`npm install --save-exact ${externals.join(' ')}`, {
cwd: tmpDir,
stdio: 'inherit',
});
if (rebuild) {
const rebuildDeps = Package.rebuildDependencies || [];
for (const dep of rebuildDeps) {
const prebuildPath = path.join(tmpDir, 'node_modules', dep, 'prebuilds');
if (fs.existsSync(prebuildPath)) {
console.log(`[InstallDependencies] Removing prebuilds: ${prebuildPath}`);
fs.rmSync(prebuildPath, { recursive: true, force: true });
}
}
console.log(`[InstallDependencies] Rebuilding: npm rebuild ${rebuildDeps.join(' ')}`);
execSync(`npm rebuild ${rebuildDeps.join(' ')}`, { cwd: tmpDir, stdio: 'inherit' });
}
callback();
} catch (error) {
console.error('[InstallDependencies] Error:', error);
callback(error);
}
});
compiler.hooks.done.tap('CleanupTemp', () => {
console.log('[CleanupTemp] Cleaning up temporary files...');
if (fs.existsSync(tmpDir)) {
console.log(`[CleanupTemp] Removing: ${tmpDir}`);
fs.rmSync(tmpDir, { recursive: true, force: true });
}
const dotPackageLock = 'bundle/production/node_modules/.package-lock.json';
if (fs.existsSync(dotPackageLock)) {
console.log(`[CleanupTemp] Removing: ${dotPackageLock}`);
fs.rmSync(dotPackageLock, { force: true });
}
console.log('[CleanupTemp] Cleanup complete');
});
},
});
plugins.push(
new CopyWebpackPlugin({
patterns: [
{
from: path.join('tmp-node-modules', 'node_modules'),
to: 'node_modules',
filter: (resourcePath) => {
const relativePath = resourcePath.replace(process.cwd(), '');
const isExternal = EXTERNALS.some((external) => {
return relativePath.includes(`/node_modules/${external}/`);
});
const keep = KEEP_FILES.some((pattern) => relativePath.endsWith(pattern));
const ignore = IGNORE_PATHS.some((pattern) => relativePath.includes(pattern));
return isExternal && keep && !ignore;
},
},
{
from: 'tmp-node-modules/package.json',
to: 'package.json',
},
...COPY_FILES.map((file) => {
return {
from: file,
to: file,
toType: 'file',
};
}),
],
}),
);
plugins.push(
new webpack.IgnorePlugin({
resourceRegExp: /^@opentelemetry\/(winston-transport|exporter-jaeger)$/,
}),
);
}
plugins.push(
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(mode),
'process.env.AWS_ENV': JSON.stringify(env),
'process.env.BUILD_TARGET': JSON.stringify(buildTarget),
}),
);
return plugins;
}
const baseConfig = {
target: 'node',
entry: {
[BUNDLE_NAME]: './src/app/standalone.ts',
'pyodide-worker': './src/services/cfnLint/pyodide-worker.ts',
},
resolve: {
extensions: ['.ts', '.js', '.node'],
alias: {
'@': resolve(__dirname, 'src'),
},
},
module: {
rules: [
{
test: /\.ts$/,
use: [
{
loader: 'ts-loader',
options: {
configFile: 'tsconfig.bundle.json',
transpileOnly: false,
},
},
],
exclude: /node_modules/,
},
{
test: /\.node$/,
use: {
loader: 'node-loader',
options: {
name: '[name].[ext]',
},
},
},
],
},
stats: 'normal',
performance: {
hints: 'warning',
},
};
module.exports = (env = {}) => {
const mode = env.mode;
let awsEnv = env.env;
const rebuild = env.rebuild === 'true' || env.rebuild === true;
const buildTarget = env.buildTarget || '';
// Validate mode
const validModes = ['development', 'production'];
if (!validModes.includes(mode)) {
console.error(`Invalid mode: ${mode}. Valid options: ${validModes.join(', ')}`);
process.exit(1);
}
if (mode === 'development') {
awsEnv = 'alpha';
}
// Validate env
const validEnvs = ['alpha', 'beta', 'prod'];
if (!validEnvs.includes(awsEnv)) {
console.error(`Invalid env: ${awsEnv}. Valid options: ${validEnvs.join(', ')}`);
process.exit(1);
}
const outputPath = resolve(join(__dirname, 'bundle', mode));
const isDevelopment = mode === 'development';
console.info(`Building server with mode: ${mode}`);
console.info(`NODE_ENV: ${mode}`);
console.info(`AWS_ENV: ${awsEnv}`);
console.info(`Platform: ${process.platform}, Arch: ${process.arch}, Rebuild: ${rebuild}`);
console.info(`Node.js ${process.version}, Versions: ${JSON.stringify(process.versions, null, 2)}`);
console.info(`Output path: ${outputPath}`);
return {
...baseConfig,
mode: isDevelopment ? 'development' : 'production',
devtool: isDevelopment ? 'eval-source-map' : 'source-map',
output: {
clean: true,
filename: `[name].js`,
chunkFilename: `[name].js`,
path: outputPath,
library: {
type: 'commonjs2',
},
},
externals: isDevelopment ? [nodeExternals()] : EXTERNALS,
optimization: {
minimize: false,
moduleIds: 'named',
chunkIds: 'named',
usedExports: true,
sideEffects: false,
splitChunks: {
chunks: 'all',
},
},
plugins: createPlugins(isDevelopment, outputPath, mode, awsEnv, rebuild, buildTarget),
};
};