extensions.ts 9.2 KB
Newer Older
J
Joao Moreno 已提交
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.
 *--------------------------------------------------------------------------------------------*/

6
import * as es from 'event-stream';
7 8 9 10
import * as fs from 'fs';
import * as glob from 'glob';
import * as gulp from 'gulp';
import * as path from 'path';
J
Joao Moreno 已提交
11
import { Stream } from 'stream';
12 13 14
import * as File from 'vinyl';
import * as vsce from 'vsce';
import * as util2 from './util';
J
Joao Moreno 已提交
15 16 17 18 19 20 21 22 23
import assign = require('object-assign');
import remote = require('gulp-remote-src');
const flatmap = require('gulp-flatmap');
const vzip = require('gulp-vinyl-zip');
const filter = require('gulp-filter');
const rename = require('gulp-rename');
const util = require('gulp-util');
const buffer = require('gulp-buffer');
const json = require('gulp-json-editor');
24 25
const webpack = require('webpack');
const webpackGulp = require('webpack-stream');
26 27

const root = path.resolve(path.join(__dirname, '..', '..'));
28

29
export function fromLocal(extensionPath: string, sourceMappingURLBase?: string): Stream {
30 31 32 33 34 35 36 37 38 39 40 41 42 43
	let result = es.through();

	vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn }).then(fileNames => {
		const files = fileNames
			.map(fileName => path.join(extensionPath, fileName))
			.map(filePath => new File({
				path: filePath,
				stat: fs.statSync(filePath),
				base: extensionPath,
				contents: fs.createReadStream(filePath) as any
			}));

		const filesStream = es.readArray(files);

44
		// check for a webpack configuration files, then invoke webpack
45 46
		// and merge its output with the files stream. also rewrite the package.json
		// file to a new entry point
47 48 49 50
		const pattern = path.join(extensionPath, '/**/extension.webpack.config.js');
		const webpackConfigLocations = (<string[]>glob.sync(pattern, { ignore: ['**/node_modules'] }));
		if (webpackConfigLocations.length) {

51 52 53 54 55 56 57 58
			const packageJsonFilter = filter(f => {
				if (path.basename(f.path) === 'package.json') {
					// only modify package.json's next to the webpack file.
					// to be safe, use existsSync instead of path comparison.
					return fs.existsSync(path.join(path.dirname(f.path), 'extension.webpack.config.js'));
				}
				return false;
			}, { restore: true });
59

60 61 62
			const patchFilesStream = filesStream
				.pipe(packageJsonFilter)
				.pipe(buffer())
63 64 65 66 67
				.pipe(json(data => {
					// hardcoded entry point directory!
					data.main = data.main.replace('/out/', /dist/);
					return data;
				}))
68 69
				.pipe(packageJsonFilter.restore);

70

71
			const webpackStreams = webpackConfigLocations.map(webpackConfigPath => {
72 73

				const webpackDone = (err, stats) => {
74
					util.log(`Bundled extension: ${util.colors.yellow(path.join(path.basename(extensionPath), path.relative(extensionPath, webpackConfigPath)))}...`);
75 76 77 78 79 80 81 82 83 84 85
					if (err) {
						result.emit('error', err);
					}
					const { compilation } = stats;
					if (compilation.errors.length > 0) {
						result.emit('error', compilation.errors.join('\n'));
					}
					if (compilation.warnings.length > 0) {
						result.emit('error', compilation.warnings.join('\n'));
					}
				};
86

87 88
				const webpackConfig = {
					...require(webpackConfigPath),
89
					...{ mode: 'production' }
90 91 92
				};
				let relativeOutputPath = path.relative(extensionPath, webpackConfig.output.path);

93
				return webpackGulp(webpackConfig, webpack, webpackDone)
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
					.pipe(es.through(function (data) {
						data.stat = data.stat || {};
						data.base = extensionPath;
						this.emit('data', data);
					}))
					.pipe(es.through(function (data: File) {
						// source map handling:
						// * rewrite sourceMappingURL
						// * save to disk so that upload-task picks this up
						if (sourceMappingURLBase) {
							const contents = (<Buffer>data.contents).toString('utf8');
							data.contents = Buffer.from(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, function (_m, g1) {
								return `\n//# sourceMappingURL=${sourceMappingURLBase}/extensions/${path.basename(extensionPath)}/${relativeOutputPath}/${g1}`;
							}), 'utf8');

							if (/\.js\.map$/.test(data.path)) {
								if (!fs.existsSync(path.dirname(data.path))) {
									fs.mkdirSync(path.dirname(data.path));
								}
								fs.writeFileSync(data.path, data.contents);
J
Johannes Rieken 已提交
114
							}
115
						}
116 117 118
						this.emit('data', data);
					}));
			});
119

120
			es.merge(...webpackStreams, patchFilesStream)
121 122
				// .pipe(es.through(function (data) {
				// 	// debug
123
				// 	console.log('out', data.path, data.contents.length);
124 125 126 127 128 129 130 131 132
				// 	this.emit('data', data);
				// }))
				.pipe(result);

		} else {
			filesStream.pipe(result);
		}

	}).catch(err => result.emit('error', err));
133 134 135

	return result;
}
J
Joao Moreno 已提交
136 137

function error(err: any): Stream {
138
	const result = es.through();
J
Joao Moreno 已提交
139 140 141 142 143 144 145
	setTimeout(() => result.emit('error', err));
	return result;
}

const baseHeaders = {
	'X-Market-Client-Id': 'VSCode Build',
	'User-Agent': 'VSCode Build',
146
	'X-Market-User-Id': '291C1CD0-051A-4123-9B4B-30D60EF52EE2',
J
Joao Moreno 已提交
147 148
};

149
export function fromMarketplace(extensionName: string, version: string): Stream {
J
Joao Moreno 已提交
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
	const filterType = 7;
	const value = extensionName;
	const criterium = { filterType, value };
	const criteria = [criterium];
	const pageNumber = 1;
	const pageSize = 1;
	const sortBy = 0;
	const sortOrder = 0;
	const flags = 0x1 | 0x2 | 0x80;
	const assetTypes = ['Microsoft.VisualStudio.Services.VSIXPackage'];
	const filters = [{ criteria, pageNumber, pageSize, sortBy, sortOrder }];
	const body = JSON.stringify({ filters, assetTypes, flags });
	const headers: any = assign({}, baseHeaders, {
		'Content-Type': 'application/json',
		'Accept': 'application/json;api-version=3.0-preview.1',
		'Content-Length': body.length
	});

	const options = {
		base: 'https://marketplace.visualstudio.com/_apis/public/gallery',
		requestOptions: {
			method: 'POST',
			gzip: true,
			headers,
			body: body
		}
	};

	return remote('/extensionquery', options)
		.pipe(flatmap((stream, f) => {
			const rawResult = f.contents.toString('utf8');
			const result = JSON.parse(rawResult);
			const extension = result.results[0].extensions[0];
			if (!extension) {
184
				return error(`No such extension: ${extension}`);
J
Joao Moreno 已提交
185 186 187 188 189 190 191 192 193 194
			}

			const metadata = {
				id: extension.extensionId,
				publisherId: extension.publisher,
				publisherDisplayName: extension.publisher.displayName
			};

			const extensionVersion = extension.versions.filter(v => v.version === version)[0];
			if (!extensionVersion) {
195
				return error(`No such extension version: ${extensionName} @ ${version}`);
J
Joao Moreno 已提交
196 197 198 199
			}

			const asset = extensionVersion.files.filter(f => f.assetType === 'Microsoft.VisualStudio.Services.VSIXPackage')[0];
			if (!asset) {
200
				return error(`No VSIX found for extension version: ${extensionName} @ ${version}`);
J
Joao Moreno 已提交
201 202
			}

203
			util.log('Downloading extension:', util.colors.yellow(`${extensionName}@${version}`), '...');
J
Joao Moreno 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227

			const options = {
				base: asset.source,
				requestOptions: {
					gzip: true,
					headers: baseHeaders
				}
			};

			return remote('', options)
				.pipe(flatmap(stream => {
					const packageJsonFilter = filter('package.json', { restore: true });

					return stream
						.pipe(vzip.src())
						.pipe(filter('extension/**'))
						.pipe(rename(p => p.dirname = p.dirname.replace(/^extension\/?/, '')))
						.pipe(packageJsonFilter)
						.pipe(buffer())
						.pipe(json({ __metadata: metadata }))
						.pipe(packageJsonFilter.restore);
				}));
		}));
}
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 274 275 276 277

interface IPackageExtensionsOptions {
	/**
	 * Set to undefined to package all of them.
	 */
	desiredExtensions?: string[];
	sourceMappingURLBase?: string;
}

const excludedExtensions = [
	'vscode-api-tests',
	'vscode-colorize-tests',
	'ms-vscode.node-debug',
	'ms-vscode.node-debug2',
];

const builtInExtensions: { name: string, version: string, repo: string; }[] = require('../builtInExtensions.json');

export function packageExtensionsStream(opts?: IPackageExtensionsOptions): NodeJS.ReadWriteStream {
	opts = opts || {};

	const localExtensionDescriptions = (<string[]>glob.sync('extensions/*/package.json'))
		.map(manifestPath => {
			const extensionPath = path.dirname(path.join(root, manifestPath));
			const extensionName = path.basename(extensionPath);
			return { name: extensionName, path: extensionPath };
		})
		.filter(({ name }) => excludedExtensions.indexOf(name) === -1)
		.filter(({ name }) => opts.desiredExtensions ? opts.desiredExtensions.indexOf(name) >= 0 : true)
		.filter(({ name }) => builtInExtensions.every(b => b.name !== name));

	const localExtensions = es.merge(...localExtensionDescriptions.map(extension => {
		return fromLocal(extension.path, opts.sourceMappingURLBase)
			.pipe(rename(p => p.dirname = `extensions/${extension.name}/${p.dirname}`));
	}));

	const localExtensionDependencies = gulp.src('extensions/node_modules/**', { base: '.' });

	const marketplaceExtensions = es.merge(
		...builtInExtensions
			.filter(({ name }) => opts.desiredExtensions ? opts.desiredExtensions.indexOf(name) >= 0 : true)
			.map(extension => {
				return fromMarketplace(extension.name, extension.version)
					.pipe(rename(p => p.dirname = `extensions/${extension.name}/${p.dirname}`));
			})
	);

	return es.merge(localExtensions, localExtensionDependencies, marketplaceExtensions)
		.pipe(util2.setExecutableBit(['**/*.sh']))
		.pipe(filter(['**', '!**/*.js.map']));
278
}