optimize.ts 8.8 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 21
import * as path from 'path';
import * as pump from 'pump';
import * as sm from 'source-map';
J
Joao Moreno 已提交
22
import * as uglifyes from 'uglify-es';
23 24
import * as VinylFile from 'vinyl';
import * as bundle from './bundle';
25 26
import { Language, processNlsFiles } from './i18n';
import { createStatsStream } from './stats';
27
import * as util from './util';
28

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

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

E
Erich Gamma 已提交
35
export function loaderConfig(emptyPaths?: string[]) {
M
Matt Bierner 已提交
36
	const result: any = {
I
isidor 已提交
37 38
		paths: {
			'vs': 'out-build/vs',
J
Joao Moreno 已提交
39
			'vscode': 'empty:'
I
isidor 已提交
40
		},
41
		nodeModules: emptyPaths || []
I
isidor 已提交
42 43
	};

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

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

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

51 52 53 54
declare class FileSourceMap extends VinylFile {
	public sourceMap: sm.RawSourceMap;
}

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

J
Joao Moreno 已提交
66
	let isFirst = true;
A
Alex Dima 已提交
67 68
	return (
		gulp
69
			.src(sources, { base: `${src}` })
70 71 72 73 74 75
			.pipe(es.through(function (data) {
				if (isFirst) {
					isFirst = false;
					this.emit('data', new VinylFile({
						path: 'fake',
						base: '',
76
						contents: Buffer.from(bundledFileHeader)
77 78 79 80 81 82 83 84 85 86 87 88
					}));
					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 已提交
89
	);
I
isidor 已提交
90 91
}

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

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

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

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

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

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

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

136
export interface IOptimizeTaskOpts {
137 138 139 140
	/**
	 * The folder to read files from.
	 */
	src: string;
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
	/**
	 * (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)
	 */
	header: string;
	/**
	 * (emit bundleInfo.json file)
	 */
	bundleInfo: boolean;
	/**
	 * (out folder name)
	 */
	out: string;
166 167 168 169
	/**
	 * (out folder name)
	 */
	languages?: Language[];
170
}
171

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

181
	return function () {
J
Joao Moreno 已提交
182 183 184
		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 已提交
185

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

189
			toBundleStream(src, bundledFileHeader, result.files).pipe(bundlesStream);
190 191

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

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

J
Joao Moreno 已提交
212
		const result = es.merge(
213
			loader(src, bundledFileHeader, bundleLoader),
I
isidor 已提交
214
			bundlesStream,
215 216
			resourcesStream,
			bundleInfoStream
I
isidor 已提交
217 218 219 220
		);

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

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

246 247 248
			if (/@minifier_do_not_preserve/.test(text)) {
				return false;
			}
I
isidor 已提交
249

250
			const isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
I
isidor 已提交
251

252 253 254 255 256 257
			if (isOurCopyright) {
				if (f.__hasOurCopyright) {
					return false;
				}
				f.__hasOurCopyright = true;
				return true;
I
isidor 已提交
258 259
			}

260 261 262 263 264 265 266 267
			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 已提交
268 269
	};

M
Matt Bierner 已提交
270
	const minify = (composer as any)(uglifyes);
271 272 273
	const input = es.through();
	const output = input
		.pipe(flatmap((stream, f) => {
J
Joao Moreno 已提交
274
			return stream.pipe(minify({
J
Joao Moreno 已提交
275
				output: {
J
Joao Moreno 已提交
276
					comments: preserveComments(<FileWithCopyright>f),
277
					max_line_len: 1024
J
Joao Moreno 已提交
278
				}
279
			}));
280
		}));
I
isidor 已提交
281

282
	return es.duplex(input, output);
I
isidor 已提交
283 284
}

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

288
	return cb => {
J
Joao Moreno 已提交
289 290
		const jsFilter = filter('**/*.js', { restore: true });
		const cssFilter = filter('**/*.css', { restore: true });
I
isidor 已提交
291

292 293 294 295 296 297 298 299 300 301
		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 已提交
302
				sourceMappingURL,
303
				sourceRoot: undefined,
I
isidor 已提交
304
				includeContent: true,
J
Joao Moreno 已提交
305
				addComment: true
306
			} as any),
307
			gulp.dest(src + '-min')
308
			, (err: any) => {
M
Matt Bierner 已提交
309
				if (err instanceof (uglify as any).GulpUglifyError) {
310 311
					console.error(`Uglify error in '${err.cause && err.cause.filename}'`);
				}
312

313 314
				cb(err);
			});
I
isidor 已提交
315
	};
D
Dirk Baeumer 已提交
316
}