-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathesbuild-federation.js
More file actions
263 lines (241 loc) · 8.39 KB
/
esbuild-federation.js
File metadata and controls
263 lines (241 loc) · 8.39 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
const esbuild = require('esbuild');
const fs = require('fs');
const { federationConfig } = require('./src/moduleFederation');
const { WEB_CHUNK_GLOBAL_KEY, LEGACY_WEB_CHUNK_GLOBAL_KEY } = require('./src/constants');
const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const alwaysReservedProps = ['activate', 'deactivate', 'provideFileDecoration', 'dispose', 'exports'];
const crossChunkPrivateProps = [
'_accessibility',
'_advancedCache',
'_allocationTelemetryEnabled',
'_batchProcessor',
'_batchProcessorModule',
'_enableWatcherFallbacks',
'_extensionContext',
'_fileSystem',
'_getIndexerMaxFiles',
'_isWeb',
'_logger',
'_maybeWarnAboutGitLimitations',
'_metrics',
'_performanceMode',
'_progressiveLoadingEnabled',
'_progressiveLoadingJobs',
'_shouldEnableProgressiveAnalysis',
'_smartWatcherFallbackManager',
'_telemetryReportInterval',
'_telemetryReportTimer',
'_themeIntegration',
'_workspaceIntelligence'
];
const reservePropsPattern = new RegExp(
`^(${[...alwaysReservedProps, ...crossChunkPrivateProps].map(escapeRegex).join('|')})$`
);
const production = process.argv.includes('--production');
const watch = process.argv.includes('--watch');
const chunks = process.argv.includes('--chunks');
/**
* @type {import('esbuild').Plugin}
*/
const esbuildProblemMatcherPlugin = {
name: 'esbuild-problem-matcher',
setup(build) {
build.onStart(() => {
console.log('[watch] build started');
});
build.onEnd(result => {
result.errors.forEach(({ text, location }) => {
console.error(`✘ [ERROR] ${text}`);
if (location == null) return;
console.error(` ${location.file}:${location.line}:${location.column}:`);
});
console.log('[watch] build finished');
});
}
};
const sharedOptions = {
bundle: true,
format: 'cjs',
minify: production,
minifyWhitespace: true,
minifyIdentifiers: production,
minifySyntax: true,
sourcemap: !production,
sourcesContent: false,
logLevel: 'warning',
keepNames: !production,
treeShaking: true,
legalComments: 'none',
drop: production ? ['console', 'debugger'] : [],
dropLabels: production ? ['DEV', 'DEBUG', 'TEST'] : [],
ignoreAnnotations: false,
metafile: production,
mangleProps: production ? /^_/ : undefined,
reserveProps: production ? reservePropsPattern : undefined,
mangleQuoted: production ? true : false,
pure: production ? [
'console.log', 'console.debug', 'console.trace', 'console.info',
'logger.debug', 'logger.trace', 'performance.mark', 'performance.measure'
] : [],
define: production ? {
'process.env.NODE_ENV': '"production"',
'process.env.DEBUG': 'false',
'process.env.DEVELOPMENT': 'false',
'__DEV__': 'false',
'DEBUG': 'false'
} : {
'process.env.NODE_ENV': '"development"',
'__DEV__': 'true'
},
plugins: [esbuildProblemMatcherPlugin],
external: [
'vscode',
'fs', 'path', 'util', 'child_process', 'os', 'crypto', 'stream', 'events',
'worker_threads', 'cluster', 'net', 'http', 'https', 'url', 'querystring'
]
};
async function buildChunks() {
console.log('🧩 Building module federation chunks...');
await fs.promises.mkdir('dist', { recursive: true }).catch(() => {});
await fs.promises.mkdir('dist/chunks', { recursive: true }).catch(() => {});
await fs.promises.mkdir('dist/web-chunks', { recursive: true }).catch(() => {});
const builds = [];
const webExcluded = [];
for (const [chunkName, chunkConfig] of Object.entries(federationConfig.chunks)) {
if (chunkConfig.webExclude) {
webExcluded.push(chunkName);
}
}
if (webExcluded.length > 0) {
await Promise.all(webExcluded.flatMap((chunkName) => {
const candidates = [
`dist/web-chunks/${chunkName}.js`,
`dist/web-chunks/${chunkName}.js.map`
];
return candidates.map(async (target) => {
try {
await fs.promises.unlink(target);
} catch (error) {
if (error && error.code !== 'ENOENT') {
console.warn(`⚠️ Failed to remove ${target}: ${error.message}`);
}
}
});
}));
}
for (const [chunkName, chunkConfig] of Object.entries(federationConfig.chunks)) {
// Build for Node.js platform to dist/chunks/ for consistent chunk location
const nodeBuildConfig = {
...sharedOptions,
entryPoints: [chunkConfig.entry],
outfile: `dist/chunks/${chunkName}.js`,
platform: 'node',
external: [...sharedOptions.external, ...chunkConfig.external]
};
builds.push(esbuild.build(nodeBuildConfig));
if (!chunkConfig.webExclude) {
const webBuildConfig = {
...sharedOptions,
entryPoints: [chunkConfig.entry],
outfile: `dist/web-chunks/${chunkName}.js`,
platform: 'browser',
format: 'cjs',
banner: {
js: `var module = { exports: {} }; var exports = module.exports; (function() {`
},
footer: {
js: `})(); (function(){const primaryKey="${WEB_CHUNK_GLOBAL_KEY}";const legacyKey="${LEGACY_WEB_CHUNK_GLOBAL_KEY}";const registry=(globalThis[primaryKey]=globalThis[primaryKey]||globalThis[legacyKey]||(globalThis[legacyKey]={}));registry["${chunkName}"]=module.exports;})();`
},
external: [...sharedOptions.external, ...chunkConfig.external]
};
builds.push(esbuild.build(webBuildConfig));
}
}
await Promise.all(builds);
// Report chunk sizes in production
if (production) {
console.log('\n📦 Built chunks:');
let totalSize = 0;
for (const [chunkName, chunkConfig] of Object.entries(federationConfig.chunks)) {
try {
const stats = fs.statSync(`dist/chunks/${chunkName}.js`);
const sizeKB = Math.round(stats.size / 1024);
totalSize += sizeKB;
console.log(` ${chunkName}: ${sizeKB}KB`);
if (chunkConfig.description) {
console.log(` ${chunkConfig.description}`);
}
} catch {
// File might not exist, skip size reporting
}
}
console.log(`\n📊 Total chunks: ${totalSize}KB`);
}
// Build src/utils/localization.js as a proper self-contained chunk.
// This replaces the broken stub at dist/chunks/utils/localization.js that
// previously used require('../../../src/utils/localization') — a path that
// doesn't exist in installed extensions (src/ is excluded from the VSIX).
await fs.promises.mkdir('dist/chunks/utils', { recursive: true }).catch(() => {});
await esbuild.build({
entryPoints: ['src/utils/localization.js'],
outfile: 'dist/chunks/utils/localization.js',
bundle: true,
format: 'cjs',
platform: 'node',
minify: production,
minifyWhitespace: true,
minifySyntax: production,
sourcemap: false,
logLevel: 'warning',
// Only vscode is truly external; localization-core and locale JSON get bundled.
external: ['vscode'],
});
// Some chunks (e.g. analysis) use the import path '../utils/localization' which
// at runtime from dist/chunks/ resolves to dist/utils/localization.js (one level
// up from chunks/). Create a small redirect so they find the real bundle.
await fs.promises.mkdir('dist/utils', { recursive: true }).catch(() => {});
await fs.promises.writeFile(
'dist/utils/localization.js',
'// Auto-generated by esbuild-federation.js — do not edit\nmodule.exports = require(\'../chunks/utils/localization\');\n'
);
console.log('✅ Module federation chunks built successfully');
}
async function buildStandard() {
// Standard monolithic build
const contexts = await Promise.all([
// Node.js build
esbuild.context({
...sharedOptions,
entryPoints: ['extension.js'],
outfile: 'dist/extension.js',
platform: 'node'
}),
// Web build
esbuild.context({
...sharedOptions,
entryPoints: ['extension.js'],
outfile: 'dist/extension.web.js',
platform: 'browser'
})
]);
if (watch) {
await Promise.all(contexts.map(ctx => ctx.watch()));
} else {
await Promise.all(contexts.map(ctx => ctx.rebuild()));
await Promise.all(contexts.map(ctx => ctx.dispose()));
}
// Print bundle sizes
for (const target of ['extension.js', 'extension.web.js']) {
try {
const fs = require('fs');
const stats = fs.statSync(`dist/${target}`);
console.log(`📦 dist/${target}: ${Math.round(stats.size / 1024)}KB`);
} catch {}
}
}
// Main build logic
if (chunks) {
buildChunks();
} else {
buildStandard();
}