gulpfile.common.js 7.9 KB
Newer Older
I
isidor 已提交
1 2 3 4 5 6 7 8 9
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

var path = require('path');
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var filter = require('gulp-filter');
J
Joao Moreno 已提交
10
var minifyCSS = require('gulp-cssnano');
I
isidor 已提交
11 12 13 14 15 16
var uglify = require('gulp-uglify');
var es = require('event-stream');
var concat = require('gulp-concat');
var File = require('vinyl');
var bundle = require('./lib/bundle');
var util = require('./lib/util');
D
Dirk Baeumer 已提交
17
var i18n = require('./lib/i18n');
18 19
var gulpUtil = require('gulp-util');

J
Joao Moreno 已提交
20 21
var quiet = !!process.env['VSCODE_BUILD_QUIET'];

22 23 24
function log(prefix, message) {
	gulpUtil.log(gulpUtil.colors.cyan('[' + prefix + ']'), message);
}
D
Dirk Baeumer 已提交
25

J
Joao Moreno 已提交
26 27
var root = path.dirname(__dirname);
var commit = util.getVersion(root);
I
isidor 已提交
28

J
Joao Moreno 已提交
29 30 31 32 33 34 35 36 37 38
var tsOptions = {
	target: 'ES5',
	module: 'amd',
	verbose: !quiet,
	preserveConstEnums: true,
	experimentalDecorators: true,
	sourceMap: true,
	rootDir: path.join(path.dirname(__dirname), 'src')
};

I
isidor 已提交
39 40 41 42
exports.loaderConfig = function (emptyPaths) {
	var result = {
		paths: {
			'vs': 'out-build/vs',
J
Joao Moreno 已提交
43
			'vscode': 'empty:'
I
isidor 已提交
44
		},
B
Benjamin Pasero 已提交
45
		nodeModules: emptyPaths||[],
I
isidor 已提交
46 47
	};

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

I
isidor 已提交
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
	return result;
};

var IS_OUR_COPYRIGHT_REGEXP = /Copyright \(C\) Microsoft Corporation/i;

function loader(bundledFileHeader) {
	var isFirst = true;
	return gulp.src([
		'out-build/vs/loader.js',
		'out-build/vs/css.js',
		'out-build/vs/nls.js',
	], { base: 'out-build' })
		.pipe(es.through(function(data) {
			if (isFirst) {
				isFirst = false;
				this.emit('data', new File({
					path: 'fake',
					base: '',
					contents: new Buffer(bundledFileHeader)
				}));
				this.emit('data', data);
			} else {
				this.emit('data', data);
			}
		}))
		.pipe(util.loadSourcemaps())
		.pipe(concat('vs/loader.js'))
		.pipe(es.mapSync(function (f) {
J
Joao Moreno 已提交
78
			f.sourceMap.sourceRoot = util.toFileUri(tsOptions.rootDir);
I
isidor 已提交
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
			return f;
		}));
}

function toConcatStream(bundledFileHeader, sources, dest) {
	var useSourcemaps = /\.js$/.test(dest) && !/\.nls\.js$/.test(dest);

	// 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
	var containsOurCopyright = false;
	for (var i = 0, len = sources.length; i < len; i++) {
		var fileContents = sources[i].contents;
		if (IS_OUR_COPYRIGHT_REGEXP.test(fileContents)) {
			containsOurCopyright = true;
			break;
		}
	}

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

	var treatedSources = sources.map(function(source) {
		var root = source.path ? path.dirname(__dirname).replace(/\\/g, '/') : '';
		var base = source.path ? root + '/out-build' : '';

		return new File({
			path: source.path ? root + '/' + source.path.replace(/\\/g, '/') : 'fake',
			base: base,
			contents: new Buffer(source.contents)
		});
	});

	return es.readArray(treatedSources)
		.pipe(useSourcemaps ? util.loadSourcemaps() : es.through())
		.pipe(concat(dest));
}

function toBundleStream(bundledFileHeader, bundles) {
	return es.merge(bundles.map(function(bundle) {
		return toConcatStream(bundledFileHeader, bundle.sources, bundle.dest);
	}));
}

/**
 * opts:
 * - entryPoints (for AMD files, will get bundled and get Copyright treatment)
 * - otherSources (for non-AMD files that should get Copyright treatment)
 * - resources (svg, etc.)
 * - loaderConfig
 * - header (basically the Copyright treatment)
133
 * - bundleInfo (boolean - emit bundleInfo.json file)
I
isidor 已提交
134 135 136 137 138 139 140 141 142 143 144
 * - out (out folder name)
 */
exports.optimizeTask = function(opts) {
	var entryPoints = opts.entryPoints;
	var otherSources = opts.otherSources;
	var resources = opts.resources;
	var loaderConfig = opts.loaderConfig;
	var bundledFileHeader = opts.header;
	var out = opts.out;

	return function() {
145 146
		var bundlesStream = es.through(); // this stream will contain the bundled files
		var resourcesStream = es.through(); // this stream will contain the resources
147
		var bundleInfoStream = es.through(); // this stream will contain bundleInfo.json
I
isidor 已提交
148 149 150 151

		bundle.bundle(entryPoints, loaderConfig, function(err, result) {
			if (err) { return bundlesStream.emit('error', JSON.stringify(err)); }

152 153 154 155 156 157 158 159 160 161
			toBundleStream(bundledFileHeader, result.files).pipe(bundlesStream);

			// Remove css inlined resources
			var filteredResources = [];
			filteredResources = filteredResources.concat(resources);
			result.cssInlinedResources.forEach(function(resource) {
				log('optimizer', 'excluding inlined: ' + resource);
				filteredResources.push('!' + resource);
			});
			gulp.src(filteredResources, { base: 'out-build' }).pipe(resourcesStream);
162 163 164 165 166 167 168 169 170 171

			var bundleInfoArray = [];
			if (opts.bundleInfo) {
				bundleInfoArray.push(new File({
					path: 'bundleInfo.json',
					base: '.',
					contents: new Buffer(JSON.stringify(result.bundleData, null, '\t'))
				}));
			}
			es.readArray(bundleInfoArray).pipe(bundleInfoStream);
I
isidor 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
		});

		var otherSourcesStream = es.through();
		var otherSourcesStreamArr = [];

		gulp.src(otherSources, { base: 'out-build' })
			.pipe(es.through(function (data) {
				otherSourcesStreamArr.push(toConcatStream(bundledFileHeader, [data], data.relative));
			}, function () {
				if (!otherSourcesStreamArr.length) {
					setTimeout(function () { otherSourcesStream.emit('end'); }, 0);
				} else {
					es.merge(otherSourcesStreamArr).pipe(otherSourcesStream);
				}
			}));

		var result = es.merge(
			loader(bundledFileHeader),
			bundlesStream,
			otherSourcesStream,
192 193
			resourcesStream,
			bundleInfoStream
I
isidor 已提交
194 195 196 197 198 199 200 201
		);

		return result
			.pipe(sourcemaps.write('./', {
				sourceRoot: null,
				addComment: true,
				includeContent: true
			}))
A
Alex Dima 已提交
202 203 204
			.pipe(i18n.processNlsFiles({
				fileHeader: bundledFileHeader
			}))
I
isidor 已提交
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
			.pipe(gulp.dest(out));
	};
};

/**
 * wrap around uglify and allow the preserveComments function
 * to have a file "context" to include our copyright only once per file
 */
function uglifyWithCopyrights() {
	var currentFileHasOurCopyright = false;

	var onNewFile = function() {
		currentFileHasOurCopyright = false;
	};

	var preserveComments = function(node, comment) {
		var text = comment.value;
		var type = comment.type;

		if (/@minifier_do_not_preserve/.test(text)) {
			return false;
		}

		var isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);

		if (isOurCopyright) {
			if (currentFileHasOurCopyright) {
				return false;
			}
			currentFileHasOurCopyright = true;
			return true;
		}

		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;
	};

	var uglifyStream = uglify({ preserveComments: preserveComments });

	return es.through(function write(data) {
		var _this = this;

		onNewFile();

		uglifyStream.once('data', function(data) {
			_this.emit('data', data);
		})
		uglifyStream.write(data);
	}, function end() {
		this.emit('end')
	});
}

exports.minifyTask = function (src, addSourceMapsComment) {
	return function() {
		var jsFilter = filter('**/*.js', { restore: true });
		var cssFilter = filter('**/*.css', { restore: true });

		return gulp.src([src + '/**', '!' + src + '/**/*.map'])
			.pipe(jsFilter)
			.pipe(sourcemaps.init({ loadMaps: true }))
			.pipe(uglifyWithCopyrights())
			.pipe(jsFilter.restore)
			.pipe(cssFilter)
274
			.pipe(minifyCSS({ reduceIdents: false }))
I
isidor 已提交
275 276
			.pipe(cssFilter.restore)
			.pipe(sourcemaps.write('./', {
J
Joao Moreno 已提交
277 278 279
				sourceMappingURL: function (file) {
					return 'https://ticino.blob.core.windows.net/sourcemaps/' + commit + '/' + file.relative + '.map';
				},
I
isidor 已提交
280 281 282 283 284 285
				sourceRoot: null,
				includeContent: true,
				addComment: addSourceMapsComment
			}))
			.pipe(gulp.dest(src + '-min'));
	};
E
Erich Gamma 已提交
286
};