optimize.ts 9.3 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';
17 18 19 20
import * as gulpUtil from 'gulp-util';
import * as path from 'path';
import * as pump from 'pump';
import * as sm from 'source-map';
J
Joao Moreno 已提交
21
import * as uglifyes from 'uglify-es';
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 {
31 32
	gulpUtil.log(gulpUtil.colors.cyan('[' + prefix + ']'), message);
}
D
Dirk Baeumer 已提交
33

E
Erich Gamma 已提交
34
export function loaderConfig(emptyPaths?: string[]) {
J
Joao Moreno 已提交
35
	const result = {
I
isidor 已提交
36 37
		paths: {
			'vs': 'out-build/vs',
J
Joao Moreno 已提交
38
			'vscode': 'empty:'
I
isidor 已提交
39
		},
40
		nodeModules: emptyPaths || []
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 51 52 53
declare class FileSourceMap extends VinylFile {
	public sourceMap: sm.RawSourceMap;
}

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

J
Joao Moreno 已提交
65
	let isFirst = true;
A
Alex Dima 已提交
66 67
	return (
		gulp
68
			.src(sources, { base: `${src}` })
69 70 71 72 73 74
			.pipe(es.through(function (data) {
				if (isFirst) {
					isFirst = false;
					this.emit('data', new VinylFile({
						path: 'fake',
						base: '',
75
						contents: Buffer.from(bundledFileHeader)
76 77 78 79 80 81 82 83 84 85 86 87
					}));
					this.emit('data', data);
				} else {
					this.emit('data', data);
				}
			}))
			.pipe(util.loadSourcemaps())
			.pipe(concat('vs/loader.js'))
			.pipe(es.mapSync<FileSourceMap, FileSourceMap>(function (f) {
				f.sourceMap.sourceRoot = util.toFileUri(path.join(REPO_ROOT_PATH, 'src'));
				return f;
			}))
A
Alex Dima 已提交
88
	);
I
isidor 已提交
89 90
}

91
function toConcatStream(src: string, bundledFileHeader: string, sources: bundle.IFile[], dest: string): NodeJS.ReadWriteStream {
J
Joao Moreno 已提交
92
	const useSourcemaps = /\.js$/.test(dest) && !/\.nls\.js$/.test(dest);
I
isidor 已提交
93 94 95

	// 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 已提交
96 97 98
	let containsOurCopyright = false;
	for (let i = 0, len = sources.length; i < len; i++) {
		const fileContents = sources[i].contents;
I
isidor 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111
		if (IS_OUR_COPYRIGHT_REGEXP.test(fileContents)) {
			containsOurCopyright = true;
			break;
		}
	}

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

112
	const treatedSources = sources.map(function (source) {
113
		const root = source.path ? REPO_ROOT_PATH.replace(/\\/g, '/') : '';
114
		const base = source.path ? root + `/${src}` : '';
I
isidor 已提交
115

116
		return new VinylFile({
I
isidor 已提交
117 118
			path: source.path ? root + '/' + source.path.replace(/\\/g, '/') : 'fake',
			base: base,
119
			contents: Buffer.from(source.contents)
I
isidor 已提交
120 121 122 123 124
		});
	});

	return es.readArray(treatedSources)
		.pipe(useSourcemaps ? util.loadSourcemaps() : es.through())
125
		.pipe(concat(dest))
126
		.pipe(createStatsStream(dest));
I
isidor 已提交
127 128
}

129
function toBundleStream(src: string, bundledFileHeader: string, bundles: bundle.IConcatFile[]): NodeJS.ReadWriteStream {
130
	return es.merge(bundles.map(function (bundle) {
131
		return toConcatStream(src, bundledFileHeader, bundle.sources, bundle.dest);
I
isidor 已提交
132 133 134
	}));
}

135
export interface IOptimizeTaskOpts {
136 137 138 139
	/**
	 * The folder to read files from.
	 */
	src: string;
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
	/**
	 * (for AMD files, will get bundled and get Copyright treatment)
	 */
	entryPoints: bundle.IEntryPoint[];
	/**
	 * (for non-AMD files that should get Copyright treatment)
	 */
	otherSources: string[];
	/**
	 * (svg, etc.)
	 */
	resources: string[];
	loaderConfig: any;
	/**
	 * (true by default - append css and nls to loader)
	 */
	bundleLoader?: boolean;
	/**
	 * (basically the Copyright treatment)
	 */
	header: string;
	/**
	 * (emit bundleInfo.json file)
	 */
	bundleInfo: boolean;
	/**
	 * (out folder name)
	 */
	out: string;
169 170 171 172
	/**
	 * (out folder name)
	 */
	languages?: Language[];
173
}
174

175
export function optimizeTask(opts: IOptimizeTaskOpts): () => NodeJS.ReadWriteStream {
176
	const src = opts.src;
J
Joao Moreno 已提交
177 178 179 180 181
	const entryPoints = opts.entryPoints;
	const otherSources = opts.otherSources;
	const resources = opts.resources;
	const loaderConfig = opts.loaderConfig;
	const bundledFileHeader = opts.header;
A
Alex Dima 已提交
182
	const bundleLoader = (typeof opts.bundleLoader === 'undefined' ? true : opts.bundleLoader);
J
Joao Moreno 已提交
183
	const out = opts.out;
I
isidor 已提交
184

185
	return function () {
J
Joao Moreno 已提交
186 187 188
		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 已提交
189

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

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

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

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

J
Joao Moreno 已提交
216
		const otherSourcesStream = es.through();
217
		const otherSourcesStreamArr: NodeJS.ReadWriteStream[] = [];
I
isidor 已提交
218

219
		gulp.src(otherSources, { base: `${src}` })
I
isidor 已提交
220
			.pipe(es.through(function (data) {
221
				otherSourcesStreamArr.push(toConcatStream(src, bundledFileHeader, [data], data.relative));
I
isidor 已提交
222 223 224 225 226 227 228 229
			}, function () {
				if (!otherSourcesStreamArr.length) {
					setTimeout(function () { otherSourcesStream.emit('end'); }, 0);
				} else {
					es.merge(otherSourcesStreamArr).pipe(otherSourcesStream);
				}
			}));

J
Joao Moreno 已提交
230
		const result = es.merge(
231
			loader(src, bundledFileHeader, bundleLoader),
I
isidor 已提交
232 233
			bundlesStream,
			otherSourcesStream,
234 235
			resourcesStream,
			bundleInfoStream
I
isidor 已提交
236 237 238 239
		);

		return result
			.pipe(sourcemaps.write('./', {
240
				sourceRoot: undefined,
I
isidor 已提交
241 242 243
				addComment: true,
				includeContent: true
			}))
244 245 246 247
			.pipe(opts.languages && opts.languages.length ? processNlsFiles({
				fileHeader: bundledFileHeader,
				languages: opts.languages
			}) : es.through())
I
isidor 已提交
248 249
			.pipe(gulp.dest(out));
	};
D
Dirk Baeumer 已提交
250
}
I
isidor 已提交
251

252 253 254
declare class FileWithCopyright extends VinylFile {
	public __hasOurCopyright: boolean;
}
I
isidor 已提交
255
/**
J
Joao Moreno 已提交
256 257
 * Wrap around uglify and allow the preserveComments function
 * to have a file "context" to include our copyright only once per file.
I
isidor 已提交
258
 */
259 260 261
function uglifyWithCopyrights(): NodeJS.ReadWriteStream {
	const preserveComments = (f: FileWithCopyright) => {
		return (node, comment: { value: string; type: string; }) => {
262 263
			const text = comment.value;
			const type = comment.type;
I
isidor 已提交
264

265 266 267
			if (/@minifier_do_not_preserve/.test(text)) {
				return false;
			}
I
isidor 已提交
268

269
			const isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
I
isidor 已提交
270

271 272 273 274 275 276
			if (isOurCopyright) {
				if (f.__hasOurCopyright) {
					return false;
				}
				f.__hasOurCopyright = true;
				return true;
I
isidor 已提交
277 278
			}

279 280 281 282 283 284 285 286
			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 已提交
287 288
	};

J
Joao Moreno 已提交
289
	const minify = composer(uglifyes);
290 291 292
	const input = es.through();
	const output = input
		.pipe(flatmap((stream, f) => {
J
Joao Moreno 已提交
293
			return stream.pipe(minify({
J
Joao Moreno 已提交
294
				output: {
J
Joao Moreno 已提交
295
					comments: preserveComments(<FileWithCopyright>f),
296
					max_line_len: 1024
J
Joao Moreno 已提交
297
				}
298
			}));
299
		}));
I
isidor 已提交
300

301
	return es.duplex(input, output);
I
isidor 已提交
302 303
}

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

307
	return cb => {
J
Joao Moreno 已提交
308 309
		const jsFilter = filter('**/*.js', { restore: true });
		const cssFilter = filter('**/*.css', { restore: true });
I
isidor 已提交
310

311 312 313 314 315 316 317 318 319 320
		pump(
			gulp.src([src + '/**', '!' + src + '/**/*.map']),
			jsFilter,
			sourcemaps.init({ loadMaps: true }),
			uglifyWithCopyrights(),
			jsFilter.restore,
			cssFilter,
			minifyCSS({ reduceIdents: false }),
			cssFilter.restore,
			sourcemaps.write('./', {
J
Joao Moreno 已提交
321
				sourceMappingURL,
322
				sourceRoot: undefined,
I
isidor 已提交
323
				includeContent: true,
J
Joao Moreno 已提交
324
				addComment: true
325 326
			}),
			gulp.dest(src + '-min')
327 328 329 330
			, (err: any) => {
				if (err instanceof uglify.GulpUglifyError) {
					console.error(`Uglify error in '${err.cause && err.cause.filename}'`);
				}
331

332 333
				cb(err);
			});
I
isidor 已提交
334
	};
D
Dirk Baeumer 已提交
335
}