vscode/build/lib/extensions.ts

613 lines
20 KiB
TypeScript
Raw Normal View History

2016-09-21 13:57:06 +00:00
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as es from 'event-stream';
import * as fs from 'fs';
2021-05-26 18:38:25 +00:00
import * as cp from 'child_process';
import * as glob from 'glob';
import * as gulp from 'gulp';
import * as path from 'path';
import * as through2 from 'through2';
import got from 'got';
2016-09-21 13:57:06 +00:00
import { Stream } from 'stream';
import * as File from 'vinyl';
import { createStatsStream } from './stats';
import * as util2 from './util';
2016-09-21 13:57:06 +00:00
const vzip = require('gulp-vinyl-zip');
2018-10-03 05:10:41 +00:00
import filter = require('gulp-filter');
import rename = require('gulp-rename');
2019-02-05 21:21:05 +00:00
import * as fancyLog from 'fancy-log';
import * as ansiColors from 'ansi-colors';
2016-09-21 13:57:06 +00:00
const buffer = require('gulp-buffer');
2020-07-24 11:56:43 +00:00
import * as jsoncParser from 'jsonc-parser';
2021-05-26 18:38:25 +00:00
import webpack = require('webpack');
import { getProductionDependencies } from './dependencies';
import _ = require('underscore');
import { getExtensionStream } from './builtInExtensions';
2019-07-01 10:01:47 +00:00
const util = require('./util');
const root = path.dirname(path.dirname(__dirname));
const commit = util.getVersion(root);
const sourceMappingURLBase = `https://ticino.blob.core.windows.net/sourcemaps/${commit}`;
2020-07-24 11:56:43 +00:00
function minifyExtensionResources(input: Stream): Stream {
const jsonFilter = filter(['**/*.json', '**/*.code-snippets'], { restore: true });
2019-08-12 14:45:12 +00:00
return input
2020-07-24 11:56:43 +00:00
.pipe(jsonFilter)
2019-08-12 14:45:12 +00:00
.pipe(buffer())
.pipe(es.mapSync((f: File) => {
2020-07-24 11:56:43 +00:00
const errors: jsoncParser.ParseError[] = [];
const value = jsoncParser.parse(f.contents.toString('utf8'), errors);
if (errors.length === 0) {
// file parsed OK => just stringify to drop whitespace and comments
f.contents = Buffer.from(JSON.stringify(value));
}
2019-08-12 14:45:12 +00:00
return f;
}))
2020-07-24 11:56:43 +00:00
.pipe(jsonFilter.restore);
2018-09-04 10:29:23 +00:00
}
function updateExtensionPackageJSON(input: Stream, update: (data: any) => any): Stream {
const packageJsonFilter = filter('extensions/*/package.json', { restore: true });
2020-06-10 12:20:51 +00:00
return input
.pipe(packageJsonFilter)
.pipe(buffer())
.pipe(es.mapSync((f: File) => {
const data = JSON.parse(f.contents.toString('utf8'));
f.contents = Buffer.from(JSON.stringify(update(data)));
return f;
}))
.pipe(packageJsonFilter.restore);
}
function fromLocal(extensionPath: string, forWeb: boolean): Stream {
const webpackConfigFileName = forWeb ? 'extension-browser.webpack.config.js' : 'extension.webpack.config.js';
const isWebPacked = fs.existsSync(path.join(extensionPath, webpackConfigFileName));
let input = isWebPacked
? fromLocalWebpack(extensionPath, webpackConfigFileName)
: fromLocalNormal(extensionPath);
if (isWebPacked) {
input = updateExtensionPackageJSON(input, (data: any) => {
2020-07-24 11:56:43 +00:00
delete data.scripts;
delete data.dependencies;
delete data.devDependencies;
2020-06-10 12:20:51 +00:00
if (data.main) {
data.main = data.main.replace('/out/', /dist/);
}
return data;
});
}
2020-07-24 11:56:43 +00:00
return input;
2020-06-10 12:20:51 +00:00
}
function fromLocalWebpack(extensionPath: string, webpackConfigFileName: string): Stream {
2018-10-04 21:04:23 +00:00
const result = es.through();
2018-10-04 21:04:23 +00:00
const packagedDependencies: string[] = [];
const packageJsonConfig = require(path.join(extensionPath, 'package.json'));
2018-11-16 08:04:02 +00:00
if (packageJsonConfig.dependencies) {
2020-06-10 12:20:51 +00:00
const webpackRootConfig = require(path.join(extensionPath, webpackConfigFileName));
2018-11-16 08:04:02 +00:00
for (const key in webpackRootConfig.externals) {
if (key in packageJsonConfig.dependencies) {
packagedDependencies.push(key);
}
2018-09-04 10:29:23 +00:00
}
}
2021-01-04 14:54:50 +00:00
const vsce = require('vsce') as typeof import('vsce');
2020-12-22 18:55:56 +00:00
const webpack = require('webpack');
const webpackGulp = require('webpack-stream');
2018-09-04 10:29:23 +00:00
vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn, packagedDependencies }).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
}));
2018-08-25 18:48:56 +00:00
// check for a webpack configuration files, then invoke webpack
2020-06-10 12:20:51 +00:00
// and merge its output with the files stream.
2018-09-04 10:29:23 +00:00
const webpackConfigLocations = (<string[]>glob.sync(
2020-06-10 12:20:51 +00:00
path.join(extensionPath, '**', webpackConfigFileName),
2018-09-04 10:29:23 +00:00
{ ignore: ['**/node_modules'] }
));
2019-07-05 14:11:50 +00:00
const webpackStreams = webpackConfigLocations.map(webpackConfigPath => {
2018-09-04 10:29:23 +00:00
2018-10-03 05:10:41 +00:00
const webpackDone = (err: any, stats: any) => {
2019-02-05 21:21:05 +00:00
fancyLog(`Bundled extension: ${ansiColors.yellow(path.join(path.basename(extensionPath), path.relative(extensionPath, webpackConfigPath)))}...`);
2018-09-04 10:29:23 +00:00
if (err) {
result.emit('error', err);
}
const { compilation } = stats;
if (compilation.errors.length > 0) {
result.emit('error', compilation.errors.join('\n'));
}
2018-09-04 10:29:23 +00:00
if (compilation.warnings.length > 0) {
result.emit('error', compilation.warnings.join('\n'));
}
};
const webpackConfig = {
...require(webpackConfigPath),
...{ mode: 'production' }
};
2018-10-04 21:04:23 +00:00
const relativeOutputPath = path.relative(extensionPath, webpackConfig.output.path);
2018-09-04 10:29:23 +00:00
return webpackGulp(webpackConfig, webpack, webpackDone)
.pipe(es.through(function (data) {
2018-09-04 10:29:23 +00:00
data.stat = data.stat || {};
data.base = extensionPath;
this.emit('data', data);
}))
.pipe(es.through(function (data: File) {
2018-09-04 10:29:23 +00:00
// source map handling:
// * rewrite sourceMappingURL
// * save to disk so that upload-task picks this up
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');
2018-09-04 10:29:23 +00:00
this.emit('data', data);
}));
});
2020-06-10 12:20:51 +00:00
es.merge(...webpackStreams, es.readArray(files))
2018-09-04 10:29:23 +00:00
// .pipe(es.through(function (data) {
// // debug
// console.log('out', data.path, data.contents.length);
// this.emit('data', data);
// }))
.pipe(result);
2018-09-20 09:37:40 +00:00
}).catch(err => {
console.error(extensionPath);
console.error(packagedDependencies);
result.emit('error', err);
});
return result.pipe(createStatsStream(path.basename(extensionPath)));
}
2016-09-21 13:57:06 +00:00
2018-09-04 10:29:23 +00:00
function fromLocalNormal(extensionPath: string): Stream {
const result = es.through();
2021-01-04 14:54:50 +00:00
const vsce = require('vsce') as typeof import('vsce');
2020-12-22 18:55:56 +00:00
2018-09-04 10:29:23 +00:00
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
}));
es.readArray(files).pipe(result);
})
.catch(err => result.emit('error', err));
2018-09-07 09:33:53 +00:00
return result.pipe(createStatsStream(path.basename(extensionPath)));
2018-09-04 10:29:23 +00:00
}
const userAgent = 'VSCode Build';
2016-09-21 13:57:06 +00:00
const baseHeaders = {
'X-Market-Client-Id': 'VSCode Build',
'User-Agent': userAgent,
'X-Market-User-Id': '291C1CD0-051A-4123-9B4B-30D60EF52EE2',
2016-09-21 13:57:06 +00:00
};
export function fromMarketplace(serviceUrl: string, { name: extensionName, version, metadata }: IBuiltInExtension): Stream {
2020-12-22 18:55:56 +00:00
const remote = require('gulp-remote-retry-src');
2021-01-04 14:54:50 +00:00
const json = require('gulp-json-editor') as typeof import('gulp-json-editor');
2020-12-22 18:55:56 +00:00
2018-09-21 10:16:23 +00:00
const [publisher, name] = extensionName.split('.');
const url = `${serviceUrl}/publishers/${publisher}/vsextensions/${name}/${version}/vspackage`;
2018-09-21 10:16:23 +00:00
2019-02-05 21:21:05 +00:00
fancyLog('Downloading extension:', ansiColors.yellow(`${extensionName}@${version}`), '...');
2016-09-21 13:57:06 +00:00
const options = {
2018-09-21 10:16:23 +00:00
base: url,
2016-09-21 13:57:06 +00:00
requestOptions: {
gzip: true,
2018-09-21 10:16:23 +00:00
headers: baseHeaders
2016-09-21 13:57:06 +00:00
}
};
2018-09-26 12:41:56 +00:00
const packageJsonFilter = filter('package.json', { restore: true });
2018-09-21 10:16:23 +00:00
return remote('', options)
2018-09-26 12:41:56 +00:00
.pipe(vzip.src())
.pipe(filter('extension/**'))
2018-10-03 05:10:41 +00:00
.pipe(rename(p => p.dirname = p.dirname!.replace(/^extension\/?/, '')))
2018-09-26 12:41:56 +00:00
.pipe(packageJsonFilter)
.pipe(buffer())
.pipe(json({ __metadata: metadata }))
.pipe(packageJsonFilter.restore);
2016-09-21 13:57:06 +00:00
}
const ghApiHeaders: Record<string, string> = {
Accept: 'application/vnd.github.v3+json',
'User-Agent': userAgent,
};
if (process.env.GITHUB_TOKEN) {
ghApiHeaders.Authorization = 'Basic ' + Buffer.from(process.env.GITHUB_TOKEN).toString('base64');
}
const ghDownloadHeaders = {
...ghApiHeaders,
Accept: 'application/octet-stream',
};
export function fromGithub({ name, version, repo, metadata }: IBuiltInExtension): Stream {
const remote = require('gulp-remote-retry-src');
const json = require('gulp-json-editor') as typeof import('gulp-json-editor');
fancyLog('Downloading extension from GH:', ansiColors.yellow(`${name}@${version}`), '...');
const packageJsonFilter = filter('package.json', { restore: true });
return remote([`/repos${new URL(repo).pathname}/releases/tags/v${version}`], {
base: 'https://api.github.com',
requestOptions: { headers: ghApiHeaders }
}).pipe(through2.obj(function (file, _enc, callback) {
const asset = JSON.parse(file.contents.toString()).assets.find((a: any) => a.name.endsWith('.vsix'));
if (!asset) {
return callback(new Error(`Could not find vsix in release of ${repo} @ ${version}`));
}
const res = got.stream(asset.url, { headers: ghDownloadHeaders, followRedirect: true });
file.contents = res.pipe(through2());
callback(null, file);
}))
.pipe(buffer())
.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);
}
const excludedExtensions = [
'vscode-api-tests',
'vscode-colorize-tests',
2019-04-11 10:34:05 +00:00
'vscode-test-resolver',
'ms-vscode.node-debug',
'ms-vscode.node-debug2',
];
2021-01-18 13:35:58 +00:00
const marketplaceWebExtensionsExclude = new Set([
'ms-vscode.node-debug',
'ms-vscode.node-debug2',
'ms-vscode.js-debug-companion',
'ms-vscode.js-debug',
'ms-vscode.vscode-js-profile-table'
]);
2020-07-27 11:18:08 +00:00
2018-09-21 10:16:23 +00:00
interface IBuiltInExtension {
name: string;
version: string;
repo: string;
metadata: any;
}
2020-08-03 14:53:08 +00:00
const productJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../../product.json'), 'utf8'));
2020-08-03 18:24:31 +00:00
const builtInExtensions: IBuiltInExtension[] = productJson.builtInExtensions || [];
const webBuiltInExtensions: IBuiltInExtension[] = productJson.webBuiltInExtensions || [];
2020-07-27 11:18:08 +00:00
type ExtensionKind = 'ui' | 'workspace' | 'web';
interface IExtensionManifest {
main?: string;
browser?: string;
2020-07-27 11:18:08 +00:00
extensionKind?: ExtensionKind | ExtensionKind[];
extensionPack?: string[];
extensionDependencies?: string[];
contributes?: { [id: string]: any };
2020-07-27 11:18:08 +00:00
}
/**
2021-06-22 14:58:23 +00:00
* Loosely based on `getExtensionKind` from `src/vs/workbench/services/extensions/common/extensionManifestPropertiesService.ts`
2020-07-27 11:18:08 +00:00
*/
function isWebExtension(manifest: IExtensionManifest): boolean {
if (Boolean(manifest.browser)) {
return true;
}
if (Boolean(manifest.main)) {
return false;
}
// neither browser nor main
2020-07-27 11:18:08 +00:00
if (typeof manifest.extensionKind !== 'undefined') {
const extensionKind = Array.isArray(manifest.extensionKind) ? manifest.extensionKind : [manifest.extensionKind];
if (extensionKind.indexOf('web') >= 0) {
return true;
}
}
if (typeof manifest.contributes !== 'undefined') {
for (const id of ['debuggers', 'terminal', 'typescriptServerPlugins']) {
if (manifest.contributes.hasOwnProperty(id)) {
return false;
}
}
2020-07-27 11:18:08 +00:00
}
return true;
2020-07-27 11:18:08 +00:00
}
2019-07-14 08:31:07 +00:00
2020-07-27 11:18:08 +00:00
export function packageLocalExtensionsStream(forWeb: boolean): Stream {
const localExtensionsDescriptions = (
(<string[]>glob.sync('extensions/*/package.json'))
.map(manifestPath => {
const absoluteManifestPath = path.join(root, manifestPath);
const extensionPath = path.dirname(path.join(root, manifestPath));
const extensionName = path.basename(extensionPath);
return { name: extensionName, path: extensionPath, manifestPath: absoluteManifestPath };
})
.filter(({ name }) => excludedExtensions.indexOf(name) === -1)
2020-07-27 11:18:08 +00:00
.filter(({ name }) => builtInExtensions.every(b => b.name !== name))
.filter(({ manifestPath }) => (forWeb ? isWebExtension(require(manifestPath)) : true))
);
const localExtensionsStream = minifyExtensionResources(
es.merge(
...localExtensionsDescriptions.map(extension => {
return fromLocal(extension.path, forWeb)
.pipe(rename(p => p.dirname = `extensions/${extension.name}/${p.dirname}`));
})
)
2020-07-24 11:56:43 +00:00
);
2020-07-27 11:18:08 +00:00
let result: Stream;
if (forWeb) {
result = localExtensionsStream;
} else {
// also include shared production node modules
const productionDependencies = getProductionDependencies('extensions/');
const dependenciesSrc = _.flatten(productionDependencies.map(d => path.relative(root, d.path)).map(d => [`${d}/**`, `!${d}/**/{test,tests}/**`]));
result = es.merge(localExtensionsStream, gulp.src(dependenciesSrc, { base: '.' }));
2020-07-27 11:18:08 +00:00
}
2020-06-10 12:20:51 +00:00
2020-07-27 11:18:08 +00:00
return (
result
.pipe(util2.setExecutableBit(['**/*.sh']))
2020-07-24 11:56:43 +00:00
);
2020-06-10 12:20:51 +00:00
}
export function packageMarketplaceExtensionsStream(forWeb: boolean): Stream {
2020-08-03 14:53:08 +00:00
const marketplaceExtensionsDescriptions = [
2021-01-18 13:35:58 +00:00
...builtInExtensions.filter(({ name }) => (forWeb ? !marketplaceWebExtensionsExclude.has(name) : true)),
2020-08-03 14:53:08 +00:00
...(forWeb ? webBuiltInExtensions : [])
];
2020-07-27 11:18:08 +00:00
const marketplaceExtensionsStream = minifyExtensionResources(
es.merge(
...marketplaceExtensionsDescriptions
.map(extension => {
const src = getExtensionStream(extension).pipe(rename(p => p.dirname = `extensions/${p.dirname}`));
return updateExtensionPackageJSON(src, (data: any) => {
2020-07-27 11:18:08 +00:00
delete data.scripts;
delete data.dependencies;
delete data.devDependencies;
return data;
});
})
)
2020-07-24 11:56:43 +00:00
);
2020-06-15 22:05:44 +00:00
2020-07-27 11:18:08 +00:00
return (
marketplaceExtensionsStream
.pipe(util2.setExecutableBit(['**/*.sh']))
2020-07-24 11:56:43 +00:00
);
2020-06-15 22:05:44 +00:00
}
2020-06-22 13:38:07 +00:00
export interface IScannedBuiltinExtension {
extensionPath: string;
packageJSON: any;
packageNLS?: any;
browserNlsMetadataPath?: string;
readmePath?: string;
changelogPath?: string;
2020-06-22 13:38:07 +00:00
}
export function scanBuiltinExtensions(extensionsRoot: string, exclude: string[] = []): IScannedBuiltinExtension[] {
2020-06-22 13:38:07 +00:00
const scannedExtensions: IScannedBuiltinExtension[] = [];
try {
const extensionsFolders = fs.readdirSync(extensionsRoot);
for (const extensionFolder of extensionsFolders) {
if (exclude.indexOf(extensionFolder) >= 0) {
continue;
}
const packageJSONPath = path.join(extensionsRoot, extensionFolder, 'package.json');
if (!fs.existsSync(packageJSONPath)) {
continue;
}
2022-06-08 15:49:21 +00:00
const packageJSON = JSON.parse(fs.readFileSync(packageJSONPath).toString('utf8'));
if (!isWebExtension(packageJSON)) {
continue;
}
const children = fs.readdirSync(path.join(extensionsRoot, extensionFolder));
const packageNLSPath = children.filter(child => child === 'package.nls.json')[0];
const packageNLS = packageNLSPath ? JSON.parse(fs.readFileSync(path.join(extensionsRoot, extensionFolder, packageNLSPath)).toString()) : undefined;
let browserNlsMetadataPath: string | undefined;
if (packageJSON.browser) {
const browserEntrypointFolderPath = path.join(extensionFolder, path.dirname(packageJSON.browser));
if (fs.existsSync(path.join(extensionsRoot, browserEntrypointFolderPath, 'nls.metadata.json'))) {
browserNlsMetadataPath = path.join(browserEntrypointFolderPath, 'nls.metadata.json');
}
}
const readme = children.filter(child => /^readme(\.txt|\.md|)$/i.test(child))[0];
const changelog = children.filter(child => /^changelog(\.txt|\.md|)$/i.test(child))[0];
scannedExtensions.push({
extensionPath: extensionFolder,
packageJSON,
packageNLS,
browserNlsMetadataPath,
readmePath: readme ? path.join(extensionFolder, readme) : undefined,
changelogPath: changelog ? path.join(extensionFolder, changelog) : undefined,
});
}
return scannedExtensions;
} catch (ex) {
return scannedExtensions;
2020-06-22 13:38:07 +00:00
}
}
export function translatePackageJSON(packageJSON: string, packageNLSPath: string) {
interface NLSFormat {
[key: string]: string | { message: string; comment: string[] };
}
const CharCode_PC = '%'.charCodeAt(0);
const packageNls: NLSFormat = JSON.parse(fs.readFileSync(packageNLSPath).toString());
const translate = (obj: any) => {
2022-06-08 15:49:21 +00:00
for (const key in obj) {
const val = obj[key];
if (Array.isArray(val)) {
val.forEach(translate);
} else if (val && typeof val === 'object') {
translate(val);
} else if (typeof val === 'string' && val.charCodeAt(0) === CharCode_PC && val.charCodeAt(val.length - 1) === CharCode_PC) {
const translated = packageNls[val.substr(1, val.length - 2)];
if (translated) {
obj[key] = typeof translated === 'string' ? translated : (typeof translated.message === 'string' ? translated.message : val);
}
}
}
};
translate(packageJSON);
return packageJSON;
}
2021-05-26 18:38:25 +00:00
const extensionsPath = path.join(root, 'extensions');
// Additional projects to run esbuild on. These typically build code for webviews
const esbuildMediaScripts = [
2022-03-09 00:09:23 +00:00
'markdown-language-features/esbuild-notebook.js',
'markdown-language-features/esbuild-preview.js',
'markdown-math/esbuild.js',
'notebook-renderers/esbuild.js',
'ipynb/esbuild.js',
'simple-browser/esbuild-preview.js',
2021-05-26 18:38:25 +00:00
];
export async function webpackExtensions(taskName: string, isWatch: boolean, webpackConfigLocations: { configPath: string; outputRoot?: string }[]) {
2021-05-26 18:38:25 +00:00
const webpack = require('webpack') as typeof import('webpack');
const webpackConfigs: webpack.Configuration[] = [];
for (const { configPath, outputRoot } of webpackConfigLocations) {
const configOrFnOrArray = require(configPath);
function addConfig(configOrFn: webpack.Configuration | Function) {
let config;
if (typeof configOrFn === 'function') {
config = (configOrFn as Function)({}, {});
2021-05-26 18:38:25 +00:00
webpackConfigs.push(config);
} else {
config = configOrFn;
}
if (outputRoot) {
config.output.path = path.join(outputRoot, path.relative(path.dirname(configPath), config.output.path));
}
webpackConfigs.push(configOrFn);
}
addConfig(configOrFnOrArray);
}
function reporter(fullStats: any) {
if (Array.isArray(fullStats.children)) {
for (const stats of fullStats.children) {
const outputPath = stats.outputPath;
if (outputPath) {
const relativePath = path.relative(extensionsPath, outputPath).replace(/\\/g, '/');
const match = relativePath.match(/[^\/]+(\/server|\/client)?/);
fancyLog(`Finished ${ansiColors.green(taskName)} ${ansiColors.cyan(match![0])} with ${stats.errors.length} errors.`);
}
if (Array.isArray(stats.errors)) {
stats.errors.forEach((error: any) => {
fancyLog.error(error);
});
}
if (Array.isArray(stats.warnings)) {
stats.warnings.forEach((warning: any) => {
fancyLog.warn(warning);
});
}
}
}
}
return new Promise<void>((resolve, reject) => {
if (isWatch) {
webpack(webpackConfigs).watch({}, (err, stats) => {
if (err) {
reject();
} else {
reporter(stats?.toJson());
2021-05-26 18:38:25 +00:00
}
});
} else {
webpack(webpackConfigs).run((err, stats) => {
if (err) {
fancyLog.error(err);
reject();
} else {
reporter(stats?.toJson());
2021-05-26 18:38:25 +00:00
resolve();
}
});
}
});
}
async function esbuildExtensions(taskName: string, isWatch: boolean, scripts: { script: string; outputRoot?: string }[]) {
2021-05-26 18:38:25 +00:00
function reporter(stdError: string, script: string) {
const matches = (stdError || '').match(/\> (.+): error: (.+)?/g);
fancyLog(`Finished ${ansiColors.green(taskName)} ${script} with ${matches ? matches.length : 0} errors.`);
for (const match of matches || []) {
fancyLog.error(match);
}
}
const tasks = scripts.map(({ script, outputRoot }) => {
return new Promise<void>((resolve, reject) => {
const args = [script];
if (isWatch) {
args.push('--watch');
}
if (outputRoot) {
args.push('--outputRoot', outputRoot);
}
const proc = cp.execFile(process.argv[0], args, {}, (error, _stdout, stderr) => {
if (error) {
return reject(error);
}
reporter(stderr, script);
if (stderr) {
return reject();
}
return resolve();
});
proc.stdout!.on('data', (data) => {
fancyLog(`${ansiColors.green(taskName)}: ${data.toString('utf8')}`);
});
});
});
return Promise.all(tasks);
}
export async function buildExtensionMedia(isWatch: boolean, outputRoot?: string) {
return esbuildExtensions('esbuilding extension media', isWatch, esbuildMediaScripts.map(p => ({
script: path.join(extensionsPath, p),
outputRoot: outputRoot ? path.join(root, outputRoot, path.dirname(p)) : undefined
})));
2021-05-26 18:38:25 +00:00
}