Use es2017 as target for build scripts (#60707)

Upgrades our build scripts to target ES2017 since they are run on modern versions of node

This allows us to remove shims for es6 features such as `Object.assign`, and also remove a few extra typings packages
This commit is contained in:
Matt Bierner 2018-10-12 11:24:15 -07:00 committed by GitHub
parent 36b60430f5
commit 3fcb671444
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
32 changed files with 1704 additions and 1964 deletions

View file

@ -13,7 +13,6 @@ const es = require('event-stream');
const util = require('./lib/util'); const util = require('./lib/util');
const remote = require('gulp-remote-src'); const remote = require('gulp-remote-src');
const zip = require('gulp-vinyl-zip'); const zip = require('gulp-vinyl-zip');
const assign = require('object-assign');
const pkg = require('../package.json'); const pkg = require('../package.json');
@ -55,7 +54,7 @@ gulp.task('mixin', function () {
.pipe(util.rebase(2)) .pipe(util.rebase(2))
.pipe(productJsonFilter) .pipe(productJsonFilter)
.pipe(buffer()) .pipe(buffer())
.pipe(json(o => assign({}, require('../product.json'), o))) .pipe(json(o => Object.assign({}, require('../product.json'), o)))
.pipe(productJsonFilter.restore); .pipe(productJsonFilter.restore);
all = es.merge(mixin); all = es.merge(mixin);

View file

@ -4,33 +4,33 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var path = require("path"); const path = require("path");
var es = require("event-stream"); const es = require("event-stream");
var pickle = require('chromium-pickle-js'); const pickle = require('chromium-pickle-js');
var Filesystem = require('asar/lib/filesystem'); const Filesystem = require('asar/lib/filesystem');
var VinylFile = require("vinyl"); const VinylFile = require("vinyl");
var minimatch = require("minimatch"); const minimatch = require("minimatch");
function createAsar(folderPath, unpackGlobs, destFilename) { function createAsar(folderPath, unpackGlobs, destFilename) {
var shouldUnpackFile = function (file) { const shouldUnpackFile = (file) => {
for (var i = 0; i < unpackGlobs.length; i++) { for (let i = 0; i < unpackGlobs.length; i++) {
if (minimatch(file.relative, unpackGlobs[i])) { if (minimatch(file.relative, unpackGlobs[i])) {
return true; return true;
} }
} }
return false; return false;
}; };
var filesystem = new Filesystem(folderPath); const filesystem = new Filesystem(folderPath);
var out = []; const out = [];
// Keep track of pending inserts // Keep track of pending inserts
var pendingInserts = 0; let pendingInserts = 0;
var onFileInserted = function () { pendingInserts--; }; let onFileInserted = () => { pendingInserts--; };
// Do not insert twice the same directory // Do not insert twice the same directory
var seenDir = {}; const seenDir = {};
var insertDirectoryRecursive = function (dir) { const insertDirectoryRecursive = (dir) => {
if (seenDir[dir]) { if (seenDir[dir]) {
return; return;
} }
var lastSlash = dir.lastIndexOf('/'); let lastSlash = dir.lastIndexOf('/');
if (lastSlash === -1) { if (lastSlash === -1) {
lastSlash = dir.lastIndexOf('\\'); lastSlash = dir.lastIndexOf('\\');
} }
@ -40,8 +40,8 @@ function createAsar(folderPath, unpackGlobs, destFilename) {
seenDir[dir] = true; seenDir[dir] = true;
filesystem.insertDirectory(dir); filesystem.insertDirectory(dir);
}; };
var insertDirectoryForFile = function (file) { const insertDirectoryForFile = (file) => {
var lastSlash = file.lastIndexOf('/'); let lastSlash = file.lastIndexOf('/');
if (lastSlash === -1) { if (lastSlash === -1) {
lastSlash = file.lastIndexOf('\\'); lastSlash = file.lastIndexOf('\\');
} }
@ -49,7 +49,7 @@ function createAsar(folderPath, unpackGlobs, destFilename) {
insertDirectoryRecursive(file.substring(0, lastSlash)); insertDirectoryRecursive(file.substring(0, lastSlash));
} }
}; };
var insertFile = function (relativePath, stat, shouldUnpack) { const insertFile = (relativePath, stat, shouldUnpack) => {
insertDirectoryForFile(relativePath); insertDirectoryForFile(relativePath);
pendingInserts++; pendingInserts++;
filesystem.insertFile(relativePath, shouldUnpack, { stat: stat }, {}, onFileInserted); filesystem.insertFile(relativePath, shouldUnpack, { stat: stat }, {}, onFileInserted);
@ -59,13 +59,13 @@ function createAsar(folderPath, unpackGlobs, destFilename) {
return; return;
} }
if (!file.stat.isFile()) { if (!file.stat.isFile()) {
throw new Error("unknown item in stream!"); throw new Error(`unknown item in stream!`);
} }
var shouldUnpack = shouldUnpackFile(file); const shouldUnpack = shouldUnpackFile(file);
insertFile(file.relative, { size: file.contents.length, mode: file.stat.mode }, shouldUnpack); insertFile(file.relative, { size: file.contents.length, mode: file.stat.mode }, shouldUnpack);
if (shouldUnpack) { if (shouldUnpack) {
// The file goes outside of xx.asar, in a folder xx.asar.unpacked // The file goes outside of xx.asar, in a folder xx.asar.unpacked
var relative = path.relative(folderPath, file.path); const relative = path.relative(folderPath, file.path);
this.queue(new VinylFile({ this.queue(new VinylFile({
cwd: folderPath, cwd: folderPath,
base: folderPath, base: folderPath,
@ -79,34 +79,33 @@ function createAsar(folderPath, unpackGlobs, destFilename) {
out.push(file.contents); out.push(file.contents);
} }
}, function () { }, function () {
var _this = this; let finish = () => {
var finish = function () {
{ {
var headerPickle = pickle.createEmpty(); const headerPickle = pickle.createEmpty();
headerPickle.writeString(JSON.stringify(filesystem.header)); headerPickle.writeString(JSON.stringify(filesystem.header));
var headerBuf = headerPickle.toBuffer(); const headerBuf = headerPickle.toBuffer();
var sizePickle = pickle.createEmpty(); const sizePickle = pickle.createEmpty();
sizePickle.writeUInt32(headerBuf.length); sizePickle.writeUInt32(headerBuf.length);
var sizeBuf = sizePickle.toBuffer(); const sizeBuf = sizePickle.toBuffer();
out.unshift(headerBuf); out.unshift(headerBuf);
out.unshift(sizeBuf); out.unshift(sizeBuf);
} }
var contents = Buffer.concat(out); const contents = Buffer.concat(out);
out.length = 0; out.length = 0;
_this.queue(new VinylFile({ this.queue(new VinylFile({
cwd: folderPath, cwd: folderPath,
base: folderPath, base: folderPath,
path: destFilename, path: destFilename,
contents: contents contents: contents
})); }));
_this.queue(null); this.queue(null);
}; };
// Call finish() only when all file inserts have finished... // Call finish() only when all file inserts have finished...
if (pendingInserts === 0) { if (pendingInserts === 0) {
finish(); finish();
} }
else { else {
onFileInserted = function () { onFileInserted = () => {
pendingInserts--; pendingInserts--;
if (pendingInserts === 0) { if (pendingInserts === 0) {
finish(); finish();

View file

@ -4,19 +4,19 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs"); const fs = require("fs");
var path = require("path"); const path = require("path");
var vm = require("vm"); const vm = require("vm");
/** /**
* Bundle `entryPoints` given config `config`. * Bundle `entryPoints` given config `config`.
*/ */
function bundle(entryPoints, config, callback) { function bundle(entryPoints, config, callback) {
var entryPointsMap = {}; const entryPointsMap = {};
entryPoints.forEach(function (module) { entryPoints.forEach((module) => {
entryPointsMap[module.name] = module; entryPointsMap[module.name] = module;
}); });
var allMentionedModulesMap = {}; const allMentionedModulesMap = {};
entryPoints.forEach(function (module) { entryPoints.forEach((module) => {
allMentionedModulesMap[module.name] = true; allMentionedModulesMap[module.name] = true;
(module.include || []).forEach(function (includedModule) { (module.include || []).forEach(function (includedModule) {
allMentionedModulesMap[includedModule] = true; allMentionedModulesMap[includedModule] = true;
@ -25,11 +25,11 @@ function bundle(entryPoints, config, callback) {
allMentionedModulesMap[excludedModule] = true; allMentionedModulesMap[excludedModule] = true;
}); });
}); });
var code = require('fs').readFileSync(path.join(__dirname, '../../src/vs/loader.js')); const code = require('fs').readFileSync(path.join(__dirname, '../../src/vs/loader.js'));
var r = vm.runInThisContext('(function(require, module, exports) { ' + code + '\n});'); const r = vm.runInThisContext('(function(require, module, exports) { ' + code + '\n});');
var loaderModule = { exports: {} }; const loaderModule = { exports: {} };
r.call({}, require, loaderModule, loaderModule.exports); r.call({}, require, loaderModule, loaderModule.exports);
var loader = loaderModule.exports; const loader = loaderModule.exports;
config.isBuild = true; config.isBuild = true;
config.paths = config.paths || {}; config.paths = config.paths || {};
if (!config.paths['vs/nls']) { if (!config.paths['vs/nls']) {
@ -39,16 +39,16 @@ function bundle(entryPoints, config, callback) {
config.paths['vs/css'] = 'out-build/vs/css.build'; config.paths['vs/css'] = 'out-build/vs/css.build';
} }
loader.config(config); loader.config(config);
loader(['require'], function (localRequire) { loader(['require'], (localRequire) => {
var resolvePath = function (path) { const resolvePath = (path) => {
var r = localRequire.toUrl(path); const r = localRequire.toUrl(path);
if (!/\.js/.test(r)) { if (!/\.js/.test(r)) {
return r + '.js'; return r + '.js';
} }
return r; return r;
}; };
for (var moduleId in entryPointsMap) { for (const moduleId in entryPointsMap) {
var entryPoint = entryPointsMap[moduleId]; const entryPoint = entryPointsMap[moduleId];
if (entryPoint.append) { if (entryPoint.append) {
entryPoint.append = entryPoint.append.map(resolvePath); entryPoint.append = entryPoint.append.map(resolvePath);
} }
@ -57,59 +57,59 @@ function bundle(entryPoints, config, callback) {
} }
} }
}); });
loader(Object.keys(allMentionedModulesMap), function () { loader(Object.keys(allMentionedModulesMap), () => {
var modules = loader.getBuildInfo(); const modules = loader.getBuildInfo();
var partialResult = emitEntryPoints(modules, entryPointsMap); const partialResult = emitEntryPoints(modules, entryPointsMap);
var cssInlinedResources = loader('vs/css').getInlinedResources(); const cssInlinedResources = loader('vs/css').getInlinedResources();
callback(null, { callback(null, {
files: partialResult.files, files: partialResult.files,
cssInlinedResources: cssInlinedResources, cssInlinedResources: cssInlinedResources,
bundleData: partialResult.bundleData bundleData: partialResult.bundleData
}); });
}, function (err) { return callback(err, null); }); }, (err) => callback(err, null));
} }
exports.bundle = bundle; exports.bundle = bundle;
function emitEntryPoints(modules, entryPoints) { function emitEntryPoints(modules, entryPoints) {
var modulesMap = {}; const modulesMap = {};
modules.forEach(function (m) { modules.forEach((m) => {
modulesMap[m.id] = m; modulesMap[m.id] = m;
}); });
var modulesGraph = {}; const modulesGraph = {};
modules.forEach(function (m) { modules.forEach((m) => {
modulesGraph[m.id] = m.dependencies; modulesGraph[m.id] = m.dependencies;
}); });
var sortedModules = topologicalSort(modulesGraph); const sortedModules = topologicalSort(modulesGraph);
var result = []; let result = [];
var usedPlugins = {}; const usedPlugins = {};
var bundleData = { const bundleData = {
graph: modulesGraph, graph: modulesGraph,
bundles: {} bundles: {}
}; };
Object.keys(entryPoints).forEach(function (moduleToBundle) { Object.keys(entryPoints).forEach((moduleToBundle) => {
var info = entryPoints[moduleToBundle]; const info = entryPoints[moduleToBundle];
var rootNodes = [moduleToBundle].concat(info.include || []); const rootNodes = [moduleToBundle].concat(info.include || []);
var allDependencies = visit(rootNodes, modulesGraph); const allDependencies = visit(rootNodes, modulesGraph);
var excludes = ['require', 'exports', 'module'].concat(info.exclude || []); const excludes = ['require', 'exports', 'module'].concat(info.exclude || []);
excludes.forEach(function (excludeRoot) { excludes.forEach((excludeRoot) => {
var allExcludes = visit([excludeRoot], modulesGraph); const allExcludes = visit([excludeRoot], modulesGraph);
Object.keys(allExcludes).forEach(function (exclude) { Object.keys(allExcludes).forEach((exclude) => {
delete allDependencies[exclude]; delete allDependencies[exclude];
}); });
}); });
var includedModules = sortedModules.filter(function (module) { const includedModules = sortedModules.filter((module) => {
return allDependencies[module]; return allDependencies[module];
}); });
bundleData.bundles[moduleToBundle] = includedModules; bundleData.bundles[moduleToBundle] = includedModules;
var res = emitEntryPoint(modulesMap, modulesGraph, moduleToBundle, includedModules, info.prepend || [], info.append || [], info.dest); const res = emitEntryPoint(modulesMap, modulesGraph, moduleToBundle, includedModules, info.prepend || [], info.append || [], info.dest);
result = result.concat(res.files); result = result.concat(res.files);
for (var pluginName in res.usedPlugins) { for (const pluginName in res.usedPlugins) {
usedPlugins[pluginName] = usedPlugins[pluginName] || res.usedPlugins[pluginName]; usedPlugins[pluginName] = usedPlugins[pluginName] || res.usedPlugins[pluginName];
} }
}); });
Object.keys(usedPlugins).forEach(function (pluginName) { Object.keys(usedPlugins).forEach((pluginName) => {
var plugin = usedPlugins[pluginName]; const plugin = usedPlugins[pluginName];
if (typeof plugin.finishBuild === 'function') { if (typeof plugin.finishBuild === 'function') {
var write = function (filename, contents) { const write = (filename, contents) => {
result.push({ result.push({
dest: filename, dest: filename,
sources: [{ sources: [{
@ -128,16 +128,16 @@ function emitEntryPoints(modules, entryPoints) {
}; };
} }
function extractStrings(destFiles) { function extractStrings(destFiles) {
var parseDefineCall = function (moduleMatch, depsMatch) { const parseDefineCall = (moduleMatch, depsMatch) => {
var module = moduleMatch.replace(/^"|"$/g, ''); const module = moduleMatch.replace(/^"|"$/g, '');
var deps = depsMatch.split(','); let deps = depsMatch.split(',');
deps = deps.map(function (dep) { deps = deps.map((dep) => {
dep = dep.trim(); dep = dep.trim();
dep = dep.replace(/^"|"$/g, ''); dep = dep.replace(/^"|"$/g, '');
dep = dep.replace(/^'|'$/g, ''); dep = dep.replace(/^'|'$/g, '');
var prefix = null; let prefix = null;
var _path = null; let _path = null;
var pieces = dep.split('!'); const pieces = dep.split('!');
if (pieces.length > 1) { if (pieces.length > 1) {
prefix = pieces[0] + '!'; prefix = pieces[0] + '!';
_path = pieces[1]; _path = pieces[1];
@ -147,7 +147,7 @@ function extractStrings(destFiles) {
_path = pieces[0]; _path = pieces[0];
} }
if (/^\.\//.test(_path) || /^\.\.\//.test(_path)) { if (/^\.\//.test(_path) || /^\.\.\//.test(_path)) {
var res = path.join(path.dirname(module), _path).replace(/\\/g, '/'); const res = path.join(path.dirname(module), _path).replace(/\\/g, '/');
return prefix + res; return prefix + res;
} }
return prefix + _path; return prefix + _path;
@ -157,7 +157,7 @@ function extractStrings(destFiles) {
deps: deps deps: deps
}; };
}; };
destFiles.forEach(function (destFile) { destFiles.forEach((destFile) => {
if (!/\.js$/.test(destFile.dest)) { if (!/\.js$/.test(destFile.dest)) {
return; return;
} }
@ -165,44 +165,44 @@ function extractStrings(destFiles) {
return; return;
} }
// Do one pass to record the usage counts for each module id // Do one pass to record the usage counts for each module id
var useCounts = {}; const useCounts = {};
destFile.sources.forEach(function (source) { destFile.sources.forEach((source) => {
var matches = source.contents.match(/define\(("[^"]+"),\s*\[(((, )?("|')[^"']+("|'))+)\]/); const matches = source.contents.match(/define\(("[^"]+"),\s*\[(((, )?("|')[^"']+("|'))+)\]/);
if (!matches) { if (!matches) {
return; return;
} }
var defineCall = parseDefineCall(matches[1], matches[2]); const defineCall = parseDefineCall(matches[1], matches[2]);
useCounts[defineCall.module] = (useCounts[defineCall.module] || 0) + 1; useCounts[defineCall.module] = (useCounts[defineCall.module] || 0) + 1;
defineCall.deps.forEach(function (dep) { defineCall.deps.forEach((dep) => {
useCounts[dep] = (useCounts[dep] || 0) + 1; useCounts[dep] = (useCounts[dep] || 0) + 1;
}); });
}); });
var sortedByUseModules = Object.keys(useCounts); const sortedByUseModules = Object.keys(useCounts);
sortedByUseModules.sort(function (a, b) { sortedByUseModules.sort((a, b) => {
return useCounts[b] - useCounts[a]; return useCounts[b] - useCounts[a];
}); });
var replacementMap = {}; const replacementMap = {};
sortedByUseModules.forEach(function (module, index) { sortedByUseModules.forEach((module, index) => {
replacementMap[module] = index; replacementMap[module] = index;
}); });
destFile.sources.forEach(function (source) { destFile.sources.forEach((source) => {
source.contents = source.contents.replace(/define\(("[^"]+"),\s*\[(((, )?("|')[^"']+("|'))+)\]/, function (_, moduleMatch, depsMatch) { source.contents = source.contents.replace(/define\(("[^"]+"),\s*\[(((, )?("|')[^"']+("|'))+)\]/, (_, moduleMatch, depsMatch) => {
var defineCall = parseDefineCall(moduleMatch, depsMatch); const defineCall = parseDefineCall(moduleMatch, depsMatch);
return "define(__m[" + replacementMap[defineCall.module] + "/*" + defineCall.module + "*/], __M([" + defineCall.deps.map(function (dep) { return replacementMap[dep] + '/*' + dep + '*/'; }).join(',') + "])"; return `define(__m[${replacementMap[defineCall.module]}/*${defineCall.module}*/], __M([${defineCall.deps.map(dep => replacementMap[dep] + '/*' + dep + '*/').join(',')}])`;
}); });
}); });
destFile.sources.unshift({ destFile.sources.unshift({
path: null, path: null,
contents: [ contents: [
'(function() {', '(function() {',
"var __m = " + JSON.stringify(sortedByUseModules) + ";", `var __m = ${JSON.stringify(sortedByUseModules)};`,
"var __M = function(deps) {", `var __M = function(deps) {`,
" var result = [];", ` var result = [];`,
" for (var i = 0, len = deps.length; i < len; i++) {", ` for (var i = 0, len = deps.length; i < len; i++) {`,
" result[i] = __m[deps[i]];", ` result[i] = __m[deps[i]];`,
" }", ` }`,
" return result;", ` return result;`,
"};" `};`
].join('\n') ].join('\n')
}); });
destFile.sources.push({ destFile.sources.push({
@ -214,7 +214,7 @@ function extractStrings(destFiles) {
} }
function removeDuplicateTSBoilerplate(destFiles) { function removeDuplicateTSBoilerplate(destFiles) {
// Taken from typescript compiler => emitFiles // Taken from typescript compiler => emitFiles
var BOILERPLATE = [ const BOILERPLATE = [
{ start: /^var __extends/, end: /^}\)\(\);$/ }, { start: /^var __extends/, end: /^}\)\(\);$/ },
{ start: /^var __assign/, end: /^};$/ }, { start: /^var __assign/, end: /^};$/ },
{ start: /^var __decorate/, end: /^};$/ }, { start: /^var __decorate/, end: /^};$/ },
@ -223,14 +223,14 @@ function removeDuplicateTSBoilerplate(destFiles) {
{ start: /^var __awaiter/, end: /^};$/ }, { start: /^var __awaiter/, end: /^};$/ },
{ start: /^var __generator/, end: /^};$/ }, { start: /^var __generator/, end: /^};$/ },
]; ];
destFiles.forEach(function (destFile) { destFiles.forEach((destFile) => {
var SEEN_BOILERPLATE = []; const SEEN_BOILERPLATE = [];
destFile.sources.forEach(function (source) { destFile.sources.forEach((source) => {
var lines = source.contents.split(/\r\n|\n|\r/); const lines = source.contents.split(/\r\n|\n|\r/);
var newLines = []; const newLines = [];
var IS_REMOVING_BOILERPLATE = false, END_BOILERPLATE; let IS_REMOVING_BOILERPLATE = false, END_BOILERPLATE;
for (var i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
var line = lines[i]; const line = lines[i];
if (IS_REMOVING_BOILERPLATE) { if (IS_REMOVING_BOILERPLATE) {
newLines.push(''); newLines.push('');
if (END_BOILERPLATE.test(line)) { if (END_BOILERPLATE.test(line)) {
@ -238,8 +238,8 @@ function removeDuplicateTSBoilerplate(destFiles) {
} }
} }
else { else {
for (var j = 0; j < BOILERPLATE.length; j++) { for (let j = 0; j < BOILERPLATE.length; j++) {
var boilerplate = BOILERPLATE[j]; const boilerplate = BOILERPLATE[j];
if (boilerplate.start.test(line)) { if (boilerplate.start.test(line)) {
if (SEEN_BOILERPLATE[j]) { if (SEEN_BOILERPLATE[j]) {
IS_REMOVING_BOILERPLATE = true; IS_REMOVING_BOILERPLATE = true;
@ -267,30 +267,30 @@ function emitEntryPoint(modulesMap, deps, entryPoint, includedModules, prepend,
if (!dest) { if (!dest) {
dest = entryPoint + '.js'; dest = entryPoint + '.js';
} }
var mainResult = { const mainResult = {
sources: [], sources: [],
dest: dest dest: dest
}, results = [mainResult]; }, results = [mainResult];
var usedPlugins = {}; const usedPlugins = {};
var getLoaderPlugin = function (pluginName) { const getLoaderPlugin = (pluginName) => {
if (!usedPlugins[pluginName]) { if (!usedPlugins[pluginName]) {
usedPlugins[pluginName] = modulesMap[pluginName].exports; usedPlugins[pluginName] = modulesMap[pluginName].exports;
} }
return usedPlugins[pluginName]; return usedPlugins[pluginName];
}; };
includedModules.forEach(function (c) { includedModules.forEach((c) => {
var bangIndex = c.indexOf('!'); const bangIndex = c.indexOf('!');
if (bangIndex >= 0) { if (bangIndex >= 0) {
var pluginName = c.substr(0, bangIndex); const pluginName = c.substr(0, bangIndex);
var plugin = getLoaderPlugin(pluginName); const plugin = getLoaderPlugin(pluginName);
mainResult.sources.push(emitPlugin(entryPoint, plugin, pluginName, c.substr(bangIndex + 1))); mainResult.sources.push(emitPlugin(entryPoint, plugin, pluginName, c.substr(bangIndex + 1)));
return; return;
} }
var module = modulesMap[c]; const module = modulesMap[c];
if (module.path === 'empty:') { if (module.path === 'empty:') {
return; return;
} }
var contents = readFileAndRemoveBOM(module.path); const contents = readFileAndRemoveBOM(module.path);
if (module.shim) { if (module.shim) {
mainResult.sources.push(emitShimmedModule(c, deps[c], module.shim, module.path, contents)); mainResult.sources.push(emitShimmedModule(c, deps[c], module.shim, module.path, contents));
} }
@ -298,14 +298,14 @@ function emitEntryPoint(modulesMap, deps, entryPoint, includedModules, prepend,
mainResult.sources.push(emitNamedModule(c, module.defineLocation, module.path, contents)); mainResult.sources.push(emitNamedModule(c, module.defineLocation, module.path, contents));
} }
}); });
Object.keys(usedPlugins).forEach(function (pluginName) { Object.keys(usedPlugins).forEach((pluginName) => {
var plugin = usedPlugins[pluginName]; const plugin = usedPlugins[pluginName];
if (typeof plugin.writeFile === 'function') { if (typeof plugin.writeFile === 'function') {
var req = (function () { const req = (() => {
throw new Error('no-no!'); throw new Error('no-no!');
}); });
req.toUrl = function (something) { return something; }; req.toUrl = something => something;
var write = function (filename, contents) { const write = (filename, contents) => {
results.push({ results.push({
dest: filename, dest: filename,
sources: [{ sources: [{
@ -317,15 +317,15 @@ function emitEntryPoint(modulesMap, deps, entryPoint, includedModules, prepend,
plugin.writeFile(pluginName, entryPoint, req, write, {}); plugin.writeFile(pluginName, entryPoint, req, write, {});
} }
}); });
var toIFile = function (path) { const toIFile = (path) => {
var contents = readFileAndRemoveBOM(path); const contents = readFileAndRemoveBOM(path);
return { return {
path: path, path: path,
contents: contents contents: contents
}; };
}; };
var toPrepend = (prepend || []).map(toIFile); const toPrepend = (prepend || []).map(toIFile);
var toAppend = (append || []).map(toIFile); const toAppend = (append || []).map(toIFile);
mainResult.sources = toPrepend.concat(mainResult.sources).concat(toAppend); mainResult.sources = toPrepend.concat(mainResult.sources).concat(toAppend);
return { return {
files: results, files: results,
@ -333,8 +333,8 @@ function emitEntryPoint(modulesMap, deps, entryPoint, includedModules, prepend,
}; };
} }
function readFileAndRemoveBOM(path) { function readFileAndRemoveBOM(path) {
var BOM_CHAR_CODE = 65279; const BOM_CHAR_CODE = 65279;
var contents = fs.readFileSync(path, 'utf8'); let contents = fs.readFileSync(path, 'utf8');
// Remove BOM // Remove BOM
if (contents.charCodeAt(0) === BOM_CHAR_CODE) { if (contents.charCodeAt(0) === BOM_CHAR_CODE) {
contents = contents.substring(1); contents = contents.substring(1);
@ -342,15 +342,15 @@ function readFileAndRemoveBOM(path) {
return contents; return contents;
} }
function emitPlugin(entryPoint, plugin, pluginName, moduleName) { function emitPlugin(entryPoint, plugin, pluginName, moduleName) {
var result = ''; let result = '';
if (typeof plugin.write === 'function') { if (typeof plugin.write === 'function') {
var write = (function (what) { const write = ((what) => {
result += what; result += what;
}); });
write.getEntryPoint = function () { write.getEntryPoint = () => {
return entryPoint; return entryPoint;
}; };
write.asModule = function (moduleId, code) { write.asModule = (moduleId, code) => {
code = code.replace(/^define\(/, 'define("' + moduleId + '",'); code = code.replace(/^define\(/, 'define("' + moduleId + '",');
result += code; result += code;
}; };
@ -363,18 +363,18 @@ function emitPlugin(entryPoint, plugin, pluginName, moduleName) {
} }
function emitNamedModule(moduleId, defineCallPosition, path, contents) { function emitNamedModule(moduleId, defineCallPosition, path, contents) {
// `defineCallPosition` is the position in code: |define() // `defineCallPosition` is the position in code: |define()
var defineCallOffset = positionToOffset(contents, defineCallPosition.line, defineCallPosition.col); const defineCallOffset = positionToOffset(contents, defineCallPosition.line, defineCallPosition.col);
// `parensOffset` is the position in code: define|() // `parensOffset` is the position in code: define|()
var parensOffset = contents.indexOf('(', defineCallOffset); const parensOffset = contents.indexOf('(', defineCallOffset);
var insertStr = '"' + moduleId + '", '; const insertStr = '"' + moduleId + '", ';
return { return {
path: path, path: path,
contents: contents.substr(0, parensOffset + 1) + insertStr + contents.substr(parensOffset + 1) contents: contents.substr(0, parensOffset + 1) + insertStr + contents.substr(parensOffset + 1)
}; };
} }
function emitShimmedModule(moduleId, myDeps, factory, path, contents) { function emitShimmedModule(moduleId, myDeps, factory, path, contents) {
var strDeps = (myDeps.length > 0 ? '"' + myDeps.join('", "') + '"' : ''); const strDeps = (myDeps.length > 0 ? '"' + myDeps.join('", "') + '"' : '');
var strDefine = 'define("' + moduleId + '", [' + strDeps + '], ' + factory + ');'; const strDefine = 'define("' + moduleId + '", [' + strDeps + '], ' + factory + ');';
return { return {
path: path, path: path,
contents: contents + '\n;\n' + strDefine contents: contents + '\n;\n' + strDefine
@ -387,8 +387,8 @@ function positionToOffset(str, desiredLine, desiredCol) {
if (desiredLine === 1) { if (desiredLine === 1) {
return desiredCol - 1; return desiredCol - 1;
} }
var line = 1; let line = 1;
var lastNewLineOffset = -1; let lastNewLineOffset = -1;
do { do {
if (desiredLine === line) { if (desiredLine === line) {
return lastNewLineOffset + 1 + desiredCol - 1; return lastNewLineOffset + 1 + desiredCol - 1;
@ -402,15 +402,15 @@ function positionToOffset(str, desiredLine, desiredCol) {
* Return a set of reachable nodes in `graph` starting from `rootNodes` * Return a set of reachable nodes in `graph` starting from `rootNodes`
*/ */
function visit(rootNodes, graph) { function visit(rootNodes, graph) {
var result = {}; const result = {};
var queue = rootNodes; const queue = rootNodes;
rootNodes.forEach(function (node) { rootNodes.forEach((node) => {
result[node] = true; result[node] = true;
}); });
while (queue.length > 0) { while (queue.length > 0) {
var el = queue.shift(); const el = queue.shift();
var myEdges = graph[el] || []; const myEdges = graph[el] || [];
myEdges.forEach(function (toNode) { myEdges.forEach((toNode) => {
if (!result[toNode]) { if (!result[toNode]) {
result[toNode] = true; result[toNode] = true;
queue.push(toNode); queue.push(toNode);
@ -423,11 +423,11 @@ function visit(rootNodes, graph) {
* Perform a topological sort on `graph` * Perform a topological sort on `graph`
*/ */
function topologicalSort(graph) { function topologicalSort(graph) {
var allNodes = {}, outgoingEdgeCount = {}, inverseEdges = {}; const allNodes = {}, outgoingEdgeCount = {}, inverseEdges = {};
Object.keys(graph).forEach(function (fromNode) { Object.keys(graph).forEach((fromNode) => {
allNodes[fromNode] = true; allNodes[fromNode] = true;
outgoingEdgeCount[fromNode] = graph[fromNode].length; outgoingEdgeCount[fromNode] = graph[fromNode].length;
graph[fromNode].forEach(function (toNode) { graph[fromNode].forEach((toNode) => {
allNodes[toNode] = true; allNodes[toNode] = true;
outgoingEdgeCount[toNode] = outgoingEdgeCount[toNode] || 0; outgoingEdgeCount[toNode] = outgoingEdgeCount[toNode] || 0;
inverseEdges[toNode] = inverseEdges[toNode] || []; inverseEdges[toNode] = inverseEdges[toNode] || [];
@ -435,8 +435,8 @@ function topologicalSort(graph) {
}); });
}); });
// https://en.wikipedia.org/wiki/Topological_sorting // https://en.wikipedia.org/wiki/Topological_sorting
var S = [], L = []; const S = [], L = [];
Object.keys(allNodes).forEach(function (node) { Object.keys(allNodes).forEach((node) => {
if (outgoingEdgeCount[node] === 0) { if (outgoingEdgeCount[node] === 0) {
delete outgoingEdgeCount[node]; delete outgoingEdgeCount[node];
S.push(node); S.push(node);
@ -445,10 +445,10 @@ function topologicalSort(graph) {
while (S.length > 0) { while (S.length > 0) {
// Ensure the exact same order all the time with the same inputs // Ensure the exact same order all the time with the same inputs
S.sort(); S.sort();
var n = S.shift(); const n = S.shift();
L.push(n); L.push(n);
var myInverseEdges = inverseEdges[n] || []; const myInverseEdges = inverseEdges[n] || [];
myInverseEdges.forEach(function (m) { myInverseEdges.forEach((m) => {
outgoingEdgeCount[m]--; outgoingEdgeCount[m]--;
if (outgoingEdgeCount[m] === 0) { if (outgoingEdgeCount[m] === 0) {
delete outgoingEdgeCount[m]; delete outgoingEdgeCount[m];

View file

@ -4,27 +4,26 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var es = require("event-stream"); const es = require("event-stream");
var fs = require("fs"); const fs = require("fs");
var gulp = require("gulp"); const gulp = require("gulp");
var bom = require("gulp-bom"); const bom = require("gulp-bom");
var sourcemaps = require("gulp-sourcemaps"); const sourcemaps = require("gulp-sourcemaps");
var tsb = require("gulp-tsb"); const tsb = require("gulp-tsb");
var path = require("path"); const path = require("path");
var _ = require("underscore"); const _ = require("underscore");
var monacodts = require("../monaco/api"); const monacodts = require("../monaco/api");
var nls = require("./nls"); const nls = require("./nls");
var reporter_1 = require("./reporter"); const reporter_1 = require("./reporter");
var util = require("./util"); const util = require("./util");
var watch = require('./watch'); const watch = require('./watch');
var assign = require("object-assign"); const reporter = reporter_1.createReporter();
var reporter = reporter_1.createReporter();
function getTypeScriptCompilerOptions(src) { function getTypeScriptCompilerOptions(src) {
var rootDir = path.join(__dirname, "../../" + src); const rootDir = path.join(__dirname, `../../${src}`);
var tsconfig = require("../../" + src + "/tsconfig.json"); const tsconfig = require(`../../${src}/tsconfig.json`);
var options; let options;
if (tsconfig.extends) { if (tsconfig.extends) {
options = assign({}, require(path.join(rootDir, tsconfig.extends)).compilerOptions, tsconfig.compilerOptions); options = Object.assign({}, require(path.join(rootDir, tsconfig.extends)).compilerOptions, tsconfig.compilerOptions);
} }
else { else {
options = tsconfig.compilerOptions; options = tsconfig.compilerOptions;
@ -41,16 +40,16 @@ function getTypeScriptCompilerOptions(src) {
return options; return options;
} }
function createCompile(src, build, emitError) { function createCompile(src, build, emitError) {
var opts = _.clone(getTypeScriptCompilerOptions(src)); const opts = _.clone(getTypeScriptCompilerOptions(src));
opts.inlineSources = !!build; opts.inlineSources = !!build;
opts.noFilesystemLookup = true; opts.noFilesystemLookup = true;
var ts = tsb.create(opts, true, undefined, function (err) { return reporter(err.toString()); }); const ts = tsb.create(opts, true, undefined, err => reporter(err.toString()));
return function (token) { return function (token) {
var utf8Filter = util.filter(function (data) { return /(\/|\\)test(\/|\\).*utf8/.test(data.path); }); const utf8Filter = util.filter(data => /(\/|\\)test(\/|\\).*utf8/.test(data.path));
var tsFilter = util.filter(function (data) { return /\.ts$/.test(data.path); }); const tsFilter = util.filter(data => /\.ts$/.test(data.path));
var noDeclarationsFilter = util.filter(function (data) { return !(/\.d\.ts$/.test(data.path)); }); const noDeclarationsFilter = util.filter(data => !(/\.d\.ts$/.test(data.path)));
var input = es.through(); const input = es.through();
var output = input const output = input
.pipe(utf8Filter) .pipe(utf8Filter)
.pipe(bom()) .pipe(bom())
.pipe(utf8Filter.restore) .pipe(utf8Filter.restore)
@ -70,7 +69,7 @@ function createCompile(src, build, emitError) {
return es.duplex(input, output); return es.duplex(input, output);
}; };
} }
var typesDts = [ const typesDts = [
'node_modules/typescript/lib/*.d.ts', 'node_modules/typescript/lib/*.d.ts',
'node_modules/@types/**/*.d.ts', 'node_modules/@types/**/*.d.ts',
'!node_modules/@types/webpack/**/*', '!node_modules/@types/webpack/**/*',
@ -78,10 +77,10 @@ var typesDts = [
]; ];
function compileTask(src, out, build) { function compileTask(src, out, build) {
return function () { return function () {
var compile = createCompile(src, build, true); const compile = createCompile(src, build, true);
var srcPipe = es.merge(gulp.src(src + "/**", { base: "" + src }), gulp.src(typesDts)); const srcPipe = es.merge(gulp.src(`${src}/**`, { base: `${src}` }), gulp.src(typesDts));
// Do not write .d.ts files to disk, as they are not needed there. // Do not write .d.ts files to disk, as they are not needed there.
var dtsFilter = util.filter(function (data) { return !/\.d\.ts$/.test(data.path); }); const dtsFilter = util.filter(data => !/\.d\.ts$/.test(data.path));
return srcPipe return srcPipe
.pipe(compile()) .pipe(compile())
.pipe(dtsFilter) .pipe(dtsFilter)
@ -93,11 +92,11 @@ function compileTask(src, out, build) {
exports.compileTask = compileTask; exports.compileTask = compileTask;
function watchTask(out, build) { function watchTask(out, build) {
return function () { return function () {
var compile = createCompile('src', build); const compile = createCompile('src', build);
var src = es.merge(gulp.src('src/**', { base: 'src' }), gulp.src(typesDts)); const src = es.merge(gulp.src('src/**', { base: 'src' }), gulp.src(typesDts));
var watchSrc = watch('src/**', { base: 'src' }); const watchSrc = watch('src/**', { base: 'src' });
// Do not write .d.ts files to disk, as they are not needed there. // Do not write .d.ts files to disk, as they are not needed there.
var dtsFilter = util.filter(function (data) { return !/\.d\.ts$/.test(data.path); }); const dtsFilter = util.filter(data => !/\.d\.ts$/.test(data.path));
return watchSrc return watchSrc
.pipe(util.incremental(compile, src, true)) .pipe(util.incremental(compile, src, true))
.pipe(dtsFilter) .pipe(dtsFilter)
@ -108,33 +107,33 @@ function watchTask(out, build) {
} }
exports.watchTask = watchTask; exports.watchTask = watchTask;
function monacodtsTask(out, isWatch) { function monacodtsTask(out, isWatch) {
var basePath = path.resolve(process.cwd(), out); const basePath = path.resolve(process.cwd(), out);
var neededFiles = {}; const neededFiles = {};
monacodts.getFilesToWatch(out).forEach(function (filePath) { monacodts.getFilesToWatch(out).forEach(function (filePath) {
filePath = path.normalize(filePath); filePath = path.normalize(filePath);
neededFiles[filePath] = true; neededFiles[filePath] = true;
}); });
var inputFiles = {}; const inputFiles = {};
for (var filePath in neededFiles) { for (const filePath in neededFiles) {
if (/\bsrc(\/|\\)vs\b/.test(filePath)) { if (/\bsrc(\/|\\)vs\b/.test(filePath)) {
// This file is needed from source => simply read it now // This file is needed from source => simply read it now
inputFiles[filePath] = fs.readFileSync(filePath).toString(); inputFiles[filePath] = fs.readFileSync(filePath).toString();
} }
} }
var setInputFile = function (filePath, contents) { const setInputFile = (filePath, contents) => {
if (inputFiles[filePath] === contents) { if (inputFiles[filePath] === contents) {
// no change // no change
return; return;
} }
inputFiles[filePath] = contents; inputFiles[filePath] = contents;
var neededInputFilesCount = Object.keys(neededFiles).length; const neededInputFilesCount = Object.keys(neededFiles).length;
var availableInputFilesCount = Object.keys(inputFiles).length; const availableInputFilesCount = Object.keys(inputFiles).length;
if (neededInputFilesCount === availableInputFilesCount) { if (neededInputFilesCount === availableInputFilesCount) {
run(); run();
} }
}; };
var run = function () { const run = () => {
var result = monacodts.run(out, inputFiles); const result = monacodts.run(out, inputFiles);
if (!result.isTheSame) { if (!result.isTheSame) {
if (isWatch) { if (isWatch) {
fs.writeFileSync(result.filePath, result.content); fs.writeFileSync(result.filePath, result.content);
@ -145,14 +144,14 @@ function monacodtsTask(out, isWatch) {
} }
} }
}; };
var resultStream; let resultStream;
if (isWatch) { if (isWatch) {
watch('build/monaco/*').pipe(es.through(function () { watch('build/monaco/*').pipe(es.through(function () {
run(); run();
})); }));
} }
resultStream = es.through(function (data) { resultStream = es.through(function (data) {
var filePath = path.normalize(path.resolve(basePath, data.relative)); const filePath = path.normalize(path.resolve(basePath, data.relative));
if (neededFiles[filePath]) { if (neededFiles[filePath]) {
setInputFile(filePath, data.contents.toString()); setInputFile(filePath, data.contents.toString());
} }

View file

@ -18,7 +18,6 @@ import * as nls from './nls';
import { createReporter } from './reporter'; import { createReporter } from './reporter';
import * as util from './util'; import * as util from './util';
const watch = require('./watch'); const watch = require('./watch');
import assign = require('object-assign');
const reporter = createReporter(); const reporter = createReporter();
@ -27,7 +26,7 @@ function getTypeScriptCompilerOptions(src: string) {
const tsconfig = require(`../../${src}/tsconfig.json`); const tsconfig = require(`../../${src}/tsconfig.json`);
let options: { [key: string]: any }; let options: { [key: string]: any };
if (tsconfig.extends) { if (tsconfig.extends) {
options = assign({}, require(path.join(rootDir, tsconfig.extends)).compilerOptions, tsconfig.compilerOptions); options = Object.assign({}, require(path.join(rootDir, tsconfig.extends)).compilerOptions, tsconfig.compilerOptions);
} else { } else {
options = tsconfig.compilerOptions; options = tsconfig.compilerOptions;
} }

View file

@ -3,39 +3,28 @@
* Copyright (c) Microsoft Corporation. All rights reserved. * Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var es = require("event-stream"); const es = require("event-stream");
var fs = require("fs"); const fs = require("fs");
var glob = require("glob"); const glob = require("glob");
var gulp = require("gulp"); const gulp = require("gulp");
var path = require("path"); const path = require("path");
var File = require("vinyl"); const File = require("vinyl");
var vsce = require("vsce"); const vsce = require("vsce");
var stats_1 = require("./stats"); const stats_1 = require("./stats");
var util2 = require("./util"); const util2 = require("./util");
var remote = require("gulp-remote-src"); const remote = require("gulp-remote-src");
var vzip = require('gulp-vinyl-zip'); const vzip = require('gulp-vinyl-zip');
var filter = require("gulp-filter"); const filter = require("gulp-filter");
var rename = require("gulp-rename"); const rename = require("gulp-rename");
var util = require('gulp-util'); const util = require('gulp-util');
var buffer = require('gulp-buffer'); const buffer = require('gulp-buffer');
var json = require("gulp-json-editor"); const json = require("gulp-json-editor");
var webpack = require('webpack'); const webpack = require('webpack');
var webpackGulp = require('webpack-stream'); const webpackGulp = require('webpack-stream');
var root = path.resolve(path.join(__dirname, '..', '..')); const root = path.resolve(path.join(__dirname, '..', '..'));
function fromLocal(extensionPath, sourceMappingURLBase) { function fromLocal(extensionPath, sourceMappingURLBase) {
var webpackFilename = path.join(extensionPath, 'extension.webpack.config.js'); const webpackFilename = path.join(extensionPath, 'extension.webpack.config.js');
if (fs.existsSync(webpackFilename)) { if (fs.existsSync(webpackFilename)) {
return fromLocalWebpack(extensionPath, sourceMappingURLBase); return fromLocalWebpack(extensionPath, sourceMappingURLBase);
} }
@ -44,30 +33,30 @@ function fromLocal(extensionPath, sourceMappingURLBase) {
} }
} }
function fromLocalWebpack(extensionPath, sourceMappingURLBase) { function fromLocalWebpack(extensionPath, sourceMappingURLBase) {
var result = es.through(); const result = es.through();
var packagedDependencies = []; const packagedDependencies = [];
var packageJsonConfig = require(path.join(extensionPath, 'package.json')); const packageJsonConfig = require(path.join(extensionPath, 'package.json'));
var webpackRootConfig = require(path.join(extensionPath, 'extension.webpack.config.js')); const webpackRootConfig = require(path.join(extensionPath, 'extension.webpack.config.js'));
for (var key in webpackRootConfig.externals) { for (const key in webpackRootConfig.externals) {
if (key in packageJsonConfig.dependencies) { if (key in packageJsonConfig.dependencies) {
packagedDependencies.push(key); packagedDependencies.push(key);
} }
} }
vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn, packagedDependencies: packagedDependencies }).then(function (fileNames) { vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn, packagedDependencies }).then(fileNames => {
var files = fileNames const files = fileNames
.map(function (fileName) { return path.join(extensionPath, fileName); }) .map(fileName => path.join(extensionPath, fileName))
.map(function (filePath) { return new File({ .map(filePath => new File({
path: filePath, path: filePath,
stat: fs.statSync(filePath), stat: fs.statSync(filePath),
base: extensionPath, base: extensionPath,
contents: fs.createReadStream(filePath) contents: fs.createReadStream(filePath)
}); }); }));
var filesStream = es.readArray(files); const filesStream = es.readArray(files);
// check for a webpack configuration files, then invoke webpack // check for a webpack configuration files, then invoke webpack
// and merge its output with the files stream. also rewrite the package.json // and merge its output with the files stream. also rewrite the package.json
// file to a new entry point // file to a new entry point
var webpackConfigLocations = glob.sync(path.join(extensionPath, '/**/extension.webpack.config.js'), { ignore: ['**/node_modules'] }); const webpackConfigLocations = glob.sync(path.join(extensionPath, '/**/extension.webpack.config.js'), { ignore: ['**/node_modules'] });
var packageJsonFilter = filter(function (f) { const packageJsonFilter = filter(f => {
if (path.basename(f.path) === 'package.json') { if (path.basename(f.path) === 'package.json') {
// only modify package.json's next to the webpack file. // only modify package.json's next to the webpack file.
// to be safe, use existsSync instead of path comparison. // to be safe, use existsSync instead of path comparison.
@ -75,22 +64,22 @@ function fromLocalWebpack(extensionPath, sourceMappingURLBase) {
} }
return false; return false;
}, { restore: true }); }, { restore: true });
var patchFilesStream = filesStream const patchFilesStream = filesStream
.pipe(packageJsonFilter) .pipe(packageJsonFilter)
.pipe(buffer()) .pipe(buffer())
.pipe(json(function (data) { .pipe(json((data) => {
// hardcoded entry point directory! // hardcoded entry point directory!
data.main = data.main.replace('/out/', /dist/); data.main = data.main.replace('/out/', /dist/);
return data; return data;
})) }))
.pipe(packageJsonFilter.restore); .pipe(packageJsonFilter.restore);
var webpackStreams = webpackConfigLocations.map(function (webpackConfigPath) { const webpackStreams = webpackConfigLocations.map(webpackConfigPath => {
var webpackDone = function (err, stats) { const webpackDone = (err, stats) => {
util.log("Bundled extension: " + util.colors.yellow(path.join(path.basename(extensionPath), path.relative(extensionPath, webpackConfigPath))) + "..."); util.log(`Bundled extension: ${util.colors.yellow(path.join(path.basename(extensionPath), path.relative(extensionPath, webpackConfigPath)))}...`);
if (err) { if (err) {
result.emit('error', err); result.emit('error', err);
} }
var compilation = stats.compilation; const { compilation } = stats;
if (compilation.errors.length > 0) { if (compilation.errors.length > 0) {
result.emit('error', compilation.errors.join('\n')); result.emit('error', compilation.errors.join('\n'));
} }
@ -98,8 +87,8 @@ function fromLocalWebpack(extensionPath, sourceMappingURLBase) {
result.emit('error', compilation.warnings.join('\n')); result.emit('error', compilation.warnings.join('\n'));
} }
}; };
var webpackConfig = __assign({}, require(webpackConfigPath), { mode: 'production' }); const webpackConfig = Object.assign({}, require(webpackConfigPath), { mode: 'production' });
var relativeOutputPath = path.relative(extensionPath, webpackConfig.output.path); const relativeOutputPath = path.relative(extensionPath, webpackConfig.output.path);
return webpackGulp(webpackConfig, webpack, webpackDone) return webpackGulp(webpackConfig, webpack, webpackDone)
.pipe(es.through(function (data) { .pipe(es.through(function (data) {
data.stat = data.stat || {}; data.stat = data.stat || {};
@ -111,9 +100,9 @@ function fromLocalWebpack(extensionPath, sourceMappingURLBase) {
// * rewrite sourceMappingURL // * rewrite sourceMappingURL
// * save to disk so that upload-task picks this up // * save to disk so that upload-task picks this up
if (sourceMappingURLBase) { if (sourceMappingURLBase) {
var contents = data.contents.toString('utf8'); const contents = data.contents.toString('utf8');
data.contents = Buffer.from(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, function (_m, g1) { data.contents = Buffer.from(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, function (_m, g1) {
return "\n//# sourceMappingURL=" + sourceMappingURLBase + "/extensions/" + path.basename(extensionPath) + "/" + relativeOutputPath + "/" + g1; return `\n//# sourceMappingURL=${sourceMappingURLBase}/extensions/${path.basename(extensionPath)}/${relativeOutputPath}/${g1}`;
}), 'utf8'); }), 'utf8');
if (/\.js\.map$/.test(data.path)) { if (/\.js\.map$/.test(data.path)) {
if (!fs.existsSync(path.dirname(data.path))) { if (!fs.existsSync(path.dirname(data.path))) {
@ -125,8 +114,14 @@ function fromLocalWebpack(extensionPath, sourceMappingURLBase) {
this.emit('data', data); this.emit('data', data);
})); }));
}); });
es.merge.apply(es, webpackStreams.concat([patchFilesStream])).pipe(result); es.merge(...webpackStreams, patchFilesStream)
}).catch(function (err) { // .pipe(es.through(function (data) {
// // debug
// console.log('out', data.path, data.contents.length);
// this.emit('data', data);
// }))
.pipe(result);
}).catch(err => {
console.error(extensionPath); console.error(extensionPath);
console.error(packagedDependencies); console.error(packagedDependencies);
result.emit('error', err); result.emit('error', err);
@ -134,56 +129,56 @@ function fromLocalWebpack(extensionPath, sourceMappingURLBase) {
return result.pipe(stats_1.createStatsStream(path.basename(extensionPath))); return result.pipe(stats_1.createStatsStream(path.basename(extensionPath)));
} }
function fromLocalNormal(extensionPath) { function fromLocalNormal(extensionPath) {
var result = es.through(); const result = es.through();
vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn }) vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn })
.then(function (fileNames) { .then(fileNames => {
var files = fileNames const files = fileNames
.map(function (fileName) { return path.join(extensionPath, fileName); }) .map(fileName => path.join(extensionPath, fileName))
.map(function (filePath) { return new File({ .map(filePath => new File({
path: filePath, path: filePath,
stat: fs.statSync(filePath), stat: fs.statSync(filePath),
base: extensionPath, base: extensionPath,
contents: fs.createReadStream(filePath) contents: fs.createReadStream(filePath)
}); }); }));
es.readArray(files).pipe(result); es.readArray(files).pipe(result);
}) })
.catch(function (err) { return result.emit('error', err); }); .catch(err => result.emit('error', err));
return result.pipe(stats_1.createStatsStream(path.basename(extensionPath))); return result.pipe(stats_1.createStatsStream(path.basename(extensionPath)));
} }
var baseHeaders = { const baseHeaders = {
'X-Market-Client-Id': 'VSCode Build', 'X-Market-Client-Id': 'VSCode Build',
'User-Agent': 'VSCode Build', 'User-Agent': 'VSCode Build',
'X-Market-User-Id': '291C1CD0-051A-4123-9B4B-30D60EF52EE2', 'X-Market-User-Id': '291C1CD0-051A-4123-9B4B-30D60EF52EE2',
}; };
function fromMarketplace(extensionName, version, metadata) { function fromMarketplace(extensionName, version, metadata) {
var _a = extensionName.split('.'), publisher = _a[0], name = _a[1]; const [publisher, name] = extensionName.split('.');
var url = "https://marketplace.visualstudio.com/_apis/public/gallery/publishers/" + publisher + "/vsextensions/" + name + "/" + version + "/vspackage"; const url = `https://marketplace.visualstudio.com/_apis/public/gallery/publishers/${publisher}/vsextensions/${name}/${version}/vspackage`;
util.log('Downloading extension:', util.colors.yellow(extensionName + "@" + version), '...'); util.log('Downloading extension:', util.colors.yellow(`${extensionName}@${version}`), '...');
var options = { const options = {
base: url, base: url,
requestOptions: { requestOptions: {
gzip: true, gzip: true,
headers: baseHeaders headers: baseHeaders
} }
}; };
var packageJsonFilter = filter('package.json', { restore: true }); const packageJsonFilter = filter('package.json', { restore: true });
return remote('', options) return remote('', options)
.pipe(vzip.src()) .pipe(vzip.src())
.pipe(filter('extension/**')) .pipe(filter('extension/**'))
.pipe(rename(function (p) { return p.dirname = p.dirname.replace(/^extension\/?/, ''); })) .pipe(rename(p => p.dirname = p.dirname.replace(/^extension\/?/, '')))
.pipe(packageJsonFilter) .pipe(packageJsonFilter)
.pipe(buffer()) .pipe(buffer())
.pipe(json({ __metadata: metadata })) .pipe(json({ __metadata: metadata }))
.pipe(packageJsonFilter.restore); .pipe(packageJsonFilter.restore);
} }
exports.fromMarketplace = fromMarketplace; exports.fromMarketplace = fromMarketplace;
var excludedExtensions = [ const excludedExtensions = [
'vscode-api-tests', 'vscode-api-tests',
'vscode-colorize-tests', 'vscode-colorize-tests',
'ms-vscode.node-debug', 'ms-vscode.node-debug',
'ms-vscode.node-debug2', 'ms-vscode.node-debug2',
]; ];
var builtInExtensions = require('../builtInExtensions.json'); const builtInExtensions = require('../builtInExtensions.json');
/** /**
* We're doing way too much stuff at once, with webpack et al. So much stuff * We're doing way too much stuff at once, with webpack et al. So much stuff
* that while downloading extensions from the marketplace, node js doesn't get enough * that while downloading extensions from the marketplace, node js doesn't get enough
@ -191,13 +186,13 @@ var builtInExtensions = require('../builtInExtensions.json');
* marketplace server cuts off the http request. So, we sequentialize the extensino tasks. * marketplace server cuts off the http request. So, we sequentialize the extensino tasks.
*/ */
function sequence(streamProviders) { function sequence(streamProviders) {
var result = es.through(); const result = es.through();
function pop() { function pop() {
if (streamProviders.length === 0) { if (streamProviders.length === 0) {
result.emit('end'); result.emit('end');
} }
else { else {
var fn = streamProviders.shift(); const fn = streamProviders.shift();
fn() fn()
.on('end', function () { setTimeout(pop, 0); }) .on('end', function () { setTimeout(pop, 0); })
.pipe(result, { end: false }); .pipe(result, { end: false });
@ -207,39 +202,27 @@ function sequence(streamProviders) {
return result; return result;
} }
function packageExtensionsStream(optsIn) { function packageExtensionsStream(optsIn) {
var opts = optsIn || {}; const opts = optsIn || {};
var localExtensionDescriptions = glob.sync('extensions/*/package.json') const localExtensionDescriptions = glob.sync('extensions/*/package.json')
.map(function (manifestPath) { .map(manifestPath => {
var extensionPath = path.dirname(path.join(root, manifestPath)); const extensionPath = path.dirname(path.join(root, manifestPath));
var extensionName = path.basename(extensionPath); const extensionName = path.basename(extensionPath);
return { name: extensionName, path: extensionPath }; return { name: extensionName, path: extensionPath };
}) })
.filter(function (_a) { .filter(({ name }) => excludedExtensions.indexOf(name) === -1)
var name = _a.name; .filter(({ name }) => opts.desiredExtensions ? opts.desiredExtensions.indexOf(name) >= 0 : true)
return excludedExtensions.indexOf(name) === -1; .filter(({ name }) => builtInExtensions.every(b => b.name !== name));
}) const localExtensions = () => es.merge(...localExtensionDescriptions.map(extension => {
.filter(function (_a) {
var name = _a.name;
return opts.desiredExtensions ? opts.desiredExtensions.indexOf(name) >= 0 : true;
})
.filter(function (_a) {
var name = _a.name;
return builtInExtensions.every(function (b) { return b.name !== name; });
});
var localExtensions = function () { return es.merge.apply(es, localExtensionDescriptions.map(function (extension) {
return fromLocal(extension.path, opts.sourceMappingURLBase) return fromLocal(extension.path, opts.sourceMappingURLBase)
.pipe(rename(function (p) { return p.dirname = "extensions/" + extension.name + "/" + p.dirname; })); .pipe(rename(p => p.dirname = `extensions/${extension.name}/${p.dirname}`));
})); }; }));
var localExtensionDependencies = function () { return gulp.src('extensions/node_modules/**', { base: '.' }); }; const localExtensionDependencies = () => gulp.src('extensions/node_modules/**', { base: '.' });
var marketplaceExtensions = function () { return es.merge.apply(es, builtInExtensions const marketplaceExtensions = () => es.merge(...builtInExtensions
.filter(function (_a) { .filter(({ name }) => opts.desiredExtensions ? opts.desiredExtensions.indexOf(name) >= 0 : true)
var name = _a.name; .map(extension => {
return opts.desiredExtensions ? opts.desiredExtensions.indexOf(name) >= 0 : true;
})
.map(function (extension) {
return fromMarketplace(extension.name, extension.version, extension.metadata) return fromMarketplace(extension.name, extension.version, extension.metadata)
.pipe(rename(function (p) { return p.dirname = "extensions/" + extension.name + "/" + p.dirname; })); .pipe(rename(p => p.dirname = `extensions/${extension.name}/${p.dirname}`));
})); }; }));
return sequence([localExtensions, localExtensionDependencies, marketplaceExtensions]) return sequence([localExtensions, localExtensionDependencies, marketplaceExtensions])
.pipe(util2.setExecutableBit(['**/*.sh'])) .pipe(util2.setExecutableBit(['**/*.sh']))
.pipe(filter(['**', '!**/*.js.map'])); .pipe(filter(['**', '!**/*.js.map']));

View file

@ -4,15 +4,15 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var path = require("path"); const path = require("path");
var fs = require("fs"); const fs = require("fs");
/** /**
* Returns the sha1 commit version of a repository or undefined in case of failure. * Returns the sha1 commit version of a repository or undefined in case of failure.
*/ */
function getVersion(repo) { function getVersion(repo) {
var git = path.join(repo, '.git'); const git = path.join(repo, '.git');
var headPath = path.join(git, 'HEAD'); const headPath = path.join(git, 'HEAD');
var head; let head;
try { try {
head = fs.readFileSync(headPath, 'utf8').trim(); head = fs.readFileSync(headPath, 'utf8').trim();
} }
@ -22,29 +22,29 @@ function getVersion(repo) {
if (/^[0-9a-f]{40}$/i.test(head)) { if (/^[0-9a-f]{40}$/i.test(head)) {
return head; return head;
} }
var refMatch = /^ref: (.*)$/.exec(head); const refMatch = /^ref: (.*)$/.exec(head);
if (!refMatch) { if (!refMatch) {
return void 0; return void 0;
} }
var ref = refMatch[1]; const ref = refMatch[1];
var refPath = path.join(git, ref); const refPath = path.join(git, ref);
try { try {
return fs.readFileSync(refPath, 'utf8').trim(); return fs.readFileSync(refPath, 'utf8').trim();
} }
catch (e) { catch (e) {
// noop // noop
} }
var packedRefsPath = path.join(git, 'packed-refs'); const packedRefsPath = path.join(git, 'packed-refs');
var refsRaw; let refsRaw;
try { try {
refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim(); refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
} }
catch (e) { catch (e) {
return void 0; return void 0;
} }
var refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm; const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
var refsMatch; let refsMatch;
var refs = {}; let refs = {};
while (refsMatch = refsRegex.exec(refsRaw)) { while (refsMatch = refsRegex.exec(refsRaw)) {
refs[refsMatch[2]] = refsMatch[1]; refs[refsMatch[2]] = refsMatch[1];
} }

File diff suppressed because it is too large Load diff

View file

@ -348,7 +348,7 @@ export interface ITask<T> {
interface ILimitedTaskFactory<T> { interface ILimitedTaskFactory<T> {
factory: ITask<Promise<T>>; factory: ITask<Promise<T>>;
c: (value?: T | Thenable<T>) => void; c: (value?: T | Promise<T>) => void;
e: (error?: any) => void; e: (error?: any) => void;
} }

View file

@ -3,13 +3,12 @@
* Copyright (c) Microsoft Corporation. All rights reserved. * Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
var ts = require("typescript"); const ts = require("typescript");
var lazy = require("lazy.js"); const lazy = require("lazy.js");
var event_stream_1 = require("event-stream"); const event_stream_1 = require("event-stream");
var File = require("vinyl"); const File = require("vinyl");
var sm = require("source-map"); const sm = require("source-map");
var assign = require("object-assign"); const path = require("path");
var path = require("path");
var CollectStepResult; var CollectStepResult;
(function (CollectStepResult) { (function (CollectStepResult) {
CollectStepResult[CollectStepResult["Yes"] = 0] = "Yes"; CollectStepResult[CollectStepResult["Yes"] = 0] = "Yes";
@ -18,9 +17,9 @@ var CollectStepResult;
CollectStepResult[CollectStepResult["NoAndRecurse"] = 3] = "NoAndRecurse"; CollectStepResult[CollectStepResult["NoAndRecurse"] = 3] = "NoAndRecurse";
})(CollectStepResult || (CollectStepResult = {})); })(CollectStepResult || (CollectStepResult = {}));
function collect(node, fn) { function collect(node, fn) {
var result = []; const result = [];
function loop(node) { function loop(node) {
var stepResult = fn(node); const stepResult = fn(node);
if (stepResult === CollectStepResult.Yes || stepResult === CollectStepResult.YesAndRecurse) { if (stepResult === CollectStepResult.Yes || stepResult === CollectStepResult.YesAndRecurse) {
result.push(node); result.push(node);
} }
@ -32,43 +31,45 @@ function collect(node, fn) {
return result; return result;
} }
function clone(object) { function clone(object) {
var result = {}; const result = {};
for (var id in object) { for (const id in object) {
result[id] = object[id]; result[id] = object[id];
} }
return result; return result;
} }
function template(lines) { function template(lines) {
var indent = '', wrap = ''; let indent = '', wrap = '';
if (lines.length > 1) { if (lines.length > 1) {
indent = '\t'; indent = '\t';
wrap = '\n'; wrap = '\n';
} }
return "/*---------------------------------------------------------\n * Copyright (C) Microsoft Corporation. All rights reserved.\n *--------------------------------------------------------*/\ndefine([], [" + (wrap + lines.map(function (l) { return indent + l; }).join(',\n') + wrap) + "]);"; return `/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
define([], [${wrap + lines.map(l => indent + l).join(',\n') + wrap}]);`;
} }
/** /**
* Returns a stream containing the patched JavaScript and source maps. * Returns a stream containing the patched JavaScript and source maps.
*/ */
function nls() { function nls() {
var input = event_stream_1.through(); const input = event_stream_1.through();
var output = input.pipe(event_stream_1.through(function (f) { const output = input.pipe(event_stream_1.through(function (f) {
var _this = this;
if (!f.sourceMap) { if (!f.sourceMap) {
return this.emit('error', new Error("File " + f.relative + " does not have sourcemaps.")); return this.emit('error', new Error(`File ${f.relative} does not have sourcemaps.`));
} }
var source = f.sourceMap.sources[0]; let source = f.sourceMap.sources[0];
if (!source) { if (!source) {
return this.emit('error', new Error("File " + f.relative + " does not have a source in the source map.")); return this.emit('error', new Error(`File ${f.relative} does not have a source in the source map.`));
} }
var root = f.sourceMap.sourceRoot; const root = f.sourceMap.sourceRoot;
if (root) { if (root) {
source = path.join(root, source); source = path.join(root, source);
} }
var typescript = f.sourceMap.sourcesContent[0]; const typescript = f.sourceMap.sourcesContent[0];
if (!typescript) { if (!typescript) {
return this.emit('error', new Error("File " + f.relative + " does not have the original content in the source map.")); return this.emit('error', new Error(`File ${f.relative} does not have the original content in the source map.`));
} }
nls.patchFiles(f, typescript).forEach(function (f) { return _this.emit('data', f); }); nls.patchFiles(f, typescript).forEach(f => this.emit('data', f));
})); }));
return event_stream_1.duplex(input, output); return event_stream_1.duplex(input, output);
} }
@ -76,8 +77,7 @@ function isImportNode(node) {
return node.kind === ts.SyntaxKind.ImportDeclaration || node.kind === ts.SyntaxKind.ImportEqualsDeclaration; return node.kind === ts.SyntaxKind.ImportDeclaration || node.kind === ts.SyntaxKind.ImportEqualsDeclaration;
} }
(function (nls_1) { (function (nls_1) {
function fileFrom(file, contents, path) { function fileFrom(file, contents, path = file.path) {
if (path === void 0) { path = file.path; }
return new File({ return new File({
contents: Buffer.from(contents), contents: Buffer.from(contents),
base: file.base, base: file.base,
@ -87,29 +87,27 @@ function isImportNode(node) {
} }
nls_1.fileFrom = fileFrom; nls_1.fileFrom = fileFrom;
function mappedPositionFrom(source, lc) { function mappedPositionFrom(source, lc) {
return { source: source, line: lc.line + 1, column: lc.character }; return { source, line: lc.line + 1, column: lc.character };
} }
nls_1.mappedPositionFrom = mappedPositionFrom; nls_1.mappedPositionFrom = mappedPositionFrom;
function lcFrom(position) { function lcFrom(position) {
return { line: position.line - 1, character: position.column }; return { line: position.line - 1, character: position.column };
} }
nls_1.lcFrom = lcFrom; nls_1.lcFrom = lcFrom;
var SingleFileServiceHost = /** @class */ (function () { class SingleFileServiceHost {
function SingleFileServiceHost(options, filename, contents) { constructor(options, filename, contents) {
var _this = this;
this.options = options; this.options = options;
this.filename = filename; this.filename = filename;
this.getCompilationSettings = function () { return _this.options; }; this.getCompilationSettings = () => this.options;
this.getScriptFileNames = function () { return [_this.filename]; }; this.getScriptFileNames = () => [this.filename];
this.getScriptVersion = function () { return '1'; }; this.getScriptVersion = () => '1';
this.getScriptSnapshot = function (name) { return name === _this.filename ? _this.file : _this.lib; }; this.getScriptSnapshot = (name) => name === this.filename ? this.file : this.lib;
this.getCurrentDirectory = function () { return ''; }; this.getCurrentDirectory = () => '';
this.getDefaultLibFileName = function () { return 'lib.d.ts'; }; this.getDefaultLibFileName = () => 'lib.d.ts';
this.file = ts.ScriptSnapshot.fromString(contents); this.file = ts.ScriptSnapshot.fromString(contents);
this.lib = ts.ScriptSnapshot.fromString(''); this.lib = ts.ScriptSnapshot.fromString('');
} }
return SingleFileServiceHost; }
}());
nls_1.SingleFileServiceHost = SingleFileServiceHost; nls_1.SingleFileServiceHost = SingleFileServiceHost;
function isCallExpressionWithinTextSpanCollectStep(textSpan, node) { function isCallExpressionWithinTextSpanCollectStep(textSpan, node) {
if (!ts.textSpanContainsTextSpan({ start: node.pos, length: node.end - node.pos }, textSpan)) { if (!ts.textSpanContainsTextSpan({ start: node.pos, length: node.end - node.pos }, textSpan)) {
@ -117,97 +115,96 @@ function isImportNode(node) {
} }
return node.kind === ts.SyntaxKind.CallExpression ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse; return node.kind === ts.SyntaxKind.CallExpression ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse;
} }
function analyze(contents, options) { function analyze(contents, options = {}) {
if (options === void 0) { options = {}; } const filename = 'file.ts';
var filename = 'file.ts'; const serviceHost = new SingleFileServiceHost(Object.assign(clone(options), { noResolve: true }), filename, contents);
var serviceHost = new SingleFileServiceHost(assign(clone(options), { noResolve: true }), filename, contents); const service = ts.createLanguageService(serviceHost);
var service = ts.createLanguageService(serviceHost); const sourceFile = ts.createSourceFile(filename, contents, ts.ScriptTarget.ES5, true);
var sourceFile = ts.createSourceFile(filename, contents, ts.ScriptTarget.ES5, true);
// all imports // all imports
var imports = lazy(collect(sourceFile, function (n) { return isImportNode(n) ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse; })); const imports = lazy(collect(sourceFile, n => isImportNode(n) ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse));
// import nls = require('vs/nls'); // import nls = require('vs/nls');
var importEqualsDeclarations = imports const importEqualsDeclarations = imports
.filter(function (n) { return n.kind === ts.SyntaxKind.ImportEqualsDeclaration; }) .filter(n => n.kind === ts.SyntaxKind.ImportEqualsDeclaration)
.map(function (n) { return n; }) .map(n => n)
.filter(function (d) { return d.moduleReference.kind === ts.SyntaxKind.ExternalModuleReference; }) .filter(d => d.moduleReference.kind === ts.SyntaxKind.ExternalModuleReference)
.filter(function (d) { return d.moduleReference.expression.getText() === '\'vs/nls\''; }); .filter(d => d.moduleReference.expression.getText() === '\'vs/nls\'');
// import ... from 'vs/nls'; // import ... from 'vs/nls';
var importDeclarations = imports const importDeclarations = imports
.filter(function (n) { return n.kind === ts.SyntaxKind.ImportDeclaration; }) .filter(n => n.kind === ts.SyntaxKind.ImportDeclaration)
.map(function (n) { return n; }) .map(n => n)
.filter(function (d) { return d.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral; }) .filter(d => d.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral)
.filter(function (d) { return d.moduleSpecifier.getText() === '\'vs/nls\''; }) .filter(d => d.moduleSpecifier.getText() === '\'vs/nls\'')
.filter(function (d) { return !!d.importClause && !!d.importClause.namedBindings; }); .filter(d => !!d.importClause && !!d.importClause.namedBindings);
var nlsExpressions = importEqualsDeclarations const nlsExpressions = importEqualsDeclarations
.map(function (d) { return d.moduleReference.expression; }) .map(d => d.moduleReference.expression)
.concat(importDeclarations.map(function (d) { return d.moduleSpecifier; })) .concat(importDeclarations.map(d => d.moduleSpecifier))
.map(function (d) { return ({ .map(d => ({
start: ts.getLineAndCharacterOfPosition(sourceFile, d.getStart()), start: ts.getLineAndCharacterOfPosition(sourceFile, d.getStart()),
end: ts.getLineAndCharacterOfPosition(sourceFile, d.getEnd()) end: ts.getLineAndCharacterOfPosition(sourceFile, d.getEnd())
}); }); }));
// `nls.localize(...)` calls // `nls.localize(...)` calls
var nlsLocalizeCallExpressions = importDeclarations const nlsLocalizeCallExpressions = importDeclarations
.filter(function (d) { return !!(d.importClause && d.importClause.namedBindings && d.importClause.namedBindings.kind === ts.SyntaxKind.NamespaceImport); }) .filter(d => !!(d.importClause && d.importClause.namedBindings && d.importClause.namedBindings.kind === ts.SyntaxKind.NamespaceImport))
.map(function (d) { return d.importClause.namedBindings.name; }) .map(d => d.importClause.namedBindings.name)
.concat(importEqualsDeclarations.map(function (d) { return d.name; })) .concat(importEqualsDeclarations.map(d => d.name))
// find read-only references to `nls` // find read-only references to `nls`
.map(function (n) { return service.getReferencesAtPosition(filename, n.pos + 1); }) .map(n => service.getReferencesAtPosition(filename, n.pos + 1))
.flatten() .flatten()
.filter(function (r) { return !r.isWriteAccess; }) .filter(r => !r.isWriteAccess)
// find the deepest call expressions AST nodes that contain those references // find the deepest call expressions AST nodes that contain those references
.map(function (r) { return collect(sourceFile, function (n) { return isCallExpressionWithinTextSpanCollectStep(r.textSpan, n); }); }) .map(r => collect(sourceFile, n => isCallExpressionWithinTextSpanCollectStep(r.textSpan, n)))
.map(function (a) { return lazy(a).last(); }) .map(a => lazy(a).last())
.filter(function (n) { return !!n; }) .filter(n => !!n)
.map(function (n) { return n; }) .map(n => n)
// only `localize` calls // only `localize` calls
.filter(function (n) { return n.expression.kind === ts.SyntaxKind.PropertyAccessExpression && n.expression.name.getText() === 'localize'; }); .filter(n => n.expression.kind === ts.SyntaxKind.PropertyAccessExpression && n.expression.name.getText() === 'localize');
// `localize` named imports // `localize` named imports
var allLocalizeImportDeclarations = importDeclarations const allLocalizeImportDeclarations = importDeclarations
.filter(function (d) { return !!(d.importClause && d.importClause.namedBindings && d.importClause.namedBindings.kind === ts.SyntaxKind.NamedImports); }) .filter(d => !!(d.importClause && d.importClause.namedBindings && d.importClause.namedBindings.kind === ts.SyntaxKind.NamedImports))
.map(function (d) { return [].concat(d.importClause.namedBindings.elements); }) .map(d => [].concat(d.importClause.namedBindings.elements))
.flatten(); .flatten();
// `localize` read-only references // `localize` read-only references
var localizeReferences = allLocalizeImportDeclarations const localizeReferences = allLocalizeImportDeclarations
.filter(function (d) { return d.name.getText() === 'localize'; }) .filter(d => d.name.getText() === 'localize')
.map(function (n) { return service.getReferencesAtPosition(filename, n.pos + 1); }) .map(n => service.getReferencesAtPosition(filename, n.pos + 1))
.flatten() .flatten()
.filter(function (r) { return !r.isWriteAccess; }); .filter(r => !r.isWriteAccess);
// custom named `localize` read-only references // custom named `localize` read-only references
var namedLocalizeReferences = allLocalizeImportDeclarations const namedLocalizeReferences = allLocalizeImportDeclarations
.filter(function (d) { return d.propertyName && d.propertyName.getText() === 'localize'; }) .filter(d => d.propertyName && d.propertyName.getText() === 'localize')
.map(function (n) { return service.getReferencesAtPosition(filename, n.name.pos + 1); }) .map(n => service.getReferencesAtPosition(filename, n.name.pos + 1))
.flatten() .flatten()
.filter(function (r) { return !r.isWriteAccess; }); .filter(r => !r.isWriteAccess);
// find the deepest call expressions AST nodes that contain those references // find the deepest call expressions AST nodes that contain those references
var localizeCallExpressions = localizeReferences const localizeCallExpressions = localizeReferences
.concat(namedLocalizeReferences) .concat(namedLocalizeReferences)
.map(function (r) { return collect(sourceFile, function (n) { return isCallExpressionWithinTextSpanCollectStep(r.textSpan, n); }); }) .map(r => collect(sourceFile, n => isCallExpressionWithinTextSpanCollectStep(r.textSpan, n)))
.map(function (a) { return lazy(a).last(); }) .map(a => lazy(a).last())
.filter(function (n) { return !!n; }) .filter(n => !!n)
.map(function (n) { return n; }); .map(n => n);
// collect everything // collect everything
var localizeCalls = nlsLocalizeCallExpressions const localizeCalls = nlsLocalizeCallExpressions
.concat(localizeCallExpressions) .concat(localizeCallExpressions)
.map(function (e) { return e.arguments; }) .map(e => e.arguments)
.filter(function (a) { return a.length > 1; }) .filter(a => a.length > 1)
.sort(function (a, b) { return a[0].getStart() - b[0].getStart(); }) .sort((a, b) => a[0].getStart() - b[0].getStart())
.map(function (a) { return ({ .map(a => ({
keySpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getEnd()) }, keySpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getEnd()) },
key: a[0].getText(), key: a[0].getText(),
valueSpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getEnd()) }, valueSpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getEnd()) },
value: a[1].getText() value: a[1].getText()
}); }); }));
return { return {
localizeCalls: localizeCalls.toArray(), localizeCalls: localizeCalls.toArray(),
nlsExpressions: nlsExpressions.toArray() nlsExpressions: nlsExpressions.toArray()
}; };
} }
nls_1.analyze = analyze; nls_1.analyze = analyze;
var TextModel = /** @class */ (function () { class TextModel {
function TextModel(contents) { constructor(contents) {
var regex = /\r\n|\r|\n/g; const regex = /\r\n|\r|\n/g;
var index = 0; let index = 0;
var match; let match;
this.lines = []; this.lines = [];
this.lineEndings = []; this.lineEndings = [];
while (match = regex.exec(contents)) { while (match = regex.exec(contents)) {
@ -220,85 +217,80 @@ function isImportNode(node) {
this.lineEndings.push(''); this.lineEndings.push('');
} }
} }
TextModel.prototype.get = function (index) { get(index) {
return this.lines[index]; return this.lines[index];
}; }
TextModel.prototype.set = function (index, line) { set(index, line) {
this.lines[index] = line; this.lines[index] = line;
}; }
Object.defineProperty(TextModel.prototype, "lineCount", { get lineCount() {
get: function () { return this.lines.length;
return this.lines.length; }
},
enumerable: true,
configurable: true
});
/** /**
* Applies patch(es) to the model. * Applies patch(es) to the model.
* Multiple patches must be ordered. * Multiple patches must be ordered.
* Does not support patches spanning multiple lines. * Does not support patches spanning multiple lines.
*/ */
TextModel.prototype.apply = function (patch) { apply(patch) {
var startLineNumber = patch.span.start.line; const startLineNumber = patch.span.start.line;
var endLineNumber = patch.span.end.line; const endLineNumber = patch.span.end.line;
var startLine = this.lines[startLineNumber] || ''; const startLine = this.lines[startLineNumber] || '';
var endLine = this.lines[endLineNumber] || ''; const endLine = this.lines[endLineNumber] || '';
this.lines[startLineNumber] = [ this.lines[startLineNumber] = [
startLine.substring(0, patch.span.start.character), startLine.substring(0, patch.span.start.character),
patch.content, patch.content,
endLine.substring(patch.span.end.character) endLine.substring(patch.span.end.character)
].join(''); ].join('');
for (var i = startLineNumber + 1; i <= endLineNumber; i++) { for (let i = startLineNumber + 1; i <= endLineNumber; i++) {
this.lines[i] = ''; this.lines[i] = '';
} }
}; }
TextModel.prototype.toString = function () { toString() {
return lazy(this.lines).zip(this.lineEndings) return lazy(this.lines).zip(this.lineEndings)
.flatten().toArray().join(''); .flatten().toArray().join('');
}; }
return TextModel; }
}());
nls_1.TextModel = TextModel; nls_1.TextModel = TextModel;
function patchJavascript(patches, contents, moduleId) { function patchJavascript(patches, contents, moduleId) {
var model = new nls.TextModel(contents); const model = new nls.TextModel(contents);
// patch the localize calls // patch the localize calls
lazy(patches).reverse().each(function (p) { return model.apply(p); }); lazy(patches).reverse().each(p => model.apply(p));
// patch the 'vs/nls' imports // patch the 'vs/nls' imports
var firstLine = model.get(0); const firstLine = model.get(0);
var patchedFirstLine = firstLine.replace(/(['"])vs\/nls\1/g, "$1vs/nls!" + moduleId + "$1"); const patchedFirstLine = firstLine.replace(/(['"])vs\/nls\1/g, `$1vs/nls!${moduleId}$1`);
model.set(0, patchedFirstLine); model.set(0, patchedFirstLine);
return model.toString(); return model.toString();
} }
nls_1.patchJavascript = patchJavascript; nls_1.patchJavascript = patchJavascript;
function patchSourcemap(patches, rsm, smc) { function patchSourcemap(patches, rsm, smc) {
var smg = new sm.SourceMapGenerator({ const smg = new sm.SourceMapGenerator({
file: rsm.file, file: rsm.file,
sourceRoot: rsm.sourceRoot sourceRoot: rsm.sourceRoot
}); });
patches = patches.reverse(); patches = patches.reverse();
var currentLine = -1; let currentLine = -1;
var currentLineDiff = 0; let currentLineDiff = 0;
var source = null; let source = null;
smc.eachMapping(function (m) { smc.eachMapping(m => {
var patch = patches[patches.length - 1]; const patch = patches[patches.length - 1];
var original = { line: m.originalLine, column: m.originalColumn }; const original = { line: m.originalLine, column: m.originalColumn };
var generated = { line: m.generatedLine, column: m.generatedColumn }; const generated = { line: m.generatedLine, column: m.generatedColumn };
if (currentLine !== generated.line) { if (currentLine !== generated.line) {
currentLineDiff = 0; currentLineDiff = 0;
} }
currentLine = generated.line; currentLine = generated.line;
generated.column += currentLineDiff; generated.column += currentLineDiff;
if (patch && m.generatedLine - 1 === patch.span.end.line && m.generatedColumn === patch.span.end.character) { if (patch && m.generatedLine - 1 === patch.span.end.line && m.generatedColumn === patch.span.end.character) {
var originalLength = patch.span.end.character - patch.span.start.character; const originalLength = patch.span.end.character - patch.span.start.character;
var modifiedLength = patch.content.length; const modifiedLength = patch.content.length;
var lengthDiff = modifiedLength - originalLength; const lengthDiff = modifiedLength - originalLength;
currentLineDiff += lengthDiff; currentLineDiff += lengthDiff;
generated.column += lengthDiff; generated.column += lengthDiff;
patches.pop(); patches.pop();
} }
source = rsm.sourceRoot ? path.relative(rsm.sourceRoot, m.source) : m.source; source = rsm.sourceRoot ? path.relative(rsm.sourceRoot, m.source) : m.source;
source = source.replace(/\\/g, '/'); source = source.replace(/\\/g, '/');
smg.addMapping({ source: source, name: m.name, original: original, generated: generated }); smg.addMapping({ source, name: m.name, original, generated });
}, null, sm.SourceMapConsumer.GENERATED_ORDER); }, null, sm.SourceMapConsumer.GENERATED_ORDER);
if (source) { if (source) {
smg.setSourceContent(source, smc.sourceContentFor(source)); smg.setSourceContent(source, smc.sourceContentFor(source));
@ -307,47 +299,47 @@ function isImportNode(node) {
} }
nls_1.patchSourcemap = patchSourcemap; nls_1.patchSourcemap = patchSourcemap;
function patch(moduleId, typescript, javascript, sourcemap) { function patch(moduleId, typescript, javascript, sourcemap) {
var _a = analyze(typescript), localizeCalls = _a.localizeCalls, nlsExpressions = _a.nlsExpressions; const { localizeCalls, nlsExpressions } = analyze(typescript);
if (localizeCalls.length === 0) { if (localizeCalls.length === 0) {
return { javascript: javascript, sourcemap: sourcemap }; return { javascript, sourcemap };
} }
var nlsKeys = template(localizeCalls.map(function (lc) { return lc.key; })); const nlsKeys = template(localizeCalls.map(lc => lc.key));
var nls = template(localizeCalls.map(function (lc) { return lc.value; })); const nls = template(localizeCalls.map(lc => lc.value));
var smc = new sm.SourceMapConsumer(sourcemap); const smc = new sm.SourceMapConsumer(sourcemap);
var positionFrom = mappedPositionFrom.bind(null, sourcemap.sources[0]); const positionFrom = mappedPositionFrom.bind(null, sourcemap.sources[0]);
var i = 0; let i = 0;
// build patches // build patches
var patches = lazy(localizeCalls) const patches = lazy(localizeCalls)
.map(function (lc) { return ([ .map(lc => ([
{ range: lc.keySpan, content: '' + (i++) }, { range: lc.keySpan, content: '' + (i++) },
{ range: lc.valueSpan, content: 'null' } { range: lc.valueSpan, content: 'null' }
]); }) ]))
.flatten() .flatten()
.map(function (c) { .map(c => {
var start = lcFrom(smc.generatedPositionFor(positionFrom(c.range.start))); const start = lcFrom(smc.generatedPositionFor(positionFrom(c.range.start)));
var end = lcFrom(smc.generatedPositionFor(positionFrom(c.range.end))); const end = lcFrom(smc.generatedPositionFor(positionFrom(c.range.end)));
return { span: { start: start, end: end }, content: c.content }; return { span: { start, end }, content: c.content };
}) })
.toArray(); .toArray();
javascript = patchJavascript(patches, javascript, moduleId); javascript = patchJavascript(patches, javascript, moduleId);
// since imports are not within the sourcemap information, // since imports are not within the sourcemap information,
// we must do this MacGyver style // we must do this MacGyver style
if (nlsExpressions.length) { if (nlsExpressions.length) {
javascript = javascript.replace(/^define\(.*$/m, function (line) { javascript = javascript.replace(/^define\(.*$/m, line => {
return line.replace(/(['"])vs\/nls\1/g, "$1vs/nls!" + moduleId + "$1"); return line.replace(/(['"])vs\/nls\1/g, `$1vs/nls!${moduleId}$1`);
}); });
} }
sourcemap = patchSourcemap(patches, sourcemap, smc); sourcemap = patchSourcemap(patches, sourcemap, smc);
return { javascript: javascript, sourcemap: sourcemap, nlsKeys: nlsKeys, nls: nls }; return { javascript, sourcemap, nlsKeys, nls };
} }
nls_1.patch = patch; nls_1.patch = patch;
function patchFiles(javascriptFile, typescript) { function patchFiles(javascriptFile, typescript) {
// hack? // hack?
var moduleId = javascriptFile.relative const moduleId = javascriptFile.relative
.replace(/\.js$/, '') .replace(/\.js$/, '')
.replace(/\\/g, '/'); .replace(/\\/g, '/');
var _a = patch(moduleId, typescript, javascriptFile.contents.toString(), javascriptFile.sourceMap), javascript = _a.javascript, sourcemap = _a.sourcemap, nlsKeys = _a.nlsKeys, nls = _a.nls; const { javascript, sourcemap, nlsKeys, nls } = patch(moduleId, typescript, javascriptFile.contents.toString(), javascriptFile.sourceMap);
var result = [fileFrom(javascriptFile, javascript)]; const result = [fileFrom(javascriptFile, javascript)];
result[0].sourceMap = sourcemap; result[0].sourceMap = sourcemap;
if (nlsKeys) { if (nlsKeys) {
result.push(fileFrom(javascriptFile, nlsKeys, javascriptFile.path.replace(/\.js$/, '.nls.keys.js'))); result.push(fileFrom(javascriptFile, nlsKeys, javascriptFile.path.replace(/\.js$/, '.nls.keys.js')));

View file

@ -8,7 +8,6 @@ import * as lazy from 'lazy.js';
import { duplex, through } from 'event-stream'; import { duplex, through } from 'event-stream';
import * as File from 'vinyl'; import * as File from 'vinyl';
import * as sm from 'source-map'; import * as sm from 'source-map';
import assign = require('object-assign');
import * as path from 'path'; import * as path from 'path';
declare class FileSourceMap extends File { declare class FileSourceMap extends File {
@ -174,7 +173,7 @@ module nls {
export function analyze(contents: string, options: ts.CompilerOptions = {}): ILocalizeAnalysisResult { export function analyze(contents: string, options: ts.CompilerOptions = {}): ILocalizeAnalysisResult {
const filename = 'file.ts'; const filename = 'file.ts';
const serviceHost = new SingleFileServiceHost(assign(clone(options), { noResolve: true }), filename, contents); const serviceHost = new SingleFileServiceHost(Object.assign(clone(options), { noResolve: true }), filename, contents);
const service = ts.createLanguageService(serviceHost); const service = ts.createLanguageService(serviceHost);
const sourceFile = ts.createSourceFile(filename, contents, ts.ScriptTarget.ES5, true); const sourceFile = ts.createSourceFile(filename, contents, ts.ScriptTarget.ES5, true);

View file

@ -4,30 +4,30 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var es = require("event-stream"); const es = require("event-stream");
var gulp = require("gulp"); const gulp = require("gulp");
var concat = require("gulp-concat"); const concat = require("gulp-concat");
var minifyCSS = require("gulp-cssnano"); const minifyCSS = require("gulp-cssnano");
var filter = require("gulp-filter"); const filter = require("gulp-filter");
var flatmap = require("gulp-flatmap"); const flatmap = require("gulp-flatmap");
var sourcemaps = require("gulp-sourcemaps"); const sourcemaps = require("gulp-sourcemaps");
var uglify = require("gulp-uglify"); const uglify = require("gulp-uglify");
var composer = require("gulp-uglify/composer"); const composer = require("gulp-uglify/composer");
var gulpUtil = require("gulp-util"); const gulpUtil = require("gulp-util");
var path = require("path"); const path = require("path");
var pump = require("pump"); const pump = require("pump");
var uglifyes = require("uglify-es"); const uglifyes = require("uglify-es");
var VinylFile = require("vinyl"); const VinylFile = require("vinyl");
var bundle = require("./bundle"); const bundle = require("./bundle");
var i18n_1 = require("./i18n"); const i18n_1 = require("./i18n");
var stats_1 = require("./stats"); const stats_1 = require("./stats");
var util = require("./util"); const util = require("./util");
var REPO_ROOT_PATH = path.join(__dirname, '../..'); const REPO_ROOT_PATH = path.join(__dirname, '../..');
function log(prefix, message) { function log(prefix, message) {
gulpUtil.log(gulpUtil.colors.cyan('[' + prefix + ']'), message); gulpUtil.log(gulpUtil.colors.cyan('[' + prefix + ']'), message);
} }
function loaderConfig(emptyPaths) { function loaderConfig(emptyPaths) {
var result = { const result = {
paths: { paths: {
'vs': 'out-build/vs', 'vs': 'out-build/vs',
'vscode': 'empty:' 'vscode': 'empty:'
@ -38,20 +38,20 @@ function loaderConfig(emptyPaths) {
return result; return result;
} }
exports.loaderConfig = loaderConfig; exports.loaderConfig = loaderConfig;
var IS_OUR_COPYRIGHT_REGEXP = /Copyright \(C\) Microsoft Corporation/i; const IS_OUR_COPYRIGHT_REGEXP = /Copyright \(C\) Microsoft Corporation/i;
function loader(src, bundledFileHeader, bundleLoader) { function loader(src, bundledFileHeader, bundleLoader) {
var sources = [ let sources = [
src + "/vs/loader.js" `${src}/vs/loader.js`
]; ];
if (bundleLoader) { if (bundleLoader) {
sources = sources.concat([ sources = sources.concat([
src + "/vs/css.js", `${src}/vs/css.js`,
src + "/vs/nls.js" `${src}/vs/nls.js`
]); ]);
} }
var isFirst = true; let isFirst = true;
return (gulp return (gulp
.src(sources, { base: "" + src }) .src(sources, { base: `${src}` })
.pipe(es.through(function (data) { .pipe(es.through(function (data) {
if (isFirst) { if (isFirst) {
isFirst = false; isFirst = false;
@ -74,12 +74,12 @@ function loader(src, bundledFileHeader, bundleLoader) {
}))); })));
} }
function toConcatStream(src, bundledFileHeader, sources, dest) { function toConcatStream(src, bundledFileHeader, sources, dest) {
var useSourcemaps = /\.js$/.test(dest) && !/\.nls\.js$/.test(dest); const useSourcemaps = /\.js$/.test(dest) && !/\.nls\.js$/.test(dest);
// If a bundle ends up including in any of the sources our copyright, then // 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 // insert a fake source at the beginning of each bundle with our copyright
var containsOurCopyright = false; let containsOurCopyright = false;
for (var i = 0, len = sources.length; i < len; i++) { for (let i = 0, len = sources.length; i < len; i++) {
var fileContents = sources[i].contents; const fileContents = sources[i].contents;
if (IS_OUR_COPYRIGHT_REGEXP.test(fileContents)) { if (IS_OUR_COPYRIGHT_REGEXP.test(fileContents)) {
containsOurCopyright = true; containsOurCopyright = true;
break; break;
@ -91,9 +91,9 @@ function toConcatStream(src, bundledFileHeader, sources, dest) {
contents: bundledFileHeader contents: bundledFileHeader
}); });
} }
var treatedSources = sources.map(function (source) { const treatedSources = sources.map(function (source) {
var root = source.path ? REPO_ROOT_PATH.replace(/\\/g, '/') : ''; const root = source.path ? REPO_ROOT_PATH.replace(/\\/g, '/') : '';
var base = source.path ? root + ("/" + src) : ''; const base = source.path ? root + `/${src}` : '';
return new VinylFile({ return new VinylFile({
path: source.path ? root + '/' + source.path.replace(/\\/g, '/') : 'fake', path: source.path ? root + '/' + source.path.replace(/\\/g, '/') : 'fake',
base: base, base: base,
@ -111,33 +111,33 @@ function toBundleStream(src, bundledFileHeader, bundles) {
})); }));
} }
function optimizeTask(opts) { function optimizeTask(opts) {
var src = opts.src; const src = opts.src;
var entryPoints = opts.entryPoints; const entryPoints = opts.entryPoints;
var otherSources = opts.otherSources; const otherSources = opts.otherSources;
var resources = opts.resources; const resources = opts.resources;
var loaderConfig = opts.loaderConfig; const loaderConfig = opts.loaderConfig;
var bundledFileHeader = opts.header; const bundledFileHeader = opts.header;
var bundleLoader = (typeof opts.bundleLoader === 'undefined' ? true : opts.bundleLoader); const bundleLoader = (typeof opts.bundleLoader === 'undefined' ? true : opts.bundleLoader);
var out = opts.out; const out = opts.out;
return function () { return function () {
var bundlesStream = es.through(); // this stream will contain the bundled files const bundlesStream = es.through(); // this stream will contain the bundled files
var resourcesStream = es.through(); // this stream will contain the resources const resourcesStream = es.through(); // this stream will contain the resources
var bundleInfoStream = es.through(); // this stream will contain bundleInfo.json const bundleInfoStream = es.through(); // this stream will contain bundleInfo.json
bundle.bundle(entryPoints, loaderConfig, function (err, result) { bundle.bundle(entryPoints, loaderConfig, function (err, result) {
if (err || !result) { if (err || !result) {
return bundlesStream.emit('error', JSON.stringify(err)); return bundlesStream.emit('error', JSON.stringify(err));
} }
toBundleStream(src, bundledFileHeader, result.files).pipe(bundlesStream); toBundleStream(src, bundledFileHeader, result.files).pipe(bundlesStream);
// Remove css inlined resources // Remove css inlined resources
var filteredResources = resources.slice(); const filteredResources = resources.slice();
result.cssInlinedResources.forEach(function (resource) { result.cssInlinedResources.forEach(function (resource) {
if (process.env['VSCODE_BUILD_VERBOSE']) { if (process.env['VSCODE_BUILD_VERBOSE']) {
log('optimizer', 'excluding inlined: ' + resource); log('optimizer', 'excluding inlined: ' + resource);
} }
filteredResources.push('!' + resource); filteredResources.push('!' + resource);
}); });
gulp.src(filteredResources, { base: "" + src }).pipe(resourcesStream); gulp.src(filteredResources, { base: `${src}` }).pipe(resourcesStream);
var bundleInfoArray = []; const bundleInfoArray = [];
if (opts.bundleInfo) { if (opts.bundleInfo) {
bundleInfoArray.push(new VinylFile({ bundleInfoArray.push(new VinylFile({
path: 'bundleInfo.json', path: 'bundleInfo.json',
@ -147,9 +147,9 @@ function optimizeTask(opts) {
} }
es.readArray(bundleInfoArray).pipe(bundleInfoStream); es.readArray(bundleInfoArray).pipe(bundleInfoStream);
}); });
var otherSourcesStream = es.through(); const otherSourcesStream = es.through();
var otherSourcesStreamArr = []; const otherSourcesStreamArr = [];
gulp.src(otherSources, { base: "" + src }) gulp.src(otherSources, { base: `${src}` })
.pipe(es.through(function (data) { .pipe(es.through(function (data) {
otherSourcesStreamArr.push(toConcatStream(src, bundledFileHeader, [data], data.relative)); otherSourcesStreamArr.push(toConcatStream(src, bundledFileHeader, [data], data.relative));
}, function () { }, function () {
@ -160,7 +160,7 @@ function optimizeTask(opts) {
es.merge(otherSourcesStreamArr).pipe(otherSourcesStream); es.merge(otherSourcesStreamArr).pipe(otherSourcesStream);
} }
})); }));
var result = es.merge(loader(src, bundledFileHeader, bundleLoader), bundlesStream, otherSourcesStream, resourcesStream, bundleInfoStream); const result = es.merge(loader(src, bundledFileHeader, bundleLoader), bundlesStream, otherSourcesStream, resourcesStream, bundleInfoStream);
return result return result
.pipe(sourcemaps.write('./', { .pipe(sourcemaps.write('./', {
sourceRoot: undefined, sourceRoot: undefined,
@ -180,14 +180,14 @@ exports.optimizeTask = optimizeTask;
* to have a file "context" to include our copyright only once per file. * to have a file "context" to include our copyright only once per file.
*/ */
function uglifyWithCopyrights() { function uglifyWithCopyrights() {
var preserveComments = function (f) { const preserveComments = (f) => {
return function (_node, comment) { return (_node, comment) => {
var text = comment.value; const text = comment.value;
var type = comment.type; const type = comment.type;
if (/@minifier_do_not_preserve/.test(text)) { if (/@minifier_do_not_preserve/.test(text)) {
return false; return false;
} }
var isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text); const isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
if (isOurCopyright) { if (isOurCopyright) {
if (f.__hasOurCopyright) { if (f.__hasOurCopyright) {
return false; return false;
@ -205,10 +205,10 @@ function uglifyWithCopyrights() {
return false; return false;
}; };
}; };
var minify = composer(uglifyes); const minify = composer(uglifyes);
var input = es.through(); const input = es.through();
var output = input const output = input
.pipe(flatmap(function (stream, f) { .pipe(flatmap((stream, f) => {
return stream.pipe(minify({ return stream.pipe(minify({
output: { output: {
comments: preserveComments(f), comments: preserveComments(f),
@ -219,18 +219,18 @@ function uglifyWithCopyrights() {
return es.duplex(input, output); return es.duplex(input, output);
} }
function minifyTask(src, sourceMapBaseUrl) { function minifyTask(src, sourceMapBaseUrl) {
var sourceMappingURL = sourceMapBaseUrl ? (function (f) { return sourceMapBaseUrl + "/" + f.relative + ".map"; }) : undefined; const sourceMappingURL = sourceMapBaseUrl ? ((f) => `${sourceMapBaseUrl}/${f.relative}.map`) : undefined;
return function (cb) { return cb => {
var jsFilter = filter('**/*.js', { restore: true }); const jsFilter = filter('**/*.js', { restore: true });
var cssFilter = filter('**/*.css', { restore: true }); const cssFilter = filter('**/*.css', { restore: true });
pump(gulp.src([src + '/**', '!' + src + '/**/*.map']), jsFilter, sourcemaps.init({ loadMaps: true }), uglifyWithCopyrights(), jsFilter.restore, cssFilter, minifyCSS({ reduceIdents: false }), cssFilter.restore, sourcemaps.write('./', { pump(gulp.src([src + '/**', '!' + src + '/**/*.map']), jsFilter, sourcemaps.init({ loadMaps: true }), uglifyWithCopyrights(), jsFilter.restore, cssFilter, minifyCSS({ reduceIdents: false }), cssFilter.restore, sourcemaps.write('./', {
sourceMappingURL: sourceMappingURL, sourceMappingURL,
sourceRoot: undefined, sourceRoot: undefined,
includeContent: true, includeContent: true,
addComment: true addComment: true
}), gulp.dest(src + '-min'), function (err) { }), gulp.dest(src + '-min'), (err) => {
if (err instanceof uglify.GulpUglifyError) { if (err instanceof uglify.GulpUglifyError) {
console.error("Uglify error in '" + (err.cause && err.cause.filename) + "'"); console.error(`Uglify error in '${err.cause && err.cause.filename}'`);
} }
cb(err); cb(err);
}); });

View file

@ -4,20 +4,20 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var es = require("event-stream"); const es = require("event-stream");
var _ = require("underscore"); const _ = require("underscore");
var util = require("gulp-util"); const util = require("gulp-util");
var fs = require("fs"); const fs = require("fs");
var path = require("path"); const path = require("path");
var allErrors = []; const allErrors = [];
var startTime = null; let startTime = null;
var count = 0; let count = 0;
function onStart() { function onStart() {
if (count++ > 0) { if (count++ > 0) {
return; return;
} }
startTime = new Date().getTime(); startTime = new Date().getTime();
util.log("Starting " + util.colors.green('compilation') + "..."); util.log(`Starting ${util.colors.green('compilation')}...`);
} }
function onEnd() { function onEnd() {
if (--count > 0) { if (--count > 0) {
@ -25,7 +25,7 @@ function onEnd() {
} }
log(); log();
} }
var buildLogPath = path.join(path.dirname(path.dirname(__dirname)), '.build', 'log'); const buildLogPath = path.join(path.dirname(path.dirname(__dirname)), '.build', 'log');
try { try {
fs.mkdirSync(path.dirname(buildLogPath)); fs.mkdirSync(path.dirname(buildLogPath));
} }
@ -33,42 +33,39 @@ catch (err) {
// ignore // ignore
} }
function log() { function log() {
var errors = _.flatten(allErrors); const errors = _.flatten(allErrors);
var seen = new Set(); const seen = new Set();
errors.map(function (err) { errors.map(err => {
if (!seen.has(err)) { if (!seen.has(err)) {
seen.add(err); seen.add(err);
util.log(util.colors.red('Error') + ": " + err); util.log(`${util.colors.red('Error')}: ${err}`);
} }
}); });
var regex = /^([^(]+)\((\d+),(\d+)\): (.*)$/; const regex = /^([^(]+)\((\d+),(\d+)\): (.*)$/;
var messages = errors const messages = errors
.map(function (err) { return regex.exec(err); }) .map(err => regex.exec(err))
.filter(function (match) { return !!match; }) .filter(match => !!match)
.map(function (x) { return x; }) .map(x => x)
.map(function (_a) { .map(([, path, line, column, message]) => ({ path, line: parseInt(line), column: parseInt(column), message }));
var path = _a[1], line = _a[2], column = _a[3], message = _a[4];
return ({ path: path, line: parseInt(line), column: parseInt(column), message: message });
});
try { try {
fs.writeFileSync(buildLogPath, JSON.stringify(messages)); fs.writeFileSync(buildLogPath, JSON.stringify(messages));
} }
catch (err) { catch (err) {
//noop //noop
} }
util.log("Finished " + util.colors.green('compilation') + " with " + errors.length + " errors after " + util.colors.magenta((new Date().getTime() - startTime) + ' ms')); util.log(`Finished ${util.colors.green('compilation')} with ${errors.length} errors after ${util.colors.magenta((new Date().getTime() - startTime) + ' ms')}`);
} }
function createReporter() { function createReporter() {
var errors = []; const errors = [];
allErrors.push(errors); allErrors.push(errors);
var ReportFunc = /** @class */ (function () { class ReportFunc {
function ReportFunc(err) { constructor(err) {
errors.push(err); errors.push(err);
} }
ReportFunc.hasErrors = function () { static hasErrors() {
return errors.length > 0; return errors.length > 0;
}; }
ReportFunc.end = function (emitError) { static end(emitError) {
errors.length = 0; errors.length = 0;
onStart(); onStart();
return es.through(undefined, function () { return es.through(undefined, function () {
@ -78,7 +75,7 @@ function createReporter() {
log(); log();
} }
errors.__logged__ = true; errors.__logged__ = true;
var err = new Error("Found " + errors.length + " errors"); const err = new Error(`Found ${errors.length} errors`);
err.__reporter__ = true; err.__reporter__ = true;
this.emit('error', err); this.emit('error', err);
} }
@ -86,9 +83,8 @@ function createReporter() {
this.emit('end'); this.emit('end');
} }
}); });
}; }
return ReportFunc; }
}());
return ReportFunc; return ReportFunc;
} }
exports.createReporter = createReporter; exports.createReporter = createReporter;

View file

@ -5,25 +5,25 @@
'use strict'; 'use strict';
var snaps; var snaps;
(function (snaps) { (function (snaps) {
var fs = require('fs'); const fs = require('fs');
var path = require('path'); const path = require('path');
var os = require('os'); const os = require('os');
var cp = require('child_process'); const cp = require('child_process');
var mksnapshot = path.join(__dirname, "../../node_modules/.bin/" + (process.platform === 'win32' ? 'mksnapshot.cmd' : 'mksnapshot')); const mksnapshot = path.join(__dirname, `../../node_modules/.bin/${process.platform === 'win32' ? 'mksnapshot.cmd' : 'mksnapshot'}`);
var product = require('../../product.json'); const product = require('../../product.json');
var arch = (process.argv.join('').match(/--arch=(.*)/) || [])[1]; const arch = (process.argv.join('').match(/--arch=(.*)/) || [])[1];
// //
var loaderFilepath; let loaderFilepath;
var startupBlobFilepath; let startupBlobFilepath;
switch (process.platform) { switch (process.platform) {
case 'darwin': case 'darwin':
loaderFilepath = "VSCode-darwin/" + product.nameLong + ".app/Contents/Resources/app/out/vs/loader.js"; loaderFilepath = `VSCode-darwin/${product.nameLong}.app/Contents/Resources/app/out/vs/loader.js`;
startupBlobFilepath = "VSCode-darwin/" + product.nameLong + ".app/Contents/Frameworks/Electron Framework.framework/Resources/snapshot_blob.bin"; startupBlobFilepath = `VSCode-darwin/${product.nameLong}.app/Contents/Frameworks/Electron Framework.framework/Resources/snapshot_blob.bin`;
break; break;
case 'win32': case 'win32':
case 'linux': case 'linux':
loaderFilepath = "VSCode-" + process.platform + "-" + arch + "/resources/app/out/vs/loader.js"; loaderFilepath = `VSCode-${process.platform}-${arch}/resources/app/out/vs/loader.js`;
startupBlobFilepath = "VSCode-" + process.platform + "-" + arch + "/snapshot_blob.bin"; startupBlobFilepath = `VSCode-${process.platform}-${arch}/snapshot_blob.bin`;
default: default:
throw new Error('Unknown platform'); throw new Error('Unknown platform');
} }
@ -31,11 +31,24 @@ var snaps;
startupBlobFilepath = path.join(__dirname, '../../../', startupBlobFilepath); startupBlobFilepath = path.join(__dirname, '../../../', startupBlobFilepath);
snapshotLoader(loaderFilepath, startupBlobFilepath); snapshotLoader(loaderFilepath, startupBlobFilepath);
function snapshotLoader(loaderFilepath, startupBlobFilepath) { function snapshotLoader(loaderFilepath, startupBlobFilepath) {
var inputFile = fs.readFileSync(loaderFilepath); const inputFile = fs.readFileSync(loaderFilepath);
var wrappedInputFile = "\n\t\tvar Monaco_Loader_Init;\n\t\t(function() {\n\t\t\tvar doNotInitLoader = true;\n\t\t\t" + inputFile.toString() + ";\n\t\t\tMonaco_Loader_Init = function() {\n\t\t\t\tAMDLoader.init();\n\t\t\t\tCSSLoaderPlugin.init();\n\t\t\t\tNLSLoaderPlugin.init();\n\n\t\t\t\treturn { define, require };\n\t\t\t}\n\t\t})();\n\t\t"; const wrappedInputFile = `
var wrappedInputFilepath = path.join(os.tmpdir(), 'wrapped-loader.js'); var Monaco_Loader_Init;
(function() {
var doNotInitLoader = true;
${inputFile.toString()};
Monaco_Loader_Init = function() {
AMDLoader.init();
CSSLoaderPlugin.init();
NLSLoaderPlugin.init();
return { define, require };
}
})();
`;
const wrappedInputFilepath = path.join(os.tmpdir(), 'wrapped-loader.js');
console.log(wrappedInputFilepath); console.log(wrappedInputFilepath);
fs.writeFileSync(wrappedInputFilepath, wrappedInputFile); fs.writeFileSync(wrappedInputFilepath, wrappedInputFile);
cp.execFileSync(mksnapshot, [wrappedInputFilepath, "--startup_blob", startupBlobFilepath]); cp.execFileSync(mksnapshot, [wrappedInputFilepath, `--startup_blob`, startupBlobFilepath]);
} }
})(snaps || (snaps = {})); })(snaps || (snaps = {}));

View file

@ -4,13 +4,13 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var ts = require("typescript"); const ts = require("typescript");
var fs = require("fs"); const fs = require("fs");
var path = require("path"); const path = require("path");
var tss = require("./treeshaking"); const tss = require("./treeshaking");
var REPO_ROOT = path.join(__dirname, '../../'); const REPO_ROOT = path.join(__dirname, '../../');
var SRC_DIR = path.join(REPO_ROOT, 'src'); const SRC_DIR = path.join(REPO_ROOT, 'src');
var dirCache = {}; let dirCache = {};
function writeFile(filePath, contents) { function writeFile(filePath, contents) {
function ensureDirs(dirPath) { function ensureDirs(dirPath) {
if (dirCache[dirPath]) { if (dirCache[dirPath]) {
@ -27,39 +27,39 @@ function writeFile(filePath, contents) {
fs.writeFileSync(filePath, contents); fs.writeFileSync(filePath, contents);
} }
function extractEditor(options) { function extractEditor(options) {
var tsConfig = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.json')).toString()); const tsConfig = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.json')).toString());
tsConfig.compilerOptions.noUnusedLocals = false; tsConfig.compilerOptions.noUnusedLocals = false;
tsConfig.compilerOptions.preserveConstEnums = false; tsConfig.compilerOptions.preserveConstEnums = false;
tsConfig.compilerOptions.declaration = false; tsConfig.compilerOptions.declaration = false;
delete tsConfig.compilerOptions.types; delete tsConfig.compilerOptions.types;
tsConfig.exclude = []; tsConfig.exclude = [];
options.compilerOptions = tsConfig.compilerOptions; options.compilerOptions = tsConfig.compilerOptions;
var result = tss.shake(options); let result = tss.shake(options);
for (var fileName in result) { for (let fileName in result) {
if (result.hasOwnProperty(fileName)) { if (result.hasOwnProperty(fileName)) {
writeFile(path.join(options.destRoot, fileName), result[fileName]); writeFile(path.join(options.destRoot, fileName), result[fileName]);
} }
} }
var copied = {}; let copied = {};
var copyFile = function (fileName) { const copyFile = (fileName) => {
if (copied[fileName]) { if (copied[fileName]) {
return; return;
} }
copied[fileName] = true; copied[fileName] = true;
var srcPath = path.join(options.sourcesRoot, fileName); const srcPath = path.join(options.sourcesRoot, fileName);
var dstPath = path.join(options.destRoot, fileName); const dstPath = path.join(options.destRoot, fileName);
writeFile(dstPath, fs.readFileSync(srcPath)); writeFile(dstPath, fs.readFileSync(srcPath));
}; };
var writeOutputFile = function (fileName, contents) { const writeOutputFile = (fileName, contents) => {
writeFile(path.join(options.destRoot, fileName), contents); writeFile(path.join(options.destRoot, fileName), contents);
}; };
for (var fileName in result) { for (let fileName in result) {
if (result.hasOwnProperty(fileName)) { if (result.hasOwnProperty(fileName)) {
var fileContents = result[fileName]; const fileContents = result[fileName];
var info = ts.preProcessFile(fileContents); const info = ts.preProcessFile(fileContents);
for (var i = info.importedFiles.length - 1; i >= 0; i--) { for (let i = info.importedFiles.length - 1; i >= 0; i--) {
var importedFileName = info.importedFiles[i].fileName; const importedFileName = info.importedFiles[i].fileName;
var importedFilePath = void 0; let importedFilePath;
if (/^vs\/css!/.test(importedFileName)) { if (/^vs\/css!/.test(importedFileName)) {
importedFilePath = importedFileName.substr('vs/css!'.length) + '.css'; importedFilePath = importedFileName.substr('vs/css!'.length) + '.css';
} }
@ -94,27 +94,27 @@ function extractEditor(options) {
} }
exports.extractEditor = extractEditor; exports.extractEditor = extractEditor;
function createESMSourcesAndResources2(options) { function createESMSourcesAndResources2(options) {
var SRC_FOLDER = path.join(REPO_ROOT, options.srcFolder); const SRC_FOLDER = path.join(REPO_ROOT, options.srcFolder);
var OUT_FOLDER = path.join(REPO_ROOT, options.outFolder); const OUT_FOLDER = path.join(REPO_ROOT, options.outFolder);
var OUT_RESOURCES_FOLDER = path.join(REPO_ROOT, options.outResourcesFolder); const OUT_RESOURCES_FOLDER = path.join(REPO_ROOT, options.outResourcesFolder);
var getDestAbsoluteFilePath = function (file) { const getDestAbsoluteFilePath = (file) => {
var dest = options.renames[file.replace(/\\/g, '/')] || file; let dest = options.renames[file.replace(/\\/g, '/')] || file;
if (dest === 'tsconfig.json') { if (dest === 'tsconfig.json') {
return path.join(OUT_FOLDER, "tsconfig.json"); return path.join(OUT_FOLDER, `tsconfig.json`);
} }
if (/\.ts$/.test(dest)) { if (/\.ts$/.test(dest)) {
return path.join(OUT_FOLDER, dest); return path.join(OUT_FOLDER, dest);
} }
return path.join(OUT_RESOURCES_FOLDER, dest); return path.join(OUT_RESOURCES_FOLDER, dest);
}; };
var allFiles = walkDirRecursive(SRC_FOLDER); const allFiles = walkDirRecursive(SRC_FOLDER);
for (var i = 0; i < allFiles.length; i++) { for (let i = 0; i < allFiles.length; i++) {
var file = allFiles[i]; const file = allFiles[i];
if (options.ignores.indexOf(file.replace(/\\/g, '/')) >= 0) { if (options.ignores.indexOf(file.replace(/\\/g, '/')) >= 0) {
continue; continue;
} }
if (file === 'tsconfig.json') { if (file === 'tsconfig.json') {
var tsConfig = JSON.parse(fs.readFileSync(path.join(SRC_FOLDER, file)).toString()); const tsConfig = JSON.parse(fs.readFileSync(path.join(SRC_FOLDER, file)).toString());
tsConfig.compilerOptions.module = 'es6'; tsConfig.compilerOptions.module = 'es6';
tsConfig.compilerOptions.outDir = path.join(path.relative(OUT_FOLDER, OUT_RESOURCES_FOLDER), 'vs'); tsConfig.compilerOptions.outDir = path.join(path.relative(OUT_FOLDER, OUT_RESOURCES_FOLDER), 'vs');
write(getDestAbsoluteFilePath(file), JSON.stringify(tsConfig, null, '\t')); write(getDestAbsoluteFilePath(file), JSON.stringify(tsConfig, null, '\t'));
@ -127,13 +127,13 @@ function createESMSourcesAndResources2(options) {
} }
if (/\.ts$/.test(file)) { if (/\.ts$/.test(file)) {
// Transform the .ts file // Transform the .ts file
var fileContents = fs.readFileSync(path.join(SRC_FOLDER, file)).toString(); let fileContents = fs.readFileSync(path.join(SRC_FOLDER, file)).toString();
var info = ts.preProcessFile(fileContents); const info = ts.preProcessFile(fileContents);
for (var i_1 = info.importedFiles.length - 1; i_1 >= 0; i_1--) { for (let i = info.importedFiles.length - 1; i >= 0; i--) {
var importedFilename = info.importedFiles[i_1].fileName; const importedFilename = info.importedFiles[i].fileName;
var pos = info.importedFiles[i_1].pos; const pos = info.importedFiles[i].pos;
var end = info.importedFiles[i_1].end; const end = info.importedFiles[i].end;
var importedFilepath = void 0; let importedFilepath;
if (/^vs\/css!/.test(importedFilename)) { if (/^vs\/css!/.test(importedFilename)) {
importedFilepath = importedFilename.substr('vs/css!'.length) + '.css'; importedFilepath = importedFilename.substr('vs/css!'.length) + '.css';
} }
@ -143,7 +143,7 @@ function createESMSourcesAndResources2(options) {
if (/(^\.\/)|(^\.\.\/)/.test(importedFilepath)) { if (/(^\.\/)|(^\.\.\/)/.test(importedFilepath)) {
importedFilepath = path.join(path.dirname(file), importedFilepath); importedFilepath = path.join(path.dirname(file), importedFilepath);
} }
var relativePath = void 0; let relativePath;
if (importedFilepath === path.dirname(file)) { if (importedFilepath === path.dirname(file)) {
relativePath = '../' + path.basename(path.dirname(file)); relativePath = '../' + path.basename(path.dirname(file));
} }
@ -161,25 +161,25 @@ function createESMSourcesAndResources2(options) {
+ fileContents.substring(end + 1)); + fileContents.substring(end + 1));
} }
fileContents = fileContents.replace(/import ([a-zA-z0-9]+) = require\(('[^']+')\);/g, function (_, m1, m2) { fileContents = fileContents.replace(/import ([a-zA-z0-9]+) = require\(('[^']+')\);/g, function (_, m1, m2) {
return "import * as " + m1 + " from " + m2 + ";"; return `import * as ${m1} from ${m2};`;
}); });
write(getDestAbsoluteFilePath(file), fileContents); write(getDestAbsoluteFilePath(file), fileContents);
continue; continue;
} }
console.log("UNKNOWN FILE: " + file); console.log(`UNKNOWN FILE: ${file}`);
} }
function walkDirRecursive(dir) { function walkDirRecursive(dir) {
if (dir.charAt(dir.length - 1) !== '/' || dir.charAt(dir.length - 1) !== '\\') { if (dir.charAt(dir.length - 1) !== '/' || dir.charAt(dir.length - 1) !== '\\') {
dir += '/'; dir += '/';
} }
var result = []; let result = [];
_walkDirRecursive(dir, result, dir.length); _walkDirRecursive(dir, result, dir.length);
return result; return result;
} }
function _walkDirRecursive(dir, result, trimPos) { function _walkDirRecursive(dir, result, trimPos) {
var files = fs.readdirSync(dir); const files = fs.readdirSync(dir);
for (var i = 0; i < files.length; i++) { for (let i = 0; i < files.length; i++) {
var file = path.join(dir, files[i]); const file = path.join(dir, files[i]);
if (fs.statSync(file).isDirectory()) { if (fs.statSync(file).isDirectory()) {
_walkDirRecursive(file, result, trimPos); _walkDirRecursive(file, result, trimPos);
} }
@ -194,10 +194,10 @@ function createESMSourcesAndResources2(options) {
} }
writeFile(absoluteFilePath, contents); writeFile(absoluteFilePath, contents);
function toggleComments(fileContents) { function toggleComments(fileContents) {
var lines = fileContents.split(/\r\n|\r|\n/); let lines = fileContents.split(/\r\n|\r|\n/);
var mode = 0; let mode = 0;
for (var i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
var line = lines[i]; const line = lines[i];
if (mode === 0) { if (mode === 0) {
if (/\/\/ ESM-comment-begin/.test(line)) { if (/\/\/ ESM-comment-begin/.test(line)) {
mode = 1; mode = 1;
@ -236,30 +236,30 @@ function transportCSS(module, enqueue, write) {
if (!/\.css/.test(module)) { if (!/\.css/.test(module)) {
return false; return false;
} }
var filename = path.join(SRC_DIR, module); const filename = path.join(SRC_DIR, module);
var fileContents = fs.readFileSync(filename).toString(); const fileContents = fs.readFileSync(filename).toString();
var inlineResources = 'base64'; // see https://github.com/Microsoft/monaco-editor/issues/148 const inlineResources = 'base64'; // see https://github.com/Microsoft/monaco-editor/issues/148
var inlineResourcesLimit = 300000; //3000; // see https://github.com/Microsoft/monaco-editor/issues/336 const inlineResourcesLimit = 300000; //3000; // see https://github.com/Microsoft/monaco-editor/issues/336
var newContents = _rewriteOrInlineUrls(fileContents, inlineResources === 'base64', inlineResourcesLimit); const newContents = _rewriteOrInlineUrls(fileContents, inlineResources === 'base64', inlineResourcesLimit);
write(module, newContents); write(module, newContents);
return true; return true;
function _rewriteOrInlineUrls(contents, forceBase64, inlineByteLimit) { function _rewriteOrInlineUrls(contents, forceBase64, inlineByteLimit) {
return _replaceURL(contents, function (url) { return _replaceURL(contents, (url) => {
var imagePath = path.join(path.dirname(module), url); let imagePath = path.join(path.dirname(module), url);
var fileContents = fs.readFileSync(path.join(SRC_DIR, imagePath)); let fileContents = fs.readFileSync(path.join(SRC_DIR, imagePath));
if (fileContents.length < inlineByteLimit) { if (fileContents.length < inlineByteLimit) {
var MIME = /\.svg$/.test(url) ? 'image/svg+xml' : 'image/png'; const MIME = /\.svg$/.test(url) ? 'image/svg+xml' : 'image/png';
var DATA = ';base64,' + fileContents.toString('base64'); let DATA = ';base64,' + fileContents.toString('base64');
if (!forceBase64 && /\.svg$/.test(url)) { if (!forceBase64 && /\.svg$/.test(url)) {
// .svg => url encode as explained at https://codepen.io/tigt/post/optimizing-svgs-in-data-uris // .svg => url encode as explained at https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
var newText = fileContents.toString() let newText = fileContents.toString()
.replace(/"/g, '\'') .replace(/"/g, '\'')
.replace(/</g, '%3C') .replace(/</g, '%3C')
.replace(/>/g, '%3E') .replace(/>/g, '%3E')
.replace(/&/g, '%26') .replace(/&/g, '%26')
.replace(/#/g, '%23') .replace(/#/g, '%23')
.replace(/\s+/g, ' '); .replace(/\s+/g, ' ');
var encodedData = ',' + newText; let encodedData = ',' + newText;
if (encodedData.length < DATA.length) { if (encodedData.length < DATA.length) {
DATA = encodedData; DATA = encodedData;
} }
@ -272,12 +272,8 @@ function transportCSS(module, enqueue, write) {
} }
function _replaceURL(contents, replacer) { function _replaceURL(contents, replacer) {
// Use ")" as the terminator as quotes are oftentimes not used at all // Use ")" as the terminator as quotes are oftentimes not used at all
return contents.replace(/url\(\s*([^\)]+)\s*\)?/g, function (_) { return contents.replace(/url\(\s*([^\)]+)\s*\)?/g, (_, ...matches) => {
var matches = []; let url = matches[0];
for (var _i = 1; _i < arguments.length; _i++) {
matches[_i - 1] = arguments[_i];
}
var url = matches[0];
// Eliminate starting quotes (the initial whitespace is not captured) // Eliminate starting quotes (the initial whitespace is not captured)
if (url.charAt(0) === '"' || url.charAt(0) === '\'') { if (url.charAt(0) === '"' || url.charAt(0) === '\'') {
url = url.substring(1); url = url.substring(1);

View file

@ -4,44 +4,43 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var es = require("event-stream"); const es = require("event-stream");
var util = require("gulp-util"); const util = require("gulp-util");
var appInsights = require("applicationinsights"); const appInsights = require("applicationinsights");
var Entry = /** @class */ (function () { class Entry {
function Entry(name, totalCount, totalSize) { constructor(name, totalCount, totalSize) {
this.name = name; this.name = name;
this.totalCount = totalCount; this.totalCount = totalCount;
this.totalSize = totalSize; this.totalSize = totalSize;
} }
Entry.prototype.toString = function (pretty) { toString(pretty) {
if (!pretty) { if (!pretty) {
if (this.totalCount === 1) { if (this.totalCount === 1) {
return this.name + ": " + this.totalSize + " bytes"; return `${this.name}: ${this.totalSize} bytes`;
} }
else { else {
return this.name + ": " + this.totalCount + " files with " + this.totalSize + " bytes"; return `${this.name}: ${this.totalCount} files with ${this.totalSize} bytes`;
} }
} }
else { else {
if (this.totalCount === 1) { if (this.totalCount === 1) {
return "Stats for '" + util.colors.grey(this.name) + "': " + Math.round(this.totalSize / 1204) + "KB"; return `Stats for '${util.colors.grey(this.name)}': ${Math.round(this.totalSize / 1204)}KB`;
} }
else { else {
var count = this.totalCount < 100 const count = this.totalCount < 100
? util.colors.green(this.totalCount.toString()) ? util.colors.green(this.totalCount.toString())
: util.colors.red(this.totalCount.toString()); : util.colors.red(this.totalCount.toString());
return "Stats for '" + util.colors.grey(this.name) + "': " + count + " files, " + Math.round(this.totalSize / 1204) + "KB"; return `Stats for '${util.colors.grey(this.name)}': ${count} files, ${Math.round(this.totalSize / 1204)}KB`;
} }
} }
}; }
return Entry; }
}()); const _entries = new Map();
var _entries = new Map();
function createStatsStream(group, log) { function createStatsStream(group, log) {
var entry = new Entry(group, 0, 0); const entry = new Entry(group, 0, 0);
_entries.set(entry.name, entry); _entries.set(entry.name, entry);
return es.through(function (data) { return es.through(function (data) {
var file = data; const file = data;
if (typeof file.path === 'string') { if (typeof file.path === 'string') {
entry.totalCount += 1; entry.totalCount += 1;
if (Buffer.isBuffer(file.contents)) { if (Buffer.isBuffer(file.contents)) {
@ -58,13 +57,13 @@ function createStatsStream(group, log) {
}, function () { }, function () {
if (log) { if (log) {
if (entry.totalCount === 1) { if (entry.totalCount === 1) {
util.log("Stats for '" + util.colors.grey(entry.name) + "': " + Math.round(entry.totalSize / 1204) + "KB"); util.log(`Stats for '${util.colors.grey(entry.name)}': ${Math.round(entry.totalSize / 1204)}KB`);
} }
else { else {
var count = entry.totalCount < 100 const count = entry.totalCount < 100
? util.colors.green(entry.totalCount.toString()) ? util.colors.green(entry.totalCount.toString())
: util.colors.red(entry.totalCount.toString()); : util.colors.red(entry.totalCount.toString());
util.log("Stats for '" + util.colors.grey(entry.name) + "': " + count + " files, " + Math.round(entry.totalSize / 1204) + "KB"); util.log(`Stats for '${util.colors.grey(entry.name)}': ${count} files, ${Math.round(entry.totalSize / 1204)}KB`);
} }
} }
this.emit('end'); this.emit('end');
@ -72,9 +71,9 @@ function createStatsStream(group, log) {
} }
exports.createStatsStream = createStatsStream; exports.createStatsStream = createStatsStream;
function submitAllStats(productJson, commit) { function submitAllStats(productJson, commit) {
var sorted = []; const sorted = [];
// move entries for single files to the front // move entries for single files to the front
_entries.forEach(function (value) { _entries.forEach(value => {
if (value.totalCount === 1) { if (value.totalCount === 1) {
sorted.unshift(value); sorted.unshift(value);
} }
@ -83,8 +82,7 @@ function submitAllStats(productJson, commit) {
} }
}); });
// print to console // print to console
for (var _i = 0, sorted_1 = sorted; _i < sorted_1.length; _i++) { for (const entry of sorted) {
var entry = sorted_1[_i];
console.log(entry.toString(true)); console.log(entry.toString(true));
} }
// send data as telementry event when the // send data as telementry event when the
@ -92,12 +90,11 @@ function submitAllStats(productJson, commit) {
if (!productJson || !productJson.aiConfig || typeof productJson.aiConfig.asimovKey !== 'string') { if (!productJson || !productJson.aiConfig || typeof productJson.aiConfig.asimovKey !== 'string') {
return Promise.resolve(false); return Promise.resolve(false);
} }
return new Promise(function (resolve) { return new Promise(resolve => {
try { try {
var sizes = {}; const sizes = {};
var counts = {}; const counts = {};
for (var _i = 0, sorted_2 = sorted; _i < sorted_2.length; _i++) { for (const entry of sorted) {
var entry = sorted_2[_i];
sizes[entry.name] = entry.totalSize; sizes[entry.name] = entry.totalSize;
counts[entry.name] = entry.totalCount; counts[entry.name] = entry.totalCount;
} }
@ -119,10 +116,10 @@ function submitAllStats(productJson, commit) {
*/ */
appInsights.defaultClient.trackEvent({ appInsights.defaultClient.trackEvent({
name: 'monacoworkbench/packagemetrics', name: 'monacoworkbench/packagemetrics',
properties: { commit: commit, size: JSON.stringify(sizes), count: JSON.stringify(counts) } properties: { commit, size: JSON.stringify(sizes), count: JSON.stringify(counts) }
}); });
appInsights.defaultClient.flush({ appInsights.defaultClient.flush({
callback: function () { callback: () => {
appInsights.dispose(); appInsights.dispose();
resolve(true); resolve(true);
} }

View file

@ -4,30 +4,30 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var assert = require("assert"); const assert = require("assert");
var i18n = require("../i18n"); const i18n = require("../i18n");
suite('XLF Parser Tests', function () { suite('XLF Parser Tests', () => {
var sampleXlf = '<?xml version="1.0" encoding="utf-8"?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"><file original="vs/base/common/keybinding" source-language="en" datatype="plaintext"><body><trans-unit id="key1"><source xml:lang="en">Key #1</source></trans-unit><trans-unit id="key2"><source xml:lang="en">Key #2 &amp;</source></trans-unit></body></file></xliff>'; const sampleXlf = '<?xml version="1.0" encoding="utf-8"?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"><file original="vs/base/common/keybinding" source-language="en" datatype="plaintext"><body><trans-unit id="key1"><source xml:lang="en">Key #1</source></trans-unit><trans-unit id="key2"><source xml:lang="en">Key #2 &amp;</source></trans-unit></body></file></xliff>';
var sampleTranslatedXlf = '<?xml version="1.0" encoding="utf-8"?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"><file original="vs/base/common/keybinding" source-language="en" target-language="ru" datatype="plaintext"><body><trans-unit id="key1"><source xml:lang="en">Key #1</source><target>Кнопка #1</target></trans-unit><trans-unit id="key2"><source xml:lang="en">Key #2 &amp;</source><target>Кнопка #2 &amp;</target></trans-unit></body></file></xliff>'; const sampleTranslatedXlf = '<?xml version="1.0" encoding="utf-8"?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"><file original="vs/base/common/keybinding" source-language="en" target-language="ru" datatype="plaintext"><body><trans-unit id="key1"><source xml:lang="en">Key #1</source><target>Кнопка #1</target></trans-unit><trans-unit id="key2"><source xml:lang="en">Key #2 &amp;</source><target>Кнопка #2 &amp;</target></trans-unit></body></file></xliff>';
var originalFilePath = 'vs/base/common/keybinding'; const originalFilePath = 'vs/base/common/keybinding';
var keys = ['key1', 'key2']; const keys = ['key1', 'key2'];
var messages = ['Key #1', 'Key #2 &']; const messages = ['Key #1', 'Key #2 &'];
var translatedMessages = { key1: 'Кнопка #1', key2: 'Кнопка #2 &' }; const translatedMessages = { key1: 'Кнопка #1', key2: 'Кнопка #2 &' };
test('Keys & messages to XLF conversion', function () { test('Keys & messages to XLF conversion', () => {
var xlf = new i18n.XLF('vscode-workbench'); const xlf = new i18n.XLF('vscode-workbench');
xlf.addFile(originalFilePath, keys, messages); xlf.addFile(originalFilePath, keys, messages);
var xlfString = xlf.toString(); const xlfString = xlf.toString();
assert.strictEqual(xlfString.replace(/\s{2,}/g, ''), sampleXlf); assert.strictEqual(xlfString.replace(/\s{2,}/g, ''), sampleXlf);
}); });
test('XLF to keys & messages conversion', function () { test('XLF to keys & messages conversion', () => {
i18n.XLF.parse(sampleTranslatedXlf).then(function (resolvedFiles) { i18n.XLF.parse(sampleTranslatedXlf).then(function (resolvedFiles) {
assert.deepEqual(resolvedFiles[0].messages, translatedMessages); assert.deepEqual(resolvedFiles[0].messages, translatedMessages);
assert.strictEqual(resolvedFiles[0].originalFilePath, originalFilePath); assert.strictEqual(resolvedFiles[0].originalFilePath, originalFilePath);
}); });
}); });
test('JSON file source path to Transifex resource match', function () { test('JSON file source path to Transifex resource match', () => {
var editorProject = 'vscode-editor', workbenchProject = 'vscode-workbench'; const editorProject = 'vscode-editor', workbenchProject = 'vscode-workbench';
var platform = { name: 'vs/platform', project: editorProject }, editorContrib = { name: 'vs/editor/contrib', project: editorProject }, editor = { name: 'vs/editor', project: editorProject }, base = { name: 'vs/base', project: editorProject }, code = { name: 'vs/code', project: workbenchProject }, workbenchParts = { name: 'vs/workbench/parts/html', project: workbenchProject }, workbenchServices = { name: 'vs/workbench/services/files', project: workbenchProject }, workbench = { name: 'vs/workbench', project: workbenchProject }; const platform = { name: 'vs/platform', project: editorProject }, editorContrib = { name: 'vs/editor/contrib', project: editorProject }, editor = { name: 'vs/editor', project: editorProject }, base = { name: 'vs/base', project: editorProject }, code = { name: 'vs/code', project: workbenchProject }, workbenchParts = { name: 'vs/workbench/parts/html', project: workbenchProject }, workbenchServices = { name: 'vs/workbench/services/files', project: workbenchProject }, workbench = { name: 'vs/workbench', project: workbenchProject };
assert.deepEqual(i18n.getResource('vs/platform/actions/browser/menusExtensionPoint'), platform); assert.deepEqual(i18n.getResource('vs/platform/actions/browser/menusExtensionPoint'), platform);
assert.deepEqual(i18n.getResource('vs/editor/contrib/clipboard/browser/clipboard'), editorContrib); assert.deepEqual(i18n.getResource('vs/editor/contrib/clipboard/browser/clipboard'), editorContrib);
assert.deepEqual(i18n.getResource('vs/editor/common/modes/modesRegistry'), editor); assert.deepEqual(i18n.getResource('vs/editor/common/modes/modesRegistry'), editor);

View file

@ -4,10 +4,10 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs"); const fs = require("fs");
var path = require("path"); const path = require("path");
var ts = require("typescript"); const ts = require("typescript");
var TYPESCRIPT_LIB_FOLDER = path.dirname(require.resolve('typescript/lib/lib.d.ts')); const TYPESCRIPT_LIB_FOLDER = path.dirname(require.resolve('typescript/lib/lib.d.ts'));
var ShakeLevel; var ShakeLevel;
(function (ShakeLevel) { (function (ShakeLevel) {
ShakeLevel[ShakeLevel["Files"] = 0] = "Files"; ShakeLevel[ShakeLevel["Files"] = 0] = "Files";
@ -15,37 +15,37 @@ var ShakeLevel;
ShakeLevel[ShakeLevel["ClassMembers"] = 2] = "ClassMembers"; ShakeLevel[ShakeLevel["ClassMembers"] = 2] = "ClassMembers";
})(ShakeLevel = exports.ShakeLevel || (exports.ShakeLevel = {})); })(ShakeLevel = exports.ShakeLevel || (exports.ShakeLevel = {}));
function printDiagnostics(diagnostics) { function printDiagnostics(diagnostics) {
for (var i = 0; i < diagnostics.length; i++) { for (let i = 0; i < diagnostics.length; i++) {
var diag = diagnostics[i]; const diag = diagnostics[i];
var result = ''; let result = '';
if (diag.file) { if (diag.file) {
result += diag.file.fileName + ": "; result += `${diag.file.fileName}: `;
} }
if (diag.file && diag.start) { if (diag.file && diag.start) {
var location_1 = diag.file.getLineAndCharacterOfPosition(diag.start); let location = diag.file.getLineAndCharacterOfPosition(diag.start);
result += "- " + (location_1.line + 1) + "," + location_1.character + " - "; result += `- ${location.line + 1},${location.character} - `;
} }
result += JSON.stringify(diag.messageText); result += JSON.stringify(diag.messageText);
console.log(result); console.log(result);
} }
} }
function shake(options) { function shake(options) {
var languageService = createTypeScriptLanguageService(options); const languageService = createTypeScriptLanguageService(options);
var program = languageService.getProgram(); const program = languageService.getProgram();
var globalDiagnostics = program.getGlobalDiagnostics(); const globalDiagnostics = program.getGlobalDiagnostics();
if (globalDiagnostics.length > 0) { if (globalDiagnostics.length > 0) {
printDiagnostics(globalDiagnostics); printDiagnostics(globalDiagnostics);
throw new Error("Compilation Errors encountered."); throw new Error(`Compilation Errors encountered.`);
} }
var syntacticDiagnostics = program.getSyntacticDiagnostics(); const syntacticDiagnostics = program.getSyntacticDiagnostics();
if (syntacticDiagnostics.length > 0) { if (syntacticDiagnostics.length > 0) {
printDiagnostics(syntacticDiagnostics); printDiagnostics(syntacticDiagnostics);
throw new Error("Compilation Errors encountered."); throw new Error(`Compilation Errors encountered.`);
} }
var semanticDiagnostics = program.getSemanticDiagnostics(); const semanticDiagnostics = program.getSemanticDiagnostics();
if (semanticDiagnostics.length > 0) { if (semanticDiagnostics.length > 0) {
printDiagnostics(semanticDiagnostics); printDiagnostics(semanticDiagnostics);
throw new Error("Compilation Errors encountered."); throw new Error(`Compilation Errors encountered.`);
} }
markNodes(languageService, options); markNodes(languageService, options);
return generateResult(languageService, options.shakeLevel); return generateResult(languageService, options.shakeLevel);
@ -54,98 +54,98 @@ exports.shake = shake;
//#region Discovery, LanguageService & Setup //#region Discovery, LanguageService & Setup
function createTypeScriptLanguageService(options) { function createTypeScriptLanguageService(options) {
// Discover referenced files // Discover referenced files
var FILES = discoverAndReadFiles(options); const FILES = discoverAndReadFiles(options);
// Add fake usage files // Add fake usage files
options.inlineEntryPoints.forEach(function (inlineEntryPoint, index) { options.inlineEntryPoints.forEach((inlineEntryPoint, index) => {
FILES["inlineEntryPoint:" + index + ".ts"] = inlineEntryPoint; FILES[`inlineEntryPoint:${index}.ts`] = inlineEntryPoint;
}); });
// Add additional typings // Add additional typings
options.typings.forEach(function (typing) { options.typings.forEach((typing) => {
var filePath = path.join(options.sourcesRoot, typing); const filePath = path.join(options.sourcesRoot, typing);
FILES[typing] = fs.readFileSync(filePath).toString(); FILES[typing] = fs.readFileSync(filePath).toString();
}); });
// Resolve libs // Resolve libs
var RESOLVED_LIBS = {}; const RESOLVED_LIBS = {};
options.libs.forEach(function (filename) { options.libs.forEach((filename) => {
var filepath = path.join(TYPESCRIPT_LIB_FOLDER, filename); const filepath = path.join(TYPESCRIPT_LIB_FOLDER, filename);
RESOLVED_LIBS["defaultLib:" + filename] = fs.readFileSync(filepath).toString(); RESOLVED_LIBS[`defaultLib:${filename}`] = fs.readFileSync(filepath).toString();
}); });
var host = new TypeScriptLanguageServiceHost(RESOLVED_LIBS, FILES, ts.convertCompilerOptionsFromJson(options.compilerOptions, "").options); const host = new TypeScriptLanguageServiceHost(RESOLVED_LIBS, FILES, ts.convertCompilerOptionsFromJson(options.compilerOptions, ``).options);
return ts.createLanguageService(host); return ts.createLanguageService(host);
} }
/** /**
* Read imports and follow them until all files have been handled * Read imports and follow them until all files have been handled
*/ */
function discoverAndReadFiles(options) { function discoverAndReadFiles(options) {
var FILES = {}; const FILES = {};
var in_queue = Object.create(null); const in_queue = Object.create(null);
var queue = []; const queue = [];
var enqueue = function (moduleId) { const enqueue = (moduleId) => {
if (in_queue[moduleId]) { if (in_queue[moduleId]) {
return; return;
} }
in_queue[moduleId] = true; in_queue[moduleId] = true;
queue.push(moduleId); queue.push(moduleId);
}; };
options.entryPoints.forEach(function (entryPoint) { return enqueue(entryPoint); }); options.entryPoints.forEach((entryPoint) => enqueue(entryPoint));
while (queue.length > 0) { while (queue.length > 0) {
var moduleId = queue.shift(); const moduleId = queue.shift();
var dts_filename = path.join(options.sourcesRoot, moduleId + '.d.ts'); const dts_filename = path.join(options.sourcesRoot, moduleId + '.d.ts');
if (fs.existsSync(dts_filename)) { if (fs.existsSync(dts_filename)) {
var dts_filecontents = fs.readFileSync(dts_filename).toString(); const dts_filecontents = fs.readFileSync(dts_filename).toString();
FILES[moduleId + ".d.ts"] = dts_filecontents; FILES[`${moduleId}.d.ts`] = dts_filecontents;
continue; continue;
} }
var ts_filename = void 0; let ts_filename;
if (options.redirects[moduleId]) { if (options.redirects[moduleId]) {
ts_filename = path.join(options.sourcesRoot, options.redirects[moduleId] + '.ts'); ts_filename = path.join(options.sourcesRoot, options.redirects[moduleId] + '.ts');
} }
else { else {
ts_filename = path.join(options.sourcesRoot, moduleId + '.ts'); ts_filename = path.join(options.sourcesRoot, moduleId + '.ts');
} }
var ts_filecontents = fs.readFileSync(ts_filename).toString(); const ts_filecontents = fs.readFileSync(ts_filename).toString();
var info = ts.preProcessFile(ts_filecontents); const info = ts.preProcessFile(ts_filecontents);
for (var i = info.importedFiles.length - 1; i >= 0; i--) { for (let i = info.importedFiles.length - 1; i >= 0; i--) {
var importedFileName = info.importedFiles[i].fileName; const importedFileName = info.importedFiles[i].fileName;
if (options.importIgnorePattern.test(importedFileName)) { if (options.importIgnorePattern.test(importedFileName)) {
// Ignore vs/css! imports // Ignore vs/css! imports
continue; continue;
} }
var importedModuleId = importedFileName; let importedModuleId = importedFileName;
if (/(^\.\/)|(^\.\.\/)/.test(importedModuleId)) { if (/(^\.\/)|(^\.\.\/)/.test(importedModuleId)) {
importedModuleId = path.join(path.dirname(moduleId), importedModuleId); importedModuleId = path.join(path.dirname(moduleId), importedModuleId);
} }
enqueue(importedModuleId); enqueue(importedModuleId);
} }
FILES[moduleId + ".ts"] = ts_filecontents; FILES[`${moduleId}.ts`] = ts_filecontents;
} }
return FILES; return FILES;
} }
/** /**
* A TypeScript language service host * A TypeScript language service host
*/ */
var TypeScriptLanguageServiceHost = /** @class */ (function () { class TypeScriptLanguageServiceHost {
function TypeScriptLanguageServiceHost(libs, files, compilerOptions) { constructor(libs, files, compilerOptions) {
this._libs = libs; this._libs = libs;
this._files = files; this._files = files;
this._compilerOptions = compilerOptions; this._compilerOptions = compilerOptions;
} }
// --- language service host --------------- // --- language service host ---------------
TypeScriptLanguageServiceHost.prototype.getCompilationSettings = function () { getCompilationSettings() {
return this._compilerOptions; return this._compilerOptions;
}; }
TypeScriptLanguageServiceHost.prototype.getScriptFileNames = function () { getScriptFileNames() {
return ([] return ([]
.concat(Object.keys(this._libs)) .concat(Object.keys(this._libs))
.concat(Object.keys(this._files))); .concat(Object.keys(this._files)));
}; }
TypeScriptLanguageServiceHost.prototype.getScriptVersion = function (_fileName) { getScriptVersion(_fileName) {
return '1'; return '1';
}; }
TypeScriptLanguageServiceHost.prototype.getProjectVersion = function () { getProjectVersion() {
return '1'; return '1';
}; }
TypeScriptLanguageServiceHost.prototype.getScriptSnapshot = function (fileName) { getScriptSnapshot(fileName) {
if (this._files.hasOwnProperty(fileName)) { if (this._files.hasOwnProperty(fileName)) {
return ts.ScriptSnapshot.fromString(this._files[fileName]); return ts.ScriptSnapshot.fromString(this._files[fileName]);
} }
@ -155,21 +155,20 @@ var TypeScriptLanguageServiceHost = /** @class */ (function () {
else { else {
return ts.ScriptSnapshot.fromString(''); return ts.ScriptSnapshot.fromString('');
} }
}; }
TypeScriptLanguageServiceHost.prototype.getScriptKind = function (_fileName) { getScriptKind(_fileName) {
return ts.ScriptKind.TS; return ts.ScriptKind.TS;
}; }
TypeScriptLanguageServiceHost.prototype.getCurrentDirectory = function () { getCurrentDirectory() {
return ''; return '';
}; }
TypeScriptLanguageServiceHost.prototype.getDefaultLibFileName = function (_options) { getDefaultLibFileName(_options) {
return 'defaultLib:lib.d.ts'; return 'defaultLib:lib.d.ts';
}; }
TypeScriptLanguageServiceHost.prototype.isDefaultLibFileName = function (fileName) { isDefaultLibFileName(fileName) {
return fileName === this.getDefaultLibFileName(this._compilerOptions); return fileName === this.getDefaultLibFileName(this._compilerOptions);
}; }
return TypeScriptLanguageServiceHost; }
}());
//#endregion //#endregion
//#region Tree Shaking //#region Tree Shaking
var NodeColor; var NodeColor;
@ -186,7 +185,7 @@ function setColor(node, color) {
} }
function nodeOrParentIsBlack(node) { function nodeOrParentIsBlack(node) {
while (node) { while (node) {
var color = getColor(node); const color = getColor(node);
if (color === 2 /* Black */) { if (color === 2 /* Black */) {
return true; return true;
} }
@ -198,8 +197,7 @@ function nodeOrChildIsBlack(node) {
if (getColor(node) === 2 /* Black */) { if (getColor(node) === 2 /* Black */) {
return true; return true;
} }
for (var _i = 0, _a = node.getChildren(); _i < _a.length; _i++) { for (const child of node.getChildren()) {
var child = _a[_i];
if (nodeOrChildIsBlack(child)) { if (nodeOrChildIsBlack(child)) {
return true; return true;
} }
@ -207,22 +205,22 @@ function nodeOrChildIsBlack(node) {
return false; return false;
} }
function markNodes(languageService, options) { function markNodes(languageService, options) {
var program = languageService.getProgram(); const program = languageService.getProgram();
if (!program) { if (!program) {
throw new Error('Could not get program from language service'); throw new Error('Could not get program from language service');
} }
if (options.shakeLevel === 0 /* Files */) { if (options.shakeLevel === 0 /* Files */) {
// Mark all source files Black // Mark all source files Black
program.getSourceFiles().forEach(function (sourceFile) { program.getSourceFiles().forEach((sourceFile) => {
setColor(sourceFile, 2 /* Black */); setColor(sourceFile, 2 /* Black */);
}); });
return; return;
} }
var black_queue = []; const black_queue = [];
var gray_queue = []; const gray_queue = [];
var sourceFilesLoaded = {}; const sourceFilesLoaded = {};
function enqueueTopLevelModuleStatements(sourceFile) { function enqueueTopLevelModuleStatements(sourceFile) {
sourceFile.forEachChild(function (node) { sourceFile.forEachChild((node) => {
if (ts.isImportDeclaration(node)) { if (ts.isImportDeclaration(node)) {
if (!node.importClause && ts.isStringLiteral(node.moduleSpecifier)) { if (!node.importClause && ts.isStringLiteral(node.moduleSpecifier)) {
setColor(node, 2 /* Black */); setColor(node, 2 /* Black */);
@ -259,7 +257,7 @@ function markNodes(languageService, options) {
gray_queue.push(node); gray_queue.push(node);
} }
function enqueue_black(node) { function enqueue_black(node) {
var previousColor = getColor(node); const previousColor = getColor(node);
if (previousColor === 2 /* Black */) { if (previousColor === 2 /* Black */) {
return; return;
} }
@ -277,12 +275,12 @@ function markNodes(languageService, options) {
if (nodeOrParentIsBlack(node)) { if (nodeOrParentIsBlack(node)) {
return; return;
} }
var fileName = node.getSourceFile().fileName; const fileName = node.getSourceFile().fileName;
if (/^defaultLib:/.test(fileName) || /\.d\.ts$/.test(fileName)) { if (/^defaultLib:/.test(fileName) || /\.d\.ts$/.test(fileName)) {
setColor(node, 2 /* Black */); setColor(node, 2 /* Black */);
return; return;
} }
var sourceFile = node.getSourceFile(); const sourceFile = node.getSourceFile();
if (!sourceFilesLoaded[sourceFile.fileName]) { if (!sourceFilesLoaded[sourceFile.fileName]) {
sourceFilesLoaded[sourceFile.fileName] = true; sourceFilesLoaded[sourceFile.fileName] = true;
enqueueTopLevelModuleStatements(sourceFile); enqueueTopLevelModuleStatements(sourceFile);
@ -293,15 +291,15 @@ function markNodes(languageService, options) {
setColor(node, 2 /* Black */); setColor(node, 2 /* Black */);
black_queue.push(node); black_queue.push(node);
if (options.shakeLevel === 2 /* ClassMembers */ && (ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isPropertySignature(node) || ts.isGetAccessor(node) || ts.isSetAccessor(node))) { if (options.shakeLevel === 2 /* ClassMembers */ && (ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isPropertySignature(node) || ts.isGetAccessor(node) || ts.isSetAccessor(node))) {
var references = languageService.getReferencesAtPosition(node.getSourceFile().fileName, node.name.pos + node.name.getLeadingTriviaWidth()); const references = languageService.getReferencesAtPosition(node.getSourceFile().fileName, node.name.pos + node.name.getLeadingTriviaWidth());
if (references) { if (references) {
for (var i = 0, len = references.length; i < len; i++) { for (let i = 0, len = references.length; i < len; i++) {
var reference = references[i]; const reference = references[i];
var referenceSourceFile = program.getSourceFile(reference.fileName); const referenceSourceFile = program.getSourceFile(reference.fileName);
if (!referenceSourceFile) { if (!referenceSourceFile) {
continue; continue;
} }
var referenceNode = getTokenAtPosition(referenceSourceFile, reference.textSpan.start, false, false); const referenceNode = getTokenAtPosition(referenceSourceFile, reference.textSpan.start, false, false);
if (ts.isMethodDeclaration(referenceNode.parent) if (ts.isMethodDeclaration(referenceNode.parent)
|| ts.isPropertyDeclaration(referenceNode.parent) || ts.isPropertyDeclaration(referenceNode.parent)
|| ts.isGetAccessor(referenceNode.parent) || ts.isGetAccessor(referenceNode.parent)
@ -313,9 +311,9 @@ function markNodes(languageService, options) {
} }
} }
function enqueueFile(filename) { function enqueueFile(filename) {
var sourceFile = program.getSourceFile(filename); const sourceFile = program.getSourceFile(filename);
if (!sourceFile) { if (!sourceFile) {
console.warn("Cannot find source file " + filename); console.warn(`Cannot find source file ${filename}`);
return; return;
} }
enqueue_black(sourceFile); enqueue_black(sourceFile);
@ -325,8 +323,8 @@ function markNodes(languageService, options) {
// this import should be ignored // this import should be ignored
return; return;
} }
var nodeSourceFile = node.getSourceFile(); const nodeSourceFile = node.getSourceFile();
var fullPath; let fullPath;
if (/(^\.\/)|(^\.\.\/)/.test(importText)) { if (/(^\.\/)|(^\.\.\/)/.test(importText)) {
fullPath = path.join(path.dirname(nodeSourceFile.fileName), importText) + '.ts'; fullPath = path.join(path.dirname(nodeSourceFile.fileName), importText) + '.ts';
} }
@ -335,25 +333,25 @@ function markNodes(languageService, options) {
} }
enqueueFile(fullPath); enqueueFile(fullPath);
} }
options.entryPoints.forEach(function (moduleId) { return enqueueFile(moduleId + '.ts'); }); options.entryPoints.forEach(moduleId => enqueueFile(moduleId + '.ts'));
// Add fake usage files // Add fake usage files
options.inlineEntryPoints.forEach(function (_, index) { return enqueueFile("inlineEntryPoint:" + index + ".ts"); }); options.inlineEntryPoints.forEach((_, index) => enqueueFile(`inlineEntryPoint:${index}.ts`));
var step = 0; let step = 0;
var checker = program.getTypeChecker(); const checker = program.getTypeChecker();
var _loop_1 = function () { while (black_queue.length > 0 || gray_queue.length > 0) {
++step; ++step;
var node = void 0; let node;
if (step % 100 === 0) { if (step % 100 === 0) {
console.log(step + "/" + (step + black_queue.length + gray_queue.length) + " (" + black_queue.length + ", " + gray_queue.length + ")"); console.log(`${step}/${step + black_queue.length + gray_queue.length} (${black_queue.length}, ${gray_queue.length})`);
} }
if (black_queue.length === 0) { if (black_queue.length === 0) {
for (var i = 0; i < gray_queue.length; i++) { for (let i = 0; i < gray_queue.length; i++) {
var node_1 = gray_queue[i]; const node = gray_queue[i];
var nodeParent = node_1.parent; const nodeParent = node.parent;
if ((ts.isClassDeclaration(nodeParent) || ts.isInterfaceDeclaration(nodeParent)) && nodeOrChildIsBlack(nodeParent)) { if ((ts.isClassDeclaration(nodeParent) || ts.isInterfaceDeclaration(nodeParent)) && nodeOrChildIsBlack(nodeParent)) {
gray_queue.splice(i, 1); gray_queue.splice(i, 1);
black_queue.push(node_1); black_queue.push(node);
setColor(node_1, 2 /* Black */); setColor(node, 2 /* Black */);
i--; i--;
} }
} }
@ -362,17 +360,18 @@ function markNodes(languageService, options) {
node = black_queue.shift(); node = black_queue.shift();
} }
else { else {
return "break"; // only gray nodes remaining...
break;
} }
var nodeSourceFile = node.getSourceFile(); const nodeSourceFile = node.getSourceFile();
var loop = function (node) { const loop = (node) => {
var _a = getRealNodeSymbol(checker, node), symbol = _a[0], symbolImportNode = _a[1]; const [symbol, symbolImportNode] = getRealNodeSymbol(checker, node);
if (symbolImportNode) { if (symbolImportNode) {
setColor(symbolImportNode, 2 /* Black */); setColor(symbolImportNode, 2 /* Black */);
} }
if (symbol && !nodeIsInItsOwnDeclaration(nodeSourceFile, node, symbol)) { if (symbol && !nodeIsInItsOwnDeclaration(nodeSourceFile, node, symbol)) {
for (var i = 0, len = symbol.declarations.length; i < len; i++) { for (let i = 0, len = symbol.declarations.length; i < len; i++) {
var declaration = symbol.declarations[i]; const declaration = symbol.declarations[i];
if (ts.isSourceFile(declaration)) { if (ts.isSourceFile(declaration)) {
// Do not enqueue full source files // Do not enqueue full source files
// (they can be the declaration of a module import) // (they can be the declaration of a module import)
@ -380,9 +379,9 @@ function markNodes(languageService, options) {
} }
if (options.shakeLevel === 2 /* ClassMembers */ && (ts.isClassDeclaration(declaration) || ts.isInterfaceDeclaration(declaration))) { if (options.shakeLevel === 2 /* ClassMembers */ && (ts.isClassDeclaration(declaration) || ts.isInterfaceDeclaration(declaration))) {
enqueue_black(declaration.name); enqueue_black(declaration.name);
for (var j = 0; j < declaration.members.length; j++) { for (let j = 0; j < declaration.members.length; j++) {
var member = declaration.members[j]; const member = declaration.members[j];
var memberName = member.name ? member.name.getText() : null; const memberName = member.name ? member.name.getText() : null;
if (ts.isConstructorDeclaration(member) if (ts.isConstructorDeclaration(member)
|| ts.isConstructSignatureDeclaration(member) || ts.isConstructSignatureDeclaration(member)
|| ts.isIndexSignatureDeclaration(member) || ts.isIndexSignatureDeclaration(member)
@ -396,8 +395,7 @@ function markNodes(languageService, options) {
} }
// queue the heritage clauses // queue the heritage clauses
if (declaration.heritageClauses) { if (declaration.heritageClauses) {
for (var _i = 0, _b = declaration.heritageClauses; _i < _b.length; _i++) { for (let heritageClause of declaration.heritageClauses) {
var heritageClause = _b[_i];
enqueue_black(heritageClause); enqueue_black(heritageClause);
} }
} }
@ -410,17 +408,12 @@ function markNodes(languageService, options) {
node.forEachChild(loop); node.forEachChild(loop);
}; };
node.forEachChild(loop); node.forEachChild(loop);
};
while (black_queue.length > 0 || gray_queue.length > 0) {
var state_1 = _loop_1();
if (state_1 === "break")
break;
} }
} }
function nodeIsInItsOwnDeclaration(nodeSourceFile, node, symbol) { function nodeIsInItsOwnDeclaration(nodeSourceFile, node, symbol) {
for (var i = 0, len = symbol.declarations.length; i < len; i++) { for (let i = 0, len = symbol.declarations.length; i < len; i++) {
var declaration = symbol.declarations[i]; const declaration = symbol.declarations[i];
var declarationSourceFile = declaration.getSourceFile(); const declarationSourceFile = declaration.getSourceFile();
if (nodeSourceFile === declarationSourceFile) { if (nodeSourceFile === declarationSourceFile) {
if (declaration.pos <= node.pos && node.end <= declaration.end) { if (declaration.pos <= node.pos && node.end <= declaration.end) {
return true; return true;
@ -430,28 +423,28 @@ function nodeIsInItsOwnDeclaration(nodeSourceFile, node, symbol) {
return false; return false;
} }
function generateResult(languageService, shakeLevel) { function generateResult(languageService, shakeLevel) {
var program = languageService.getProgram(); const program = languageService.getProgram();
if (!program) { if (!program) {
throw new Error('Could not get program from language service'); throw new Error('Could not get program from language service');
} }
var result = {}; let result = {};
var writeFile = function (filePath, contents) { const writeFile = (filePath, contents) => {
result[filePath] = contents; result[filePath] = contents;
}; };
program.getSourceFiles().forEach(function (sourceFile) { program.getSourceFiles().forEach((sourceFile) => {
var fileName = sourceFile.fileName; const fileName = sourceFile.fileName;
if (/^defaultLib:/.test(fileName)) { if (/^defaultLib:/.test(fileName)) {
return; return;
} }
var destination = fileName; const destination = fileName;
if (/\.d\.ts$/.test(fileName)) { if (/\.d\.ts$/.test(fileName)) {
if (nodeOrChildIsBlack(sourceFile)) { if (nodeOrChildIsBlack(sourceFile)) {
writeFile(destination, sourceFile.text); writeFile(destination, sourceFile.text);
} }
return; return;
} }
var text = sourceFile.text; let text = sourceFile.text;
var result = ''; let result = '';
function keep(node) { function keep(node) {
result += text.substring(node.pos, node.end); result += text.substring(node.pos, node.end);
} }
@ -480,24 +473,24 @@ function generateResult(languageService, shakeLevel) {
} }
} }
else { else {
var survivingImports = []; let survivingImports = [];
for (var i = 0; i < node.importClause.namedBindings.elements.length; i++) { for (let i = 0; i < node.importClause.namedBindings.elements.length; i++) {
var importNode = node.importClause.namedBindings.elements[i]; const importNode = node.importClause.namedBindings.elements[i];
if (getColor(importNode) === 2 /* Black */) { if (getColor(importNode) === 2 /* Black */) {
survivingImports.push(importNode.getFullText(sourceFile)); survivingImports.push(importNode.getFullText(sourceFile));
} }
} }
var leadingTriviaWidth = node.getLeadingTriviaWidth(); const leadingTriviaWidth = node.getLeadingTriviaWidth();
var leadingTrivia = sourceFile.text.substr(node.pos, leadingTriviaWidth); const leadingTrivia = sourceFile.text.substr(node.pos, leadingTriviaWidth);
if (survivingImports.length > 0) { if (survivingImports.length > 0) {
if (node.importClause && node.importClause.name && getColor(node.importClause) === 2 /* Black */) { if (node.importClause && node.importClause.name && getColor(node.importClause) === 2 /* Black */) {
return write(leadingTrivia + "import " + node.importClause.name.text + ", {" + survivingImports.join(',') + " } from" + node.moduleSpecifier.getFullText(sourceFile) + ";"); return write(`${leadingTrivia}import ${node.importClause.name.text}, {${survivingImports.join(',')} } from${node.moduleSpecifier.getFullText(sourceFile)};`);
} }
return write(leadingTrivia + "import {" + survivingImports.join(',') + " } from" + node.moduleSpecifier.getFullText(sourceFile) + ";"); return write(`${leadingTrivia}import {${survivingImports.join(',')} } from${node.moduleSpecifier.getFullText(sourceFile)};`);
} }
else { else {
if (node.importClause && node.importClause.name && getColor(node.importClause) === 2 /* Black */) { if (node.importClause && node.importClause.name && getColor(node.importClause) === 2 /* Black */) {
return write(leadingTrivia + "import " + node.importClause.name.text + " from" + node.moduleSpecifier.getFullText(sourceFile) + ";"); return write(`${leadingTrivia}import ${node.importClause.name.text} from${node.moduleSpecifier.getFullText(sourceFile)};`);
} }
} }
} }
@ -509,9 +502,9 @@ function generateResult(languageService, shakeLevel) {
} }
} }
if (shakeLevel === 2 /* ClassMembers */ && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node)) && nodeOrChildIsBlack(node)) { if (shakeLevel === 2 /* ClassMembers */ && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node)) && nodeOrChildIsBlack(node)) {
var toWrite = node.getFullText(); let toWrite = node.getFullText();
for (var i = node.members.length - 1; i >= 0; i--) { for (let i = node.members.length - 1; i >= 0; i--) {
var member = node.members[i]; const member = node.members[i];
if (getColor(member) === 2 /* Black */ || !member.name) { if (getColor(member) === 2 /* Black */ || !member.name) {
// keep method // keep method
continue; continue;
@ -520,8 +513,8 @@ function generateResult(languageService, shakeLevel) {
// TODO: keep all members ending with `Brand`... // TODO: keep all members ending with `Brand`...
continue; continue;
} }
var pos = member.pos - node.pos; let pos = member.pos - node.pos;
var end = member.end - node.pos; let end = member.end - node.pos;
toWrite = toWrite.substring(0, pos) + toWrite.substring(end); toWrite = toWrite.substring(0, pos) + toWrite.substring(end);
} }
return write(toWrite); return write(toWrite);
@ -553,9 +546,9 @@ function generateResult(languageService, shakeLevel) {
* Returns the node's symbol and the `import` node (if the symbol resolved from a different module) * Returns the node's symbol and the `import` node (if the symbol resolved from a different module)
*/ */
function getRealNodeSymbol(checker, node) { function getRealNodeSymbol(checker, node) {
var getPropertySymbolsFromContextualType = ts.getPropertySymbolsFromContextualType; const getPropertySymbolsFromContextualType = ts.getPropertySymbolsFromContextualType;
var getContainingObjectLiteralElement = ts.getContainingObjectLiteralElement; const getContainingObjectLiteralElement = ts.getContainingObjectLiteralElement;
var getNameFromPropertyName = ts.getNameFromPropertyName; const getNameFromPropertyName = ts.getNameFromPropertyName;
// Go to the original declaration for cases: // Go to the original declaration for cases:
// //
// (1) when the aliased symbol was declared in the location(parent). // (1) when the aliased symbol was declared in the location(parent).
@ -583,15 +576,15 @@ function getRealNodeSymbol(checker, node) {
return [null, null]; return [null, null];
} }
} }
var parent = node.parent; const { parent } = node;
var symbol = checker.getSymbolAtLocation(node); let symbol = checker.getSymbolAtLocation(node);
var importNode = null; let importNode = null;
// If this is an alias, and the request came at the declaration location // If this is an alias, and the request came at the declaration location
// get the aliased symbol instead. This allows for goto def on an import e.g. // get the aliased symbol instead. This allows for goto def on an import e.g.
// import {A, B} from "mod"; // import {A, B} from "mod";
// to jump to the implementation directly. // to jump to the implementation directly.
if (symbol && symbol.flags & ts.SymbolFlags.Alias && shouldSkipAlias(node, symbol.declarations[0])) { if (symbol && symbol.flags & ts.SymbolFlags.Alias && shouldSkipAlias(node, symbol.declarations[0])) {
var aliased = checker.getAliasedSymbol(symbol); const aliased = checker.getAliasedSymbol(symbol);
if (aliased.declarations) { if (aliased.declarations) {
// We should mark the import as visited // We should mark the import as visited
importNode = symbol.declarations[0]; importNode = symbol.declarations[0];
@ -620,17 +613,17 @@ function getRealNodeSymbol(checker, node) {
// bar<Test>(({pr/*goto*/op1})=>{}); // bar<Test>(({pr/*goto*/op1})=>{});
if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) &&
(node === (parent.propertyName || parent.name))) { (node === (parent.propertyName || parent.name))) {
var name_1 = getNameFromPropertyName(node); const name = getNameFromPropertyName(node);
var type = checker.getTypeAtLocation(parent.parent); const type = checker.getTypeAtLocation(parent.parent);
if (name_1 && type) { if (name && type) {
if (type.isUnion()) { if (type.isUnion()) {
var prop = type.types[0].getProperty(name_1); const prop = type.types[0].getProperty(name);
if (prop) { if (prop) {
symbol = prop; symbol = prop;
} }
} }
else { else {
var prop = type.getProperty(name_1); const prop = type.getProperty(name);
if (prop) { if (prop) {
symbol = prop; symbol = prop;
} }
@ -646,11 +639,11 @@ function getRealNodeSymbol(checker, node) {
// } // }
// function Foo(arg: Props) {} // function Foo(arg: Props) {}
// Foo( { pr/*1*/op1: 10, prop2: false }) // Foo( { pr/*1*/op1: 10, prop2: false })
var element = getContainingObjectLiteralElement(node); const element = getContainingObjectLiteralElement(node);
if (element) { if (element) {
var contextualType = element && checker.getContextualType(element.parent); const contextualType = element && checker.getContextualType(element.parent);
if (contextualType) { if (contextualType) {
var propertySymbols = getPropertySymbolsFromContextualType(element, checker, contextualType, /*unionSymbolOk*/ false); const propertySymbols = getPropertySymbolsFromContextualType(element, checker, contextualType, /*unionSymbolOk*/ false);
if (propertySymbols) { if (propertySymbols) {
symbol = propertySymbols[0]; symbol = propertySymbols[0];
} }
@ -664,17 +657,16 @@ function getRealNodeSymbol(checker, node) {
} }
/** Get the token whose text contains the position */ /** Get the token whose text contains the position */
function getTokenAtPosition(sourceFile, position, allowPositionInLeadingTrivia, includeEndPosition) { function getTokenAtPosition(sourceFile, position, allowPositionInLeadingTrivia, includeEndPosition) {
var current = sourceFile; let current = sourceFile;
outer: while (true) { outer: while (true) {
// find the child that contains 'position' // find the child that contains 'position'
for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { for (const child of current.getChildren()) {
var child = _a[_i]; const start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true);
var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true);
if (start > position) { if (start > position) {
// If this child begins after position, then all subsequent children will as well. // If this child begins after position, then all subsequent children will as well.
break; break;
} }
var end = child.getEnd(); const end = child.getEnd();
if (position < end || (position === end && (child.kind === ts.SyntaxKind.EndOfFileToken || includeEndPosition))) { if (position < end || (position === end && (child.kind === ts.SyntaxKind.EndOfFileToken || includeEndPosition))) {
current = child; current = child;
continue outer; continue outer;

View file

@ -3,51 +3,30 @@
* Copyright (c) Microsoft Corporation. All rights reserved. * Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var path_1 = require("path"); const path_1 = require("path");
var Lint = require("tslint"); const Lint = require("tslint");
var Rule = /** @class */ (function (_super) { class Rule extends Lint.Rules.AbstractRule {
__extends(Rule, _super); apply(sourceFile) {
function Rule() {
return _super !== null && _super.apply(this, arguments) || this;
}
Rule.prototype.apply = function (sourceFile) {
return this.applyWithWalker(new ImportPatterns(sourceFile, this.getOptions())); return this.applyWithWalker(new ImportPatterns(sourceFile, this.getOptions()));
};
return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
var ImportPatterns = /** @class */ (function (_super) {
__extends(ImportPatterns, _super);
function ImportPatterns(file, opts) {
var _this = _super.call(this, file, opts) || this;
_this.imports = Object.create(null);
return _this;
} }
ImportPatterns.prototype.visitImportDeclaration = function (node) { }
var path = node.moduleSpecifier.getText(); exports.Rule = Rule;
class ImportPatterns extends Lint.RuleWalker {
constructor(file, opts) {
super(file, opts);
this.imports = Object.create(null);
}
visitImportDeclaration(node) {
let path = node.moduleSpecifier.getText();
// remove quotes // remove quotes
path = path.slice(1, -1); path = path.slice(1, -1);
if (path[0] === '.') { if (path[0] === '.') {
path = path_1.join(path_1.dirname(node.getSourceFile().fileName), path); path = path_1.join(path_1.dirname(node.getSourceFile().fileName), path);
} }
if (this.imports[path]) { if (this.imports[path]) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), "Duplicate imports for '" + path + "'.")); this.addFailure(this.createFailure(node.getStart(), node.getWidth(), `Duplicate imports for '${path}'.`));
} }
this.imports[path] = true; this.imports[path] = true;
}; }
return ImportPatterns; }
}(Lint.RuleWalker));

View file

@ -3,82 +3,60 @@
* Copyright (c) Microsoft Corporation. All rights reserved. * Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var ts = require("typescript"); const ts = require("typescript");
var Lint = require("tslint"); const Lint = require("tslint");
var minimatch = require("minimatch"); const minimatch = require("minimatch");
var path_1 = require("path"); const path_1 = require("path");
var Rule = /** @class */ (function (_super) { class Rule extends Lint.Rules.AbstractRule {
__extends(Rule, _super); apply(sourceFile) {
function Rule() { const configs = this.getOptions().ruleArguments;
return _super !== null && _super.apply(this, arguments) || this; for (const config of configs) {
}
Rule.prototype.apply = function (sourceFile) {
var configs = this.getOptions().ruleArguments;
for (var _i = 0, configs_1 = configs; _i < configs_1.length; _i++) {
var config = configs_1[_i];
if (minimatch(sourceFile.fileName, config.target)) { if (minimatch(sourceFile.fileName, config.target)) {
return this.applyWithWalker(new ImportPatterns(sourceFile, this.getOptions(), config)); return this.applyWithWalker(new ImportPatterns(sourceFile, this.getOptions(), config));
} }
} }
return []; return [];
};
return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
var ImportPatterns = /** @class */ (function (_super) {
__extends(ImportPatterns, _super);
function ImportPatterns(file, opts, _config) {
var _this = _super.call(this, file, opts) || this;
_this._config = _config;
return _this;
} }
ImportPatterns.prototype.visitImportEqualsDeclaration = function (node) { }
exports.Rule = Rule;
class ImportPatterns extends Lint.RuleWalker {
constructor(file, opts, _config) {
super(file, opts);
this._config = _config;
}
visitImportEqualsDeclaration(node) {
if (node.moduleReference.kind === ts.SyntaxKind.ExternalModuleReference) { if (node.moduleReference.kind === ts.SyntaxKind.ExternalModuleReference) {
this._validateImport(node.moduleReference.expression.getText(), node); this._validateImport(node.moduleReference.expression.getText(), node);
} }
}; }
ImportPatterns.prototype.visitImportDeclaration = function (node) { visitImportDeclaration(node) {
this._validateImport(node.moduleSpecifier.getText(), node); this._validateImport(node.moduleSpecifier.getText(), node);
}; }
ImportPatterns.prototype.visitCallExpression = function (node) { visitCallExpression(node) {
_super.prototype.visitCallExpression.call(this, node); super.visitCallExpression(node);
// import('foo') statements inside the code // import('foo') statements inside the code
if (node.expression.kind === ts.SyntaxKind.ImportKeyword) { if (node.expression.kind === ts.SyntaxKind.ImportKeyword) {
var path = node.arguments[0]; const [path] = node.arguments;
this._validateImport(path.getText(), node); this._validateImport(path.getText(), node);
} }
}; }
ImportPatterns.prototype._validateImport = function (path, node) { _validateImport(path, node) {
// remove quotes // remove quotes
path = path.slice(1, -1); path = path.slice(1, -1);
// resolve relative paths // resolve relative paths
if (path[0] === '.') { if (path[0] === '.') {
path = path_1.join(this.getSourceFile().fileName, path); path = path_1.join(this.getSourceFile().fileName, path);
} }
var restrictions; let restrictions;
if (typeof this._config.restrictions === 'string') { if (typeof this._config.restrictions === 'string') {
restrictions = [this._config.restrictions]; restrictions = [this._config.restrictions];
} }
else { else {
restrictions = this._config.restrictions; restrictions = this._config.restrictions;
} }
var matched = false; let matched = false;
for (var _i = 0, restrictions_1 = restrictions; _i < restrictions_1.length; _i++) { for (const pattern of restrictions) {
var pattern = restrictions_1[_i];
if (minimatch(path, pattern)) { if (minimatch(path, pattern)) {
matched = true; matched = true;
break; break;
@ -86,8 +64,7 @@ var ImportPatterns = /** @class */ (function (_super) {
} }
if (!matched) { if (!matched) {
// None of the restrictions matched // None of the restrictions matched
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), "Imports violates '" + restrictions.join(' or ') + "' restrictions. See https://github.com/Microsoft/vscode/wiki/Code-Organization")); this.addFailure(this.createFailure(node.getStart(), node.getWidth(), `Imports violates '${restrictions.join(' or ')}' restrictions. See https://github.com/Microsoft/vscode/wiki/Code-Organization`));
} }
}; }
return ImportPatterns; }
}(Lint.RuleWalker));

View file

@ -3,39 +3,22 @@
* Copyright (c) Microsoft Corporation. All rights reserved. * Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var ts = require("typescript"); const ts = require("typescript");
var Lint = require("tslint"); const Lint = require("tslint");
var path_1 = require("path"); const path_1 = require("path");
var Rule = /** @class */ (function (_super) { class Rule extends Lint.Rules.AbstractRule {
__extends(Rule, _super); apply(sourceFile) {
function Rule() { const parts = path_1.dirname(sourceFile.fileName).split(/\\|\//);
return _super !== null && _super.apply(this, arguments) || this; const ruleArgs = this.getOptions().ruleArguments[0];
} let config;
Rule.prototype.apply = function (sourceFile) { for (let i = parts.length - 1; i >= 0; i--) {
var parts = path_1.dirname(sourceFile.fileName).split(/\\|\//);
var ruleArgs = this.getOptions().ruleArguments[0];
var config;
for (var i = parts.length - 1; i >= 0; i--) {
if (ruleArgs[parts[i]]) { if (ruleArgs[parts[i]]) {
config = { config = {
allowed: new Set(ruleArgs[parts[i]]).add(parts[i]), allowed: new Set(ruleArgs[parts[i]]).add(parts[i]),
disallowed: new Set() disallowed: new Set()
}; };
Object.keys(ruleArgs).forEach(function (key) { Object.keys(ruleArgs).forEach(key => {
if (!config.allowed.has(key)) { if (!config.allowed.has(key)) {
config.disallowed.add(key); config.disallowed.add(key);
} }
@ -47,58 +30,54 @@ var Rule = /** @class */ (function (_super) {
return []; return [];
} }
return this.applyWithWalker(new LayeringRule(sourceFile, config, this.getOptions())); return this.applyWithWalker(new LayeringRule(sourceFile, config, this.getOptions()));
};
return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
var LayeringRule = /** @class */ (function (_super) {
__extends(LayeringRule, _super);
function LayeringRule(file, config, opts) {
var _this = _super.call(this, file, opts) || this;
_this._config = config;
return _this;
} }
LayeringRule.prototype.visitImportEqualsDeclaration = function (node) { }
exports.Rule = Rule;
class LayeringRule extends Lint.RuleWalker {
constructor(file, config, opts) {
super(file, opts);
this._config = config;
}
visitImportEqualsDeclaration(node) {
if (node.moduleReference.kind === ts.SyntaxKind.ExternalModuleReference) { if (node.moduleReference.kind === ts.SyntaxKind.ExternalModuleReference) {
this._validateImport(node.moduleReference.expression.getText(), node); this._validateImport(node.moduleReference.expression.getText(), node);
} }
}; }
LayeringRule.prototype.visitImportDeclaration = function (node) { visitImportDeclaration(node) {
this._validateImport(node.moduleSpecifier.getText(), node); this._validateImport(node.moduleSpecifier.getText(), node);
}; }
LayeringRule.prototype.visitCallExpression = function (node) { visitCallExpression(node) {
_super.prototype.visitCallExpression.call(this, node); super.visitCallExpression(node);
// import('foo') statements inside the code // import('foo') statements inside the code
if (node.expression.kind === ts.SyntaxKind.ImportKeyword) { if (node.expression.kind === ts.SyntaxKind.ImportKeyword) {
var path = node.arguments[0]; const [path] = node.arguments;
this._validateImport(path.getText(), node); this._validateImport(path.getText(), node);
} }
}; }
LayeringRule.prototype._validateImport = function (path, node) { _validateImport(path, node) {
// remove quotes // remove quotes
path = path.slice(1, -1); path = path.slice(1, -1);
if (path[0] === '.') { if (path[0] === '.') {
path = path_1.join(path_1.dirname(node.getSourceFile().fileName), path); path = path_1.join(path_1.dirname(node.getSourceFile().fileName), path);
} }
var parts = path_1.dirname(path).split(/\\|\//); const parts = path_1.dirname(path).split(/\\|\//);
for (var i = parts.length - 1; i >= 0; i--) { for (let i = parts.length - 1; i >= 0; i--) {
var part = parts[i]; const part = parts[i];
if (this._config.allowed.has(part)) { if (this._config.allowed.has(part)) {
// GOOD - same layer // GOOD - same layer
return; return;
} }
if (this._config.disallowed.has(part)) { if (this._config.disallowed.has(part)) {
// BAD - wrong layer // BAD - wrong layer
var message = "Bad layering. You are not allowed to access '" + part + "' from here, allowed layers are: [" + LayeringRule._print(this._config.allowed) + "]"; const message = `Bad layering. You are not allowed to access '${part}' from here, allowed layers are: [${LayeringRule._print(this._config.allowed)}]`;
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), message)); this.addFailure(this.createFailure(node.getStart(), node.getWidth(), message));
return; return;
} }
} }
}; }
LayeringRule._print = function (set) { static _print(set) {
var r = []; const r = [];
set.forEach(function (e) { return r.push(e); }); set.forEach(e => r.push(e));
return r.join(', '); return r.join(', ');
}; }
return LayeringRule; }
}(Lint.RuleWalker));

View file

@ -3,60 +3,41 @@
* Copyright (c) Microsoft Corporation. All rights reserved. * Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var ts = require("typescript"); const ts = require("typescript");
var Lint = require("tslint"); const Lint = require("tslint");
var path_1 = require("path"); const path_1 = require("path");
var Rule = /** @class */ (function (_super) { class Rule extends Lint.Rules.AbstractRule {
__extends(Rule, _super); apply(sourceFile) {
function Rule() {
return _super !== null && _super.apply(this, arguments) || this;
}
Rule.prototype.apply = function (sourceFile) {
if (/vs(\/|\\)editor/.test(sourceFile.fileName)) { if (/vs(\/|\\)editor/.test(sourceFile.fileName)) {
// the vs/editor folder is allowed to use the standalone editor // the vs/editor folder is allowed to use the standalone editor
return []; return [];
} }
return this.applyWithWalker(new NoStandaloneEditorRuleWalker(sourceFile, this.getOptions())); return this.applyWithWalker(new NoStandaloneEditorRuleWalker(sourceFile, this.getOptions()));
};
return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
var NoStandaloneEditorRuleWalker = /** @class */ (function (_super) {
__extends(NoStandaloneEditorRuleWalker, _super);
function NoStandaloneEditorRuleWalker(file, opts) {
return _super.call(this, file, opts) || this;
} }
NoStandaloneEditorRuleWalker.prototype.visitImportEqualsDeclaration = function (node) { }
exports.Rule = Rule;
class NoStandaloneEditorRuleWalker extends Lint.RuleWalker {
constructor(file, opts) {
super(file, opts);
}
visitImportEqualsDeclaration(node) {
if (node.moduleReference.kind === ts.SyntaxKind.ExternalModuleReference) { if (node.moduleReference.kind === ts.SyntaxKind.ExternalModuleReference) {
this._validateImport(node.moduleReference.expression.getText(), node); this._validateImport(node.moduleReference.expression.getText(), node);
} }
}; }
NoStandaloneEditorRuleWalker.prototype.visitImportDeclaration = function (node) { visitImportDeclaration(node) {
this._validateImport(node.moduleSpecifier.getText(), node); this._validateImport(node.moduleSpecifier.getText(), node);
}; }
NoStandaloneEditorRuleWalker.prototype.visitCallExpression = function (node) { visitCallExpression(node) {
_super.prototype.visitCallExpression.call(this, node); super.visitCallExpression(node);
// import('foo') statements inside the code // import('foo') statements inside the code
if (node.expression.kind === ts.SyntaxKind.ImportKeyword) { if (node.expression.kind === ts.SyntaxKind.ImportKeyword) {
var path = node.arguments[0]; const [path] = node.arguments;
this._validateImport(path.getText(), node); this._validateImport(path.getText(), node);
} }
}; }
NoStandaloneEditorRuleWalker.prototype._validateImport = function (path, node) { _validateImport(path, node) {
// remove quotes // remove quotes
path = path.slice(1, -1); path = path.slice(1, -1);
// resolve relative paths // resolve relative paths
@ -68,8 +49,7 @@ var NoStandaloneEditorRuleWalker = /** @class */ (function (_super) {
|| /vs(\/|\\)editor(\/|\\)editor.api/.test(path) || /vs(\/|\\)editor(\/|\\)editor.api/.test(path)
|| /vs(\/|\\)editor(\/|\\)editor.main/.test(path) || /vs(\/|\\)editor(\/|\\)editor.main/.test(path)
|| /vs(\/|\\)editor(\/|\\)editor.worker/.test(path)) { || /vs(\/|\\)editor(\/|\\)editor.worker/.test(path)) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), "Not allowed to import standalone editor modules. See https://github.com/Microsoft/vscode/wiki/Code-Organization")); this.addFailure(this.createFailure(node.getStart(), node.getWidth(), `Not allowed to import standalone editor modules. See https://github.com/Microsoft/vscode/wiki/Code-Organization`));
} }
}; }
return NoStandaloneEditorRuleWalker; }
}(Lint.RuleWalker));

View file

@ -3,35 +3,17 @@
* Copyright (c) Microsoft Corporation. All rights reserved. * Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var ts = require("typescript"); const ts = require("typescript");
var Lint = require("tslint"); const Lint = require("tslint");
/** /**
* Implementation of the no-unexternalized-strings rule. * Implementation of the no-unexternalized-strings rule.
*/ */
var Rule = /** @class */ (function (_super) { class Rule extends Lint.Rules.AbstractRule {
__extends(Rule, _super); apply(sourceFile) {
function Rule() {
return _super !== null && _super.apply(this, arguments) || this;
}
Rule.prototype.apply = function (sourceFile) {
return this.applyWithWalker(new NoUnexternalizedStringsRuleWalker(sourceFile, this.getOptions())); return this.applyWithWalker(new NoUnexternalizedStringsRuleWalker(sourceFile, this.getOptions()));
}; }
return Rule; }
}(Lint.Rules.AbstractRule));
exports.Rule = Rule; exports.Rule = Rule;
function isStringLiteral(node) { function isStringLiteral(node) {
return node && node.kind === ts.SyntaxKind.StringLiteral; return node && node.kind === ts.SyntaxKind.StringLiteral;
@ -42,73 +24,70 @@ function isObjectLiteral(node) {
function isPropertyAssignment(node) { function isPropertyAssignment(node) {
return node && node.kind === ts.SyntaxKind.PropertyAssignment; return node && node.kind === ts.SyntaxKind.PropertyAssignment;
} }
var NoUnexternalizedStringsRuleWalker = /** @class */ (function (_super) { class NoUnexternalizedStringsRuleWalker extends Lint.RuleWalker {
__extends(NoUnexternalizedStringsRuleWalker, _super); constructor(file, opts) {
function NoUnexternalizedStringsRuleWalker(file, opts) { super(file, opts);
var _this = _super.call(this, file, opts) || this; this.signatures = Object.create(null);
_this.signatures = Object.create(null); this.ignores = Object.create(null);
_this.ignores = Object.create(null); this.messageIndex = undefined;
_this.messageIndex = undefined; this.keyIndex = undefined;
_this.keyIndex = undefined; this.usedKeys = Object.create(null);
_this.usedKeys = Object.create(null); const options = this.getOptions();
var options = _this.getOptions(); const first = options && options.length > 0 ? options[0] : null;
var first = options && options.length > 0 ? options[0] : null;
if (first) { if (first) {
if (Array.isArray(first.signatures)) { if (Array.isArray(first.signatures)) {
first.signatures.forEach(function (signature) { return _this.signatures[signature] = true; }); first.signatures.forEach((signature) => this.signatures[signature] = true);
} }
if (Array.isArray(first.ignores)) { if (Array.isArray(first.ignores)) {
first.ignores.forEach(function (ignore) { return _this.ignores[ignore] = true; }); first.ignores.forEach((ignore) => this.ignores[ignore] = true);
} }
if (typeof first.messageIndex !== 'undefined') { if (typeof first.messageIndex !== 'undefined') {
_this.messageIndex = first.messageIndex; this.messageIndex = first.messageIndex;
} }
if (typeof first.keyIndex !== 'undefined') { if (typeof first.keyIndex !== 'undefined') {
_this.keyIndex = first.keyIndex; this.keyIndex = first.keyIndex;
} }
} }
return _this;
} }
NoUnexternalizedStringsRuleWalker.prototype.visitSourceFile = function (node) { visitSourceFile(node) {
var _this = this; super.visitSourceFile(node);
_super.prototype.visitSourceFile.call(this, node); Object.keys(this.usedKeys).forEach(key => {
Object.keys(this.usedKeys).forEach(function (key) { const occurrences = this.usedKeys[key];
var occurrences = _this.usedKeys[key];
if (occurrences.length > 1) { if (occurrences.length > 1) {
occurrences.forEach(function (occurrence) { occurrences.forEach(occurrence => {
_this.addFailure((_this.createFailure(occurrence.key.getStart(), occurrence.key.getWidth(), "Duplicate key " + occurrence.key.getText() + " with different message value."))); this.addFailure((this.createFailure(occurrence.key.getStart(), occurrence.key.getWidth(), `Duplicate key ${occurrence.key.getText()} with different message value.`)));
}); });
} }
}); });
}; }
NoUnexternalizedStringsRuleWalker.prototype.visitStringLiteral = function (node) { visitStringLiteral(node) {
this.checkStringLiteral(node); this.checkStringLiteral(node);
_super.prototype.visitStringLiteral.call(this, node); super.visitStringLiteral(node);
}; }
NoUnexternalizedStringsRuleWalker.prototype.checkStringLiteral = function (node) { checkStringLiteral(node) {
var text = node.getText(); const text = node.getText();
var doubleQuoted = text.length >= 2 && text[0] === NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE && text[text.length - 1] === NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE; const doubleQuoted = text.length >= 2 && text[0] === NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE && text[text.length - 1] === NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE;
var info = this.findDescribingParent(node); const info = this.findDescribingParent(node);
// Ignore strings in import and export nodes. // Ignore strings in import and export nodes.
if (info && info.isImport && doubleQuoted) { if (info && info.isImport && doubleQuoted) {
var fix = [ const fix = [
Lint.Replacement.replaceFromTo(node.getStart(), 1, '\''), Lint.Replacement.replaceFromTo(node.getStart(), 1, '\''),
Lint.Replacement.replaceFromTo(node.getStart() + text.length - 1, 1, '\''), Lint.Replacement.replaceFromTo(node.getStart() + text.length - 1, 1, '\''),
]; ];
this.addFailureAtNode(node, NoUnexternalizedStringsRuleWalker.ImportFailureMessage, fix); this.addFailureAtNode(node, NoUnexternalizedStringsRuleWalker.ImportFailureMessage, fix);
return; return;
} }
var callInfo = info ? info.callInfo : null; const callInfo = info ? info.callInfo : null;
var functionName = callInfo ? callInfo.callExpression.expression.getText() : null; const functionName = callInfo ? callInfo.callExpression.expression.getText() : null;
if (functionName && this.ignores[functionName]) { if (functionName && this.ignores[functionName]) {
return; return;
} }
if (doubleQuoted && (!callInfo || callInfo.argIndex === -1 || !this.signatures[functionName])) { if (doubleQuoted && (!callInfo || callInfo.argIndex === -1 || !this.signatures[functionName])) {
var s = node.getText(); const s = node.getText();
var fix = [ const fix = [
Lint.Replacement.replaceFromTo(node.getStart(), node.getWidth(), "nls.localize('KEY-" + s.substring(1, s.length - 1) + "', " + s + ")"), Lint.Replacement.replaceFromTo(node.getStart(), node.getWidth(), `nls.localize('KEY-${s.substring(1, s.length - 1)}', ${s})`),
]; ];
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), "Unexternalized string found: " + node.getText(), fix)); this.addFailure(this.createFailure(node.getStart(), node.getWidth(), `Unexternalized string found: ${node.getText()}`, fix));
return; return;
} }
// We have a single quoted string outside a localize function name. // We have a single quoted string outside a localize function name.
@ -116,7 +95,7 @@ var NoUnexternalizedStringsRuleWalker = /** @class */ (function (_super) {
return; return;
} }
// We have a string that is a direct argument into the localize call. // We have a string that is a direct argument into the localize call.
var keyArg = callInfo && callInfo.argIndex === this.keyIndex const keyArg = callInfo && callInfo.argIndex === this.keyIndex
? callInfo.callExpression.arguments[this.keyIndex] ? callInfo.callExpression.arguments[this.keyIndex]
: null; : null;
if (keyArg) { if (keyArg) {
@ -124,12 +103,12 @@ var NoUnexternalizedStringsRuleWalker = /** @class */ (function (_super) {
this.recordKey(keyArg, this.messageIndex && callInfo ? callInfo.callExpression.arguments[this.messageIndex] : undefined); this.recordKey(keyArg, this.messageIndex && callInfo ? callInfo.callExpression.arguments[this.messageIndex] : undefined);
} }
else if (isObjectLiteral(keyArg)) { else if (isObjectLiteral(keyArg)) {
for (var i = 0; i < keyArg.properties.length; i++) { for (let i = 0; i < keyArg.properties.length; i++) {
var property = keyArg.properties[i]; const property = keyArg.properties[i];
if (isPropertyAssignment(property)) { if (isPropertyAssignment(property)) {
var name_1 = property.name.getText(); const name = property.name.getText();
if (name_1 === 'key') { if (name === 'key') {
var initializer = property.initializer; const initializer = property.initializer;
if (isStringLiteral(initializer)) { if (isStringLiteral(initializer)) {
this.recordKey(initializer, this.messageIndex && callInfo ? callInfo.callExpression.arguments[this.messageIndex] : undefined); this.recordKey(initializer, this.messageIndex && callInfo ? callInfo.callExpression.arguments[this.messageIndex] : undefined);
} }
@ -139,42 +118,42 @@ var NoUnexternalizedStringsRuleWalker = /** @class */ (function (_super) {
} }
} }
} }
var messageArg = callInfo.callExpression.arguments[this.messageIndex]; const messageArg = callInfo.callExpression.arguments[this.messageIndex];
if (messageArg && messageArg.kind !== ts.SyntaxKind.StringLiteral) { if (messageArg && messageArg.kind !== ts.SyntaxKind.StringLiteral) {
this.addFailure(this.createFailure(messageArg.getStart(), messageArg.getWidth(), "Message argument to '" + callInfo.callExpression.expression.getText() + "' must be a string literal.")); this.addFailure(this.createFailure(messageArg.getStart(), messageArg.getWidth(), `Message argument to '${callInfo.callExpression.expression.getText()}' must be a string literal.`));
return; return;
} }
}; }
NoUnexternalizedStringsRuleWalker.prototype.recordKey = function (keyNode, messageNode) { recordKey(keyNode, messageNode) {
var text = keyNode.getText(); const text = keyNode.getText();
// We have an empty key // We have an empty key
if (text.match(/(['"]) *\1/)) { if (text.match(/(['"]) *\1/)) {
if (messageNode) { if (messageNode) {
this.addFailureAtNode(keyNode, "Key is empty for message: " + messageNode.getText()); this.addFailureAtNode(keyNode, `Key is empty for message: ${messageNode.getText()}`);
} }
else { else {
this.addFailureAtNode(keyNode, "Key is empty."); this.addFailureAtNode(keyNode, `Key is empty.`);
} }
return; return;
} }
var occurrences = this.usedKeys[text]; let occurrences = this.usedKeys[text];
if (!occurrences) { if (!occurrences) {
occurrences = []; occurrences = [];
this.usedKeys[text] = occurrences; this.usedKeys[text] = occurrences;
} }
if (messageNode) { if (messageNode) {
if (occurrences.some(function (pair) { return pair.message ? pair.message.getText() === messageNode.getText() : false; })) { if (occurrences.some(pair => pair.message ? pair.message.getText() === messageNode.getText() : false)) {
return; return;
} }
} }
occurrences.push({ key: keyNode, message: messageNode }); occurrences.push({ key: keyNode, message: messageNode });
}; }
NoUnexternalizedStringsRuleWalker.prototype.findDescribingParent = function (node) { findDescribingParent(node) {
var parent; let parent;
while ((parent = node.parent)) { while ((parent = node.parent)) {
var kind = parent.kind; const kind = parent.kind;
if (kind === ts.SyntaxKind.CallExpression) { if (kind === ts.SyntaxKind.CallExpression) {
var callExpression = parent; const callExpression = parent;
return { callInfo: { callExpression: callExpression, argIndex: callExpression.arguments.indexOf(node) } }; return { callInfo: { callExpression: callExpression, argIndex: callExpression.arguments.indexOf(node) } };
} }
else if (kind === ts.SyntaxKind.ImportEqualsDeclaration || kind === ts.SyntaxKind.ImportDeclaration || kind === ts.SyntaxKind.ExportDeclaration) { else if (kind === ts.SyntaxKind.ImportEqualsDeclaration || kind === ts.SyntaxKind.ImportDeclaration || kind === ts.SyntaxKind.ExportDeclaration) {
@ -189,8 +168,7 @@ var NoUnexternalizedStringsRuleWalker = /** @class */ (function (_super) {
node = parent; node = parent;
} }
return null; return null;
}; }
NoUnexternalizedStringsRuleWalker.ImportFailureMessage = 'Do not use double quotes for imports.'; }
NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE = '"'; NoUnexternalizedStringsRuleWalker.ImportFailureMessage = 'Do not use double quotes for imports.';
return NoUnexternalizedStringsRuleWalker; NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE = '"';
}(Lint.RuleWalker));

View file

@ -3,62 +3,43 @@
* Copyright (c) Microsoft Corporation. All rights reserved. * Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var Lint = require("tslint"); const Lint = require("tslint");
var fs = require("fs"); const fs = require("fs");
var Rule = /** @class */ (function (_super) { class Rule extends Lint.Rules.AbstractRule {
__extends(Rule, _super); apply(sourceFile) {
function Rule() {
return _super !== null && _super.apply(this, arguments) || this;
}
Rule.prototype.apply = function (sourceFile) {
return this.applyWithWalker(new TranslationRemindRuleWalker(sourceFile, this.getOptions())); return this.applyWithWalker(new TranslationRemindRuleWalker(sourceFile, this.getOptions()));
};
return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
var TranslationRemindRuleWalker = /** @class */ (function (_super) {
__extends(TranslationRemindRuleWalker, _super);
function TranslationRemindRuleWalker(file, opts) {
return _super.call(this, file, opts) || this;
} }
TranslationRemindRuleWalker.prototype.visitImportDeclaration = function (node) { }
var declaration = node.moduleSpecifier.getText(); exports.Rule = Rule;
if (declaration !== "'" + TranslationRemindRuleWalker.NLS_MODULE + "'") { class TranslationRemindRuleWalker extends Lint.RuleWalker {
constructor(file, opts) {
super(file, opts);
}
visitImportDeclaration(node) {
const declaration = node.moduleSpecifier.getText();
if (declaration !== `'${TranslationRemindRuleWalker.NLS_MODULE}'`) {
return; return;
} }
this.visitImportLikeDeclaration(node); this.visitImportLikeDeclaration(node);
}; }
TranslationRemindRuleWalker.prototype.visitImportEqualsDeclaration = function (node) { visitImportEqualsDeclaration(node) {
var reference = node.moduleReference.getText(); const reference = node.moduleReference.getText();
if (reference !== "require('" + TranslationRemindRuleWalker.NLS_MODULE + "')") { if (reference !== `require('${TranslationRemindRuleWalker.NLS_MODULE}')`) {
return; return;
} }
this.visitImportLikeDeclaration(node); this.visitImportLikeDeclaration(node);
}; }
TranslationRemindRuleWalker.prototype.visitImportLikeDeclaration = function (node) { visitImportLikeDeclaration(node) {
var currentFile = node.getSourceFile().fileName; const currentFile = node.getSourceFile().fileName;
var matchService = currentFile.match(/vs\/workbench\/services\/\w+/); const matchService = currentFile.match(/vs\/workbench\/services\/\w+/);
var matchPart = currentFile.match(/vs\/workbench\/parts\/\w+/); const matchPart = currentFile.match(/vs\/workbench\/parts\/\w+/);
if (!matchService && !matchPart) { if (!matchService && !matchPart) {
return; return;
} }
var resource = matchService ? matchService[0] : matchPart[0]; const resource = matchService ? matchService[0] : matchPart[0];
var resourceDefined = false; let resourceDefined = false;
var json; let json;
try { try {
json = fs.readFileSync('./build/lib/i18n.resources.json', 'utf8'); json = fs.readFileSync('./build/lib/i18n.resources.json', 'utf8');
} }
@ -66,17 +47,16 @@ var TranslationRemindRuleWalker = /** @class */ (function (_super) {
console.error('[translation-remind rule]: File with resources to pull from Transifex was not found. Aborting translation resource check for newly defined workbench part/service.'); console.error('[translation-remind rule]: File with resources to pull from Transifex was not found. Aborting translation resource check for newly defined workbench part/service.');
return; return;
} }
var workbenchResources = JSON.parse(json).workbench; const workbenchResources = JSON.parse(json).workbench;
workbenchResources.forEach(function (existingResource) { workbenchResources.forEach((existingResource) => {
if (existingResource.name === resource) { if (existingResource.name === resource) {
resourceDefined = true; resourceDefined = true;
return; return;
} }
}); });
if (!resourceDefined) { if (!resourceDefined) {
this.addFailureAtNode(node, "Please add '" + resource + "' to ./build/lib/i18n.resources.json file to use translations here."); this.addFailureAtNode(node, `Please add '${resource}' to ./build/lib/i18n.resources.json file to use translations here.`);
} }
}; }
TranslationRemindRuleWalker.NLS_MODULE = 'vs/nls'; }
return TranslationRemindRuleWalker; TranslationRemindRuleWalker.NLS_MODULE = 'vs/nls';
}(Lint.RuleWalker));

View file

@ -1,4 +0,0 @@
declare module 'object-assign' {
function fn(target: any, ...sources: any[]): any;
export = fn;
}

View file

@ -4,29 +4,29 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var es = require("event-stream"); const es = require("event-stream");
var debounce = require("debounce"); const debounce = require("debounce");
var _filter = require("gulp-filter"); const _filter = require("gulp-filter");
var rename = require("gulp-rename"); const rename = require("gulp-rename");
var _ = require("underscore"); const _ = require("underscore");
var path = require("path"); const path = require("path");
var fs = require("fs"); const fs = require("fs");
var _rimraf = require("rimraf"); const _rimraf = require("rimraf");
var git = require("./git"); const git = require("./git");
var VinylFile = require("vinyl"); const VinylFile = require("vinyl");
var NoCancellationToken = { isCancellationRequested: function () { return false; } }; const NoCancellationToken = { isCancellationRequested: () => false };
function incremental(streamProvider, initial, supportsCancellation) { function incremental(streamProvider, initial, supportsCancellation) {
var input = es.through(); const input = es.through();
var output = es.through(); const output = es.through();
var state = 'idle'; let state = 'idle';
var buffer = Object.create(null); let buffer = Object.create(null);
var token = !supportsCancellation ? undefined : { isCancellationRequested: function () { return Object.keys(buffer).length > 0; } }; const token = !supportsCancellation ? undefined : { isCancellationRequested: () => Object.keys(buffer).length > 0 };
var run = function (input, isCancellable) { const run = (input, isCancellable) => {
state = 'running'; state = 'running';
var stream = !supportsCancellation ? streamProvider() : streamProvider(isCancellable ? token : NoCancellationToken); const stream = !supportsCancellation ? streamProvider() : streamProvider(isCancellable ? token : NoCancellationToken);
input input
.pipe(stream) .pipe(stream)
.pipe(es.through(undefined, function () { .pipe(es.through(undefined, () => {
state = 'idle'; state = 'idle';
eventuallyRun(); eventuallyRun();
})) }))
@ -35,16 +35,16 @@ function incremental(streamProvider, initial, supportsCancellation) {
if (initial) { if (initial) {
run(initial, false); run(initial, false);
} }
var eventuallyRun = debounce(function () { const eventuallyRun = debounce(() => {
var paths = Object.keys(buffer); const paths = Object.keys(buffer);
if (paths.length === 0) { if (paths.length === 0) {
return; return;
} }
var data = paths.map(function (path) { return buffer[path]; }); const data = paths.map(path => buffer[path]);
buffer = Object.create(null); buffer = Object.create(null);
run(es.readArray(data), true); run(es.readArray(data), true);
}, 500); }, 500);
input.on('data', function (f) { input.on('data', (f) => {
buffer[f.path] = f; buffer[f.path] = f;
if (state === 'idle') { if (state === 'idle') {
eventuallyRun(); eventuallyRun();
@ -57,7 +57,7 @@ function fixWin32DirectoryPermissions() {
if (!/win32/.test(process.platform)) { if (!/win32/.test(process.platform)) {
return es.through(); return es.through();
} }
return es.mapSync(function (f) { return es.mapSync(f => {
if (f.stat && f.stat.isDirectory && f.stat.isDirectory()) { if (f.stat && f.stat.isDirectory && f.stat.isDirectory()) {
f.stat.mode = 16877; f.stat.mode = 16877;
} }
@ -66,16 +66,16 @@ function fixWin32DirectoryPermissions() {
} }
exports.fixWin32DirectoryPermissions = fixWin32DirectoryPermissions; exports.fixWin32DirectoryPermissions = fixWin32DirectoryPermissions;
function setExecutableBit(pattern) { function setExecutableBit(pattern) {
var setBit = es.mapSync(function (f) { const setBit = es.mapSync(f => {
f.stat.mode = /* 100755 */ 33261; f.stat.mode = /* 100755 */ 33261;
return f; return f;
}); });
if (!pattern) { if (!pattern) {
return setBit; return setBit;
} }
var input = es.through(); const input = es.through();
var filter = _filter(pattern, { restore: true }); const filter = _filter(pattern, { restore: true });
var output = input const output = input
.pipe(filter) .pipe(filter)
.pipe(setBit) .pipe(setBit)
.pipe(filter.restore); .pipe(filter.restore);
@ -83,7 +83,7 @@ function setExecutableBit(pattern) {
} }
exports.setExecutableBit = setExecutableBit; exports.setExecutableBit = setExecutableBit;
function toFileUri(filePath) { function toFileUri(filePath) {
var match = filePath.match(/^([a-z])\:(.*)$/i); const match = filePath.match(/^([a-z])\:(.*)$/i);
if (match) { if (match) {
filePath = '/' + match[1].toUpperCase() + ':' + match[2]; filePath = '/' + match[1].toUpperCase() + ':' + match[2];
} }
@ -91,7 +91,7 @@ function toFileUri(filePath) {
} }
exports.toFileUri = toFileUri; exports.toFileUri = toFileUri;
function skipDirectories() { function skipDirectories() {
return es.mapSync(function (f) { return es.mapSync(f => {
if (!f.isDirectory()) { if (!f.isDirectory()) {
return f; return f;
} }
@ -99,15 +99,15 @@ function skipDirectories() {
} }
exports.skipDirectories = skipDirectories; exports.skipDirectories = skipDirectories;
function cleanNodeModule(name, excludes, includes) { function cleanNodeModule(name, excludes, includes) {
var toGlob = function (path) { return '**/node_modules/' + name + (path ? '/' + path : ''); }; const toGlob = (path) => '**/node_modules/' + name + (path ? '/' + path : '');
var negate = function (str) { return '!' + str; }; const negate = (str) => '!' + str;
var allFilter = _filter(toGlob('**'), { restore: true }); const allFilter = _filter(toGlob('**'), { restore: true });
var globs = [toGlob('**')].concat(excludes.map(_.compose(negate, toGlob))); const globs = [toGlob('**')].concat(excludes.map(_.compose(negate, toGlob)));
var input = es.through(); const input = es.through();
var nodeModuleInput = input.pipe(allFilter); const nodeModuleInput = input.pipe(allFilter);
var output = nodeModuleInput.pipe(_filter(globs)); let output = nodeModuleInput.pipe(_filter(globs));
if (includes) { if (includes) {
var includeGlobs = includes.map(toGlob); const includeGlobs = includes.map(toGlob);
output = es.merge(output, nodeModuleInput.pipe(_filter(includeGlobs))); output = es.merge(output, nodeModuleInput.pipe(_filter(includeGlobs)));
} }
output = output.pipe(allFilter.restore); output = output.pipe(allFilter.restore);
@ -115,9 +115,9 @@ function cleanNodeModule(name, excludes, includes) {
} }
exports.cleanNodeModule = cleanNodeModule; exports.cleanNodeModule = cleanNodeModule;
function loadSourcemaps() { function loadSourcemaps() {
var input = es.through(); const input = es.through();
var output = input const output = input
.pipe(es.map(function (f, cb) { .pipe(es.map((f, cb) => {
if (f.sourceMap) { if (f.sourceMap) {
cb(undefined, f); cb(undefined, f);
return; return;
@ -126,10 +126,10 @@ function loadSourcemaps() {
cb(new Error('empty file')); cb(new Error('empty file'));
return; return;
} }
var contents = f.contents.toString('utf8'); const contents = f.contents.toString('utf8');
var reg = /\/\/# sourceMappingURL=(.*)$/g; const reg = /\/\/# sourceMappingURL=(.*)$/g;
var lastMatch = null; let lastMatch = null;
var match = null; let match = null;
while (match = reg.exec(contents)) { while (match = reg.exec(contents)) {
lastMatch = match; lastMatch = match;
} }
@ -145,7 +145,7 @@ function loadSourcemaps() {
return; return;
} }
f.contents = Buffer.from(contents.replace(/\/\/# sourceMappingURL=(.*)$/g, ''), 'utf8'); f.contents = Buffer.from(contents.replace(/\/\/# sourceMappingURL=(.*)$/g, ''), 'utf8');
fs.readFile(path.join(path.dirname(f.path), lastMatch[1]), 'utf8', function (err, contents) { fs.readFile(path.join(path.dirname(f.path), lastMatch[1]), 'utf8', (err, contents) => {
if (err) { if (err) {
return cb(err); return cb(err);
} }
@ -157,10 +157,10 @@ function loadSourcemaps() {
} }
exports.loadSourcemaps = loadSourcemaps; exports.loadSourcemaps = loadSourcemaps;
function stripSourceMappingURL() { function stripSourceMappingURL() {
var input = es.through(); const input = es.through();
var output = input const output = input
.pipe(es.mapSync(function (f) { .pipe(es.mapSync(f => {
var contents = f.contents.toString('utf8'); const contents = f.contents.toString('utf8');
f.contents = Buffer.from(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, ''), 'utf8'); f.contents = Buffer.from(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, ''), 'utf8');
return f; return f;
})); }));
@ -168,23 +168,23 @@ function stripSourceMappingURL() {
} }
exports.stripSourceMappingURL = stripSourceMappingURL; exports.stripSourceMappingURL = stripSourceMappingURL;
function rimraf(dir) { function rimraf(dir) {
var retries = 0; let retries = 0;
var retry = function (cb) { const retry = (cb) => {
_rimraf(dir, { maxBusyTries: 1 }, function (err) { _rimraf(dir, { maxBusyTries: 1 }, (err) => {
if (!err) { if (!err) {
return cb(); return cb();
} }
if (err.code === 'ENOTEMPTY' && ++retries < 5) { if (err.code === 'ENOTEMPTY' && ++retries < 5) {
return setTimeout(function () { return retry(cb); }, 10); return setTimeout(() => retry(cb), 10);
} }
return cb(err); return cb(err);
}); });
}; };
return function (cb) { return retry(cb); }; return cb => retry(cb);
} }
exports.rimraf = rimraf; exports.rimraf = rimraf;
function getVersion(root) { function getVersion(root) {
var version = process.env['BUILD_SOURCEVERSION']; let version = process.env['BUILD_SOURCEVERSION'];
if (!version || !/^[0-9a-f]{40}$/i.test(version)) { if (!version || !/^[0-9a-f]{40}$/i.test(version)) {
version = git.getVersion(root); version = git.getVersion(root);
} }
@ -192,14 +192,14 @@ function getVersion(root) {
} }
exports.getVersion = getVersion; exports.getVersion = getVersion;
function rebase(count) { function rebase(count) {
return rename(function (f) { return rename(f => {
var parts = f.dirname ? f.dirname.split(/[\/\\]/) : []; const parts = f.dirname ? f.dirname.split(/[\/\\]/) : [];
f.dirname = parts.slice(count).join(path.sep); f.dirname = parts.slice(count).join(path.sep);
}); });
} }
exports.rebase = rebase; exports.rebase = rebase;
function filter(fn) { function filter(fn) {
var result = es.through(function (data) { const result = es.through(function (data) {
if (fn(data)) { if (fn(data)) {
this.emit('data', data); this.emit('data', data);
} }
@ -212,8 +212,8 @@ function filter(fn) {
} }
exports.filter = filter; exports.filter = filter;
function versionStringToNumber(versionStr) { function versionStringToNumber(versionStr) {
var semverRegex = /(\d+)\.(\d+)\.(\d+)/; const semverRegex = /(\d+)\.(\d+)\.(\d+)/;
var match = versionStr.match(semverRegex); const match = versionStr.match(semverRegex);
if (!match) { if (!match) {
throw new Error('Version string is not properly formatted: ' + versionStr); throw new Error('Version string is not properly formatted: ' + versionStr);
} }

View file

@ -4,30 +4,22 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs"); const fs = require("fs");
var ts = require("typescript"); const ts = require("typescript");
var path = require("path"); const path = require("path");
var util = require("gulp-util"); const util = require("gulp-util");
var tsfmt = require('../../tsfmt.json'); const tsfmt = require('../../tsfmt.json');
function log(message) { function log(message, ...rest) {
var rest = []; util.log(util.colors.cyan('[monaco.d.ts]'), message, ...rest);
for (var _i = 1; _i < arguments.length; _i++) {
rest[_i - 1] = arguments[_i];
}
util.log.apply(util, [util.colors.cyan('[monaco.d.ts]'), message].concat(rest));
} }
var SRC = path.join(__dirname, '../../src'); const SRC = path.join(__dirname, '../../src');
var OUT_ROOT = path.join(__dirname, '../../'); const OUT_ROOT = path.join(__dirname, '../../');
var RECIPE_PATH = path.join(__dirname, './monaco.d.ts.recipe'); const RECIPE_PATH = path.join(__dirname, './monaco.d.ts.recipe');
var DECLARATION_PATH = path.join(__dirname, '../../src/vs/monaco.d.ts'); const DECLARATION_PATH = path.join(__dirname, '../../src/vs/monaco.d.ts');
var CURRENT_PROCESSING_RULE = ''; var CURRENT_PROCESSING_RULE = '';
function logErr(message) { function logErr(message, ...rest) {
var rest = [];
for (var _i = 1; _i < arguments.length; _i++) {
rest[_i - 1] = arguments[_i];
}
util.log(util.colors.red('[monaco.d.ts]'), 'WHILE HANDLING RULE: ', CURRENT_PROCESSING_RULE); util.log(util.colors.red('[monaco.d.ts]'), 'WHILE HANDLING RULE: ', CURRENT_PROCESSING_RULE);
util.log.apply(util, [util.colors.red('[monaco.d.ts]'), message].concat(rest)); util.log(util.colors.red('[monaco.d.ts]'), message, ...rest);
} }
function moduleIdToPath(out, moduleId) { function moduleIdToPath(out, moduleId) {
if (/\.d\.ts/.test(moduleId)) { if (/\.d\.ts/.test(moduleId)) {
@ -35,16 +27,16 @@ function moduleIdToPath(out, moduleId) {
} }
return path.join(OUT_ROOT, out, moduleId) + '.d.ts'; return path.join(OUT_ROOT, out, moduleId) + '.d.ts';
} }
var SOURCE_FILE_MAP = {}; let SOURCE_FILE_MAP = {};
function getSourceFile(out, inputFiles, moduleId) { function getSourceFile(out, inputFiles, moduleId) {
if (!SOURCE_FILE_MAP[moduleId]) { if (!SOURCE_FILE_MAP[moduleId]) {
var filePath = path.normalize(moduleIdToPath(out, moduleId)); let filePath = path.normalize(moduleIdToPath(out, moduleId));
if (!inputFiles.hasOwnProperty(filePath)) { if (!inputFiles.hasOwnProperty(filePath)) {
logErr('CANNOT FIND FILE ' + filePath + '. YOU MIGHT NEED TO RESTART gulp'); logErr('CANNOT FIND FILE ' + filePath + '. YOU MIGHT NEED TO RESTART gulp');
return null; return null;
} }
var fileContents = inputFiles[filePath]; let fileContents = inputFiles[filePath];
var sourceFile = ts.createSourceFile(filePath, fileContents, ts.ScriptTarget.ES5); let sourceFile = ts.createSourceFile(filePath, fileContents, ts.ScriptTarget.ES5);
SOURCE_FILE_MAP[moduleId] = sourceFile; SOURCE_FILE_MAP[moduleId] = sourceFile;
} }
return SOURCE_FILE_MAP[moduleId]; return SOURCE_FILE_MAP[moduleId];
@ -58,8 +50,8 @@ function isDeclaration(a) {
|| a.kind === ts.SyntaxKind.ModuleDeclaration); || a.kind === ts.SyntaxKind.ModuleDeclaration);
} }
function visitTopLevelDeclarations(sourceFile, visitor) { function visitTopLevelDeclarations(sourceFile, visitor) {
var stop = false; let stop = false;
var visit = function (node) { let visit = (node) => {
if (stop) { if (stop) {
return; return;
} }
@ -81,19 +73,19 @@ function visitTopLevelDeclarations(sourceFile, visitor) {
visit(sourceFile); visit(sourceFile);
} }
function getAllTopLevelDeclarations(sourceFile) { function getAllTopLevelDeclarations(sourceFile) {
var all = []; let all = [];
visitTopLevelDeclarations(sourceFile, function (node) { visitTopLevelDeclarations(sourceFile, (node) => {
if (node.kind === ts.SyntaxKind.InterfaceDeclaration || node.kind === ts.SyntaxKind.ClassDeclaration || node.kind === ts.SyntaxKind.ModuleDeclaration) { if (node.kind === ts.SyntaxKind.InterfaceDeclaration || node.kind === ts.SyntaxKind.ClassDeclaration || node.kind === ts.SyntaxKind.ModuleDeclaration) {
var interfaceDeclaration = node; let interfaceDeclaration = node;
var triviaStart = interfaceDeclaration.pos; let triviaStart = interfaceDeclaration.pos;
var triviaEnd = interfaceDeclaration.name.pos; let triviaEnd = interfaceDeclaration.name.pos;
var triviaText = getNodeText(sourceFile, { pos: triviaStart, end: triviaEnd }); let triviaText = getNodeText(sourceFile, { pos: triviaStart, end: triviaEnd });
if (triviaText.indexOf('@internal') === -1) { if (triviaText.indexOf('@internal') === -1) {
all.push(node); all.push(node);
} }
} }
else { else {
var nodeText = getNodeText(sourceFile, node); let nodeText = getNodeText(sourceFile, node);
if (nodeText.indexOf('@internal') === -1) { if (nodeText.indexOf('@internal') === -1) {
all.push(node); all.push(node);
} }
@ -103,8 +95,8 @@ function getAllTopLevelDeclarations(sourceFile) {
return all; return all;
} }
function getTopLevelDeclaration(sourceFile, typeName) { function getTopLevelDeclaration(sourceFile, typeName) {
var result = null; let result = null;
visitTopLevelDeclarations(sourceFile, function (node) { visitTopLevelDeclarations(sourceFile, (node) => {
if (isDeclaration(node) && node.name) { if (isDeclaration(node) && node.name) {
if (node.name.text === typeName) { if (node.name.text === typeName) {
result = node; result = node;
@ -126,8 +118,8 @@ function getNodeText(sourceFile, node) {
} }
function hasModifier(modifiers, kind) { function hasModifier(modifiers, kind) {
if (modifiers) { if (modifiers) {
for (var i = 0; i < modifiers.length; i++) { for (let i = 0; i < modifiers.length; i++) {
var mod = modifiers[i]; let mod = modifiers[i];
if (mod.kind === kind) { if (mod.kind === kind) {
return true; return true;
} }
@ -143,35 +135,35 @@ function isDefaultExport(declaration) {
&& hasModifier(declaration.modifiers, ts.SyntaxKind.ExportKeyword)); && hasModifier(declaration.modifiers, ts.SyntaxKind.ExportKeyword));
} }
function getMassagedTopLevelDeclarationText(sourceFile, declaration, importName, usage) { function getMassagedTopLevelDeclarationText(sourceFile, declaration, importName, usage) {
var result = getNodeText(sourceFile, declaration); let result = getNodeText(sourceFile, declaration);
if (declaration.kind === ts.SyntaxKind.InterfaceDeclaration || declaration.kind === ts.SyntaxKind.ClassDeclaration) { if (declaration.kind === ts.SyntaxKind.InterfaceDeclaration || declaration.kind === ts.SyntaxKind.ClassDeclaration) {
var interfaceDeclaration = declaration; let interfaceDeclaration = declaration;
var staticTypeName_1 = (isDefaultExport(interfaceDeclaration) const staticTypeName = (isDefaultExport(interfaceDeclaration)
? importName + ".default" ? `${importName}.default`
: importName + "." + declaration.name.text); : `${importName}.${declaration.name.text}`);
var instanceTypeName_1 = staticTypeName_1; let instanceTypeName = staticTypeName;
var typeParametersCnt = (interfaceDeclaration.typeParameters ? interfaceDeclaration.typeParameters.length : 0); const typeParametersCnt = (interfaceDeclaration.typeParameters ? interfaceDeclaration.typeParameters.length : 0);
if (typeParametersCnt > 0) { if (typeParametersCnt > 0) {
var arr = []; let arr = [];
for (var i = 0; i < typeParametersCnt; i++) { for (let i = 0; i < typeParametersCnt; i++) {
arr.push('any'); arr.push('any');
} }
instanceTypeName_1 = instanceTypeName_1 + "<" + arr.join(',') + ">"; instanceTypeName = `${instanceTypeName}<${arr.join(',')}>`;
} }
var members = interfaceDeclaration.members; const members = interfaceDeclaration.members;
members.forEach(function (member) { members.forEach((member) => {
try { try {
var memberText = getNodeText(sourceFile, member); let memberText = getNodeText(sourceFile, member);
if (memberText.indexOf('@internal') >= 0 || memberText.indexOf('private') >= 0) { if (memberText.indexOf('@internal') >= 0 || memberText.indexOf('private') >= 0) {
result = result.replace(memberText, ''); result = result.replace(memberText, '');
} }
else { else {
var memberName = member.name.text; const memberName = member.name.text;
if (isStatic(member)) { if (isStatic(member)) {
usage.push("a = " + staticTypeName_1 + "." + memberName + ";"); usage.push(`a = ${staticTypeName}.${memberName};`);
} }
else { else {
usage.push("a = (<" + instanceTypeName_1 + ">b)." + memberName + ";"); usage.push(`a = (<${instanceTypeName}>b).${memberName};`);
} }
} }
} }
@ -186,9 +178,9 @@ function getMassagedTopLevelDeclarationText(sourceFile, declaration, importName,
} }
function format(text) { function format(text) {
// Parse the source text // Parse the source text
var sourceFile = ts.createSourceFile('file.ts', text, ts.ScriptTarget.Latest, /*setParentPointers*/ true); let sourceFile = ts.createSourceFile('file.ts', text, ts.ScriptTarget.Latest, /*setParentPointers*/ true);
// Get the formatting edits on the input sources // Get the formatting edits on the input sources
var edits = ts.formatting.formatDocument(sourceFile, getRuleProvider(tsfmt), tsfmt); let edits = ts.formatting.formatDocument(sourceFile, getRuleProvider(tsfmt), tsfmt);
// Apply the edits on the input code // Apply the edits on the input code
return applyEdits(text, edits); return applyEdits(text, edits);
function getRuleProvider(options) { function getRuleProvider(options) {
@ -198,11 +190,11 @@ function format(text) {
} }
function applyEdits(text, edits) { function applyEdits(text, edits) {
// Apply edits in reverse on the existing text // Apply edits in reverse on the existing text
var result = text; let result = text;
for (var i = edits.length - 1; i >= 0; i--) { for (let i = edits.length - 1; i >= 0; i--) {
var change = edits[i]; let change = edits[i];
var head = result.slice(0, change.span.start); let head = result.slice(0, change.span.start);
var tail = result.slice(change.span.start + change.span.length); let tail = result.slice(change.span.start + change.span.length);
result = head + change.newText + tail; result = head + change.newText + tail;
} }
return result; return result;
@ -210,131 +202,131 @@ function format(text) {
} }
function createReplacer(data) { function createReplacer(data) {
data = data || ''; data = data || '';
var rawDirectives = data.split(';'); let rawDirectives = data.split(';');
var directives = []; let directives = [];
rawDirectives.forEach(function (rawDirective) { rawDirectives.forEach((rawDirective) => {
if (rawDirective.length === 0) { if (rawDirective.length === 0) {
return; return;
} }
var pieces = rawDirective.split('=>'); let pieces = rawDirective.split('=>');
var findStr = pieces[0]; let findStr = pieces[0];
var replaceStr = pieces[1]; let replaceStr = pieces[1];
findStr = findStr.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&'); findStr = findStr.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&');
findStr = '\\b' + findStr + '\\b'; findStr = '\\b' + findStr + '\\b';
directives.push([new RegExp(findStr, 'g'), replaceStr]); directives.push([new RegExp(findStr, 'g'), replaceStr]);
}); });
return function (str) { return (str) => {
for (var i = 0; i < directives.length; i++) { for (let i = 0; i < directives.length; i++) {
str = str.replace(directives[i][0], directives[i][1]); str = str.replace(directives[i][0], directives[i][1]);
} }
return str; return str;
}; };
} }
function generateDeclarationFile(out, inputFiles, recipe) { function generateDeclarationFile(out, inputFiles, recipe) {
var endl = /\r\n/.test(recipe) ? '\r\n' : '\n'; const endl = /\r\n/.test(recipe) ? '\r\n' : '\n';
var lines = recipe.split(endl); let lines = recipe.split(endl);
var result = []; let result = [];
var usageCounter = 0; let usageCounter = 0;
var usageImports = []; let usageImports = [];
var usage = []; let usage = [];
usage.push("var a;"); usage.push(`var a;`);
usage.push("var b;"); usage.push(`var b;`);
var generateUsageImport = function (moduleId) { const generateUsageImport = (moduleId) => {
var importName = 'm' + (++usageCounter); let importName = 'm' + (++usageCounter);
usageImports.push("import * as " + importName + " from './" + moduleId.replace(/\.d\.ts$/, '') + "';"); usageImports.push(`import * as ${importName} from './${moduleId.replace(/\.d\.ts$/, '')}';`);
return importName; return importName;
}; };
lines.forEach(function (line) { lines.forEach(line => {
var m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/); let m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
if (m1) { if (m1) {
CURRENT_PROCESSING_RULE = line; CURRENT_PROCESSING_RULE = line;
var moduleId = m1[1]; let moduleId = m1[1];
var sourceFile_1 = getSourceFile(out, inputFiles, moduleId); const sourceFile = getSourceFile(out, inputFiles, moduleId);
if (!sourceFile_1) { if (!sourceFile) {
return; return;
} }
var importName_1 = generateUsageImport(moduleId); const importName = generateUsageImport(moduleId);
var replacer_1 = createReplacer(m1[2]); let replacer = createReplacer(m1[2]);
var typeNames = m1[3].split(/,/); let typeNames = m1[3].split(/,/);
typeNames.forEach(function (typeName) { typeNames.forEach((typeName) => {
typeName = typeName.trim(); typeName = typeName.trim();
if (typeName.length === 0) { if (typeName.length === 0) {
return; return;
} }
var declaration = getTopLevelDeclaration(sourceFile_1, typeName); let declaration = getTopLevelDeclaration(sourceFile, typeName);
if (!declaration) { if (!declaration) {
logErr('Cannot find type ' + typeName); logErr('Cannot find type ' + typeName);
return; return;
} }
result.push(replacer_1(getMassagedTopLevelDeclarationText(sourceFile_1, declaration, importName_1, usage))); result.push(replacer(getMassagedTopLevelDeclarationText(sourceFile, declaration, importName, usage)));
}); });
return; return;
} }
var m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/); let m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
if (m2) { if (m2) {
CURRENT_PROCESSING_RULE = line; CURRENT_PROCESSING_RULE = line;
var moduleId = m2[1]; let moduleId = m2[1];
var sourceFile_2 = getSourceFile(out, inputFiles, moduleId); const sourceFile = getSourceFile(out, inputFiles, moduleId);
if (!sourceFile_2) { if (!sourceFile) {
return; return;
} }
var importName_2 = generateUsageImport(moduleId); const importName = generateUsageImport(moduleId);
var replacer_2 = createReplacer(m2[2]); let replacer = createReplacer(m2[2]);
var typeNames = m2[3].split(/,/); let typeNames = m2[3].split(/,/);
var typesToExcludeMap_1 = {}; let typesToExcludeMap = {};
var typesToExcludeArr_1 = []; let typesToExcludeArr = [];
typeNames.forEach(function (typeName) { typeNames.forEach((typeName) => {
typeName = typeName.trim(); typeName = typeName.trim();
if (typeName.length === 0) { if (typeName.length === 0) {
return; return;
} }
typesToExcludeMap_1[typeName] = true; typesToExcludeMap[typeName] = true;
typesToExcludeArr_1.push(typeName); typesToExcludeArr.push(typeName);
}); });
getAllTopLevelDeclarations(sourceFile_2).forEach(function (declaration) { getAllTopLevelDeclarations(sourceFile).forEach((declaration) => {
if (isDeclaration(declaration) && declaration.name) { if (isDeclaration(declaration) && declaration.name) {
if (typesToExcludeMap_1[declaration.name.text]) { if (typesToExcludeMap[declaration.name.text]) {
return; return;
} }
} }
else { else {
// node is ts.VariableStatement // node is ts.VariableStatement
var nodeText = getNodeText(sourceFile_2, declaration); let nodeText = getNodeText(sourceFile, declaration);
for (var i = 0; i < typesToExcludeArr_1.length; i++) { for (let i = 0; i < typesToExcludeArr.length; i++) {
if (nodeText.indexOf(typesToExcludeArr_1[i]) >= 0) { if (nodeText.indexOf(typesToExcludeArr[i]) >= 0) {
return; return;
} }
} }
} }
result.push(replacer_2(getMassagedTopLevelDeclarationText(sourceFile_2, declaration, importName_2, usage))); result.push(replacer(getMassagedTopLevelDeclarationText(sourceFile, declaration, importName, usage)));
}); });
return; return;
} }
result.push(line); result.push(line);
}); });
var resultTxt = result.join(endl); let resultTxt = result.join(endl);
resultTxt = resultTxt.replace(/\bURI\b/g, 'Uri'); resultTxt = resultTxt.replace(/\bURI\b/g, 'Uri');
resultTxt = resultTxt.replace(/\bEvent</g, 'IEvent<'); resultTxt = resultTxt.replace(/\bEvent</g, 'IEvent<');
resultTxt = format(resultTxt); resultTxt = format(resultTxt);
return [ return [
resultTxt, resultTxt,
usageImports.join('\n') + "\n\n" + usage.join('\n') `${usageImports.join('\n')}\n\n${usage.join('\n')}`
]; ];
} }
function getIncludesInRecipe() { function getIncludesInRecipe() {
var recipe = fs.readFileSync(RECIPE_PATH).toString(); let recipe = fs.readFileSync(RECIPE_PATH).toString();
var lines = recipe.split(/\r\n|\n|\r/); let lines = recipe.split(/\r\n|\n|\r/);
var result = []; let result = [];
lines.forEach(function (line) { lines.forEach(line => {
var m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/); let m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
if (m1) { if (m1) {
var moduleId = m1[1]; let moduleId = m1[1];
result.push(moduleId); result.push(moduleId);
return; return;
} }
var m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/); let m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
if (m2) { if (m2) {
var moduleId = m2[1]; let moduleId = m2[1];
result.push(moduleId); result.push(moduleId);
return; return;
} }
@ -342,24 +334,24 @@ function getIncludesInRecipe() {
return result; return result;
} }
function getFilesToWatch(out) { function getFilesToWatch(out) {
return getIncludesInRecipe().map(function (moduleId) { return moduleIdToPath(out, moduleId); }); return getIncludesInRecipe().map((moduleId) => moduleIdToPath(out, moduleId));
} }
exports.getFilesToWatch = getFilesToWatch; exports.getFilesToWatch = getFilesToWatch;
function run(out, inputFiles) { function run(out, inputFiles) {
log('Starting monaco.d.ts generation'); log('Starting monaco.d.ts generation');
SOURCE_FILE_MAP = {}; SOURCE_FILE_MAP = {};
var recipe = fs.readFileSync(RECIPE_PATH).toString(); let recipe = fs.readFileSync(RECIPE_PATH).toString();
var _a = generateDeclarationFile(out, inputFiles, recipe), result = _a[0], usageContent = _a[1]; let [result, usageContent] = generateDeclarationFile(out, inputFiles, recipe);
var currentContent = fs.readFileSync(DECLARATION_PATH).toString(); let currentContent = fs.readFileSync(DECLARATION_PATH).toString();
log('Finished monaco.d.ts generation'); log('Finished monaco.d.ts generation');
var one = currentContent.replace(/\r\n/gm, '\n'); const one = currentContent.replace(/\r\n/gm, '\n');
var other = result.replace(/\r\n/gm, '\n'); const other = result.replace(/\r\n/gm, '\n');
var isTheSame = one === other; const isTheSame = one === other;
return { return {
content: result, content: result,
usageContent: usageContent, usageContent: usageContent,
filePath: DECLARATION_PATH, filePath: DECLARATION_PATH,
isTheSame: isTheSame isTheSame
}; };
} }
exports.run = run; exports.run = run;
@ -367,28 +359,28 @@ function complainErrors() {
logErr('Not running monaco.d.ts generation due to compile errors'); logErr('Not running monaco.d.ts generation due to compile errors');
} }
exports.complainErrors = complainErrors; exports.complainErrors = complainErrors;
var TypeScriptLanguageServiceHost = /** @class */ (function () { class TypeScriptLanguageServiceHost {
function TypeScriptLanguageServiceHost(libs, files, compilerOptions) { constructor(libs, files, compilerOptions) {
this._libs = libs; this._libs = libs;
this._files = files; this._files = files;
this._compilerOptions = compilerOptions; this._compilerOptions = compilerOptions;
} }
// --- language service host --------------- // --- language service host ---------------
TypeScriptLanguageServiceHost.prototype.getCompilationSettings = function () { getCompilationSettings() {
return this._compilerOptions; return this._compilerOptions;
}; }
TypeScriptLanguageServiceHost.prototype.getScriptFileNames = function () { getScriptFileNames() {
return ([] return ([]
.concat(Object.keys(this._libs)) .concat(Object.keys(this._libs))
.concat(Object.keys(this._files))); .concat(Object.keys(this._files)));
}; }
TypeScriptLanguageServiceHost.prototype.getScriptVersion = function (_fileName) { getScriptVersion(_fileName) {
return '1'; return '1';
}; }
TypeScriptLanguageServiceHost.prototype.getProjectVersion = function () { getProjectVersion() {
return '1'; return '1';
}; }
TypeScriptLanguageServiceHost.prototype.getScriptSnapshot = function (fileName) { getScriptSnapshot(fileName) {
if (this._files.hasOwnProperty(fileName)) { if (this._files.hasOwnProperty(fileName)) {
return ts.ScriptSnapshot.fromString(this._files[fileName]); return ts.ScriptSnapshot.fromString(this._files[fileName]);
} }
@ -398,42 +390,41 @@ var TypeScriptLanguageServiceHost = /** @class */ (function () {
else { else {
return ts.ScriptSnapshot.fromString(''); return ts.ScriptSnapshot.fromString('');
} }
}; }
TypeScriptLanguageServiceHost.prototype.getScriptKind = function (_fileName) { getScriptKind(_fileName) {
return ts.ScriptKind.TS; return ts.ScriptKind.TS;
}; }
TypeScriptLanguageServiceHost.prototype.getCurrentDirectory = function () { getCurrentDirectory() {
return ''; return '';
}; }
TypeScriptLanguageServiceHost.prototype.getDefaultLibFileName = function (_options) { getDefaultLibFileName(_options) {
return 'defaultLib:es5'; return 'defaultLib:es5';
}; }
TypeScriptLanguageServiceHost.prototype.isDefaultLibFileName = function (fileName) { isDefaultLibFileName(fileName) {
return fileName === this.getDefaultLibFileName(this._compilerOptions); return fileName === this.getDefaultLibFileName(this._compilerOptions);
}; }
return TypeScriptLanguageServiceHost; }
}());
function execute() { function execute() {
var OUTPUT_FILES = {}; const OUTPUT_FILES = {};
var SRC_FILES = {}; const SRC_FILES = {};
var SRC_FILE_TO_EXPECTED_NAME = {}; const SRC_FILE_TO_EXPECTED_NAME = {};
getIncludesInRecipe().forEach(function (moduleId) { getIncludesInRecipe().forEach((moduleId) => {
if (/\.d\.ts$/.test(moduleId)) { if (/\.d\.ts$/.test(moduleId)) {
var fileName_1 = path.join(SRC, moduleId); let fileName = path.join(SRC, moduleId);
OUTPUT_FILES[moduleIdToPath('src', moduleId)] = fs.readFileSync(fileName_1).toString(); OUTPUT_FILES[moduleIdToPath('src', moduleId)] = fs.readFileSync(fileName).toString();
return; return;
} }
var fileName = path.join(SRC, moduleId) + '.ts'; let fileName = path.join(SRC, moduleId) + '.ts';
SRC_FILES[fileName] = fs.readFileSync(fileName).toString(); SRC_FILES[fileName] = fs.readFileSync(fileName).toString();
SRC_FILE_TO_EXPECTED_NAME[fileName] = moduleIdToPath('src', moduleId); SRC_FILE_TO_EXPECTED_NAME[fileName] = moduleIdToPath('src', moduleId);
}); });
var languageService = ts.createLanguageService(new TypeScriptLanguageServiceHost({}, SRC_FILES, {})); const languageService = ts.createLanguageService(new TypeScriptLanguageServiceHost({}, SRC_FILES, {}));
var t1 = Date.now(); var t1 = Date.now();
Object.keys(SRC_FILES).forEach(function (fileName) { Object.keys(SRC_FILES).forEach((fileName) => {
var emitOutput = languageService.getEmitOutput(fileName, true); const emitOutput = languageService.getEmitOutput(fileName, true);
OUTPUT_FILES[SRC_FILE_TO_EXPECTED_NAME[fileName]] = emitOutput.outputFiles[0].text; OUTPUT_FILES[SRC_FILE_TO_EXPECTED_NAME[fileName]] = emitOutput.outputFiles[0].text;
}); });
console.log("Generating .d.ts took " + (Date.now() - t1) + " ms"); console.log(`Generating .d.ts took ${Date.now() - t1} ms`);
return run('src', OUTPUT_FILES); return run('src', OUTPUT_FILES);
} }
exports.execute = execute; exports.execute = execute;

View file

@ -5,8 +5,6 @@
"@types/azure": "0.9.19", "@types/azure": "0.9.19",
"@types/debounce": "^1.0.0", "@types/debounce": "^1.0.0",
"@types/documentdb": "1.10.2", "@types/documentdb": "1.10.2",
"@types/es6-collections": "0.5.31",
"@types/es6-promise": "0.0.33",
"@types/glob": "^7.1.1", "@types/glob": "^7.1.1",
"@types/gulp": "^4.0.5", "@types/gulp": "^4.0.5",
"@types/gulp-concat": "^0.0.32", "@types/gulp-concat": "^0.0.32",

View file

@ -3,70 +3,27 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
'use strict'; 'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var child_process_1 = require("child_process"); const child_process_1 = require("child_process");
var azure = require("azure-storage"); const azure = require("azure-storage");
function queueSigningRequest(quality, commit) { function queueSigningRequest(quality, commit) {
var retryOperations = new azure.ExponentialRetryPolicyFilter(); const retryOperations = new azure.ExponentialRetryPolicyFilter();
var queueSvc = azure const queueSvc = azure
.createQueueService(process.env['AZURE_STORAGE_ACCOUNT_2'], process.env['AZURE_STORAGE_ACCESS_KEY_2']) .createQueueService(process.env['AZURE_STORAGE_ACCOUNT_2'], process.env['AZURE_STORAGE_ACCESS_KEY_2'])
.withFilter(retryOperations); .withFilter(retryOperations);
queueSvc.messageEncoder = new azure.QueueMessageEncoder.TextBase64QueueMessageEncoder(); queueSvc.messageEncoder = new azure.QueueMessageEncoder.TextBase64QueueMessageEncoder();
var message = quality + "/" + commit; const message = `${quality}/${commit}`;
return new Promise(function (c, e) { return queueSvc.createMessage('sign-darwin', message, function (err) { return err ? e(err) : c(); }); }); return new Promise((c, e) => queueSvc.createMessage('sign-darwin', message, err => err ? e(err) : c()));
} }
function main(quality) { async function main(quality) {
return __awaiter(this, void 0, void 0, function () { const commit = child_process_1.execSync('git rev-parse HEAD', { encoding: 'utf8' }).trim();
var commit; console.log(`Queueing signing request for '${quality}/${commit}'...`);
return __generator(this, function (_a) { await queueSigningRequest(quality, commit);
switch (_a.label) { // console.log('Waiting on signed build...');
case 0: // await waitForSignedBuild(quality, commit);
commit = child_process_1.execSync('git rev-parse HEAD', { encoding: 'utf8' }).trim(); // console.log('Found signed build!');
console.log("Queueing signing request for '" + quality + "/" + commit + "'...");
return [4 /*yield*/, queueSigningRequest(quality, commit)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
} }
main(process.argv[2]).catch(function (err) { main(process.argv[2]).catch(err => {
console.error(err); console.error(err);
process.exit(1); process.exit(1);
}); });

View file

@ -1,6 +1,6 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "es5", "target": "es2017",
"module": "commonjs", "module": "commonjs",
"removeComments": false, "removeComments": false,
"preserveConstEnums": true, "preserveConstEnums": true,

View file

@ -42,16 +42,6 @@
dependencies: dependencies:
"@types/node" "*" "@types/node" "*"
"@types/es6-collections@0.5.31":
version "0.5.31"
resolved "https://registry.yarnpkg.com/@types/es6-collections/-/es6-collections-0.5.31.tgz#faad21c930cd0ea7f71f51b9e5b555796c5ab23f"
integrity sha512-djEvbdTH5Uw7V0WqdMQLG4NK3+iu/FMZy/ylyhWEFnW5xOsXEWpivo/dhP+cR43Az+ipytza7dTSnpsWCxKYAw==
"@types/es6-promise@0.0.33":
version "0.0.33"
resolved "https://registry.yarnpkg.com/@types/es6-promise/-/es6-promise-0.0.33.tgz#280a707e62b1b6bef1a86cc0861ec63cd06c7ff3"
integrity sha512-HKJFVLCGrWQ/1unEw8JdaTxu6n3EUxmwTxJ6D0O1x0gD8joCsgoTWxEgevb7fp2XIogNjof3KEd+3bJoGne/nw==
"@types/events@*": "@types/events@*":
version "1.2.0" version "1.2.0"
resolved "https://registry.yarnpkg.com/@types/events/-/events-1.2.0.tgz#81a6731ce4df43619e5c8c945383b3e62a89ea86" resolved "https://registry.yarnpkg.com/@types/events/-/events-1.2.0.tgz#81a6731ce4df43619e5c8c945383b3e62a89ea86"

View file

@ -111,7 +111,6 @@
"mkdirp": "^0.5.0", "mkdirp": "^0.5.0",
"mocha": "^2.2.5", "mocha": "^2.2.5",
"mocha-junit-reporter": "^1.17.0", "mocha-junit-reporter": "^1.17.0",
"object-assign": "^4.0.1",
"optimist": "0.3.5", "optimist": "0.3.5",
"p-all": "^1.0.0", "p-all": "^1.0.0",
"pump": "^1.0.1", "pump": "^1.0.1",