optimize.ts 9.5 KB
Newer Older
I
isidor 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

J
Joao Moreno 已提交
6 7
'use strict';

8
import * as es from 'event-stream';
9
import * as gulp from 'gulp';
10
import * as concat from 'gulp-concat';
11
import * as minifyCSS from 'gulp-cssnano';
12 13 14
import * as filter from 'gulp-filter';
import * as flatmap from 'gulp-flatmap';
import * as sourcemaps from 'gulp-sourcemaps';
15
import * as uglify from 'gulp-uglify';
J
Joao Moreno 已提交
16
import * as composer from 'gulp-uglify/composer';
A
Alex Dima 已提交
17 18
import * as fancyLog from 'fancy-log';
import * as ansiColors from 'ansi-colors';
19 20
import * as path from 'path';
import * as pump from 'pump';
21
import * as terser from 'terser';
22 23
import * as VinylFile from 'vinyl';
import * as bundle from './bundle';
24 25
import { Language, processNlsFiles } from './i18n';
import { createStatsStream } from './stats';
26
import * as util from './util';
27

28 29
const REPO_ROOT_PATH = path.join(__dirname, '../..');

30
function log(prefix: string, message: string): void {
A
Alex Dima 已提交
31
	fancyLog(ansiColors.cyan('[' + prefix + ']'), message);
32
}
D
Dirk Baeumer 已提交
33

34
export function loaderConfig() {
M
Matt Bierner 已提交
35
	const result: any = {
I
isidor 已提交
36 37
		paths: {
			'vs': 'out-build/vs',
J
Joao Moreno 已提交
38
			'vscode': 'empty:'
I
isidor 已提交
39
		},
40
		amdModulesPattern: /^vs\//
I
isidor 已提交
41 42
	};

B
Benjamin Pasero 已提交
43 44
	result['vs/css'] = { inlineResources: true };

I
isidor 已提交
45
	return result;
46
}
I
isidor 已提交
47

J
Joao Moreno 已提交
48
const IS_OUR_COPYRIGHT_REGEXP = /Copyright \(C\) Microsoft Corporation/i;
I
isidor 已提交
49

50
function loader(src: string, bundledFileHeader: string, bundleLoader: boolean): NodeJS.ReadWriteStream {
A
Alex Dima 已提交
51
	let sources = [
52
		`${src}/vs/loader.js`
A
Alex Dima 已提交
53 54 55
	];
	if (bundleLoader) {
		sources = sources.concat([
56 57
			`${src}/vs/css.js`,
			`${src}/vs/nls.js`
A
Alex Dima 已提交
58 59 60
		]);
	}

J
Joao Moreno 已提交
61
	let isFirst = true;
A
Alex Dima 已提交
62 63
	return (
		gulp
64
			.src(sources, { base: `${src}` })
65 66 67 68 69 70
			.pipe(es.through(function (data) {
				if (isFirst) {
					isFirst = false;
					this.emit('data', new VinylFile({
						path: 'fake',
						base: '',
71
						contents: Buffer.from(bundledFileHeader)
72 73 74 75 76 77 78
					}));
					this.emit('data', data);
				} else {
					this.emit('data', data);
				}
			}))
			.pipe(concat('vs/loader.js'))
A
Alex Dima 已提交
79
	);
I
isidor 已提交
80 81
}

82
function toConcatStream(src: string, bundledFileHeader: string, sources: bundle.IFile[], dest: string, fileContentMapper: (contents: string, path: string) => string): NodeJS.ReadWriteStream {
J
Joao Moreno 已提交
83
	const useSourcemaps = /\.js$/.test(dest) && !/\.nls\.js$/.test(dest);
I
isidor 已提交
84 85 86

	// If a bundle ends up including in any of the sources our copyright, then
	// insert a fake source at the beginning of each bundle with our copyright
J
Joao Moreno 已提交
87 88 89
	let containsOurCopyright = false;
	for (let i = 0, len = sources.length; i < len; i++) {
		const fileContents = sources[i].contents;
I
isidor 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102
		if (IS_OUR_COPYRIGHT_REGEXP.test(fileContents)) {
			containsOurCopyright = true;
			break;
		}
	}

	if (containsOurCopyright) {
		sources.unshift({
			path: null,
			contents: bundledFileHeader
		});
	}

103
	const treatedSources = sources.map(function (source) {
104
		const root = source.path ? REPO_ROOT_PATH.replace(/\\/g, '/') : '';
105
		const base = source.path ? root + `/${src}` : '';
106 107
		const path = source.path ? root + '/' + source.path.replace(/\\/g, '/') : 'fake';
		const contents = source.path ? fileContentMapper(source.contents, path) : source.contents;
I
isidor 已提交
108

109
		return new VinylFile({
110
			path: path,
I
isidor 已提交
111
			base: base,
112
			contents: Buffer.from(contents)
I
isidor 已提交
113 114 115 116 117
		});
	});

	return es.readArray(treatedSources)
		.pipe(useSourcemaps ? util.loadSourcemaps() : es.through())
118
		.pipe(concat(dest))
119
		.pipe(createStatsStream(dest));
I
isidor 已提交
120 121
}

122
function toBundleStream(src: string, bundledFileHeader: string, bundles: bundle.IConcatFile[], fileContentMapper: (contents: string, path: string) => string): NodeJS.ReadWriteStream {
123
	return es.merge(bundles.map(function (bundle) {
124
		return toConcatStream(src, bundledFileHeader, bundle.sources, bundle.dest, fileContentMapper);
I
isidor 已提交
125 126 127
	}));
}

128
export interface IOptimizeTaskOpts {
129 130 131 132
	/**
	 * The folder to read files from.
	 */
	src: string;
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
	/**
	 * (for AMD files, will get bundled and get Copyright treatment)
	 */
	entryPoints: bundle.IEntryPoint[];
	/**
	 * (svg, etc.)
	 */
	resources: string[];
	loaderConfig: any;
	/**
	 * (true by default - append css and nls to loader)
	 */
	bundleLoader?: boolean;
	/**
	 * (basically the Copyright treatment)
	 */
B
Benjamin Pasero 已提交
149
	header?: string;
150 151 152 153 154 155 156 157
	/**
	 * (emit bundleInfo.json file)
	 */
	bundleInfo: boolean;
	/**
	 * (out folder name)
	 */
	out: string;
158 159 160 161
	/**
	 * (out folder name)
	 */
	languages?: Language[];
162 163 164 165 166 167
	/**
	 * File contents interceptor
	 * @param contents The contens of the file
	 * @param path The absolute file path, always using `/`, even on Windows
	 */
	fileContentMapper?: (contents: string, path: string) => string;
168
}
169

B
Benjamin Pasero 已提交
170 171 172 173 174 175
const DEFAULT_FILE_HEADER = [
	'/*!--------------------------------------------------------',
	' * Copyright (C) Microsoft Corporation. All rights reserved.',
	' *--------------------------------------------------------*/'
].join('\n');

176
export function optimizeTask(opts: IOptimizeTaskOpts): () => NodeJS.ReadWriteStream {
177
	const src = opts.src;
J
Joao Moreno 已提交
178 179 180
	const entryPoints = opts.entryPoints;
	const resources = opts.resources;
	const loaderConfig = opts.loaderConfig;
B
Benjamin Pasero 已提交
181
	const bundledFileHeader = opts.header || DEFAULT_FILE_HEADER;
A
Alex Dima 已提交
182
	const bundleLoader = (typeof opts.bundleLoader === 'undefined' ? true : opts.bundleLoader);
J
Joao Moreno 已提交
183
	const out = opts.out;
184
	const fileContentMapper = opts.fileContentMapper || ((contents: string, _path: string) => contents);
I
isidor 已提交
185

186
	return function () {
J
Joao Moreno 已提交
187 188 189
		const bundlesStream = es.through(); // this stream will contain the bundled files
		const resourcesStream = es.through(); // this stream will contain the resources
		const bundleInfoStream = es.through(); // this stream will contain bundleInfo.json
I
isidor 已提交
190

191
		bundle.bundle(entryPoints, loaderConfig, function (err, result) {
192
			if (err || !result) { return bundlesStream.emit('error', JSON.stringify(err)); }
I
isidor 已提交
193

194
			toBundleStream(src, bundledFileHeader, result.files, fileContentMapper).pipe(bundlesStream);
195 196

			// Remove css inlined resources
J
Joao Moreno 已提交
197
			const filteredResources = resources.slice();
198
			result.cssInlinedResources.forEach(function (resource) {
J
Joao Moreno 已提交
199 200 201
				if (process.env['VSCODE_BUILD_VERBOSE']) {
					log('optimizer', 'excluding inlined: ' + resource);
				}
202 203
				filteredResources.push('!' + resource);
			});
A
Alex Dima 已提交
204
			gulp.src(filteredResources, { base: `${src}`, allowEmpty: true }).pipe(resourcesStream);
205

206
			const bundleInfoArray: VinylFile[] = [];
207
			if (opts.bundleInfo) {
208
				bundleInfoArray.push(new VinylFile({
209 210
					path: 'bundleInfo.json',
					base: '.',
211
					contents: Buffer.from(JSON.stringify(result.bundleData, null, '\t'))
212 213 214
				}));
			}
			es.readArray(bundleInfoArray).pipe(bundleInfoStream);
I
isidor 已提交
215 216
		});

J
Joao Moreno 已提交
217
		const result = es.merge(
218
			loader(src, bundledFileHeader, bundleLoader),
I
isidor 已提交
219
			bundlesStream,
220 221
			resourcesStream,
			bundleInfoStream
I
isidor 已提交
222 223 224 225
		);

		return result
			.pipe(sourcemaps.write('./', {
226
				sourceRoot: undefined,
I
isidor 已提交
227 228 229
				addComment: true,
				includeContent: true
			}))
230 231 232 233
			.pipe(opts.languages && opts.languages.length ? processNlsFiles({
				fileHeader: bundledFileHeader,
				languages: opts.languages
			}) : es.through())
I
isidor 已提交
234 235
			.pipe(gulp.dest(out));
	};
D
Dirk Baeumer 已提交
236
}
I
isidor 已提交
237

238 239 240
declare class FileWithCopyright extends VinylFile {
	public __hasOurCopyright: boolean;
}
I
isidor 已提交
241
/**
J
Joao Moreno 已提交
242 243
 * Wrap around uglify and allow the preserveComments function
 * to have a file "context" to include our copyright only once per file.
I
isidor 已提交
244
 */
245 246
function uglifyWithCopyrights(): NodeJS.ReadWriteStream {
	const preserveComments = (f: FileWithCopyright) => {
M
Matt Bierner 已提交
247
		return (_node: any, comment: { value: string; type: string; }) => {
248 249
			const text = comment.value;
			const type = comment.type;
I
isidor 已提交
250

251 252 253
			if (/@minifier_do_not_preserve/.test(text)) {
				return false;
			}
I
isidor 已提交
254

255
			const isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
I
isidor 已提交
256

257 258 259 260 261 262
			if (isOurCopyright) {
				if (f.__hasOurCopyright) {
					return false;
				}
				f.__hasOurCopyright = true;
				return true;
I
isidor 已提交
263 264
			}

265 266 267 268 269 270 271 272
			if ('comment2' === type) {
				// check for /*!. Note that text doesn't contain leading /*
				return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
			} else if ('comment1' === type) {
				return /license|copyright/i.test(text);
			}
			return false;
		};
I
isidor 已提交
273 274
	};

275
	const minify = (composer as any)(terser);
276 277 278
	const input = es.through();
	const output = input
		.pipe(flatmap((stream, f) => {
J
Joao Moreno 已提交
279
			return stream.pipe(minify({
J
Joao Moreno 已提交
280
				output: {
J
Joao Moreno 已提交
281
					comments: preserveComments(<FileWithCopyright>f),
282
					max_line_len: 1024
J
Joao Moreno 已提交
283
				}
284
			}));
285
		}));
I
isidor 已提交
286

287
	return es.duplex(input, output);
I
isidor 已提交
288 289
}

E
Erich Gamma 已提交
290
export function minifyTask(src: string, sourceMapBaseUrl?: string): (cb: any) => void {
291
	const sourceMappingURL = sourceMapBaseUrl ? ((f: any) => `${sourceMapBaseUrl}/${f.relative}.map`) : undefined;
J
Joao Moreno 已提交
292

293
	return cb => {
J
Joao Moreno 已提交
294 295
		const jsFilter = filter('**/*.js', { restore: true });
		const cssFilter = filter('**/*.css', { restore: true });
I
isidor 已提交
296

297 298 299 300 301 302 303 304 305
		pump(
			gulp.src([src + '/**', '!' + src + '/**/*.map']),
			jsFilter,
			sourcemaps.init({ loadMaps: true }),
			uglifyWithCopyrights(),
			jsFilter.restore,
			cssFilter,
			minifyCSS({ reduceIdents: false }),
			cssFilter.restore,
R
Rob Lourens 已提交
306 307 308 309 310 311 312
			(<any>sourcemaps).mapSources((sourcePath: string) => {
				if (sourcePath === 'bootstrap-fork.js') {
					return 'bootstrap-fork.orig.js';
				}

				return sourcePath;
			}),
313
			sourcemaps.write('./', {
J
Joao Moreno 已提交
314
				sourceMappingURL,
315
				sourceRoot: undefined,
I
isidor 已提交
316
				includeContent: true,
J
Joao Moreno 已提交
317
				addComment: true
318
			} as any),
319
			gulp.dest(src + '-min')
320
			, (err: any) => {
M
Matt Bierner 已提交
321
				if (err instanceof (uglify as any).GulpUglifyError) {
322 323
					console.error(`Uglify error in '${err.cause && err.cause.filename}'`);
				}
324

325 326
				cb(err);
			});
I
isidor 已提交
327
	};
D
Dirk Baeumer 已提交
328
}