hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 0,
"code_window": [
"\tconst extensionsOut = gulp.src('extensions/**/out/**/*.map', { base: '.' });\n",
"\tconst extensionsDist = gulp.src('extensions/**/dist/**/*.map', { base: '.' });\n",
"\n",
"\tconst res = es.merge(vs, extensionsOut, extensionsDist)\n",
"\t\t.pipe(es.through(function (data) {\n",
"\t\t\t// debug\n",
"\t\t\tconsole.log('Uploading Sourcemap', data.relative);\n",
"\t\t\tthis.emit('data', data);\n",
"\t\t}))\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\treturn es.merge(vs, extensionsOut, extensionsDist)\n"
],
"file_path": "build/gulpfile.vscode.js",
"type": "replace",
"edit_start_line_idx": 516
} | extensions/html-language-features/server/src/test/pathCompletionFixtures/index.html | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.00017154618399217725,
0.00017154618399217725,
0.00017154618399217725,
0.00017154618399217725,
0
] |
|
{
"id": 0,
"code_window": [
"\tconst extensionsOut = gulp.src('extensions/**/out/**/*.map', { base: '.' });\n",
"\tconst extensionsDist = gulp.src('extensions/**/dist/**/*.map', { base: '.' });\n",
"\n",
"\tconst res = es.merge(vs, extensionsOut, extensionsDist)\n",
"\t\t.pipe(es.through(function (data) {\n",
"\t\t\t// debug\n",
"\t\t\tconsole.log('Uploading Sourcemap', data.relative);\n",
"\t\t\tthis.emit('data', data);\n",
"\t\t}))\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\treturn es.merge(vs, extensionsOut, extensionsDist)\n"
],
"file_path": "build/gulpfile.vscode.js",
"type": "replace",
"edit_start_line_idx": 516
} | <!DOCTYPE html>
<html>
<head id='headID'>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Strada </title>
<link href="site.css" rel="stylesheet" type="text/css" />
<script src="jquery-1.4.1.js"></script>
<script src="../compiler/dtree.js" type="text/javascript"></script>
<script src="../compiler/typescript.js" type="text/javascript"></script>
<script type="text/javascript">
// Compile strada source into resulting javascript
function compile(prog, libText) {
var outfile = {
source: "",
Write: function (s) { this.source += s; },
WriteLine: function (s) { this.source += s + "\r"; },
}
var parseErrors = []
var compiler=new Tools.TypeScriptCompiler(outfile,true);
compiler.setErrorCallback(function(start,len, message) { parseErrors.push({start:start, len:len, message:message}); });
compiler.addUnit(libText,"lib.ts");
compiler.addUnit(prog,"input.ts");
compiler.typeCheck();
compiler.emit();
if(parseErrors.length > 0 ) {
//throw new Error(parseErrors);
}
while(outfile.source[0] == '/' && outfile.source[1] == '/' && outfile.source[2] == ' ') {
outfile.source = outfile.source.slice(outfile.source.indexOf('\r')+1);
}
var errorPrefix = "";
for(var i = 0;i<parseErrors.length;i++) {
errorPrefix += "// Error: (" + parseErrors[i].start + "," + parseErrors[i].len + ") " + parseErrors[i].message + "\r";
}
return errorPrefix + outfile.source;
}
</script>
<script type="text/javascript">
var libText = "";
$.get("../compiler/lib.ts", function(newLibText) {
libText = newLibText;
});
// execute the javascript in the compiledOutput pane
function execute() {
$('#compilation').text("Running...");
var txt = $('#compiledOutput').val();
var res;
try {
var ret = eval(txt);
res = "Ran successfully!";
} catch(e) {
res = "Exception thrown: " + e;
}
$('#compilation').text(String(res));
}
// recompile the stradaSrc and populate the compiledOutput pane
function srcUpdated() {
var newText = $('#stradaSrc').val();
var compiledSource;
try {
compiledSource = compile(newText, libText);
} catch (e) {
compiledSource = "//Parse error"
for(var i in e)
compiledSource += "\r// " + e[i];
}
$('#compiledOutput').val(compiledSource);
}
// Populate the stradaSrc pane with one of the built in samples
function exampleSelectionChanged() {
var examples = document.getElementById('examples');
var selectedExample = examples.options[examples.selectedIndex].value;
if (selectedExample != "") {
$.get('examples/' + selectedExample, function (srcText) {
$('#stradaSrc').val(srcText);
setTimeout(srcUpdated,100);
}, function (err) {
console.log(err);
});
}
}
</script>
</head>
<body>
<h1>TypeScript</h1>
<br />
<select id="examples" onchange='exampleSelectionChanged()'>
<option value="">Select...</option>
<option value="small.ts">Small</option>
<option value="employee.ts">Employees</option>
<option value="conway.ts">Conway Game of Life</option>
<option value="typescript.ts">TypeScript Compiler</option>
</select>
<div>
<textarea id='stradaSrc' rows='40' cols='80' onchange='srcUpdated()' onkeyup='srcUpdated()' spellcheck="false">
//Type your TypeScript here...
</textarea>
<textarea id='compiledOutput' rows='40' cols='80' spellcheck="false">
//Compiled code will show up here...
</textarea>
<br />
<button onclick='execute()'/>Run</button>
<div id='compilation'>Press 'run' to execute code...</div>
<div id='results'>...write your results into #results...</div>
</div>
<div id='bod' style='display:none'></div>
</body>
</html>
| src/vs/workbench/services/files/test/electron-browser/fixtures/resolver/index.html | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.9956433773040771,
0.07959525287151337,
0.00016611558385193348,
0.00017166580073535442,
0.26462322473526
] |
{
"id": 1,
"code_window": [
"\t\t\tkey: process.env.AZURE_STORAGE_ACCESS_KEY,\n",
"\t\t\tcontainer: 'sourcemaps',\n",
"\t\t\tprefix: commit + '/'\n",
"\t\t}));\n",
"\tres.on('error', (err) => {\n",
"\t\tconsole.log('ERROR uploading sourcemaps');\n",
"\t\tconsole.error(err);\n",
"\t});\n",
"\tres.on('end', () => {\n",
"\t\tconsole.log('Completed uploading sourcemaps');\n",
"\t});\n",
"\treturn res;\n",
"});\n",
"\n",
"const allConfigDetailsPath = path.join(os.tmpdir(), 'configuration.json');\n",
"gulp.task('upload-vscode-configuration', ['generate-vscode-configuration'], () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "build/gulpfile.vscode.js",
"type": "replace",
"edit_start_line_idx": 528
} | "use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* 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 });
var es = require("event-stream");
var fs = require("fs");
var glob = require("glob");
var gulp = require("gulp");
var path = require("path");
var File = require("vinyl");
var vsce = require("vsce");
var stats_1 = require("./stats");
var util2 = require("./util");
var remote = require("gulp-remote-src");
var vzip = require('gulp-vinyl-zip');
var filter = require('gulp-filter');
var rename = require('gulp-rename');
var util = require('gulp-util');
var buffer = require('gulp-buffer');
var json = require('gulp-json-editor');
var webpack = require('webpack');
var webpackGulp = require('webpack-stream');
var root = path.resolve(path.join(__dirname, '..', '..'));
function fromLocal(extensionPath, sourceMappingURLBase) {
var webpackFilename = path.join(extensionPath, 'extension.webpack.config.js');
if (fs.existsSync(webpackFilename)) {
return fromLocalWebpack(extensionPath, sourceMappingURLBase);
}
else {
return fromLocalNormal(extensionPath);
}
}
function fromLocalWebpack(extensionPath, sourceMappingURLBase) {
var result = es.through();
var packagedDependencies = [];
var packageJsonConfig = require(path.join(extensionPath, 'package.json'));
var webpackRootConfig = require(path.join(extensionPath, 'extension.webpack.config.js'));
for (var key in webpackRootConfig.externals) {
if (key in packageJsonConfig.dependencies) {
packagedDependencies.push(key);
}
}
vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn, packagedDependencies: packagedDependencies }).then(function (fileNames) {
var files = fileNames
.map(function (fileName) { return path.join(extensionPath, fileName); })
.map(function (filePath) { return new File({
path: filePath,
stat: fs.statSync(filePath),
base: extensionPath,
contents: fs.createReadStream(filePath)
}); });
var filesStream = es.readArray(files);
// check for a webpack configuration files, then invoke webpack
// and merge its output with the files stream. also rewrite the package.json
// file to a new entry point
var webpackConfigLocations = glob.sync(path.join(extensionPath, '/**/extension.webpack.config.js'), { ignore: ['**/node_modules'] });
var packageJsonFilter = filter(function (f) {
if (path.basename(f.path) === 'package.json') {
// only modify package.json's next to the webpack file.
// to be safe, use existsSync instead of path comparison.
return fs.existsSync(path.join(path.dirname(f.path), 'extension.webpack.config.js'));
}
return false;
}, { restore: true });
var patchFilesStream = filesStream
.pipe(packageJsonFilter)
.pipe(buffer())
.pipe(json(function (data) {
// hardcoded entry point directory!
data.main = data.main.replace('/out/', /dist/);
return data;
}))
.pipe(packageJsonFilter.restore);
var webpackStreams = webpackConfigLocations.map(function (webpackConfigPath) {
var webpackDone = function (err, stats) {
util.log("Bundled extension: " + util.colors.yellow(path.join(path.basename(extensionPath), path.relative(extensionPath, webpackConfigPath))) + "...");
if (err) {
result.emit('error', err);
}
var compilation = stats.compilation;
if (compilation.errors.length > 0) {
result.emit('error', compilation.errors.join('\n'));
}
if (compilation.warnings.length > 0) {
result.emit('error', compilation.warnings.join('\n'));
}
};
var webpackConfig = __assign({}, require(webpackConfigPath), { mode: 'production' });
var relativeOutputPath = path.relative(extensionPath, webpackConfig.output.path);
return webpackGulp(webpackConfig, webpack, webpackDone)
.pipe(es.through(function (data) {
data.stat = data.stat || {};
data.base = extensionPath;
this.emit('data', data);
}))
.pipe(es.through(function (data) {
// source map handling:
// * rewrite sourceMappingURL
// * save to disk so that upload-task picks this up
if (sourceMappingURLBase) {
var contents = data.contents.toString('utf8');
data.contents = Buffer.from(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, function (_m, g1) {
return "\n//# sourceMappingURL=" + sourceMappingURLBase + "/extensions/" + path.basename(extensionPath) + "/" + relativeOutputPath + "/" + g1;
}), 'utf8');
if (/\.js\.map$/.test(data.path)) {
if (!fs.existsSync(path.dirname(data.path))) {
fs.mkdirSync(path.dirname(data.path));
}
fs.writeFileSync(data.path, data.contents);
}
}
this.emit('data', data);
}));
});
es.merge.apply(es, webpackStreams.concat([patchFilesStream])).pipe(result);
}).catch(function (err) {
console.error(extensionPath);
console.error(packagedDependencies);
result.emit('error', err);
});
return result.pipe(stats_1.createStatsStream(path.basename(extensionPath)));
}
function fromLocalNormal(extensionPath) {
var result = es.through();
vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn })
.then(function (fileNames) {
var files = fileNames
.map(function (fileName) { return path.join(extensionPath, fileName); })
.map(function (filePath) { return new File({
path: filePath,
stat: fs.statSync(filePath),
base: extensionPath,
contents: fs.createReadStream(filePath)
}); });
es.readArray(files).pipe(result);
})
.catch(function (err) { return result.emit('error', err); });
return result.pipe(stats_1.createStatsStream(path.basename(extensionPath)));
}
var baseHeaders = {
'X-Market-Client-Id': 'VSCode Build',
'User-Agent': 'VSCode Build',
'X-Market-User-Id': '291C1CD0-051A-4123-9B4B-30D60EF52EE2',
};
function fromMarketplace(extensionName, version, metadata) {
var _a = extensionName.split('.'), publisher = _a[0], name = _a[1];
var url = "https://marketplace.visualstudio.com/_apis/public/gallery/publishers/" + publisher + "/vsextensions/" + name + "/" + version + "/vspackage";
util.log('Downloading extension:', util.colors.yellow(extensionName + "@" + version), '...');
var options = {
base: url,
requestOptions: {
gzip: true,
headers: baseHeaders
}
};
var packageJsonFilter = filter('package.json', { restore: true });
return remote('', options)
.on('error', function (err) {
console.log('Error downloading extension:', util.colors.yellow(extensionName + "@" + version));
console.error(err);
})
.on('end', function () {
console.log('Downloaded extension:', util.colors.yellow(extensionName + "@" + version));
})
.pipe(vzip.src())
.pipe(filter('extension/**'))
.pipe(rename(function (p) { return p.dirname = p.dirname.replace(/^extension\/?/, ''); }))
.pipe(packageJsonFilter)
.pipe(buffer())
.pipe(json({ __metadata: metadata }))
.pipe(packageJsonFilter.restore);
}
exports.fromMarketplace = fromMarketplace;
var excludedExtensions = [
'vscode-api-tests',
'vscode-colorize-tests',
'ms-vscode.node-debug',
'ms-vscode.node-debug2',
];
var builtInExtensions = require('../builtInExtensions.json');
/**
* 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
* stack frames to complete the download in under 2 minutes, at which point the
* marketplace server cuts off the http request. So, we sequentialize the extensino tasks.
*/
function sequence(streamProviders) {
var result = es.through();
function pop() {
if (streamProviders.length === 0) {
result.emit('end');
}
else {
var fn = streamProviders.shift();
fn()
.on('end', function () { setTimeout(pop, 0); })
.pipe(result, { end: false });
}
}
pop();
return result;
}
function packageExtensionsStream(opts) {
opts = opts || {};
var localExtensionDescriptions = glob.sync('extensions/*/package.json')
.map(function (manifestPath) {
var extensionPath = path.dirname(path.join(root, manifestPath));
var extensionName = path.basename(extensionPath);
return { name: extensionName, path: extensionPath };
})
.filter(function (_a) {
var name = _a.name;
return excludedExtensions.indexOf(name) === -1;
})
.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)
.pipe(rename(function (p) { return p.dirname = "extensions/" + extension.name + "/" + p.dirname; }));
})); };
var localExtensionDependencies = function () { return gulp.src('extensions/node_modules/**', { base: '.' }); };
var marketplaceExtensions = function () { return es.merge.apply(es, builtInExtensions
.filter(function (_a) {
var name = _a.name;
return opts.desiredExtensions ? opts.desiredExtensions.indexOf(name) >= 0 : true;
})
.map(function (extension) {
return fromMarketplace(extension.name, extension.version, extension.metadata)
.pipe(rename(function (p) { return p.dirname = "extensions/" + extension.name + "/" + p.dirname; }));
})); };
return sequence([localExtensions, localExtensionDependencies, marketplaceExtensions])
.pipe(util2.setExecutableBit(['**/*.sh']))
.pipe(filter(['**', '!**/*.js.map']));
}
exports.packageExtensionsStream = packageExtensionsStream;
| build/lib/extensions.js | 1 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.0015739541267976165,
0.00025074504083022475,
0.00016346438496839255,
0.00016723171574994922,
0.00029619524138979614
] |
{
"id": 1,
"code_window": [
"\t\t\tkey: process.env.AZURE_STORAGE_ACCESS_KEY,\n",
"\t\t\tcontainer: 'sourcemaps',\n",
"\t\t\tprefix: commit + '/'\n",
"\t\t}));\n",
"\tres.on('error', (err) => {\n",
"\t\tconsole.log('ERROR uploading sourcemaps');\n",
"\t\tconsole.error(err);\n",
"\t});\n",
"\tres.on('end', () => {\n",
"\t\tconsole.log('Completed uploading sourcemaps');\n",
"\t});\n",
"\treturn res;\n",
"});\n",
"\n",
"const allConfigDetailsPath = path.join(os.tmpdir(), 'configuration.json');\n",
"gulp.task('upload-vscode-configuration', ['generate-vscode-configuration'], () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "build/gulpfile.vscode.js",
"type": "replace",
"edit_start_line_idx": 528
} | {
"name": "objective-c",
"displayName": "%displayName%",
"description": "%description%",
"version": "1.0.0",
"publisher": "vscode",
"engines": {
"vscode": "*"
},
"scripts": {
"update-grammar": "node ../../build/npm/update-grammar.js atom/language-objective-c grammars/objective-c.cson ./syntaxes/objective-c.tmLanguage.json && node ../../build/npm/update-grammar.js atom/language-objective-c grammars/objective-c%2B%2B.cson ./syntaxes/objective-c++.tmLanguage.json"
},
"contributes": {
"languages": [
{
"id": "objective-c",
"extensions": [
".m"
],
"aliases": [
"Objective-C"
],
"configuration": "./language-configuration.json"
},
{
"id": "objective-cpp",
"extensions": [
".mm"
],
"aliases": [
"Objective-C++"
],
"configuration": "./language-configuration.json"
}
],
"grammars": [
{
"language": "objective-c",
"scopeName": "source.objc",
"path": "./syntaxes/objective-c.tmLanguage.json"
},
{
"language": "objective-cpp",
"scopeName": "source.objcpp",
"path": "./syntaxes/objective-c++.tmLanguage.json"
}
]
}
} | extensions/objective-c/package.json | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.00017692438268568367,
0.00016820344899315387,
0.00016403022164013237,
0.0001676589745329693,
0.0000046323448259499855
] |
{
"id": 1,
"code_window": [
"\t\t\tkey: process.env.AZURE_STORAGE_ACCESS_KEY,\n",
"\t\t\tcontainer: 'sourcemaps',\n",
"\t\t\tprefix: commit + '/'\n",
"\t\t}));\n",
"\tres.on('error', (err) => {\n",
"\t\tconsole.log('ERROR uploading sourcemaps');\n",
"\t\tconsole.error(err);\n",
"\t});\n",
"\tres.on('end', () => {\n",
"\t\tconsole.log('Completed uploading sourcemaps');\n",
"\t});\n",
"\treturn res;\n",
"});\n",
"\n",
"const allConfigDetailsPath = path.join(os.tmpdir(), 'configuration.json');\n",
"gulp.task('upload-vscode-configuration', ['generate-vscode-configuration'], () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "build/gulpfile.vscode.js",
"type": "replace",
"edit_start_line_idx": 528
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#f6f6f6}.icon-vs-out{fill:#f6f6f6}.icon-vs-bg{fill:#424242}.icon-vs-fg{fill:#f0eff1}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M16 5V2H9V1H0v14h13v-3h3V9h-1V6H9V5h7zm-8 7V9h1v3H8z" id="outline"/><path class="icon-vs-fg" d="M2 3h5v1H2V3z" id="iconFg"/><path class="icon-vs-bg" d="M15 4h-5V3h5v1zm-1 3h-2v1h2V7zm-4 0H1v1h9V7zm2 6H1v1h11v-1zm-5-3H1v1h6v-1zm8 0h-5v1h5v-1zM8 2v3H1V2h7zM7 3H2v1h5V3z" id="iconBg"/></svg> | src/vs/editor/contrib/suggest/media/IntelliSenseKeyword_16x.svg | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.0003672107413876802,
0.0003672107413876802,
0.0003672107413876802,
0.0003672107413876802,
0
] |
{
"id": 1,
"code_window": [
"\t\t\tkey: process.env.AZURE_STORAGE_ACCESS_KEY,\n",
"\t\t\tcontainer: 'sourcemaps',\n",
"\t\t\tprefix: commit + '/'\n",
"\t\t}));\n",
"\tres.on('error', (err) => {\n",
"\t\tconsole.log('ERROR uploading sourcemaps');\n",
"\t\tconsole.error(err);\n",
"\t});\n",
"\tres.on('end', () => {\n",
"\t\tconsole.log('Completed uploading sourcemaps');\n",
"\t});\n",
"\treturn res;\n",
"});\n",
"\n",
"const allConfigDetailsPath = path.join(os.tmpdir(), 'configuration.json');\n",
"gulp.task('upload-vscode-configuration', ['generate-vscode-configuration'], () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "build/gulpfile.vscode.js",
"type": "replace",
"edit_start_line_idx": 528
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { isObject, isUndefinedOrNull, isArray } from 'vs/base/common/types';
export function deepClone<T>(obj: T): T {
if (!obj || typeof obj !== 'object') {
return obj;
}
if (obj instanceof RegExp) {
// See https://github.com/Microsoft/TypeScript/issues/10990
return obj as any;
}
const result: any = Array.isArray(obj) ? [] : {};
Object.keys(obj).forEach((key: string) => {
if (obj[key] && typeof obj[key] === 'object') {
result[key] = deepClone(obj[key]);
} else {
result[key] = obj[key];
}
});
return result;
}
export function deepFreeze<T>(obj: T): T {
if (!obj || typeof obj !== 'object') {
return obj;
}
const stack: any[] = [obj];
while (stack.length > 0) {
let obj = stack.shift();
Object.freeze(obj);
for (const key in obj) {
if (_hasOwnProperty.call(obj, key)) {
let prop = obj[key];
if (typeof prop === 'object' && !Object.isFrozen(prop)) {
stack.push(prop);
}
}
}
}
return obj;
}
const _hasOwnProperty = Object.prototype.hasOwnProperty;
export function cloneAndChange(obj: any, changer: (orig: any) => any): any {
return _cloneAndChange(obj, changer, []);
}
function _cloneAndChange(obj: any, changer: (orig: any) => any, encounteredObjects: any[]): any {
if (isUndefinedOrNull(obj)) {
return obj;
}
const changed = changer(obj);
if (typeof changed !== 'undefined') {
return changed;
}
if (isArray(obj)) {
const r1: any[] = [];
for (let i1 = 0; i1 < obj.length; i1++) {
r1.push(_cloneAndChange(obj[i1], changer, encounteredObjects));
}
return r1;
}
if (isObject(obj)) {
if (encounteredObjects.indexOf(obj) >= 0) {
throw new Error('Cannot clone recursive data-structure');
}
encounteredObjects.push(obj);
const r2 = {};
for (let i2 in obj) {
if (_hasOwnProperty.call(obj, i2)) {
(r2 as any)[i2] = _cloneAndChange(obj[i2], changer, encounteredObjects);
}
}
encounteredObjects.pop();
return r2;
}
return obj;
}
/**
* Copies all properties of source into destination. The optional parameter "overwrite" allows to control
* if existing properties on the destination should be overwritten or not. Defaults to true (overwrite).
*/
export function mixin(destination: any, source: any, overwrite: boolean = true): any {
if (!isObject(destination)) {
return source;
}
if (isObject(source)) {
Object.keys(source).forEach(key => {
if (key in destination) {
if (overwrite) {
if (isObject(destination[key]) && isObject(source[key])) {
mixin(destination[key], source[key], overwrite);
} else {
destination[key] = source[key];
}
}
} else {
destination[key] = source[key];
}
});
}
return destination;
}
export function assign(destination: any, ...sources: any[]): any {
sources.forEach(source => Object.keys(source).forEach(key => destination[key] = source[key]));
return destination;
}
export function equals(one: any, other: any): boolean {
if (one === other) {
return true;
}
if (one === null || one === undefined || other === null || other === undefined) {
return false;
}
if (typeof one !== typeof other) {
return false;
}
if (typeof one !== 'object') {
return false;
}
if ((Array.isArray(one)) !== (Array.isArray(other))) {
return false;
}
let i: number;
let key: string;
if (Array.isArray(one)) {
if (one.length !== other.length) {
return false;
}
for (i = 0; i < one.length; i++) {
if (!equals(one[i], other[i])) {
return false;
}
}
} else {
const oneKeys: string[] = [];
for (key in one) {
oneKeys.push(key);
}
oneKeys.sort();
const otherKeys: string[] = [];
for (key in other) {
otherKeys.push(key);
}
otherKeys.sort();
if (!equals(oneKeys, otherKeys)) {
return false;
}
for (i = 0; i < oneKeys.length; i++) {
if (!equals(one[oneKeys[i]], other[oneKeys[i]])) {
return false;
}
}
}
return true;
}
export function arrayToHash(array: any[]) {
const result: any = {};
for (let i = 0; i < array.length; ++i) {
result[array[i]] = true;
}
return result;
}
/**
* Given an array of strings, returns a function which, given a string
* returns true or false whether the string is in that array.
*/
export function createKeywordMatcher(arr: string[], caseInsensitive: boolean = false): (str: string) => boolean {
if (caseInsensitive) {
arr = arr.map(function (x) { return x.toLowerCase(); });
}
const hash = arrayToHash(arr);
if (caseInsensitive) {
return function (word) {
return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase());
};
} else {
return function (word) {
return hash[word] !== undefined && hash.hasOwnProperty(word);
};
}
}
/**
* Calls JSON.Stringify with a replacer to break apart any circular references.
* This prevents JSON.stringify from throwing the exception
* "Uncaught TypeError: Converting circular structure to JSON"
*/
export function safeStringify(obj: any): string {
const seen: any[] = [];
return JSON.stringify(obj, (key, value) => {
if (isObject(value) || Array.isArray(value)) {
if (seen.indexOf(value) !== -1) {
return '[Circular]';
} else {
seen.push(value);
}
}
return value;
});
}
export function getOrDefault<T, R>(obj: T, fn: (obj: T) => R, defaultValue: R = null): R {
const result = fn(obj);
return typeof result === 'undefined' ? defaultValue : result;
}
type obj = { [key: string]: any; };
/**
* Returns an object that has keys for each value that is different in the base object. Keys
* that do not exist in the target but in the base object are not considered.
*
* Note: This is not a deep-diffing method, so the values are strictly taken into the resulting
* object if they differ.
*
* @param base the object to diff against
* @param obj the object to use for diffing
*/
export function distinct(base: obj, target: obj): obj {
const result = Object.create(null);
if (!base || !target) {
return result;
}
const targetKeys = Object.keys(target);
targetKeys.forEach(k => {
const baseValue = base[k];
const targetValue = target[k];
if (!equals(baseValue, targetValue)) {
result[k] = targetValue;
}
});
return result;
}
| src/vs/base/common/objects.ts | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.0010133088799193501,
0.00020208652131259441,
0.0001617834932403639,
0.00016994000179693103,
0.00016227905871346593
] |
{
"id": 2,
"code_window": [
" es.readArray(files).pipe(result);\n",
" })\n",
" .catch(function (err) { return result.emit('error', err); });\n",
" return result.pipe(stats_1.createStatsStream(path.basename(extensionPath)));\n",
"}\n",
"var baseHeaders = {\n",
" 'X-Market-Client-Id': 'VSCode Build',\n",
" 'User-Agent': 'VSCode Build',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"function error(err) {\n",
" var result = es.through();\n",
" setTimeout(function () { return result.emit('error', err); });\n",
" return result;\n",
"}\n"
],
"file_path": "build/lib/extensions.js",
"type": "add",
"edit_start_line_idx": 152
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as es from 'event-stream';
import * as fs from 'fs';
import * as glob from 'glob';
import * as gulp from 'gulp';
import * as path from 'path';
import { Stream } from 'stream';
import * as File from 'vinyl';
import * as vsce from 'vsce';
import { createStatsStream } from './stats';
import * as util2 from './util';
import remote = require('gulp-remote-src');
const vzip = require('gulp-vinyl-zip');
const filter = require('gulp-filter');
const rename = require('gulp-rename');
const util = require('gulp-util');
const buffer = require('gulp-buffer');
const json = require('gulp-json-editor');
const webpack = require('webpack');
const webpackGulp = require('webpack-stream');
const root = path.resolve(path.join(__dirname, '..', '..'));
function fromLocal(extensionPath: string, sourceMappingURLBase?: string): Stream {
const webpackFilename = path.join(extensionPath, 'extension.webpack.config.js');
if (fs.existsSync(webpackFilename)) {
return fromLocalWebpack(extensionPath, sourceMappingURLBase);
} else {
return fromLocalNormal(extensionPath);
}
}
function fromLocalWebpack(extensionPath: string, sourceMappingURLBase: string): Stream {
let result = es.through();
let packagedDependencies: string[] = [];
let packageJsonConfig = require(path.join(extensionPath, 'package.json'));
let webpackRootConfig = require(path.join(extensionPath, 'extension.webpack.config.js'));
for (const key in webpackRootConfig.externals) {
if (key in packageJsonConfig.dependencies) {
packagedDependencies.push(key);
}
}
vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn, packagedDependencies }).then(fileNames => {
const files = fileNames
.map(fileName => path.join(extensionPath, fileName))
.map(filePath => new File({
path: filePath,
stat: fs.statSync(filePath),
base: extensionPath,
contents: fs.createReadStream(filePath) as any
}));
const filesStream = es.readArray(files);
// check for a webpack configuration files, then invoke webpack
// and merge its output with the files stream. also rewrite the package.json
// file to a new entry point
const webpackConfigLocations = (<string[]>glob.sync(
path.join(extensionPath, '/**/extension.webpack.config.js'),
{ ignore: ['**/node_modules'] }
));
const packageJsonFilter = filter(f => {
if (path.basename(f.path) === 'package.json') {
// only modify package.json's next to the webpack file.
// to be safe, use existsSync instead of path comparison.
return fs.existsSync(path.join(path.dirname(f.path), 'extension.webpack.config.js'));
}
return false;
}, { restore: true });
const patchFilesStream = filesStream
.pipe(packageJsonFilter)
.pipe(buffer())
.pipe(json(data => {
// hardcoded entry point directory!
data.main = data.main.replace('/out/', /dist/);
return data;
}))
.pipe(packageJsonFilter.restore);
const webpackStreams = webpackConfigLocations.map(webpackConfigPath => {
const webpackDone = (err, stats) => {
util.log(`Bundled extension: ${util.colors.yellow(path.join(path.basename(extensionPath), path.relative(extensionPath, webpackConfigPath)))}...`);
if (err) {
result.emit('error', err);
}
const { compilation } = stats;
if (compilation.errors.length > 0) {
result.emit('error', compilation.errors.join('\n'));
}
if (compilation.warnings.length > 0) {
result.emit('error', compilation.warnings.join('\n'));
}
};
const webpackConfig = {
...require(webpackConfigPath),
...{ mode: 'production' }
};
let relativeOutputPath = path.relative(extensionPath, webpackConfig.output.path);
return webpackGulp(webpackConfig, webpack, webpackDone)
.pipe(es.through(function (data) {
data.stat = data.stat || {};
data.base = extensionPath;
this.emit('data', data);
}))
.pipe(es.through(function (data: File) {
// source map handling:
// * rewrite sourceMappingURL
// * save to disk so that upload-task picks this up
if (sourceMappingURLBase) {
const contents = (<Buffer>data.contents).toString('utf8');
data.contents = Buffer.from(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, function (_m, g1) {
return `\n//# sourceMappingURL=${sourceMappingURLBase}/extensions/${path.basename(extensionPath)}/${relativeOutputPath}/${g1}`;
}), 'utf8');
if (/\.js\.map$/.test(data.path)) {
if (!fs.existsSync(path.dirname(data.path))) {
fs.mkdirSync(path.dirname(data.path));
}
fs.writeFileSync(data.path, data.contents);
}
}
this.emit('data', data);
}));
});
es.merge(...webpackStreams, patchFilesStream)
// .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(packagedDependencies);
result.emit('error', err);
});
return result.pipe(createStatsStream(path.basename(extensionPath)));
}
function fromLocalNormal(extensionPath: string): Stream {
const result = es.through();
vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn })
.then(fileNames => {
const files = fileNames
.map(fileName => path.join(extensionPath, fileName))
.map(filePath => new File({
path: filePath,
stat: fs.statSync(filePath),
base: extensionPath,
contents: fs.createReadStream(filePath) as any
}));
es.readArray(files).pipe(result);
})
.catch(err => result.emit('error', err));
return result.pipe(createStatsStream(path.basename(extensionPath)));
}
const baseHeaders = {
'X-Market-Client-Id': 'VSCode Build',
'User-Agent': 'VSCode Build',
'X-Market-User-Id': '291C1CD0-051A-4123-9B4B-30D60EF52EE2',
};
export function fromMarketplace(extensionName: string, version: string, metadata: any): Stream {
const [publisher, name] = extensionName.split('.');
const url = `https://marketplace.visualstudio.com/_apis/public/gallery/publishers/${publisher}/vsextensions/${name}/${version}/vspackage`;
util.log('Downloading extension:', util.colors.yellow(`${extensionName}@${version}`), '...');
const options = {
base: url,
requestOptions: {
gzip: true,
headers: baseHeaders
}
};
const packageJsonFilter = filter('package.json', { restore: true });
return remote('', options)
.on('error', function (err) {
console.log('Error downloading extension:', util.colors.yellow(extensionName + "@" + version));
console.error(err);
})
.on('end', function () {
console.log('Downloaded extension:', util.colors.yellow(extensionName + "@" + version));
})
.pipe(vzip.src())
.pipe(filter('extension/**'))
.pipe(rename(p => p.dirname = p.dirname.replace(/^extension\/?/, '')))
.pipe(packageJsonFilter)
.pipe(buffer())
.pipe(json({ __metadata: metadata }))
.pipe(packageJsonFilter.restore);
}
interface IPackageExtensionsOptions {
/**
* Set to undefined to package all of them.
*/
desiredExtensions?: string[];
sourceMappingURLBase?: string;
}
const excludedExtensions = [
'vscode-api-tests',
'vscode-colorize-tests',
'ms-vscode.node-debug',
'ms-vscode.node-debug2',
];
interface IBuiltInExtension {
name: string;
version: string;
repo: string;
metadata: any;
}
const builtInExtensions: IBuiltInExtension[] = require('../builtInExtensions.json');
/**
* 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
* stack frames to complete the download in under 2 minutes, at which point the
* marketplace server cuts off the http request. So, we sequentialize the extensino tasks.
*/
function sequence(streamProviders: { (): Stream }[]): Stream {
const result = es.through();
function pop() {
if (streamProviders.length === 0) {
result.emit('end');
} else {
const fn = streamProviders.shift();
fn()
.on('end', function () { setTimeout(pop, 0); })
.pipe(result, { end: false });
}
}
pop();
return result;
}
export function packageExtensionsStream(opts?: IPackageExtensionsOptions): NodeJS.ReadWriteStream {
opts = opts || {};
const localExtensionDescriptions = (<string[]>glob.sync('extensions/*/package.json'))
.map(manifestPath => {
const extensionPath = path.dirname(path.join(root, manifestPath));
const extensionName = path.basename(extensionPath);
return { name: extensionName, path: extensionPath };
})
.filter(({ name }) => excludedExtensions.indexOf(name) === -1)
.filter(({ name }) => opts.desiredExtensions ? opts.desiredExtensions.indexOf(name) >= 0 : true)
.filter(({ name }) => builtInExtensions.every(b => b.name !== name));
const localExtensions = () => es.merge(...localExtensionDescriptions.map(extension => {
return fromLocal(extension.path, opts.sourceMappingURLBase)
.pipe(rename(p => p.dirname = `extensions/${extension.name}/${p.dirname}`));
}));
const localExtensionDependencies = () => gulp.src('extensions/node_modules/**', { base: '.' });
const marketplaceExtensions = () => es.merge(
...builtInExtensions
.filter(({ name }) => opts.desiredExtensions ? opts.desiredExtensions.indexOf(name) >= 0 : true)
.map(extension => {
return fromMarketplace(extension.name, extension.version, extension.metadata)
.pipe(rename(p => p.dirname = `extensions/${extension.name}/${p.dirname}`));
})
);
return sequence([localExtensions, localExtensionDependencies, marketplaceExtensions])
.pipe(util2.setExecutableBit(['**/*.sh']))
.pipe(filter(['**', '!**/*.js.map']));
}
| build/lib/extensions.ts | 1 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.9987680315971375,
0.0673590898513794,
0.00016554318426642567,
0.00021340530656743795,
0.24886329472064972
] |
{
"id": 2,
"code_window": [
" es.readArray(files).pipe(result);\n",
" })\n",
" .catch(function (err) { return result.emit('error', err); });\n",
" return result.pipe(stats_1.createStatsStream(path.basename(extensionPath)));\n",
"}\n",
"var baseHeaders = {\n",
" 'X-Market-Client-Id': 'VSCode Build',\n",
" 'User-Agent': 'VSCode Build',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"function error(err) {\n",
" var result = es.through();\n",
" setTimeout(function () { return result.emit('error', err); });\n",
" return result;\n",
"}\n"
],
"file_path": "build/lib/extensions.js",
"type": "add",
"edit_start_line_idx": 152
} | {
"displayName": "Log",
"description": "Provides syntax highlighting for files with .log extension."
} | extensions/log/package.nls.json | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.0001647498575039208,
0.0001647498575039208,
0.0001647498575039208,
0.0001647498575039208,
0
] |
{
"id": 2,
"code_window": [
" es.readArray(files).pipe(result);\n",
" })\n",
" .catch(function (err) { return result.emit('error', err); });\n",
" return result.pipe(stats_1.createStatsStream(path.basename(extensionPath)));\n",
"}\n",
"var baseHeaders = {\n",
" 'X-Market-Client-Id': 'VSCode Build',\n",
" 'User-Agent': 'VSCode Build',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"function error(err) {\n",
" var result = es.through();\n",
" setTimeout(function () { return result.emit('error', err); });\n",
" return result;\n",
"}\n"
],
"file_path": "build/lib/extensions.js",
"type": "add",
"edit_start_line_idx": 152
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#f6f6f6}.icon-vs-out{fill:#f6f6f6}.icon-vs-bg{fill:#424242}.icon-vs-fg{fill:#f0eff1}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M0 16V0h11v6h5v10H0z" id="outline" style="display: none;"/><path class="icon-vs-fg" d="M4 14H2V4h7v3H4v7zm10 0H5v-4h9v4z" id="iconFg" style="display: none;"/><path class="icon-vs-bg" d="M10 7V1H1v14h14V7h-5zm-6 7H2V4h7v3H4v7zm10 0H5v-4h9v4z" id="iconBg"/></svg> | src/vs/workbench/browser/actions/media/editor-layout.svg | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.0001734782854327932,
0.0001734782854327932,
0.0001734782854327932,
0.0001734782854327932,
0
] |
{
"id": 2,
"code_window": [
" es.readArray(files).pipe(result);\n",
" })\n",
" .catch(function (err) { return result.emit('error', err); });\n",
" return result.pipe(stats_1.createStatsStream(path.basename(extensionPath)));\n",
"}\n",
"var baseHeaders = {\n",
" 'X-Market-Client-Id': 'VSCode Build',\n",
" 'User-Agent': 'VSCode Build',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"function error(err) {\n",
" var result = es.through();\n",
" setTimeout(function () { return result.emit('error', err); });\n",
" return result;\n",
"}\n"
],
"file_path": "build/lib/extensions.js",
"type": "add",
"edit_start_line_idx": 152
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { URI } from 'vs/base/common/uri';
import * as assert from 'assert';
import { TPromise } from 'vs/base/common/winjs.base';
import { TestCodeEditorService } from 'vs/editor/test/browser/editorTestServices';
import { ICommandService, NullCommandService, CommandsRegistry } from 'vs/platform/commands/common/commands';
import { OpenerService } from 'vs/editor/browser/services/openerService';
suite('OpenerService', function () {
const editorService = new TestCodeEditorService();
let lastCommand: { id: string, args: any[] };
const commandService = new class implements ICommandService {
_serviceBrand: any;
onWillExecuteCommand = () => ({ dispose: () => { } });
executeCommand(id: string, ...args: any[]): TPromise<any> {
lastCommand = { id, args };
return Promise.resolve(undefined);
}
};
setup(function () {
lastCommand = undefined;
});
test('delegate to editorService, scheme:///fff', function () {
const openerService = new OpenerService(editorService, NullCommandService);
openerService.open(URI.parse('another:///somepath'));
assert.equal(editorService.lastInput.options.selection, undefined);
});
test('delegate to editorService, scheme:///fff#L123', function () {
const openerService = new OpenerService(editorService, NullCommandService);
openerService.open(URI.parse('file:///somepath#L23'));
assert.equal(editorService.lastInput.options.selection.startLineNumber, 23);
assert.equal(editorService.lastInput.options.selection.startColumn, 1);
assert.equal(editorService.lastInput.options.selection.endLineNumber, undefined);
assert.equal(editorService.lastInput.options.selection.endColumn, undefined);
assert.equal(editorService.lastInput.resource.fragment, '');
openerService.open(URI.parse('another:///somepath#L23'));
assert.equal(editorService.lastInput.options.selection.startLineNumber, 23);
assert.equal(editorService.lastInput.options.selection.startColumn, 1);
openerService.open(URI.parse('another:///somepath#L23,45'));
assert.equal(editorService.lastInput.options.selection.startLineNumber, 23);
assert.equal(editorService.lastInput.options.selection.startColumn, 45);
assert.equal(editorService.lastInput.options.selection.endLineNumber, undefined);
assert.equal(editorService.lastInput.options.selection.endColumn, undefined);
assert.equal(editorService.lastInput.resource.fragment, '');
});
test('delegate to editorService, scheme:///fff#123,123', function () {
const openerService = new OpenerService(editorService, NullCommandService);
openerService.open(URI.parse('file:///somepath#23'));
assert.equal(editorService.lastInput.options.selection.startLineNumber, 23);
assert.equal(editorService.lastInput.options.selection.startColumn, 1);
assert.equal(editorService.lastInput.options.selection.endLineNumber, undefined);
assert.equal(editorService.lastInput.options.selection.endColumn, undefined);
assert.equal(editorService.lastInput.resource.fragment, '');
openerService.open(URI.parse('file:///somepath#23,45'));
assert.equal(editorService.lastInput.options.selection.startLineNumber, 23);
assert.equal(editorService.lastInput.options.selection.startColumn, 45);
assert.equal(editorService.lastInput.options.selection.endLineNumber, undefined);
assert.equal(editorService.lastInput.options.selection.endColumn, undefined);
assert.equal(editorService.lastInput.resource.fragment, '');
});
test('delegate to commandsService, command:someid', function () {
const openerService = new OpenerService(editorService, commandService);
// unknown command
openerService.open(URI.parse('command:foobar'));
assert.equal(lastCommand, undefined);
assert.equal(editorService.lastInput.resource.toString(), 'command:foobar');
assert.equal(editorService.lastInput.options.selection, undefined);
const id = `aCommand${Math.random()}`;
CommandsRegistry.registerCommand(id, function () { });
openerService.open(URI.parse('command:' + id));
assert.equal(lastCommand.id, id);
assert.equal(lastCommand.args.length, 0);
openerService.open(URI.parse('command:' + id).with({ query: '123' }));
assert.equal(lastCommand.id, id);
assert.equal(lastCommand.args.length, 1);
assert.equal(lastCommand.args[0], '123');
openerService.open(URI.parse('command:' + id).with({ query: JSON.stringify([12, true]) }));
assert.equal(lastCommand.id, id);
assert.equal(lastCommand.args.length, 2);
assert.equal(lastCommand.args[0], 12);
assert.equal(lastCommand.args[1], true);
});
});
| src/vs/editor/test/browser/services/openerService.test.ts | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.00017933208437170833,
0.00017623582971282303,
0.0001725445908959955,
0.00017679485608823597,
0.0000019286740098323207
] |
{
"id": 3,
"code_window": [
" };\n",
" var packageJsonFilter = filter('package.json', { restore: true });\n",
" return remote('', options)\n",
" .on('error', function (err) {\n",
" console.log('Error downloading extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
" console.error(err);\n",
" })\n",
" .on('end', function () {\n",
" console.log('Downloaded extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
" })\n",
" .pipe(vzip.src())\n",
" .pipe(filter('extension/**'))\n",
" .pipe(rename(function (p) { return p.dirname = p.dirname.replace(/^extension\\/?/, ''); }))\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "build/lib/extensions.js",
"type": "replace",
"edit_start_line_idx": 170
} | "use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* 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 });
var es = require("event-stream");
var fs = require("fs");
var glob = require("glob");
var gulp = require("gulp");
var path = require("path");
var File = require("vinyl");
var vsce = require("vsce");
var stats_1 = require("./stats");
var util2 = require("./util");
var remote = require("gulp-remote-src");
var vzip = require('gulp-vinyl-zip');
var filter = require('gulp-filter');
var rename = require('gulp-rename');
var util = require('gulp-util');
var buffer = require('gulp-buffer');
var json = require('gulp-json-editor');
var webpack = require('webpack');
var webpackGulp = require('webpack-stream');
var root = path.resolve(path.join(__dirname, '..', '..'));
function fromLocal(extensionPath, sourceMappingURLBase) {
var webpackFilename = path.join(extensionPath, 'extension.webpack.config.js');
if (fs.existsSync(webpackFilename)) {
return fromLocalWebpack(extensionPath, sourceMappingURLBase);
}
else {
return fromLocalNormal(extensionPath);
}
}
function fromLocalWebpack(extensionPath, sourceMappingURLBase) {
var result = es.through();
var packagedDependencies = [];
var packageJsonConfig = require(path.join(extensionPath, 'package.json'));
var webpackRootConfig = require(path.join(extensionPath, 'extension.webpack.config.js'));
for (var key in webpackRootConfig.externals) {
if (key in packageJsonConfig.dependencies) {
packagedDependencies.push(key);
}
}
vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn, packagedDependencies: packagedDependencies }).then(function (fileNames) {
var files = fileNames
.map(function (fileName) { return path.join(extensionPath, fileName); })
.map(function (filePath) { return new File({
path: filePath,
stat: fs.statSync(filePath),
base: extensionPath,
contents: fs.createReadStream(filePath)
}); });
var filesStream = es.readArray(files);
// check for a webpack configuration files, then invoke webpack
// and merge its output with the files stream. also rewrite the package.json
// file to a new entry point
var webpackConfigLocations = glob.sync(path.join(extensionPath, '/**/extension.webpack.config.js'), { ignore: ['**/node_modules'] });
var packageJsonFilter = filter(function (f) {
if (path.basename(f.path) === 'package.json') {
// only modify package.json's next to the webpack file.
// to be safe, use existsSync instead of path comparison.
return fs.existsSync(path.join(path.dirname(f.path), 'extension.webpack.config.js'));
}
return false;
}, { restore: true });
var patchFilesStream = filesStream
.pipe(packageJsonFilter)
.pipe(buffer())
.pipe(json(function (data) {
// hardcoded entry point directory!
data.main = data.main.replace('/out/', /dist/);
return data;
}))
.pipe(packageJsonFilter.restore);
var webpackStreams = webpackConfigLocations.map(function (webpackConfigPath) {
var webpackDone = function (err, stats) {
util.log("Bundled extension: " + util.colors.yellow(path.join(path.basename(extensionPath), path.relative(extensionPath, webpackConfigPath))) + "...");
if (err) {
result.emit('error', err);
}
var compilation = stats.compilation;
if (compilation.errors.length > 0) {
result.emit('error', compilation.errors.join('\n'));
}
if (compilation.warnings.length > 0) {
result.emit('error', compilation.warnings.join('\n'));
}
};
var webpackConfig = __assign({}, require(webpackConfigPath), { mode: 'production' });
var relativeOutputPath = path.relative(extensionPath, webpackConfig.output.path);
return webpackGulp(webpackConfig, webpack, webpackDone)
.pipe(es.through(function (data) {
data.stat = data.stat || {};
data.base = extensionPath;
this.emit('data', data);
}))
.pipe(es.through(function (data) {
// source map handling:
// * rewrite sourceMappingURL
// * save to disk so that upload-task picks this up
if (sourceMappingURLBase) {
var contents = data.contents.toString('utf8');
data.contents = Buffer.from(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, function (_m, g1) {
return "\n//# sourceMappingURL=" + sourceMappingURLBase + "/extensions/" + path.basename(extensionPath) + "/" + relativeOutputPath + "/" + g1;
}), 'utf8');
if (/\.js\.map$/.test(data.path)) {
if (!fs.existsSync(path.dirname(data.path))) {
fs.mkdirSync(path.dirname(data.path));
}
fs.writeFileSync(data.path, data.contents);
}
}
this.emit('data', data);
}));
});
es.merge.apply(es, webpackStreams.concat([patchFilesStream])).pipe(result);
}).catch(function (err) {
console.error(extensionPath);
console.error(packagedDependencies);
result.emit('error', err);
});
return result.pipe(stats_1.createStatsStream(path.basename(extensionPath)));
}
function fromLocalNormal(extensionPath) {
var result = es.through();
vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn })
.then(function (fileNames) {
var files = fileNames
.map(function (fileName) { return path.join(extensionPath, fileName); })
.map(function (filePath) { return new File({
path: filePath,
stat: fs.statSync(filePath),
base: extensionPath,
contents: fs.createReadStream(filePath)
}); });
es.readArray(files).pipe(result);
})
.catch(function (err) { return result.emit('error', err); });
return result.pipe(stats_1.createStatsStream(path.basename(extensionPath)));
}
var baseHeaders = {
'X-Market-Client-Id': 'VSCode Build',
'User-Agent': 'VSCode Build',
'X-Market-User-Id': '291C1CD0-051A-4123-9B4B-30D60EF52EE2',
};
function fromMarketplace(extensionName, version, metadata) {
var _a = extensionName.split('.'), publisher = _a[0], name = _a[1];
var url = "https://marketplace.visualstudio.com/_apis/public/gallery/publishers/" + publisher + "/vsextensions/" + name + "/" + version + "/vspackage";
util.log('Downloading extension:', util.colors.yellow(extensionName + "@" + version), '...');
var options = {
base: url,
requestOptions: {
gzip: true,
headers: baseHeaders
}
};
var packageJsonFilter = filter('package.json', { restore: true });
return remote('', options)
.on('error', function (err) {
console.log('Error downloading extension:', util.colors.yellow(extensionName + "@" + version));
console.error(err);
})
.on('end', function () {
console.log('Downloaded extension:', util.colors.yellow(extensionName + "@" + version));
})
.pipe(vzip.src())
.pipe(filter('extension/**'))
.pipe(rename(function (p) { return p.dirname = p.dirname.replace(/^extension\/?/, ''); }))
.pipe(packageJsonFilter)
.pipe(buffer())
.pipe(json({ __metadata: metadata }))
.pipe(packageJsonFilter.restore);
}
exports.fromMarketplace = fromMarketplace;
var excludedExtensions = [
'vscode-api-tests',
'vscode-colorize-tests',
'ms-vscode.node-debug',
'ms-vscode.node-debug2',
];
var builtInExtensions = require('../builtInExtensions.json');
/**
* 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
* stack frames to complete the download in under 2 minutes, at which point the
* marketplace server cuts off the http request. So, we sequentialize the extensino tasks.
*/
function sequence(streamProviders) {
var result = es.through();
function pop() {
if (streamProviders.length === 0) {
result.emit('end');
}
else {
var fn = streamProviders.shift();
fn()
.on('end', function () { setTimeout(pop, 0); })
.pipe(result, { end: false });
}
}
pop();
return result;
}
function packageExtensionsStream(opts) {
opts = opts || {};
var localExtensionDescriptions = glob.sync('extensions/*/package.json')
.map(function (manifestPath) {
var extensionPath = path.dirname(path.join(root, manifestPath));
var extensionName = path.basename(extensionPath);
return { name: extensionName, path: extensionPath };
})
.filter(function (_a) {
var name = _a.name;
return excludedExtensions.indexOf(name) === -1;
})
.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)
.pipe(rename(function (p) { return p.dirname = "extensions/" + extension.name + "/" + p.dirname; }));
})); };
var localExtensionDependencies = function () { return gulp.src('extensions/node_modules/**', { base: '.' }); };
var marketplaceExtensions = function () { return es.merge.apply(es, builtInExtensions
.filter(function (_a) {
var name = _a.name;
return opts.desiredExtensions ? opts.desiredExtensions.indexOf(name) >= 0 : true;
})
.map(function (extension) {
return fromMarketplace(extension.name, extension.version, extension.metadata)
.pipe(rename(function (p) { return p.dirname = "extensions/" + extension.name + "/" + p.dirname; }));
})); };
return sequence([localExtensions, localExtensionDependencies, marketplaceExtensions])
.pipe(util2.setExecutableBit(['**/*.sh']))
.pipe(filter(['**', '!**/*.js.map']));
}
exports.packageExtensionsStream = packageExtensionsStream;
| build/lib/extensions.js | 1 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.997651994228363,
0.1924946904182434,
0.000162399242981337,
0.0013158980291336775,
0.3879214823246002
] |
{
"id": 3,
"code_window": [
" };\n",
" var packageJsonFilter = filter('package.json', { restore: true });\n",
" return remote('', options)\n",
" .on('error', function (err) {\n",
" console.log('Error downloading extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
" console.error(err);\n",
" })\n",
" .on('end', function () {\n",
" console.log('Downloaded extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
" })\n",
" .pipe(vzip.src())\n",
" .pipe(filter('extension/**'))\n",
" .pipe(rename(function (p) { return p.dirname = p.dirname.replace(/^extension\\/?/, ''); }))\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "build/lib/extensions.js",
"type": "replace",
"edit_start_line_idx": 170
} | src/vs/code/test/node/fixtures/vscode_folder/nested_vscode_folder/_vscode/settings.json | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.00016577617498114705,
0.00016577617498114705,
0.00016577617498114705,
0.00016577617498114705,
0
] |
|
{
"id": 3,
"code_window": [
" };\n",
" var packageJsonFilter = filter('package.json', { restore: true });\n",
" return remote('', options)\n",
" .on('error', function (err) {\n",
" console.log('Error downloading extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
" console.error(err);\n",
" })\n",
" .on('end', function () {\n",
" console.log('Downloaded extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
" })\n",
" .pipe(vzip.src())\n",
" .pipe(filter('extension/**'))\n",
" .pipe(rename(function (p) { return p.dirname = p.dirname.replace(/^extension\\/?/, ''); }))\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "build/lib/extensions.js",
"type": "replace",
"edit_start_line_idx": 170
} | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@types/[email protected]":
version "8.0.33"
resolved "https://registry.yarnpkg.com/@types/node/-/node-8.0.33.tgz#1126e94374014e54478092830704f6ea89df04cd"
integrity sha512-vmCdO8Bm1ExT+FWfC9sd9r4jwqM7o97gGy2WBshkkXbf/2nLAJQUrZfIhw27yVOtLUev6kSZc4cav/46KbDd8A==
"@types/semver@^5.5.0":
version "5.5.0"
resolved "https://registry.yarnpkg.com/@types/semver/-/semver-5.5.0.tgz#146c2a29ee7d3bae4bf2fcb274636e264c813c45"
integrity sha512-41qEJgBH/TWgo5NFSvBCJ1qkoi3Q6ONSF2avrHq1LVEZfYpdHmj0y9SuTK+u9ZhG1sYQKBL1AWXKyLWP4RaUoQ==
ajv@^5.1.0:
version "5.5.2"
resolved "https://registry.yarnpkg.com/ajv/-/ajv-5.5.2.tgz#73b5eeca3fab653e3d3f9422b341ad42205dc965"
integrity sha1-c7Xuyj+rZT49P5Qis0GtQiBdyWU=
dependencies:
co "^4.6.0"
fast-deep-equal "^1.0.0"
fast-json-stable-stringify "^2.0.0"
json-schema-traverse "^0.3.0"
ansi-cyan@^0.1.1:
version "0.1.1"
resolved "https://registry.yarnpkg.com/ansi-cyan/-/ansi-cyan-0.1.1.tgz#538ae528af8982f28ae30d86f2f17456d2609873"
integrity sha1-U4rlKK+JgvKK4w2G8vF0VtJgmHM=
dependencies:
ansi-wrap "0.1.0"
ansi-gray@^0.1.1:
version "0.1.1"
resolved "https://registry.yarnpkg.com/ansi-gray/-/ansi-gray-0.1.1.tgz#2962cf54ec9792c48510a3deb524436861ef7251"
integrity sha1-KWLPVOyXksSFEKPetSRDaGHvclE=
dependencies:
ansi-wrap "0.1.0"
ansi-red@^0.1.1:
version "0.1.1"
resolved "https://registry.yarnpkg.com/ansi-red/-/ansi-red-0.1.1.tgz#8c638f9d1080800a353c9c28c8a81ca4705d946c"
integrity sha1-jGOPnRCAgAo1PJwoyKgcpHBdlGw=
dependencies:
ansi-wrap "0.1.0"
ansi-regex@^2.0.0:
version "2.1.1"
resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df"
integrity sha1-w7M6te42DYbg5ijwRorn7yfWVN8=
ansi-styles@^2.2.1:
version "2.2.1"
resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe"
integrity sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=
[email protected]:
version "0.1.0"
resolved "https://registry.yarnpkg.com/ansi-wrap/-/ansi-wrap-0.1.0.tgz#a82250ddb0015e9a27ca82e82ea603bbfa45efaf"
integrity sha1-qCJQ3bABXponyoLoLqYDu/pF768=
[email protected]:
version "1.0.5"
resolved "https://registry.yarnpkg.com/applicationinsights/-/applicationinsights-1.0.5.tgz#a60d1ffdf7aa1ac77c637c0ef7fcf2a9671cc869"
integrity sha512-T6V4ZyhikGKnuqYGbNz1q5+ORROutUp58UqfLLwHH+X1RkcnEU+gW15kIKWJ8zqGWbilhn6bONJa+T5en642mg==
dependencies:
diagnostic-channel "0.2.0"
diagnostic-channel-publishers "0.2.1"
zone.js "0.7.6"
arr-diff@^1.0.1:
version "1.1.0"
resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-1.1.0.tgz#687c32758163588fef7de7b36fabe495eb1a399a"
integrity sha1-aHwydYFjWI/vfeezb6vklesaOZo=
dependencies:
arr-flatten "^1.0.1"
array-slice "^0.2.3"
arr-diff@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-2.0.0.tgz#8f3b827f955a8bd669697e4a4256ac3ceae356cf"
integrity sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=
dependencies:
arr-flatten "^1.0.1"
arr-flatten@^1.0.1:
version "1.1.0"
resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1"
integrity sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==
arr-union@^2.0.1:
version "2.1.0"
resolved "https://registry.yarnpkg.com/arr-union/-/arr-union-2.1.0.tgz#20f9eab5ec70f5c7d215b1077b1c39161d292c7d"
integrity sha1-IPnqtexw9cfSFbEHexw5Fh0pLH0=
array-differ@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/array-differ/-/array-differ-1.0.0.tgz#eff52e3758249d33be402b8bb8e564bb2b5d4031"
integrity sha1-7/UuN1gknTO+QCuLuOVkuytdQDE=
array-slice@^0.2.3:
version "0.2.3"
resolved "https://registry.yarnpkg.com/array-slice/-/array-slice-0.2.3.tgz#dd3cfb80ed7973a75117cdac69b0b99ec86186f5"
integrity sha1-3Tz7gO15c6dRF82sabC5nshhhvU=
array-union@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/array-union/-/array-union-1.0.2.tgz#9a34410e4f4e3da23dea375be5be70f24778ec39"
integrity sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=
dependencies:
array-uniq "^1.0.1"
array-uniq@^1.0.1, array-uniq@^1.0.2:
version "1.0.3"
resolved "https://registry.yarnpkg.com/array-uniq/-/array-uniq-1.0.3.tgz#af6ac877a25cc7f74e058894753858dfdb24fdb6"
integrity sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=
array-unique@^0.2.1:
version "0.2.1"
resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.2.1.tgz#a1d97ccafcbc2625cc70fadceb36a50c58b01a53"
integrity sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=
arrify@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d"
integrity sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=
asn1@~0.2.3:
version "0.2.3"
resolved "https://registry.yarnpkg.com/asn1/-/asn1-0.2.3.tgz#dac8787713c9966849fc8180777ebe9c1ddf3b86"
integrity sha1-2sh4dxPJlmhJ/IGAd36+nB3fO4Y=
[email protected], assert-plus@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525"
integrity sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=
asynckit@^0.4.0:
version "0.4.0"
resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
integrity sha1-x57Zf380y48robyXkLzDZkdLS3k=
aws-sign2@~0.7.0:
version "0.7.0"
resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.7.0.tgz#b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8"
integrity sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=
aws4@^1.6.0:
version "1.7.0"
resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.7.0.tgz#d4d0e9b9dbfca77bf08eeb0a8a471550fe39e289"
integrity sha512-32NDda82rhwD9/JBCCkB+MRYDp0oSvlo2IL6rQWA10PQi7tDUM3eqMSltXmY+Oyl/7N3P3qNtAlv7X0d9bI28w==
balanced-match@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767"
integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c=
bcrypt-pbkdf@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.1.tgz#63bc5dcb61331b92bc05fd528953c33462a06f8d"
integrity sha1-Y7xdy2EzG5K8Bf1SiVPDNGKgb40=
dependencies:
tweetnacl "^0.14.3"
beeper@^1.0.0:
version "1.1.1"
resolved "https://registry.yarnpkg.com/beeper/-/beeper-1.1.1.tgz#e6d5ea8c5dad001304a70b22638447f69cb2f809"
integrity sha1-5tXqjF2tABMEpwsiY4RH9pyy+Ak=
block-stream@*:
version "0.0.9"
resolved "https://registry.yarnpkg.com/block-stream/-/block-stream-0.0.9.tgz#13ebfe778a03205cfe03751481ebb4b3300c126a"
integrity sha1-E+v+d4oDIFz+A3UUgeu0szAMEmo=
dependencies:
inherits "~2.0.0"
[email protected]:
version "4.3.1"
resolved "https://registry.yarnpkg.com/boom/-/boom-4.3.1.tgz#4f8a3005cb4a7e3889f749030fd25b96e01d2e31"
integrity sha1-T4owBctKfjiJ90kDD9JbluAdLjE=
dependencies:
hoek "4.x.x"
[email protected]:
version "5.2.0"
resolved "https://registry.yarnpkg.com/boom/-/boom-5.2.0.tgz#5dd9da6ee3a5f302077436290cb717d3f4a54e02"
integrity sha512-Z5BTk6ZRe4tXXQlkqftmsAUANpXmuwlsF5Oov8ThoMbQRzdGTA1ngYRW160GexgOgjsFOKJz0LYhoNi+2AMBUw==
dependencies:
hoek "4.x.x"
brace-expansion@^1.1.7:
version "1.1.11"
resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd"
integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==
dependencies:
balanced-match "^1.0.0"
concat-map "0.0.1"
braces@^1.8.2:
version "1.8.5"
resolved "https://registry.yarnpkg.com/braces/-/braces-1.8.5.tgz#ba77962e12dff969d6b76711e914b737857bf6a7"
integrity sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=
dependencies:
expand-range "^1.8.1"
preserve "^0.2.0"
repeat-element "^1.1.2"
[email protected]:
version "1.3.0"
resolved "https://registry.yarnpkg.com/browser-stdout/-/browser-stdout-1.3.0.tgz#f351d32969d32fa5d7a5567154263d928ae3bd1f"
integrity sha1-81HTKWnTL6XXpVZxVCY9korjvR8=
buffer-crc32@~0.2.3:
version "0.2.13"
resolved "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242"
integrity sha1-DTM+PwDqxQqhRUq9MO+MKl2ackI=
buffer-from@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.0.0.tgz#4cb8832d23612589b0406e9e2956c17f06fdf531"
integrity sha512-83apNb8KK0Se60UE1+4Ukbe3HbfELJ6UlI4ldtOGs7So4KD26orJM8hIY9lxdzP+UpItH1Yh/Y8GUvNFWFFRxA==
caseless@~0.12.0:
version "0.12.0"
resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.12.0.tgz#1b681c21ff84033c826543090689420d187151dc"
integrity sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=
chalk@^1.0.0:
version "1.1.3"
resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98"
integrity sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=
dependencies:
ansi-styles "^2.2.1"
escape-string-regexp "^1.0.2"
has-ansi "^2.0.0"
strip-ansi "^3.0.0"
supports-color "^2.0.0"
clone-buffer@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/clone-buffer/-/clone-buffer-1.0.0.tgz#e3e25b207ac4e701af721e2cb5a16792cac3dc58"
integrity sha1-4+JbIHrE5wGvch4staFnksrD3Fg=
clone-stats@^0.0.1:
version "0.0.1"
resolved "https://registry.yarnpkg.com/clone-stats/-/clone-stats-0.0.1.tgz#b88f94a82cf38b8791d58046ea4029ad88ca99d1"
integrity sha1-uI+UqCzzi4eR1YBG6kAprYjKmdE=
clone-stats@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/clone-stats/-/clone-stats-1.0.0.tgz#b3782dff8bb5474e18b9b6bf0fdfe782f8777680"
integrity sha1-s3gt/4u1R04Yuba/D9/ngvh3doA=
clone@^0.2.0:
version "0.2.0"
resolved "https://registry.yarnpkg.com/clone/-/clone-0.2.0.tgz#c6126a90ad4f72dbf5acdb243cc37724fe93fc1f"
integrity sha1-xhJqkK1Pctv1rNskPMN3JP6T/B8=
clone@^1.0.0:
version "1.0.4"
resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.4.tgz#da309cc263df15994c688ca902179ca3c7cd7c7e"
integrity sha1-2jCcwmPfFZlMaIypAheco8fNfH4=
clone@^2.1.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/clone/-/clone-2.1.1.tgz#d217d1e961118e3ac9a4b8bba3285553bf647cdb"
integrity sha1-0hfR6WERjjrJpLi7oyhVU79kfNs=
cloneable-readable@^1.0.0:
version "1.1.2"
resolved "https://registry.yarnpkg.com/cloneable-readable/-/cloneable-readable-1.1.2.tgz#d591dee4a8f8bc15da43ce97dceeba13d43e2a65"
integrity sha512-Bq6+4t+lbM8vhTs/Bef5c5AdEMtapp/iFb6+s4/Hh9MVTt8OLKH7ZOOZSCT+Ys7hsHvqv0GuMPJ1lnQJVHvxpg==
dependencies:
inherits "^2.0.1"
process-nextick-args "^2.0.0"
readable-stream "^2.3.5"
co@^4.6.0:
version "4.6.0"
resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184"
integrity sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=
color-support@^1.1.3:
version "1.1.3"
resolved "https://registry.yarnpkg.com/color-support/-/color-support-1.1.3.tgz#93834379a1cc9a0c61f82f52f0d04322251bd5a2"
integrity sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==
[email protected], combined-stream@~1.0.5:
version "1.0.6"
resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.6.tgz#723e7df6e801ac5613113a7e445a9b69cb632818"
integrity sha1-cj599ugBrFYTETp+RFqbactjKBg=
dependencies:
delayed-stream "~1.0.0"
[email protected]:
version "2.11.0"
resolved "https://registry.yarnpkg.com/commander/-/commander-2.11.0.tgz#157152fd1e7a6c8d98a5b715cf376df928004563"
integrity sha512-b0553uYA5YAEGgyYIGYROzKQ7X5RAqedkfjiZxwi0kL1g3bOaBNNZfYkzt/CL0umgD5wc9Jec2FbB98CjkMRvQ==
[email protected]:
version "0.0.1"
resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"
integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=
convert-source-map@^1.1.1:
version "1.5.1"
resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.5.1.tgz#b8278097b9bc229365de5c62cf5fcaed8b5599e5"
integrity sha1-uCeAl7m8IpNl3lxiz1/K7YtVmeU=
[email protected], core-util-is@~1.0.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7"
integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=
[email protected]:
version "3.1.2"
resolved "https://registry.yarnpkg.com/cryptiles/-/cryptiles-3.1.2.tgz#a89fbb220f5ce25ec56e8c4aa8a4fd7b5b0d29fe"
integrity sha1-qJ+7Ig9c4l7FboxKqKT9e1sNKf4=
dependencies:
boom "5.x.x"
dashdash@^1.12.0:
version "1.14.1"
resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0"
integrity sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=
dependencies:
assert-plus "^1.0.0"
dateformat@^2.0.0:
version "2.2.0"
resolved "https://registry.yarnpkg.com/dateformat/-/dateformat-2.2.0.tgz#4065e2013cf9fb916ddfd82efb506ad4c6769062"
integrity sha1-QGXiATz5+5Ft39gu+1Bq1MZ2kGI=
[email protected]:
version "3.1.0"
resolved "https://registry.yarnpkg.com/debug/-/debug-3.1.0.tgz#5bb5a0672628b64149566ba16819e61518c67261"
integrity sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==
dependencies:
ms "2.0.0"
deep-assign@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/deep-assign/-/deep-assign-1.0.0.tgz#b092743be8427dc621ea0067cdec7e70dd19f37b"
integrity sha1-sJJ0O+hCfcYh6gBnzex+cN0Z83s=
dependencies:
is-obj "^1.0.0"
delayed-stream@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619"
integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk=
[email protected]:
version "0.2.1"
resolved "https://registry.yarnpkg.com/diagnostic-channel-publishers/-/diagnostic-channel-publishers-0.2.1.tgz#8e2d607a8b6d79fe880b548bc58cc6beb288c4f3"
integrity sha1-ji1geottef6IC1SLxYzGvrKIxPM=
[email protected]:
version "0.2.0"
resolved "https://registry.yarnpkg.com/diagnostic-channel/-/diagnostic-channel-0.2.0.tgz#cc99af9612c23fb1fff13612c72f2cbfaa8d5a17"
integrity sha1-zJmvlhLCP7H/8TYSxy8sv6qNWhc=
dependencies:
semver "^5.3.0"
[email protected]:
version "3.3.1"
resolved "https://registry.yarnpkg.com/diff/-/diff-3.3.1.tgz#aa8567a6eed03c531fc89d3f711cd0e5259dec75"
integrity sha512-MKPHZDMB0o6yHyDryUOScqZibp914ksXwAMYMTHj6KO8UeKsRYNJD3oNCKjTqZon+V488P7N/HzXF8t7ZR95ww==
[email protected]:
version "0.0.2"
resolved "https://registry.yarnpkg.com/duplexer2/-/duplexer2-0.0.2.tgz#c614dcf67e2fb14995a91711e5a617e8a60a31db"
integrity sha1-xhTc9n4vsUmVqRcR5aYX6KYKMds=
dependencies:
readable-stream "~1.1.9"
duplexer@~0.1.1:
version "0.1.1"
resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1"
integrity sha1-rOb/gIwc5mtX0ev5eXessCM0z8E=
duplexify@^3.2.0:
version "3.5.4"
resolved "https://registry.yarnpkg.com/duplexify/-/duplexify-3.5.4.tgz#4bb46c1796eabebeec4ca9a2e66b808cb7a3d8b4"
integrity sha512-JzYSLYMhoVVBe8+mbHQ4KgpvHpm0DZpJuL8PY93Vyv1fW7jYJ90LoXa1di/CVbJM+TgMs91rbDapE/RNIfnJsA==
dependencies:
end-of-stream "^1.0.0"
inherits "^2.0.1"
readable-stream "^2.0.0"
stream-shift "^1.0.0"
ecc-jsbn@~0.1.1:
version "0.1.1"
resolved "https://registry.yarnpkg.com/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz#0fc73a9ed5f0d53c38193398523ef7e543777505"
integrity sha1-D8c6ntXw1Tw4GTOYUj735UN3dQU=
dependencies:
jsbn "~0.1.0"
end-of-stream@^1.0.0:
version "1.4.1"
resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.1.tgz#ed29634d19baba463b6ce6b80a37213eab71ec43"
integrity sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==
dependencies:
once "^1.4.0"
[email protected], escape-string-regexp@^1.0.2:
version "1.0.5"
resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4"
integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=
event-stream@^3.3.1, event-stream@^3.3.4, event-stream@~3.3.4:
version "3.3.4"
resolved "http://registry.npmjs.org/event-stream/-/event-stream-3.3.4.tgz#4ab4c9a0f5a54db9338b4c34d86bfce8f4b35571"
integrity sha1-SrTJoPWlTbkzi0w02Gv86PSzVXE=
dependencies:
duplexer "~0.1.1"
from "~0"
map-stream "~0.1.0"
pause-stream "0.0.11"
split "0.3"
stream-combiner "~0.0.4"
through "~2.3.1"
expand-brackets@^0.1.4:
version "0.1.5"
resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-0.1.5.tgz#df07284e342a807cd733ac5af72411e581d1177b"
integrity sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=
dependencies:
is-posix-bracket "^0.1.0"
expand-range@^1.8.1:
version "1.8.2"
resolved "https://registry.yarnpkg.com/expand-range/-/expand-range-1.8.2.tgz#a299effd335fe2721ebae8e257ec79644fc85337"
integrity sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc=
dependencies:
fill-range "^2.1.0"
extend-shallow@^1.1.2:
version "1.1.4"
resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-1.1.4.tgz#19d6bf94dfc09d76ba711f39b872d21ff4dd9071"
integrity sha1-Gda/lN/AnXa6cR85uHLSH/TdkHE=
dependencies:
kind-of "^1.1.0"
extend-shallow@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-2.0.1.tgz#51af7d614ad9a9f610ea1bafbb989d6b1c56890f"
integrity sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=
dependencies:
is-extendable "^0.1.0"
extend@^3.0.0, extend@~3.0.1:
version "3.0.1"
resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.1.tgz#a755ea7bc1adfcc5a31ce7e762dbaadc5e636444"
integrity sha1-p1Xqe8Gt/MWjHOfnYtuq3F5jZEQ=
extglob@^0.3.1:
version "0.3.2"
resolved "https://registry.yarnpkg.com/extglob/-/extglob-0.3.2.tgz#2e18ff3d2f49ab2765cec9023f011daa8d8349a1"
integrity sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=
dependencies:
is-extglob "^1.0.0"
[email protected]:
version "1.3.0"
resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05"
integrity sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=
extsprintf@^1.2.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.4.0.tgz#e2689f8f356fad62cca65a3a91c5df5f9551692f"
integrity sha1-4mifjzVvrWLMplo6kcXfX5VRaS8=
fancy-log@^1.1.0:
version "1.3.2"
resolved "https://registry.yarnpkg.com/fancy-log/-/fancy-log-1.3.2.tgz#f41125e3d84f2e7d89a43d06d958c8f78be16be1"
integrity sha1-9BEl49hPLn2JpD0G2VjI94vha+E=
dependencies:
ansi-gray "^0.1.1"
color-support "^1.1.3"
time-stamp "^1.0.0"
fast-deep-equal@^1.0.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz#c053477817c86b51daa853c81e059b733d023614"
integrity sha1-wFNHeBfIa1HaqFPIHgWbcz0CNhQ=
fast-json-stable-stringify@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz#d5142c0caee6b1189f87d3a76111064f86c8bbf2"
integrity sha1-1RQsDK7msRifh9OnYREGT4bIu/I=
fd-slicer@~1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/fd-slicer/-/fd-slicer-1.0.1.tgz#8b5bcbd9ec327c5041bf9ab023fd6750f1177e65"
integrity sha1-i1vL2ewyfFBBv5qwI/1nUPEXfmU=
dependencies:
pend "~1.2.0"
filename-regex@^2.0.0:
version "2.0.1"
resolved "https://registry.yarnpkg.com/filename-regex/-/filename-regex-2.0.1.tgz#c1c4b9bee3e09725ddb106b75c1e301fe2f18b26"
integrity sha1-wcS5vuPglyXdsQa3XB4wH+LxiyY=
fill-range@^2.1.0:
version "2.2.3"
resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-2.2.3.tgz#50b77dfd7e469bc7492470963699fe7a8485a723"
integrity sha1-ULd9/X5Gm8dJJHCWNpn+eoSFpyM=
dependencies:
is-number "^2.1.0"
isobject "^2.0.0"
randomatic "^1.1.3"
repeat-element "^1.1.2"
repeat-string "^1.5.2"
first-chunk-stream@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/first-chunk-stream/-/first-chunk-stream-1.0.0.tgz#59bfb50cd905f60d7c394cd3d9acaab4e6ad934e"
integrity sha1-Wb+1DNkF9g18OUzT2ayqtOatk04=
for-in@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80"
integrity sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=
for-own@^0.1.4:
version "0.1.5"
resolved "https://registry.yarnpkg.com/for-own/-/for-own-0.1.5.tgz#5265c681a4f294dabbf17c9509b6763aa84510ce"
integrity sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4=
dependencies:
for-in "^1.0.1"
forever-agent@~0.6.1:
version "0.6.1"
resolved "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91"
integrity sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=
form-data@~2.3.1:
version "2.3.2"
resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.3.2.tgz#4970498be604c20c005d4f5c23aecd21d6b49099"
integrity sha1-SXBJi+YEwgwAXU9cI67NIda0kJk=
dependencies:
asynckit "^0.4.0"
combined-stream "1.0.6"
mime-types "^2.1.12"
from@~0:
version "0.1.7"
resolved "https://registry.yarnpkg.com/from/-/from-0.1.7.tgz#83c60afc58b9c56997007ed1a768b3ab303a44fe"
integrity sha1-g8YK/Fi5xWmXAH7Rp2izqzA6RP4=
fs.realpath@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"
integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8=
fstream@^1.0.2:
version "1.0.11"
resolved "https://registry.yarnpkg.com/fstream/-/fstream-1.0.11.tgz#5c1fb1f117477114f0632a0eb4b71b3cb0fd3171"
integrity sha1-XB+x8RdHcRTwYyoOtLcbPLD9MXE=
dependencies:
graceful-fs "^4.1.2"
inherits "~2.0.0"
mkdirp ">=0.5 0"
rimraf "2"
getpass@^0.1.1:
version "0.1.7"
resolved "https://registry.yarnpkg.com/getpass/-/getpass-0.1.7.tgz#5eff8e3e684d569ae4cb2b1282604e8ba62149fa"
integrity sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=
dependencies:
assert-plus "^1.0.0"
glob-base@^0.3.0:
version "0.3.0"
resolved "https://registry.yarnpkg.com/glob-base/-/glob-base-0.3.0.tgz#dbb164f6221b1c0b1ccf82aea328b497df0ea3c4"
integrity sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q=
dependencies:
glob-parent "^2.0.0"
is-glob "^2.0.0"
glob-parent@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-2.0.0.tgz#81383d72db054fcccf5336daa902f182f6edbb28"
integrity sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=
dependencies:
is-glob "^2.0.0"
glob-parent@^3.0.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-3.1.0.tgz#9e6af6299d8d3bd2bd40430832bd113df906c5ae"
integrity sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=
dependencies:
is-glob "^3.1.0"
path-dirname "^1.0.0"
glob-stream@^5.3.2:
version "5.3.5"
resolved "https://registry.yarnpkg.com/glob-stream/-/glob-stream-5.3.5.tgz#a55665a9a8ccdc41915a87c701e32d4e016fad22"
integrity sha1-pVZlqajM3EGRWofHAeMtTgFvrSI=
dependencies:
extend "^3.0.0"
glob "^5.0.3"
glob-parent "^3.0.0"
micromatch "^2.3.7"
ordered-read-streams "^0.3.0"
through2 "^0.6.0"
to-absolute-glob "^0.1.1"
unique-stream "^2.0.2"
[email protected], glob@^7.0.5, glob@^7.1.2:
version "7.1.2"
resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15"
integrity sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==
dependencies:
fs.realpath "^1.0.0"
inflight "^1.0.4"
inherits "2"
minimatch "^3.0.4"
once "^1.3.0"
path-is-absolute "^1.0.0"
glob@^5.0.3:
version "5.0.15"
resolved "https://registry.yarnpkg.com/glob/-/glob-5.0.15.tgz#1bc936b9e02f4a603fcc222ecf7633d30b8b93b1"
integrity sha1-G8k2ueAvSmA/zCIuz3Yz0wuLk7E=
dependencies:
inflight "^1.0.4"
inherits "2"
minimatch "2 || 3"
once "^1.3.0"
path-is-absolute "^1.0.0"
glogg@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/glogg/-/glogg-1.0.1.tgz#dcf758e44789cc3f3d32c1f3562a3676e6a34810"
integrity sha512-ynYqXLoluBKf9XGR1gA59yEJisIL7YHEH4xr3ZziHB5/yl4qWfaK8Js9jGe6gBGCSCKVqiyO30WnRZADvemUNw==
dependencies:
sparkles "^1.0.0"
graceful-fs@^4.0.0, graceful-fs@^4.1.2:
version "4.1.11"
resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.11.tgz#0e8bdfe4d1ddb8854d64e04ea7c00e2a026e5658"
integrity sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg=
[email protected]:
version "1.10.3"
resolved "https://registry.yarnpkg.com/growl/-/growl-1.10.3.tgz#1926ba90cf3edfe2adb4927f5880bc22c66c790f"
integrity sha512-hKlsbA5Vu3xsh1Cg3J7jSmX/WaW6A5oBeqzM88oNbCRQFz+zUaXm6yxS4RVytp1scBoJzSYl4YAEOQIt6O8V1Q==
gulp-chmod@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/gulp-chmod/-/gulp-chmod-2.0.0.tgz#00c390b928a0799b251accf631aa09e01cc6299c"
integrity sha1-AMOQuSigeZslGsz2MaoJ4BzGKZw=
dependencies:
deep-assign "^1.0.0"
stat-mode "^0.2.0"
through2 "^2.0.0"
gulp-filter@^5.0.1:
version "5.1.0"
resolved "https://registry.yarnpkg.com/gulp-filter/-/gulp-filter-5.1.0.tgz#a05e11affb07cf7dcf41a7de1cb7b63ac3783e73"
integrity sha1-oF4Rr/sHz33PQafeHLe2OsN4PnM=
dependencies:
multimatch "^2.0.0"
plugin-error "^0.1.2"
streamfilter "^1.0.5"
[email protected]:
version "1.0.0"
resolved "https://registry.yarnpkg.com/gulp-gunzip/-/gulp-gunzip-1.0.0.tgz#15b741145e83a9c6f50886241b57cc5871f151a9"
integrity sha1-FbdBFF6Dqcb1CIYkG1fMWHHxUak=
dependencies:
through2 "~0.6.5"
vinyl "~0.4.6"
gulp-remote-src-vscode@^0.5.0:
version "0.5.0"
resolved "https://registry.yarnpkg.com/gulp-remote-src-vscode/-/gulp-remote-src-vscode-0.5.0.tgz#71785553bc491880088ad971f90910c4b2d80a99"
integrity sha512-/9vtSk9eI9DEWCqzGieglPqmx0WUQ9pwPHyHFpKmfxqdgqGJC2l0vFMdYs54hLdDsMDEZFLDL2J4ikjc4hQ5HQ==
dependencies:
event-stream "^3.3.4"
node.extend "^1.1.2"
request "^2.79.0"
through2 "^2.0.3"
vinyl "^2.0.1"
[email protected]:
version "1.6.0"
resolved "https://registry.yarnpkg.com/gulp-sourcemaps/-/gulp-sourcemaps-1.6.0.tgz#b86ff349d801ceb56e1d9e7dc7bbcb4b7dee600c"
integrity sha1-uG/zSdgBzrVuHZ59x7vLS33uYAw=
dependencies:
convert-source-map "^1.1.1"
graceful-fs "^4.1.2"
strip-bom "^2.0.0"
through2 "^2.0.0"
vinyl "^1.0.0"
gulp-symdest@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/gulp-symdest/-/gulp-symdest-1.1.0.tgz#c165320732d192ce56fd94271ffa123234bf2ae0"
integrity sha1-wWUyBzLRks5W/ZQnH/oSMjS/KuA=
dependencies:
event-stream "^3.3.1"
mkdirp "^0.5.1"
queue "^3.1.0"
vinyl-fs "^2.4.3"
gulp-untar@^0.0.6:
version "0.0.6"
resolved "https://registry.yarnpkg.com/gulp-untar/-/gulp-untar-0.0.6.tgz#d6bdefde7e9a8e054c9f162385a0782c4be74000"
integrity sha1-1r3v3n6ajgVMnxYjhaB4LEvnQAA=
dependencies:
event-stream "~3.3.4"
gulp-util "~3.0.8"
streamifier "~0.1.1"
tar "^2.2.1"
through2 "~2.0.3"
gulp-util@~3.0.8:
version "3.0.8"
resolved "https://registry.yarnpkg.com/gulp-util/-/gulp-util-3.0.8.tgz#0054e1e744502e27c04c187c3ecc505dd54bbb4f"
integrity sha1-AFTh50RQLifATBh8PsxQXdVLu08=
dependencies:
array-differ "^1.0.0"
array-uniq "^1.0.2"
beeper "^1.0.0"
chalk "^1.0.0"
dateformat "^2.0.0"
fancy-log "^1.1.0"
gulplog "^1.0.0"
has-gulplog "^0.1.0"
lodash._reescape "^3.0.0"
lodash._reevaluate "^3.0.0"
lodash._reinterpolate "^3.0.0"
lodash.template "^3.0.0"
minimist "^1.1.0"
multipipe "^0.1.2"
object-assign "^3.0.0"
replace-ext "0.0.1"
through2 "^2.0.0"
vinyl "^0.5.0"
gulp-vinyl-zip@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/gulp-vinyl-zip/-/gulp-vinyl-zip-2.1.0.tgz#24e40685dc05b7149995245099e0590263be8dad"
integrity sha1-JOQGhdwFtxSZlSRQmeBZAmO+ja0=
dependencies:
event-stream "^3.3.1"
queue "^4.2.1"
through2 "^2.0.3"
vinyl "^2.0.2"
vinyl-fs "^2.0.0"
yauzl "^2.2.1"
yazl "^2.2.1"
gulplog@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/gulplog/-/gulplog-1.0.0.tgz#e28c4d45d05ecbbed818363ce8f9c5926229ffe5"
integrity sha1-4oxNRdBey77YGDY86PnFkmIp/+U=
dependencies:
glogg "^1.0.0"
har-schema@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/har-schema/-/har-schema-2.0.0.tgz#a94c2224ebcac04782a0d9035521f24735b7ec92"
integrity sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=
har-validator@~5.0.3:
version "5.0.3"
resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-5.0.3.tgz#ba402c266194f15956ef15e0fcf242993f6a7dfd"
integrity sha1-ukAsJmGU8VlW7xXg/PJCmT9qff0=
dependencies:
ajv "^5.1.0"
har-schema "^2.0.0"
has-ansi@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91"
integrity sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=
dependencies:
ansi-regex "^2.0.0"
has-flag@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-2.0.0.tgz#e8207af1cc7b30d446cc70b734b5e8be18f88d51"
integrity sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=
has-gulplog@^0.1.0:
version "0.1.0"
resolved "https://registry.yarnpkg.com/has-gulplog/-/has-gulplog-0.1.0.tgz#6414c82913697da51590397dafb12f22967811ce"
integrity sha1-ZBTIKRNpfaUVkDl9r7EvIpZ4Ec4=
dependencies:
sparkles "^1.0.0"
hawk@~6.0.2:
version "6.0.2"
resolved "https://registry.yarnpkg.com/hawk/-/hawk-6.0.2.tgz#af4d914eb065f9b5ce4d9d11c1cb2126eecc3038"
integrity sha512-miowhl2+U7Qle4vdLqDdPt9m09K6yZhkLDTWGoUiUzrQCn+mHHSmfJgAyGaLRZbPmTqfFFjRV1QWCW0VWUJBbQ==
dependencies:
boom "4.x.x"
cryptiles "3.x.x"
hoek "4.x.x"
sntp "2.x.x"
[email protected]:
version "1.1.1"
resolved "https://registry.yarnpkg.com/he/-/he-1.1.1.tgz#93410fd21b009735151f8868c2f271f3427e23fd"
integrity sha1-k0EP0hsAlzUVH4howvJx80J+I/0=
[email protected]:
version "4.2.1"
resolved "https://registry.yarnpkg.com/hoek/-/hoek-4.2.1.tgz#9634502aa12c445dd5a7c5734b572bb8738aacbb"
integrity sha512-QLg82fGkfnJ/4iy1xZ81/9SIJiq1NGFUMGs6ParyjBZr6jW2Ufj/snDqTHixNlHdPNwN2RLVD0Pi3igeK9+JfA==
http-signature@~1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.2.0.tgz#9aecd925114772f3d95b65a60abb8f7c18fbace1"
integrity sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=
dependencies:
assert-plus "^1.0.0"
jsprim "^1.2.2"
sshpk "^1.7.0"
inflight@^1.0.4:
version "1.0.6"
resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9"
integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=
dependencies:
once "^1.3.0"
wrappy "1"
inherits@2, inherits@^2.0.1, inherits@~2.0.0, inherits@~2.0.1, inherits@~2.0.3:
version "2.0.3"
resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de"
integrity sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=
is-buffer@^1.1.5:
version "1.1.6"
resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be"
integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==
is-dotfile@^1.0.0:
version "1.0.3"
resolved "https://registry.yarnpkg.com/is-dotfile/-/is-dotfile-1.0.3.tgz#a6a2f32ffd2dfb04f5ca25ecd0f6b83cf798a1e1"
integrity sha1-pqLzL/0t+wT1yiXs0Pa4PPeYoeE=
is-equal-shallow@^0.1.3:
version "0.1.3"
resolved "https://registry.yarnpkg.com/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz#2238098fc221de0bcfa5d9eac4c45d638aa1c534"
integrity sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ=
dependencies:
is-primitive "^2.0.0"
is-extendable@^0.1.0, is-extendable@^0.1.1:
version "0.1.1"
resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89"
integrity sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=
is-extglob@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-1.0.0.tgz#ac468177c4943405a092fc8f29760c6ffc6206c0"
integrity sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=
is-extglob@^2.1.0:
version "2.1.1"
resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2"
integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=
is-glob@^2.0.0, is-glob@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-2.0.1.tgz#d096f926a3ded5600f3fdfd91198cb0888c2d863"
integrity sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=
dependencies:
is-extglob "^1.0.0"
is-glob@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-3.1.0.tgz#7ba5ae24217804ac70707b96922567486cc3e84a"
integrity sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=
dependencies:
is-extglob "^2.1.0"
is-number@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/is-number/-/is-number-2.1.0.tgz#01fcbbb393463a548f2f466cce16dece49db908f"
integrity sha1-Afy7s5NGOlSPL0ZszhbezknbkI8=
dependencies:
kind-of "^3.0.2"
is-number@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195"
integrity sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=
dependencies:
kind-of "^3.0.2"
is-obj@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-1.0.1.tgz#3e4729ac1f5fde025cd7d83a896dab9f4f67db0f"
integrity sha1-PkcprB9f3gJc19g6iW2rn09n2w8=
is-posix-bracket@^0.1.0:
version "0.1.1"
resolved "https://registry.yarnpkg.com/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz#3334dc79774368e92f016e6fbc0a88f5cd6e6bc4"
integrity sha1-MzTceXdDaOkvAW5vvAqI9c1ua8Q=
is-primitive@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/is-primitive/-/is-primitive-2.0.0.tgz#207bab91638499c07b2adf240a41a87210034575"
integrity sha1-IHurkWOEmcB7Kt8kCkGochADRXU=
is-stream@^1.0.1:
version "1.1.0"
resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-1.1.0.tgz#12d4a3dd4e68e0b79ceb8dbc84173ae80d91ca44"
integrity sha1-EtSj3U5o4Lec6428hBc66A2RykQ=
is-typedarray@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a"
integrity sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=
is-utf8@^0.2.0:
version "0.2.1"
resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72"
integrity sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=
is-valid-glob@^0.3.0:
version "0.3.0"
resolved "https://registry.yarnpkg.com/is-valid-glob/-/is-valid-glob-0.3.0.tgz#d4b55c69f51886f9b65c70d6c2622d37e29f48fe"
integrity sha1-1LVcafUYhvm2XHDWwmItN+KfSP4=
is@^3.1.0:
version "3.2.1"
resolved "https://registry.yarnpkg.com/is/-/is-3.2.1.tgz#d0ac2ad55eb7b0bec926a5266f6c662aaa83dca5"
integrity sha1-0Kwq1V63sL7JJqUmb2xmKqqD3KU=
[email protected]:
version "0.0.1"
resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf"
integrity sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=
[email protected], isarray@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11"
integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=
isobject@^2.0.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89"
integrity sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=
dependencies:
isarray "1.0.0"
isstream@~0.1.2:
version "0.1.2"
resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a"
integrity sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=
jsbn@~0.1.0:
version "0.1.1"
resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513"
integrity sha1-peZUwuWi3rXyAdls77yoDA7y9RM=
json-schema-traverse@^0.3.0:
version "0.3.1"
resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz#349a6d44c53a51de89b40805c5d5e59b417d3340"
integrity sha1-NJptRMU6Ud6JtAgFxdXlm0F9M0A=
[email protected]:
version "0.2.3"
resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13"
integrity sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=
json-stable-stringify@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/json-stable-stringify/-/json-stable-stringify-1.0.1.tgz#9a759d39c5f2ff503fd5300646ed445f88c4f9af"
integrity sha1-mnWdOcXy/1A/1TAGRu1EX4jE+a8=
dependencies:
jsonify "~0.0.0"
json-stringify-safe@~5.0.1:
version "5.0.1"
resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb"
integrity sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=
jsonc-parser@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-2.0.1.tgz#9d23cd2709714fff508a1a6679d82135bee1ae60"
integrity sha512-9w/QyN9qF1dTlffzkmyITa6qAYt6sDArlVZqaP+CXnRh66V73wImQGG8GIBkuas0XLAxddWEWYQ8PPFoK5KNQA==
jsonify@~0.0.0:
version "0.0.0"
resolved "https://registry.yarnpkg.com/jsonify/-/jsonify-0.0.0.tgz#2c74b6ee41d93ca51b7b5aaee8f503631d252a73"
integrity sha1-LHS27kHZPKUbe1qu6PUDYx0lKnM=
jsprim@^1.2.2:
version "1.4.1"
resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2"
integrity sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=
dependencies:
assert-plus "1.0.0"
extsprintf "1.3.0"
json-schema "0.2.3"
verror "1.10.0"
kind-of@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-1.1.0.tgz#140a3d2d41a36d2efcfa9377b62c24f8495a5c44"
integrity sha1-FAo9LUGjbS78+pN3tiwk+ElaXEQ=
kind-of@^3.0.2:
version "3.2.2"
resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64"
integrity sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=
dependencies:
is-buffer "^1.1.5"
kind-of@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57"
integrity sha1-IIE989cSkosgc3hpGkUGb65y3Vc=
dependencies:
is-buffer "^1.1.5"
lazystream@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/lazystream/-/lazystream-1.0.0.tgz#f6995fe0f820392f61396be89462407bb77168e4"
integrity sha1-9plf4PggOS9hOWvolGJAe7dxaOQ=
dependencies:
readable-stream "^2.0.5"
lodash._basecopy@^3.0.0:
version "3.0.1"
resolved "https://registry.yarnpkg.com/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz#8da0e6a876cf344c0ad8a54882111dd3c5c7ca36"
integrity sha1-jaDmqHbPNEwK2KVIghEd08XHyjY=
lodash._basetostring@^3.0.0:
version "3.0.1"
resolved "https://registry.yarnpkg.com/lodash._basetostring/-/lodash._basetostring-3.0.1.tgz#d1861d877f824a52f669832dcaf3ee15566a07d5"
integrity sha1-0YYdh3+CSlL2aYMtyvPuFVZqB9U=
lodash._basevalues@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/lodash._basevalues/-/lodash._basevalues-3.0.0.tgz#5b775762802bde3d3297503e26300820fdf661b7"
integrity sha1-W3dXYoAr3j0yl1A+JjAIIP32Ybc=
lodash._getnative@^3.0.0:
version "3.9.1"
resolved "https://registry.yarnpkg.com/lodash._getnative/-/lodash._getnative-3.9.1.tgz#570bc7dede46d61cdcde687d65d3eecbaa3aaff5"
integrity sha1-VwvH3t5G1hzc3mh9ZdPuy6o6r/U=
lodash._isiterateecall@^3.0.0:
version "3.0.9"
resolved "https://registry.yarnpkg.com/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz#5203ad7ba425fae842460e696db9cf3e6aac057c"
integrity sha1-UgOte6Ql+uhCRg5pbbnPPmqsBXw=
lodash._reescape@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/lodash._reescape/-/lodash._reescape-3.0.0.tgz#2b1d6f5dfe07c8a355753e5f27fac7f1cde1616a"
integrity sha1-Kx1vXf4HyKNVdT5fJ/rH8c3hYWo=
lodash._reevaluate@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/lodash._reevaluate/-/lodash._reevaluate-3.0.0.tgz#58bc74c40664953ae0b124d806996daca431e2ed"
integrity sha1-WLx0xAZklTrgsSTYBpltrKQx4u0=
lodash._reinterpolate@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz#0ccf2d89166af03b3663c796538b75ac6e114d9d"
integrity sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=
lodash._root@^3.0.0:
version "3.0.1"
resolved "https://registry.yarnpkg.com/lodash._root/-/lodash._root-3.0.1.tgz#fba1c4524c19ee9a5f8136b4609f017cf4ded692"
integrity sha1-+6HEUkwZ7ppfgTa0YJ8BfPTe1pI=
lodash.escape@^3.0.0:
version "3.2.0"
resolved "https://registry.yarnpkg.com/lodash.escape/-/lodash.escape-3.2.0.tgz#995ee0dc18c1b48cc92effae71a10aab5b487698"
integrity sha1-mV7g3BjBtIzJLv+ucaEKq1tIdpg=
dependencies:
lodash._root "^3.0.0"
lodash.isarguments@^3.0.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz#2f573d85c6a24289ff00663b491c1d338ff3458a"
integrity sha1-L1c9hcaiQon/AGY7SRwdM4/zRYo=
lodash.isarray@^3.0.0:
version "3.0.4"
resolved "https://registry.yarnpkg.com/lodash.isarray/-/lodash.isarray-3.0.4.tgz#79e4eb88c36a8122af86f844aa9bcd851b5fbb55"
integrity sha1-eeTriMNqgSKvhvhEqpvNhRtfu1U=
lodash.isequal@^4.0.0:
version "4.5.0"
resolved "https://registry.yarnpkg.com/lodash.isequal/-/lodash.isequal-4.5.0.tgz#415c4478f2bcc30120c22ce10ed3226f7d3e18e0"
integrity sha1-QVxEePK8wwEgwizhDtMib30+GOA=
lodash.keys@^3.0.0:
version "3.1.2"
resolved "https://registry.yarnpkg.com/lodash.keys/-/lodash.keys-3.1.2.tgz#4dbc0472b156be50a0b286855d1bd0b0c656098a"
integrity sha1-TbwEcrFWvlCgsoaFXRvQsMZWCYo=
dependencies:
lodash._getnative "^3.0.0"
lodash.isarguments "^3.0.0"
lodash.isarray "^3.0.0"
lodash.restparam@^3.0.0:
version "3.6.1"
resolved "https://registry.yarnpkg.com/lodash.restparam/-/lodash.restparam-3.6.1.tgz#936a4e309ef330a7645ed4145986c85ae5b20805"
integrity sha1-k2pOMJ7zMKdkXtQUWYbIWuWyCAU=
lodash.template@^3.0.0:
version "3.6.2"
resolved "https://registry.yarnpkg.com/lodash.template/-/lodash.template-3.6.2.tgz#f8cdecc6169a255be9098ae8b0c53d378931d14f"
integrity sha1-+M3sxhaaJVvpCYrosMU9N4kx0U8=
dependencies:
lodash._basecopy "^3.0.0"
lodash._basetostring "^3.0.0"
lodash._basevalues "^3.0.0"
lodash._isiterateecall "^3.0.0"
lodash._reinterpolate "^3.0.0"
lodash.escape "^3.0.0"
lodash.keys "^3.0.0"
lodash.restparam "^3.0.0"
lodash.templatesettings "^3.0.0"
lodash.templatesettings@^3.0.0:
version "3.1.1"
resolved "https://registry.yarnpkg.com/lodash.templatesettings/-/lodash.templatesettings-3.1.1.tgz#fb307844753b66b9f1afa54e262c745307dba8e5"
integrity sha1-+zB4RHU7Zrnxr6VOJix0UwfbqOU=
dependencies:
lodash._reinterpolate "^3.0.0"
lodash.escape "^3.0.0"
map-stream@~0.1.0:
version "0.1.0"
resolved "https://registry.yarnpkg.com/map-stream/-/map-stream-0.1.0.tgz#e56aa94c4c8055a16404a0674b78f215f7c8e194"
integrity sha1-5WqpTEyAVaFkBKBnS3jyFffI4ZQ=
merge-stream@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-1.0.1.tgz#4041202d508a342ba00174008df0c251b8c135e1"
integrity sha1-QEEgLVCKNCugAXQAjfDCUbjBNeE=
dependencies:
readable-stream "^2.0.1"
micromatch@^2.3.7:
version "2.3.11"
resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-2.3.11.tgz#86677c97d1720b363431d04d0d15293bd38c1565"
integrity sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=
dependencies:
arr-diff "^2.0.0"
array-unique "^0.2.1"
braces "^1.8.2"
expand-brackets "^0.1.4"
extglob "^0.3.1"
filename-regex "^2.0.0"
is-extglob "^1.0.0"
is-glob "^2.0.1"
kind-of "^3.0.2"
normalize-path "^2.0.1"
object.omit "^2.0.0"
parse-glob "^3.0.4"
regex-cache "^0.4.2"
mime-db@~1.33.0:
version "1.33.0"
resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.33.0.tgz#a3492050a5cb9b63450541e39d9788d2272783db"
integrity sha512-BHJ/EKruNIqJf/QahvxwQZXKygOQ256myeN/Ew+THcAa5q+PjyTTMMeNQC4DZw5AwfvelsUrA6B67NKMqXDbzQ==
mime-types@^2.1.12, mime-types@~2.1.17:
version "2.1.18"
resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.18.tgz#6f323f60a83d11146f831ff11fd66e2fe5503bb8"
integrity sha512-lc/aahn+t4/SWV/qcmumYjymLsWfN3ELhpmVuUFjgsORruuZPVSwAQryq+HHGvO/SI2KVX26bx+En+zhM8g8hQ==
dependencies:
mime-db "~1.33.0"
"minimatch@2 || 3", minimatch@^3.0.0, minimatch@^3.0.4:
version "3.0.4"
resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083"
integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==
dependencies:
brace-expansion "^1.1.7"
[email protected]:
version "0.0.8"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d"
integrity sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=
minimist@^1.1.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284"
integrity sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=
[email protected], "mkdirp@>=0.5 0", mkdirp@^0.5.0, mkdirp@^0.5.1:
version "0.5.1"
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903"
integrity sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=
dependencies:
minimist "0.0.8"
mocha@^4.0.1:
version "4.1.0"
resolved "https://registry.yarnpkg.com/mocha/-/mocha-4.1.0.tgz#7d86cfbcf35cb829e2754c32e17355ec05338794"
integrity sha512-0RVnjg1HJsXY2YFDoTNzcc1NKhYuXKRrBAG2gDygmJJA136Cs2QlRliZG1mA0ap7cuaT30mw16luAeln+4RiNA==
dependencies:
browser-stdout "1.3.0"
commander "2.11.0"
debug "3.1.0"
diff "3.3.1"
escape-string-regexp "1.0.5"
glob "7.1.2"
growl "1.10.3"
he "1.1.1"
mkdirp "0.5.1"
supports-color "4.4.0"
[email protected]:
version "2.0.0"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=
multimatch@^2.0.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/multimatch/-/multimatch-2.1.0.tgz#9c7906a22fb4c02919e2f5f75161b4cdbd4b2a2b"
integrity sha1-nHkGoi+0wCkZ4vX3UWG0zb1LKis=
dependencies:
array-differ "^1.0.0"
array-union "^1.0.1"
arrify "^1.0.0"
minimatch "^3.0.0"
multipipe@^0.1.2:
version "0.1.2"
resolved "https://registry.yarnpkg.com/multipipe/-/multipipe-0.1.2.tgz#2a8f2ddf70eed564dff2d57f1e1a137d9f05078b"
integrity sha1-Ko8t33Du1WTf8tV/HhoTfZ8FB4s=
dependencies:
duplexer2 "0.0.2"
node.extend@^1.1.2:
version "1.1.6"
resolved "https://registry.yarnpkg.com/node.extend/-/node.extend-1.1.6.tgz#a7b882c82d6c93a4863a5504bd5de8ec86258b96"
integrity sha1-p7iCyC1sk6SGOlUEvV3o7IYli5Y=
dependencies:
is "^3.1.0"
normalize-path@^2.0.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz#1ab28b556e198363a8c1a6f7e6fa20137fe6aed9"
integrity sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=
dependencies:
remove-trailing-separator "^1.0.1"
oauth-sign@~0.8.2:
version "0.8.2"
resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.8.2.tgz#46a6ab7f0aead8deae9ec0565780b7d4efeb9d43"
integrity sha1-Rqarfwrq2N6unsBWV4C31O/rnUM=
object-assign@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-3.0.0.tgz#9bedd5ca0897949bca47e7ff408062d549f587f2"
integrity sha1-m+3VygiXlJvKR+f/QIBi1Un1h/I=
object-assign@^4.0.0:
version "4.1.1"
resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863"
integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=
object.omit@^2.0.0:
version "2.0.1"
resolved "https://registry.yarnpkg.com/object.omit/-/object.omit-2.0.1.tgz#1a9c744829f39dbb858c76ca3579ae2a54ebd1fa"
integrity sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo=
dependencies:
for-own "^0.1.4"
is-extendable "^0.1.1"
once@^1.3.0, once@^1.4.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1"
integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E=
dependencies:
wrappy "1"
ordered-read-streams@^0.3.0:
version "0.3.0"
resolved "https://registry.yarnpkg.com/ordered-read-streams/-/ordered-read-streams-0.3.0.tgz#7137e69b3298bb342247a1bbee3881c80e2fd78b"
integrity sha1-cTfmmzKYuzQiR6G77jiByA4v14s=
dependencies:
is-stream "^1.0.1"
readable-stream "^2.0.1"
parse-glob@^3.0.4:
version "3.0.4"
resolved "https://registry.yarnpkg.com/parse-glob/-/parse-glob-3.0.4.tgz#b2c376cfb11f35513badd173ef0bb6e3a388391c"
integrity sha1-ssN2z7EfNVE7rdFz7wu246OIORw=
dependencies:
glob-base "^0.3.0"
is-dotfile "^1.0.0"
is-extglob "^1.0.0"
is-glob "^2.0.0"
path-dirname@^1.0.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/path-dirname/-/path-dirname-1.0.2.tgz#cc33d24d525e099a5388c0336c6e32b9160609e0"
integrity sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=
path-is-absolute@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f"
integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18=
[email protected]:
version "0.0.11"
resolved "https://registry.yarnpkg.com/pause-stream/-/pause-stream-0.0.11.tgz#fe5a34b0cbce12b5aa6a2b403ee2e73b602f1445"
integrity sha1-/lo0sMvOErWqaitAPuLnO2AvFEU=
dependencies:
through "~2.3"
pend@~1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/pend/-/pend-1.2.0.tgz#7a57eb550a6783f9115331fcf4663d5c8e007a50"
integrity sha1-elfrVQpng/kRUzH89GY9XI4AelA=
performance-now@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b"
integrity sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=
plugin-error@^0.1.2:
version "0.1.2"
resolved "https://registry.yarnpkg.com/plugin-error/-/plugin-error-0.1.2.tgz#3b9bb3335ccf00f425e07437e19276967da47ace"
integrity sha1-O5uzM1zPAPQl4HQ34ZJ2ln2kes4=
dependencies:
ansi-cyan "^0.1.1"
ansi-red "^0.1.1"
arr-diff "^1.0.1"
arr-union "^2.0.1"
extend-shallow "^1.1.2"
preserve@^0.2.0:
version "0.2.0"
resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b"
integrity sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=
process-nextick-args@^2.0.0, process-nextick-args@~2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.0.tgz#a37d732f4271b4ab1ad070d35508e8290788ffaa"
integrity sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==
punycode@^1.4.1:
version "1.4.1"
resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e"
integrity sha1-wNWmOycYgArY4esPpSachN1BhF4=
qs@~6.5.1:
version "6.5.1"
resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.1.tgz#349cdf6eef89ec45c12d7d5eb3fc0c870343a6d8"
integrity sha512-eRzhrN1WSINYCDCbrz796z37LOe3m5tmW7RQf6oBntukAG1nmovJvhnwHHRMAfeoItc1m2Hk02WER2aQ/iqs+A==
querystringify@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/querystringify/-/querystringify-2.0.0.tgz#fa3ed6e68eb15159457c89b37bc6472833195755"
integrity sha512-eTPo5t/4bgaMNZxyjWx6N2a6AuE0mq51KWvpc7nU/MAqixcI6v6KrGUKES0HaomdnolQBBXU/++X6/QQ9KL4tw==
queue@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/queue/-/queue-3.1.0.tgz#6c49d01f009e2256788789f2bffac6b8b9990585"
integrity sha1-bEnQHwCeIlZ4h4nyv/rGuLmZBYU=
dependencies:
inherits "~2.0.0"
queue@^4.2.1:
version "4.4.2"
resolved "https://registry.yarnpkg.com/queue/-/queue-4.4.2.tgz#5a9733d9a8b8bd1b36e934bc9c55ab89b28e29c7"
integrity sha512-fSMRXbwhMwipcDZ08enW2vl+YDmAmhcNcr43sCJL8DIg+CFOsoRLG23ctxA+fwNk1w55SePSiS7oqQQSgQoVJQ==
dependencies:
inherits "~2.0.0"
randomatic@^1.1.3:
version "1.1.7"
resolved "https://registry.yarnpkg.com/randomatic/-/randomatic-1.1.7.tgz#c7abe9cc8b87c0baa876b19fde83fd464797e38c"
integrity sha512-D5JUjPyJbaJDkuAazpVnSfVkLlpeO3wDlPROTMLGKG1zMFNFRgrciKo1ltz/AzNTkqE0HzDx655QOL51N06how==
dependencies:
is-number "^3.0.0"
kind-of "^4.0.0"
"readable-stream@>=1.0.33-1 <1.1.0-0":
version "1.0.34"
resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.0.34.tgz#125820e34bc842d2f2aaafafe4c2916ee32c157c"
integrity sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=
dependencies:
core-util-is "~1.0.0"
inherits "~2.0.1"
isarray "0.0.1"
string_decoder "~0.10.x"
readable-stream@^2.0.0, readable-stream@^2.0.1, readable-stream@^2.0.2, readable-stream@^2.0.4, readable-stream@^2.0.5, readable-stream@^2.1.5, readable-stream@^2.3.5:
version "2.3.6"
resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf"
integrity sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==
dependencies:
core-util-is "~1.0.0"
inherits "~2.0.3"
isarray "~1.0.0"
process-nextick-args "~2.0.0"
safe-buffer "~5.1.1"
string_decoder "~1.1.1"
util-deprecate "~1.0.1"
readable-stream@~1.1.9:
version "1.1.14"
resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.1.14.tgz#7cf4c54ef648e3813084c636dd2079e166c081d9"
integrity sha1-fPTFTvZI44EwhMY23SB54WbAgdk=
dependencies:
core-util-is "~1.0.0"
inherits "~2.0.1"
isarray "0.0.1"
string_decoder "~0.10.x"
regex-cache@^0.4.2:
version "0.4.4"
resolved "https://registry.yarnpkg.com/regex-cache/-/regex-cache-0.4.4.tgz#75bdc58a2a1496cec48a12835bc54c8d562336dd"
integrity sha512-nVIZwtCjkC9YgvWkpM55B5rBhBYRZhAaJbgcFYXXsHnbZ9UZI9nnVWYZpBlCqv9ho2eZryPnWrZGsOdPwVWXWQ==
dependencies:
is-equal-shallow "^0.1.3"
remove-trailing-separator@^1.0.1:
version "1.1.0"
resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz#c24bce2a283adad5bc3f58e0d48249b92379d8ef"
integrity sha1-wkvOKig62tW8P1jg1IJJuSN52O8=
repeat-element@^1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.2.tgz#ef089a178d1483baae4d93eb98b4f9e4e11d990a"
integrity sha1-7wiaF40Ug7quTZPrmLT55OEdmQo=
repeat-string@^1.5.2:
version "1.6.1"
resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637"
integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc=
[email protected]:
version "0.0.1"
resolved "https://registry.yarnpkg.com/replace-ext/-/replace-ext-0.0.1.tgz#29bbd92078a739f0bcce2b4ee41e837953522924"
integrity sha1-KbvZIHinOfC8zitO5B6DeVNSKSQ=
replace-ext@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/replace-ext/-/replace-ext-1.0.0.tgz#de63128373fcbf7c3ccfa4de5a480c45a67958eb"
integrity sha1-3mMSg3P8v3w8z6TeWkgMRaZ5WOs=
request@^2.79.0, request@^2.83.0:
version "2.85.0"
resolved "https://registry.yarnpkg.com/request/-/request-2.85.0.tgz#5a03615a47c61420b3eb99b7dba204f83603e1fa"
integrity sha512-8H7Ehijd4js+s6wuVPLjwORxD4zeuyjYugprdOXlPSqaApmL/QOy+EB/beICHVCHkGMKNh5rvihb5ov+IDw4mg==
dependencies:
aws-sign2 "~0.7.0"
aws4 "^1.6.0"
caseless "~0.12.0"
combined-stream "~1.0.5"
extend "~3.0.1"
forever-agent "~0.6.1"
form-data "~2.3.1"
har-validator "~5.0.3"
hawk "~6.0.2"
http-signature "~1.2.0"
is-typedarray "~1.0.0"
isstream "~0.1.2"
json-stringify-safe "~5.0.1"
mime-types "~2.1.17"
oauth-sign "~0.8.2"
performance-now "^2.1.0"
qs "~6.5.1"
safe-buffer "^5.1.1"
stringstream "~0.0.5"
tough-cookie "~2.3.3"
tunnel-agent "^0.6.0"
uuid "^3.1.0"
requires-port@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/requires-port/-/requires-port-1.0.0.tgz#925d2601d39ac485e091cf0da5c6e694dc3dcaff"
integrity sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=
rimraf@2:
version "2.6.2"
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.2.tgz#2ed8150d24a16ea8651e6d6ef0f47c4158ce7a36"
integrity sha512-lreewLK/BlghmxtfH36YYVg1i8IAce4TI7oao75I1g245+6BctqTVQiBP3YUJ9C6DQOXJmkYR9X9fCLtCOJc5w==
dependencies:
glob "^7.0.5"
safe-buffer@^5.0.1, safe-buffer@^5.1.1, safe-buffer@~5.1.0, safe-buffer@~5.1.1:
version "5.1.2"
resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d"
integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==
[email protected]:
version "5.5.1"
resolved "https://registry.yarnpkg.com/semver/-/semver-5.5.1.tgz#7dfdd8814bdb7cabc7be0fb1d734cfb66c940477"
integrity sha512-PqpAxfrEhlSUWge8dwIp4tZnQ25DIOthpiaHNIthsjEFQD6EvqUKUDM7L8O2rShkFccYo1VjJR0coWfNkCubRw==
semver@^5.3.0, semver@^5.4.1:
version "5.5.0"
resolved "https://registry.yarnpkg.com/semver/-/semver-5.5.0.tgz#dc4bbc7a6ca9d916dee5d43516f0092b58f7b8ab"
integrity sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==
[email protected]:
version "2.1.0"
resolved "https://registry.yarnpkg.com/sntp/-/sntp-2.1.0.tgz#2c6cec14fedc2222739caf9b5c3d85d1cc5a2cc8"
integrity sha512-FL1b58BDrqS3A11lJ0zEdnJ3UOKqVxawAkF3k7F0CVN7VQ34aZrV+G8BZ1WC9ZL7NyrwsW0oviwsWDgRuVYtJg==
dependencies:
hoek "4.x.x"
source-map-support@^0.5.0:
version "0.5.5"
resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.5.tgz#0d4af9e00493e855402e8ec36ebed2d266fceb90"
integrity sha512-mR7/Nd5l1z6g99010shcXJiNEaf3fEtmLhRB/sBcQVJGodcHCULPp2y4Sfa43Kv2zq7T+Izmfp/WHCR6dYkQCA==
dependencies:
buffer-from "^1.0.0"
source-map "^0.6.0"
source-map@^0.6.0:
version "0.6.1"
resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263"
integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==
sparkles@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/sparkles/-/sparkles-1.0.0.tgz#1acbbfb592436d10bbe8f785b7cc6f82815012c3"
integrity sha1-Gsu/tZJDbRC76PeFt8xvgoFQEsM=
[email protected]:
version "0.3.3"
resolved "https://registry.yarnpkg.com/split/-/split-0.3.3.tgz#cd0eea5e63a211dfff7eb0f091c4133e2d0dd28f"
integrity sha1-zQ7qXmOiEd//frDwkcQTPi0N0o8=
dependencies:
through "2"
sshpk@^1.7.0:
version "1.14.1"
resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.14.1.tgz#130f5975eddad963f1d56f92b9ac6c51fa9f83eb"
integrity sha1-Ew9Zde3a2WPx1W+SuaxsUfqfg+s=
dependencies:
asn1 "~0.2.3"
assert-plus "^1.0.0"
dashdash "^1.12.0"
getpass "^0.1.1"
optionalDependencies:
bcrypt-pbkdf "^1.0.0"
ecc-jsbn "~0.1.1"
jsbn "~0.1.0"
tweetnacl "~0.14.0"
stat-mode@^0.2.0:
version "0.2.2"
resolved "https://registry.yarnpkg.com/stat-mode/-/stat-mode-0.2.2.tgz#e6c80b623123d7d80cf132ce538f346289072502"
integrity sha1-5sgLYjEj19gM8TLOU480YokHJQI=
stream-combiner@~0.0.4:
version "0.0.4"
resolved "https://registry.yarnpkg.com/stream-combiner/-/stream-combiner-0.0.4.tgz#4d5e433c185261dde623ca3f44c586bcf5c4ad14"
integrity sha1-TV5DPBhSYd3mI8o/RMWGvPXErRQ=
dependencies:
duplexer "~0.1.1"
stream-shift@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/stream-shift/-/stream-shift-1.0.0.tgz#d5c752825e5367e786f78e18e445ea223a155952"
integrity sha1-1cdSgl5TZ+eG944Y5EXqIjoVWVI=
streamfilter@^1.0.5:
version "1.0.7"
resolved "https://registry.yarnpkg.com/streamfilter/-/streamfilter-1.0.7.tgz#ae3e64522aa5a35c061fd17f67620c7653c643c9"
integrity sha512-Gk6KZM+yNA1JpW0KzlZIhjo3EaBJDkYfXtYSbOwNIQ7Zd6006E6+sCFlW1NDvFG/vnXhKmw6TJJgiEQg/8lXfQ==
dependencies:
readable-stream "^2.0.2"
streamifier@~0.1.1:
version "0.1.1"
resolved "https://registry.yarnpkg.com/streamifier/-/streamifier-0.1.1.tgz#97e98d8fa4d105d62a2691d1dc07e820db8dfc4f"
integrity sha1-l+mNj6TRBdYqJpHR3AfoINuN/E8=
string_decoder@~0.10.x:
version "0.10.31"
resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-0.10.31.tgz#62e203bc41766c6c28c9fc84301dab1c5310fa94"
integrity sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=
string_decoder@~1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8"
integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==
dependencies:
safe-buffer "~5.1.0"
stringstream@~0.0.5:
version "0.0.5"
resolved "https://registry.yarnpkg.com/stringstream/-/stringstream-0.0.5.tgz#4e484cd4de5a0bbbee18e46307710a8a81621878"
integrity sha1-TkhM1N5aC7vuGORjB3EKioFiGHg=
strip-ansi@^3.0.0:
version "3.0.1"
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf"
integrity sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=
dependencies:
ansi-regex "^2.0.0"
strip-bom-stream@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/strip-bom-stream/-/strip-bom-stream-1.0.0.tgz#e7144398577d51a6bed0fa1994fa05f43fd988ee"
integrity sha1-5xRDmFd9Uaa+0PoZlPoF9D/ZiO4=
dependencies:
first-chunk-stream "^1.0.0"
strip-bom "^2.0.0"
strip-bom@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz#6219a85616520491f35788bdbf1447a99c7e6b0e"
integrity sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=
dependencies:
is-utf8 "^0.2.0"
[email protected]:
version "4.4.0"
resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-4.4.0.tgz#883f7ddabc165142b2a61427f3352ded195d1a3e"
integrity sha512-rKC3+DyXWgK0ZLKwmRsrkyHVZAjNkfzeehuFWdGGcqGDTZFH73+RH6S/RDAAxl9GusSjZSUWYLmT9N5pzXFOXQ==
dependencies:
has-flag "^2.0.0"
supports-color@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7"
integrity sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=
tar@^2.2.1:
version "2.2.1"
resolved "https://registry.yarnpkg.com/tar/-/tar-2.2.1.tgz#8e4d2a256c0e2185c6b18ad694aec968b83cb1d1"
integrity sha1-jk0qJWwOIYXGsYrWlK7JaLg8sdE=
dependencies:
block-stream "*"
fstream "^1.0.2"
inherits "2"
through2-filter@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/through2-filter/-/through2-filter-2.0.0.tgz#60bc55a0dacb76085db1f9dae99ab43f83d622ec"
integrity sha1-YLxVoNrLdghdsfna6Zq0P4PWIuw=
dependencies:
through2 "~2.0.0"
xtend "~4.0.0"
through2@^0.6.0, through2@~0.6.5:
version "0.6.5"
resolved "https://registry.yarnpkg.com/through2/-/through2-0.6.5.tgz#41ab9c67b29d57209071410e1d7a7a968cd3ad48"
integrity sha1-QaucZ7KdVyCQcUEOHXp6lozTrUg=
dependencies:
readable-stream ">=1.0.33-1 <1.1.0-0"
xtend ">=4.0.0 <4.1.0-0"
through2@^2.0.0, through2@^2.0.3, through2@~2.0.0, through2@~2.0.3:
version "2.0.3"
resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.3.tgz#0004569b37c7c74ba39c43f3ced78d1ad94140be"
integrity sha1-AARWmzfHx0ujnEPzzteNGtlBQL4=
dependencies:
readable-stream "^2.1.5"
xtend "~4.0.1"
through@2, through@~2.3, through@~2.3.1:
version "2.3.8"
resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5"
integrity sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=
time-stamp@^1.0.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/time-stamp/-/time-stamp-1.1.0.tgz#764a5a11af50561921b133f3b44e618687e0f5c3"
integrity sha1-dkpaEa9QVhkhsTPztE5hhofg9cM=
to-absolute-glob@^0.1.1:
version "0.1.1"
resolved "https://registry.yarnpkg.com/to-absolute-glob/-/to-absolute-glob-0.1.1.tgz#1cdfa472a9ef50c239ee66999b662ca0eb39937f"
integrity sha1-HN+kcqnvUMI57maZm2YsoOs5k38=
dependencies:
extend-shallow "^2.0.1"
tough-cookie@~2.3.3:
version "2.3.4"
resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.3.4.tgz#ec60cee38ac675063ffc97a5c18970578ee83655"
integrity sha512-TZ6TTfI5NtZnuyy/Kecv+CnoROnyXn2DN97LontgQpCwsX2XyLYCC0ENhYkehSOwAp8rTQKc/NUIF7BkQ5rKLA==
dependencies:
punycode "^1.4.1"
tunnel-agent@^0.6.0:
version "0.6.0"
resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd"
integrity sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=
dependencies:
safe-buffer "^5.0.1"
tweetnacl@^0.14.3, tweetnacl@~0.14.0:
version "0.14.5"
resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64"
integrity sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=
unique-stream@^2.0.2:
version "2.2.1"
resolved "https://registry.yarnpkg.com/unique-stream/-/unique-stream-2.2.1.tgz#5aa003cfbe94c5ff866c4e7d668bb1c4dbadb369"
integrity sha1-WqADz76Uxf+GbE59ZouxxNuts2k=
dependencies:
json-stable-stringify "^1.0.0"
through2-filter "^2.0.0"
url-parse@^1.1.9:
version "1.4.0"
resolved "https://registry.yarnpkg.com/url-parse/-/url-parse-1.4.0.tgz#6bfdaad60098c7fe06f623e42b22de62de0d3d75"
integrity sha512-ERuGxDiQ6Xw/agN4tuoCRbmwRuZP0cJ1lJxJubXr5Q/5cDa78+Dc4wfvtxzhzhkm5VvmW6Mf8EVj9SPGN4l8Lg==
dependencies:
querystringify "^2.0.0"
requires-port "^1.0.0"
util-deprecate@~1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"
integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=
uuid@^3.1.0:
version "3.2.1"
resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.2.1.tgz#12c528bb9d58d0b9265d9a2f6f0fe8be17ff1f14"
integrity sha512-jZnMwlb9Iku/O3smGWvZhauCf6cvvpKi4BKRiliS3cxnI+Gz9j5MEpTz2UFuXiKPJocb7gnsLHwiS05ige5BEA==
vali-date@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/vali-date/-/vali-date-1.0.0.tgz#1b904a59609fb328ef078138420934f6b86709a6"
integrity sha1-G5BKWWCfsyjvB4E4Qgk09rhnCaY=
[email protected]:
version "1.10.0"
resolved "https://registry.yarnpkg.com/verror/-/verror-1.10.0.tgz#3a105ca17053af55d6e270c1f8288682e18da400"
integrity sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=
dependencies:
assert-plus "^1.0.0"
core-util-is "1.0.2"
extsprintf "^1.2.0"
vinyl-fs@^2.0.0, vinyl-fs@^2.4.3:
version "2.4.4"
resolved "https://registry.yarnpkg.com/vinyl-fs/-/vinyl-fs-2.4.4.tgz#be6ff3270cb55dfd7d3063640de81f25d7532239"
integrity sha1-vm/zJwy1Xf19MGNkDegfJddTIjk=
dependencies:
duplexify "^3.2.0"
glob-stream "^5.3.2"
graceful-fs "^4.0.0"
gulp-sourcemaps "1.6.0"
is-valid-glob "^0.3.0"
lazystream "^1.0.0"
lodash.isequal "^4.0.0"
merge-stream "^1.0.0"
mkdirp "^0.5.0"
object-assign "^4.0.0"
readable-stream "^2.0.4"
strip-bom "^2.0.0"
strip-bom-stream "^1.0.0"
through2 "^2.0.0"
through2-filter "^2.0.0"
vali-date "^1.0.0"
vinyl "^1.0.0"
vinyl-source-stream@^1.1.0:
version "1.1.2"
resolved "https://registry.yarnpkg.com/vinyl-source-stream/-/vinyl-source-stream-1.1.2.tgz#62b53a135610a896e98ca96bee3a87f008a8e780"
integrity sha1-YrU6E1YQqJbpjKlr7jqH8Aio54A=
dependencies:
through2 "^2.0.3"
vinyl "^0.4.3"
vinyl@^0.4.3, vinyl@~0.4.6:
version "0.4.6"
resolved "https://registry.yarnpkg.com/vinyl/-/vinyl-0.4.6.tgz#2f356c87a550a255461f36bbeb2a5ba8bf784847"
integrity sha1-LzVsh6VQolVGHza76ypbqL94SEc=
dependencies:
clone "^0.2.0"
clone-stats "^0.0.1"
vinyl@^0.5.0:
version "0.5.3"
resolved "https://registry.yarnpkg.com/vinyl/-/vinyl-0.5.3.tgz#b0455b38fc5e0cf30d4325132e461970c2091cde"
integrity sha1-sEVbOPxeDPMNQyUTLkYZcMIJHN4=
dependencies:
clone "^1.0.0"
clone-stats "^0.0.1"
replace-ext "0.0.1"
vinyl@^1.0.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/vinyl/-/vinyl-1.2.0.tgz#5c88036cf565e5df05558bfc911f8656df218884"
integrity sha1-XIgDbPVl5d8FVYv8kR+GVt8hiIQ=
dependencies:
clone "^1.0.0"
clone-stats "^0.0.1"
replace-ext "0.0.1"
vinyl@^2.0.1, vinyl@^2.0.2:
version "2.1.0"
resolved "https://registry.yarnpkg.com/vinyl/-/vinyl-2.1.0.tgz#021f9c2cf951d6b939943c89eb5ee5add4fd924c"
integrity sha1-Ah+cLPlR1rk5lDyJ617lrdT9kkw=
dependencies:
clone "^2.1.1"
clone-buffer "^1.0.0"
clone-stats "^1.0.0"
cloneable-readable "^1.0.0"
remove-trailing-separator "^1.0.1"
replace-ext "^1.0.0"
[email protected]:
version "0.0.22"
resolved "https://registry.yarnpkg.com/vscode-extension-telemetry/-/vscode-extension-telemetry-0.0.22.tgz#ec7d6d85afb5b198aab09e80cba9e16b6d588e56"
integrity sha512-6/xT3UG6nPcNbBT29RPRJ6uRplI0l1m5ZBX9VXV3XGWrINDvWw2Nk/84xMeWDF1zI1YoPCcjeD0u4gH2OIsrcA==
dependencies:
applicationinsights "1.0.5"
vscode-nls@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/vscode-nls/-/vscode-nls-4.0.0.tgz#4001c8a6caba5cedb23a9c5ce1090395c0e44002"
integrity sha512-qCfdzcH+0LgQnBpZA53bA32kzp9rpq/f66Som577ObeuDlFIrtbEJ+A/+CCxjIh4G8dpJYNCKIsxpRAHIfsbNw==
vscode@^1.1.10:
version "1.1.17"
resolved "https://registry.yarnpkg.com/vscode/-/vscode-1.1.17.tgz#cc2a61731e925301f03f003c009cbf454022cd83"
integrity sha512-yNMyrgEua2qyW7+trNNYhA6PeldRrBcwtLtlazkdtzcmkHMKECM/08bPF8HF2ZFuwHgD+8FQsdqd/DvJYQYjJg==
dependencies:
glob "^7.1.2"
gulp-chmod "^2.0.0"
gulp-filter "^5.0.1"
gulp-gunzip "1.0.0"
gulp-remote-src-vscode "^0.5.0"
gulp-symdest "^1.1.0"
gulp-untar "^0.0.6"
gulp-vinyl-zip "^2.1.0"
mocha "^4.0.1"
request "^2.83.0"
semver "^5.4.1"
source-map-support "^0.5.0"
url-parse "^1.1.9"
vinyl-source-stream "^1.1.0"
wrappy@1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"
integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=
"xtend@>=4.0.0 <4.1.0-0", xtend@~4.0.0, xtend@~4.0.1:
version "4.0.1"
resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.1.tgz#a5c6d532be656e23db820efb943a1f04998d63af"
integrity sha1-pcbVMr5lbiPbgg77lDofBJmNY68=
yauzl@^2.2.1:
version "2.9.1"
resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.9.1.tgz#a81981ea70a57946133883f029c5821a89359a7f"
integrity sha1-qBmB6nCleUYTOIPwKcWCGok1mn8=
dependencies:
buffer-crc32 "~0.2.3"
fd-slicer "~1.0.1"
yazl@^2.2.1:
version "2.4.3"
resolved "https://registry.yarnpkg.com/yazl/-/yazl-2.4.3.tgz#ec26e5cc87d5601b9df8432dbdd3cd2e5173a071"
integrity sha1-7CblzIfVYBud+EMtvdPNLlFzoHE=
dependencies:
buffer-crc32 "~0.2.3"
[email protected]:
version "0.7.6"
resolved "https://registry.yarnpkg.com/zone.js/-/zone.js-0.7.6.tgz#fbbc39d3e0261d0986f1ba06306eb3aeb0d22009"
integrity sha1-+7w50+AmHQmG8boGMG6zrrDSIAk=
| extensions/typescript-language-features/yarn.lock | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.00021338116494007409,
0.0001671859936323017,
0.0001607848098501563,
0.00016642830451019108,
0.0000054594993343926035
] |
{
"id": 3,
"code_window": [
" };\n",
" var packageJsonFilter = filter('package.json', { restore: true });\n",
" return remote('', options)\n",
" .on('error', function (err) {\n",
" console.log('Error downloading extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
" console.error(err);\n",
" })\n",
" .on('end', function () {\n",
" console.log('Downloaded extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
" })\n",
" .pipe(vzip.src())\n",
" .pipe(filter('extension/**'))\n",
" .pipe(rename(function (p) { return p.dirname = p.dirname.replace(/^extension\\/?/, ''); }))\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "build/lib/extensions.js",
"type": "replace",
"edit_start_line_idx": 170
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { illegalArgument, onUnexpectedExternalError } from 'vs/base/common/errors';
import { mergeSort } from 'vs/base/common/arrays';
import { URI } from 'vs/base/common/uri';
import { ITextModel } from 'vs/editor/common/model';
import { registerLanguageCommand } from 'vs/editor/browser/editorExtensions';
import { CodeLensProviderRegistry, CodeLensProvider, ICodeLensSymbol } from 'vs/editor/common/modes';
import { IModelService } from 'vs/editor/common/services/modelService';
import { CancellationToken } from 'vs/base/common/cancellation';
export interface ICodeLensData {
symbol: ICodeLensSymbol;
provider: CodeLensProvider;
}
export function getCodeLensData(model: ITextModel, token: CancellationToken): Promise<ICodeLensData[]> {
const symbols: ICodeLensData[] = [];
const provider = CodeLensProviderRegistry.ordered(model);
const promises = provider.map(provider => Promise.resolve(provider.provideCodeLenses(model, token)).then(result => {
if (Array.isArray(result)) {
for (let symbol of result) {
symbols.push({ symbol, provider });
}
}
}).catch(onUnexpectedExternalError));
return Promise.all(promises).then(() => {
return mergeSort(symbols, (a, b) => {
// sort by lineNumber, provider-rank, and column
if (a.symbol.range.startLineNumber < b.symbol.range.startLineNumber) {
return -1;
} else if (a.symbol.range.startLineNumber > b.symbol.range.startLineNumber) {
return 1;
} else if (provider.indexOf(a.provider) < provider.indexOf(b.provider)) {
return -1;
} else if (provider.indexOf(a.provider) > provider.indexOf(b.provider)) {
return 1;
} else if (a.symbol.range.startColumn < b.symbol.range.startColumn) {
return -1;
} else if (a.symbol.range.startColumn > b.symbol.range.startColumn) {
return 1;
} else {
return 0;
}
});
});
}
registerLanguageCommand('_executeCodeLensProvider', function (accessor, args) {
let { resource, itemResolveCount } = args;
if (!(resource instanceof URI)) {
throw illegalArgument();
}
const model = accessor.get(IModelService).getModel(resource);
if (!model) {
throw illegalArgument();
}
const result: ICodeLensSymbol[] = [];
return getCodeLensData(model, CancellationToken.None).then(value => {
let resolve: Thenable<any>[] = [];
for (const item of value) {
if (typeof itemResolveCount === 'undefined' || Boolean(item.symbol.command)) {
result.push(item.symbol);
} else if (itemResolveCount-- > 0) {
resolve.push(Promise.resolve(item.provider.resolveCodeLens(model, item.symbol, CancellationToken.None)).then(symbol => result.push(symbol)));
}
}
return Promise.all(resolve);
}).then(() => {
return result;
});
});
| src/vs/editor/contrib/codelens/codelens.ts | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.00017511278565507382,
0.00017104244034271687,
0.00016236813098657876,
0.00017176779510919005,
0.000004356157205620548
] |
{
"id": 4,
"code_window": [
"\t\t.catch(err => result.emit('error', err));\n",
"\n",
"\treturn result.pipe(createStatsStream(path.basename(extensionPath)));\n",
"}\n",
"\n",
"const baseHeaders = {\n",
"\t'X-Market-Client-Id': 'VSCode Build',\n",
"\t'User-Agent': 'VSCode Build',\n",
"\t'X-Market-User-Id': '291C1CD0-051A-4123-9B4B-30D60EF52EE2',\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"function error(err: any): Stream {\n",
"\tconst result = es.through();\n",
"\tsetTimeout(() => result.emit('error', err));\n",
"\treturn result;\n",
"}\n",
"\n"
],
"file_path": "build/lib/extensions.ts",
"type": "add",
"edit_start_line_idx": 176
} | "use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* 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 });
var es = require("event-stream");
var fs = require("fs");
var glob = require("glob");
var gulp = require("gulp");
var path = require("path");
var File = require("vinyl");
var vsce = require("vsce");
var stats_1 = require("./stats");
var util2 = require("./util");
var remote = require("gulp-remote-src");
var vzip = require('gulp-vinyl-zip');
var filter = require('gulp-filter');
var rename = require('gulp-rename');
var util = require('gulp-util');
var buffer = require('gulp-buffer');
var json = require('gulp-json-editor');
var webpack = require('webpack');
var webpackGulp = require('webpack-stream');
var root = path.resolve(path.join(__dirname, '..', '..'));
function fromLocal(extensionPath, sourceMappingURLBase) {
var webpackFilename = path.join(extensionPath, 'extension.webpack.config.js');
if (fs.existsSync(webpackFilename)) {
return fromLocalWebpack(extensionPath, sourceMappingURLBase);
}
else {
return fromLocalNormal(extensionPath);
}
}
function fromLocalWebpack(extensionPath, sourceMappingURLBase) {
var result = es.through();
var packagedDependencies = [];
var packageJsonConfig = require(path.join(extensionPath, 'package.json'));
var webpackRootConfig = require(path.join(extensionPath, 'extension.webpack.config.js'));
for (var key in webpackRootConfig.externals) {
if (key in packageJsonConfig.dependencies) {
packagedDependencies.push(key);
}
}
vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn, packagedDependencies: packagedDependencies }).then(function (fileNames) {
var files = fileNames
.map(function (fileName) { return path.join(extensionPath, fileName); })
.map(function (filePath) { return new File({
path: filePath,
stat: fs.statSync(filePath),
base: extensionPath,
contents: fs.createReadStream(filePath)
}); });
var filesStream = es.readArray(files);
// check for a webpack configuration files, then invoke webpack
// and merge its output with the files stream. also rewrite the package.json
// file to a new entry point
var webpackConfigLocations = glob.sync(path.join(extensionPath, '/**/extension.webpack.config.js'), { ignore: ['**/node_modules'] });
var packageJsonFilter = filter(function (f) {
if (path.basename(f.path) === 'package.json') {
// only modify package.json's next to the webpack file.
// to be safe, use existsSync instead of path comparison.
return fs.existsSync(path.join(path.dirname(f.path), 'extension.webpack.config.js'));
}
return false;
}, { restore: true });
var patchFilesStream = filesStream
.pipe(packageJsonFilter)
.pipe(buffer())
.pipe(json(function (data) {
// hardcoded entry point directory!
data.main = data.main.replace('/out/', /dist/);
return data;
}))
.pipe(packageJsonFilter.restore);
var webpackStreams = webpackConfigLocations.map(function (webpackConfigPath) {
var webpackDone = function (err, stats) {
util.log("Bundled extension: " + util.colors.yellow(path.join(path.basename(extensionPath), path.relative(extensionPath, webpackConfigPath))) + "...");
if (err) {
result.emit('error', err);
}
var compilation = stats.compilation;
if (compilation.errors.length > 0) {
result.emit('error', compilation.errors.join('\n'));
}
if (compilation.warnings.length > 0) {
result.emit('error', compilation.warnings.join('\n'));
}
};
var webpackConfig = __assign({}, require(webpackConfigPath), { mode: 'production' });
var relativeOutputPath = path.relative(extensionPath, webpackConfig.output.path);
return webpackGulp(webpackConfig, webpack, webpackDone)
.pipe(es.through(function (data) {
data.stat = data.stat || {};
data.base = extensionPath;
this.emit('data', data);
}))
.pipe(es.through(function (data) {
// source map handling:
// * rewrite sourceMappingURL
// * save to disk so that upload-task picks this up
if (sourceMappingURLBase) {
var contents = data.contents.toString('utf8');
data.contents = Buffer.from(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, function (_m, g1) {
return "\n//# sourceMappingURL=" + sourceMappingURLBase + "/extensions/" + path.basename(extensionPath) + "/" + relativeOutputPath + "/" + g1;
}), 'utf8');
if (/\.js\.map$/.test(data.path)) {
if (!fs.existsSync(path.dirname(data.path))) {
fs.mkdirSync(path.dirname(data.path));
}
fs.writeFileSync(data.path, data.contents);
}
}
this.emit('data', data);
}));
});
es.merge.apply(es, webpackStreams.concat([patchFilesStream])).pipe(result);
}).catch(function (err) {
console.error(extensionPath);
console.error(packagedDependencies);
result.emit('error', err);
});
return result.pipe(stats_1.createStatsStream(path.basename(extensionPath)));
}
function fromLocalNormal(extensionPath) {
var result = es.through();
vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn })
.then(function (fileNames) {
var files = fileNames
.map(function (fileName) { return path.join(extensionPath, fileName); })
.map(function (filePath) { return new File({
path: filePath,
stat: fs.statSync(filePath),
base: extensionPath,
contents: fs.createReadStream(filePath)
}); });
es.readArray(files).pipe(result);
})
.catch(function (err) { return result.emit('error', err); });
return result.pipe(stats_1.createStatsStream(path.basename(extensionPath)));
}
var baseHeaders = {
'X-Market-Client-Id': 'VSCode Build',
'User-Agent': 'VSCode Build',
'X-Market-User-Id': '291C1CD0-051A-4123-9B4B-30D60EF52EE2',
};
function fromMarketplace(extensionName, version, metadata) {
var _a = extensionName.split('.'), publisher = _a[0], name = _a[1];
var url = "https://marketplace.visualstudio.com/_apis/public/gallery/publishers/" + publisher + "/vsextensions/" + name + "/" + version + "/vspackage";
util.log('Downloading extension:', util.colors.yellow(extensionName + "@" + version), '...');
var options = {
base: url,
requestOptions: {
gzip: true,
headers: baseHeaders
}
};
var packageJsonFilter = filter('package.json', { restore: true });
return remote('', options)
.on('error', function (err) {
console.log('Error downloading extension:', util.colors.yellow(extensionName + "@" + version));
console.error(err);
})
.on('end', function () {
console.log('Downloaded extension:', util.colors.yellow(extensionName + "@" + version));
})
.pipe(vzip.src())
.pipe(filter('extension/**'))
.pipe(rename(function (p) { return p.dirname = p.dirname.replace(/^extension\/?/, ''); }))
.pipe(packageJsonFilter)
.pipe(buffer())
.pipe(json({ __metadata: metadata }))
.pipe(packageJsonFilter.restore);
}
exports.fromMarketplace = fromMarketplace;
var excludedExtensions = [
'vscode-api-tests',
'vscode-colorize-tests',
'ms-vscode.node-debug',
'ms-vscode.node-debug2',
];
var builtInExtensions = require('../builtInExtensions.json');
/**
* 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
* stack frames to complete the download in under 2 minutes, at which point the
* marketplace server cuts off the http request. So, we sequentialize the extensino tasks.
*/
function sequence(streamProviders) {
var result = es.through();
function pop() {
if (streamProviders.length === 0) {
result.emit('end');
}
else {
var fn = streamProviders.shift();
fn()
.on('end', function () { setTimeout(pop, 0); })
.pipe(result, { end: false });
}
}
pop();
return result;
}
function packageExtensionsStream(opts) {
opts = opts || {};
var localExtensionDescriptions = glob.sync('extensions/*/package.json')
.map(function (manifestPath) {
var extensionPath = path.dirname(path.join(root, manifestPath));
var extensionName = path.basename(extensionPath);
return { name: extensionName, path: extensionPath };
})
.filter(function (_a) {
var name = _a.name;
return excludedExtensions.indexOf(name) === -1;
})
.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)
.pipe(rename(function (p) { return p.dirname = "extensions/" + extension.name + "/" + p.dirname; }));
})); };
var localExtensionDependencies = function () { return gulp.src('extensions/node_modules/**', { base: '.' }); };
var marketplaceExtensions = function () { return es.merge.apply(es, builtInExtensions
.filter(function (_a) {
var name = _a.name;
return opts.desiredExtensions ? opts.desiredExtensions.indexOf(name) >= 0 : true;
})
.map(function (extension) {
return fromMarketplace(extension.name, extension.version, extension.metadata)
.pipe(rename(function (p) { return p.dirname = "extensions/" + extension.name + "/" + p.dirname; }));
})); };
return sequence([localExtensions, localExtensionDependencies, marketplaceExtensions])
.pipe(util2.setExecutableBit(['**/*.sh']))
.pipe(filter(['**', '!**/*.js.map']));
}
exports.packageExtensionsStream = packageExtensionsStream;
| build/lib/extensions.js | 1 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.9990354776382446,
0.11727908998727798,
0.00017203234892804176,
0.004224572330713272,
0.2916097044944763
] |
{
"id": 4,
"code_window": [
"\t\t.catch(err => result.emit('error', err));\n",
"\n",
"\treturn result.pipe(createStatsStream(path.basename(extensionPath)));\n",
"}\n",
"\n",
"const baseHeaders = {\n",
"\t'X-Market-Client-Id': 'VSCode Build',\n",
"\t'User-Agent': 'VSCode Build',\n",
"\t'X-Market-User-Id': '291C1CD0-051A-4123-9B4B-30D60EF52EE2',\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"function error(err: any): Stream {\n",
"\tconst result = es.through();\n",
"\tsetTimeout(() => result.emit('error', err));\n",
"\treturn result;\n",
"}\n",
"\n"
],
"file_path": "build/lib/extensions.ts",
"type": "add",
"edit_start_line_idx": 176
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as assert from 'assert';
import { Client } from 'vs/base/parts/ipc/node/ipc.cp';
import { always } from 'vs/base/common/async';
import { ITestChannel, TestServiceClient } from './testService';
import { getPathFromAmdModule } from 'vs/base/common/amd';
function createClient(): Client {
return new Client(getPathFromAmdModule(require, 'bootstrap-fork'), {
serverName: 'TestServer',
env: { AMD_ENTRYPOINT: 'vs/base/parts/ipc/test/node/testApp', verbose: true }
});
}
suite('IPC, Child Process', () => {
test('createChannel', () => {
const client = createClient();
const channel = client.getChannel<ITestChannel>('test');
const service = new TestServiceClient(channel);
const result = service.pong('ping').then(r => {
assert.equal(r.incoming, 'ping');
assert.equal(r.outgoing, 'pong');
});
return always(result, () => client.dispose());
});
test('events', () => {
const client = createClient();
const channel = client.getChannel<ITestChannel>('test');
const service = new TestServiceClient(channel);
const event = new Promise((c, e) => {
service.onMarco(({ answer }) => {
try {
assert.equal(answer, 'polo');
c(null);
} catch (err) {
e(err);
}
});
});
const request = service.marco();
const result = Promise.all([request, event]);
return always(result, () => client.dispose());
});
test('event dispose', () => {
const client = createClient();
const channel = client.getChannel<ITestChannel>('test');
const service = new TestServiceClient(channel);
let count = 0;
const disposable = service.onMarco(() => count++);
const result = service.marco().then(answer => {
assert.equal(answer, 'polo');
assert.equal(count, 1);
return service.marco().then(answer => {
assert.equal(answer, 'polo');
assert.equal(count, 2);
disposable.dispose();
return service.marco().then(answer => {
assert.equal(answer, 'polo');
assert.equal(count, 2);
});
});
});
return always(result, () => client.dispose());
});
});
| src/vs/base/parts/ipc/test/node/ipc.cp.test.ts | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.001593180000782013,
0.0005319428164511919,
0.00016868379316292703,
0.00025751342764124274,
0.00048718496691435575
] |
{
"id": 4,
"code_window": [
"\t\t.catch(err => result.emit('error', err));\n",
"\n",
"\treturn result.pipe(createStatsStream(path.basename(extensionPath)));\n",
"}\n",
"\n",
"const baseHeaders = {\n",
"\t'X-Market-Client-Id': 'VSCode Build',\n",
"\t'User-Agent': 'VSCode Build',\n",
"\t'X-Market-User-Id': '291C1CD0-051A-4123-9B4B-30D60EF52EE2',\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"function error(err: any): Stream {\n",
"\tconst result = es.through();\n",
"\tsetTimeout(() => result.emit('error', err));\n",
"\treturn result;\n",
"}\n",
"\n"
],
"file_path": "build/lib/extensions.ts",
"type": "add",
"edit_start_line_idx": 176
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { RunOnceScheduler, TimeoutTimer } from 'vs/base/common/async';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { ReplacePattern, parseReplaceString } from 'vs/editor/contrib/find/replacePattern';
import { ReplaceCommand, ReplaceCommandThatPreservesSelection } from 'vs/editor/common/commands/replaceCommand';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { FindDecorations } from './findDecorations';
import { FindReplaceState, FindReplaceStateChangedEvent } from './findState';
import { ReplaceAllCommand } from './replaceAllCommand';
import { Selection } from 'vs/editor/common/core/selection';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { Constants } from 'vs/editor/common/core/uint';
import { SearchParams } from 'vs/editor/common/model/textModelSearch';
import { IKeybindings } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { CursorChangeReason, ICursorPositionChangedEvent } from 'vs/editor/common/controller/cursorEvents';
import { RawContextKey, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { ITextModel, FindMatch, EndOfLinePreference } from 'vs/editor/common/model';
export const CONTEXT_FIND_WIDGET_VISIBLE = new RawContextKey<boolean>('findWidgetVisible', false);
export const CONTEXT_FIND_WIDGET_NOT_VISIBLE: ContextKeyExpr = CONTEXT_FIND_WIDGET_VISIBLE.toNegated();
// Keep ContextKey use of 'Focussed' to not break when clauses
export const CONTEXT_FIND_INPUT_FOCUSED = new RawContextKey<boolean>('findInputFocussed', false);
export const CONTEXT_REPLACE_INPUT_FOCUSED = new RawContextKey<boolean>('replaceInputFocussed', false);
export const ToggleCaseSensitiveKeybinding: IKeybindings = {
primary: KeyMod.Alt | KeyCode.KEY_C,
mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C }
};
export const ToggleWholeWordKeybinding: IKeybindings = {
primary: KeyMod.Alt | KeyCode.KEY_W,
mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_W }
};
export const ToggleRegexKeybinding: IKeybindings = {
primary: KeyMod.Alt | KeyCode.KEY_R,
mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_R }
};
export const ToggleSearchScopeKeybinding: IKeybindings = {
primary: KeyMod.Alt | KeyCode.KEY_L,
mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_L }
};
export const FIND_IDS = {
StartFindAction: 'actions.find',
StartFindWithSelection: 'actions.findWithSelection',
NextMatchFindAction: 'editor.action.nextMatchFindAction',
PreviousMatchFindAction: 'editor.action.previousMatchFindAction',
NextSelectionMatchFindAction: 'editor.action.nextSelectionMatchFindAction',
PreviousSelectionMatchFindAction: 'editor.action.previousSelectionMatchFindAction',
StartFindReplaceAction: 'editor.action.startFindReplaceAction',
CloseFindWidgetCommand: 'closeFindWidget',
ToggleCaseSensitiveCommand: 'toggleFindCaseSensitive',
ToggleWholeWordCommand: 'toggleFindWholeWord',
ToggleRegexCommand: 'toggleFindRegex',
ToggleSearchScopeCommand: 'toggleFindInSelection',
ReplaceOneAction: 'editor.action.replaceOne',
ReplaceAllAction: 'editor.action.replaceAll',
SelectAllMatchesAction: 'editor.action.selectAllMatches'
};
export const MATCHES_LIMIT = 19999;
const RESEARCH_DELAY = 240;
export class FindModelBoundToEditorModel {
private _editor: ICodeEditor;
private _state: FindReplaceState;
private _toDispose: IDisposable[];
private _decorations: FindDecorations;
private _ignoreModelContentChanged: boolean;
private _startSearchingTimer: TimeoutTimer;
private _updateDecorationsScheduler: RunOnceScheduler;
private _isDisposed: boolean;
constructor(editor: ICodeEditor, state: FindReplaceState) {
this._editor = editor;
this._state = state;
this._toDispose = [];
this._isDisposed = false;
this._startSearchingTimer = new TimeoutTimer();
this._decorations = new FindDecorations(editor);
this._toDispose.push(this._decorations);
this._updateDecorationsScheduler = new RunOnceScheduler(() => this.research(false), 100);
this._toDispose.push(this._updateDecorationsScheduler);
this._toDispose.push(this._editor.onDidChangeCursorPosition((e: ICursorPositionChangedEvent) => {
if (
e.reason === CursorChangeReason.Explicit
|| e.reason === CursorChangeReason.Undo
|| e.reason === CursorChangeReason.Redo
) {
this._decorations.setStartPosition(this._editor.getPosition());
}
}));
this._ignoreModelContentChanged = false;
this._toDispose.push(this._editor.onDidChangeModelContent((e) => {
if (this._ignoreModelContentChanged) {
return;
}
if (e.isFlush) {
// a model.setValue() was called
this._decorations.reset();
}
this._decorations.setStartPosition(this._editor.getPosition());
this._updateDecorationsScheduler.schedule();
}));
this._toDispose.push(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
this.research(false, this._state.searchScope);
}
public dispose(): void {
this._isDisposed = true;
dispose(this._startSearchingTimer);
this._toDispose = dispose(this._toDispose);
}
private _onStateChanged(e: FindReplaceStateChangedEvent): void {
if (this._isDisposed) {
// The find model is disposed during a find state changed event
return;
}
if (!this._editor.getModel()) {
// The find model will be disposed momentarily
return;
}
if (e.searchString || e.isReplaceRevealed || e.isRegex || e.wholeWord || e.matchCase || e.searchScope) {
let model = this._editor.getModel();
if (model.isTooLargeForSyncing()) {
this._startSearchingTimer.cancel();
this._startSearchingTimer.setIfNotSet(() => {
if (e.searchScope) {
this.research(e.moveCursor, this._state.searchScope);
} else {
this.research(e.moveCursor);
}
}, RESEARCH_DELAY);
} else {
if (e.searchScope) {
this.research(e.moveCursor, this._state.searchScope);
} else {
this.research(e.moveCursor);
}
}
}
}
private static _getSearchRange(model: ITextModel, findScope: Range): Range {
let searchRange = model.getFullModelRange();
// If we have set now or before a find scope, use it for computing the search range
if (findScope) {
searchRange = searchRange.intersectRanges(findScope);
}
return searchRange;
}
private research(moveCursor: boolean, newFindScope?: Range): void {
let findScope: Range = null;
if (typeof newFindScope !== 'undefined') {
findScope = newFindScope;
} else {
findScope = this._decorations.getFindScope();
}
if (findScope !== null) {
if (findScope.startLineNumber !== findScope.endLineNumber) {
if (findScope.endColumn === 1) {
findScope = new Range(findScope.startLineNumber, 1, findScope.endLineNumber - 1, this._editor.getModel().getLineMaxColumn(findScope.endLineNumber - 1));
} else {
// multiline find scope => expand to line starts / ends
findScope = new Range(findScope.startLineNumber, 1, findScope.endLineNumber, this._editor.getModel().getLineMaxColumn(findScope.endLineNumber));
}
}
}
let findMatches = this._findMatches(findScope, false, MATCHES_LIMIT);
this._decorations.set(findMatches, findScope);
this._state.changeMatchInfo(
this._decorations.getCurrentMatchesPosition(this._editor.getSelection()),
this._decorations.getCount(),
undefined
);
if (moveCursor) {
this._moveToNextMatch(this._decorations.getStartPosition());
}
}
private _hasMatches(): boolean {
return (this._state.matchesCount > 0);
}
private _cannotFind(): boolean {
if (!this._hasMatches()) {
let findScope = this._decorations.getFindScope();
if (findScope) {
// Reveal the selection so user is reminded that 'selection find' is on.
this._editor.revealRangeInCenterIfOutsideViewport(findScope, editorCommon.ScrollType.Smooth);
}
return true;
}
return false;
}
private _setCurrentFindMatch(match: Range): void {
let matchesPosition = this._decorations.setCurrentFindMatch(match);
this._state.changeMatchInfo(
matchesPosition,
this._decorations.getCount(),
match
);
this._editor.setSelection(match);
this._editor.revealRangeInCenterIfOutsideViewport(match, editorCommon.ScrollType.Smooth);
}
private _prevSearchPosition(before: Position) {
let isUsingLineStops = this._state.isRegex && (
this._state.searchString.indexOf('^') >= 0
|| this._state.searchString.indexOf('$') >= 0
);
let { lineNumber, column } = before;
let model = this._editor.getModel();
if (isUsingLineStops || column === 1) {
if (lineNumber === 1) {
lineNumber = model.getLineCount();
} else {
lineNumber--;
}
column = model.getLineMaxColumn(lineNumber);
} else {
column--;
}
return new Position(lineNumber, column);
}
private _moveToPrevMatch(before: Position, isRecursed: boolean = false): void {
if (this._decorations.getCount() < MATCHES_LIMIT) {
let prevMatchRange = this._decorations.matchBeforePosition(before);
if (prevMatchRange && prevMatchRange.isEmpty() && prevMatchRange.getStartPosition().equals(before)) {
before = this._prevSearchPosition(before);
prevMatchRange = this._decorations.matchBeforePosition(before);
}
if (prevMatchRange) {
this._setCurrentFindMatch(prevMatchRange);
}
return;
}
if (this._cannotFind()) {
return;
}
let findScope = this._decorations.getFindScope();
let searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), findScope);
// ...(----)...|...
if (searchRange.getEndPosition().isBefore(before)) {
before = searchRange.getEndPosition();
}
// ...|...(----)...
if (before.isBefore(searchRange.getStartPosition())) {
before = searchRange.getEndPosition();
}
let { lineNumber, column } = before;
let model = this._editor.getModel();
let position = new Position(lineNumber, column);
let prevMatch = model.findPreviousMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getConfiguration().wordSeparators : null, false);
if (prevMatch && prevMatch.range.isEmpty() && prevMatch.range.getStartPosition().equals(position)) {
// Looks like we're stuck at this position, unacceptable!
position = this._prevSearchPosition(position);
prevMatch = model.findPreviousMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getConfiguration().wordSeparators : null, false);
}
if (!prevMatch) {
// there is precisely one match and selection is on top of it
return null;
}
if (!isRecursed && !searchRange.containsRange(prevMatch.range)) {
return this._moveToPrevMatch(prevMatch.range.getStartPosition(), true);
}
this._setCurrentFindMatch(prevMatch.range);
}
public moveToPrevMatch(): void {
this._moveToPrevMatch(this._editor.getSelection().getStartPosition());
}
private _nextSearchPosition(after: Position) {
let isUsingLineStops = this._state.isRegex && (
this._state.searchString.indexOf('^') >= 0
|| this._state.searchString.indexOf('$') >= 0
);
let { lineNumber, column } = after;
let model = this._editor.getModel();
if (isUsingLineStops || column === model.getLineMaxColumn(lineNumber)) {
if (lineNumber === model.getLineCount()) {
lineNumber = 1;
} else {
lineNumber++;
}
column = 1;
} else {
column++;
}
return new Position(lineNumber, column);
}
private _moveToNextMatch(after: Position): void {
if (this._decorations.getCount() < MATCHES_LIMIT) {
let nextMatchRange = this._decorations.matchAfterPosition(after);
if (nextMatchRange && nextMatchRange.isEmpty() && nextMatchRange.getStartPosition().equals(after)) {
// Looks like we're stuck at this position, unacceptable!
after = this._nextSearchPosition(after);
nextMatchRange = this._decorations.matchAfterPosition(after);
}
if (nextMatchRange) {
this._setCurrentFindMatch(nextMatchRange);
}
return;
}
let nextMatch = this._getNextMatch(after, false, true);
if (nextMatch) {
this._setCurrentFindMatch(nextMatch.range);
}
}
private _getNextMatch(after: Position, captureMatches: boolean, forceMove: boolean, isRecursed: boolean = false): FindMatch {
if (this._cannotFind()) {
return null;
}
let findScope = this._decorations.getFindScope();
let searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), findScope);
// ...(----)...|...
if (searchRange.getEndPosition().isBefore(after)) {
after = searchRange.getStartPosition();
}
// ...|...(----)...
if (after.isBefore(searchRange.getStartPosition())) {
after = searchRange.getStartPosition();
}
let { lineNumber, column } = after;
let model = this._editor.getModel();
let position = new Position(lineNumber, column);
let nextMatch = model.findNextMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getConfiguration().wordSeparators : null, captureMatches);
if (forceMove && nextMatch && nextMatch.range.isEmpty() && nextMatch.range.getStartPosition().equals(position)) {
// Looks like we're stuck at this position, unacceptable!
position = this._nextSearchPosition(position);
nextMatch = model.findNextMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getConfiguration().wordSeparators : null, captureMatches);
}
if (!nextMatch) {
// there is precisely one match and selection is on top of it
return null;
}
if (!isRecursed && !searchRange.containsRange(nextMatch.range)) {
return this._getNextMatch(nextMatch.range.getEndPosition(), captureMatches, forceMove, true);
}
return nextMatch;
}
public moveToNextMatch(): void {
this._moveToNextMatch(this._editor.getSelection().getEndPosition());
}
private _getReplacePattern(): ReplacePattern {
if (this._state.isRegex) {
return parseReplaceString(this._state.replaceString);
}
return ReplacePattern.fromStaticValue(this._state.replaceString);
}
public replace(): void {
if (!this._hasMatches()) {
return;
}
let replacePattern = this._getReplacePattern();
let selection = this._editor.getSelection();
let nextMatch = this._getNextMatch(selection.getStartPosition(), replacePattern.hasReplacementPatterns, false);
if (nextMatch) {
if (selection.equalsRange(nextMatch.range)) {
// selection sits on a find match => replace it!
let replaceString = replacePattern.buildReplaceString(nextMatch.matches);
let command = new ReplaceCommand(selection, replaceString);
this._executeEditorCommand('replace', command);
this._decorations.setStartPosition(new Position(selection.startLineNumber, selection.startColumn + replaceString.length));
this.research(true);
} else {
this._decorations.setStartPosition(this._editor.getPosition());
this._setCurrentFindMatch(nextMatch.range);
}
}
}
private _findMatches(findScope: Range, captureMatches: boolean, limitResultCount: number): FindMatch[] {
let searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), findScope);
return this._editor.getModel().findMatches(this._state.searchString, searchRange, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getConfiguration().wordSeparators : null, captureMatches, limitResultCount);
}
public replaceAll(): void {
if (!this._hasMatches()) {
return;
}
const findScope = this._decorations.getFindScope();
if (findScope === null && this._state.matchesCount >= MATCHES_LIMIT) {
// Doing a replace on the entire file that is over ${MATCHES_LIMIT} matches
this._largeReplaceAll();
} else {
this._regularReplaceAll(findScope);
}
this.research(false);
}
private _largeReplaceAll(): void {
const searchParams = new SearchParams(this._state.searchString, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getConfiguration().wordSeparators : null);
const searchData = searchParams.parseSearchRequest();
if (!searchData) {
return;
}
let searchRegex = searchData.regex;
if (!searchRegex.multiline) {
let mod = 'm';
if (searchRegex.ignoreCase) {
mod += 'i';
}
if (searchRegex.global) {
mod += 'g';
}
searchRegex = new RegExp(searchRegex.source, mod);
}
const model = this._editor.getModel();
const modelText = model.getValue(EndOfLinePreference.LF);
const fullModelRange = model.getFullModelRange();
const replacePattern = this._getReplacePattern();
let resultText: string;
if (replacePattern.hasReplacementPatterns) {
resultText = modelText.replace(searchRegex, function () {
return replacePattern.buildReplaceString(<string[]><any>arguments);
});
} else {
resultText = modelText.replace(searchRegex, replacePattern.buildReplaceString(null));
}
let command = new ReplaceCommandThatPreservesSelection(fullModelRange, resultText, this._editor.getSelection());
this._executeEditorCommand('replaceAll', command);
}
private _regularReplaceAll(findScope: Range): void {
const replacePattern = this._getReplacePattern();
// Get all the ranges (even more than the highlighted ones)
let matches = this._findMatches(findScope, replacePattern.hasReplacementPatterns, Constants.MAX_SAFE_SMALL_INTEGER);
let replaceStrings: string[] = [];
for (let i = 0, len = matches.length; i < len; i++) {
replaceStrings[i] = replacePattern.buildReplaceString(matches[i].matches);
}
let command = new ReplaceAllCommand(this._editor.getSelection(), matches.map(m => m.range), replaceStrings);
this._executeEditorCommand('replaceAll', command);
}
public selectAllMatches(): void {
if (!this._hasMatches()) {
return;
}
let findScope = this._decorations.getFindScope();
// Get all the ranges (even more than the highlighted ones)
let matches = this._findMatches(findScope, false, Constants.MAX_SAFE_SMALL_INTEGER);
let selections = matches.map(m => new Selection(m.range.startLineNumber, m.range.startColumn, m.range.endLineNumber, m.range.endColumn));
// If one of the ranges is the editor selection, then maintain it as primary
let editorSelection = this._editor.getSelection();
for (let i = 0, len = selections.length; i < len; i++) {
let sel = selections[i];
if (sel.equalsRange(editorSelection)) {
selections = [editorSelection].concat(selections.slice(0, i)).concat(selections.slice(i + 1));
break;
}
}
this._editor.setSelections(selections);
}
private _executeEditorCommand(source: string, command: editorCommon.ICommand): void {
try {
this._ignoreModelContentChanged = true;
this._editor.pushUndoStop();
this._editor.executeCommand(source, command);
this._editor.pushUndoStop();
} finally {
this._ignoreModelContentChanged = false;
}
}
}
| src/vs/editor/contrib/find/findModel.ts | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.0001812970294849947,
0.0001699993445072323,
0.00016556748596485704,
0.00016905090888030827,
0.0000028880147056042915
] |
{
"id": 4,
"code_window": [
"\t\t.catch(err => result.emit('error', err));\n",
"\n",
"\treturn result.pipe(createStatsStream(path.basename(extensionPath)));\n",
"}\n",
"\n",
"const baseHeaders = {\n",
"\t'X-Market-Client-Id': 'VSCode Build',\n",
"\t'User-Agent': 'VSCode Build',\n",
"\t'X-Market-User-Id': '291C1CD0-051A-4123-9B4B-30D60EF52EE2',\n",
"};\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"function error(err: any): Stream {\n",
"\tconst result = es.through();\n",
"\tsetTimeout(() => result.emit('error', err));\n",
"\treturn result;\n",
"}\n",
"\n"
],
"file_path": "build/lib/extensions.ts",
"type": "add",
"edit_start_line_idx": 176
} | {
"compilerOptions": {
"target": "es6",
"lib": [
"es2016"
],
"module": "commonjs",
"outDir": "./out",
"noImplicitAny": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strict": true,
"experimentalDecorators": true
},
"include": [
"src/**/*"
]
}
| extensions/merge-conflict/tsconfig.json | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.0001702969748293981,
0.00016907035023905337,
0.0001678437110967934,
0.00016907035023905337,
0.0000012266318663023412
] |
{
"id": 5,
"code_window": [
"\tconst packageJsonFilter = filter('package.json', { restore: true });\n",
"\n",
"\treturn remote('', options)\n",
"\t\t.on('error', function (err) {\n",
"\t\t\tconsole.log('Error downloading extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
"\t\t\tconsole.error(err);\n",
"\t\t})\n",
"\t\t.on('end', function () {\n",
"\t\t\tconsole.log('Downloaded extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
"\t\t})\n",
"\t\t.pipe(vzip.src())\n",
"\t\t.pipe(filter('extension/**'))\n",
"\t\t.pipe(rename(p => p.dirname = p.dirname.replace(/^extension\\/?/, '')))\n",
"\t\t.pipe(packageJsonFilter)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "build/lib/extensions.ts",
"type": "replace",
"edit_start_line_idx": 199
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as es from 'event-stream';
import * as fs from 'fs';
import * as glob from 'glob';
import * as gulp from 'gulp';
import * as path from 'path';
import { Stream } from 'stream';
import * as File from 'vinyl';
import * as vsce from 'vsce';
import { createStatsStream } from './stats';
import * as util2 from './util';
import remote = require('gulp-remote-src');
const vzip = require('gulp-vinyl-zip');
const filter = require('gulp-filter');
const rename = require('gulp-rename');
const util = require('gulp-util');
const buffer = require('gulp-buffer');
const json = require('gulp-json-editor');
const webpack = require('webpack');
const webpackGulp = require('webpack-stream');
const root = path.resolve(path.join(__dirname, '..', '..'));
function fromLocal(extensionPath: string, sourceMappingURLBase?: string): Stream {
const webpackFilename = path.join(extensionPath, 'extension.webpack.config.js');
if (fs.existsSync(webpackFilename)) {
return fromLocalWebpack(extensionPath, sourceMappingURLBase);
} else {
return fromLocalNormal(extensionPath);
}
}
function fromLocalWebpack(extensionPath: string, sourceMappingURLBase: string): Stream {
let result = es.through();
let packagedDependencies: string[] = [];
let packageJsonConfig = require(path.join(extensionPath, 'package.json'));
let webpackRootConfig = require(path.join(extensionPath, 'extension.webpack.config.js'));
for (const key in webpackRootConfig.externals) {
if (key in packageJsonConfig.dependencies) {
packagedDependencies.push(key);
}
}
vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn, packagedDependencies }).then(fileNames => {
const files = fileNames
.map(fileName => path.join(extensionPath, fileName))
.map(filePath => new File({
path: filePath,
stat: fs.statSync(filePath),
base: extensionPath,
contents: fs.createReadStream(filePath) as any
}));
const filesStream = es.readArray(files);
// check for a webpack configuration files, then invoke webpack
// and merge its output with the files stream. also rewrite the package.json
// file to a new entry point
const webpackConfigLocations = (<string[]>glob.sync(
path.join(extensionPath, '/**/extension.webpack.config.js'),
{ ignore: ['**/node_modules'] }
));
const packageJsonFilter = filter(f => {
if (path.basename(f.path) === 'package.json') {
// only modify package.json's next to the webpack file.
// to be safe, use existsSync instead of path comparison.
return fs.existsSync(path.join(path.dirname(f.path), 'extension.webpack.config.js'));
}
return false;
}, { restore: true });
const patchFilesStream = filesStream
.pipe(packageJsonFilter)
.pipe(buffer())
.pipe(json(data => {
// hardcoded entry point directory!
data.main = data.main.replace('/out/', /dist/);
return data;
}))
.pipe(packageJsonFilter.restore);
const webpackStreams = webpackConfigLocations.map(webpackConfigPath => {
const webpackDone = (err, stats) => {
util.log(`Bundled extension: ${util.colors.yellow(path.join(path.basename(extensionPath), path.relative(extensionPath, webpackConfigPath)))}...`);
if (err) {
result.emit('error', err);
}
const { compilation } = stats;
if (compilation.errors.length > 0) {
result.emit('error', compilation.errors.join('\n'));
}
if (compilation.warnings.length > 0) {
result.emit('error', compilation.warnings.join('\n'));
}
};
const webpackConfig = {
...require(webpackConfigPath),
...{ mode: 'production' }
};
let relativeOutputPath = path.relative(extensionPath, webpackConfig.output.path);
return webpackGulp(webpackConfig, webpack, webpackDone)
.pipe(es.through(function (data) {
data.stat = data.stat || {};
data.base = extensionPath;
this.emit('data', data);
}))
.pipe(es.through(function (data: File) {
// source map handling:
// * rewrite sourceMappingURL
// * save to disk so that upload-task picks this up
if (sourceMappingURLBase) {
const contents = (<Buffer>data.contents).toString('utf8');
data.contents = Buffer.from(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, function (_m, g1) {
return `\n//# sourceMappingURL=${sourceMappingURLBase}/extensions/${path.basename(extensionPath)}/${relativeOutputPath}/${g1}`;
}), 'utf8');
if (/\.js\.map$/.test(data.path)) {
if (!fs.existsSync(path.dirname(data.path))) {
fs.mkdirSync(path.dirname(data.path));
}
fs.writeFileSync(data.path, data.contents);
}
}
this.emit('data', data);
}));
});
es.merge(...webpackStreams, patchFilesStream)
// .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(packagedDependencies);
result.emit('error', err);
});
return result.pipe(createStatsStream(path.basename(extensionPath)));
}
function fromLocalNormal(extensionPath: string): Stream {
const result = es.through();
vsce.listFiles({ cwd: extensionPath, packageManager: vsce.PackageManager.Yarn })
.then(fileNames => {
const files = fileNames
.map(fileName => path.join(extensionPath, fileName))
.map(filePath => new File({
path: filePath,
stat: fs.statSync(filePath),
base: extensionPath,
contents: fs.createReadStream(filePath) as any
}));
es.readArray(files).pipe(result);
})
.catch(err => result.emit('error', err));
return result.pipe(createStatsStream(path.basename(extensionPath)));
}
const baseHeaders = {
'X-Market-Client-Id': 'VSCode Build',
'User-Agent': 'VSCode Build',
'X-Market-User-Id': '291C1CD0-051A-4123-9B4B-30D60EF52EE2',
};
export function fromMarketplace(extensionName: string, version: string, metadata: any): Stream {
const [publisher, name] = extensionName.split('.');
const url = `https://marketplace.visualstudio.com/_apis/public/gallery/publishers/${publisher}/vsextensions/${name}/${version}/vspackage`;
util.log('Downloading extension:', util.colors.yellow(`${extensionName}@${version}`), '...');
const options = {
base: url,
requestOptions: {
gzip: true,
headers: baseHeaders
}
};
const packageJsonFilter = filter('package.json', { restore: true });
return remote('', options)
.on('error', function (err) {
console.log('Error downloading extension:', util.colors.yellow(extensionName + "@" + version));
console.error(err);
})
.on('end', function () {
console.log('Downloaded extension:', util.colors.yellow(extensionName + "@" + version));
})
.pipe(vzip.src())
.pipe(filter('extension/**'))
.pipe(rename(p => p.dirname = p.dirname.replace(/^extension\/?/, '')))
.pipe(packageJsonFilter)
.pipe(buffer())
.pipe(json({ __metadata: metadata }))
.pipe(packageJsonFilter.restore);
}
interface IPackageExtensionsOptions {
/**
* Set to undefined to package all of them.
*/
desiredExtensions?: string[];
sourceMappingURLBase?: string;
}
const excludedExtensions = [
'vscode-api-tests',
'vscode-colorize-tests',
'ms-vscode.node-debug',
'ms-vscode.node-debug2',
];
interface IBuiltInExtension {
name: string;
version: string;
repo: string;
metadata: any;
}
const builtInExtensions: IBuiltInExtension[] = require('../builtInExtensions.json');
/**
* 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
* stack frames to complete the download in under 2 minutes, at which point the
* marketplace server cuts off the http request. So, we sequentialize the extensino tasks.
*/
function sequence(streamProviders: { (): Stream }[]): Stream {
const result = es.through();
function pop() {
if (streamProviders.length === 0) {
result.emit('end');
} else {
const fn = streamProviders.shift();
fn()
.on('end', function () { setTimeout(pop, 0); })
.pipe(result, { end: false });
}
}
pop();
return result;
}
export function packageExtensionsStream(opts?: IPackageExtensionsOptions): NodeJS.ReadWriteStream {
opts = opts || {};
const localExtensionDescriptions = (<string[]>glob.sync('extensions/*/package.json'))
.map(manifestPath => {
const extensionPath = path.dirname(path.join(root, manifestPath));
const extensionName = path.basename(extensionPath);
return { name: extensionName, path: extensionPath };
})
.filter(({ name }) => excludedExtensions.indexOf(name) === -1)
.filter(({ name }) => opts.desiredExtensions ? opts.desiredExtensions.indexOf(name) >= 0 : true)
.filter(({ name }) => builtInExtensions.every(b => b.name !== name));
const localExtensions = () => es.merge(...localExtensionDescriptions.map(extension => {
return fromLocal(extension.path, opts.sourceMappingURLBase)
.pipe(rename(p => p.dirname = `extensions/${extension.name}/${p.dirname}`));
}));
const localExtensionDependencies = () => gulp.src('extensions/node_modules/**', { base: '.' });
const marketplaceExtensions = () => es.merge(
...builtInExtensions
.filter(({ name }) => opts.desiredExtensions ? opts.desiredExtensions.indexOf(name) >= 0 : true)
.map(extension => {
return fromMarketplace(extension.name, extension.version, extension.metadata)
.pipe(rename(p => p.dirname = `extensions/${extension.name}/${p.dirname}`));
})
);
return sequence([localExtensions, localExtensionDependencies, marketplaceExtensions])
.pipe(util2.setExecutableBit(['**/*.sh']))
.pipe(filter(['**', '!**/*.js.map']));
}
| build/lib/extensions.ts | 1 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.9980820417404175,
0.10457747429609299,
0.00016378516738768667,
0.00018196928431279957,
0.2959233522415161
] |
{
"id": 5,
"code_window": [
"\tconst packageJsonFilter = filter('package.json', { restore: true });\n",
"\n",
"\treturn remote('', options)\n",
"\t\t.on('error', function (err) {\n",
"\t\t\tconsole.log('Error downloading extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
"\t\t\tconsole.error(err);\n",
"\t\t})\n",
"\t\t.on('end', function () {\n",
"\t\t\tconsole.log('Downloaded extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
"\t\t})\n",
"\t\t.pipe(vzip.src())\n",
"\t\t.pipe(filter('extension/**'))\n",
"\t\t.pipe(rename(p => p.dirname = p.dirname.replace(/^extension\\/?/, '')))\n",
"\t\t.pipe(packageJsonFilter)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "build/lib/extensions.ts",
"type": "replace",
"edit_start_line_idx": 199
} | <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><path d="M17.705 8h-8.705s-2 .078-2 2v15s0 2 2 2l11-.004c2 .004 2-1.996 2-1.996v-11.491l-4.295-5.509zm-1.705 2v5h4v10h-11v-15h7zm5.509-6h-8.493s-2.016.016-2.031 2h8.015v.454l3.931 4.546h1.069v12c2 0 2-1.995 2-1.995v-11.357l-4.491-5.648z" fill="#fff"/></svg> | src/vs/workbench/parts/files/electron-browser/media/files-dark.svg | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.00016966018301900476,
0.00016966018301900476,
0.00016966018301900476,
0.00016966018301900476,
0
] |
{
"id": 5,
"code_window": [
"\tconst packageJsonFilter = filter('package.json', { restore: true });\n",
"\n",
"\treturn remote('', options)\n",
"\t\t.on('error', function (err) {\n",
"\t\t\tconsole.log('Error downloading extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
"\t\t\tconsole.error(err);\n",
"\t\t})\n",
"\t\t.on('end', function () {\n",
"\t\t\tconsole.log('Downloaded extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
"\t\t})\n",
"\t\t.pipe(vzip.src())\n",
"\t\t.pipe(filter('extension/**'))\n",
"\t\t.pipe(rename(p => p.dirname = p.dirname.replace(/^extension\\/?/, '')))\n",
"\t\t.pipe(packageJsonFilter)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "build/lib/extensions.ts",
"type": "replace",
"edit_start_line_idx": 199
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { alert } from 'vs/base/browser/ui/aria/aria';
import { isFalsyOrEmpty } from 'vs/base/common/arrays';
import { onUnexpectedError } from 'vs/base/common/errors';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorAction, EditorCommand, registerEditorAction, registerEditorCommand, registerEditorContribution, ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Range } from 'vs/editor/common/core/range';
import { IEditorContribution, ScrollType, Handler } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { ISuggestion, ISuggestSupport } from 'vs/editor/common/modes';
import { SnippetController2 } from 'vs/editor/contrib/snippet/snippetController2';
import { SnippetParser } from 'vs/editor/contrib/snippet/snippetParser';
import { SuggestMemories } from 'vs/editor/contrib/suggest/suggestMemory';
import * as nls from 'vs/nls';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ICompletionItem } from './completionModel';
import { Context as SuggestContext, ISuggestionItem } from './suggest';
import { SuggestAlternatives } from './suggestAlternatives';
import { State, SuggestModel } from './suggestModel';
import { ISelectedSuggestion, SuggestWidget } from './suggestWidget';
import { WordContextKey } from 'vs/editor/contrib/suggest/wordContextKey';
import { once, anyEvent } from 'vs/base/common/event';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorkerService';
class AcceptOnCharacterOracle {
private _disposables: IDisposable[] = [];
private _activeAcceptCharacters = new Set<string>();
private _activeItem: ISelectedSuggestion;
constructor(editor: ICodeEditor, widget: SuggestWidget, accept: (selected: ISelectedSuggestion) => any) {
this._disposables.push(widget.onDidShow(() => this._onItem(widget.getFocusedItem())));
this._disposables.push(widget.onDidFocus(this._onItem, this));
this._disposables.push(widget.onDidHide(this.reset, this));
this._disposables.push(editor.onWillType(text => {
if (this._activeItem) {
const ch = text[text.length - 1];
if (this._activeAcceptCharacters.has(ch) && editor.getConfiguration().contribInfo.acceptSuggestionOnCommitCharacter) {
accept(this._activeItem);
}
}
}));
}
private _onItem(selected: ISelectedSuggestion): void {
if (!selected || isFalsyOrEmpty(selected.item.suggestion.commitCharacters)) {
this.reset();
return;
}
this._activeItem = selected;
this._activeAcceptCharacters.clear();
for (const ch of selected.item.suggestion.commitCharacters) {
if (ch.length > 0) {
this._activeAcceptCharacters.add(ch[0]);
}
}
}
reset(): void {
this._activeItem = undefined;
}
dispose() {
dispose(this._disposables);
}
}
export class SuggestController implements IEditorContribution {
private static readonly ID: string = 'editor.contrib.suggestController';
public static get(editor: ICodeEditor): SuggestController {
return editor.getContribution<SuggestController>(SuggestController.ID);
}
private _model: SuggestModel;
private _widget: SuggestWidget;
private _memory: SuggestMemories;
private _alternatives: SuggestAlternatives;
private _toDispose: IDisposable[] = [];
private readonly _sticky = false; // for development purposes only
constructor(
private _editor: ICodeEditor,
@IEditorWorkerService editorWorker: IEditorWorkerService,
@ICommandService private readonly _commandService: ICommandService,
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
@ITelemetryService private readonly _telemetryService: ITelemetryService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
) {
this._model = new SuggestModel(this._editor, editorWorker);
this._memory = _instantiationService.createInstance(SuggestMemories, this._editor.getConfiguration().contribInfo.suggestSelection);
this._alternatives = new SuggestAlternatives(this._editor, item => this._onDidSelectItem(item, false, false), this._contextKeyService);
this._toDispose.push(_instantiationService.createInstance(WordContextKey, _editor));
this._toDispose.push(this._model.onDidTrigger(e => {
if (!this._widget) {
this._createSuggestWidget();
}
this._widget.showTriggered(e.auto, e.shy ? 250 : 50);
}));
this._toDispose.push(this._model.onDidSuggest(e => {
if (!e.shy) {
let index = this._memory.select(this._editor.getModel(), this._editor.getPosition(), e.completionModel.items);
this._widget.showSuggestions(e.completionModel, index, e.isFrozen, e.auto);
}
}));
this._toDispose.push(this._model.onDidCancel(e => {
if (this._widget && !e.retrigger) {
this._widget.hideWidget();
}
}));
this._toDispose.push(this._editor.onDidBlurEditorText(() => {
if (!this._sticky) {
this._model.cancel();
}
}));
// Manage the acceptSuggestionsOnEnter context key
let acceptSuggestionsOnEnter = SuggestContext.AcceptSuggestionsOnEnter.bindTo(_contextKeyService);
let updateFromConfig = () => {
const { acceptSuggestionOnEnter, suggestSelection } = this._editor.getConfiguration().contribInfo;
acceptSuggestionsOnEnter.set(acceptSuggestionOnEnter === 'on' || acceptSuggestionOnEnter === 'smart');
this._memory.setMode(suggestSelection);
};
this._toDispose.push(this._editor.onDidChangeConfiguration((e) => updateFromConfig()));
updateFromConfig();
}
private _createSuggestWidget(): void {
this._widget = this._instantiationService.createInstance(SuggestWidget, this._editor);
this._toDispose.push(this._widget.onDidSelect(item => this._onDidSelectItem(item, false, true), this));
// Wire up logic to accept a suggestion on certain characters
const autoAcceptOracle = new AcceptOnCharacterOracle(this._editor, this._widget, item => this._onDidSelectItem(item, false, true));
this._toDispose.push(
autoAcceptOracle,
this._model.onDidSuggest(e => {
if (e.completionModel.items.length === 0) {
autoAcceptOracle.reset();
}
})
);
let makesTextEdit = SuggestContext.MakesTextEdit.bindTo(this._contextKeyService);
this._toDispose.push(this._widget.onDidFocus(({ item }) => {
const position = this._editor.getPosition();
const startColumn = item.position.column - item.suggestion.overwriteBefore;
const endColumn = position.column;
let value = true;
if (
this._editor.getConfiguration().contribInfo.acceptSuggestionOnEnter === 'smart'
&& this._model.state === State.Auto
&& !item.suggestion.command
&& !item.suggestion.additionalTextEdits
&& !item.suggestion.insertTextIsSnippet
&& endColumn - startColumn === item.suggestion.insertText.length
) {
const oldText = this._editor.getModel().getValueInRange({
startLineNumber: position.lineNumber,
startColumn,
endLineNumber: position.lineNumber,
endColumn
});
value = oldText !== item.suggestion.insertText;
}
makesTextEdit.set(value);
}));
this._toDispose.push({
dispose() { makesTextEdit.reset(); }
});
}
getId(): string {
return SuggestController.ID;
}
dispose(): void {
this._toDispose = dispose(this._toDispose);
if (this._widget) {
this._widget.dispose();
this._widget = null;
}
if (this._model) {
this._model.dispose();
this._model = null;
}
}
protected _onDidSelectItem(event: ISelectedSuggestion, keepAlternativeSuggestions: boolean, undoStops: boolean): void {
if (!event || !event.item) {
this._alternatives.reset();
this._model.cancel();
return;
}
const { suggestion, position } = event.item;
const editorColumn = this._editor.getPosition().column;
const columnDelta = editorColumn - position.column;
// pushing undo stops *before* additional text edits and
// *after* the main edit
if (undoStops) {
this._editor.pushUndoStop();
}
if (Array.isArray(suggestion.additionalTextEdits)) {
this._editor.executeEdits('suggestController.additionalTextEdits', suggestion.additionalTextEdits.map(edit => EditOperation.replace(Range.lift(edit.range), edit.text)));
}
// keep item in memory
this._memory.memorize(this._editor.getModel(), this._editor.getPosition(), event.item);
let { insertText } = suggestion;
if (!suggestion.insertTextIsSnippet) {
insertText = SnippetParser.escape(insertText);
}
SnippetController2.get(this._editor).insert(
insertText,
suggestion.overwriteBefore + columnDelta,
suggestion.overwriteAfter,
false, false,
!suggestion.noWhitespaceAdjust
);
if (undoStops) {
this._editor.pushUndoStop();
}
if (!suggestion.command) {
// done
this._model.cancel();
} else if (suggestion.command.id === TriggerSuggestAction.id) {
// retigger
this._model.trigger({ auto: true }, true);
} else {
// exec command, done
this._commandService.executeCommand(suggestion.command.id, ...suggestion.command.arguments).then(undefined, onUnexpectedError);
this._model.cancel();
}
if (keepAlternativeSuggestions) {
this._alternatives.set(event);
}
this._alertCompletionItem(event.item);
SuggestController._onDidSelectTelemetry(this._telemetryService, suggestion);
}
private static _onDidSelectTelemetry(service: ITelemetryService, item: ISuggestion): void {
/* __GDPR__
"acceptSuggestion" : {
"type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"multiline" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
service.publicLog('acceptSuggestion', {
type: item.kind,
multiline: item.insertText.match(/\r|\n/)
});
}
private _alertCompletionItem({ suggestion }: ICompletionItem): void {
let msg = nls.localize('arai.alert.snippet', "Accepting '{0}' did insert the following text: {1}", suggestion.label, suggestion.insertText);
alert(msg);
}
triggerSuggest(onlyFrom?: ISuggestSupport[]): void {
this._model.trigger({ auto: false }, false, onlyFrom);
this._editor.revealLine(this._editor.getPosition().lineNumber, ScrollType.Smooth);
this._editor.focus();
}
triggerSuggestAndAcceptBest(defaultTypeText: string): void {
const positionNow = this._editor.getPosition();
const fallback = () => {
if (positionNow.equals(this._editor.getPosition())) {
this._editor.trigger('suggest', Handler.Type, { text: defaultTypeText });
}
};
const makesTextEdit = (item: ISuggestionItem): boolean => {
if (item.suggestion.insertTextIsSnippet || item.suggestion.additionalTextEdits) {
// snippet, other editor -> makes edit
return true;
}
const position = this._editor.getPosition();
const startColumn = item.position.column - item.suggestion.overwriteBefore;
const endColumn = position.column;
if (endColumn - startColumn !== item.suggestion.insertText.length) {
// unequal lengths -> makes edit
return true;
}
const textNow = this._editor.getModel().getValueInRange({
startLineNumber: position.lineNumber,
startColumn,
endLineNumber: position.lineNumber,
endColumn
});
// unequal text -> makes edit
return textNow !== item.suggestion.insertText;
};
once(this._model.onDidTrigger)(_ => {
// wait for trigger because only then the cancel-event is trustworthy
let listener: IDisposable[] = [];
anyEvent<any>(this._model.onDidTrigger, this._model.onDidCancel)(() => {
// retrigger or cancel -> try to type default text
dispose(listener);
fallback();
}, undefined, listener);
this._model.onDidSuggest(({ completionModel }) => {
dispose(listener);
if (completionModel.items.length === 0) {
fallback();
return;
}
const index = this._memory.select(this._editor.getModel(), this._editor.getPosition(), completionModel.items);
const item = completionModel.items[index];
if (!makesTextEdit(item)) {
fallback();
return;
}
this._editor.pushUndoStop();
this._onDidSelectItem({ index, item, model: completionModel }, true, false);
}, undefined, listener);
});
this._model.trigger({ auto: false, shy: true });
this._editor.revealLine(positionNow.lineNumber, ScrollType.Smooth);
this._editor.focus();
}
acceptSelectedSuggestion(keepAlternativeSuggestions?: boolean): void {
if (this._widget) {
const item = this._widget.getFocusedItem();
this._onDidSelectItem(item, keepAlternativeSuggestions, true);
}
}
acceptNextSuggestion() {
this._alternatives.next();
}
acceptPrevSuggestion() {
this._alternatives.prev();
}
cancelSuggestWidget(): void {
if (this._widget) {
this._model.cancel();
this._widget.hideWidget();
}
}
selectNextSuggestion(): void {
if (this._widget) {
this._widget.selectNext();
}
}
selectNextPageSuggestion(): void {
if (this._widget) {
this._widget.selectNextPage();
}
}
selectLastSuggestion(): void {
if (this._widget) {
this._widget.selectLast();
}
}
selectPrevSuggestion(): void {
if (this._widget) {
this._widget.selectPrevious();
}
}
selectPrevPageSuggestion(): void {
if (this._widget) {
this._widget.selectPreviousPage();
}
}
selectFirstSuggestion(): void {
if (this._widget) {
this._widget.selectFirst();
}
}
toggleSuggestionDetails(): void {
if (this._widget) {
this._widget.toggleDetails();
}
}
toggleSuggestionFocus(): void {
if (this._widget) {
this._widget.toggleDetailsFocus();
}
}
}
export class TriggerSuggestAction extends EditorAction {
static readonly id = 'editor.action.triggerSuggest';
constructor() {
super({
id: TriggerSuggestAction.id,
label: nls.localize('suggest.trigger.label', "Trigger Suggest"),
alias: 'Trigger Suggest',
precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCompletionItemProvider),
kbOpts: {
kbExpr: EditorContextKeys.textInputFocus,
primary: KeyMod.CtrlCmd | KeyCode.Space,
mac: { primary: KeyMod.WinCtrl | KeyCode.Space },
weight: KeybindingWeight.EditorContrib
}
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
const controller = SuggestController.get(editor);
if (!controller) {
return;
}
controller.triggerSuggest();
}
}
registerEditorContribution(SuggestController);
registerEditorAction(TriggerSuggestAction);
const weight = KeybindingWeight.EditorContrib + 90;
const SuggestCommand = EditorCommand.bindToContribution<SuggestController>(SuggestController.get);
registerEditorCommand(new SuggestCommand({
id: 'acceptSelectedSuggestion',
precondition: SuggestContext.Visible,
handler: x => x.acceptSelectedSuggestion(true),
kbOpts: {
weight: weight,
kbExpr: EditorContextKeys.textInputFocus,
primary: KeyCode.Tab
}
}));
registerEditorCommand(new SuggestCommand({
id: 'acceptSelectedSuggestionOnEnter',
precondition: SuggestContext.Visible,
handler: x => x.acceptSelectedSuggestion(false),
kbOpts: {
weight: weight,
kbExpr: ContextKeyExpr.and(EditorContextKeys.textInputFocus, SuggestContext.AcceptSuggestionsOnEnter, SuggestContext.MakesTextEdit),
primary: KeyCode.Enter
}
}));
registerEditorCommand(new SuggestCommand({
id: 'hideSuggestWidget',
precondition: SuggestContext.Visible,
handler: x => x.cancelSuggestWidget(),
kbOpts: {
weight: weight,
kbExpr: EditorContextKeys.textInputFocus,
primary: KeyCode.Escape,
secondary: [KeyMod.Shift | KeyCode.Escape]
}
}));
registerEditorCommand(new SuggestCommand({
id: 'selectNextSuggestion',
precondition: ContextKeyExpr.and(SuggestContext.Visible, SuggestContext.MultipleSuggestions),
handler: c => c.selectNextSuggestion(),
kbOpts: {
weight: weight,
kbExpr: EditorContextKeys.textInputFocus,
primary: KeyCode.DownArrow,
secondary: [KeyMod.CtrlCmd | KeyCode.DownArrow],
mac: { primary: KeyCode.DownArrow, secondary: [KeyMod.CtrlCmd | KeyCode.DownArrow, KeyMod.WinCtrl | KeyCode.KEY_N] }
}
}));
registerEditorCommand(new SuggestCommand({
id: 'selectNextPageSuggestion',
precondition: ContextKeyExpr.and(SuggestContext.Visible, SuggestContext.MultipleSuggestions),
handler: c => c.selectNextPageSuggestion(),
kbOpts: {
weight: weight,
kbExpr: EditorContextKeys.textInputFocus,
primary: KeyCode.PageDown,
secondary: [KeyMod.CtrlCmd | KeyCode.PageDown]
}
}));
registerEditorCommand(new SuggestCommand({
id: 'selectLastSuggestion',
precondition: ContextKeyExpr.and(SuggestContext.Visible, SuggestContext.MultipleSuggestions),
handler: c => c.selectLastSuggestion()
}));
registerEditorCommand(new SuggestCommand({
id: 'selectPrevSuggestion',
precondition: ContextKeyExpr.and(SuggestContext.Visible, SuggestContext.MultipleSuggestions),
handler: c => c.selectPrevSuggestion(),
kbOpts: {
weight: weight,
kbExpr: EditorContextKeys.textInputFocus,
primary: KeyCode.UpArrow,
secondary: [KeyMod.CtrlCmd | KeyCode.UpArrow],
mac: { primary: KeyCode.UpArrow, secondary: [KeyMod.CtrlCmd | KeyCode.UpArrow, KeyMod.WinCtrl | KeyCode.KEY_P] }
}
}));
registerEditorCommand(new SuggestCommand({
id: 'selectPrevPageSuggestion',
precondition: ContextKeyExpr.and(SuggestContext.Visible, SuggestContext.MultipleSuggestions),
handler: c => c.selectPrevPageSuggestion(),
kbOpts: {
weight: weight,
kbExpr: EditorContextKeys.textInputFocus,
primary: KeyCode.PageUp,
secondary: [KeyMod.CtrlCmd | KeyCode.PageUp]
}
}));
registerEditorCommand(new SuggestCommand({
id: 'selectFirstSuggestion',
precondition: ContextKeyExpr.and(SuggestContext.Visible, SuggestContext.MultipleSuggestions),
handler: c => c.selectFirstSuggestion()
}));
registerEditorCommand(new SuggestCommand({
id: 'toggleSuggestionDetails',
precondition: SuggestContext.Visible,
handler: x => x.toggleSuggestionDetails(),
kbOpts: {
weight: weight,
kbExpr: EditorContextKeys.textInputFocus,
primary: KeyMod.CtrlCmd | KeyCode.Space,
mac: { primary: KeyMod.WinCtrl | KeyCode.Space }
}
}));
registerEditorCommand(new SuggestCommand({
id: 'toggleSuggestionFocus',
precondition: SuggestContext.Visible,
handler: x => x.toggleSuggestionFocus(),
kbOpts: {
weight: weight,
kbExpr: EditorContextKeys.textInputFocus,
primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.Space,
mac: { primary: KeyMod.WinCtrl | KeyMod.Alt | KeyCode.Space }
}
}));
//#region tab completions
registerEditorCommand(new SuggestCommand({
id: 'insertBestCompletion',
precondition: ContextKeyExpr.and(
ContextKeyExpr.equals('config.editor.tabCompletion', 'on'),
WordContextKey.AtEnd,
SuggestContext.Visible.toNegated(),
SuggestAlternatives.OtherSuggestions.toNegated(),
SnippetController2.InSnippetMode.toNegated()
),
handler: x => x.triggerSuggestAndAcceptBest('\t'),//todo@joh fallback/default configurable?
kbOpts: {
weight,
primary: KeyCode.Tab
}
}));
registerEditorCommand(new SuggestCommand({
id: 'insertNextSuggestion',
precondition: ContextKeyExpr.and(
ContextKeyExpr.equals('config.editor.tabCompletion', 'on'),
SuggestAlternatives.OtherSuggestions,
SuggestContext.Visible.toNegated(),
SnippetController2.InSnippetMode.toNegated()
),
handler: x => x.acceptNextSuggestion(),
kbOpts: {
weight: weight,
kbExpr: EditorContextKeys.textInputFocus,
primary: KeyCode.Tab
}
}));
registerEditorCommand(new SuggestCommand({
id: 'insertPrevSuggestion',
precondition: ContextKeyExpr.and(
ContextKeyExpr.equals('config.editor.tabCompletion', 'on'),
SuggestAlternatives.OtherSuggestions,
SuggestContext.Visible.toNegated(),
SnippetController2.InSnippetMode.toNegated()
),
handler: x => x.acceptPrevSuggestion(),
kbOpts: {
weight: weight,
kbExpr: EditorContextKeys.textInputFocus,
primary: KeyMod.Shift | KeyCode.Tab
}
}));
| src/vs/editor/contrib/suggest/suggestController.ts | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.00017785889212973416,
0.00017338426550850272,
0.0001672928046900779,
0.00017386638501193374,
0.0000024039659365371335
] |
{
"id": 5,
"code_window": [
"\tconst packageJsonFilter = filter('package.json', { restore: true });\n",
"\n",
"\treturn remote('', options)\n",
"\t\t.on('error', function (err) {\n",
"\t\t\tconsole.log('Error downloading extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
"\t\t\tconsole.error(err);\n",
"\t\t})\n",
"\t\t.on('end', function () {\n",
"\t\t\tconsole.log('Downloaded extension:', util.colors.yellow(extensionName + \"@\" + version));\n",
"\t\t})\n",
"\t\t.pipe(vzip.src())\n",
"\t\t.pipe(filter('extension/**'))\n",
"\t\t.pipe(rename(p => p.dirname = p.dirname.replace(/^extension\\/?/, '')))\n",
"\t\t.pipe(packageJsonFilter)\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "build/lib/extensions.ts",
"type": "replace",
"edit_start_line_idx": 199
} | // ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS:
[{
"name": "textmate/ini.tmbundle",
"version": "0.0.0",
"license": "TextMate Bundle License",
"repositoryURL": "https://github.com/textmate/ini.tmbundle",
"licenseDetail": [
"Copyright (c) textmate-ini.tmbundle project authors",
"",
"If not otherwise specified (see below), files in this folder fall under the following license: ",
"",
"Permission to copy, use, modify, sell and distribute this",
"software is granted. This software is provided \"as is\" without",
"express or implied warranty, and with no claim as to its",
"suitability for any purpose.",
"",
"An exception is made for files in readable text which contain their own license information, ",
"or files where an accompanying file exists (in the same directory) with a \"-license\" suffix added ",
"to the base-name name of the original file, and an extension of txt, html, or similar. For example ",
"\"tidy\" is accompanied by \"tidy-license.txt\"."
]
}]
| extensions/ini/OSSREADME.json | 0 | https://github.com/microsoft/vscode/commit/13436602b10aa4fe7adba3982bd06c13135caca1 | [
0.00017300635227002203,
0.00017117545939981937,
0.00016892507846932858,
0.00017159493290819228,
0.0000016923692101045162
] |
{
"id": 0,
"code_window": [
"import { Plugin, TransformResult } from 'rollup'\n",
"import MagicString from 'magic-string'\n",
"\n",
"const filter = /\\.(j|t)sx?$/\n",
"\n",
"export const createReplacePlugin = (\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/node/build/buildPluginReplace.ts",
"type": "replace",
"edit_start_line_idx": 3
} | import path from 'path'
import fs from 'fs-extra'
import chalk from 'chalk'
import { Ora } from 'ora'
import { resolveFrom } from '../utils'
import { rollup as Rollup, RollupOutput, ExternalOption, Plugin } from 'rollup'
import { createResolver, supportedExts, InternalResolver } from '../resolver'
import { createBuildResolvePlugin } from './buildPluginResolve'
import { createBuildHtmlPlugin } from './buildPluginHtml'
import { createBuildCssPlugin } from './buildPluginCss'
import { createBuildAssetPlugin } from './buildPluginAsset'
import { createEsbuildPlugin } from './buildPluginEsbuild'
import { createReplacePlugin } from './buildPluginReplace'
import { stopService } from '../esbuildService'
import { BuildConfig } from '../config'
import { createBuildJsTransformPlugin } from '../transform'
import hash_sum from 'hash-sum'
export interface BuildResult {
html: string
assets: RollupOutput['output']
}
const enum WriteType {
JS,
CSS,
ASSET,
HTML,
SOURCE_MAP
}
const writeColors = {
[WriteType.JS]: chalk.cyan,
[WriteType.CSS]: chalk.magenta,
[WriteType.ASSET]: chalk.green,
[WriteType.HTML]: chalk.blue,
[WriteType.SOURCE_MAP]: chalk.gray
}
/**
* Named exports detection logic from Snowpack
* MIT License
* https://github.com/pikapkg/snowpack/blob/master/LICENSE
*/
const PACKAGES_TO_AUTO_DETECT_EXPORTS = [
path.join('react', 'index.js'),
path.join('react-dom', 'index.js'),
'react-is',
'prop-types',
'scheduler',
'rxjs',
'exenv',
'body-scroll-lock'
]
function detectExports(root: string, id: string): string[] | undefined {
try {
const fileLoc = resolveFrom(root, id)
if (fs.existsSync(fileLoc)) {
return Object.keys(require(fileLoc)).filter((e) => e[0] !== '_')
}
} catch (err) {
// ignore
}
}
/**
* Creates non-application specific plugins that are shared between the main
* app and the dependencies. This is used by the `optimize` command to
* pre-bundle dependencies.
*/
export async function createBaseRollupPlugins(
root: string,
resolver: InternalResolver,
options: BuildConfig
): Promise<Plugin[]> {
const { rollupInputOptions = {}, transforms = [] } = options
const knownNamedExports: Record<string, string[]> = {
...options.rollupPluginCommonJSNamedExports
}
for (const id of PACKAGES_TO_AUTO_DETECT_EXPORTS) {
knownNamedExports[id] =
knownNamedExports[id] || detectExports(root, id) || []
}
return [
// user plugins
...(rollupInputOptions.plugins || []),
// vite:resolve
createBuildResolvePlugin(root, resolver),
// vite:esbuild
await createEsbuildPlugin(options.minify === 'esbuild', options.jsx),
// vue
require('rollup-plugin-vue')({
...options.rollupPluginVueOptions,
transformAssetUrls: {
includeAbsolute: true
},
preprocessStyles: true,
preprocessCustomRequire: (id: string) => require(resolveFrom(root, id)),
compilerOptions: options.vueCompilerOptions,
cssModulesOptions: {
generateScopedName: (local: string, filename: string) =>
`${local}_${hash_sum(filename)}`
}
}),
require('@rollup/plugin-json')({
preferConst: true,
indent: ' ',
compact: false,
namedExports: true
}),
// user transforms
...(transforms.length ? [createBuildJsTransformPlugin(transforms)] : []),
require('@rollup/plugin-node-resolve')({
rootDir: root,
extensions: supportedExts,
preferBuiltins: false
}),
require('@rollup/plugin-commonjs')({
extensions: ['.js', '.cjs'],
namedExports: knownNamedExports
})
].filter(Boolean)
}
/**
* Bundles the app for production.
* Returns a Promise containing the build result.
*/
export async function build(options: BuildConfig = {}): Promise<BuildResult> {
if (options.ssr) {
return ssrBuild({
...options,
ssr: false // since ssrBuild calls build, this avoids an infinite loop.
})
}
const isTest = process.env.NODE_ENV === 'test'
process.env.NODE_ENV = 'production'
const start = Date.now()
const {
root = process.cwd(),
base = '/',
outDir = path.resolve(root, 'dist'),
assetsDir = '_assets',
assetsInlineLimit = 4096,
cssCodeSplit = true,
alias = {},
transforms = [],
resolvers = [],
rollupInputOptions = {},
rollupOutputOptions = {},
emitIndex = true,
emitAssets = true,
write = true,
minify = true,
silent = false,
sourcemap = false,
shouldPreload = null,
env = {}
} = options
let spinner: Ora | undefined
const msg = 'Building for production...'
if (!silent) {
if (process.env.DEBUG || isTest) {
console.log(msg)
} else {
spinner = require('ora')(msg + '\n').start()
}
}
const indexPath = path.resolve(root, 'index.html')
const publicBasePath = base.replace(/([^/])$/, '$1/') // ensure ending slash
const resolvedAssetsPath = path.join(outDir, assetsDir)
const resolver = createResolver(root, resolvers, alias)
const { htmlPlugin, renderIndex } = await createBuildHtmlPlugin(
root,
indexPath,
publicBasePath,
assetsDir,
assetsInlineLimit,
resolver,
shouldPreload
)
const basePlugins = await createBaseRollupPlugins(root, resolver, options)
env.NODE_ENV = 'production'
const envReplacements = Object.keys(env).reduce((replacements, key) => {
replacements[`process.env.${key}`] = JSON.stringify(env[key])
return replacements
}, {} as Record<string, string>)
// lazy require rollup so that we don't load it when only using the dev server
// importing it just for the types
const rollup = require('rollup').rollup as typeof Rollup
const bundle = await rollup({
input: path.resolve(root, 'index.html'),
preserveEntrySignatures: false,
treeshake: { moduleSideEffects: 'no-external' },
onwarn(warning, warn) {
if (warning.code !== 'CIRCULAR_DEPENDENCY') {
warn(warning)
}
},
...rollupInputOptions,
plugins: [
...basePlugins,
// vite:html
htmlPlugin,
// we use a custom replacement plugin because @rollup/plugin-replace
// performs replacements twice, once at transform and once at renderChunk
// - which makes it impossible to exclude Vue templates from it since
// Vue templates are compiled into js and included in chunks.
createReplacePlugin(
{
...envReplacements,
'process.env.': `({}).`,
__DEV__: 'false',
__BASE__: JSON.stringify(publicBasePath)
},
sourcemap
),
// vite:css
createBuildCssPlugin(
root,
publicBasePath,
assetsDir,
minify,
assetsInlineLimit,
cssCodeSplit,
transforms
),
// vite:asset
createBuildAssetPlugin(
root,
publicBasePath,
assetsDir,
assetsInlineLimit
),
// minify with terser
// this is the default which has better compression, but slow
// the user can opt-in to use esbuild which is much faster but results
// in ~8-10% larger file size.
minify && minify !== 'esbuild'
? require('rollup-plugin-terser').terser()
: undefined
]
})
const { output } = await bundle.generate({
format: 'es',
sourcemap,
entryFileNames: `[name].[hash].js`,
chunkFileNames: `[name].[hash].js`,
...rollupOutputOptions
})
spinner && spinner.stop()
const cssFileName = output.find(
(a) => a.type === 'asset' && a.fileName.endsWith('.css')
)!.fileName
const indexHtml = emitIndex ? renderIndex(output, cssFileName) : ''
if (write) {
const cwd = process.cwd()
const writeFile = async (
filepath: string,
content: string | Uint8Array,
type: WriteType
) => {
await fs.ensureDir(path.dirname(filepath))
await fs.writeFile(filepath, content)
if (!silent) {
console.log(
`${chalk.gray(`[write]`)} ${writeColors[type](
path.relative(cwd, filepath)
)} ${(content.length / 1024).toFixed(2)}kb, brotli: ${(
require('brotli-size').sync(content) / 1024
).toFixed(2)}kb`
)
}
}
await fs.remove(outDir)
await fs.ensureDir(outDir)
// write js chunks and assets
for (const chunk of output) {
if (chunk.type === 'chunk') {
// write chunk
const filepath = path.join(resolvedAssetsPath, chunk.fileName)
let code = chunk.code
if (chunk.map) {
code += `\n//# sourceMappingURL=${path.basename(filepath)}.map`
}
await writeFile(filepath, code, WriteType.JS)
if (chunk.map) {
await writeFile(
filepath + '.map',
chunk.map.toString(),
WriteType.SOURCE_MAP
)
}
} else if (emitAssets) {
// write asset
const filepath = path.join(resolvedAssetsPath, chunk.fileName)
await writeFile(
filepath,
chunk.source,
chunk.fileName.endsWith('.css') ? WriteType.CSS : WriteType.ASSET
)
}
}
// write html
if (indexHtml && emitIndex) {
await writeFile(
path.join(outDir, 'index.html'),
indexHtml,
WriteType.HTML
)
}
// copy over /public if it exists
if (emitAssets) {
const publicDir = path.resolve(root, 'public')
if (fs.existsSync(publicDir)) {
await fs.copy(publicDir, path.resolve(outDir, 'public'))
}
}
}
if (!silent) {
console.log(
`Build completed in ${((Date.now() - start) / 1000).toFixed(2)}s.\n`
)
}
// stop the esbuild service after each build
stopService()
return {
assets: output,
html: indexHtml
}
}
/**
* Bundles the app in SSR mode.
* - All Vue dependencies are automatically externalized
* - Imports to dependencies are compiled into require() calls
* - Templates are compiled with SSR specific optimizations.
*/
export async function ssrBuild(
options: BuildConfig = {}
): Promise<BuildResult> {
const {
rollupInputOptions,
rollupOutputOptions,
rollupPluginVueOptions
} = options
return build({
outDir: path.resolve(options.root || process.cwd(), 'dist-ssr'),
assetsDir: '.',
...options,
rollupPluginVueOptions: {
...rollupPluginVueOptions,
target: 'node'
},
rollupInputOptions: {
...rollupInputOptions,
external: resolveExternal(
rollupInputOptions && rollupInputOptions.external
)
},
rollupOutputOptions: {
...rollupOutputOptions,
format: 'cjs',
exports: 'named',
entryFileNames: '[name].js'
},
emitIndex: false,
emitAssets: false,
cssCodeSplit: false,
minify: false
})
}
function resolveExternal(
userExternal: ExternalOption | undefined
): ExternalOption {
const required = ['vue', /^@vue\//]
if (!userExternal) {
return required
}
if (Array.isArray(userExternal)) {
return [...required, ...userExternal]
} else if (typeof userExternal === 'function') {
return (src, importer, isResolved) => {
if (src === 'vue' || /^@vue\//.test(src)) {
return true
}
return userExternal(src, importer, isResolved)
}
} else {
return [...required, userExternal]
}
}
| src/node/build/index.ts | 1 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.9983383417129517,
0.047877103090286255,
0.00016383733600378036,
0.00018505961634218693,
0.21248185634613037
] |
{
"id": 0,
"code_window": [
"import { Plugin, TransformResult } from 'rollup'\n",
"import MagicString from 'magic-string'\n",
"\n",
"const filter = /\\.(j|t)sx?$/\n",
"\n",
"export const createReplacePlugin = (\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/node/build/buildPluginReplace.ts",
"type": "replace",
"edit_start_line_idx": 3
} | import { Plugin, RollupOutput, OutputChunk } from 'rollup'
import path from 'path'
import fs from 'fs-extra'
import { isExternalUrl, cleanUrl, isStaticAsset } from '../utils/pathUtils'
import { resolveAsset } from './buildPluginAsset'
import {
parse,
transform,
NodeTransform,
NodeTypes,
TextNode,
AttributeNode
} from '@vue/compiler-dom'
import MagicString from 'magic-string'
import { InternalResolver } from '../resolver'
export const createBuildHtmlPlugin = async (
root: string,
indexPath: string | null,
publicBasePath: string,
assetsDir: string,
inlineLimit: number,
resolver: InternalResolver,
shouldPreload: ((chunk: OutputChunk) => boolean) | null
) => {
if (!indexPath || !fs.existsSync(indexPath)) {
return {
renderIndex: (...args: any[]) => '',
htmlPlugin: null
}
}
const rawHtml = await fs.readFile(indexPath, 'utf-8')
let { html: processedHtml, js } = await compileHtml(
root,
rawHtml,
publicBasePath,
assetsDir,
inlineLimit,
resolver
)
const htmlPlugin: Plugin = {
name: 'vite:html',
async load(id) {
if (id === indexPath) {
return js
}
}
}
const injectCSS = (html: string, filename: string) => {
const tag = `<link rel="stylesheet" href="${publicBasePath}${path.posix.join(
assetsDir,
filename
)}">`
if (/<\/head>/.test(html)) {
return html.replace(/<\/head>/, `${tag}\n</head>`)
} else {
return tag + '\n' + html
}
}
const injectScript = (html: string, filename: string) => {
filename = isExternalUrl(filename)
? filename
: `${publicBasePath}${path.posix.join(assetsDir, filename)}`
const tag = `<script type="module" src="${filename}"></script>`
if (/<\/body>/.test(html)) {
return html.replace(/<\/body>/, `${tag}\n</body>`)
} else {
return html + '\n' + tag
}
}
const injectPreload = (html: string, filename: string) => {
filename = isExternalUrl(filename)
? filename
: `${publicBasePath}${path.posix.join(assetsDir, filename)}`
const tag = `<link rel="modulepreload" href="${filename}" />`
if (/<\/head>/.test(html)) {
return html.replace(/<\/head>/, `${tag}\n</head>`)
} else {
return tag + '\n' + html
}
}
const renderIndex = (
bundleOutput: RollupOutput['output'],
cssFileName: string
) => {
// inject css link
processedHtml = injectCSS(processedHtml, cssFileName)
// inject js entry chunks
for (const chunk of bundleOutput) {
if (chunk.type === 'chunk') {
if (chunk.isEntry) {
processedHtml = injectScript(processedHtml, chunk.fileName)
} else if (shouldPreload && shouldPreload(chunk)) {
processedHtml = injectPreload(processedHtml, chunk.fileName)
}
}
}
return processedHtml
}
return {
renderIndex,
htmlPlugin
}
}
// this extends the config in @vue/compiler-sfc with <link href>
const assetAttrsConfig: Record<string, string[]> = {
link: ['href'],
video: ['src', 'poster'],
source: ['src'],
img: ['src'],
image: ['xlink:href', 'href'],
use: ['xlink:href', 'href']
}
// compile index.html to a JS module, importing referenced assets
// and scripts
const compileHtml = async (
root: string,
html: string,
publicBasePath: string,
assetsDir: string,
inlineLimit: number,
resolver: InternalResolver
) => {
// @vue/compiler-core doesn't like lowercase doctypes
html = html.replace(/<!doctype\s/i, '<!DOCTYPE ')
const ast = parse(html)
let js = ''
const s = new MagicString(html)
const assetUrls: AttributeNode[] = []
const viteHtmlTransfrom: NodeTransform = (node) => {
if (node.type === NodeTypes.ELEMENT) {
if (node.tag === 'script') {
let shouldRemove = true
const srcAttr = node.props.find(
(p) => p.type === NodeTypes.ATTRIBUTE && p.name === 'src'
) as AttributeNode
if (srcAttr && srcAttr.value) {
if (!isExternalUrl(srcAttr.value.content)) {
// <script type="module" src="..."/>
// add it as an import
js += `\nimport ${JSON.stringify(srcAttr.value.content)}`
} else {
shouldRemove = false
}
} else if (node.children.length) {
// <script type="module">...</script>
// add its content
// TODO: if there are multiple inline module scripts on the page,
// they should technically be turned into separate modules, but
// it's hard to imagine any reason for anyone to do that.
js += `\n` + (node.children[0] as TextNode).content.trim() + `\n`
}
if (shouldRemove) {
// remove the script tag from the html. we are going to inject new
// ones in the end.
s.remove(node.loc.start.offset, node.loc.end.offset)
}
}
// For asset references in index.html, also generate an import
// statement for each - this will be handled by the asset plugin
const assetAttrs = assetAttrsConfig[node.tag]
if (assetAttrs) {
for (const p of node.props) {
if (
p.type === NodeTypes.ATTRIBUTE &&
p.value &&
assetAttrs.includes(p.name) &&
!isExternalUrl(p.value.content)
) {
const url = cleanUrl(p.value.content)
js += `\nimport ${JSON.stringify(url)}`
if (isStaticAsset(url)) {
assetUrls.push(p)
}
}
}
}
}
}
transform(ast, {
nodeTransforms: [viteHtmlTransfrom]
})
// for each encountered asset url, rewrite original html so that it
// references the post-build location.
for (const attr of assetUrls) {
const value = attr.value!
const { url } = await resolveAsset(
resolver.requestToFile(value.content),
root,
publicBasePath,
assetsDir,
inlineLimit
)
s.overwrite(value.loc.start.offset, value.loc.end.offset, url)
}
return {
html: s.toString(),
js
}
}
| src/node/build/buildPluginHtml.ts | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.0006882176385261118,
0.00020789970585610718,
0.0001641441194806248,
0.0001704999158391729,
0.00011168629134772345
] |
{
"id": 0,
"code_window": [
"import { Plugin, TransformResult } from 'rollup'\n",
"import MagicString from 'magic-string'\n",
"\n",
"const filter = /\\.(j|t)sx?$/\n",
"\n",
"export const createReplacePlugin = (\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/node/build/buildPluginReplace.ts",
"type": "replace",
"edit_start_line_idx": 3
} | import { ServerPlugin } from '.'
import path from 'path'
import LRUCache from 'lru-cache'
import MagicString from 'magic-string'
import {
init as initLexer,
parse as parseImports,
ImportSpecifier
} from 'es-module-lexer'
import { InternalResolver, resolveBareModule, jsSrcRE } from '../resolver'
import {
debugHmr,
importerMap,
importeeMap,
ensureMapEntry,
rewriteFileWithHMR,
hmrClientPublicPath,
hmrClientId,
hmrDirtyFilesMap
} from './serverPluginHmr'
import {
readBody,
cleanUrl,
isExternalUrl,
resolveRelativeRequest
} from '../utils'
import chalk from 'chalk'
const debug = require('debug')('vite:rewrite')
const rewriteCache = new LRUCache({ max: 1024 })
// Plugin for rewriting served js.
// - Rewrites named module imports to `/@modules/:id` requests, e.g.
// "vue" => "/@modules/vue"
// - Rewrites HMR `hot.accept` calls to inject the file's own path. e.g.
// `hot.accept('./dep.js', cb)` -> `hot.accept('/importer.js', './dep.js', cb)`
// - Also tracks importer/importee relationship graph during the rewrite.
// The graph is used by the HMR plugin to perform analysis on file change.
export const moduleRewritePlugin: ServerPlugin = ({
root,
app,
watcher,
resolver
}) => {
app.use(async (ctx, next) => {
await next()
if (ctx.status === 304) {
return
}
// we are doing the js rewrite after all other middlewares have finished;
// this allows us to post-process javascript produced by user middlewares
// regardless of the extension of the original files.
if (
ctx.body &&
ctx.response.is('js') &&
!ctx.url.endsWith('.map') &&
// skip internal client
!ctx.path.startsWith(hmrClientPublicPath) &&
// only need to rewrite for <script> part in vue files
!((ctx.path.endsWith('.vue') || ctx.vue) && ctx.query.type != null)
) {
const content = await readBody(ctx.body)
if (!ctx.query.t && rewriteCache.has(content)) {
debug(`(cached) ${ctx.url}`)
ctx.body = rewriteCache.get(content)
} else {
await initLexer
ctx.body = rewriteImports(
root,
content!,
ctx.path,
resolver,
ctx.query.t
)
rewriteCache.set(content, ctx.body)
}
} else {
debug(`(skipped) ${ctx.url}`)
}
})
// bust module rewrite cache on file change
watcher.on('change', (file) => {
const publicPath = resolver.fileToRequest(file)
debug(`${publicPath}: cache busted`)
rewriteCache.del(publicPath)
})
}
export function rewriteImports(
root: string,
source: string,
importer: string,
resolver: InternalResolver,
timestamp?: string
) {
if (typeof source !== 'string') {
source = String(source)
}
try {
let imports: ImportSpecifier[] = []
try {
imports = parseImports(source)[0]
} catch (e) {
console.error(
chalk.yellow(
`[vite] failed to parse ${chalk.cyan(
importer
)} for import rewrite.\nIf you are using ` +
`JSX, make sure to named the file with the .jsx extension.`
)
)
}
if (imports.length) {
debug(`${importer}: rewriting`)
const s = new MagicString(source)
let hasReplaced = false
const prevImportees = importeeMap.get(importer)
const currentImportees = new Set<string>()
importeeMap.set(importer, currentImportees)
for (let i = 0; i < imports.length; i++) {
const { s: start, e: end, ss, se, d: dynamicIndex } = imports[i]
let id = source.substring(start, end)
let hasLiteralDynamicId = false
if (dynamicIndex >= 0) {
const literalIdMatch = id.match(/^(?:'([^']+)'|"([^"]+)")$/)
if (literalIdMatch) {
hasLiteralDynamicId = true
id = literalIdMatch[1] || literalIdMatch[2]
}
}
if (dynamicIndex === -1 || hasLiteralDynamicId) {
// do not rewrite external imports
if (isExternalUrl(id)) {
continue
}
let resolved
if (id === hmrClientId) {
resolved = hmrClientPublicPath
if (
/\bhot\b/.test(source.substring(ss, se)) &&
!/.vue$|.vue\?type=/.test(importer)
) {
// the user explicit imports the HMR API in a js file
// making the module hot.
rewriteFileWithHMR(root, source, importer, resolver, s)
// we rewrite the hot.accept call
hasReplaced = true
}
} else {
resolved = resolveImport(root, importer, id, resolver, timestamp)
}
if (resolved !== id) {
debug(` "${id}" --> "${resolved}"`)
s.overwrite(
start,
end,
hasLiteralDynamicId ? `'${resolved}'` : resolved
)
hasReplaced = true
}
// save the import chain for hmr analysis
const importee = cleanUrl(resolved)
if (
importee !== importer &&
// no need to track hmr client or module dependencies
importee !== hmrClientPublicPath
) {
currentImportees.add(importee)
debugHmr(` ${importer} imports ${importee}`)
ensureMapEntry(importerMap, importee).add(importer)
}
} else {
console.log(`[vite] ignored dynamic import(${id})`)
}
}
// since the importees may have changed due to edits,
// check if we need to remove this importer from certain importees
if (prevImportees) {
prevImportees.forEach((importee) => {
if (!currentImportees.has(importee)) {
const importers = importerMap.get(importee)
if (importers) {
importers.delete(importer)
}
}
})
}
if (!hasReplaced) {
debug(` no imports rewritten.`)
}
return hasReplaced ? s.toString() : source
} else {
debug(`${importer}: no imports found.`)
}
return source
} catch (e) {
console.error(
`[vite] Error: module imports rewrite failed for ${importer}.\n`,
e
)
debug(source)
return source
}
}
const bareImportRE = /^[^\/\.]/
export const resolveImport = (
root: string,
importer: string,
id: string,
resolver: InternalResolver,
timestamp?: string
): string => {
id = resolver.alias(id) || id
if (bareImportRE.test(id)) {
// directly resolve bare module names to its entry path so that relative
// imports from it (including source map urls) can work correctly
let resolvedModulePath = resolveBareModule(root, id, importer)
const ext = path.extname(resolvedModulePath)
if (ext && !jsSrcRE.test(ext)) {
resolvedModulePath += `?import`
}
return `/@modules/${resolvedModulePath}`
} else {
let { pathname, query } = resolveRelativeRequest(importer, id)
// append an extension to extension-less imports
if (!path.extname(pathname)) {
const file = resolver.requestToFile(pathname)
const indexMatch = file.match(/\/index\.\w+$/)
if (indexMatch) {
pathname = pathname.replace(/\/(index)?$/, '') + indexMatch[0]
} else {
pathname += path.extname(file)
}
}
// mark non-src imports
const ext = path.extname(pathname)
if (ext && !jsSrcRE.test(pathname)) {
query += `${query ? `&` : `?`}import`
}
// force re-fetch dirty imports by appending timestamp
if (timestamp) {
const dirtyFiles = hmrDirtyFilesMap.get(timestamp)
// only force re-fetch if this is a marked dirty file (in the import
// chain of the changed file) or a vue part request (made by a dirty
// vue main request)
if ((dirtyFiles && dirtyFiles.has(pathname)) || /\.vue\?type/.test(id)) {
query += `${query ? `&` : `?`}t=${timestamp}`
}
}
return pathname + query
}
}
| src/node/server/serverPluginModuleRewrite.ts | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.0002995571994688362,
0.00017946319712791592,
0.00016277255781460553,
0.0001704965834505856,
0.0000315684374072589
] |
{
"id": 0,
"code_window": [
"import { Plugin, TransformResult } from 'rollup'\n",
"import MagicString from 'magic-string'\n",
"\n",
"const filter = /\\.(j|t)sx?$/\n",
"\n",
"export const createReplacePlugin = (\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "src/node/build/buildPluginReplace.ts",
"type": "replace",
"edit_start_line_idx": 3
} | <template>
<h2>Transforms</h2>
<div class="transform-scss">This should be cyan</div>
<div class="transform-js">{{ transformed }}</div>
</template>
<script>
import './testTransform.scss'
import { __TEST_TRANSFORM__ } from './testTransform.js'
export default {
data() {
return {
transformed: __TEST_TRANSFORM__
}
}
}
</script>
| playground/TestTransform.vue | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017262932669837028,
0.00017168500926345587,
0.00017074067727662623,
0.00017168500926345587,
9.443247108720243e-7
] |
{
"id": 1,
"code_window": [
"export const createReplacePlugin = (\n",
" replacements: Record<string, string>,\n",
" sourcemap: boolean\n",
"): Plugin => {\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" test: (id: string) => boolean,\n"
],
"file_path": "src/node/build/buildPluginReplace.ts",
"type": "add",
"edit_start_line_idx": 6
} | import fs from 'fs-extra'
import path from 'path'
import { createHash } from 'crypto'
import { ResolvedConfig } from './config'
import type Rollup from 'rollup'
import {
createResolver,
supportedExts,
resolveNodeModuleEntry
} from './resolver'
import { createBaseRollupPlugins } from './build'
import { resolveFrom, lookupFile } from './utils'
import { init, parse } from 'es-module-lexer'
import chalk from 'chalk'
import { Ora } from 'ora'
import { createBuildCssPlugin } from './build/buildPluginCss'
const KNOWN_IGNORE_LIST = new Set([
'tailwindcss',
'@tailwindcss/ui',
'@pika/react',
'@pika/react-dom'
])
export interface DepOptimizationOptions {
/**
* Only optimize explicitly listed dependencies.
*/
include?: string[]
/**
* Do not optimize these dependencies.
*/
exclude?: string[]
/**
* Explicitly allow these CommonJS deps to be bundled.
*/
commonJSWhitelist?: string[]
/**
* Automatically run `vite optimize` on server start?
* @default true
*/
auto?: boolean
}
export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`
export async function optimizeDeps(
config: ResolvedConfig & { force?: boolean },
asCommand = false
) {
const debug = require('debug')('vite:optimize')
const log = asCommand ? console.log : debug
const root = config.root || process.cwd()
// warn presence of web_modules
if (fs.existsSync(path.join(root, 'web_modules'))) {
console.warn(
chalk.yellow(
`[vite] vite 0.15 has built-in dependency pre-bundling and resolving ` +
`from web_modules is no longer supported.`
)
)
}
const pkgPath = lookupFile(root, [`package.json`], true /* pathOnly */)
if (!pkgPath) {
log(`package.json not found. Skipping.`)
return
}
const cacheDir = resolveOptimizedCacheDir(root, pkgPath)!
const hashPath = path.join(cacheDir, 'hash')
const depHash = getDepHash(root, config.__path)
if (!config.force) {
let prevhash
try {
prevhash = await fs.readFile(hashPath, 'utf-8')
} catch (e) {}
// hash is consistent, no need to re-bundle
if (prevhash === depHash) {
log('Hash is consistent. Skipping. Use --force to override.')
return
}
}
await fs.remove(cacheDir)
await fs.ensureDir(cacheDir)
const deps = Object.keys(require(pkgPath).dependencies || {})
if (!deps.length) {
await fs.writeFile(hashPath, depHash)
log(`No dependencies listed in package.json. Skipping.`)
return
}
const resolver = createResolver(root, config.resolvers, config.alias)
const { include, exclude, commonJSWhitelist } = config.optimizeDeps || {}
// Determine deps to optimize. The goal is to only pre-bundle deps that falls
// under one of the following categories:
// 1. Has imports to relative files (e.g. lodash-es, lit-html)
// 2. Has imports to bare modules that are not in the project's own deps
// (i.e. esm that imports its own dependencies, e.g. styled-components)
await init
const cjsDeps: string[] = []
const qualifiedDeps = deps.filter((id) => {
if (include && !include.includes(id)) {
debug(`skipping ${id} (not included)`)
return false
}
if (exclude && exclude.includes(id)) {
debug(`skipping ${id} (excluded)`)
return false
}
if (commonJSWhitelist && commonJSWhitelist.includes(id)) {
debug(`optimizing ${id} (commonJSWhitelist)`)
return true
}
if (KNOWN_IGNORE_LIST.has(id)) {
debug(`skipping ${id} (internal excluded)`)
return false
}
const pkgInfo = resolveNodeModuleEntry(root, id)
if (!pkgInfo) {
debug(`skipping ${id} (cannot resolve entry)`)
return false
}
const [entry, pkg] = pkgInfo
if (!supportedExts.includes(path.extname(entry))) {
debug(`skipping ${id} (entry is not js)`)
return false
}
const content = fs.readFileSync(resolveFrom(root, entry), 'utf-8')
const [imports, exports] = parse(content)
if (!exports.length && !/export\s+\*\s+from/.test(content)) {
if (!pkg.module) {
cjsDeps.push(id)
}
debug(`skipping ${id} (no exports, likely commonjs)`)
return false
}
for (const { s, e } of imports) {
let i = content.slice(s, e).trim()
i = resolver.alias(i) || i
if (i.startsWith('.')) {
debug(`optimizing ${id} (contains relative imports)`)
return true
}
if (!deps.includes(i)) {
debug(`optimizing ${id} (imports sub dependencies)`)
return true
}
}
debug(`skipping ${id} (single esm file, doesn't need optimization)`)
})
if (!qualifiedDeps.length) {
if (!cjsDeps.length) {
await fs.writeFile(hashPath, depHash)
log(`No listed dependency requires optimization. Skipping.`)
} else {
console.error(
chalk.yellow(
`[vite] The following dependencies seem to be CommonJS modules that\n` +
`do not provide ESM-friendly file formats:\n\n ` +
cjsDeps.map((dep) => chalk.magenta(dep)).join(`\n `) +
`\n` +
`\n- If you are not using them in browser code, you can move them\n` +
`to devDependencies or exclude them from this check by adding\n` +
`them to ${chalk.cyan(
`optimizeDeps.exclude`
)} in vue.config.js.\n` +
`\n- If you do intend to use them in the browser, you can try adding\n` +
`them to ${chalk.cyan(
`optimizeDeps.commonJSWhitelist`
)} in vue.config.js but they\n` +
`may fail to bundle or work properly. Consider choosing more modern\n` +
`alternatives that provide ES module build formts.`
)
)
}
return
}
if (!asCommand) {
// This is auto run on server start - let the user know that we are
// pre-optimizing deps
console.log(chalk.greenBright(`[vite] Optimizable dependencies detected.`))
}
let spinner: Ora | undefined
const msg = asCommand
? `Pre-bundling dependencies to speed up dev server page load...`
: `Pre-bundling them to speed up dev server page load...\n` +
`(this will be run only when your dependencies have changed)`
if (process.env.DEBUG || process.env.NODE_ENV === 'test') {
console.log(msg)
} else {
spinner = require('ora')(msg + '\n').start()
}
try {
// Non qualified deps are marked as externals, since they will be preserved
// and resolved from their original node_modules locations.
const preservedDeps = deps
.filter((id) => !qualifiedDeps.includes(id))
// make sure aliased deps are external
// https://github.com/vitejs/vite-plugin-react/issues/4
.map((id) => resolver.alias(id) || id)
const input = qualifiedDeps.reduce((entries, name) => {
entries[name] = name
return entries
}, {} as Record<string, string>)
const rollup = require('rollup') as typeof Rollup
const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]
const bundle = await rollup.rollup({
input,
external: preservedDeps,
treeshake: { moduleSideEffects: 'no-external' },
onwarn(warning, warn) {
if (!warningIgnoreList.includes(warning.code!)) {
warn(warning)
}
},
...config.rollupInputOptions,
plugins: [
...(await createBaseRollupPlugins(root, resolver, config)),
createBuildCssPlugin(root, '/', 'assets')
]
})
const { output } = await bundle.generate({
...config.rollupOutputOptions,
format: 'es',
exports: 'named',
entryFileNames: '[name]',
chunkFileNames: 'common/[name]-[hash].js'
})
spinner && spinner.stop()
const optimized = []
for (const chunk of output) {
if (chunk.type === 'chunk') {
const fileName = chunk.fileName
const filePath = path.join(cacheDir, fileName)
await fs.ensureDir(path.dirname(filePath))
await fs.writeFile(filePath, chunk.code)
if (!fileName.startsWith('common/')) {
optimized.push(fileName.replace(/\.js$/, ''))
}
}
}
console.log(
`Optimized modules:\n${optimized
.map((id) => chalk.yellowBright(id))
.join(`, `)}`
)
await fs.writeFile(hashPath, depHash)
} catch (e) {
spinner && spinner.stop()
if (asCommand) {
throw e
} else {
console.error(chalk.red(`[vite] Dep optimization failed with error:`))
console.error(e)
console.log()
console.log(
chalk.yellow(
`Tip: You can configure what deps to include/exclude for optimization\n` +
`using the \`optimizeDeps\` option in the Vite config file.`
)
)
}
}
}
const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']
let cachedHash: string | undefined
export function getDepHash(
root: string,
configPath: string | undefined
): string {
if (cachedHash) {
return cachedHash
}
let content = lookupFile(root, lockfileFormats) || ''
const pkg = JSON.parse(lookupFile(root, [`package.json`]) || '{}')
content += JSON.stringify(pkg.dependencies)
// also take config into account
if (configPath) {
content += fs.readFileSync(configPath, 'utf-8')
}
return createHash('sha1').update(content).digest('base64')
}
const cacheDirCache = new Map<string, string | null>()
export function resolveOptimizedCacheDir(
root: string,
pkgPath?: string
): string | null {
const cached = cacheDirCache.get(root)
if (cached !== undefined) return cached
pkgPath = pkgPath || lookupFile(root, [`package.json`], true /* pathOnly */)
if (!pkgPath) {
return null
}
const cacheDir = path.join(path.dirname(pkgPath), OPTIMIZE_CACHE_DIR)
cacheDirCache.set(root, cacheDir)
return cacheDir
}
| src/node/depOptimizer.ts | 1 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.010312207043170929,
0.0006013697711750865,
0.0001668472250457853,
0.0001713248493615538,
0.0017813483718782663
] |
{
"id": 1,
"code_window": [
"export const createReplacePlugin = (\n",
" replacements: Record<string, string>,\n",
" sourcemap: boolean\n",
"): Plugin => {\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" test: (id: string) => boolean,\n"
],
"file_path": "src/node/build/buildPluginReplace.ts",
"type": "add",
"edit_start_line_idx": 6
} | import { hot } from 'vite/hmr'
import './testHmrManualDep'
export const foo = 1
if (__DEV__) {
hot.accept(({ foo }) => {
console.log('(self-accepting)1.foo is now:', foo)
})
hot.accept(({ foo }) => {
console.log('(self-accepting)2.foo is now:', foo)
})
hot.dispose(() => {
console.log(`foo was: ${foo}`)
})
hot.accept('./testHmrManualDep.js', ({ foo }) => {
console.log('(single dep) foo is now:', foo)
})
hot.accept(['./testHmrManualDep.js'], (modules) => {
console.log('(multiple deps) foo is now:', modules[0].foo)
})
}
| playground/testHmrManual.js | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017382815713062882,
0.00017242554167751223,
0.00017093567294068635,
0.00017251282406505197,
0.0000011824631656054407
] |
{
"id": 1,
"code_window": [
"export const createReplacePlugin = (\n",
" replacements: Record<string, string>,\n",
" sourcemap: boolean\n",
"): Plugin => {\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" test: (id: string) => boolean,\n"
],
"file_path": "src/node/build/buildPluginReplace.ts",
"type": "add",
"edit_start_line_idx": 6
} | // These are injected by the server on the fly so that we invalidate the cache.
const __ENABLED__ = true
const __PROJECT_ROOT__ = '/'
const __SERVER_ID__ = 1
const __LOCKFILE_HASH__ = 'a'
// We use two separate caches:
// 1. The user files cache is based on the server start timestamp: i.e. it
// persists only for the session of a server process. It is reset every time
// the user restarts the server.
const USER_CACHE_NAME = `vite-cache-${__PROJECT_ROOT__}-${__SERVER_ID__}`
// 2. The deps cache is based on the project's lockfile. They are less likely
// to change, so they are only invalidated when the lockfile has changed.
const DEPS_CACHE_NAME = `vite-cache-${__PROJECT_ROOT__}-${__LOCKFILE_HASH__}`
const sw = (self as any) as ServiceWorkerGlobalScope
sw.addEventListener('install', () => {
// console.log('[vite:sw] install')
sw.skipWaiting()
})
sw.addEventListener('activate', (e) => {
// console.log('[vite:sw] activated')
sw.clients.claim()
// delete any non-matching caches
e.waitUntil(
(async () => {
const keys = await caches.keys()
for (const key of keys) {
if (key !== USER_CACHE_NAME && key !== DEPS_CACHE_NAME) {
await caches.delete(key)
}
}
})()
)
})
sw.addEventListener('message', async (e) => {
if (e.data.type === 'bust-cache') {
// console.log(`[vite:sw] busted cache for ${e.data.path}`)
;(await caches.open(USER_CACHE_NAME)).delete(e.data.path)
;(await caches.open(DEPS_CACHE_NAME)).delete(e.data.path)
// notify the client that cache has been busted
e.ports[0].postMessage({
busted: true
})
}
})
const depsRE = /^\/@modules\//
const hmrClientPath = `/vite/hmr`
const hmrRequestRE = /(&|\?)t=\d+/
sw.addEventListener('fetch', (e) => {
if (!__ENABLED__) {
return
}
const url = new URL(e.request.url)
// no need to cache hmr update requests
if (url.pathname !== hmrClientPath && !url.search.match(hmrRequestRE)) {
const cacheToUse = depsRE.test(url.pathname)
? DEPS_CACHE_NAME
: USER_CACHE_NAME
e.respondWith(tryCache(e.request, cacheToUse))
}
})
async function tryCache(req: Request, cacheName: string) {
const cache = await caches.open(cacheName)
const cached = await cache.match(req)
if (cached) {
// console.log(`[vite:sw] serving ${req.url} from cache`)
return cached
} else {
// console.log(`[vite:sw] fetching`, req)
const res = await fetch(req)
// console.log(`[vite:sw] got res:`, res)
if (!res || res.status !== 200 || res.type !== 'basic') {
// console.log(`not caching ${req.url}`)
return res
}
// console.log(`[vite:sw] caching ${req.url}`)
cache.put(req, res.clone())
return res
}
}
| src/sw/serviceWorker.ts | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00041500473162159324,
0.00020196229161228985,
0.00016975111793726683,
0.00017391287838108838,
0.00007573658513138071
] |
{
"id": 1,
"code_window": [
"export const createReplacePlugin = (\n",
" replacements: Record<string, string>,\n",
" sourcemap: boolean\n",
"): Plugin => {\n"
],
"labels": [
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" test: (id: string) => boolean,\n"
],
"file_path": "src/node/build/buildPluginReplace.ts",
"type": "add",
"edit_start_line_idx": 6
} | <template>
<h2>Hot Module Replacement</h2>
<p>
<span>
HMR: click button and edit template part of <code>./TestHmr.vue</code>,
count should not reset
</span>
<button class="hmr-increment" @click="count++">
>>> {{ count }} <<<
</button>
</p>
<p>
<span>
HMR: edit the return value of <code>foo()</code> in
<code>./testHmrPropagation.js</code>, should update without reloading
page:
</span>
<span class="hmr-propagation">{{ foo() }}</span>
</p>
<p>
HMR: manual API (see console) - edit <code>./testHmrManual.js</code> and it
should log new exported value without reloading the page.
</p>
</template>
<script>
import { foo } from './testHmrPropagation'
export default {
setup() {
return {
count: 0,
foo
}
}
}
</script>
| playground/TestHmr.vue | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017490136087872088,
0.0001712564699118957,
0.00016836273425724357,
0.00017088088497985154,
0.000002343535015825182
] |
{
"id": 2,
"code_window": [
" return {\n",
" name: 'vite:replace',\n",
" transform(code, id) {\n",
" if (filter.test(id)) {\n",
" const s = new MagicString(code)\n",
" let hasReplaced = false\n",
" let match\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (test(id)) {\n"
],
"file_path": "src/node/build/buildPluginReplace.ts",
"type": "replace",
"edit_start_line_idx": 23
} | import fs from 'fs-extra'
import path from 'path'
import { createHash } from 'crypto'
import { ResolvedConfig } from './config'
import type Rollup from 'rollup'
import {
createResolver,
supportedExts,
resolveNodeModuleEntry
} from './resolver'
import { createBaseRollupPlugins } from './build'
import { resolveFrom, lookupFile } from './utils'
import { init, parse } from 'es-module-lexer'
import chalk from 'chalk'
import { Ora } from 'ora'
import { createBuildCssPlugin } from './build/buildPluginCss'
const KNOWN_IGNORE_LIST = new Set([
'tailwindcss',
'@tailwindcss/ui',
'@pika/react',
'@pika/react-dom'
])
export interface DepOptimizationOptions {
/**
* Only optimize explicitly listed dependencies.
*/
include?: string[]
/**
* Do not optimize these dependencies.
*/
exclude?: string[]
/**
* Explicitly allow these CommonJS deps to be bundled.
*/
commonJSWhitelist?: string[]
/**
* Automatically run `vite optimize` on server start?
* @default true
*/
auto?: boolean
}
export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`
export async function optimizeDeps(
config: ResolvedConfig & { force?: boolean },
asCommand = false
) {
const debug = require('debug')('vite:optimize')
const log = asCommand ? console.log : debug
const root = config.root || process.cwd()
// warn presence of web_modules
if (fs.existsSync(path.join(root, 'web_modules'))) {
console.warn(
chalk.yellow(
`[vite] vite 0.15 has built-in dependency pre-bundling and resolving ` +
`from web_modules is no longer supported.`
)
)
}
const pkgPath = lookupFile(root, [`package.json`], true /* pathOnly */)
if (!pkgPath) {
log(`package.json not found. Skipping.`)
return
}
const cacheDir = resolveOptimizedCacheDir(root, pkgPath)!
const hashPath = path.join(cacheDir, 'hash')
const depHash = getDepHash(root, config.__path)
if (!config.force) {
let prevhash
try {
prevhash = await fs.readFile(hashPath, 'utf-8')
} catch (e) {}
// hash is consistent, no need to re-bundle
if (prevhash === depHash) {
log('Hash is consistent. Skipping. Use --force to override.')
return
}
}
await fs.remove(cacheDir)
await fs.ensureDir(cacheDir)
const deps = Object.keys(require(pkgPath).dependencies || {})
if (!deps.length) {
await fs.writeFile(hashPath, depHash)
log(`No dependencies listed in package.json. Skipping.`)
return
}
const resolver = createResolver(root, config.resolvers, config.alias)
const { include, exclude, commonJSWhitelist } = config.optimizeDeps || {}
// Determine deps to optimize. The goal is to only pre-bundle deps that falls
// under one of the following categories:
// 1. Has imports to relative files (e.g. lodash-es, lit-html)
// 2. Has imports to bare modules that are not in the project's own deps
// (i.e. esm that imports its own dependencies, e.g. styled-components)
await init
const cjsDeps: string[] = []
const qualifiedDeps = deps.filter((id) => {
if (include && !include.includes(id)) {
debug(`skipping ${id} (not included)`)
return false
}
if (exclude && exclude.includes(id)) {
debug(`skipping ${id} (excluded)`)
return false
}
if (commonJSWhitelist && commonJSWhitelist.includes(id)) {
debug(`optimizing ${id} (commonJSWhitelist)`)
return true
}
if (KNOWN_IGNORE_LIST.has(id)) {
debug(`skipping ${id} (internal excluded)`)
return false
}
const pkgInfo = resolveNodeModuleEntry(root, id)
if (!pkgInfo) {
debug(`skipping ${id} (cannot resolve entry)`)
return false
}
const [entry, pkg] = pkgInfo
if (!supportedExts.includes(path.extname(entry))) {
debug(`skipping ${id} (entry is not js)`)
return false
}
const content = fs.readFileSync(resolveFrom(root, entry), 'utf-8')
const [imports, exports] = parse(content)
if (!exports.length && !/export\s+\*\s+from/.test(content)) {
if (!pkg.module) {
cjsDeps.push(id)
}
debug(`skipping ${id} (no exports, likely commonjs)`)
return false
}
for (const { s, e } of imports) {
let i = content.slice(s, e).trim()
i = resolver.alias(i) || i
if (i.startsWith('.')) {
debug(`optimizing ${id} (contains relative imports)`)
return true
}
if (!deps.includes(i)) {
debug(`optimizing ${id} (imports sub dependencies)`)
return true
}
}
debug(`skipping ${id} (single esm file, doesn't need optimization)`)
})
if (!qualifiedDeps.length) {
if (!cjsDeps.length) {
await fs.writeFile(hashPath, depHash)
log(`No listed dependency requires optimization. Skipping.`)
} else {
console.error(
chalk.yellow(
`[vite] The following dependencies seem to be CommonJS modules that\n` +
`do not provide ESM-friendly file formats:\n\n ` +
cjsDeps.map((dep) => chalk.magenta(dep)).join(`\n `) +
`\n` +
`\n- If you are not using them in browser code, you can move them\n` +
`to devDependencies or exclude them from this check by adding\n` +
`them to ${chalk.cyan(
`optimizeDeps.exclude`
)} in vue.config.js.\n` +
`\n- If you do intend to use them in the browser, you can try adding\n` +
`them to ${chalk.cyan(
`optimizeDeps.commonJSWhitelist`
)} in vue.config.js but they\n` +
`may fail to bundle or work properly. Consider choosing more modern\n` +
`alternatives that provide ES module build formts.`
)
)
}
return
}
if (!asCommand) {
// This is auto run on server start - let the user know that we are
// pre-optimizing deps
console.log(chalk.greenBright(`[vite] Optimizable dependencies detected.`))
}
let spinner: Ora | undefined
const msg = asCommand
? `Pre-bundling dependencies to speed up dev server page load...`
: `Pre-bundling them to speed up dev server page load...\n` +
`(this will be run only when your dependencies have changed)`
if (process.env.DEBUG || process.env.NODE_ENV === 'test') {
console.log(msg)
} else {
spinner = require('ora')(msg + '\n').start()
}
try {
// Non qualified deps are marked as externals, since they will be preserved
// and resolved from their original node_modules locations.
const preservedDeps = deps
.filter((id) => !qualifiedDeps.includes(id))
// make sure aliased deps are external
// https://github.com/vitejs/vite-plugin-react/issues/4
.map((id) => resolver.alias(id) || id)
const input = qualifiedDeps.reduce((entries, name) => {
entries[name] = name
return entries
}, {} as Record<string, string>)
const rollup = require('rollup') as typeof Rollup
const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]
const bundle = await rollup.rollup({
input,
external: preservedDeps,
treeshake: { moduleSideEffects: 'no-external' },
onwarn(warning, warn) {
if (!warningIgnoreList.includes(warning.code!)) {
warn(warning)
}
},
...config.rollupInputOptions,
plugins: [
...(await createBaseRollupPlugins(root, resolver, config)),
createBuildCssPlugin(root, '/', 'assets')
]
})
const { output } = await bundle.generate({
...config.rollupOutputOptions,
format: 'es',
exports: 'named',
entryFileNames: '[name]',
chunkFileNames: 'common/[name]-[hash].js'
})
spinner && spinner.stop()
const optimized = []
for (const chunk of output) {
if (chunk.type === 'chunk') {
const fileName = chunk.fileName
const filePath = path.join(cacheDir, fileName)
await fs.ensureDir(path.dirname(filePath))
await fs.writeFile(filePath, chunk.code)
if (!fileName.startsWith('common/')) {
optimized.push(fileName.replace(/\.js$/, ''))
}
}
}
console.log(
`Optimized modules:\n${optimized
.map((id) => chalk.yellowBright(id))
.join(`, `)}`
)
await fs.writeFile(hashPath, depHash)
} catch (e) {
spinner && spinner.stop()
if (asCommand) {
throw e
} else {
console.error(chalk.red(`[vite] Dep optimization failed with error:`))
console.error(e)
console.log()
console.log(
chalk.yellow(
`Tip: You can configure what deps to include/exclude for optimization\n` +
`using the \`optimizeDeps\` option in the Vite config file.`
)
)
}
}
}
const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']
let cachedHash: string | undefined
export function getDepHash(
root: string,
configPath: string | undefined
): string {
if (cachedHash) {
return cachedHash
}
let content = lookupFile(root, lockfileFormats) || ''
const pkg = JSON.parse(lookupFile(root, [`package.json`]) || '{}')
content += JSON.stringify(pkg.dependencies)
// also take config into account
if (configPath) {
content += fs.readFileSync(configPath, 'utf-8')
}
return createHash('sha1').update(content).digest('base64')
}
const cacheDirCache = new Map<string, string | null>()
export function resolveOptimizedCacheDir(
root: string,
pkgPath?: string
): string | null {
const cached = cacheDirCache.get(root)
if (cached !== undefined) return cached
pkgPath = pkgPath || lookupFile(root, [`package.json`], true /* pathOnly */)
if (!pkgPath) {
return null
}
const cacheDir = path.join(path.dirname(pkgPath), OPTIMIZE_CACHE_DIR)
cacheDirCache.set(root, cacheDir)
return cacheDir
}
| src/node/depOptimizer.ts | 1 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.1224072203040123,
0.0039973389357328415,
0.00016350680380128324,
0.000173578824615106,
0.021267054602503777
] |
{
"id": 2,
"code_window": [
" return {\n",
" name: 'vite:replace',\n",
" transform(code, id) {\n",
" if (filter.test(id)) {\n",
" const s = new MagicString(code)\n",
" let hasReplaced = false\n",
" let match\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (test(id)) {\n"
],
"file_path": "src/node/build/buildPluginReplace.ts",
"type": "replace",
"edit_start_line_idx": 23
} | .turquoise {
color: rgb(255, 140, 0);
}
| playground/testCssModules.module.css | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.0001688166958047077,
0.0001688166958047077,
0.0001688166958047077,
0.0001688166958047077,
0
] |
{
"id": 2,
"code_window": [
" return {\n",
" name: 'vite:replace',\n",
" transform(code, id) {\n",
" if (filter.test(id)) {\n",
" const s = new MagicString(code)\n",
" let hasReplaced = false\n",
" let match\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (test(id)) {\n"
],
"file_path": "src/node/build/buildPluginReplace.ts",
"type": "replace",
"edit_start_line_idx": 23
} | import path from 'path'
import { resolveFrom } from './pathUtils'
import sfcCompiler from '@vue/compiler-sfc'
import chalk from 'chalk'
import { lookupFile } from './fsUtils'
interface ResolvedVuePaths {
vue: string | undefined
'@vue/runtime-dom': string | undefined
'@vue/runtime-core': string | undefined
'@vue/reactivity': string | undefined
'@vue/shared': string | undefined
compiler: string
version: string
isLocal: boolean
}
let resolved: ResolvedVuePaths | undefined = undefined
// Resolve the correct `vue` and `@vue.compiler-sfc` to use.
// If the user project has local installations of these, they should be used;
// otherwise, fallback to the dependency of Vite itself.
export function resolveVue(root: string): ResolvedVuePaths {
if (resolved) {
return resolved
}
let vueVersion: string | undefined
let vuePath: string | undefined
let compilerPath: string
const projectPkg = JSON.parse(lookupFile(root, ['package.json']) || `{}`)
let isLocal = !!(projectPkg.dependencies && projectPkg.dependencies.vue)
if (isLocal) {
try {
resolveFrom(root, 'vue')
} catch (e) {
// user has vue listed but not actually installed.
isLocal = false
}
}
if (isLocal) {
// user has local vue, verify that the same version of @vue/compiler-sfc
// is also installed.
// vuePath will be undefined in this case since vue itself will be
// optimized by the deps optimizer and we can just let the resolver locate
// it.
try {
const userVuePkg = resolveFrom(root, 'vue/package.json')
vueVersion = require(userVuePkg).version
const compilerPkgPath = resolveFrom(
root,
'@vue/compiler-sfc/package.json'
)
const compilerPkg = require(compilerPkgPath)
if (compilerPkg.version !== vueVersion) {
throw new Error()
}
compilerPath = path.join(path.dirname(compilerPkgPath), compilerPkg.main)
} catch (e) {
// user has local vue but has no compiler-sfc
console.error(
chalk.red(
`[vite] Error: a local installation of \`vue\` is detected but ` +
`no matching \`@vue/compiler-sfc\` is found. Make sure to install ` +
`both and use the same version.`
)
)
compilerPath = require.resolve('@vue/compiler-sfc')
}
} else {
// user has no local vue, use vite's dependency version
vueVersion = require('vue/package.json').version
vuePath = require.resolve(
'@vue/runtime-dom/dist/runtime-dom.esm-bundler.js'
)
compilerPath = require.resolve('@vue/compiler-sfc')
}
const inferPath = (name: string) =>
vuePath && vuePath.replace(/runtime-dom/g, name)
resolved = {
version: vueVersion!,
vue: vuePath,
'@vue/runtime-dom': vuePath,
'@vue/runtime-core': inferPath('runtime-core'),
'@vue/reactivity': inferPath('reactivity'),
'@vue/shared': inferPath('shared'),
compiler: compilerPath,
isLocal
}
return resolved
}
export function resolveCompiler(cwd: string): typeof sfcCompiler {
return require(resolveVue(cwd).compiler)
}
| src/node/utils/resolveVue.ts | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017619591380935162,
0.0001699873391771689,
0.00016470681293867528,
0.00017003886750899255,
0.000003759931360036717
] |
{
"id": 2,
"code_window": [
" return {\n",
" name: 'vite:replace',\n",
" transform(code, id) {\n",
" if (filter.test(id)) {\n",
" const s = new MagicString(code)\n",
" let hasReplaced = false\n",
" let match\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (test(id)) {\n"
],
"file_path": "src/node/build/buildPluginReplace.ts",
"type": "replace",
"edit_start_line_idx": 23
} | {
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "../../dist",
"module": "esnext",
"types": [],
"lib": ["ESNext", "WebWorker"]
},
"include": ["./"]
}
| src/sw/tsconfig.json | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017594711971469223,
0.00017591574578545988,
0.00017588438640814275,
0.00017591574578545988,
3.136665327474475e-8
] |
{
"id": 3,
"code_window": [
"import path from 'path'\n",
"import fs from 'fs-extra'\n",
"import chalk from 'chalk'\n",
"import { Ora } from 'ora'\n",
"import { resolveFrom } from '../utils'\n",
"import { rollup as Rollup, RollupOutput, ExternalOption, Plugin } from 'rollup'\n",
"import { createResolver, supportedExts, InternalResolver } from '../resolver'\n",
"import { createBuildResolvePlugin } from './buildPluginResolve'\n",
"import { createBuildHtmlPlugin } from './buildPluginHtml'\n",
"import { createBuildCssPlugin } from './buildPluginCss'\n",
"import { createBuildAssetPlugin } from './buildPluginAsset'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" rollup as Rollup,\n",
" RollupOutput,\n",
" ExternalOption,\n",
" Plugin,\n",
" InputOptions\n",
"} from 'rollup'\n"
],
"file_path": "src/node/build/index.ts",
"type": "replace",
"edit_start_line_idx": 5
} | import fs from 'fs-extra'
import path from 'path'
import { createHash } from 'crypto'
import { ResolvedConfig } from './config'
import type Rollup from 'rollup'
import {
createResolver,
supportedExts,
resolveNodeModuleEntry
} from './resolver'
import { createBaseRollupPlugins } from './build'
import { resolveFrom, lookupFile } from './utils'
import { init, parse } from 'es-module-lexer'
import chalk from 'chalk'
import { Ora } from 'ora'
import { createBuildCssPlugin } from './build/buildPluginCss'
const KNOWN_IGNORE_LIST = new Set([
'tailwindcss',
'@tailwindcss/ui',
'@pika/react',
'@pika/react-dom'
])
export interface DepOptimizationOptions {
/**
* Only optimize explicitly listed dependencies.
*/
include?: string[]
/**
* Do not optimize these dependencies.
*/
exclude?: string[]
/**
* Explicitly allow these CommonJS deps to be bundled.
*/
commonJSWhitelist?: string[]
/**
* Automatically run `vite optimize` on server start?
* @default true
*/
auto?: boolean
}
export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`
export async function optimizeDeps(
config: ResolvedConfig & { force?: boolean },
asCommand = false
) {
const debug = require('debug')('vite:optimize')
const log = asCommand ? console.log : debug
const root = config.root || process.cwd()
// warn presence of web_modules
if (fs.existsSync(path.join(root, 'web_modules'))) {
console.warn(
chalk.yellow(
`[vite] vite 0.15 has built-in dependency pre-bundling and resolving ` +
`from web_modules is no longer supported.`
)
)
}
const pkgPath = lookupFile(root, [`package.json`], true /* pathOnly */)
if (!pkgPath) {
log(`package.json not found. Skipping.`)
return
}
const cacheDir = resolveOptimizedCacheDir(root, pkgPath)!
const hashPath = path.join(cacheDir, 'hash')
const depHash = getDepHash(root, config.__path)
if (!config.force) {
let prevhash
try {
prevhash = await fs.readFile(hashPath, 'utf-8')
} catch (e) {}
// hash is consistent, no need to re-bundle
if (prevhash === depHash) {
log('Hash is consistent. Skipping. Use --force to override.')
return
}
}
await fs.remove(cacheDir)
await fs.ensureDir(cacheDir)
const deps = Object.keys(require(pkgPath).dependencies || {})
if (!deps.length) {
await fs.writeFile(hashPath, depHash)
log(`No dependencies listed in package.json. Skipping.`)
return
}
const resolver = createResolver(root, config.resolvers, config.alias)
const { include, exclude, commonJSWhitelist } = config.optimizeDeps || {}
// Determine deps to optimize. The goal is to only pre-bundle deps that falls
// under one of the following categories:
// 1. Has imports to relative files (e.g. lodash-es, lit-html)
// 2. Has imports to bare modules that are not in the project's own deps
// (i.e. esm that imports its own dependencies, e.g. styled-components)
await init
const cjsDeps: string[] = []
const qualifiedDeps = deps.filter((id) => {
if (include && !include.includes(id)) {
debug(`skipping ${id} (not included)`)
return false
}
if (exclude && exclude.includes(id)) {
debug(`skipping ${id} (excluded)`)
return false
}
if (commonJSWhitelist && commonJSWhitelist.includes(id)) {
debug(`optimizing ${id} (commonJSWhitelist)`)
return true
}
if (KNOWN_IGNORE_LIST.has(id)) {
debug(`skipping ${id} (internal excluded)`)
return false
}
const pkgInfo = resolveNodeModuleEntry(root, id)
if (!pkgInfo) {
debug(`skipping ${id} (cannot resolve entry)`)
return false
}
const [entry, pkg] = pkgInfo
if (!supportedExts.includes(path.extname(entry))) {
debug(`skipping ${id} (entry is not js)`)
return false
}
const content = fs.readFileSync(resolveFrom(root, entry), 'utf-8')
const [imports, exports] = parse(content)
if (!exports.length && !/export\s+\*\s+from/.test(content)) {
if (!pkg.module) {
cjsDeps.push(id)
}
debug(`skipping ${id} (no exports, likely commonjs)`)
return false
}
for (const { s, e } of imports) {
let i = content.slice(s, e).trim()
i = resolver.alias(i) || i
if (i.startsWith('.')) {
debug(`optimizing ${id} (contains relative imports)`)
return true
}
if (!deps.includes(i)) {
debug(`optimizing ${id} (imports sub dependencies)`)
return true
}
}
debug(`skipping ${id} (single esm file, doesn't need optimization)`)
})
if (!qualifiedDeps.length) {
if (!cjsDeps.length) {
await fs.writeFile(hashPath, depHash)
log(`No listed dependency requires optimization. Skipping.`)
} else {
console.error(
chalk.yellow(
`[vite] The following dependencies seem to be CommonJS modules that\n` +
`do not provide ESM-friendly file formats:\n\n ` +
cjsDeps.map((dep) => chalk.magenta(dep)).join(`\n `) +
`\n` +
`\n- If you are not using them in browser code, you can move them\n` +
`to devDependencies or exclude them from this check by adding\n` +
`them to ${chalk.cyan(
`optimizeDeps.exclude`
)} in vue.config.js.\n` +
`\n- If you do intend to use them in the browser, you can try adding\n` +
`them to ${chalk.cyan(
`optimizeDeps.commonJSWhitelist`
)} in vue.config.js but they\n` +
`may fail to bundle or work properly. Consider choosing more modern\n` +
`alternatives that provide ES module build formts.`
)
)
}
return
}
if (!asCommand) {
// This is auto run on server start - let the user know that we are
// pre-optimizing deps
console.log(chalk.greenBright(`[vite] Optimizable dependencies detected.`))
}
let spinner: Ora | undefined
const msg = asCommand
? `Pre-bundling dependencies to speed up dev server page load...`
: `Pre-bundling them to speed up dev server page load...\n` +
`(this will be run only when your dependencies have changed)`
if (process.env.DEBUG || process.env.NODE_ENV === 'test') {
console.log(msg)
} else {
spinner = require('ora')(msg + '\n').start()
}
try {
// Non qualified deps are marked as externals, since they will be preserved
// and resolved from their original node_modules locations.
const preservedDeps = deps
.filter((id) => !qualifiedDeps.includes(id))
// make sure aliased deps are external
// https://github.com/vitejs/vite-plugin-react/issues/4
.map((id) => resolver.alias(id) || id)
const input = qualifiedDeps.reduce((entries, name) => {
entries[name] = name
return entries
}, {} as Record<string, string>)
const rollup = require('rollup') as typeof Rollup
const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]
const bundle = await rollup.rollup({
input,
external: preservedDeps,
treeshake: { moduleSideEffects: 'no-external' },
onwarn(warning, warn) {
if (!warningIgnoreList.includes(warning.code!)) {
warn(warning)
}
},
...config.rollupInputOptions,
plugins: [
...(await createBaseRollupPlugins(root, resolver, config)),
createBuildCssPlugin(root, '/', 'assets')
]
})
const { output } = await bundle.generate({
...config.rollupOutputOptions,
format: 'es',
exports: 'named',
entryFileNames: '[name]',
chunkFileNames: 'common/[name]-[hash].js'
})
spinner && spinner.stop()
const optimized = []
for (const chunk of output) {
if (chunk.type === 'chunk') {
const fileName = chunk.fileName
const filePath = path.join(cacheDir, fileName)
await fs.ensureDir(path.dirname(filePath))
await fs.writeFile(filePath, chunk.code)
if (!fileName.startsWith('common/')) {
optimized.push(fileName.replace(/\.js$/, ''))
}
}
}
console.log(
`Optimized modules:\n${optimized
.map((id) => chalk.yellowBright(id))
.join(`, `)}`
)
await fs.writeFile(hashPath, depHash)
} catch (e) {
spinner && spinner.stop()
if (asCommand) {
throw e
} else {
console.error(chalk.red(`[vite] Dep optimization failed with error:`))
console.error(e)
console.log()
console.log(
chalk.yellow(
`Tip: You can configure what deps to include/exclude for optimization\n` +
`using the \`optimizeDeps\` option in the Vite config file.`
)
)
}
}
}
const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']
let cachedHash: string | undefined
export function getDepHash(
root: string,
configPath: string | undefined
): string {
if (cachedHash) {
return cachedHash
}
let content = lookupFile(root, lockfileFormats) || ''
const pkg = JSON.parse(lookupFile(root, [`package.json`]) || '{}')
content += JSON.stringify(pkg.dependencies)
// also take config into account
if (configPath) {
content += fs.readFileSync(configPath, 'utf-8')
}
return createHash('sha1').update(content).digest('base64')
}
const cacheDirCache = new Map<string, string | null>()
export function resolveOptimizedCacheDir(
root: string,
pkgPath?: string
): string | null {
const cached = cacheDirCache.get(root)
if (cached !== undefined) return cached
pkgPath = pkgPath || lookupFile(root, [`package.json`], true /* pathOnly */)
if (!pkgPath) {
return null
}
const cacheDir = path.join(path.dirname(pkgPath), OPTIMIZE_CACHE_DIR)
cacheDirCache.set(root, cacheDir)
return cacheDir
}
| src/node/depOptimizer.ts | 1 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.0014317427994683385,
0.00026503740809857845,
0.0001609776372788474,
0.0001685164461378008,
0.0002634097181726247
] |
{
"id": 3,
"code_window": [
"import path from 'path'\n",
"import fs from 'fs-extra'\n",
"import chalk from 'chalk'\n",
"import { Ora } from 'ora'\n",
"import { resolveFrom } from '../utils'\n",
"import { rollup as Rollup, RollupOutput, ExternalOption, Plugin } from 'rollup'\n",
"import { createResolver, supportedExts, InternalResolver } from '../resolver'\n",
"import { createBuildResolvePlugin } from './buildPluginResolve'\n",
"import { createBuildHtmlPlugin } from './buildPluginHtml'\n",
"import { createBuildCssPlugin } from './buildPluginCss'\n",
"import { createBuildAssetPlugin } from './buildPluginAsset'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" rollup as Rollup,\n",
" RollupOutput,\n",
" ExternalOption,\n",
" Plugin,\n",
" InputOptions\n",
"} from 'rollup'\n"
],
"file_path": "src/node/build/index.ts",
"type": "replace",
"edit_start_line_idx": 5
} | import { render } from 'preact'
import { Test } from './testTsx.tsx'
const Component = () => <div>
Rendered from Preact JSX
<Test count={1337} />
</div>
export function renderPreact(el) {
render(<Component/>, el)
}
| playground/testJsx.jsx | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017465870769228786,
0.0001722521847113967,
0.00016984566173050553,
0.0001722521847113967,
0.000002406522980891168
] |
{
"id": 3,
"code_window": [
"import path from 'path'\n",
"import fs from 'fs-extra'\n",
"import chalk from 'chalk'\n",
"import { Ora } from 'ora'\n",
"import { resolveFrom } from '../utils'\n",
"import { rollup as Rollup, RollupOutput, ExternalOption, Plugin } from 'rollup'\n",
"import { createResolver, supportedExts, InternalResolver } from '../resolver'\n",
"import { createBuildResolvePlugin } from './buildPluginResolve'\n",
"import { createBuildHtmlPlugin } from './buildPluginHtml'\n",
"import { createBuildCssPlugin } from './buildPluginCss'\n",
"import { createBuildAssetPlugin } from './buildPluginAsset'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" rollup as Rollup,\n",
" RollupOutput,\n",
" ExternalOption,\n",
" Plugin,\n",
" InputOptions\n",
"} from 'rollup'\n"
],
"file_path": "src/node/build/index.ts",
"type": "replace",
"edit_start_line_idx": 5
} | import path from 'path'
import { asyncReplace } from './transformUtils'
import { isExternalUrl } from './pathUtils'
export const urlRE = /(url\(\s*['"]?)([^"')]+)(["']?\s*\))/
type Replacer = (url: string) => string | Promise<string>
export function rewriteCssUrls(
css: string,
replacerOrBase: string | Replacer
): Promise<string> {
let replacer: Replacer
if (typeof replacerOrBase === 'string') {
replacer = (rawUrl) => {
return path.posix.resolve(path.posix.dirname(replacerOrBase), rawUrl)
}
} else {
replacer = replacerOrBase
}
return asyncReplace(css, urlRE, async (match) => {
const [matched, before, rawUrl, after] = match
if (
isExternalUrl(rawUrl) ||
rawUrl.startsWith('data:') ||
rawUrl.startsWith('#')
) {
return matched
}
return before + (await replacer(rawUrl)) + after
})
}
| src/node/utils/cssUtils.ts | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00018166526569984853,
0.0001724911853671074,
0.00016725403838790953,
0.0001705227477941662,
0.00000547599529454601
] |
{
"id": 3,
"code_window": [
"import path from 'path'\n",
"import fs from 'fs-extra'\n",
"import chalk from 'chalk'\n",
"import { Ora } from 'ora'\n",
"import { resolveFrom } from '../utils'\n",
"import { rollup as Rollup, RollupOutput, ExternalOption, Plugin } from 'rollup'\n",
"import { createResolver, supportedExts, InternalResolver } from '../resolver'\n",
"import { createBuildResolvePlugin } from './buildPluginResolve'\n",
"import { createBuildHtmlPlugin } from './buildPluginHtml'\n",
"import { createBuildCssPlugin } from './buildPluginCss'\n",
"import { createBuildAssetPlugin } from './buildPluginAsset'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" rollup as Rollup,\n",
" RollupOutput,\n",
" ExternalOption,\n",
" Plugin,\n",
" InputOptions\n",
"} from 'rollup'\n"
],
"file_path": "src/node/build/index.ts",
"type": "replace",
"edit_start_line_idx": 5
} | export * from './fsUtils'
export * from './pathUtils'
export * from './transformUtils'
export * from './resolveVue'
export * from './resolvePostCssConfig'
| src/node/utils/index.ts | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00016514872550033033,
0.00016514872550033033,
0.00016514872550033033,
0.00016514872550033033,
0
] |
{
"id": 4,
"code_window": [
" [WriteType.SOURCE_MAP]: chalk.gray\n",
"}\n",
"\n",
"/**\n",
" * Named exports detection logic from Snowpack\n",
" * MIT License\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]\n",
"\n",
"export const onRollupWarning: InputOptions['onwarn'] = (warning, warn) => {\n",
" if (!warningIgnoreList.includes(warning.code!)) {\n",
" warn(warning)\n",
" }\n",
"}\n",
"\n"
],
"file_path": "src/node/build/index.ts",
"type": "add",
"edit_start_line_idx": 39
} | import fs from 'fs-extra'
import path from 'path'
import { createHash } from 'crypto'
import { ResolvedConfig } from './config'
import type Rollup from 'rollup'
import {
createResolver,
supportedExts,
resolveNodeModuleEntry
} from './resolver'
import { createBaseRollupPlugins } from './build'
import { resolveFrom, lookupFile } from './utils'
import { init, parse } from 'es-module-lexer'
import chalk from 'chalk'
import { Ora } from 'ora'
import { createBuildCssPlugin } from './build/buildPluginCss'
const KNOWN_IGNORE_LIST = new Set([
'tailwindcss',
'@tailwindcss/ui',
'@pika/react',
'@pika/react-dom'
])
export interface DepOptimizationOptions {
/**
* Only optimize explicitly listed dependencies.
*/
include?: string[]
/**
* Do not optimize these dependencies.
*/
exclude?: string[]
/**
* Explicitly allow these CommonJS deps to be bundled.
*/
commonJSWhitelist?: string[]
/**
* Automatically run `vite optimize` on server start?
* @default true
*/
auto?: boolean
}
export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`
export async function optimizeDeps(
config: ResolvedConfig & { force?: boolean },
asCommand = false
) {
const debug = require('debug')('vite:optimize')
const log = asCommand ? console.log : debug
const root = config.root || process.cwd()
// warn presence of web_modules
if (fs.existsSync(path.join(root, 'web_modules'))) {
console.warn(
chalk.yellow(
`[vite] vite 0.15 has built-in dependency pre-bundling and resolving ` +
`from web_modules is no longer supported.`
)
)
}
const pkgPath = lookupFile(root, [`package.json`], true /* pathOnly */)
if (!pkgPath) {
log(`package.json not found. Skipping.`)
return
}
const cacheDir = resolveOptimizedCacheDir(root, pkgPath)!
const hashPath = path.join(cacheDir, 'hash')
const depHash = getDepHash(root, config.__path)
if (!config.force) {
let prevhash
try {
prevhash = await fs.readFile(hashPath, 'utf-8')
} catch (e) {}
// hash is consistent, no need to re-bundle
if (prevhash === depHash) {
log('Hash is consistent. Skipping. Use --force to override.')
return
}
}
await fs.remove(cacheDir)
await fs.ensureDir(cacheDir)
const deps = Object.keys(require(pkgPath).dependencies || {})
if (!deps.length) {
await fs.writeFile(hashPath, depHash)
log(`No dependencies listed in package.json. Skipping.`)
return
}
const resolver = createResolver(root, config.resolvers, config.alias)
const { include, exclude, commonJSWhitelist } = config.optimizeDeps || {}
// Determine deps to optimize. The goal is to only pre-bundle deps that falls
// under one of the following categories:
// 1. Has imports to relative files (e.g. lodash-es, lit-html)
// 2. Has imports to bare modules that are not in the project's own deps
// (i.e. esm that imports its own dependencies, e.g. styled-components)
await init
const cjsDeps: string[] = []
const qualifiedDeps = deps.filter((id) => {
if (include && !include.includes(id)) {
debug(`skipping ${id} (not included)`)
return false
}
if (exclude && exclude.includes(id)) {
debug(`skipping ${id} (excluded)`)
return false
}
if (commonJSWhitelist && commonJSWhitelist.includes(id)) {
debug(`optimizing ${id} (commonJSWhitelist)`)
return true
}
if (KNOWN_IGNORE_LIST.has(id)) {
debug(`skipping ${id} (internal excluded)`)
return false
}
const pkgInfo = resolveNodeModuleEntry(root, id)
if (!pkgInfo) {
debug(`skipping ${id} (cannot resolve entry)`)
return false
}
const [entry, pkg] = pkgInfo
if (!supportedExts.includes(path.extname(entry))) {
debug(`skipping ${id} (entry is not js)`)
return false
}
const content = fs.readFileSync(resolveFrom(root, entry), 'utf-8')
const [imports, exports] = parse(content)
if (!exports.length && !/export\s+\*\s+from/.test(content)) {
if (!pkg.module) {
cjsDeps.push(id)
}
debug(`skipping ${id} (no exports, likely commonjs)`)
return false
}
for (const { s, e } of imports) {
let i = content.slice(s, e).trim()
i = resolver.alias(i) || i
if (i.startsWith('.')) {
debug(`optimizing ${id} (contains relative imports)`)
return true
}
if (!deps.includes(i)) {
debug(`optimizing ${id} (imports sub dependencies)`)
return true
}
}
debug(`skipping ${id} (single esm file, doesn't need optimization)`)
})
if (!qualifiedDeps.length) {
if (!cjsDeps.length) {
await fs.writeFile(hashPath, depHash)
log(`No listed dependency requires optimization. Skipping.`)
} else {
console.error(
chalk.yellow(
`[vite] The following dependencies seem to be CommonJS modules that\n` +
`do not provide ESM-friendly file formats:\n\n ` +
cjsDeps.map((dep) => chalk.magenta(dep)).join(`\n `) +
`\n` +
`\n- If you are not using them in browser code, you can move them\n` +
`to devDependencies or exclude them from this check by adding\n` +
`them to ${chalk.cyan(
`optimizeDeps.exclude`
)} in vue.config.js.\n` +
`\n- If you do intend to use them in the browser, you can try adding\n` +
`them to ${chalk.cyan(
`optimizeDeps.commonJSWhitelist`
)} in vue.config.js but they\n` +
`may fail to bundle or work properly. Consider choosing more modern\n` +
`alternatives that provide ES module build formts.`
)
)
}
return
}
if (!asCommand) {
// This is auto run on server start - let the user know that we are
// pre-optimizing deps
console.log(chalk.greenBright(`[vite] Optimizable dependencies detected.`))
}
let spinner: Ora | undefined
const msg = asCommand
? `Pre-bundling dependencies to speed up dev server page load...`
: `Pre-bundling them to speed up dev server page load...\n` +
`(this will be run only when your dependencies have changed)`
if (process.env.DEBUG || process.env.NODE_ENV === 'test') {
console.log(msg)
} else {
spinner = require('ora')(msg + '\n').start()
}
try {
// Non qualified deps are marked as externals, since they will be preserved
// and resolved from their original node_modules locations.
const preservedDeps = deps
.filter((id) => !qualifiedDeps.includes(id))
// make sure aliased deps are external
// https://github.com/vitejs/vite-plugin-react/issues/4
.map((id) => resolver.alias(id) || id)
const input = qualifiedDeps.reduce((entries, name) => {
entries[name] = name
return entries
}, {} as Record<string, string>)
const rollup = require('rollup') as typeof Rollup
const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]
const bundle = await rollup.rollup({
input,
external: preservedDeps,
treeshake: { moduleSideEffects: 'no-external' },
onwarn(warning, warn) {
if (!warningIgnoreList.includes(warning.code!)) {
warn(warning)
}
},
...config.rollupInputOptions,
plugins: [
...(await createBaseRollupPlugins(root, resolver, config)),
createBuildCssPlugin(root, '/', 'assets')
]
})
const { output } = await bundle.generate({
...config.rollupOutputOptions,
format: 'es',
exports: 'named',
entryFileNames: '[name]',
chunkFileNames: 'common/[name]-[hash].js'
})
spinner && spinner.stop()
const optimized = []
for (const chunk of output) {
if (chunk.type === 'chunk') {
const fileName = chunk.fileName
const filePath = path.join(cacheDir, fileName)
await fs.ensureDir(path.dirname(filePath))
await fs.writeFile(filePath, chunk.code)
if (!fileName.startsWith('common/')) {
optimized.push(fileName.replace(/\.js$/, ''))
}
}
}
console.log(
`Optimized modules:\n${optimized
.map((id) => chalk.yellowBright(id))
.join(`, `)}`
)
await fs.writeFile(hashPath, depHash)
} catch (e) {
spinner && spinner.stop()
if (asCommand) {
throw e
} else {
console.error(chalk.red(`[vite] Dep optimization failed with error:`))
console.error(e)
console.log()
console.log(
chalk.yellow(
`Tip: You can configure what deps to include/exclude for optimization\n` +
`using the \`optimizeDeps\` option in the Vite config file.`
)
)
}
}
}
const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']
let cachedHash: string | undefined
export function getDepHash(
root: string,
configPath: string | undefined
): string {
if (cachedHash) {
return cachedHash
}
let content = lookupFile(root, lockfileFormats) || ''
const pkg = JSON.parse(lookupFile(root, [`package.json`]) || '{}')
content += JSON.stringify(pkg.dependencies)
// also take config into account
if (configPath) {
content += fs.readFileSync(configPath, 'utf-8')
}
return createHash('sha1').update(content).digest('base64')
}
const cacheDirCache = new Map<string, string | null>()
export function resolveOptimizedCacheDir(
root: string,
pkgPath?: string
): string | null {
const cached = cacheDirCache.get(root)
if (cached !== undefined) return cached
pkgPath = pkgPath || lookupFile(root, [`package.json`], true /* pathOnly */)
if (!pkgPath) {
return null
}
const cacheDir = path.join(path.dirname(pkgPath), OPTIMIZE_CACHE_DIR)
cacheDirCache.set(root, cacheDir)
return cacheDir
}
| src/node/depOptimizer.ts | 1 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.0002155176771339029,
0.00017014611512422562,
0.0001652901992201805,
0.00016867021622601897,
0.000008299835826619528
] |
{
"id": 4,
"code_window": [
" [WriteType.SOURCE_MAP]: chalk.gray\n",
"}\n",
"\n",
"/**\n",
" * Named exports detection logic from Snowpack\n",
" * MIT License\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]\n",
"\n",
"export const onRollupWarning: InputOptions['onwarn'] = (warning, warn) => {\n",
" if (!warningIgnoreList.includes(warning.code!)) {\n",
" warn(warning)\n",
" }\n",
"}\n",
"\n"
],
"file_path": "src/node/build/index.ts",
"type": "add",
"edit_start_line_idx": 39
} | import fs from 'fs'
import path from 'path'
import { ServerPlugin } from '.'
import { getDepHash } from '../depOptimizer'
export const serviceWorkerPlugin: ServerPlugin = ({
root,
app,
watcher,
resolver,
config
}) => {
const enabled = (config.serviceWorker = !!config.serviceWorker)
let swScript = fs
.readFileSync(path.resolve(__dirname, '../serviceWorker.js'), 'utf-8')
.replace(/const __ENABLED__ =.*/, `const __ENABLED__ = ${enabled}`)
// make sure the sw cache is unique per project
.replace(
/const __PROJECT_ROOT__ =.*/,
`const __PROJECT_ROOT__ = ${JSON.stringify(root)}`
)
.replace(
/const __LOCKFILE_HASH__ =.*/,
`const __LOCKFILE_HASH__ = ${JSON.stringify(
getDepHash(root, config.__path)
)}`
)
// inject server id so the sw cache is invalidated on restart.
.replace(
/const __SERVER_ID__ =.*/,
`const __SERVER_ID__ = ${
// only inject if caching user files. When caching deps only, only
// the lockfile change invalidates the cache.
config.serviceWorker === true ? Date.now() : '0'
}`
)
// enable console logs in debug mode
if (process.env.DEBUG === 'vite:sw') {
swScript = swScript.replace(/\/\/ console.log/g, 'console.log')
}
watcher.on('unlink', (file: string) => {
watcher.send({
type: 'sw-bust-cache',
path: resolver.fileToRequest(file),
timestamp: Date.now()
})
})
// TODO watch lockfile hash
// - update swScript
// - notify the client to update the sw
app.use(async (ctx, next) => {
// expose config to cachedRead
ctx.__serviceWorker = enabled
if (ctx.path === '/sw.js') {
ctx.type = 'js'
ctx.status = 200
ctx.body = swScript
return
}
return next()
})
}
| src/node/server/serverPluginServiceWorker.ts | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017111292982008308,
0.000168737955391407,
0.00016583198157604784,
0.00016861673793755472,
0.0000017174895674543222
] |
{
"id": 4,
"code_window": [
" [WriteType.SOURCE_MAP]: chalk.gray\n",
"}\n",
"\n",
"/**\n",
" * Named exports detection logic from Snowpack\n",
" * MIT License\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]\n",
"\n",
"export const onRollupWarning: InputOptions['onwarn'] = (warning, warn) => {\n",
" if (!warningIgnoreList.includes(warning.code!)) {\n",
" warn(warning)\n",
" }\n",
"}\n",
"\n"
],
"file_path": "src/node/build/index.ts",
"type": "add",
"edit_start_line_idx": 39
} | CUSTOM_ENV_VARIABLE=9527
| playground/.env | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017026482964865863,
0.00017026482964865863,
0.00017026482964865863,
0.00017026482964865863,
0
] |
{
"id": 4,
"code_window": [
" [WriteType.SOURCE_MAP]: chalk.gray\n",
"}\n",
"\n",
"/**\n",
" * Named exports detection logic from Snowpack\n",
" * MIT License\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]\n",
"\n",
"export const onRollupWarning: InputOptions['onwarn'] = (warning, warn) => {\n",
" if (!warningIgnoreList.includes(warning.code!)) {\n",
" warn(warning)\n",
" }\n",
"}\n",
"\n"
],
"file_path": "src/node/build/index.ts",
"type": "add",
"edit_start_line_idx": 39
} | import path from 'path'
import fs from 'fs-extra'
import chalk from 'chalk'
import { DotenvParseOutput } from 'dotenv'
import { Options as RollupPluginVueOptions } from 'rollup-plugin-vue'
import { CompilerOptions } from '@vue/compiler-sfc'
import Rollup, {
InputOptions as RollupInputOptions,
OutputOptions as RollupOutputOptions,
OutputChunk
} from 'rollup'
import { createEsbuildPlugin } from './build/buildPluginEsbuild'
import { ServerPlugin } from './server'
import { Resolver } from './resolver'
import { Transform } from './transform'
import { DepOptimizationOptions } from './depOptimizer'
import { IKoaProxiesOptions } from 'koa-proxies'
import { ServerOptions } from 'https'
export { Resolver, Transform }
/**
* Options shared between server and build.
*/
export interface SharedConfig {
/**
* Project root directory. Can be an absolute path, or a path relative from
* the location of the config file itself.
* @default process.cwd()
*/
root?: string
/**
* Import alias. Can only be exact mapping, does not support wildcard syntax.
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* alias: {
* 'react': '@pika/react',
* 'react-dom': '@pika/react-dom'
* }
* }
* ```
*/
alias?: Record<string, string>
/**
* Custom file transforms.
*/
transforms?: Transform[]
/**
* Resolvers to map dev server public path requests to/from file system paths,
* and optionally map module ids to public path requests.
*/
resolvers?: Resolver[]
/**
* Configure dep optimization behavior.
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* optimizeDeps: {
* exclude: ['dep-a', 'dep-b']
* }
* }
* ```
*/
optimizeDeps?: DepOptimizationOptions
/**
* Options to pass to `@vue/compiler-dom`
*
* https://github.com/vuejs/vue-next/blob/master/packages/compiler-core/src/options.ts
*/
vueCompilerOptions?: CompilerOptions
/**
* Configure what to use for jsx factory and fragment.
* @default 'vue'
*/
jsx?:
| 'vue'
| 'preact'
| 'react'
| {
factory?: string
fragment?: string
}
/**
* Environment variables .
*/
env?: DotenvParseOutput
}
export interface ServerConfig extends SharedConfig {
port?: number
open?: boolean
/**
* Configure https.
*/
https?: boolean
httpsOption?: ServerOptions
/**
* Configure custom proxy rules for the dev server. Uses
* [`koa-proxies`](https://github.com/vagusX/koa-proxies) which in turn uses
* [`http-proxy`](https://github.com/http-party/node-http-proxy). Each key can
* be a path Full options
* [here](https://github.com/http-party/node-http-proxy#options).
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* proxy: {
* proxy: {
* // string shorthand
* '/foo': 'http://localhost:4567/foo',
* // with options
* '/api': {
* target: 'http://jsonplaceholder.typicode.com',
* changeOrigin: true,
* rewrite: path => path.replace(/^\/api/, '')
* }
* }
* }
* }
* ```
*/
proxy?: Record<string, string | IKoaProxiesOptions>
/**
* Whether to use a Service Worker to cache served code. This can greatly
* improve full page reload performance, but requires a Service Worker
* update + reload on each server restart.
*
* @default false
*/
serviceWorker?: boolean
configureServer?: ServerPlugin | ServerPlugin[]
}
export interface BuildConfig extends SharedConfig {
/**
* Base public path when served in production.
* @default '/'
*/
base?: string
/**
* Directory relative from `root` where build output will be placed. If the
* directory exists, it will be removed before the build.
* @default 'dist'
*/
outDir?: string
/**
* Directory relative from `outDir` where the built js/css/image assets will
* be placed.
* @default '_assets'
*/
assetsDir?: string
/**
* Static asset files smaller than this number (in bytes) will be inlined as
* base64 strings. Default limit is `4096` (4kb). Set to `0` to disable.
* @default 4096
*/
assetsInlineLimit?: number
/**
* Whether to code-split CSS. When enabled, CSS in async chunks will be
* inlined as strings in the chunk and inserted via dynamically created
* style tags when the chunk is loaded.
* @default true
*/
cssCodeSplit?: boolean
/**
* Whether to generate sourcemap
* @default false
*/
sourcemap?: boolean
/**
* Set to `false` to dsiable minification, or specify the minifier to use.
* Available options are 'terser' or 'esbuild'.
* @default 'terser'
*/
minify?: boolean | 'terser' | 'esbuild'
/**
* Build for server-side rendering
* @default false
*/
ssr?: boolean
// The following are API only and not documented in the CLI. -----------------
/**
* Will be passed to rollup.rollup()
*
* https://rollupjs.org/guide/en/#big-list-of-options
*/
rollupInputOptions?: RollupInputOptions
/**
* Will be passed to @rollup/plugin-commonjs
* https://github.com/rollup/plugins/tree/commonjs-v11.1.0/packages/commonjs#namedexports
* This config can be removed after master branch is released.
* But there are some issues blocking it:
* https://github.com/rollup/plugins/issues/392
*/
rollupPluginCommonJSNamedExports?: Record<string, string[]>
/**
* Will be passed to bundle.generate()
*
* https://rollupjs.org/guide/en/#big-list-of-options
*/
rollupOutputOptions?: RollupOutputOptions
/**
* Will be passed to rollup-plugin-vue
*
* https://github.com/vuejs/rollup-plugin-vue/blob/next/src/index.ts
*/
rollupPluginVueOptions?: Partial<RollupPluginVueOptions>
/**
* Whether to log asset info to console
* @default false
*/
silent?: boolean
/**
* Whether to write bundle to disk
* @default true
*/
write?: boolean
/**
* Whether to emit index.html
* @default true
*/
emitIndex?: boolean
/**
* Whether to emit assets other than JavaScript
* @default true
*/
emitAssets?: boolean
/**
* Predicate function that determines whether a link rel=modulepreload shall be
* added to the index.html for the chunk passed in
*/
shouldPreload?: (chunk: OutputChunk) => boolean
}
export interface UserConfig extends BuildConfig, ServerConfig {
plugins?: Plugin[]
}
export interface Plugin
extends Pick<
UserConfig,
| 'alias'
| 'transforms'
| 'resolvers'
| 'configureServer'
| 'vueCompilerOptions'
| 'rollupInputOptions'
| 'rollupOutputOptions'
> {}
export type ResolvedConfig = UserConfig & { __path?: string }
export async function resolveConfig(
configPath: string | undefined
): Promise<ResolvedConfig | undefined> {
const start = Date.now()
const cwd = process.cwd()
let config: ResolvedConfig | undefined
let resolvedPath: string | undefined
let isTS = false
if (configPath) {
resolvedPath = path.resolve(cwd, configPath)
} else {
const jsConfigPath = path.resolve(cwd, 'vite.config.js')
if (fs.existsSync(jsConfigPath)) {
resolvedPath = jsConfigPath
} else {
const tsConfigPath = path.resolve(cwd, 'vite.config.ts')
if (fs.existsSync(tsConfigPath)) {
isTS = true
resolvedPath = tsConfigPath
}
}
}
if (!resolvedPath) {
return
}
try {
if (!isTS) {
try {
config = require(resolvedPath)
} catch (e) {
if (
!/Cannot use import statement|Unexpected token 'export'/.test(
e.message
)
) {
throw e
}
}
}
if (!config) {
// 2. if we reach here, the file is ts or using es import syntax.
// transpile es import syntax to require syntax using rollup.
const rollup = require('rollup') as typeof Rollup
const esbuilPlugin = await createEsbuildPlugin(false, {})
const bundle = await rollup.rollup({
external: (id: string) =>
(id[0] !== '.' && !path.isAbsolute(id)) ||
id.slice(-5, id.length) === '.json',
input: resolvedPath,
treeshake: false,
plugins: [esbuilPlugin]
})
const {
output: [{ code }]
} = await bundle.generate({
exports: 'named',
format: 'cjs'
})
config = await loadConfigFromBundledFile(resolvedPath, code)
}
// normalize config root to absolute
if (config.root && !path.isAbsolute(config.root)) {
config.root = path.resolve(path.dirname(resolvedPath), config.root)
}
// resolve plugins
if (config.plugins) {
for (const plugin of config.plugins) {
config = resolvePlugin(config, plugin)
}
}
// load environment variables
const envConfigPath = path.resolve(cwd, '.env')
if (fs.existsSync(envConfigPath) && fs.statSync(envConfigPath).isFile()) {
const env = require('dotenv').config()
if (env.error) {
throw env.error
}
config.env = env.parsed
}
require('debug')('vite:config')(
`config resolved in ${Date.now() - start}ms`
)
config.__path = resolvedPath
return config
} catch (e) {
console.error(
chalk.red(`[vite] failed to load config from ${resolvedPath}:`)
)
console.error(e)
process.exit(1)
}
}
interface NodeModuleWithCompile extends NodeModule {
_compile(code: string, filename: string): any
}
async function loadConfigFromBundledFile(
fileName: string,
bundledCode: string
): Promise<UserConfig> {
const extension = path.extname(fileName)
const defaultLoader = require.extensions[extension]!
require.extensions[extension] = (module: NodeModule, filename: string) => {
if (filename === fileName) {
;(module as NodeModuleWithCompile)._compile(bundledCode, filename)
} else {
defaultLoader(module, filename)
}
}
delete require.cache[fileName]
const raw = require(fileName)
const config = raw.__esModule ? raw.default : raw
require.extensions[extension] = defaultLoader
return config
}
function resolvePlugin(config: UserConfig, plugin: Plugin): UserConfig {
return {
...config,
alias: {
...plugin.alias,
...config.alias
},
transforms: [...(config.transforms || []), ...(plugin.transforms || [])],
resolvers: [...(config.resolvers || []), ...(plugin.resolvers || [])],
configureServer: ([] as any[]).concat(
config.configureServer || [],
plugin.configureServer || []
),
vueCompilerOptions: {
...config.vueCompilerOptions,
...plugin.vueCompilerOptions
},
rollupInputOptions: {
...config.rollupInputOptions,
...plugin.rollupInputOptions
},
rollupOutputOptions: {
...config.rollupOutputOptions,
...plugin.rollupOutputOptions
}
}
}
| src/node/config.ts | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00022818511934019625,
0.00016996037447825074,
0.0001644627918722108,
0.0001682093570707366,
0.00000939947767619742
] |
{
"id": 5,
"code_window": [
" const rollup = require('rollup').rollup as typeof Rollup\n",
" const bundle = await rollup({\n",
" input: path.resolve(root, 'index.html'),\n",
" preserveEntrySignatures: false,\n",
" treeshake: { moduleSideEffects: 'no-external' },\n",
" onwarn(warning, warn) {\n",
" if (warning.code !== 'CIRCULAR_DEPENDENCY') {\n",
" warn(warning)\n",
" }\n",
" },\n",
" ...rollupInputOptions,\n",
" plugins: [\n",
" ...basePlugins,\n",
" // vite:html\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" onwarn: onRollupWarning,\n"
],
"file_path": "src/node/build/index.ts",
"type": "replace",
"edit_start_line_idx": 206
} | import path from 'path'
import fs from 'fs-extra'
import chalk from 'chalk'
import { Ora } from 'ora'
import { resolveFrom } from '../utils'
import { rollup as Rollup, RollupOutput, ExternalOption, Plugin } from 'rollup'
import { createResolver, supportedExts, InternalResolver } from '../resolver'
import { createBuildResolvePlugin } from './buildPluginResolve'
import { createBuildHtmlPlugin } from './buildPluginHtml'
import { createBuildCssPlugin } from './buildPluginCss'
import { createBuildAssetPlugin } from './buildPluginAsset'
import { createEsbuildPlugin } from './buildPluginEsbuild'
import { createReplacePlugin } from './buildPluginReplace'
import { stopService } from '../esbuildService'
import { BuildConfig } from '../config'
import { createBuildJsTransformPlugin } from '../transform'
import hash_sum from 'hash-sum'
export interface BuildResult {
html: string
assets: RollupOutput['output']
}
const enum WriteType {
JS,
CSS,
ASSET,
HTML,
SOURCE_MAP
}
const writeColors = {
[WriteType.JS]: chalk.cyan,
[WriteType.CSS]: chalk.magenta,
[WriteType.ASSET]: chalk.green,
[WriteType.HTML]: chalk.blue,
[WriteType.SOURCE_MAP]: chalk.gray
}
/**
* Named exports detection logic from Snowpack
* MIT License
* https://github.com/pikapkg/snowpack/blob/master/LICENSE
*/
const PACKAGES_TO_AUTO_DETECT_EXPORTS = [
path.join('react', 'index.js'),
path.join('react-dom', 'index.js'),
'react-is',
'prop-types',
'scheduler',
'rxjs',
'exenv',
'body-scroll-lock'
]
function detectExports(root: string, id: string): string[] | undefined {
try {
const fileLoc = resolveFrom(root, id)
if (fs.existsSync(fileLoc)) {
return Object.keys(require(fileLoc)).filter((e) => e[0] !== '_')
}
} catch (err) {
// ignore
}
}
/**
* Creates non-application specific plugins that are shared between the main
* app and the dependencies. This is used by the `optimize` command to
* pre-bundle dependencies.
*/
export async function createBaseRollupPlugins(
root: string,
resolver: InternalResolver,
options: BuildConfig
): Promise<Plugin[]> {
const { rollupInputOptions = {}, transforms = [] } = options
const knownNamedExports: Record<string, string[]> = {
...options.rollupPluginCommonJSNamedExports
}
for (const id of PACKAGES_TO_AUTO_DETECT_EXPORTS) {
knownNamedExports[id] =
knownNamedExports[id] || detectExports(root, id) || []
}
return [
// user plugins
...(rollupInputOptions.plugins || []),
// vite:resolve
createBuildResolvePlugin(root, resolver),
// vite:esbuild
await createEsbuildPlugin(options.minify === 'esbuild', options.jsx),
// vue
require('rollup-plugin-vue')({
...options.rollupPluginVueOptions,
transformAssetUrls: {
includeAbsolute: true
},
preprocessStyles: true,
preprocessCustomRequire: (id: string) => require(resolveFrom(root, id)),
compilerOptions: options.vueCompilerOptions,
cssModulesOptions: {
generateScopedName: (local: string, filename: string) =>
`${local}_${hash_sum(filename)}`
}
}),
require('@rollup/plugin-json')({
preferConst: true,
indent: ' ',
compact: false,
namedExports: true
}),
// user transforms
...(transforms.length ? [createBuildJsTransformPlugin(transforms)] : []),
require('@rollup/plugin-node-resolve')({
rootDir: root,
extensions: supportedExts,
preferBuiltins: false
}),
require('@rollup/plugin-commonjs')({
extensions: ['.js', '.cjs'],
namedExports: knownNamedExports
})
].filter(Boolean)
}
/**
* Bundles the app for production.
* Returns a Promise containing the build result.
*/
export async function build(options: BuildConfig = {}): Promise<BuildResult> {
if (options.ssr) {
return ssrBuild({
...options,
ssr: false // since ssrBuild calls build, this avoids an infinite loop.
})
}
const isTest = process.env.NODE_ENV === 'test'
process.env.NODE_ENV = 'production'
const start = Date.now()
const {
root = process.cwd(),
base = '/',
outDir = path.resolve(root, 'dist'),
assetsDir = '_assets',
assetsInlineLimit = 4096,
cssCodeSplit = true,
alias = {},
transforms = [],
resolvers = [],
rollupInputOptions = {},
rollupOutputOptions = {},
emitIndex = true,
emitAssets = true,
write = true,
minify = true,
silent = false,
sourcemap = false,
shouldPreload = null,
env = {}
} = options
let spinner: Ora | undefined
const msg = 'Building for production...'
if (!silent) {
if (process.env.DEBUG || isTest) {
console.log(msg)
} else {
spinner = require('ora')(msg + '\n').start()
}
}
const indexPath = path.resolve(root, 'index.html')
const publicBasePath = base.replace(/([^/])$/, '$1/') // ensure ending slash
const resolvedAssetsPath = path.join(outDir, assetsDir)
const resolver = createResolver(root, resolvers, alias)
const { htmlPlugin, renderIndex } = await createBuildHtmlPlugin(
root,
indexPath,
publicBasePath,
assetsDir,
assetsInlineLimit,
resolver,
shouldPreload
)
const basePlugins = await createBaseRollupPlugins(root, resolver, options)
env.NODE_ENV = 'production'
const envReplacements = Object.keys(env).reduce((replacements, key) => {
replacements[`process.env.${key}`] = JSON.stringify(env[key])
return replacements
}, {} as Record<string, string>)
// lazy require rollup so that we don't load it when only using the dev server
// importing it just for the types
const rollup = require('rollup').rollup as typeof Rollup
const bundle = await rollup({
input: path.resolve(root, 'index.html'),
preserveEntrySignatures: false,
treeshake: { moduleSideEffects: 'no-external' },
onwarn(warning, warn) {
if (warning.code !== 'CIRCULAR_DEPENDENCY') {
warn(warning)
}
},
...rollupInputOptions,
plugins: [
...basePlugins,
// vite:html
htmlPlugin,
// we use a custom replacement plugin because @rollup/plugin-replace
// performs replacements twice, once at transform and once at renderChunk
// - which makes it impossible to exclude Vue templates from it since
// Vue templates are compiled into js and included in chunks.
createReplacePlugin(
{
...envReplacements,
'process.env.': `({}).`,
__DEV__: 'false',
__BASE__: JSON.stringify(publicBasePath)
},
sourcemap
),
// vite:css
createBuildCssPlugin(
root,
publicBasePath,
assetsDir,
minify,
assetsInlineLimit,
cssCodeSplit,
transforms
),
// vite:asset
createBuildAssetPlugin(
root,
publicBasePath,
assetsDir,
assetsInlineLimit
),
// minify with terser
// this is the default which has better compression, but slow
// the user can opt-in to use esbuild which is much faster but results
// in ~8-10% larger file size.
minify && minify !== 'esbuild'
? require('rollup-plugin-terser').terser()
: undefined
]
})
const { output } = await bundle.generate({
format: 'es',
sourcemap,
entryFileNames: `[name].[hash].js`,
chunkFileNames: `[name].[hash].js`,
...rollupOutputOptions
})
spinner && spinner.stop()
const cssFileName = output.find(
(a) => a.type === 'asset' && a.fileName.endsWith('.css')
)!.fileName
const indexHtml = emitIndex ? renderIndex(output, cssFileName) : ''
if (write) {
const cwd = process.cwd()
const writeFile = async (
filepath: string,
content: string | Uint8Array,
type: WriteType
) => {
await fs.ensureDir(path.dirname(filepath))
await fs.writeFile(filepath, content)
if (!silent) {
console.log(
`${chalk.gray(`[write]`)} ${writeColors[type](
path.relative(cwd, filepath)
)} ${(content.length / 1024).toFixed(2)}kb, brotli: ${(
require('brotli-size').sync(content) / 1024
).toFixed(2)}kb`
)
}
}
await fs.remove(outDir)
await fs.ensureDir(outDir)
// write js chunks and assets
for (const chunk of output) {
if (chunk.type === 'chunk') {
// write chunk
const filepath = path.join(resolvedAssetsPath, chunk.fileName)
let code = chunk.code
if (chunk.map) {
code += `\n//# sourceMappingURL=${path.basename(filepath)}.map`
}
await writeFile(filepath, code, WriteType.JS)
if (chunk.map) {
await writeFile(
filepath + '.map',
chunk.map.toString(),
WriteType.SOURCE_MAP
)
}
} else if (emitAssets) {
// write asset
const filepath = path.join(resolvedAssetsPath, chunk.fileName)
await writeFile(
filepath,
chunk.source,
chunk.fileName.endsWith('.css') ? WriteType.CSS : WriteType.ASSET
)
}
}
// write html
if (indexHtml && emitIndex) {
await writeFile(
path.join(outDir, 'index.html'),
indexHtml,
WriteType.HTML
)
}
// copy over /public if it exists
if (emitAssets) {
const publicDir = path.resolve(root, 'public')
if (fs.existsSync(publicDir)) {
await fs.copy(publicDir, path.resolve(outDir, 'public'))
}
}
}
if (!silent) {
console.log(
`Build completed in ${((Date.now() - start) / 1000).toFixed(2)}s.\n`
)
}
// stop the esbuild service after each build
stopService()
return {
assets: output,
html: indexHtml
}
}
/**
* Bundles the app in SSR mode.
* - All Vue dependencies are automatically externalized
* - Imports to dependencies are compiled into require() calls
* - Templates are compiled with SSR specific optimizations.
*/
export async function ssrBuild(
options: BuildConfig = {}
): Promise<BuildResult> {
const {
rollupInputOptions,
rollupOutputOptions,
rollupPluginVueOptions
} = options
return build({
outDir: path.resolve(options.root || process.cwd(), 'dist-ssr'),
assetsDir: '.',
...options,
rollupPluginVueOptions: {
...rollupPluginVueOptions,
target: 'node'
},
rollupInputOptions: {
...rollupInputOptions,
external: resolveExternal(
rollupInputOptions && rollupInputOptions.external
)
},
rollupOutputOptions: {
...rollupOutputOptions,
format: 'cjs',
exports: 'named',
entryFileNames: '[name].js'
},
emitIndex: false,
emitAssets: false,
cssCodeSplit: false,
minify: false
})
}
function resolveExternal(
userExternal: ExternalOption | undefined
): ExternalOption {
const required = ['vue', /^@vue\//]
if (!userExternal) {
return required
}
if (Array.isArray(userExternal)) {
return [...required, ...userExternal]
} else if (typeof userExternal === 'function') {
return (src, importer, isResolved) => {
if (src === 'vue' || /^@vue\//.test(src)) {
return true
}
return userExternal(src, importer, isResolved)
}
} else {
return [...required, userExternal]
}
}
| src/node/build/index.ts | 1 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.9984246492385864,
0.024755986407399178,
0.00016356137348338962,
0.00017361133359372616,
0.15206974744796753
] |
{
"id": 5,
"code_window": [
" const rollup = require('rollup').rollup as typeof Rollup\n",
" const bundle = await rollup({\n",
" input: path.resolve(root, 'index.html'),\n",
" preserveEntrySignatures: false,\n",
" treeshake: { moduleSideEffects: 'no-external' },\n",
" onwarn(warning, warn) {\n",
" if (warning.code !== 'CIRCULAR_DEPENDENCY') {\n",
" warn(warning)\n",
" }\n",
" },\n",
" ...rollupInputOptions,\n",
" plugins: [\n",
" ...basePlugins,\n",
" // vite:html\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" onwarn: onRollupWarning,\n"
],
"file_path": "src/node/build/index.ts",
"type": "replace",
"edit_start_line_idx": 206
} | #!/usr/bin/env node
require('../dist/cli')
| bin/vite.js | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.0001701085566310212,
0.0001701085566310212,
0.0001701085566310212,
0.0001701085566310212,
0
] |
{
"id": 5,
"code_window": [
" const rollup = require('rollup').rollup as typeof Rollup\n",
" const bundle = await rollup({\n",
" input: path.resolve(root, 'index.html'),\n",
" preserveEntrySignatures: false,\n",
" treeshake: { moduleSideEffects: 'no-external' },\n",
" onwarn(warning, warn) {\n",
" if (warning.code !== 'CIRCULAR_DEPENDENCY') {\n",
" warn(warning)\n",
" }\n",
" },\n",
" ...rollupInputOptions,\n",
" plugins: [\n",
" ...basePlugins,\n",
" // vite:html\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" onwarn: onRollupWarning,\n"
],
"file_path": "src/node/build/index.ts",
"type": "replace",
"edit_start_line_idx": 206
} | <template lang="pug">
h2 Pre-Processors
p.pug
| This is rendered from <template lang="pug">
| and styled with <style lang="sass">. It should be megenta.
</template>
<style lang="scss">
$color: magenta;
.pug {
color: $color;
}
</style>
| playground/TestPreprocessors.vue | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017545609443914145,
0.0001724799512885511,
0.00016950380813796073,
0.0001724799512885511,
0.00000297614315059036
] |
{
"id": 5,
"code_window": [
" const rollup = require('rollup').rollup as typeof Rollup\n",
" const bundle = await rollup({\n",
" input: path.resolve(root, 'index.html'),\n",
" preserveEntrySignatures: false,\n",
" treeshake: { moduleSideEffects: 'no-external' },\n",
" onwarn(warning, warn) {\n",
" if (warning.code !== 'CIRCULAR_DEPENDENCY') {\n",
" warn(warning)\n",
" }\n",
" },\n",
" ...rollupInputOptions,\n",
" plugins: [\n",
" ...basePlugins,\n",
" // vite:html\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" onwarn: onRollupWarning,\n"
],
"file_path": "src/node/build/index.ts",
"type": "replace",
"edit_start_line_idx": 206
} | {
"compilerOptions": {
"target": "esnext",
"moduleResolution": "node",
"strict": true,
"declaration": true,
"noUnusedLocals": true,
"esModuleInterop": true
}
}
| tsconfig.base.json | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017295009456574917,
0.00017232750542461872,
0.00017170491628348827,
0.00017232750542461872,
6.225891411304474e-7
] |
{
"id": 6,
"code_window": [
" // - which makes it impossible to exclude Vue templates from it since\n",
" // Vue templates are compiled into js and included in chunks.\n",
" createReplacePlugin(\n",
" {\n",
" ...envReplacements,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" (id) => /\\.(j|t)sx?$/.test(id),\n"
],
"file_path": "src/node/build/index.ts",
"type": "add",
"edit_start_line_idx": 221
} | import fs from 'fs-extra'
import path from 'path'
import { createHash } from 'crypto'
import { ResolvedConfig } from './config'
import type Rollup from 'rollup'
import {
createResolver,
supportedExts,
resolveNodeModuleEntry
} from './resolver'
import { createBaseRollupPlugins } from './build'
import { resolveFrom, lookupFile } from './utils'
import { init, parse } from 'es-module-lexer'
import chalk from 'chalk'
import { Ora } from 'ora'
import { createBuildCssPlugin } from './build/buildPluginCss'
const KNOWN_IGNORE_LIST = new Set([
'tailwindcss',
'@tailwindcss/ui',
'@pika/react',
'@pika/react-dom'
])
export interface DepOptimizationOptions {
/**
* Only optimize explicitly listed dependencies.
*/
include?: string[]
/**
* Do not optimize these dependencies.
*/
exclude?: string[]
/**
* Explicitly allow these CommonJS deps to be bundled.
*/
commonJSWhitelist?: string[]
/**
* Automatically run `vite optimize` on server start?
* @default true
*/
auto?: boolean
}
export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`
export async function optimizeDeps(
config: ResolvedConfig & { force?: boolean },
asCommand = false
) {
const debug = require('debug')('vite:optimize')
const log = asCommand ? console.log : debug
const root = config.root || process.cwd()
// warn presence of web_modules
if (fs.existsSync(path.join(root, 'web_modules'))) {
console.warn(
chalk.yellow(
`[vite] vite 0.15 has built-in dependency pre-bundling and resolving ` +
`from web_modules is no longer supported.`
)
)
}
const pkgPath = lookupFile(root, [`package.json`], true /* pathOnly */)
if (!pkgPath) {
log(`package.json not found. Skipping.`)
return
}
const cacheDir = resolveOptimizedCacheDir(root, pkgPath)!
const hashPath = path.join(cacheDir, 'hash')
const depHash = getDepHash(root, config.__path)
if (!config.force) {
let prevhash
try {
prevhash = await fs.readFile(hashPath, 'utf-8')
} catch (e) {}
// hash is consistent, no need to re-bundle
if (prevhash === depHash) {
log('Hash is consistent. Skipping. Use --force to override.')
return
}
}
await fs.remove(cacheDir)
await fs.ensureDir(cacheDir)
const deps = Object.keys(require(pkgPath).dependencies || {})
if (!deps.length) {
await fs.writeFile(hashPath, depHash)
log(`No dependencies listed in package.json. Skipping.`)
return
}
const resolver = createResolver(root, config.resolvers, config.alias)
const { include, exclude, commonJSWhitelist } = config.optimizeDeps || {}
// Determine deps to optimize. The goal is to only pre-bundle deps that falls
// under one of the following categories:
// 1. Has imports to relative files (e.g. lodash-es, lit-html)
// 2. Has imports to bare modules that are not in the project's own deps
// (i.e. esm that imports its own dependencies, e.g. styled-components)
await init
const cjsDeps: string[] = []
const qualifiedDeps = deps.filter((id) => {
if (include && !include.includes(id)) {
debug(`skipping ${id} (not included)`)
return false
}
if (exclude && exclude.includes(id)) {
debug(`skipping ${id} (excluded)`)
return false
}
if (commonJSWhitelist && commonJSWhitelist.includes(id)) {
debug(`optimizing ${id} (commonJSWhitelist)`)
return true
}
if (KNOWN_IGNORE_LIST.has(id)) {
debug(`skipping ${id} (internal excluded)`)
return false
}
const pkgInfo = resolveNodeModuleEntry(root, id)
if (!pkgInfo) {
debug(`skipping ${id} (cannot resolve entry)`)
return false
}
const [entry, pkg] = pkgInfo
if (!supportedExts.includes(path.extname(entry))) {
debug(`skipping ${id} (entry is not js)`)
return false
}
const content = fs.readFileSync(resolveFrom(root, entry), 'utf-8')
const [imports, exports] = parse(content)
if (!exports.length && !/export\s+\*\s+from/.test(content)) {
if (!pkg.module) {
cjsDeps.push(id)
}
debug(`skipping ${id} (no exports, likely commonjs)`)
return false
}
for (const { s, e } of imports) {
let i = content.slice(s, e).trim()
i = resolver.alias(i) || i
if (i.startsWith('.')) {
debug(`optimizing ${id} (contains relative imports)`)
return true
}
if (!deps.includes(i)) {
debug(`optimizing ${id} (imports sub dependencies)`)
return true
}
}
debug(`skipping ${id} (single esm file, doesn't need optimization)`)
})
if (!qualifiedDeps.length) {
if (!cjsDeps.length) {
await fs.writeFile(hashPath, depHash)
log(`No listed dependency requires optimization. Skipping.`)
} else {
console.error(
chalk.yellow(
`[vite] The following dependencies seem to be CommonJS modules that\n` +
`do not provide ESM-friendly file formats:\n\n ` +
cjsDeps.map((dep) => chalk.magenta(dep)).join(`\n `) +
`\n` +
`\n- If you are not using them in browser code, you can move them\n` +
`to devDependencies or exclude them from this check by adding\n` +
`them to ${chalk.cyan(
`optimizeDeps.exclude`
)} in vue.config.js.\n` +
`\n- If you do intend to use them in the browser, you can try adding\n` +
`them to ${chalk.cyan(
`optimizeDeps.commonJSWhitelist`
)} in vue.config.js but they\n` +
`may fail to bundle or work properly. Consider choosing more modern\n` +
`alternatives that provide ES module build formts.`
)
)
}
return
}
if (!asCommand) {
// This is auto run on server start - let the user know that we are
// pre-optimizing deps
console.log(chalk.greenBright(`[vite] Optimizable dependencies detected.`))
}
let spinner: Ora | undefined
const msg = asCommand
? `Pre-bundling dependencies to speed up dev server page load...`
: `Pre-bundling them to speed up dev server page load...\n` +
`(this will be run only when your dependencies have changed)`
if (process.env.DEBUG || process.env.NODE_ENV === 'test') {
console.log(msg)
} else {
spinner = require('ora')(msg + '\n').start()
}
try {
// Non qualified deps are marked as externals, since they will be preserved
// and resolved from their original node_modules locations.
const preservedDeps = deps
.filter((id) => !qualifiedDeps.includes(id))
// make sure aliased deps are external
// https://github.com/vitejs/vite-plugin-react/issues/4
.map((id) => resolver.alias(id) || id)
const input = qualifiedDeps.reduce((entries, name) => {
entries[name] = name
return entries
}, {} as Record<string, string>)
const rollup = require('rollup') as typeof Rollup
const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]
const bundle = await rollup.rollup({
input,
external: preservedDeps,
treeshake: { moduleSideEffects: 'no-external' },
onwarn(warning, warn) {
if (!warningIgnoreList.includes(warning.code!)) {
warn(warning)
}
},
...config.rollupInputOptions,
plugins: [
...(await createBaseRollupPlugins(root, resolver, config)),
createBuildCssPlugin(root, '/', 'assets')
]
})
const { output } = await bundle.generate({
...config.rollupOutputOptions,
format: 'es',
exports: 'named',
entryFileNames: '[name]',
chunkFileNames: 'common/[name]-[hash].js'
})
spinner && spinner.stop()
const optimized = []
for (const chunk of output) {
if (chunk.type === 'chunk') {
const fileName = chunk.fileName
const filePath = path.join(cacheDir, fileName)
await fs.ensureDir(path.dirname(filePath))
await fs.writeFile(filePath, chunk.code)
if (!fileName.startsWith('common/')) {
optimized.push(fileName.replace(/\.js$/, ''))
}
}
}
console.log(
`Optimized modules:\n${optimized
.map((id) => chalk.yellowBright(id))
.join(`, `)}`
)
await fs.writeFile(hashPath, depHash)
} catch (e) {
spinner && spinner.stop()
if (asCommand) {
throw e
} else {
console.error(chalk.red(`[vite] Dep optimization failed with error:`))
console.error(e)
console.log()
console.log(
chalk.yellow(
`Tip: You can configure what deps to include/exclude for optimization\n` +
`using the \`optimizeDeps\` option in the Vite config file.`
)
)
}
}
}
const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']
let cachedHash: string | undefined
export function getDepHash(
root: string,
configPath: string | undefined
): string {
if (cachedHash) {
return cachedHash
}
let content = lookupFile(root, lockfileFormats) || ''
const pkg = JSON.parse(lookupFile(root, [`package.json`]) || '{}')
content += JSON.stringify(pkg.dependencies)
// also take config into account
if (configPath) {
content += fs.readFileSync(configPath, 'utf-8')
}
return createHash('sha1').update(content).digest('base64')
}
const cacheDirCache = new Map<string, string | null>()
export function resolveOptimizedCacheDir(
root: string,
pkgPath?: string
): string | null {
const cached = cacheDirCache.get(root)
if (cached !== undefined) return cached
pkgPath = pkgPath || lookupFile(root, [`package.json`], true /* pathOnly */)
if (!pkgPath) {
return null
}
const cacheDir = path.join(path.dirname(pkgPath), OPTIMIZE_CACHE_DIR)
cacheDirCache.set(root, cacheDir)
return cacheDir
}
| src/node/depOptimizer.ts | 1 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.0005822040257044137,
0.00018944857583846897,
0.0001643104333197698,
0.0001717116974759847,
0.00007212303171399981
] |
{
"id": 6,
"code_window": [
" // - which makes it impossible to exclude Vue templates from it since\n",
" // Vue templates are compiled into js and included in chunks.\n",
" createReplacePlugin(\n",
" {\n",
" ...envReplacements,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" (id) => /\\.(j|t)sx?$/.test(id),\n"
],
"file_path": "src/node/build/index.ts",
"type": "add",
"edit_start_line_idx": 221
} | <template>
<h2>Transforms</h2>
<div class="transform-scss">This should be cyan</div>
<div class="transform-js">{{ transformed }}</div>
</template>
<script>
import './testTransform.scss'
import { __TEST_TRANSFORM__ } from './testTransform.js'
export default {
data() {
return {
transformed: __TEST_TRANSFORM__
}
}
}
</script>
| playground/TestTransform.vue | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017437779752071947,
0.00017088364984374493,
0.0001673895021667704,
0.00017088364984374493,
0.000003494147676974535
] |
{
"id": 6,
"code_window": [
" // - which makes it impossible to exclude Vue templates from it since\n",
" // Vue templates are compiled into js and included in chunks.\n",
" createReplacePlugin(\n",
" {\n",
" ...envReplacements,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" (id) => /\\.(j|t)sx?$/.test(id),\n"
],
"file_path": "src/node/build/index.ts",
"type": "add",
"edit_start_line_idx": 221
} | export const jsPlugin = {
transforms: [
{
test(id) {
return id.endsWith('testTransform.js')
},
transform(code) {
return code.replace(/__TEST_TRANSFORM__ = (\d)/, (matched, n) => {
return `__TEST_TRANSFORM__ = ${Number(n) + 1}`
})
}
}
]
}
| playground/plugins/jsPlugin.js | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017676940478850156,
0.00017624718020670116,
0.000175724970176816,
0.00017624718020670116,
5.22217305842787e-7
] |
{
"id": 6,
"code_window": [
" // - which makes it impossible to exclude Vue templates from it since\n",
" // Vue templates are compiled into js and included in chunks.\n",
" createReplacePlugin(\n",
" {\n",
" ...envReplacements,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
" (id) => /\\.(j|t)sx?$/.test(id),\n"
],
"file_path": "src/node/build/index.ts",
"type": "add",
"edit_start_line_idx": 221
} | import { ServerPlugin } from '.'
import {
tjsxRE,
transform,
resolveJsxOptions,
vueJsxPublicPath,
vueJsxFilePath
} from '../esbuildService'
import { readBody, genSourceMapString, cachedRead } from '../utils'
export const esbuildPlugin: ServerPlugin = ({ app, config }) => {
const jsxConfig = resolveJsxOptions(config.jsx)
app.use(async (ctx, next) => {
// intercept and return vue jsx helper import
if (ctx.path === vueJsxPublicPath) {
await cachedRead(ctx, vueJsxFilePath)
}
await next()
if (ctx.body && tjsxRE.test(ctx.path)) {
ctx.type = 'js'
const src = await readBody(ctx.body)
let { code, map } = await transform(src!, ctx.path, jsxConfig, config.jsx)
if (map) {
code += genSourceMapString(map)
}
ctx.body = code
}
})
}
| src/node/server/serverPluginEsbuild.ts | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.0001791760150808841,
0.0001745424378896132,
0.00016886483354028314,
0.00017506448784843087,
0.000004480144980334444
] |
{
"id": 7,
"code_window": [
" {\n",
" ...envReplacements,\n",
" 'process.env.': `({}).`,\n",
" __DEV__: 'false',\n",
" __BASE__: JSON.stringify(publicBasePath)\n",
" },\n",
" sourcemap\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'process.env.': `({}).`\n",
" },\n",
" sourcemap\n",
" ),\n",
" // for vite spcific replacements, make sure to only apply them to\n",
" // non-dependency code to avoid collision (e.g. #224 antd has __DEV__)\n",
" createReplacePlugin(\n",
" (id) => !id.includes('node_modules') && /\\.(j|t)sx?$/.test(id),\n",
" {\n",
" __DEV__: `false`,\n"
],
"file_path": "src/node/build/index.ts",
"type": "replace",
"edit_start_line_idx": 223
} | import path from 'path'
import fs from 'fs-extra'
import chalk from 'chalk'
import { Ora } from 'ora'
import { resolveFrom } from '../utils'
import { rollup as Rollup, RollupOutput, ExternalOption, Plugin } from 'rollup'
import { createResolver, supportedExts, InternalResolver } from '../resolver'
import { createBuildResolvePlugin } from './buildPluginResolve'
import { createBuildHtmlPlugin } from './buildPluginHtml'
import { createBuildCssPlugin } from './buildPluginCss'
import { createBuildAssetPlugin } from './buildPluginAsset'
import { createEsbuildPlugin } from './buildPluginEsbuild'
import { createReplacePlugin } from './buildPluginReplace'
import { stopService } from '../esbuildService'
import { BuildConfig } from '../config'
import { createBuildJsTransformPlugin } from '../transform'
import hash_sum from 'hash-sum'
export interface BuildResult {
html: string
assets: RollupOutput['output']
}
const enum WriteType {
JS,
CSS,
ASSET,
HTML,
SOURCE_MAP
}
const writeColors = {
[WriteType.JS]: chalk.cyan,
[WriteType.CSS]: chalk.magenta,
[WriteType.ASSET]: chalk.green,
[WriteType.HTML]: chalk.blue,
[WriteType.SOURCE_MAP]: chalk.gray
}
/**
* Named exports detection logic from Snowpack
* MIT License
* https://github.com/pikapkg/snowpack/blob/master/LICENSE
*/
const PACKAGES_TO_AUTO_DETECT_EXPORTS = [
path.join('react', 'index.js'),
path.join('react-dom', 'index.js'),
'react-is',
'prop-types',
'scheduler',
'rxjs',
'exenv',
'body-scroll-lock'
]
function detectExports(root: string, id: string): string[] | undefined {
try {
const fileLoc = resolveFrom(root, id)
if (fs.existsSync(fileLoc)) {
return Object.keys(require(fileLoc)).filter((e) => e[0] !== '_')
}
} catch (err) {
// ignore
}
}
/**
* Creates non-application specific plugins that are shared between the main
* app and the dependencies. This is used by the `optimize` command to
* pre-bundle dependencies.
*/
export async function createBaseRollupPlugins(
root: string,
resolver: InternalResolver,
options: BuildConfig
): Promise<Plugin[]> {
const { rollupInputOptions = {}, transforms = [] } = options
const knownNamedExports: Record<string, string[]> = {
...options.rollupPluginCommonJSNamedExports
}
for (const id of PACKAGES_TO_AUTO_DETECT_EXPORTS) {
knownNamedExports[id] =
knownNamedExports[id] || detectExports(root, id) || []
}
return [
// user plugins
...(rollupInputOptions.plugins || []),
// vite:resolve
createBuildResolvePlugin(root, resolver),
// vite:esbuild
await createEsbuildPlugin(options.minify === 'esbuild', options.jsx),
// vue
require('rollup-plugin-vue')({
...options.rollupPluginVueOptions,
transformAssetUrls: {
includeAbsolute: true
},
preprocessStyles: true,
preprocessCustomRequire: (id: string) => require(resolveFrom(root, id)),
compilerOptions: options.vueCompilerOptions,
cssModulesOptions: {
generateScopedName: (local: string, filename: string) =>
`${local}_${hash_sum(filename)}`
}
}),
require('@rollup/plugin-json')({
preferConst: true,
indent: ' ',
compact: false,
namedExports: true
}),
// user transforms
...(transforms.length ? [createBuildJsTransformPlugin(transforms)] : []),
require('@rollup/plugin-node-resolve')({
rootDir: root,
extensions: supportedExts,
preferBuiltins: false
}),
require('@rollup/plugin-commonjs')({
extensions: ['.js', '.cjs'],
namedExports: knownNamedExports
})
].filter(Boolean)
}
/**
* Bundles the app for production.
* Returns a Promise containing the build result.
*/
export async function build(options: BuildConfig = {}): Promise<BuildResult> {
if (options.ssr) {
return ssrBuild({
...options,
ssr: false // since ssrBuild calls build, this avoids an infinite loop.
})
}
const isTest = process.env.NODE_ENV === 'test'
process.env.NODE_ENV = 'production'
const start = Date.now()
const {
root = process.cwd(),
base = '/',
outDir = path.resolve(root, 'dist'),
assetsDir = '_assets',
assetsInlineLimit = 4096,
cssCodeSplit = true,
alias = {},
transforms = [],
resolvers = [],
rollupInputOptions = {},
rollupOutputOptions = {},
emitIndex = true,
emitAssets = true,
write = true,
minify = true,
silent = false,
sourcemap = false,
shouldPreload = null,
env = {}
} = options
let spinner: Ora | undefined
const msg = 'Building for production...'
if (!silent) {
if (process.env.DEBUG || isTest) {
console.log(msg)
} else {
spinner = require('ora')(msg + '\n').start()
}
}
const indexPath = path.resolve(root, 'index.html')
const publicBasePath = base.replace(/([^/])$/, '$1/') // ensure ending slash
const resolvedAssetsPath = path.join(outDir, assetsDir)
const resolver = createResolver(root, resolvers, alias)
const { htmlPlugin, renderIndex } = await createBuildHtmlPlugin(
root,
indexPath,
publicBasePath,
assetsDir,
assetsInlineLimit,
resolver,
shouldPreload
)
const basePlugins = await createBaseRollupPlugins(root, resolver, options)
env.NODE_ENV = 'production'
const envReplacements = Object.keys(env).reduce((replacements, key) => {
replacements[`process.env.${key}`] = JSON.stringify(env[key])
return replacements
}, {} as Record<string, string>)
// lazy require rollup so that we don't load it when only using the dev server
// importing it just for the types
const rollup = require('rollup').rollup as typeof Rollup
const bundle = await rollup({
input: path.resolve(root, 'index.html'),
preserveEntrySignatures: false,
treeshake: { moduleSideEffects: 'no-external' },
onwarn(warning, warn) {
if (warning.code !== 'CIRCULAR_DEPENDENCY') {
warn(warning)
}
},
...rollupInputOptions,
plugins: [
...basePlugins,
// vite:html
htmlPlugin,
// we use a custom replacement plugin because @rollup/plugin-replace
// performs replacements twice, once at transform and once at renderChunk
// - which makes it impossible to exclude Vue templates from it since
// Vue templates are compiled into js and included in chunks.
createReplacePlugin(
{
...envReplacements,
'process.env.': `({}).`,
__DEV__: 'false',
__BASE__: JSON.stringify(publicBasePath)
},
sourcemap
),
// vite:css
createBuildCssPlugin(
root,
publicBasePath,
assetsDir,
minify,
assetsInlineLimit,
cssCodeSplit,
transforms
),
// vite:asset
createBuildAssetPlugin(
root,
publicBasePath,
assetsDir,
assetsInlineLimit
),
// minify with terser
// this is the default which has better compression, but slow
// the user can opt-in to use esbuild which is much faster but results
// in ~8-10% larger file size.
minify && minify !== 'esbuild'
? require('rollup-plugin-terser').terser()
: undefined
]
})
const { output } = await bundle.generate({
format: 'es',
sourcemap,
entryFileNames: `[name].[hash].js`,
chunkFileNames: `[name].[hash].js`,
...rollupOutputOptions
})
spinner && spinner.stop()
const cssFileName = output.find(
(a) => a.type === 'asset' && a.fileName.endsWith('.css')
)!.fileName
const indexHtml = emitIndex ? renderIndex(output, cssFileName) : ''
if (write) {
const cwd = process.cwd()
const writeFile = async (
filepath: string,
content: string | Uint8Array,
type: WriteType
) => {
await fs.ensureDir(path.dirname(filepath))
await fs.writeFile(filepath, content)
if (!silent) {
console.log(
`${chalk.gray(`[write]`)} ${writeColors[type](
path.relative(cwd, filepath)
)} ${(content.length / 1024).toFixed(2)}kb, brotli: ${(
require('brotli-size').sync(content) / 1024
).toFixed(2)}kb`
)
}
}
await fs.remove(outDir)
await fs.ensureDir(outDir)
// write js chunks and assets
for (const chunk of output) {
if (chunk.type === 'chunk') {
// write chunk
const filepath = path.join(resolvedAssetsPath, chunk.fileName)
let code = chunk.code
if (chunk.map) {
code += `\n//# sourceMappingURL=${path.basename(filepath)}.map`
}
await writeFile(filepath, code, WriteType.JS)
if (chunk.map) {
await writeFile(
filepath + '.map',
chunk.map.toString(),
WriteType.SOURCE_MAP
)
}
} else if (emitAssets) {
// write asset
const filepath = path.join(resolvedAssetsPath, chunk.fileName)
await writeFile(
filepath,
chunk.source,
chunk.fileName.endsWith('.css') ? WriteType.CSS : WriteType.ASSET
)
}
}
// write html
if (indexHtml && emitIndex) {
await writeFile(
path.join(outDir, 'index.html'),
indexHtml,
WriteType.HTML
)
}
// copy over /public if it exists
if (emitAssets) {
const publicDir = path.resolve(root, 'public')
if (fs.existsSync(publicDir)) {
await fs.copy(publicDir, path.resolve(outDir, 'public'))
}
}
}
if (!silent) {
console.log(
`Build completed in ${((Date.now() - start) / 1000).toFixed(2)}s.\n`
)
}
// stop the esbuild service after each build
stopService()
return {
assets: output,
html: indexHtml
}
}
/**
* Bundles the app in SSR mode.
* - All Vue dependencies are automatically externalized
* - Imports to dependencies are compiled into require() calls
* - Templates are compiled with SSR specific optimizations.
*/
export async function ssrBuild(
options: BuildConfig = {}
): Promise<BuildResult> {
const {
rollupInputOptions,
rollupOutputOptions,
rollupPluginVueOptions
} = options
return build({
outDir: path.resolve(options.root || process.cwd(), 'dist-ssr'),
assetsDir: '.',
...options,
rollupPluginVueOptions: {
...rollupPluginVueOptions,
target: 'node'
},
rollupInputOptions: {
...rollupInputOptions,
external: resolveExternal(
rollupInputOptions && rollupInputOptions.external
)
},
rollupOutputOptions: {
...rollupOutputOptions,
format: 'cjs',
exports: 'named',
entryFileNames: '[name].js'
},
emitIndex: false,
emitAssets: false,
cssCodeSplit: false,
minify: false
})
}
function resolveExternal(
userExternal: ExternalOption | undefined
): ExternalOption {
const required = ['vue', /^@vue\//]
if (!userExternal) {
return required
}
if (Array.isArray(userExternal)) {
return [...required, ...userExternal]
} else if (typeof userExternal === 'function') {
return (src, importer, isResolved) => {
if (src === 'vue' || /^@vue\//.test(src)) {
return true
}
return userExternal(src, importer, isResolved)
}
} else {
return [...required, userExternal]
}
}
| src/node/build/index.ts | 1 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.9826177954673767,
0.02407170832157135,
0.00016346843040082604,
0.00017062654660549015,
0.149704709649086
] |
{
"id": 7,
"code_window": [
" {\n",
" ...envReplacements,\n",
" 'process.env.': `({}).`,\n",
" __DEV__: 'false',\n",
" __BASE__: JSON.stringify(publicBasePath)\n",
" },\n",
" sourcemap\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'process.env.': `({}).`\n",
" },\n",
" sourcemap\n",
" ),\n",
" // for vite spcific replacements, make sure to only apply them to\n",
" // non-dependency code to avoid collision (e.g. #224 antd has __DEV__)\n",
" createReplacePlugin(\n",
" (id) => !id.includes('node_modules') && /\\.(j|t)sx?$/.test(id),\n",
" {\n",
" __DEV__: `false`,\n"
],
"file_path": "src/node/build/index.ts",
"type": "replace",
"edit_start_line_idx": 223
} | import { createApp } from 'vue'
import App from './App.vue'
import './testHmrManual'
createApp(App).mount('#app')
| playground/main.js | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.0001714559184620157,
0.0001714559184620157,
0.0001714559184620157,
0.0001714559184620157,
0
] |
{
"id": 7,
"code_window": [
" {\n",
" ...envReplacements,\n",
" 'process.env.': `({}).`,\n",
" __DEV__: 'false',\n",
" __BASE__: JSON.stringify(publicBasePath)\n",
" },\n",
" sourcemap\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'process.env.': `({}).`\n",
" },\n",
" sourcemap\n",
" ),\n",
" // for vite spcific replacements, make sure to only apply them to\n",
" // non-dependency code to avoid collision (e.g. #224 antd has __DEV__)\n",
" createReplacePlugin(\n",
" (id) => !id.includes('node_modules') && /\\.(j|t)sx?$/.test(id),\n",
" {\n",
" __DEV__: `false`,\n"
],
"file_path": "src/node/build/index.ts",
"type": "replace",
"edit_start_line_idx": 223
} | environment:
nodejs_version: '12'
install:
- ps: Install-Product node $env:nodejs_version x64
- yarn
test_script:
- git --version
- node --version
- yarn --version
- yarn build
- yarn test
- yarn test-sw
cache:
- node_modules -> yarn.lock
build: off
| appveyor.yml | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00021125473722349852,
0.00019212576444260776,
0.00017299677710980177,
0.00019212576444260776,
0.000019128980056848377
] |
{
"id": 7,
"code_window": [
" {\n",
" ...envReplacements,\n",
" 'process.env.': `({}).`,\n",
" __DEV__: 'false',\n",
" __BASE__: JSON.stringify(publicBasePath)\n",
" },\n",
" sourcemap\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" 'process.env.': `({}).`\n",
" },\n",
" sourcemap\n",
" ),\n",
" // for vite spcific replacements, make sure to only apply them to\n",
" // non-dependency code to avoid collision (e.g. #224 antd has __DEV__)\n",
" createReplacePlugin(\n",
" (id) => !id.includes('node_modules') && /\\.(j|t)sx?$/.test(id),\n",
" {\n",
" __DEV__: `false`,\n"
],
"file_path": "src/node/build/index.ts",
"type": "replace",
"edit_start_line_idx": 223
} | <template>
<h2>Static Asset Handling</h2>
<p>
Fonts should be italic if font asset reference from CSS works.
</p>
<p class="asset-import">
Path for assets import from js: <code>{{ filepath }}</code>
</p>
<p>
Relative asset reference in template:
<img src="../testAssets.png" style="width: 30px;" />
</p>
<p>
Absolute asset reference in template:
<img src="/public/icon.png" style="width: 30px;" />
</p>
<div class="css-bg">
<span style="background: #fff;">CSS background</span>
</div>
<div class="css-import-bg">
<span style="background: #fff;">CSS background with relative paths</span>
</div>
<div class="css-bg-data-uri">
<span style="background: #fff;">CSS background with Data URI</span>
</div>
</template>
<script>
import './testAssets.css'
import filepath from '../testAssets.png'
export default {
data() {
return {
filepath
}
}
}
</script>
<style>
@font-face {
font-family: 'Inter';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url('../fonts/Inter-Italic.woff2') format('woff2'),
url('/fonts/Inter-Italic.woff') format('woff');
}
body {
font-family: 'Inter';
}
.css-bg {
background: url(/public/icon.png);
background-size: 10px;
}
.css-bg-data-uri {
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA0CAYAAADWr1sfAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTM4IDc5LjE1OTgyNCwgMjAxNi8wOS8xNC0wMTowOTowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NTAyNkI1RkE4N0VCMTFFQUFBQzJENzUzNDFGRjc1N0UiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NTAyNkI1Rjk4N0VCMTFFQUFBQzJENzUzNDFGRjc1N0UiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChNYWNpbnRvc2gpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6QTc3NzA2Q0Y4N0FCMTFFM0I3MERFRTAzNzcwNkMxMjMiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6QTc3NzA2RDA4N0FCMTFFM0I3MERFRTAzNzcwNkMxMjMiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6nwnGxAAAJtklEQVR42txZ6W9c1RU/970373nsJHgZ27FThahSV8BCqGQTlIQ2EiUBReqHVpT8Af0r+NA/ogpqqWiDKrZuKYQPLGEpAlEFiqOgICSUBOKQhDjxeGY885bb37n3TGKPZ+4bx0uWK53Ec+cu53fPfkbtfu13B4noF6AQVAEpah0ak3cUSBU8qh46RfWj50ltKJDXXyBKdMtibI+TXlLqm2C87y/+eO/vlVIVnWbUcShFyld8T19ypvLbZKpyALOjVPCqrUcT1mWXYtIzMUV7Rqn315tJJyk+J51OZwb7QA3QkQD/fAL6JWiIXKMOhkOPwp1DFE/OkJ6NAQxn+fhuPhaFOc8DE9loern+hD9SfJVCdaLdOy5gif9rpHfyHp3pCX5cs6X1PfnORkr+SA9FO4bsgkZm1ykngm8ZK06ll0EvgWY6SwDn1fGKcykVfriewh2D5oKskhhw5KmFzLO0MJdO1yfS87UD2Uxc0tXErM+qLYQ5XUspK8el9JvagXSmPmH2W4lfG3wHNMHciXnmIfj+OvCVga8sD+yMYHyZAZ8H/Qk06dySaiNljf/DB0vklWAB1RQqnS0WA18eQE0Dz0++rjyRluOJDHuzWkwZNAPgLPHfPIeHTK/EEzHWKt/zDdh2asBmUUnJg3TDB0rQIuYptby5x6RgPO/JxIes304p44V1DMAzKQUbe4xqa62h2vbFyWuxeUie1RKqvVmXG/sxOaYKPqliQKp3HmEOB43pWaxJaTPvUV6rdK3Z6FloGUt35yD54EGXEwvaU3nSPSIYF7D5T/mio1rzS7Jaa1we4YWDzb1GUpptqJ1OGUl7BJX+jS7HP/OKEPlgRH5/SP5AZMjrCTz+jtdQQckxauEZ/IZ4bKyhYEsv7h6GpmGuhnsznafORwQbtQKGY6F/gy64pMxPnF2JSQ33UM/ecWNX/PJG3RbYsn15qCiYTQdhr49j9m4jQd8zXlkFZv3d/B087SBM4OodC+5kJYIX5r09+8ZIDYYAn4gqOdFeEEwn2gFmMb0BesEpZeOxARAOJ4SXjLbDlljKcbaQ0ebwrRNLy409oH1Xz1H2xrRc3wfaYx1dm/sgQTyYMZ1wZ4nC+4es76gnC3lqP14QTFk7wDymQH8DnXKCZibKiQHY89gY+aUeGwcT66xaw40JMUnWn52t7NWVeKt5GNaUarw1naruxXn9Rrrz9jRjLsd5PtsfZY3aaBZo9tT5qnxKsExRizto59EOccRzJQomHAC0DzsOHxwy3lvXk8VxU1u1VJFPaSW5B177SRtfNaVnq08izNyjQl9UefFe4zNwdoTI4I8XTfznu3NUORYMiyKP10HvD4neZy7VzqBaHEOjnw5TsKnXfgaDRjKqxWuzzRKtTy/Wt2W1ZAukuyX9tr4Ns+vZpheAVfKoOCuDKrNzDB8Ysp9Znd2qnAnvh9r5I8+hDs86HRhfCIlyQqGgbuHDI0Sz9gHaZj0sQXhhpJhbktOVp5Kvak/x31Sg9rarRXVxXvjwKJxk0Z7N/sOjPEf1bCez7LS1Ji/0iduBAUAD6JDpRFsHqfDjDZRdTqyU26gn2ykkXUovzf2KCV66ZGxXL9YeVtsMMb9w1x0U/WTAADWqnGO4wvMhwdA14PmqfbLjClZdTkaqCFPrAor2byIvUsZrd5Syp4BaFYW8RUmDeG8+wwsVRY+Pk7c+MJpkChXfCfhkJ1XuBjCPV0Bvt0nhFwoPiQfbVjixgaKHho3qGSlbgIu9ti/VEdHifJkdVc2aRoizwnv7kT+nNuy5hxZeX3EtygM8DfoX6FPnCcxL1Yap6NGNCCFFk5x0ETra2i7v9TcWqbh3zIbASmzvcHP7qfA6vRzAJIH7JWeYktRPz2a2bHuoZKpEdjgWdBeoWboMTpwea4o3GiF1lXzZPWLh8Y3ca7oAPAd6E/RubjLCkgBz4fYhCu6cl2d73UmX13KSUcDecNugqX2Np9a5mvKu8Di3EoB5HAP9WboGnZMRFiiXb0MhhYjNOrbeVsc5DPPexEqXz+C9HufLHHPT3PyxIbwd6wZIt4DnxCG81lG1JT9miZiaGeVj8L0+m3I2UrdaezY/z65Auj9ab0vPNLOlp+fEGwtPb3cj3aUA5nEWdDA3GTGMpqT6AupFmLLpYWaL9Hag2XZZdVHqcR1cfGzchDhdyWwFpnKTjIPCG600YFad96S+rHeOzZ5tB7Et3jeItLNk8+Fa2j6jYnU2YSyhaNcwFe4dMHv5DD7L1WUTXt5zmtoyADe7Bwfn15cdHZix3cxIzB+ObC+q2Z1Q6pq0E6gynF0A715ErasbqQWbH9JOCC8zSwGwVMA8Phb3X3a2g5BnZ5cRT78Dj7trxMRR7liY+lhdu5ntVnFDFLm4N1a0nr2e5rVtysLDx0tl/noAc9X7TLNH5KxZuC1Tg6puH0SYKtoaumFrYWPbsS0xg+/2UbjVVkNXW67u8aHwkKwFYB6fgQ47nYXXBBSbEBPtGjUtnWy6YcEm/F1q5sLdkO5AQTonuap8Vu7+7HoYv17APF4Fve6KrabEkzhcuH+AAuTFGmmjkeScbdsU7hswxGtMkqJzM7PX5W5aa8BfSDdwyt30I9Nw44qn+MgYef1IKC42SLN9D4TU8+iYCWGmKSfdEceYkju/uBGAebwvDW53KcOeFxlYcBeqqd3DBiznyCHCUPCDdUTsweM0765M7np/OQwvF/A5aYOedDcKmo23zP5qsalovTfny9wL4xQyP18+KXedu5GAmx0G9pizrsrAJCOQsuovUPTIKIU/HzG/SPKczks97dnPODswXY5gBQDXxK72g3a0fURT5yoTY7nw5w6ksVcAzZq/C7mbcv+TO2rLZXYlJMzjtNjXBedN7IlBXuibtq3ph8W5vw1dkLNPrwSjKwWY89oXQf9xNgqaXruaWLulXK8cy5kvOvP3GwC4mWc/50wImj+xaLrmpFRugvPcUvPltQJMUr0cXcHzjpLrF82bAHBN1O+dFTjrHTmrdjMD5vER6B/LZLQmZ3y00sytBuC65LtvLeOMt+SM+q0AmMekNNbK17G3LHsnV4Ox1QLM4wNRy3gJe2LZ88FqMbWagL8CPe2sptpXQ0/L3lsOMGcW3Cv+O+hyF+svy9pjsveWA9z0tn8Afd7F2s9lbW01GVptwJxTHZfE3/Uj17SsOU7ddLRuYsDN8decDOyorFn1sVaAvyT7k8iZNt+dke++vJ0A8+CfMw+3mT8s39HtBviSgDs+b+64zF26HQHz+C/o+Xmfn5c5ul0BXyT7w/U5oTdlbs1GQGs/vgb9cd7fazr+L8AAD0zRYMSYHQAAAAAASUVORK5CYII=);
background-size: 10px;
}
</style>
| playground/test-assets/TestAssets.vue | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.0002806716656778008,
0.00018735190678853542,
0.00016859406605362892,
0.00017266636132262647,
0.000038179528928594664
] |
{
"id": 8,
"code_window": [
"import {\n",
" createResolver,\n",
" supportedExts,\n",
" resolveNodeModuleEntry\n",
"} from './resolver'\n",
"import { createBaseRollupPlugins } from './build'\n",
"import { resolveFrom, lookupFile } from './utils'\n",
"import { init, parse } from 'es-module-lexer'\n",
"import chalk from 'chalk'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createBaseRollupPlugins, onRollupWarning } from './build'\n"
],
"file_path": "src/node/depOptimizer.ts",
"type": "replace",
"edit_start_line_idx": 10
} | import path from 'path'
import fs from 'fs-extra'
import chalk from 'chalk'
import { Ora } from 'ora'
import { resolveFrom } from '../utils'
import { rollup as Rollup, RollupOutput, ExternalOption, Plugin } from 'rollup'
import { createResolver, supportedExts, InternalResolver } from '../resolver'
import { createBuildResolvePlugin } from './buildPluginResolve'
import { createBuildHtmlPlugin } from './buildPluginHtml'
import { createBuildCssPlugin } from './buildPluginCss'
import { createBuildAssetPlugin } from './buildPluginAsset'
import { createEsbuildPlugin } from './buildPluginEsbuild'
import { createReplacePlugin } from './buildPluginReplace'
import { stopService } from '../esbuildService'
import { BuildConfig } from '../config'
import { createBuildJsTransformPlugin } from '../transform'
import hash_sum from 'hash-sum'
export interface BuildResult {
html: string
assets: RollupOutput['output']
}
const enum WriteType {
JS,
CSS,
ASSET,
HTML,
SOURCE_MAP
}
const writeColors = {
[WriteType.JS]: chalk.cyan,
[WriteType.CSS]: chalk.magenta,
[WriteType.ASSET]: chalk.green,
[WriteType.HTML]: chalk.blue,
[WriteType.SOURCE_MAP]: chalk.gray
}
/**
* Named exports detection logic from Snowpack
* MIT License
* https://github.com/pikapkg/snowpack/blob/master/LICENSE
*/
const PACKAGES_TO_AUTO_DETECT_EXPORTS = [
path.join('react', 'index.js'),
path.join('react-dom', 'index.js'),
'react-is',
'prop-types',
'scheduler',
'rxjs',
'exenv',
'body-scroll-lock'
]
function detectExports(root: string, id: string): string[] | undefined {
try {
const fileLoc = resolveFrom(root, id)
if (fs.existsSync(fileLoc)) {
return Object.keys(require(fileLoc)).filter((e) => e[0] !== '_')
}
} catch (err) {
// ignore
}
}
/**
* Creates non-application specific plugins that are shared between the main
* app and the dependencies. This is used by the `optimize` command to
* pre-bundle dependencies.
*/
export async function createBaseRollupPlugins(
root: string,
resolver: InternalResolver,
options: BuildConfig
): Promise<Plugin[]> {
const { rollupInputOptions = {}, transforms = [] } = options
const knownNamedExports: Record<string, string[]> = {
...options.rollupPluginCommonJSNamedExports
}
for (const id of PACKAGES_TO_AUTO_DETECT_EXPORTS) {
knownNamedExports[id] =
knownNamedExports[id] || detectExports(root, id) || []
}
return [
// user plugins
...(rollupInputOptions.plugins || []),
// vite:resolve
createBuildResolvePlugin(root, resolver),
// vite:esbuild
await createEsbuildPlugin(options.minify === 'esbuild', options.jsx),
// vue
require('rollup-plugin-vue')({
...options.rollupPluginVueOptions,
transformAssetUrls: {
includeAbsolute: true
},
preprocessStyles: true,
preprocessCustomRequire: (id: string) => require(resolveFrom(root, id)),
compilerOptions: options.vueCompilerOptions,
cssModulesOptions: {
generateScopedName: (local: string, filename: string) =>
`${local}_${hash_sum(filename)}`
}
}),
require('@rollup/plugin-json')({
preferConst: true,
indent: ' ',
compact: false,
namedExports: true
}),
// user transforms
...(transforms.length ? [createBuildJsTransformPlugin(transforms)] : []),
require('@rollup/plugin-node-resolve')({
rootDir: root,
extensions: supportedExts,
preferBuiltins: false
}),
require('@rollup/plugin-commonjs')({
extensions: ['.js', '.cjs'],
namedExports: knownNamedExports
})
].filter(Boolean)
}
/**
* Bundles the app for production.
* Returns a Promise containing the build result.
*/
export async function build(options: BuildConfig = {}): Promise<BuildResult> {
if (options.ssr) {
return ssrBuild({
...options,
ssr: false // since ssrBuild calls build, this avoids an infinite loop.
})
}
const isTest = process.env.NODE_ENV === 'test'
process.env.NODE_ENV = 'production'
const start = Date.now()
const {
root = process.cwd(),
base = '/',
outDir = path.resolve(root, 'dist'),
assetsDir = '_assets',
assetsInlineLimit = 4096,
cssCodeSplit = true,
alias = {},
transforms = [],
resolvers = [],
rollupInputOptions = {},
rollupOutputOptions = {},
emitIndex = true,
emitAssets = true,
write = true,
minify = true,
silent = false,
sourcemap = false,
shouldPreload = null,
env = {}
} = options
let spinner: Ora | undefined
const msg = 'Building for production...'
if (!silent) {
if (process.env.DEBUG || isTest) {
console.log(msg)
} else {
spinner = require('ora')(msg + '\n').start()
}
}
const indexPath = path.resolve(root, 'index.html')
const publicBasePath = base.replace(/([^/])$/, '$1/') // ensure ending slash
const resolvedAssetsPath = path.join(outDir, assetsDir)
const resolver = createResolver(root, resolvers, alias)
const { htmlPlugin, renderIndex } = await createBuildHtmlPlugin(
root,
indexPath,
publicBasePath,
assetsDir,
assetsInlineLimit,
resolver,
shouldPreload
)
const basePlugins = await createBaseRollupPlugins(root, resolver, options)
env.NODE_ENV = 'production'
const envReplacements = Object.keys(env).reduce((replacements, key) => {
replacements[`process.env.${key}`] = JSON.stringify(env[key])
return replacements
}, {} as Record<string, string>)
// lazy require rollup so that we don't load it when only using the dev server
// importing it just for the types
const rollup = require('rollup').rollup as typeof Rollup
const bundle = await rollup({
input: path.resolve(root, 'index.html'),
preserveEntrySignatures: false,
treeshake: { moduleSideEffects: 'no-external' },
onwarn(warning, warn) {
if (warning.code !== 'CIRCULAR_DEPENDENCY') {
warn(warning)
}
},
...rollupInputOptions,
plugins: [
...basePlugins,
// vite:html
htmlPlugin,
// we use a custom replacement plugin because @rollup/plugin-replace
// performs replacements twice, once at transform and once at renderChunk
// - which makes it impossible to exclude Vue templates from it since
// Vue templates are compiled into js and included in chunks.
createReplacePlugin(
{
...envReplacements,
'process.env.': `({}).`,
__DEV__: 'false',
__BASE__: JSON.stringify(publicBasePath)
},
sourcemap
),
// vite:css
createBuildCssPlugin(
root,
publicBasePath,
assetsDir,
minify,
assetsInlineLimit,
cssCodeSplit,
transforms
),
// vite:asset
createBuildAssetPlugin(
root,
publicBasePath,
assetsDir,
assetsInlineLimit
),
// minify with terser
// this is the default which has better compression, but slow
// the user can opt-in to use esbuild which is much faster but results
// in ~8-10% larger file size.
minify && minify !== 'esbuild'
? require('rollup-plugin-terser').terser()
: undefined
]
})
const { output } = await bundle.generate({
format: 'es',
sourcemap,
entryFileNames: `[name].[hash].js`,
chunkFileNames: `[name].[hash].js`,
...rollupOutputOptions
})
spinner && spinner.stop()
const cssFileName = output.find(
(a) => a.type === 'asset' && a.fileName.endsWith('.css')
)!.fileName
const indexHtml = emitIndex ? renderIndex(output, cssFileName) : ''
if (write) {
const cwd = process.cwd()
const writeFile = async (
filepath: string,
content: string | Uint8Array,
type: WriteType
) => {
await fs.ensureDir(path.dirname(filepath))
await fs.writeFile(filepath, content)
if (!silent) {
console.log(
`${chalk.gray(`[write]`)} ${writeColors[type](
path.relative(cwd, filepath)
)} ${(content.length / 1024).toFixed(2)}kb, brotli: ${(
require('brotli-size').sync(content) / 1024
).toFixed(2)}kb`
)
}
}
await fs.remove(outDir)
await fs.ensureDir(outDir)
// write js chunks and assets
for (const chunk of output) {
if (chunk.type === 'chunk') {
// write chunk
const filepath = path.join(resolvedAssetsPath, chunk.fileName)
let code = chunk.code
if (chunk.map) {
code += `\n//# sourceMappingURL=${path.basename(filepath)}.map`
}
await writeFile(filepath, code, WriteType.JS)
if (chunk.map) {
await writeFile(
filepath + '.map',
chunk.map.toString(),
WriteType.SOURCE_MAP
)
}
} else if (emitAssets) {
// write asset
const filepath = path.join(resolvedAssetsPath, chunk.fileName)
await writeFile(
filepath,
chunk.source,
chunk.fileName.endsWith('.css') ? WriteType.CSS : WriteType.ASSET
)
}
}
// write html
if (indexHtml && emitIndex) {
await writeFile(
path.join(outDir, 'index.html'),
indexHtml,
WriteType.HTML
)
}
// copy over /public if it exists
if (emitAssets) {
const publicDir = path.resolve(root, 'public')
if (fs.existsSync(publicDir)) {
await fs.copy(publicDir, path.resolve(outDir, 'public'))
}
}
}
if (!silent) {
console.log(
`Build completed in ${((Date.now() - start) / 1000).toFixed(2)}s.\n`
)
}
// stop the esbuild service after each build
stopService()
return {
assets: output,
html: indexHtml
}
}
/**
* Bundles the app in SSR mode.
* - All Vue dependencies are automatically externalized
* - Imports to dependencies are compiled into require() calls
* - Templates are compiled with SSR specific optimizations.
*/
export async function ssrBuild(
options: BuildConfig = {}
): Promise<BuildResult> {
const {
rollupInputOptions,
rollupOutputOptions,
rollupPluginVueOptions
} = options
return build({
outDir: path.resolve(options.root || process.cwd(), 'dist-ssr'),
assetsDir: '.',
...options,
rollupPluginVueOptions: {
...rollupPluginVueOptions,
target: 'node'
},
rollupInputOptions: {
...rollupInputOptions,
external: resolveExternal(
rollupInputOptions && rollupInputOptions.external
)
},
rollupOutputOptions: {
...rollupOutputOptions,
format: 'cjs',
exports: 'named',
entryFileNames: '[name].js'
},
emitIndex: false,
emitAssets: false,
cssCodeSplit: false,
minify: false
})
}
function resolveExternal(
userExternal: ExternalOption | undefined
): ExternalOption {
const required = ['vue', /^@vue\//]
if (!userExternal) {
return required
}
if (Array.isArray(userExternal)) {
return [...required, ...userExternal]
} else if (typeof userExternal === 'function') {
return (src, importer, isResolved) => {
if (src === 'vue' || /^@vue\//.test(src)) {
return true
}
return userExternal(src, importer, isResolved)
}
} else {
return [...required, userExternal]
}
}
| src/node/build/index.ts | 1 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.010649326257407665,
0.0009161699563264847,
0.00016294819943141192,
0.00017722122720442712,
0.0019147377461194992
] |
{
"id": 8,
"code_window": [
"import {\n",
" createResolver,\n",
" supportedExts,\n",
" resolveNodeModuleEntry\n",
"} from './resolver'\n",
"import { createBaseRollupPlugins } from './build'\n",
"import { resolveFrom, lookupFile } from './utils'\n",
"import { init, parse } from 'es-module-lexer'\n",
"import chalk from 'chalk'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createBaseRollupPlugins, onRollupWarning } from './build'\n"
],
"file_path": "src/node/depOptimizer.ts",
"type": "replace",
"edit_start_line_idx": 10
} | .DS_Store
node_modules
dist
dist-ssr
TODOs.md
*.log
test/temp
explorations
.idea
| .gitignore | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.0001659166009631008,
0.0001659166009631008,
0.0001659166009631008,
0.0001659166009631008,
0
] |
{
"id": 8,
"code_window": [
"import {\n",
" createResolver,\n",
" supportedExts,\n",
" resolveNodeModuleEntry\n",
"} from './resolver'\n",
"import { createBaseRollupPlugins } from './build'\n",
"import { resolveFrom, lookupFile } from './utils'\n",
"import { init, parse } from 'es-module-lexer'\n",
"import chalk from 'chalk'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createBaseRollupPlugins, onRollupWarning } from './build'\n"
],
"file_path": "src/node/depOptimizer.ts",
"type": "replace",
"edit_start_line_idx": 10
} | import { ServerPlugin } from '.'
import { readBody, isImportRequest } from '../utils'
export const jsonPlugin: ServerPlugin = ({ app }) => {
app.use(async (ctx, next) => {
await next()
// handle .json imports
// note ctx.body could be null if upstream set status to 304
if (ctx.path.endsWith('.json') && isImportRequest(ctx) && ctx.body) {
ctx.type = 'js'
ctx.body = `export default ${await readBody(ctx.body)}`
}
})
}
| src/node/server/serverPluginJson.ts | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017361927893944085,
0.00017161553842015564,
0.00016961181245278567,
0.00017161553842015564,
0.000002003733243327588
] |
{
"id": 8,
"code_window": [
"import {\n",
" createResolver,\n",
" supportedExts,\n",
" resolveNodeModuleEntry\n",
"} from './resolver'\n",
"import { createBaseRollupPlugins } from './build'\n",
"import { resolveFrom, lookupFile } from './utils'\n",
"import { init, parse } from 'es-module-lexer'\n",
"import chalk from 'chalk'\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { createBaseRollupPlugins, onRollupWarning } from './build'\n"
],
"file_path": "src/node/depOptimizer.ts",
"type": "replace",
"edit_start_line_idx": 10
} | <template>
<h2>Hot Module Replacement</h2>
<p>
<span>
HMR: click button and edit template part of <code>./TestHmr.vue</code>,
count should not reset
</span>
<button class="hmr-increment" @click="count++">
>>> {{ count }} <<<
</button>
</p>
<p>
<span>
HMR: edit the return value of <code>foo()</code> in
<code>./testHmrPropagation.js</code>, should update without reloading
page:
</span>
<span class="hmr-propagation">{{ foo() }}</span>
</p>
<p>
HMR: manual API (see console) - edit <code>./testHmrManual.js</code> and it
should log new exported value without reloading the page.
</p>
</template>
<script>
import { foo } from './testHmrPropagation'
export default {
setup() {
return {
count: 0,
foo
}
}
}
</script>
| playground/TestHmr.vue | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017676806601230055,
0.00017109984764829278,
0.00016299233539029956,
0.00017231950187124312,
0.000005028204213886056
] |
{
"id": 9,
"code_window": [
" }, {} as Record<string, string>)\n",
"\n",
" const rollup = require('rollup') as typeof Rollup\n",
" const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]\n",
" const bundle = await rollup.rollup({\n",
" input,\n",
" external: preservedDeps,\n",
" treeshake: { moduleSideEffects: 'no-external' },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/node/depOptimizer.ts",
"type": "replace",
"edit_start_line_idx": 216
} | import fs from 'fs-extra'
import path from 'path'
import { createHash } from 'crypto'
import { ResolvedConfig } from './config'
import type Rollup from 'rollup'
import {
createResolver,
supportedExts,
resolveNodeModuleEntry
} from './resolver'
import { createBaseRollupPlugins } from './build'
import { resolveFrom, lookupFile } from './utils'
import { init, parse } from 'es-module-lexer'
import chalk from 'chalk'
import { Ora } from 'ora'
import { createBuildCssPlugin } from './build/buildPluginCss'
const KNOWN_IGNORE_LIST = new Set([
'tailwindcss',
'@tailwindcss/ui',
'@pika/react',
'@pika/react-dom'
])
export interface DepOptimizationOptions {
/**
* Only optimize explicitly listed dependencies.
*/
include?: string[]
/**
* Do not optimize these dependencies.
*/
exclude?: string[]
/**
* Explicitly allow these CommonJS deps to be bundled.
*/
commonJSWhitelist?: string[]
/**
* Automatically run `vite optimize` on server start?
* @default true
*/
auto?: boolean
}
export const OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`
export async function optimizeDeps(
config: ResolvedConfig & { force?: boolean },
asCommand = false
) {
const debug = require('debug')('vite:optimize')
const log = asCommand ? console.log : debug
const root = config.root || process.cwd()
// warn presence of web_modules
if (fs.existsSync(path.join(root, 'web_modules'))) {
console.warn(
chalk.yellow(
`[vite] vite 0.15 has built-in dependency pre-bundling and resolving ` +
`from web_modules is no longer supported.`
)
)
}
const pkgPath = lookupFile(root, [`package.json`], true /* pathOnly */)
if (!pkgPath) {
log(`package.json not found. Skipping.`)
return
}
const cacheDir = resolveOptimizedCacheDir(root, pkgPath)!
const hashPath = path.join(cacheDir, 'hash')
const depHash = getDepHash(root, config.__path)
if (!config.force) {
let prevhash
try {
prevhash = await fs.readFile(hashPath, 'utf-8')
} catch (e) {}
// hash is consistent, no need to re-bundle
if (prevhash === depHash) {
log('Hash is consistent. Skipping. Use --force to override.')
return
}
}
await fs.remove(cacheDir)
await fs.ensureDir(cacheDir)
const deps = Object.keys(require(pkgPath).dependencies || {})
if (!deps.length) {
await fs.writeFile(hashPath, depHash)
log(`No dependencies listed in package.json. Skipping.`)
return
}
const resolver = createResolver(root, config.resolvers, config.alias)
const { include, exclude, commonJSWhitelist } = config.optimizeDeps || {}
// Determine deps to optimize. The goal is to only pre-bundle deps that falls
// under one of the following categories:
// 1. Has imports to relative files (e.g. lodash-es, lit-html)
// 2. Has imports to bare modules that are not in the project's own deps
// (i.e. esm that imports its own dependencies, e.g. styled-components)
await init
const cjsDeps: string[] = []
const qualifiedDeps = deps.filter((id) => {
if (include && !include.includes(id)) {
debug(`skipping ${id} (not included)`)
return false
}
if (exclude && exclude.includes(id)) {
debug(`skipping ${id} (excluded)`)
return false
}
if (commonJSWhitelist && commonJSWhitelist.includes(id)) {
debug(`optimizing ${id} (commonJSWhitelist)`)
return true
}
if (KNOWN_IGNORE_LIST.has(id)) {
debug(`skipping ${id} (internal excluded)`)
return false
}
const pkgInfo = resolveNodeModuleEntry(root, id)
if (!pkgInfo) {
debug(`skipping ${id} (cannot resolve entry)`)
return false
}
const [entry, pkg] = pkgInfo
if (!supportedExts.includes(path.extname(entry))) {
debug(`skipping ${id} (entry is not js)`)
return false
}
const content = fs.readFileSync(resolveFrom(root, entry), 'utf-8')
const [imports, exports] = parse(content)
if (!exports.length && !/export\s+\*\s+from/.test(content)) {
if (!pkg.module) {
cjsDeps.push(id)
}
debug(`skipping ${id} (no exports, likely commonjs)`)
return false
}
for (const { s, e } of imports) {
let i = content.slice(s, e).trim()
i = resolver.alias(i) || i
if (i.startsWith('.')) {
debug(`optimizing ${id} (contains relative imports)`)
return true
}
if (!deps.includes(i)) {
debug(`optimizing ${id} (imports sub dependencies)`)
return true
}
}
debug(`skipping ${id} (single esm file, doesn't need optimization)`)
})
if (!qualifiedDeps.length) {
if (!cjsDeps.length) {
await fs.writeFile(hashPath, depHash)
log(`No listed dependency requires optimization. Skipping.`)
} else {
console.error(
chalk.yellow(
`[vite] The following dependencies seem to be CommonJS modules that\n` +
`do not provide ESM-friendly file formats:\n\n ` +
cjsDeps.map((dep) => chalk.magenta(dep)).join(`\n `) +
`\n` +
`\n- If you are not using them in browser code, you can move them\n` +
`to devDependencies or exclude them from this check by adding\n` +
`them to ${chalk.cyan(
`optimizeDeps.exclude`
)} in vue.config.js.\n` +
`\n- If you do intend to use them in the browser, you can try adding\n` +
`them to ${chalk.cyan(
`optimizeDeps.commonJSWhitelist`
)} in vue.config.js but they\n` +
`may fail to bundle or work properly. Consider choosing more modern\n` +
`alternatives that provide ES module build formts.`
)
)
}
return
}
if (!asCommand) {
// This is auto run on server start - let the user know that we are
// pre-optimizing deps
console.log(chalk.greenBright(`[vite] Optimizable dependencies detected.`))
}
let spinner: Ora | undefined
const msg = asCommand
? `Pre-bundling dependencies to speed up dev server page load...`
: `Pre-bundling them to speed up dev server page load...\n` +
`(this will be run only when your dependencies have changed)`
if (process.env.DEBUG || process.env.NODE_ENV === 'test') {
console.log(msg)
} else {
spinner = require('ora')(msg + '\n').start()
}
try {
// Non qualified deps are marked as externals, since they will be preserved
// and resolved from their original node_modules locations.
const preservedDeps = deps
.filter((id) => !qualifiedDeps.includes(id))
// make sure aliased deps are external
// https://github.com/vitejs/vite-plugin-react/issues/4
.map((id) => resolver.alias(id) || id)
const input = qualifiedDeps.reduce((entries, name) => {
entries[name] = name
return entries
}, {} as Record<string, string>)
const rollup = require('rollup') as typeof Rollup
const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]
const bundle = await rollup.rollup({
input,
external: preservedDeps,
treeshake: { moduleSideEffects: 'no-external' },
onwarn(warning, warn) {
if (!warningIgnoreList.includes(warning.code!)) {
warn(warning)
}
},
...config.rollupInputOptions,
plugins: [
...(await createBaseRollupPlugins(root, resolver, config)),
createBuildCssPlugin(root, '/', 'assets')
]
})
const { output } = await bundle.generate({
...config.rollupOutputOptions,
format: 'es',
exports: 'named',
entryFileNames: '[name]',
chunkFileNames: 'common/[name]-[hash].js'
})
spinner && spinner.stop()
const optimized = []
for (const chunk of output) {
if (chunk.type === 'chunk') {
const fileName = chunk.fileName
const filePath = path.join(cacheDir, fileName)
await fs.ensureDir(path.dirname(filePath))
await fs.writeFile(filePath, chunk.code)
if (!fileName.startsWith('common/')) {
optimized.push(fileName.replace(/\.js$/, ''))
}
}
}
console.log(
`Optimized modules:\n${optimized
.map((id) => chalk.yellowBright(id))
.join(`, `)}`
)
await fs.writeFile(hashPath, depHash)
} catch (e) {
spinner && spinner.stop()
if (asCommand) {
throw e
} else {
console.error(chalk.red(`[vite] Dep optimization failed with error:`))
console.error(e)
console.log()
console.log(
chalk.yellow(
`Tip: You can configure what deps to include/exclude for optimization\n` +
`using the \`optimizeDeps\` option in the Vite config file.`
)
)
}
}
}
const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']
let cachedHash: string | undefined
export function getDepHash(
root: string,
configPath: string | undefined
): string {
if (cachedHash) {
return cachedHash
}
let content = lookupFile(root, lockfileFormats) || ''
const pkg = JSON.parse(lookupFile(root, [`package.json`]) || '{}')
content += JSON.stringify(pkg.dependencies)
// also take config into account
if (configPath) {
content += fs.readFileSync(configPath, 'utf-8')
}
return createHash('sha1').update(content).digest('base64')
}
const cacheDirCache = new Map<string, string | null>()
export function resolveOptimizedCacheDir(
root: string,
pkgPath?: string
): string | null {
const cached = cacheDirCache.get(root)
if (cached !== undefined) return cached
pkgPath = pkgPath || lookupFile(root, [`package.json`], true /* pathOnly */)
if (!pkgPath) {
return null
}
const cacheDir = path.join(path.dirname(pkgPath), OPTIMIZE_CACHE_DIR)
cacheDirCache.set(root, cacheDir)
return cacheDir
}
| src/node/depOptimizer.ts | 1 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.9988144636154175,
0.09385062009096146,
0.0001643602445255965,
0.00017360998026560992,
0.2908592224121094
] |
{
"id": 9,
"code_window": [
" }, {} as Record<string, string>)\n",
"\n",
" const rollup = require('rollup') as typeof Rollup\n",
" const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]\n",
" const bundle = await rollup.rollup({\n",
" input,\n",
" external: preservedDeps,\n",
" treeshake: { moduleSideEffects: 'no-external' },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/node/depOptimizer.ts",
"type": "replace",
"edit_start_line_idx": 216
} | import path from 'path'
import fs from 'fs-extra'
import { Plugin, OutputBundle } from 'rollup'
import { isStaticAsset } from '../utils'
import hash_sum from 'hash-sum'
import slash from 'slash'
import mime from 'mime-types'
const debug = require('debug')('vite:build:asset')
interface AssetCacheEntry {
content: Buffer | null
fileName: string | null
url: string
}
const assetResolveCache = new Map<string, AssetCacheEntry>()
export const resolveAsset = async (
id: string,
root: string,
publicBase: string,
assetsDir: string,
inlineLimit: number
): Promise<AssetCacheEntry> => {
const cached = assetResolveCache.get(id)
if (cached) {
return cached
}
let resolved: AssetCacheEntry | undefined
const pathFromRoot = path.relative(root, id)
if (/^public(\/|\\)/.test(pathFromRoot)) {
// assets inside the public directory will be copied over verbatim
// so all we need to do is just append the baseDir
resolved = {
content: null,
fileName: null,
url: slash(path.join(publicBase, pathFromRoot))
}
}
if (!resolved) {
const ext = path.extname(id)
const baseName = path.basename(id, ext)
const resolvedFileName = `${baseName}.${hash_sum(id)}${ext}`
let url = slash(path.join(publicBase, assetsDir, resolvedFileName))
const content = await fs.readFile(id)
if (!id.endsWith(`.svg`) && content.length < Number(inlineLimit)) {
url = `data:${mime.lookup(id)};base64,${content.toString('base64')}`
}
resolved = {
content,
fileName: resolvedFileName,
url
}
}
assetResolveCache.set(id, resolved)
return resolved
}
export const registerAssets = (
assets: Map<string, Buffer>,
bundle: OutputBundle
) => {
for (const [fileName, source] of assets) {
bundle[fileName] = {
isAsset: true,
type: 'asset',
fileName,
source
}
}
}
export const createBuildAssetPlugin = (
root: string,
publicBase: string,
assetsDir: string,
inlineLimit: number
): Plugin => {
const assets = new Map<string, Buffer>()
return {
name: 'vite:asset',
async load(id) {
if (isStaticAsset(id)) {
const { fileName, content, url } = await resolveAsset(
id,
root,
publicBase,
assetsDir,
inlineLimit
)
if (fileName && content) {
assets.set(fileName, content)
}
debug(`${id} -> ${url.startsWith('data:') ? `base64 inlined` : url}`)
return `export default ${JSON.stringify(url)}`
}
},
generateBundle(_options, bundle) {
registerAssets(assets, bundle)
}
}
}
| src/node/build/buildPluginAsset.ts | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.9974976181983948,
0.1634201854467392,
0.00016623965348117054,
0.00017197230772580951,
0.36445558071136475
] |
{
"id": 9,
"code_window": [
" }, {} as Record<string, string>)\n",
"\n",
" const rollup = require('rollup') as typeof Rollup\n",
" const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]\n",
" const bundle = await rollup.rollup({\n",
" input,\n",
" external: preservedDeps,\n",
" treeshake: { moduleSideEffects: 'no-external' },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/node/depOptimizer.ts",
"type": "replace",
"edit_start_line_idx": 216
} | import path from 'path'
import fs from 'fs-extra'
import LRUCache from 'lru-cache'
import { Context } from 'koa'
import { Readable } from 'stream'
import { seenUrls } from '../server/serverPluginServeStatic'
const getETag = require('etag')
interface CacheEntry {
lastModified: number
etag: string
content: string
}
const moduleReadCache = new LRUCache<string, CacheEntry>({
max: 10000
})
/**
* Read a file with in-memory cache.
* Also sets appropriate headers and body on the Koa context.
*/
export async function cachedRead(
ctx: Context | null,
file: string
): Promise<string> {
const lastModified = fs.statSync(file).mtimeMs
const cached = moduleReadCache.get(file)
if (ctx) {
ctx.set('Cache-Control', 'no-cache')
ctx.type = path.extname(file) || 'js'
}
if (cached && cached.lastModified === lastModified) {
if (ctx) {
ctx.etag = cached.etag
ctx.lastModified = new Date(cached.lastModified)
if (
ctx.__serviceWorker !== true &&
ctx.get('If-None-Match') === ctx.etag &&
seenUrls.has(ctx.url)
) {
ctx.status = 304
}
seenUrls.add(ctx.url)
ctx.body = cached.content
}
return cached.content
}
const content = await fs.readFile(file, 'utf-8')
const etag = getETag(content)
moduleReadCache.set(file, {
content,
etag,
lastModified
})
if (ctx) {
ctx.etag = etag
ctx.lastModified = new Date(lastModified)
ctx.body = content
ctx.status = 200
}
return content
}
/**
* Read already set body on a Koa context and normalize it into a string.
* Useful in post-processing middlewares.
*/
export async function readBody(
stream: Readable | Buffer | string | null
): Promise<string | null> {
if (stream instanceof Readable) {
return new Promise((resolve, reject) => {
let res = ''
stream
.on('data', (chunk) => (res += chunk))
.on('error', reject)
.on('end', () => {
resolve(res)
})
})
} else {
return !stream || typeof stream === 'string' ? stream : stream.toString()
}
}
export function lookupFile(
dir: string,
formats: string[],
pathOnly = false
): string | undefined {
for (const format of formats) {
const fullPath = path.join(dir, format)
if (fs.existsSync(fullPath)) {
return pathOnly ? fullPath : fs.readFileSync(fullPath, 'utf-8')
}
}
const parentDir = path.dirname(dir)
if (parentDir !== dir) {
return lookupFile(parentDir, formats, pathOnly)
}
}
| src/node/utils/fsUtils.ts | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00032264250330626965,
0.0001844267244450748,
0.00016547359700780362,
0.00017187511548399925,
0.00004382370025268756
] |
{
"id": 9,
"code_window": [
" }, {} as Record<string, string>)\n",
"\n",
" const rollup = require('rollup') as typeof Rollup\n",
" const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]\n",
" const bundle = await rollup.rollup({\n",
" input,\n",
" external: preservedDeps,\n",
" treeshake: { moduleSideEffects: 'no-external' },\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/node/depOptimizer.ts",
"type": "replace",
"edit_start_line_idx": 216
} | import { hot } from 'vite/hmr'
export const foo = 1
if (__DEV__) {
hot.dispose(() => {
console.log(`(dep) foo was: ${foo}`)
})
}
| playground/testHmrManualDep.js | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017319482867605984,
0.00017319482867605984,
0.00017319482867605984,
0.00017319482867605984,
0
] |
{
"id": 10,
"code_window": [
" const bundle = await rollup.rollup({\n",
" input,\n",
" external: preservedDeps,\n",
" treeshake: { moduleSideEffects: 'no-external' },\n",
" onwarn(warning, warn) {\n",
" if (!warningIgnoreList.includes(warning.code!)) {\n",
" warn(warning)\n",
" }\n",
" },\n",
" ...config.rollupInputOptions,\n",
" plugins: [\n",
" ...(await createBaseRollupPlugins(root, resolver, config)),\n",
" createBuildCssPlugin(root, '/', 'assets')\n",
" ]\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" onwarn: onRollupWarning,\n"
],
"file_path": "src/node/depOptimizer.ts",
"type": "replace",
"edit_start_line_idx": 221
} | import { Plugin, TransformResult } from 'rollup'
import MagicString from 'magic-string'
const filter = /\.(j|t)sx?$/
export const createReplacePlugin = (
replacements: Record<string, string>,
sourcemap: boolean
): Plugin => {
const pattern = new RegExp(
'\\b(' +
Object.keys(replacements)
.map((str) => {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&')
})
.join('|') +
')\\b',
'g'
)
return {
name: 'vite:replace',
transform(code, id) {
if (filter.test(id)) {
const s = new MagicString(code)
let hasReplaced = false
let match
while ((match = pattern.exec(code))) {
hasReplaced = true
const start = match.index
const end = start + match[0].length
const replacement = replacements[match[1]]
s.overwrite(start, end, replacement)
}
if (!hasReplaced) {
return null
}
const result: TransformResult = { code: s.toString() }
if (sourcemap) {
result.map = s.generateMap({ hires: true })
}
return result
}
}
}
}
| src/node/build/buildPluginReplace.ts | 1 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00019956103642471135,
0.00018078912398777902,
0.00017425000260118395,
0.00017692639084998518,
0.000009516922546026763
] |
{
"id": 10,
"code_window": [
" const bundle = await rollup.rollup({\n",
" input,\n",
" external: preservedDeps,\n",
" treeshake: { moduleSideEffects: 'no-external' },\n",
" onwarn(warning, warn) {\n",
" if (!warningIgnoreList.includes(warning.code!)) {\n",
" warn(warning)\n",
" }\n",
" },\n",
" ...config.rollupInputOptions,\n",
" plugins: [\n",
" ...(await createBaseRollupPlugins(root, resolver, config)),\n",
" createBuildCssPlugin(root, '/', 'assets')\n",
" ]\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" onwarn: onRollupWarning,\n"
],
"file_path": "src/node/depOptimizer.ts",
"type": "replace",
"edit_start_line_idx": 221
} | import path from 'path'
import { Plugin } from 'rollup'
import { resolveAsset, registerAssets } from './buildPluginAsset'
import { loadPostcssConfig, parseWithQuery } from '../utils'
import { Transform, BuildConfig } from '../config'
import hash_sum from 'hash-sum'
import { urlRE, rewriteCssUrls } from '../utils/cssUtils'
const debug = require('debug')('vite:build:css')
const cssInjectionMarker = `__VITE_CSS__`
const cssInjectionRE = /__VITE_CSS__\(\)/g
export const createBuildCssPlugin = (
root: string,
publicBase: string,
assetsDir: string,
minify: BuildConfig['minify'] = false,
inlineLimit = 0,
cssCodeSplit = true,
transforms: Transform[] = []
): Plugin => {
const styles: Map<string, string> = new Map()
const assets = new Map<string, Buffer>()
transforms = transforms.filter((t) => t.as === 'css')
return {
name: 'vite:css',
async transform(css: string, id: string) {
let transformed = false
if (transforms.length) {
const { path, query } = parseWithQuery(id)
for (const t of transforms) {
if (t.test(path, query)) {
css = await t.transform(css, true, true, path, query)
transformed = true
break
}
}
}
if (transformed || id.endsWith('.css')) {
// process url() - register referenced files as assets
// and rewrite the url to the resolved public path
if (urlRE.test(css)) {
const fileDir = path.dirname(id)
css = await rewriteCssUrls(css, async (rawUrl) => {
const file = path.posix.isAbsolute(rawUrl)
? path.join(root, rawUrl)
: path.join(fileDir, rawUrl)
const { fileName, content, url } = await resolveAsset(
file,
root,
publicBase,
assetsDir,
inlineLimit
)
if (fileName && content) {
assets.set(fileName, content)
}
debug(
`url(${rawUrl}) -> ${
url.startsWith('data:') ? `base64 inlined` : `url(${url})`
}`
)
return url
})
}
// postcss
let modules
const postcssConfig = await loadPostcssConfig(root)
const expectsModule = id.endsWith('.module.css')
if (postcssConfig || expectsModule) {
try {
const result = await require('postcss')([
...((postcssConfig && postcssConfig.plugins) || []),
...(expectsModule
? [
require('postcss-modules')({
generateScopedName: `[local]_${hash_sum(id)}`,
getJSON(_: string, json: Record<string, string>) {
modules = json
}
})
]
: [])
]).process(css, {
...(postcssConfig && postcssConfig.options),
from: id
})
css = result.css
} catch (e) {
console.error(`[vite] error applying postcss transforms: `, e)
}
}
styles.set(id, css)
return {
code: modules
? `export default ${JSON.stringify(modules)}`
: cssCodeSplit
? // If code-splitting CSS, inject a fake marker to avoid the module
// from being tree-shaken. This preserves the .css file as a
// module in the chunk's metadata so that we can retrive them in
// renderChunk.
`${cssInjectionMarker}()\n`
: ``,
map: null
}
}
},
async renderChunk(code, chunk) {
if (!cssCodeSplit) {
return null
}
// for each dynamic entry chunk, collect its css and inline it as JS
// strings.
if (chunk.isDynamicEntry) {
let chunkCSS = ''
for (const id in chunk.modules) {
if (styles.has(id)) {
chunkCSS += styles.get(id)
styles.delete(id) // remove inlined css
}
}
chunkCSS = await minifyCSS(chunkCSS)
let isFirst = true
code = code.replace(cssInjectionRE, () => {
if (isFirst) {
isFirst = false
// make sure the code is in one line so that source map is preserved.
return (
`let ${cssInjectionMarker} = document.createElement('style');` +
`${cssInjectionMarker}.innerHTML = ${JSON.stringify(chunkCSS)};` +
`document.head.appendChild(${cssInjectionMarker});`
)
} else {
return ''
}
})
} else {
code = code.replace(cssInjectionRE, '')
}
return {
code,
map: null
}
},
async generateBundle(_options, bundle) {
let css = ''
// finalize extracted css
styles.forEach((s) => {
css += s
})
// minify with cssnano
if (minify) {
css = await minifyCSS(css)
}
const cssFileName = `style.${hash_sum(css)}.css`
bundle[cssFileName] = {
isAsset: true,
type: 'asset',
fileName: cssFileName,
source: css
}
registerAssets(assets, bundle)
}
}
}
let postcss: any
let cssnano: any
async function minifyCSS(css: string) {
postcss = postcss || require('postcss')
cssnano = cssnano || require('cssnano')
return (await postcss(cssnano).process(css, { from: undefined })).css
}
| src/node/build/buildPluginCss.ts | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.005778040271252394,
0.0005870143068023026,
0.0001616834051674232,
0.00017671362729743123,
0.0012528117513284087
] |
{
"id": 10,
"code_window": [
" const bundle = await rollup.rollup({\n",
" input,\n",
" external: preservedDeps,\n",
" treeshake: { moduleSideEffects: 'no-external' },\n",
" onwarn(warning, warn) {\n",
" if (!warningIgnoreList.includes(warning.code!)) {\n",
" warn(warning)\n",
" }\n",
" },\n",
" ...config.rollupInputOptions,\n",
" plugins: [\n",
" ...(await createBaseRollupPlugins(root, resolver, config)),\n",
" createBuildCssPlugin(root, '/', 'assets')\n",
" ]\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" onwarn: onRollupWarning,\n"
],
"file_path": "src/node/depOptimizer.ts",
"type": "replace",
"edit_start_line_idx": 221
} | <template lang="pug">
h2 Pre-Processors
p.pug
| This is rendered from <template lang="pug">
| and styled with <style lang="sass">. It should be megenta.
</template>
<style lang="scss">
$color: magenta;
.pug {
color: $color;
}
</style>
| playground/TestPreprocessors.vue | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00017618801211938262,
0.00017526320880278945,
0.00017433840548619628,
0.00017526320880278945,
9.248033165931702e-7
] |
{
"id": 10,
"code_window": [
" const bundle = await rollup.rollup({\n",
" input,\n",
" external: preservedDeps,\n",
" treeshake: { moduleSideEffects: 'no-external' },\n",
" onwarn(warning, warn) {\n",
" if (!warningIgnoreList.includes(warning.code!)) {\n",
" warn(warning)\n",
" }\n",
" },\n",
" ...config.rollupInputOptions,\n",
" plugins: [\n",
" ...(await createBaseRollupPlugins(root, resolver, config)),\n",
" createBuildCssPlugin(root, '/', 'assets')\n",
" ]\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" onwarn: onRollupWarning,\n"
],
"file_path": "src/node/depOptimizer.ts",
"type": "replace",
"edit_start_line_idx": 221
} | export const __TEST_TRANSFORM__ = 1
| playground/testTransform.js | 0 | https://github.com/vitejs/vite/commit/b96ed689970a1c0ab87f21c7cdf7d72a12c493c2 | [
0.00016806600615382195,
0.00016806600615382195,
0.00016806600615382195,
0.00016806600615382195,
0
] |
{
"id": 0,
"code_window": [
" ' \"$COMMIT_MESSAGE\")\n",
"\n",
" git commit -m \"$COMMIT_MESSAGE\"\n",
" done\n",
" LAST_COMMIT_MESSAGE=$(git show -s --format=%B)\n",
" echo \"::set-output name=PR_TITLE::$LAST_COMMIT_MESSAGE\"\n",
" - name: Prepare branch\n",
" id: prepare-branch\n",
" run: |\n",
" BRANCH_NAME=\"cherry-pick-${{ github.event.inputs.version }}-$(date +%Y-%m-%d-%H-%M-%S)\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"PR_TITLE=$LAST_COMMIT_MESSAGE\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/cherry_pick_into_release_branch.yml",
"type": "replace",
"edit_start_line_idx": 50
} | name: Roll Browser into Playwright
on:
repository_dispatch:
types: [roll_into_pw]
jobs:
roll:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 14
- run: npm i -g npm@8
- run: npm ci
- run: npm run build
- name: Install dependencies
run: npx playwright install-deps
- name: Roll to new revision
run: |
./utils/roll_browser.js ${{ github.event.client_payload.browser }} ${{ github.event.client_payload.revision }}
npm run build
- name: Prepare branch
id: prepare-branch
run: |
BRANCH_NAME="roll-into-pw-${{ github.event.client_payload.browser }}/${{ github.event.client_payload.revision }}"
echo "::set-output name=BRANCH_NAME::$BRANCH_NAME"
git config --global user.name github-actions
git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com
git checkout -b "$BRANCH_NAME"
git add .
git commit -m "feat(${{ github.event.client_payload.browser }}): roll to r${{ github.event.client_payload.revision }}"
git push origin $BRANCH_NAME
- name: Create Pull Request
uses: actions/github-script@v6
with:
github-token: ${{ secrets.REPOSITORY_DISPATCH_PERSONAL_ACCESS_TOKEN }}
script: |
const response = await github.rest.pulls.create({
owner: 'microsoft',
repo: 'playwright',
head: 'microsoft:${{ steps.prepare-branch.outputs.BRANCH_NAME }}',
base: 'main',
title: 'feat(${{ github.event.client_payload.browser }}): roll to r${{ github.event.client_payload.revision }}',
});
await github.rest.issues.addLabels({
owner: 'microsoft',
repo: 'playwright',
issue_number: response.data.number,
labels: ['CQ1'],
});
| .github/workflows/roll_browser_into_playwright.yml | 1 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.00203692982904613,
0.0005973789957351983,
0.00016966972907539457,
0.00019184418488293886,
0.000684981350786984
] |
{
"id": 0,
"code_window": [
" ' \"$COMMIT_MESSAGE\")\n",
"\n",
" git commit -m \"$COMMIT_MESSAGE\"\n",
" done\n",
" LAST_COMMIT_MESSAGE=$(git show -s --format=%B)\n",
" echo \"::set-output name=PR_TITLE::$LAST_COMMIT_MESSAGE\"\n",
" - name: Prepare branch\n",
" id: prepare-branch\n",
" run: |\n",
" BRANCH_NAME=\"cherry-pick-${{ github.event.inputs.version }}-$(date +%Y-%m-%d-%H-%M-%S)\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"PR_TITLE=$LAST_COMMIT_MESSAGE\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/cherry_pick_into_release_branch.yml",
"type": "replace",
"edit_start_line_idx": 50
} | # -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
# vim: set filetype=python:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
XPIDL_SOURCES += [
'nsIScreencastService.idl',
]
XPIDL_MODULE = 'jugglerscreencast'
SOURCES += [
'HeadlessWindowCapturer.cpp',
'nsScreencastService.cpp',
'ScreencastEncoder.cpp',
]
XPCOM_MANIFESTS += [
'components.conf',
]
LOCAL_INCLUDES += [
'/dom/media/systemservices',
'/media/libyuv/libyuv/include',
'/third_party/libwebrtc',
'/third_party/libwebrtc/third_party/abseil-cpp',
]
LOCAL_INCLUDES += [
'/widget',
'/widget/headless',
]
LOCAL_INCLUDES += [
'/third_party/aom/third_party/libwebm',
]
SOURCES += [
'/third_party/aom/third_party/libwebm/mkvmuxer/mkvmuxer.cc',
'/third_party/aom/third_party/libwebm/mkvmuxer/mkvmuxerutil.cc',
'/third_party/aom/third_party/libwebm/mkvmuxer/mkvwriter.cc',
'WebMFileWriter.cpp',
]
include('/dom/media/webrtc/third_party_build/webrtc.mozbuild')
include('/ipc/chromium/chromium-config.mozbuild')
FINAL_LIBRARY = 'xul'
| browser_patches/firefox/juggler/screencast/moz.build | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.0010956492042168975,
0.00035359719186089933,
0.0001608134771231562,
0.00017468085570726544,
0.000371077680028975
] |
{
"id": 0,
"code_window": [
" ' \"$COMMIT_MESSAGE\")\n",
"\n",
" git commit -m \"$COMMIT_MESSAGE\"\n",
" done\n",
" LAST_COMMIT_MESSAGE=$(git show -s --format=%B)\n",
" echo \"::set-output name=PR_TITLE::$LAST_COMMIT_MESSAGE\"\n",
" - name: Prepare branch\n",
" id: prepare-branch\n",
" run: |\n",
" BRANCH_NAME=\"cherry-pick-${{ github.event.inputs.version }}-$(date +%Y-%m-%d-%H-%M-%S)\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"PR_TITLE=$LAST_COMMIT_MESSAGE\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/cherry_pick_into_release_branch.yml",
"type": "replace",
"edit_start_line_idx": 50
} | export default function MultiRoot() {
return <>
<div>root 1</div>
<div>root 2</div>
</>
}
| tests/components/ct-react-vite/src/components/MultiRoot.tsx | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.00018916286353487521,
0.00018916286353487521,
0.00018916286353487521,
0.00018916286353487521,
0
] |
{
"id": 0,
"code_window": [
" ' \"$COMMIT_MESSAGE\")\n",
"\n",
" git commit -m \"$COMMIT_MESSAGE\"\n",
" done\n",
" LAST_COMMIT_MESSAGE=$(git show -s --format=%B)\n",
" echo \"::set-output name=PR_TITLE::$LAST_COMMIT_MESSAGE\"\n",
" - name: Prepare branch\n",
" id: prepare-branch\n",
" run: |\n",
" BRANCH_NAME=\"cherry-pick-${{ github.event.inputs.version }}-$(date +%Y-%m-%d-%H-%M-%S)\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"PR_TITLE=$LAST_COMMIT_MESSAGE\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/cherry_pick_into_release_branch.yml",
"type": "replace",
"edit_start_line_idx": 50
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the 'License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { RootDispatcher } from './dispatcher';
import { Dispatcher } from './dispatcher';
import type { Electron } from '../electron/electron';
import { ElectronApplication } from '../electron/electron';
import type * as channels from '@protocol/channels';
import { BrowserContextDispatcher } from './browserContextDispatcher';
import type { PageDispatcher } from './pageDispatcher';
import { parseArgument, serializeResult } from './jsHandleDispatcher';
import { ElementHandleDispatcher } from './elementHandlerDispatcher';
export class ElectronDispatcher extends Dispatcher<Electron, channels.ElectronChannel, RootDispatcher> implements channels.ElectronChannel {
_type_Electron = true;
constructor(scope: RootDispatcher, electron: Electron) {
super(scope, electron, 'Electron', {});
}
async launch(params: channels.ElectronLaunchParams): Promise<channels.ElectronLaunchResult> {
const electronApplication = await this._object.launch(params);
return { electronApplication: new ElectronApplicationDispatcher(this, electronApplication) };
}
}
export class ElectronApplicationDispatcher extends Dispatcher<ElectronApplication, channels.ElectronApplicationChannel, ElectronDispatcher> implements channels.ElectronApplicationChannel {
_type_EventTarget = true;
_type_ElectronApplication = true;
constructor(scope: ElectronDispatcher, electronApplication: ElectronApplication) {
super(scope, electronApplication, 'ElectronApplication', {
context: new BrowserContextDispatcher(scope, electronApplication.context())
});
this.addObjectListener(ElectronApplication.Events.Close, () => {
this._dispatchEvent('close');
this._dispose();
});
}
async browserWindow(params: channels.ElectronApplicationBrowserWindowParams): Promise<channels.ElectronApplicationBrowserWindowResult> {
const handle = await this._object.browserWindow((params.page as PageDispatcher).page());
return { handle: ElementHandleDispatcher.fromJSHandle(this, handle) };
}
async evaluateExpression(params: channels.ElectronApplicationEvaluateExpressionParams): Promise<channels.ElectronApplicationEvaluateExpressionResult> {
const handle = await this._object._nodeElectronHandlePromise;
return { value: serializeResult(await handle.evaluateExpressionAndWaitForSignals(params.expression, params.isFunction, true /* returnByValue */, parseArgument(params.arg))) };
}
async evaluateExpressionHandle(params: channels.ElectronApplicationEvaluateExpressionHandleParams): Promise<channels.ElectronApplicationEvaluateExpressionHandleResult> {
const handle = await this._object._nodeElectronHandlePromise;
const result = await handle.evaluateExpressionAndWaitForSignals(params.expression, params.isFunction, false /* returnByValue */, parseArgument(params.arg));
return { handle: ElementHandleDispatcher.fromJSHandle(this, result) };
}
async close(): Promise<void> {
await this._object.close();
}
}
| packages/playwright-core/src/server/dispatchers/electronDispatcher.ts | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.0001780888414941728,
0.00017292826669290662,
0.00016157120990101248,
0.00017588547780178487,
0.0000053031035349704325
] |
{
"id": 1,
"code_window": [
" id: prepare-branch\n",
" run: |\n",
" BRANCH_NAME=\"cherry-pick-${{ github.event.inputs.version }}-$(date +%Y-%m-%d-%H-%M-%S)\"\n",
" echo \"::set-output name=BRANCH_NAME::$BRANCH_NAME\"\n",
" git checkout -b \"$BRANCH_NAME\"\n",
" git push origin $BRANCH_NAME\n",
" - name: Create Pull Request\n",
" uses: actions/github-script@v6\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"BRANCH_NAME=$BRANCH_NAME\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/cherry_pick_into_release_branch.yml",
"type": "replace",
"edit_start_line_idx": 55
} | name: "PR: bump driver Node.js"
on:
workflow_dispatch:
schedule:
# At 10:00am UTC (3AM PST) every tuesday and thursday to roll to new Node.js driver
- cron: "0 10 * * 2,4"
jobs:
trigger-nodejs-roll:
name: Trigger Roll
runs-on: ubuntu-22.04
if: github.repository == 'microsoft/playwright'
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
- run: node utils/build/update-playwright-driver-version.mjs
- name: Prepare branch
id: prepare-branch
run: |
if [[ "$(git status --porcelain)" == "" ]]; then
echo "there are no changes";
exit 0;
fi
echo "::set-output name=HAS_CHANGES::1"
BRANCH_NAME="roll-driver-nodejs/$(date +%Y-%b-%d)"
echo "::set-output name=BRANCH_NAME::$BRANCH_NAME"
git config --global user.name github-actions
git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com
git checkout -b "$BRANCH_NAME"
git add .
git commit -m "chore(driver): roll driver to recent Node.js LTS version"
git push origin $BRANCH_NAME
- name: Create Pull Request
if: ${{ steps.prepare-branch.outputs.HAS_CHANGES == '1' }}
uses: actions/github-script@v6
with:
script: |
await github.rest.pulls.create({
owner: 'microsoft',
repo: 'playwright',
head: 'microsoft:${{ steps.prepare-branch.outputs.BRANCH_NAME }}',
base: 'main',
title: 'chore(driver): roll driver to recent Node.js LTS version',
});
| .github/workflows/roll_driver_nodejs.yml | 1 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.12521858513355255,
0.04270380735397339,
0.00017145232413895428,
0.007952087558805943,
0.050587382167577744
] |
{
"id": 1,
"code_window": [
" id: prepare-branch\n",
" run: |\n",
" BRANCH_NAME=\"cherry-pick-${{ github.event.inputs.version }}-$(date +%Y-%m-%d-%H-%M-%S)\"\n",
" echo \"::set-output name=BRANCH_NAME::$BRANCH_NAME\"\n",
" git checkout -b \"$BRANCH_NAME\"\n",
" git push origin $BRANCH_NAME\n",
" - name: Create Pull Request\n",
" uses: actions/github-script@v6\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"BRANCH_NAME=$BRANCH_NAME\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/cherry_pick_into_release_branch.yml",
"type": "replace",
"edit_start_line_idx": 55
} | <script>
import { createEventDispatcher } from "svelte";
export let title;
const dispatch = createEventDispatcher();
</script>
<button on:click={() => dispatch('submit', 'hello')}>{title}</button>
| tests/components/ct-svelte/src/components/Button.svelte | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.000172860745806247,
0.000172860745806247,
0.000172860745806247,
0.000172860745806247,
0
] |
{
"id": 1,
"code_window": [
" id: prepare-branch\n",
" run: |\n",
" BRANCH_NAME=\"cherry-pick-${{ github.event.inputs.version }}-$(date +%Y-%m-%d-%H-%M-%S)\"\n",
" echo \"::set-output name=BRANCH_NAME::$BRANCH_NAME\"\n",
" git checkout -b \"$BRANCH_NAME\"\n",
" git push origin $BRANCH_NAME\n",
" - name: Create Pull Request\n",
" uses: actions/github-script@v6\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"BRANCH_NAME=$BRANCH_NAME\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/cherry_pick_into_release_branch.yml",
"type": "replace",
"edit_start_line_idx": 55
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { Metadata } from '@playwright/test';
export type Stats = {
total: number;
expected: number;
unexpected: number;
flaky: number;
skipped: number;
ok: boolean;
duration: number;
};
export type Location = {
file: string;
line: number;
column: number;
};
export type HTMLReport = {
metadata: Metadata;
files: TestFileSummary[];
stats: Stats;
projectNames: string[];
};
export type TestFile = {
fileId: string;
fileName: string;
tests: TestCase[];
};
export type TestFileSummary = {
fileId: string;
fileName: string;
tests: TestCaseSummary[];
stats: Stats;
};
export type TestCaseSummary = {
testId: string,
title: string;
path: string[];
projectName: string;
location: Location;
annotations: { type: string, description?: string }[];
outcome: 'skipped' | 'expected' | 'unexpected' | 'flaky';
duration: number;
ok: boolean;
results: TestResultSummary[];
};
export type TestResultSummary = {
attachments: { name: string, contentType: string, path?: string }[];
};
export type TestCase = Omit<TestCaseSummary, 'results'> & {
results: TestResult[];
};
export type TestAttachment = {
name: string;
body?: string;
path?: string;
contentType: string;
};
export type TestResult = {
retry: number;
startTime: string;
duration: number;
steps: TestStep[];
errors: string[];
attachments: TestAttachment[];
status: 'passed' | 'failed' | 'timedOut' | 'skipped' | 'interrupted';
};
export type TestStep = {
title: string;
startTime: string;
duration: number;
location?: Location;
snippet?: string;
error?: string;
steps: TestStep[];
count: number;
};
| packages/html-reporter/src/types.ts | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.00017824869428295642,
0.00017589076014701277,
0.0001722219167277217,
0.00017627942725084722,
0.0000018201429838882177
] |
{
"id": 1,
"code_window": [
" id: prepare-branch\n",
" run: |\n",
" BRANCH_NAME=\"cherry-pick-${{ github.event.inputs.version }}-$(date +%Y-%m-%d-%H-%M-%S)\"\n",
" echo \"::set-output name=BRANCH_NAME::$BRANCH_NAME\"\n",
" git checkout -b \"$BRANCH_NAME\"\n",
" git push origin $BRANCH_NAME\n",
" - name: Create Pull Request\n",
" uses: actions/github-script@v6\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"BRANCH_NAME=$BRANCH_NAME\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/cherry_pick_into_release_branch.yml",
"type": "replace",
"edit_start_line_idx": 55
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// @ts-check
// This file is injected into the registry as text, no dependencies are allowed.
import { createApp, setDevtoolsHook, h } from 'vue';
import { compile } from '@vue/compiler-dom';
import * as Vue from 'vue';
/** @typedef {import('@playwright/test/types/component').Component} Component */
/** @typedef {import('vue').Component} FrameworkComponent */
/** @type {Map<string, FrameworkComponent>} */
const registry = new Map();
/**
* @param {{[key: string]: FrameworkComponent}} components
*/
export function register(components) {
for (const [name, value] of Object.entries(components))
registry.set(name, value);
}
const allListeners = new Map();
/**
* @param {Component | string} child
* @returns {import('vue').VNode | string}
*/
function createChild(child) {
return typeof child === 'string' ? child : createWrapper(child);
}
/**
* Copied from: https://github.com/vuejs/test-utils/blob/main/src/utils/compileSlots.ts
* Vue does not provide an easy way to compile template in "slot" mode
* Since we do not want to rely on compiler internals and specify
* transforms manually we create fake component invocation with the slot we
* need and pick slots param from render function later. Fake component will
* never be instantiated but it requires to be a component so compile
* properly generate invocation. Since we do not want to monkey-patch
* `resolveComponent` function we are just using one of built-in components.
*
* @param {string} html
*/
function createSlot(html) {
let template = html.trim();
const hasWrappingTemplate = template && template.startsWith('<template');
// allow content without `template` tag, for easier testing
if (!hasWrappingTemplate)
template = `<template #default="params">${template}</template>`;
const { code } = compile(`<transition>${template}</transition>`, {
mode: 'function',
prefixIdentifiers: false
});
const createRenderFunction = new Function('Vue', code);
const renderFn = createRenderFunction(Vue);
return (ctx = {}) => {
const result = renderFn(ctx);
const slotName = Object.keys(result.children)[0];
return result.children[slotName](ctx);
};
}
function slotToFunction(slot) {
if (typeof slot === 'string')
return createSlot(slot)();
if (Array.isArray(slot))
return slot.map(slot => createSlot(slot)());
throw Error(`Invalid slot received.`);
}
/**
* @param {Component} component
*/
function createComponent(component) {
if (typeof component === 'string')
return component;
/**
* @type {import('vue').Component | string | undefined}
*/
let componentFunc = registry.get(component.type);
if (!componentFunc) {
// Lookup by shorthand.
for (const [name, value] of registry) {
if (component.type.endsWith(`_${name}_vue`)) {
componentFunc = value;
break;
}
}
}
if (!componentFunc && component.type[0].toUpperCase() === component.type[0])
throw new Error(`Unregistered component: ${component.type}. Following components are registered: ${[...registry.keys()]}`);
componentFunc = componentFunc || component.type;
const isVueComponent = componentFunc !== component.type;
/**
* @type {(import('vue').VNode | string)[]}
*/
const children = [];
/** @type {{[key: string]: any}} */
const slots = {};
const listeners = {};
/** @type {{[key: string]: any}} */
let props = {};
if (component.kind === 'jsx') {
for (const child of component.children || []) {
if (typeof child !== 'string' && child.type === 'template' && child.kind === 'jsx') {
const slotProperty = Object.keys(child.props).find(k => k.startsWith('v-slot:'));
const slot = slotProperty ? slotProperty.substring('v-slot:'.length) : 'default';
slots[slot] = child.children.map(createChild);
} else {
children.push(createChild(child));
}
}
for (const [key, value] of Object.entries(component.props)) {
if (key.startsWith('v-on:')) {
const event = key.substring('v-on:'.length);
if (isVueComponent)
listeners[event] = value;
else
props[`on${event[0].toUpperCase()}${event.substring(1)}`] = value;
} else {
props[key] = value;
}
}
}
if (component.kind === 'object') {
// Vue test util syntax.
for (const [key, value] of Object.entries(component.options?.slots || {})) {
if (key === 'default')
children.push(slotToFunction(value));
else
slots[key] = slotToFunction(value);
}
props = component.options?.props || {};
for (const [key, value] of Object.entries(component.options?.on || {}))
listeners[key] = value;
}
let lastArg;
if (Object.entries(slots).length) {
lastArg = slots;
if (children.length)
slots.default = children;
} else if (children.length) {
lastArg = children;
}
return { Component: componentFunc, props, slots: lastArg, listeners };
}
function wrapFunctions(slots) {
const slotsWithRenderFunctions = {};
if (!Array.isArray(slots)) {
for (const [key, value] of Object.entries(slots || {}))
slotsWithRenderFunctions[key] = () => [value];
} else if (slots?.length) {
slots['default'] = () => slots;
}
return slotsWithRenderFunctions;
}
/**
* @param {Component} component
* @returns {import('vue').VNode | string}
*/
function createWrapper(component) {
const { Component, props, slots, listeners } = createComponent(component);
// @ts-ignore
const wrapper = h(Component, props, slots);
allListeners.set(wrapper, listeners);
return wrapper;
}
/**
* @returns {any}
*/
function createDevTools() {
return {
emit(eventType, ...payload) {
if (eventType === 'component:emit') {
const [, componentVM, event, eventArgs] = payload;
for (const [wrapper, listeners] of allListeners) {
if (wrapper.component !== componentVM)
continue;
const listener = listeners[event];
if (!listener)
return;
listener(...eventArgs);
}
}
}
};
}
const appKey = Symbol('appKey');
const wrapperKey = Symbol('wrapperKey');
window.playwrightMount = async (component, rootElement, hooksConfig) => {
const app = createApp({
render: () => {
const wrapper = createWrapper(component);
rootElement[wrapperKey] = wrapper;
return wrapper;
}
});
setDevtoolsHook(createDevTools(), {});
for (const hook of /** @type {any} */(window).__pw_hooks_before_mount || [])
await hook({ app, hooksConfig });
const instance = app.mount(rootElement);
rootElement[appKey] = app;
for (const hook of /** @type {any} */(window).__pw_hooks_after_mount || [])
await hook({ app, hooksConfig, instance });
};
window.playwrightUnmount = async rootElement => {
const app = /** @type {import('vue').App} */ (rootElement[appKey]);
if (!app)
throw new Error('Component was not mounted');
app.unmount();
};
window.playwrightUpdate = async (rootElement, options) => {
const wrapper = rootElement[wrapperKey];
if (!wrapper)
throw new Error('Component was not mounted');
const { slots, listeners, props } = createComponent(options);
wrapper.component.slots = wrapFunctions(slots);
allListeners.set(wrapper, listeners);
for (const [key, value] of Object.entries(props))
wrapper.component.props[key] = value;
if (!Object.keys(props).length)
wrapper.component.update();
};
| packages/playwright-ct-vue/registerSource.mjs | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.00017693771224003285,
0.00017234381812158972,
0.00016407464863732457,
0.00017290411051362753,
0.000002694193881325191
] |
{
"id": 2,
"code_window": [
" npm run build\n",
" - name: Prepare branch\n",
" id: prepare-branch\n",
" run: |\n",
" BRANCH_NAME=\"roll-into-pw-${{ github.event.client_payload.browser }}/${{ github.event.client_payload.revision }}\"\n",
" echo \"::set-output name=BRANCH_NAME::$BRANCH_NAME\"\n",
" git config --global user.name github-actions\n",
" git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com\n",
" git checkout -b \"$BRANCH_NAME\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"BRANCH_NAME=$BRANCH_NAME\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/roll_browser_into_playwright.yml",
"type": "replace",
"edit_start_line_idx": 27
} | name: Roll Browser into Playwright
on:
repository_dispatch:
types: [roll_into_pw]
jobs:
roll:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 14
- run: npm i -g npm@8
- run: npm ci
- run: npm run build
- name: Install dependencies
run: npx playwright install-deps
- name: Roll to new revision
run: |
./utils/roll_browser.js ${{ github.event.client_payload.browser }} ${{ github.event.client_payload.revision }}
npm run build
- name: Prepare branch
id: prepare-branch
run: |
BRANCH_NAME="roll-into-pw-${{ github.event.client_payload.browser }}/${{ github.event.client_payload.revision }}"
echo "::set-output name=BRANCH_NAME::$BRANCH_NAME"
git config --global user.name github-actions
git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com
git checkout -b "$BRANCH_NAME"
git add .
git commit -m "feat(${{ github.event.client_payload.browser }}): roll to r${{ github.event.client_payload.revision }}"
git push origin $BRANCH_NAME
- name: Create Pull Request
uses: actions/github-script@v6
with:
github-token: ${{ secrets.REPOSITORY_DISPATCH_PERSONAL_ACCESS_TOKEN }}
script: |
const response = await github.rest.pulls.create({
owner: 'microsoft',
repo: 'playwright',
head: 'microsoft:${{ steps.prepare-branch.outputs.BRANCH_NAME }}',
base: 'main',
title: 'feat(${{ github.event.client_payload.browser }}): roll to r${{ github.event.client_payload.revision }}',
});
await github.rest.issues.addLabels({
owner: 'microsoft',
repo: 'playwright',
issue_number: response.data.number,
labels: ['CQ1'],
});
| .github/workflows/roll_browser_into_playwright.yml | 1 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.9297866821289062,
0.1585342288017273,
0.00016913360741455108,
0.0002902602427639067,
0.34499379992485046
] |
{
"id": 2,
"code_window": [
" npm run build\n",
" - name: Prepare branch\n",
" id: prepare-branch\n",
" run: |\n",
" BRANCH_NAME=\"roll-into-pw-${{ github.event.client_payload.browser }}/${{ github.event.client_payload.revision }}\"\n",
" echo \"::set-output name=BRANCH_NAME::$BRANCH_NAME\"\n",
" git config --global user.name github-actions\n",
" git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com\n",
" git checkout -b \"$BRANCH_NAME\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"BRANCH_NAME=$BRANCH_NAME\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/roll_browser_into_playwright.yml",
"type": "replace",
"edit_start_line_idx": 27
} | // @ts-check
const { test, expect } = require('@playwright/test');
let log = [];
test.beforeEach(async ({page}) => {
log = [];
// Expose function for pushing messages to the Node.js script.
await page.exposeFunction('logCall', msg => log.push(msg));
await page.addInitScript(() => {
const mockBattery = {
level: 0.75,
charging: true,
chargingTime: 1800, // seconds
dischargingTime: Infinity,
addEventListener: (name, cb) => logCall(`addEventListener:${name}`)
};
// Override the method to always return mock battery info.
window.navigator.getBattery = async () => {
logCall('getBattery');
return mockBattery;
};
// application tries navigator.battery first
// so we delete this method
delete window.navigator.battery;
});
})
test('verify battery calls', async ({ page }) => {
await page.goto('/');
await expect(page.locator('.battery-percentage')).toHaveText('75%');
// Ensure expected method calls were made.
expect(log).toEqual([
'getBattery',
'addEventListener:chargingchange',
'addEventListener:levelchange'
]);
});
| examples/mock-battery/tests/verify-calls.spec.js | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.00017196543922182173,
0.00017127866158261895,
0.00017062676488421857,
0.00017126121383626014,
5.127690769768378e-7
] |
{
"id": 2,
"code_window": [
" npm run build\n",
" - name: Prepare branch\n",
" id: prepare-branch\n",
" run: |\n",
" BRANCH_NAME=\"roll-into-pw-${{ github.event.client_payload.browser }}/${{ github.event.client_payload.revision }}\"\n",
" echo \"::set-output name=BRANCH_NAME::$BRANCH_NAME\"\n",
" git config --global user.name github-actions\n",
" git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com\n",
" git checkout -b \"$BRANCH_NAME\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"BRANCH_NAME=$BRANCH_NAME\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/roll_browser_into_playwright.yml",
"type": "replace",
"edit_start_line_idx": 27
} | ---
id: test-runners
title: "Pytest Plugin Reference"
---
Playwright provides a [Pytest](https://docs.pytest.org/en/stable/) plugin to write end-to-end tests. To get started with it, refer to the [getting started guide](./intro.md).
## Usage
To run your tests, use [Pytest](https://docs.pytest.org/en/stable/) CLI.
```bash
pytest --browser webkit --headed
```
If you want to add the CLI arguments automatically without specifying them, you can use the [pytest.ini](https://docs.pytest.org/en/stable/reference.html#ini-options-ref) file:
```ini
# content of pytest.ini
[pytest]
# Run firefox with UI
addopts = --headed --browser firefox
```
## CLI arguments
- `--headed`: Run tests in headed mode (default: headless).
- `--browser`: Run tests in a different browser `chromium`, `firefox`, or `webkit`. It can be specified multiple times (default: `chromium`).
- `--browser-channel` [Browser channel](./browsers.md) to be used.
- `--slowmo` Run tests with slow mo.
- `--device` [Device](./emulation.md) to be emulated.
- `--output` Directory for artifacts produced by tests (default: `test-results`).
- `--tracing` Whether to record a [trace](./trace-viewer.md) for each test. `on`, `off`, or `retain-on-failure` (default: `off`).
- `--video` Whether to record video for each test. `on`, `off`, or `retain-on-failure` (default: `off`).
- `--screenshot` Whether to automatically capture a screenshot after each test. `on`, `off`, or `only-on-failure` (default: `off`).
## Fixtures
This plugin configures Playwright-specific [fixtures for pytest](https://docs.pytest.org/en/latest/fixture.html). To use these fixtures, use the fixture name as an argument to the test function.
```py
def test_my_app_is_working(fixture_name):
# Test using fixture_name
# ...
```
**Function scope**: These fixtures are created when requested in a test function and destroyed when the test ends.
- `context`: New [browser context](https://playwright.dev/python/docs/browser-contexts) for a test.
- `page`: New [browser page](https://playwright.dev/python/docs/pages) for a test.
**Session scope**: These fixtures are created when requested in a test function and destroyed when all tests end.
- `playwright`: [Playwright](https://playwright.dev/python/docs/api/class-playwright) instance.
- `browser_type`: [BrowserType](https://playwright.dev/python/docs/api/class-browsertype) instance of the current browser.
- `browser`: [Browser](https://playwright.dev/python/docs/api/class-browser) instance launched by Playwright.
- `browser_name`: Browser name as string.
- `browser_channel`: Browser channel as string.
- `is_chromium`, `is_webkit`, `is_firefox`: Booleans for the respective browser types.
**Customizing fixture options**: For `browser` and `context` fixtures, use the following fixtures to define custom launch options.
- `browser_type_launch_args`: Override launch arguments for [`method: BrowserType.launch`]. It should return a Dict.
- `browser_context_args`: Override the options for [`method: Browser.newContext`]. It should return a Dict.
## Parallelism: Running Multiple Tests at Once
If your tests are running on a machine with a lot of CPUs, you can speed up the overall execution time of your test suite by using [`pytest-xdist`](https://pypi.org/project/pytest-xdist/) to run multiple tests at once:
```bash
# install dependency
pip install pytest-xdist
# use the --numprocesses flag
pytest --numprocesses auto
```
Depending on the hardware and nature of your tests, you can set `numprocesses` to be anywhere from `2` to the number of CPUs on the machine. If set too high, you may notice unexpected behavior.
See [Running Tests](./running-tests.md) for general information on `pytest` options.
## Examples
### Configure Mypy typings for auto-completion
```py
# test_my_application.py
from playwright.sync_api import Page
def test_visit_admin_dashboard(page: Page):
page.goto("/admin")
# ...
```
### Configure slow mo
Run tests with slow mo with the `--slowmo` argument.
```bash
pytest --slowmo 100
```
### Skip test by browser
```py
# test_my_application.py
import pytest
@pytest.mark.skip_browser("firefox")
def test_visit_example(page):
page.goto("https://example.com")
# ...
```
### Run on a specific browser
```py
# conftest.py
import pytest
@pytest.mark.only_browser("chromium")
def test_visit_example(page):
page.goto("https://example.com")
# ...
```
### Run with a custom browser channel like Google Chrome or Microsoft Edge
```bash
pytest --browser-channel chrome
```
```python
# test_my_application.py
def test_example(page):
page.goto("https://example.com")
```
### Configure base-url
Start Pytest with the `base-url` argument. The [`pytest-base-url`](https://github.com/pytest-dev/pytest-base-url) plugin is used
for that which allows you to set the base url from the config, CLI arg or as a fixture.
```bash
pytest --base-url http://localhost:8080
```
```py
# test_my_application.py
def test_visit_example(page):
page.goto("/admin")
# -> Will result in http://localhost:8080/admin
```
### Ignore HTTPS errors
```py
# conftest.py
import pytest
@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
return {
**browser_context_args,
"ignore_https_errors": True
}
```
### Use custom viewport size
```py
# conftest.py
import pytest
@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
return {
**browser_context_args,
"viewport": {
"width": 1920,
"height": 1080,
}
}
```
### Device emulation
```py
# conftest.py
import pytest
@pytest.fixture(scope="session")
def browser_context_args(browser_context_args, playwright):
iphone_11 = playwright.devices['iPhone 11 Pro']
return {
**browser_context_args,
**iphone_11,
}
```
Or via the CLI `--device="iPhone 11 Pro"`
### Persistent context
```py
# conftest.py
import pytest
from playwright.sync_api import BrowserType
from typing import Dict
@pytest.fixture(scope="session")
def context(
browser_type: BrowserType,
browser_type_launch_args: Dict,
browser_context_args: Dict
):
context = browser_type.launch_persistent_context("./foobar", **{
**browser_type_launch_args,
**browser_context_args,
"locale": "de-DE",
})
yield context
context.close()
```
When using that all pages inside your test are created from the persistent context.
### Using with `unittest.TestCase`
See the following example for using it with `unittest.TestCase`. This has a limitation,
that only a single browser can be specified and no matrix of multiple browsers gets
generated when specifying multiple.
```py
import pytest
import unittest
from playwright.sync_api import Page
class MyTest(unittest.TestCase):
@pytest.fixture(autouse=True)
def setup(self, page: Page):
self.page = page
def test_foobar(self):
self.page.goto("https://microsoft.com")
self.page.locator("#foobar").click()
assert self.page.evaluate("1 + 1") == 2
```
## Debugging
### Use with pdb
Use the `breakpoint()` statement in your test code to pause execution and get a [pdb](https://docs.python.org/3/library/pdb.html) REPL.
```py
def test_bing_is_working(page):
page.goto("https://bing.com")
breakpoint()
# ...
```
## Deploy to CI
See the [guides for CI providers](./ci.md) to deploy your tests to CI/CD.
| docs/src/test-runners-python.md | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.00017302103515248746,
0.00016711100761312991,
0.00016074463201221079,
0.00016780674923211336,
0.000003640181603259407
] |
{
"id": 2,
"code_window": [
" npm run build\n",
" - name: Prepare branch\n",
" id: prepare-branch\n",
" run: |\n",
" BRANCH_NAME=\"roll-into-pw-${{ github.event.client_payload.browser }}/${{ github.event.client_payload.revision }}\"\n",
" echo \"::set-output name=BRANCH_NAME::$BRANCH_NAME\"\n",
" git config --global user.name github-actions\n",
" git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com\n",
" git checkout -b \"$BRANCH_NAME\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"BRANCH_NAME=$BRANCH_NAME\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/roll_browser_into_playwright.yml",
"type": "replace",
"edit_start_line_idx": 27
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import path from 'path';
import { Page } from './page';
import { assert } from '../utils';
import { Artifact } from './artifact';
export class Download {
readonly artifact: Artifact;
readonly url: string;
private _page: Page;
private _suggestedFilename: string | undefined;
constructor(page: Page, downloadsPath: string, uuid: string, url: string, suggestedFilename?: string) {
const unaccessibleErrorMessage = !page._browserContext._options.acceptDownloads ? 'Pass { acceptDownloads: true } when you are creating your browser context.' : undefined;
this.artifact = new Artifact(page, path.join(downloadsPath, uuid), unaccessibleErrorMessage, () => {
return this._page._browserContext.cancelDownload(uuid);
});
this._page = page;
this.url = url;
this._suggestedFilename = suggestedFilename;
page._browserContext._downloads.add(this);
if (suggestedFilename !== undefined)
this._page.emit(Page.Events.Download, this);
}
_filenameSuggested(suggestedFilename: string) {
assert(this._suggestedFilename === undefined);
this._suggestedFilename = suggestedFilename;
this._page.emit(Page.Events.Download, this);
}
suggestedFilename(): string {
return this._suggestedFilename!;
}
}
| packages/playwright-core/src/server/download.ts | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.0001756973215378821,
0.0001711166260065511,
0.00016579293878749013,
0.00017144143930636346,
0.000003372133051016135
] |
{
"id": 3,
"code_window": [
" run: |\n",
" if [[ \"$(git status --porcelain)\" == \"\" ]]; then\n",
" echo \"there are no changes\";\n",
" exit 0;\n",
" fi\n",
" echo \"::set-output name=HAS_CHANGES::1\"\n",
" BRANCH_NAME=\"roll-driver-nodejs/$(date +%Y-%b-%d)\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" echo \"HAS_CHANGES=1\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/roll_driver_nodejs.yml",
"type": "replace",
"edit_start_line_idx": 24
} | name: Roll Browser into Playwright
on:
repository_dispatch:
types: [roll_into_pw]
jobs:
roll:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 14
- run: npm i -g npm@8
- run: npm ci
- run: npm run build
- name: Install dependencies
run: npx playwright install-deps
- name: Roll to new revision
run: |
./utils/roll_browser.js ${{ github.event.client_payload.browser }} ${{ github.event.client_payload.revision }}
npm run build
- name: Prepare branch
id: prepare-branch
run: |
BRANCH_NAME="roll-into-pw-${{ github.event.client_payload.browser }}/${{ github.event.client_payload.revision }}"
echo "::set-output name=BRANCH_NAME::$BRANCH_NAME"
git config --global user.name github-actions
git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com
git checkout -b "$BRANCH_NAME"
git add .
git commit -m "feat(${{ github.event.client_payload.browser }}): roll to r${{ github.event.client_payload.revision }}"
git push origin $BRANCH_NAME
- name: Create Pull Request
uses: actions/github-script@v6
with:
github-token: ${{ secrets.REPOSITORY_DISPATCH_PERSONAL_ACCESS_TOKEN }}
script: |
const response = await github.rest.pulls.create({
owner: 'microsoft',
repo: 'playwright',
head: 'microsoft:${{ steps.prepare-branch.outputs.BRANCH_NAME }}',
base: 'main',
title: 'feat(${{ github.event.client_payload.browser }}): roll to r${{ github.event.client_payload.revision }}',
});
await github.rest.issues.addLabels({
owner: 'microsoft',
repo: 'playwright',
issue_number: response.data.number,
labels: ['CQ1'],
});
| .github/workflows/roll_browser_into_playwright.yml | 1 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.0006338973762467504,
0.00027088794740848243,
0.00016930997662711889,
0.00017293129349127412,
0.00016969352145679295
] |
{
"id": 3,
"code_window": [
" run: |\n",
" if [[ \"$(git status --porcelain)\" == \"\" ]]; then\n",
" echo \"there are no changes\";\n",
" exit 0;\n",
" fi\n",
" echo \"::set-output name=HAS_CHANGES::1\"\n",
" BRANCH_NAME=\"roll-driver-nodejs/$(date +%Y-%b-%d)\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" echo \"HAS_CHANGES=1\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/roll_driver_nodejs.yml",
"type": "replace",
"edit_start_line_idx": 24
} | <!doctype html>
<html>
<head>
<title>Name checkbox-label-embedded-spinbutton</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<link rel="stylesheet" href="/wai-aria/scripts/manual.css">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/wai-aria/scripts/ATTAcomm.js"></script>
<script>
setup({explicit_timeout: true, explicit_done: true });
var theTest = new ATTAcomm(
{
"steps" : [
{
"element" : "test",
"test" : {
"ATK" : [
[
"property",
"name",
"is",
"foo 5 baz"
]
],
"AXAPI" : [
[
"property",
"AXDescription",
"is",
"foo 5 baz"
]
],
"IAccessible2" : [
[
"property",
"accName",
"is",
"foo 5 baz"
]
],
"UIA" : [
[
"property",
"Name",
"is",
"foo 5 baz"
]
]
},
"title" : "step 1",
"type" : "test"
}
],
"title" : "Name checkbox-label-embedded-spinbutton"
}
) ;
</script>
</head>
<body>
<p>This test examines the ARIA properties for Name checkbox-label-embedded-spinbutton.</p>
<input type="checkbox" id="test" />
<label for="test">foo <input role="spinbutton" type="number" value="5" min="1" max="10" aria-valuenow="5" aria-valuemin="1" aria-valuemax="10"> baz
</label>
<div id="manualMode"></div>
<div id="log"></div>
<div id="ATTAmessages"></div>
</body>
</html>
| tests/assets/wpt/accname/name_checkbox-label-embedded-spinbutton-manual.html | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.00017520482651889324,
0.00017055709031410515,
0.00016677280655130744,
0.00016990430594887584,
0.0000025420849851798266
] |
{
"id": 3,
"code_window": [
" run: |\n",
" if [[ \"$(git status --porcelain)\" == \"\" ]]; then\n",
" echo \"there are no changes\";\n",
" exit 0;\n",
" fi\n",
" echo \"::set-output name=HAS_CHANGES::1\"\n",
" BRANCH_NAME=\"roll-driver-nodejs/$(date +%Y-%b-%d)\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" echo \"HAS_CHANGES=1\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/roll_driver_nodejs.yml",
"type": "replace",
"edit_start_line_idx": 24
} | # class: JSHandle
* since: v1.8
JSHandle represents an in-page JavaScript object. JSHandles can be created with the [`method: Page.evaluateHandle`]
method.
```js
const windowHandle = await page.evaluateHandle(() => window);
// ...
```
```java
JSHandle windowHandle = page.evaluateHandle("() => window");
// ...
```
```python async
window_handle = await page.evaluate_handle("window")
# ...
```
```python sync
window_handle = page.evaluate_handle("window")
# ...
```
```csharp
var windowHandle = await page.EvaluateHandleAsync("() => window");
```
JSHandle prevents the referenced JavaScript object being garbage collected unless the handle is exposed with
[`method: JSHandle.dispose`]. JSHandles are auto-disposed when their origin frame gets navigated or the parent context
gets destroyed.
JSHandle instances can be used as an argument in [`method: Page.evalOnSelector`], [`method: Page.evaluate`] and
[`method: Page.evaluateHandle`] methods.
## method: JSHandle.asElement
* since: v1.8
- returns: <[null]|[ElementHandle]>
Returns either `null` or the object handle itself, if the object handle is an instance of [ElementHandle].
## async method: JSHandle.dispose
* since: v1.8
The `jsHandle.dispose` method stops referencing the element handle.
## async method: JSHandle.evaluate
* since: v1.8
- returns: <[Serializable]>
Returns the return value of [`param: expression`].
This method passes this handle as the first argument to [`param: expression`].
If [`param: expression`] returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return
its value.
**Usage**
```js
const tweetHandle = await page.$('.tweet .retweets');
expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10 retweets');
```
```java
ElementHandle tweetHandle = page.querySelector(".tweet .retweets");
assertEquals("10 retweets", tweetHandle.evaluate("node => node.innerText"));
```
```python async
tweet_handle = await page.query_selector(".tweet .retweets")
assert await tweet_handle.evaluate("node => node.innerText") == "10 retweets"
```
```python sync
tweet_handle = page.query_selector(".tweet .retweets")
assert tweet_handle.evaluate("node => node.innerText") == "10 retweets"
```
```csharp
var tweetHandle = await page.QuerySelectorAsync(".tweet .retweets");
Assert.AreEqual("10 retweets", await tweetHandle.EvaluateAsync("node => node.innerText"));
```
### param: JSHandle.evaluate.expression = %%-evaluate-expression-%%
* since: v1.8
### param: JSHandle.evaluate.arg
* since: v1.8
- `arg` ?<[EvaluationArgument]>
Optional argument to pass to [`param: expression`].
## async method: JSHandle.evaluateHandle
* since: v1.8
- returns: <[JSHandle]>
Returns the return value of [`param: expression`] as a [JSHandle].
This method passes this handle as the first argument to [`param: expression`].
The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `jsHandle.evaluateHandle` returns [JSHandle].
If the function passed to the `jsHandle.evaluateHandle` returns a [Promise], then `jsHandle.evaluateHandle` would wait
for the promise to resolve and return its value.
See [`method: Page.evaluateHandle`] for more details.
### param: JSHandle.evaluateHandle.expression = %%-evaluate-expression-%%
* since: v1.8
### param: JSHandle.evaluateHandle.arg
* since: v1.8
- `arg` ?<[EvaluationArgument]>
Optional argument to pass to [`param: expression`].
## async method: JSHandle.getProperties
* since: v1.8
- returns: <[Map]<[string], [JSHandle]>>
The method returns a map with **own property names** as keys and JSHandle instances for the property values.
**Usage**
```js
const handle = await page.evaluateHandle(() => ({window, document}));
const properties = await handle.getProperties();
const windowHandle = properties.get('window');
const documentHandle = properties.get('document');
await handle.dispose();
```
```java
JSHandle handle = page.evaluateHandle("() => ({window, document}"););
Map<String, JSHandle> properties = handle.getProperties();
JSHandle windowHandle = properties.get("window");
JSHandle documentHandle = properties.get("document");
handle.dispose();
```
```python async
handle = await page.evaluate_handle("({window, document})")
properties = await handle.get_properties()
window_handle = properties.get("window")
document_handle = properties.get("document")
await handle.dispose()
```
```python sync
handle = page.evaluate_handle("({window, document})")
properties = handle.get_properties()
window_handle = properties.get("window")
document_handle = properties.get("document")
handle.dispose()
```
```csharp
var handle = await page.EvaluateHandleAsync("() => ({window, document}");
var properties = await handle.GetPropertiesAsync();
var windowHandle = properties["window"];
var documentHandle = properties["document"];
await handle.DisposeAsync();
```
## async method: JSHandle.getProperty
* since: v1.8
- returns: <[JSHandle]>
Fetches a single property from the referenced object.
### param: JSHandle.getProperty.propertyName
* since: v1.8
- `propertyName` <[string]>
property to get
## async method: JSHandle.jsonValue
* since: v1.8
- returns: <[Serializable]>
Returns a JSON representation of the object. If the object has a `toJSON` function, it **will not be called**.
:::note
The method will return an empty JSON object if the referenced object is not stringifiable. It will throw an error if the
object has circular references.
:::
| docs/src/api/class-jshandle.md | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.00017482333350926638,
0.00017007588758133352,
0.00016308622434735298,
0.00017110869521275163,
0.0000034681197575991973
] |
{
"id": 3,
"code_window": [
" run: |\n",
" if [[ \"$(git status --porcelain)\" == \"\" ]]; then\n",
" echo \"there are no changes\";\n",
" exit 0;\n",
" fi\n",
" echo \"::set-output name=HAS_CHANGES::1\"\n",
" BRANCH_NAME=\"roll-driver-nodejs/$(date +%Y-%b-%d)\"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" echo \"HAS_CHANGES=1\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/roll_driver_nodejs.yml",
"type": "replace",
"edit_start_line_idx": 24
} | # class: ConsoleMessage
* since: v1.8
[ConsoleMessage] objects are dispatched by page via the [`event: Page.console`] event.
For each console messages logged in the page there will be corresponding event in the Playwright
context.
```js
// Listen for all console logs
page.on('console', msg => console.log(msg.text()))
// Listen for all console events and handle errors
page.on('console', msg => {
if (msg.type() === 'error')
console.log(`Error text: "${msg.text()}"`);
});
// Get the next console log
const msgPromise = page.waitForEvent('console');
await page.evaluate(() => {
console.log('hello', 42, { foo: 'bar' }); // Issue console.log inside the page
});
const msg = await msgPromise;
// Deconstruct console log arguments
await msg.args[0].jsonValue() // hello
await msg.args[1].jsonValue() // 42
```
```java
// Listen for all console messages and print them to the standard output.
page.onConsoleMessage(msg -> System.out.println(msg.text()));
// Listen for all console messages and print errors to the standard output.
page.onConsoleMessage(msg -> {
if ("error".equals(msg.type()))
System.out.println("Error text: " + msg.text());
});
// Get the next console message
ConsoleMessage msg = page.waitForConsoleMessage(() -> {
// Issue console.log inside the page
page.evaluate("console.log('hello', 42, { foo: 'bar' });");
});
// Deconstruct console.log arguments
msg.args().get(0).jsonValue() // hello
msg.args().get(1).jsonValue() // 42
```
```python async
# Listen for all console logs
page.on("console", lambda msg: print(msg.text))
# Listen for all console events and handle errors
page.on("console", lambda msg: print(f"error: {msg.text}") if msg.type == "error" else None)
# Get the next console log
async with page.expect_console_message() as msg_info:
# Issue console.log inside the page
await page.evaluate("console.log('hello', 42, { foo: 'bar' })")
msg = await msg_info.value
# Deconstruct print arguments
await msg.args[0].json_value() # hello
await msg.args[1].json_value() # 42
```
```python sync
# Listen for all console logs
page.on("console", lambda msg: print(msg.text))
# Listen for all console events and handle errors
page.on("console", lambda msg: print(f"error: {msg.text}") if msg.type == "error" else None)
# Get the next console log
with page.expect_console_message() as msg_info:
# Issue console.log inside the page
page.evaluate("console.log('hello', 42, { foo: 'bar' })")
msg = msg_info.value
# Deconstruct print arguments
msg.args[0].json_value() # hello
msg.args[1].json_value() # 42
```
```csharp
// Listen for all console messages and print them to the standard output.
page.Console += (_, msg) => Console.WriteLine(msg.Text);
// Listen for all console messages and print errors to the standard output.
page.Console += (_, msg) =>
{
if ("error".Equals(msg.Type))
Console.WriteLine("Error text: " + msg.Text);
};
// Get the next console message
var waitForMessageTask = page.WaitForConsoleMessageAsync();
await page.EvaluateAsync("console.log('hello', 42, { foo: 'bar' });");
var message = await waitForMessageTask;
// Deconstruct console.log arguments
await message.Args.ElementAt(0).JsonValueAsync<string>(); // hello
await message.Args.ElementAt(1).JsonValueAsync<int>(); // 42
```
## method: ConsoleMessage.args
* since: v1.8
- returns: <[Array]<[JSHandle]>>
List of arguments passed to a `console` function call. See also [`event: Page.console`].
## method: ConsoleMessage.location
* since: v1.8
* langs: js, python
- returns: <[Object]>
- `url` <[string]> URL of the resource.
- `lineNumber` <[int]> 0-based line number in the resource.
- `columnNumber` <[int]> 0-based column number in the resource.
## method: ConsoleMessage.location
* since: v1.8
* langs: csharp, java
- returns: <[string]>
URL of the resource followed by 0-based line and column numbers in the resource formatted as `URL:line:column`.
## method: ConsoleMessage.text
* since: v1.8
- returns: <[string]>
The text of the console message.
## method: ConsoleMessage.type
* since: v1.8
- returns: <[string]>
One of the following values: `'log'`, `'debug'`, `'info'`, `'error'`, `'warning'`, `'dir'`, `'dirxml'`, `'table'`,
`'trace'`, `'clear'`, `'startGroup'`, `'startGroupCollapsed'`, `'endGroup'`, `'assert'`, `'profile'`, `'profileEnd'`,
`'count'`, `'timeEnd'`.
| docs/src/api/class-consolemessage.md | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.0001720751606626436,
0.00016835839778650552,
0.0001609332684893161,
0.00016950284771155566,
0.000003206733254046412
] |
{
"id": 4,
"code_window": [
" BRANCH_NAME=\"roll-driver-nodejs/$(date +%Y-%b-%d)\"\n",
" echo \"::set-output name=BRANCH_NAME::$BRANCH_NAME\"\n",
" git config --global user.name github-actions\n",
" git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com\n",
" git checkout -b \"$BRANCH_NAME\"\n",
" git add .\n",
" git commit -m \"chore(driver): roll driver to recent Node.js LTS version\"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"BRANCH_NAME=$BRANCH_NAME\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/roll_driver_nodejs.yml",
"type": "replace",
"edit_start_line_idx": 26
} | name: Cherry-pick into release branch
on:
workflow_dispatch:
inputs:
version:
type: string
description: Version number, e.g. 1.25
required: true
commit_hashes:
type: string
description: Comma-separated list of commit hashes to cherry-pick
required: true
jobs:
roll:
runs-on: ubuntu-22.04
steps:
- name: Validate input version number
run: |
VERSION="${{ github.event.inputs.version }}"
if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+$ ]]; then
echo "Version is not a two digit semver version"
exit 1
fi
- uses: actions/checkout@v3
with:
ref: release-${{ github.event.inputs.version }}
fetch-depth: 0
- name: Cherry-pick commits
id: cherry-pick
run: |
git config --global user.name github-actions
git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com
for COMMIT_HASH in $(echo "${{ github.event.inputs.commit_hashes }}" | tr "," "\n"); do
git cherry-pick --no-commit "$COMMIT_HASH"
COMMIT_MESSAGE="$(git show -s --format=%B $COMMIT_HASH | head -n 1)"
COMMIT_MESSAGE=$(node -e '
const match = /^(.*) (\(#\d+\))$/.exec(process.argv[1]);
if (!match) {
console.log(process.argv[1]);
process.exit(0);
}
console.log(`cherry-pick${match[2]}: ${match[1]}`);
' "$COMMIT_MESSAGE")
git commit -m "$COMMIT_MESSAGE"
done
LAST_COMMIT_MESSAGE=$(git show -s --format=%B)
echo "::set-output name=PR_TITLE::$LAST_COMMIT_MESSAGE"
- name: Prepare branch
id: prepare-branch
run: |
BRANCH_NAME="cherry-pick-${{ github.event.inputs.version }}-$(date +%Y-%m-%d-%H-%M-%S)"
echo "::set-output name=BRANCH_NAME::$BRANCH_NAME"
git checkout -b "$BRANCH_NAME"
git push origin $BRANCH_NAME
- name: Create Pull Request
uses: actions/github-script@v6
with:
github-token: ${{ secrets.REPOSITORY_DISPATCH_PERSONAL_ACCESS_TOKEN }}
script: |
const readableCommitHashesList = '${{ github.event.inputs.commit_hashes }}'.split(',').map(hash => `- ${hash}`).join('\n');
const response = await github.rest.pulls.create({
owner: 'microsoft',
repo: 'playwright',
head: 'microsoft:${{ steps.prepare-branch.outputs.BRANCH_NAME }}',
base: 'release-${{ github.event.inputs.version }}',
title: '${{ steps.cherry-pick.outputs.PR_TITLE }}',
body: `This PR cherry-picks the following commits:\n\n${readableCommitHashesList}`,
});
await github.rest.issues.addLabels({
owner: 'microsoft',
repo: 'playwright',
issue_number: response.data.number,
labels: ['CQ1'],
});
| .github/workflows/cherry_pick_into_release_branch.yml | 1 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.025829141959547997,
0.0054524559527635574,
0.00016690674237906933,
0.00020117650274187326,
0.009299873374402523
] |
{
"id": 4,
"code_window": [
" BRANCH_NAME=\"roll-driver-nodejs/$(date +%Y-%b-%d)\"\n",
" echo \"::set-output name=BRANCH_NAME::$BRANCH_NAME\"\n",
" git config --global user.name github-actions\n",
" git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com\n",
" git checkout -b \"$BRANCH_NAME\"\n",
" git add .\n",
" git commit -m \"chore(driver): roll driver to recent Node.js LTS version\"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"BRANCH_NAME=$BRANCH_NAME\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/roll_driver_nodejs.yml",
"type": "replace",
"edit_start_line_idx": 26
} | /**
* Copyright 2018 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { browserTest as it, expect } from '../config/browserTest';
import * as path from 'path';
import fs from 'fs';
import http2 from 'http2';
import type { BrowserContext, BrowserContextOptions } from 'playwright-core';
import type { AddressInfo } from 'net';
import type { Log } from '../../packages/trace/src/har';
import { parseHar } from '../config/utils';
async function pageWithHar(contextFactory: (options?: BrowserContextOptions) => Promise<BrowserContext>, testInfo: any, options: { outputPath?: string, content?: 'embed' | 'attach' | 'omit', omitContent?: boolean } = {}) {
const harPath = testInfo.outputPath(options.outputPath || 'test.har');
const context = await contextFactory({ recordHar: { path: harPath, content: options.content, omitContent: options.omitContent }, ignoreHTTPSErrors: true });
const page = await context.newPage();
return {
page,
context,
getLog: async () => {
await context.close();
return JSON.parse(fs.readFileSync(harPath).toString())['log'] as Log;
},
getZip: async () => {
await context.close();
return parseHar(harPath);
},
};
}
it('should throw without path', async ({ browser }) => {
const error = await browser.newContext({ recordHar: {} as any }).catch(e => e);
expect(error.message).toContain('recordHar.path: expected string, got undefined');
});
it('should have version and creator', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.EMPTY_PAGE);
const log = await getLog();
expect(log.version).toBe('1.2');
expect(log.creator.name).toBe('Playwright');
expect(log.creator.version).toBe(require('../../package.json')['version']);
});
it('should have browser', async ({ browserName, browser, contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.EMPTY_PAGE);
const log = await getLog();
expect(log.browser.name.toLowerCase()).toBe(browserName);
expect(log.browser.version).toBe(browser.version());
});
it('should have pages', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto('data:text/html,<title>Hello</title>');
// For data: load comes before domcontentloaded...
await page.waitForLoadState('domcontentloaded');
const log = await getLog();
expect(log.pages.length).toBe(1);
const pageEntry = log.pages[0];
expect(pageEntry.id).toBeTruthy();
expect(pageEntry.title).toBe('Hello');
expect(new Date(pageEntry.startedDateTime).valueOf()).toBeGreaterThan(Date.now() - 3600 * 1000);
expect(pageEntry.pageTimings.onContentLoad).toBeGreaterThan(0);
expect(pageEntry.pageTimings.onLoad).toBeGreaterThan(0);
});
it('should have pages in persistent context', async ({ launchPersistent, browserName }, testInfo) => {
const harPath = testInfo.outputPath('test.har');
const { context, page } = await launchPersistent({ recordHar: { path: harPath } });
await page.goto('data:text/html,<title>Hello</title>');
// For data: load comes before domcontentloaded...
await page.waitForLoadState('domcontentloaded');
await context.close();
const log = JSON.parse(fs.readFileSync(harPath).toString())['log'];
let pageEntry;
if (browserName === 'webkit') {
// Explicit locale emulation forces a new page creation when
// doing a new context.
// See https://github.com/microsoft/playwright/blob/13dd41c2e36a63f35ddef5dc5dec322052d670c6/packages/playwright-core/src/server/browserContext.ts#L232-L242
expect(log.pages.length).toBe(2);
pageEntry = log.pages[1];
} else {
expect(log.pages.length).toBe(1);
pageEntry = log.pages[0];
}
expect(pageEntry.id).toBeTruthy();
expect(pageEntry.title).toBe('Hello');
});
it('should include request', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.EMPTY_PAGE);
const log = await getLog();
expect(log.entries.length).toBe(1);
const entry = log.entries[0];
expect(entry.pageref).toBe(log.pages[0].id);
expect(entry.request.url).toBe(server.EMPTY_PAGE);
expect(entry.request.method).toBe('GET');
expect(entry.request.httpVersion).toBe('HTTP/1.1');
expect(entry.request.headers.length).toBeGreaterThan(1);
expect(entry.request.headers.find(h => h.name.toLowerCase() === 'user-agent')).toBeTruthy();
expect(entry.request.bodySize).toBe(0);
});
it('should include response', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.EMPTY_PAGE);
const log = await getLog();
const entry = log.entries[0];
expect(entry.response.status).toBe(200);
expect(entry.response.statusText).toBe('OK');
expect(entry.response.httpVersion).toBe('HTTP/1.1');
expect(entry.response.headers.length).toBeGreaterThan(1);
expect(entry.response.headers.find(h => h.name.toLowerCase() === 'content-type').value).toContain('text/html');
});
it('should include redirectURL', async ({ contextFactory, server }, testInfo) => {
server.setRedirect('/foo.html', '/empty.html');
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.PREFIX + '/foo.html');
const log = await getLog();
expect(log.entries.length).toBe(2);
const entry = log.entries[0];
expect(entry.response.status).toBe(302);
expect(entry.response.redirectURL).toBe(server.EMPTY_PAGE);
});
it('should include query params', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.PREFIX + '/har.html?name=value');
const log = await getLog();
expect(log.entries[0].request.queryString).toEqual([{ name: 'name', value: 'value' }]);
});
it('should include postData', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => fetch('./post', { method: 'POST', body: 'Hello' }));
const log = await getLog();
expect(log.entries[1].request.postData).toEqual({
mimeType: 'text/plain;charset=UTF-8',
params: [],
text: 'Hello'
});
});
it('should include binary postData', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.EMPTY_PAGE);
await page.evaluate(async () => {
await fetch('./post', { method: 'POST', body: new Uint8Array(Array.from(Array(16).keys())) });
});
const log = await getLog();
expect(log.entries[1].request.postData).toEqual({
mimeType: 'application/octet-stream',
params: [],
text: ''
});
});
it('should include form params', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.EMPTY_PAGE);
await page.setContent(`<form method='POST' action='/post'><input type='text' name='foo' value='bar'><input type='number' name='baz' value='123'><input type='submit'></form>`);
await page.click('input[type=submit]');
const log = await getLog();
expect(log.entries[1].request.postData).toEqual({
mimeType: 'application/x-www-form-urlencoded',
params: [
{ name: 'foo', value: 'bar' },
{ name: 'baz', value: '123' }
],
text: 'foo=bar&baz=123'
});
});
it('should include cookies', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
const context = page.context();
await context.addCookies([
{ name: 'name1', value: '"value1"', domain: 'localhost', path: '/', httpOnly: true },
{ name: 'name2', value: 'val"ue2', domain: 'localhost', path: '/', sameSite: 'Lax' },
{ name: 'name3', value: 'val=ue3', domain: 'localhost', path: '/' },
{ name: 'name4', value: 'val,ue4', domain: 'localhost', path: '/' },
]);
await page.goto(server.EMPTY_PAGE);
const log = await getLog();
expect(log.entries[0].request.cookies).toEqual([
{ name: 'name1', value: '"value1"' },
{ name: 'name2', value: 'val"ue2' },
{ name: 'name3', value: 'val=ue3' },
{ name: 'name4', value: 'val,ue4' },
]);
});
it('should include set-cookies', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
server.setRoute('/empty.html', (req, res) => {
res.setHeader('Set-Cookie', [
'name1=value1; HttpOnly',
'name2="value2"',
'name3=value4; Path=/; Domain=example.com; Max-Age=1500',
]);
res.end();
});
await page.goto(server.EMPTY_PAGE);
const log = await getLog();
const cookies = log.entries[0].response.cookies;
expect(cookies[0]).toEqual({ name: 'name1', value: 'value1', httpOnly: true });
expect(cookies[1]).toEqual({ name: 'name2', value: '"value2"' });
expect(new Date(cookies[2].expires).valueOf()).toBeGreaterThan(Date.now());
});
it('should include set-cookies with comma', async ({ contextFactory, server, browserName }, testInfo) => {
it.fixme(browserName === 'webkit', 'We get "name1=val, ue1, name2=val, ue2" as a header value');
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
server.setRoute('/empty.html', (req, res) => {
res.setHeader('Set-Cookie', [
'name1=val, ue1', 'name2=val, ue2',
]);
res.end();
});
await page.goto(server.EMPTY_PAGE);
const log = await getLog();
const cookies = log.entries[0].response.cookies;
expect(cookies[0]).toEqual({ name: 'name1', value: 'val, ue1' });
expect(cookies[1]).toEqual({ name: 'name2', value: 'val, ue2' });
});
it('should include secure set-cookies', async ({ contextFactory, httpsServer }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
httpsServer.setRoute('/empty.html', (req, res) => {
res.setHeader('Set-Cookie', [
'name1=value1; Secure',
]);
res.end();
});
await page.goto(httpsServer.EMPTY_PAGE);
const log = await getLog();
const cookies = log.entries[0].response.cookies;
expect(cookies[0]).toEqual({ name: 'name1', value: 'value1', secure: true });
});
it('should record request overrides', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
page.route('**/foo', route => {
route.fallback({
url: server.EMPTY_PAGE,
method: 'POST',
headers: {
...route.request().headers(),
'content-type': 'text/plain',
'cookie': 'foo=bar',
'custom': 'value'
},
postData: 'Hi!'
});
});
await page.goto(server.PREFIX + '/foo');
const log = await getLog();
const request = log.entries[0].request;
expect(request.url).toBe(server.EMPTY_PAGE);
expect(request.method).toBe('POST');
expect(request.headers).toContainEqual({ name: 'custom', value: 'value' });
expect(request.cookies).toContainEqual({ name: 'foo', value: 'bar' });
expect(request.postData).toEqual({ 'mimeType': 'text/plain', 'params': [], 'text': 'Hi!' });
});
it('should include content @smoke', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.PREFIX + '/har.html');
await page.evaluate(() => fetch('/pptr.png').then(r => r.arrayBuffer()));
const log = await getLog();
expect(log.entries[0].response.content.encoding).toBe(undefined);
expect(log.entries[0].response.content.mimeType).toBe('text/html; charset=utf-8');
expect(log.entries[0].response.content.text).toContain('HAR Page');
expect(log.entries[0].response.content.size).toBeGreaterThanOrEqual(96);
expect(log.entries[0].response.content.compression).toBe(0);
expect(log.entries[1].response.content.encoding).toBe(undefined);
expect(log.entries[1].response.content.mimeType).toBe('text/css; charset=utf-8');
expect(log.entries[1].response.content.text).toContain('pink');
expect(log.entries[1].response.content.size).toBeGreaterThanOrEqual(37);
expect(log.entries[1].response.content.compression).toBe(0);
expect(log.entries[2].response.content.encoding).toBe('base64');
expect(log.entries[2].response.content.mimeType).toBe('image/png');
expect(Buffer.from(log.entries[2].response.content.text, 'base64').byteLength).toBeGreaterThan(0);
expect(log.entries[2].response.content.size).toBeGreaterThanOrEqual(6000);
expect(log.entries[2].response.content.compression).toBe(0);
});
it('should use attach mode for zip extension', async ({ contextFactory, server }, testInfo) => {
const { page, getZip } = await pageWithHar(contextFactory, testInfo, { outputPath: 'test.har.zip' });
await page.goto(server.PREFIX + '/har.html');
await page.evaluate(() => fetch('/pptr.png').then(r => r.arrayBuffer()));
const zip = await getZip();
const log = JSON.parse(zip.get('har.har').toString())['log'] as Log;
expect(log.entries[0].response.content.text).toBe(undefined);
expect(zip.get('75841480e2606c03389077304342fac2c58ccb1b.html').toString()).toContain('HAR Page');
});
it('should omit content', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo, { content: 'omit', outputPath: 'test.har' });
await page.goto(server.PREFIX + '/har.html');
await page.evaluate(() => fetch('/pptr.png').then(r => r.arrayBuffer()));
const log = await getLog();
expect(log.entries[0].response.content.text).toBe(undefined);
expect(log.entries[0].response.content._file).toBe(undefined);
});
it('should omit content legacy', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo, { omitContent: true, outputPath: 'test.har' });
await page.goto(server.PREFIX + '/har.html');
await page.evaluate(() => fetch('/pptr.png').then(r => r.arrayBuffer()));
const log = await getLog();
expect(log.entries[0].response.content.text).toBe(undefined);
expect(log.entries[0].response.content._file).toBe(undefined);
});
it('should attach content', async ({ contextFactory, server }, testInfo) => {
const { page, getZip } = await pageWithHar(contextFactory, testInfo, { content: 'attach', outputPath: 'test.har.zip' });
await page.goto(server.PREFIX + '/har.html');
await page.evaluate(() => fetch('/pptr.png').then(r => r.arrayBuffer()));
const zip = await getZip();
const log = JSON.parse(zip.get('har.har').toString())['log'] as Log;
expect(log.entries[0].response.content.encoding).toBe(undefined);
expect(log.entries[0].response.content.mimeType).toBe('text/html; charset=utf-8');
expect(log.entries[0].response.content._file).toContain('75841480e2606c03389077304342fac2c58ccb1b');
expect(log.entries[0].response.content.size).toBeGreaterThanOrEqual(96);
expect(log.entries[0].response.content.compression).toBe(0);
expect(log.entries[1].response.content.encoding).toBe(undefined);
expect(log.entries[1].response.content.mimeType).toBe('text/css; charset=utf-8');
expect(log.entries[1].response.content._file).toContain('79f739d7bc88e80f55b9891a22bf13a2b4e18adb');
expect(log.entries[1].response.content.size).toBeGreaterThanOrEqual(37);
expect(log.entries[1].response.content.compression).toBe(0);
expect(log.entries[2].response.content.encoding).toBe(undefined);
expect(log.entries[2].response.content.mimeType).toBe('image/png');
expect(log.entries[2].response.content._file).toContain('a4c3a18f0bb83f5d9fe7ce561e065c36205762fa');
expect(log.entries[2].response.content.size).toBeGreaterThanOrEqual(6000);
expect(log.entries[2].response.content.compression).toBe(0);
expect(zip.get('75841480e2606c03389077304342fac2c58ccb1b.html').toString()).toContain('HAR Page');
expect(zip.get('79f739d7bc88e80f55b9891a22bf13a2b4e18adb.css').toString()).toContain('pink');
expect(zip.get('a4c3a18f0bb83f5d9fe7ce561e065c36205762fa.png').byteLength).toBe(log.entries[2].response.content.size);
});
it('should filter by glob', async ({ contextFactory, server }, testInfo) => {
const harPath = testInfo.outputPath('test.har');
const context = await contextFactory({ baseURL: server.PREFIX, recordHar: { path: harPath, urlFilter: '/*.css' }, ignoreHTTPSErrors: true });
const page = await context.newPage();
await page.goto('/har.html');
await context.close();
const log = JSON.parse(fs.readFileSync(harPath).toString())['log'] as Log;
expect(log.entries.length).toBe(1);
expect(log.entries[0].request.url.endsWith('one-style.css')).toBe(true);
});
it('should filter by regexp', async ({ contextFactory, server }, testInfo) => {
const harPath = testInfo.outputPath('test.har');
const context = await contextFactory({ recordHar: { path: harPath, urlFilter: /HAR.X?HTML/i }, ignoreHTTPSErrors: true });
const page = await context.newPage();
await page.goto(server.PREFIX + '/har.html');
await context.close();
const log = JSON.parse(fs.readFileSync(harPath).toString())['log'] as Log;
expect(log.entries.length).toBe(1);
expect(log.entries[0].request.url.endsWith('har.html')).toBe(true);
});
it('should include sizes', async ({ contextFactory, server, asset }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.PREFIX + '/har.html');
const log = await getLog();
expect(log.entries.length).toBe(2);
expect(log.entries[0].request.url.endsWith('har.html')).toBe(true);
expect(log.entries[0].request.headersSize).toBeGreaterThanOrEqual(100);
expect(log.entries[0].response.bodySize).toBe(fs.statSync(asset('har.html')).size);
expect(log.entries[0].response.headersSize).toBeGreaterThanOrEqual(100);
expect(log.entries[0].response._transferSize).toBeGreaterThanOrEqual(250);
expect(log.entries[1].request.url.endsWith('one-style.css')).toBe(true);
expect(log.entries[1].response.bodySize).toBe(fs.statSync(asset('one-style.css')).size);
expect(log.entries[1].response.headersSize).toBeGreaterThanOrEqual(100);
expect(log.entries[1].response._transferSize).toBeGreaterThanOrEqual(150);
});
it('should work with gzip compression', async ({ contextFactory, server, browserName }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
server.enableGzip('/simplezip.json');
const response = await page.goto(server.PREFIX + '/simplezip.json');
expect(response.headers()['content-encoding']).toBe('gzip');
const log = await getLog();
expect(log.entries.length).toBe(1);
expect(log.entries[0].response.content.compression).toBeGreaterThan(4000);
});
it('should calculate time', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.PREFIX + '/har.html');
const log = await getLog();
expect(log.entries[0].time).toBeGreaterThan(0);
});
it('should return receive time', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.PREFIX + '/har.html');
const log = await getLog();
expect(log.entries[0].timings.receive).toBeGreaterThan(0);
});
it('should report the correct _transferSize with PNG files', async ({ contextFactory, server, asset }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.EMPTY_PAGE);
await page.setContent(`
<img src="${server.PREFIX}/pptr.png" />
`);
const log = await getLog();
expect(log.entries[1].response._transferSize).toBeGreaterThan(fs.statSync(asset('pptr.png')).size);
});
it('should have -1 _transferSize when its a failed request', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
server.setRoute('/one-style.css', (req, res) => {
res.setHeader('Content-Type', 'text/css');
res.socket.destroy();
});
const failedRequests = [];
page.on('requestfailed', request => failedRequests.push(request));
await page.goto(server.PREFIX + '/har.html');
const log = await getLog();
expect(log.entries[1].request.url.endsWith('/one-style.css')).toBe(true);
expect(log.entries[1].response._transferSize).toBe(-1);
});
it('should record failed request headers', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
server.setRoute('/har.html', (req, res) => {
res.socket.destroy();
});
await page.goto(server.PREFIX + '/har.html').catch(() => {});
const log = await getLog();
expect(log.entries[0].response._failureText).toBeTruthy();
const request = log.entries[0].request;
expect(request.url.endsWith('/har.html')).toBe(true);
expect(request.method).toBe('GET');
expect(request.headers).toContainEqual(expect.objectContaining({ name: 'User-Agent' }));
});
it('should record failed request overrides', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
server.setRoute('/empty.html', (req, res) => {
res.socket.destroy();
});
await page.route('**/foo', route => {
route.fallback({
url: server.EMPTY_PAGE,
method: 'POST',
headers: {
...route.request().headers(),
'content-type': 'text/plain',
'cookie': 'foo=bar',
'custom': 'value'
},
postData: 'Hi!'
});
});
await page.goto(server.PREFIX + '/foo').catch(() => {});
const log = await getLog();
expect(log.entries[0].response._failureText).toBeTruthy();
const request = log.entries[0].request;
expect(request.url).toBe(server.EMPTY_PAGE);
expect(request.method).toBe('POST');
expect(request.headers).toContainEqual({ name: 'custom', value: 'value' });
expect(request.cookies).toContainEqual({ name: 'foo', value: 'bar' });
expect(request.postData).toEqual({ 'mimeType': 'text/plain', 'params': [], 'text': 'Hi!' });
});
it('should report the correct request body size', async ({ contextFactory, server }, testInfo) => {
server.setRoute('/api', (req, res) => res.end());
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.EMPTY_PAGE);
await Promise.all([
page.waitForResponse(server.PREFIX + '/api1'),
page.evaluate(() => {
fetch('/api1', {
method: 'POST',
body: 'abc123'
});
})
]);
const log = await getLog();
expect(log.entries[1].request.bodySize).toBe(6);
});
it('should report the correct request body size when the bodySize is 0', async ({ contextFactory, server }, testInfo) => {
server.setRoute('/api', (req, res) => res.end());
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.EMPTY_PAGE);
await Promise.all([
page.waitForResponse(server.PREFIX + '/api2'),
page.evaluate(() => {
fetch('/api2', {
method: 'POST',
body: ''
});
})
]);
const log = await getLog();
expect(log.entries[1].request.bodySize).toBe(0);
});
it('should report the correct response body size when the bodySize is 0', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
const response = await page.goto(server.EMPTY_PAGE);
await response.finished();
const log = await getLog();
expect(log.entries[0].response.bodySize).toBe(0);
});
it('should have popup requests', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.EMPTY_PAGE);
await page.setContent('<a target=_blank rel=noopener href="/one-style.html">yo</a>');
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.click('a'),
]);
await popup.waitForLoadState();
const log = await getLog();
expect(log.pages.length).toBe(2);
const entries = log.entries.filter(entry => entry.pageref === log.pages[1].id);
expect(entries.length).toBe(2);
expect(entries[0].request.url).toBe(server.PREFIX + '/one-style.html');
expect(entries[0].response.status).toBe(200);
expect(entries[1].request.url).toBe(server.PREFIX + '/one-style.css');
expect(entries[1].response.status).toBe(200);
});
it('should not contain internal pages', async ({ browserName, contextFactory, server }, testInfo) => {
it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/6743' });
server.setRoute('/empty.html', (req, res) => {
res.setHeader('Set-Cookie', 'name=value');
res.end();
});
const { page, context, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.EMPTY_PAGE);
const cookies = await context.cookies();
expect(cookies.length).toBe(1);
// Get storage state, this create internal page.
await context.storageState();
const log = await getLog();
expect(log.pages.length).toBe(1);
});
it('should have connection details', async ({ contextFactory, server, browserName, platform, mode }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.EMPTY_PAGE);
const log = await getLog();
const { serverIPAddress, _serverPort: port, _securityDetails: securityDetails } = log.entries[0];
expect(serverIPAddress).toMatch(/^127\.0\.0\.1|\[::1\]/);
if (mode !== 'service')
expect(port).toBe(server.PORT);
expect(securityDetails).toEqual({});
});
it('should have security details', async ({ contextFactory, httpsServer, browserName, platform, mode }, testInfo) => {
it.fail(browserName === 'webkit' && platform === 'linux', 'https://github.com/microsoft/playwright/issues/6759');
it.fail(browserName === 'webkit' && platform === 'win32');
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(httpsServer.EMPTY_PAGE);
const log = await getLog();
const { serverIPAddress, _serverPort: port, _securityDetails: securityDetails } = log.entries[0];
expect(serverIPAddress).toMatch(/^127\.0\.0\.1|\[::1\]/);
if (mode !== 'service')
expect(port).toBe(httpsServer.PORT);
if (browserName === 'webkit' && platform === 'darwin')
expect(securityDetails).toEqual({ protocol: 'TLS 1.3', subjectName: 'puppeteer-tests', validFrom: 1550084863, validTo: 33086084863 });
else
expect(securityDetails).toEqual({ issuer: 'puppeteer-tests', protocol: 'TLS 1.3', subjectName: 'puppeteer-tests', validFrom: 1550084863, validTo: 33086084863 });
});
it('should have connection details for redirects', async ({ contextFactory, server, browserName, mode }, testInfo) => {
server.setRedirect('/foo.html', '/empty.html');
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.PREFIX + '/foo.html');
const log = await getLog();
expect(log.entries.length).toBe(2);
const detailsFoo = log.entries[0];
if (browserName === 'webkit') {
expect(detailsFoo.serverIPAddress).toBeUndefined();
expect(detailsFoo._serverPort).toBeUndefined();
} else {
expect(detailsFoo.serverIPAddress).toMatch(/^127\.0\.0\.1|\[::1\]/);
if (mode !== 'service')
expect(detailsFoo._serverPort).toBe(server.PORT);
}
const detailsEmpty = log.entries[1];
expect(detailsEmpty.serverIPAddress).toMatch(/^127\.0\.0\.1|\[::1\]/);
if (mode !== 'service')
expect(detailsEmpty._serverPort).toBe(server.PORT);
});
it('should have connection details for failed requests', async ({ contextFactory, server, browserName, platform, mode }, testInfo) => {
server.setRoute('/one-style.css', (_, res) => {
res.setHeader('Content-Type', 'text/css');
res.socket.destroy();
});
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.PREFIX + '/one-style.html');
const log = await getLog();
const { serverIPAddress, _serverPort: port } = log.entries[0];
expect(serverIPAddress).toMatch(/^127\.0\.0\.1|\[::1\]/);
if (mode !== 'service')
expect(port).toBe(server.PORT);
});
it('should return server address directly from response', async ({ page, server, mode }) => {
const response = await page.goto(server.EMPTY_PAGE);
const { ipAddress, port } = await response.serverAddr();
expect(ipAddress).toMatch(/^127\.0\.0\.1|\[::1\]/);
if (mode !== 'service')
expect(port).toBe(server.PORT);
});
it('should return security details directly from response', async ({ contextFactory, httpsServer, browserName, platform }) => {
it.fail(browserName === 'webkit' && platform === 'linux', 'https://github.com/microsoft/playwright/issues/6759');
it.fail(browserName === 'webkit' && platform === 'win32');
const context = await contextFactory({ ignoreHTTPSErrors: true });
const page = await context.newPage();
const response = await page.goto(httpsServer.EMPTY_PAGE);
const securityDetails = await response.securityDetails();
if (browserName === 'webkit' && platform === 'win32')
expect(securityDetails).toEqual({ subjectName: 'puppeteer-tests', validFrom: 1550084863, validTo: -1 });
else if (browserName === 'webkit')
expect(securityDetails).toEqual({ protocol: 'TLS 1.3', subjectName: 'puppeteer-tests', validFrom: 1550084863, validTo: 33086084863 });
else
expect(securityDetails).toEqual({ issuer: 'puppeteer-tests', protocol: 'TLS 1.3', subjectName: 'puppeteer-tests', validFrom: 1550084863, validTo: 33086084863 });
});
it('should contain http2 for http2 requests', async ({ contextFactory, browserName, platform }, testInfo) => {
it.fixme(browserName === 'webkit' && platform === 'linux');
it.fixme(browserName === 'webkit' && platform === 'win32');
const server = http2.createSecureServer({
key: await fs.promises.readFile(path.join(__dirname, '..', '..', 'utils', 'testserver', 'key.pem')),
cert: await fs.promises.readFile(path.join(__dirname, '..', '..', 'utils', 'testserver', 'cert.pem')),
});
server.on('stream', stream => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200
});
stream.end('<h1>Hello World</h1>');
});
server.listen(0);
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(`https://localhost:${(server.address() as AddressInfo).port}`);
const log = await getLog();
expect(log.entries[0].request.httpVersion).toBe('HTTP/2.0');
expect(log.entries[0].response.httpVersion).toBe('HTTP/2.0');
expect(log.entries[0].response.content.text).toBe('<h1>Hello World</h1>');
server.close();
});
it('should filter favicon and favicon redirects', async ({ server, browserName, channel, headless, asset, contextFactory }, testInfo) => {
it.skip(headless && browserName !== 'firefox', 'headless browsers, except firefox, do not request favicons');
it.skip(!headless && browserName === 'webkit' && !channel, 'headed webkit does not have a favicon feature');
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
// Browsers aggresively cache favicons, so force bust with the
// `d` parameter to make iterating on this test more predictable and isolated.
const favicon = `/no-cache-2/favicon.ico`;
const hashedFaviconUrl = `/favicon-hashed.ico`;
server.setRedirect(favicon, hashedFaviconUrl);
server.setRoute(hashedFaviconUrl, (req, res) => {
server.serveFile(req, res, asset('media-query-prefers-color-scheme.svg'));
});
server.setRoute('/page.html', (_, res) => {
res.end(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="icon" type="image/svg+xml" href="${favicon}">
<title>SVG Favicon Test</title>
</head>
<body>
favicons
</body>
</html>
`);
});
await Promise.all([
server.waitForRequest(favicon),
server.waitForRequest(hashedFaviconUrl),
page.goto(server.PREFIX + '/page.html'),
]);
await page.waitForTimeout(500);
// Text still being around ensures we haven't actually lost our browser to a crash.
await page.waitForSelector('text=favicons');
// favicon and 302 redirects to favicons should be filtered out of request logs
const log = await getLog();
expect(log.entries.length).toBe(1);
const entry = log.entries[0];
expect(entry.request.url).toBe(server.PREFIX + '/page.html');
});
it('should have different hars for concurrent contexts', async ({ contextFactory }, testInfo) => {
const session0 = await pageWithHar(contextFactory, testInfo, { outputPath: 'test-0.har' });
await session0.page.goto('data:text/html,<title>Zero</title>');
await session0.page.waitForLoadState('domcontentloaded');
const session1 = await pageWithHar(contextFactory, testInfo, { outputPath: 'test-1.har' });
await session1.page.goto('data:text/html,<title>One</title>');
await session1.page.waitForLoadState('domcontentloaded');
// Trigger flushing on the server and ensure they are not racing to same
// location. NB: Run this test with --repeat-each 10.
const [log0, log1] = await Promise.all([
session0.getLog(),
session1.getLog()
]);
{
expect(log0.pages.length).toBe(1);
const pageEntry = log0.pages[0];
expect(pageEntry.title).toBe('Zero');
}
{
expect(log1.pages.length).toBe(1);
const pageEntry = log1.pages[0];
expect(pageEntry.id).not.toBe(log0.pages[0].id);
expect(pageEntry.title).toBe('One');
}
});
it('should include API request', async ({ contextFactory, server }, testInfo) => {
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
const url = server.PREFIX + '/simple.json';
const response = await page.request.post(url, {
headers: { cookie: 'a=b; c=d' },
data: { foo: 'bar' }
});
const responseBody = await response.body();
const log = await getLog();
expect(log.entries.length).toBe(1);
const entry = log.entries[0];
expect(entry.request.url).toBe(url);
expect(entry.request.method).toBe('POST');
expect(entry.request.httpVersion).toBe('HTTP/1.1');
expect(entry.request.cookies).toEqual([
{
'name': 'a',
'value': 'b'
},
{
'name': 'c',
'value': 'd'
}
]);
expect(entry.request.headers.length).toBeGreaterThan(1);
expect(entry.request.headers.find(h => h.name.toLowerCase() === 'user-agent')).toBeTruthy();
expect(entry.request.headers.find(h => h.name.toLowerCase() === 'content-type')?.value).toBe('application/json');
expect(entry.request.headers.find(h => h.name.toLowerCase() === 'content-length')?.value).toBe('13');
expect(entry.request.bodySize).toBe(13);
expect(entry.response.status).toBe(200);
expect(entry.response.headers.find(h => h.name.toLowerCase() === 'content-type')?.value).toContain('application/json');
expect(entry.response.content.size).toBe(15);
expect(entry.response.content.text).toBe(responseBody.toString());
});
it('should not hang on resources served from cache', async ({ contextFactory, server, browserName }, testInfo) => {
it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/11435' });
server.setRoute('/one-style.css', (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/css',
'Cache-Control': 'public, max-age=10031518'
});
res.end(`body { background: red }`);
});
const { page, getLog } = await pageWithHar(contextFactory, testInfo);
await page.goto(server.PREFIX + '/har.html');
await page.goto(server.PREFIX + '/har.html');
const log = await getLog();
const entries = log.entries.filter(e => e.request.url.endsWith('one-style.css'));
// In firefox no request events are fired for cached resources.
if (browserName === 'firefox')
expect(entries.length).toBe(1);
else
expect(entries.length).toBe(2);
});
| tests/library/har.spec.ts | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.00017837484483607113,
0.00017328553076367825,
0.00016749183123465627,
0.00017325248336419463,
0.0000020723368834296707
] |
{
"id": 4,
"code_window": [
" BRANCH_NAME=\"roll-driver-nodejs/$(date +%Y-%b-%d)\"\n",
" echo \"::set-output name=BRANCH_NAME::$BRANCH_NAME\"\n",
" git config --global user.name github-actions\n",
" git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com\n",
" git checkout -b \"$BRANCH_NAME\"\n",
" git add .\n",
" git commit -m \"chore(driver): roll driver to recent Node.js LTS version\"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"BRANCH_NAME=$BRANCH_NAME\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/roll_driver_nodejs.yml",
"type": "replace",
"edit_start_line_idx": 26
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { test, expect } from './pageTest';
test('should work', async ({ page, server, toImpl }) => {
await page.goto(server.EMPTY_PAGE);
const result = await toImpl(page.mainFrame()).nonStallingRawEvaluateInExistingMainContext('2+2');
expect(result).toBe(4);
});
test('should throw while pending navigation', async ({ page, server, toImpl }) => {
await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => document.body.textContent = 'HELLO WORLD');
let error;
await page.route('**/empty.html', async (route, request) => {
error = await toImpl(page.mainFrame()).nonStallingRawEvaluateInExistingMainContext('2+2').catch(e => e);
route.abort();
});
await page.goto(server.EMPTY_PAGE).catch(() => {});
expect(error.message).toContain('Frame is currently attempting a navigation');
});
test('should throw when no main execution context', async ({ page, toImpl }) => {
let errorPromise;
page.on('frameattached', frame => {
errorPromise = toImpl(frame).nonStallingRawEvaluateInExistingMainContext('2+2').catch(e => e);
});
await page.setContent('<iframe></iframe>');
const error = await errorPromise;
// bail out if we accidentally succeeded
if (error === 4)
return;
// Testing this as a race.
expect([
'Frame does not yet have a main execution context',
'Frame is currently attempting a navigation',
'Navigation interrupted the evaluation',
]).toContain(error.message);
});
| tests/page/page-evaluate-no-stall.spec.ts | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.00017579032282810658,
0.00017307310190517455,
0.0001719057618174702,
0.00017250885139219463,
0.0000013548569768317975
] |
{
"id": 4,
"code_window": [
" BRANCH_NAME=\"roll-driver-nodejs/$(date +%Y-%b-%d)\"\n",
" echo \"::set-output name=BRANCH_NAME::$BRANCH_NAME\"\n",
" git config --global user.name github-actions\n",
" git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com\n",
" git checkout -b \"$BRANCH_NAME\"\n",
" git add .\n",
" git commit -m \"chore(driver): roll driver to recent Node.js LTS version\"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" echo \"BRANCH_NAME=$BRANCH_NAME\" >> $GITHUB_OUTPUT\n"
],
"file_path": ".github/workflows/roll_driver_nodejs.yml",
"type": "replace",
"edit_start_line_idx": 26
} | const { app, BrowserWindow } = require('electron');
app.whenReady().then(() => {
const win = new BrowserWindow({
width: 800,
height: 600,
});
win.loadURL('about:blank');
})
app.on('window-all-closed', e => e.preventDefault());
| tests/electron/electron-window-app.js | 0 | https://github.com/microsoft/playwright/commit/d962f3b70a87cd41bbdcccba404d09729a9defc5 | [
0.00016877871530596167,
0.00016848977247718722,
0.00016820082964841276,
0.00016848977247718722,
2.889428287744522e-7
] |
{
"id": 0,
"code_window": [
"import React, { Component, PropTypes } from 'react';\n",
"import { createStyleSheet } from 'jss-theme-reactor';\n",
"import { LabelRadio, RadioGroup } from 'material-ui/Radio';\n",
"import { FormLabel } from 'material-ui/Form';\n",
"\n",
"const styleSheet = createStyleSheet('RadioButtonsGroup', () => ({\n",
" group: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { FormLabel, FormControl } from 'material-ui/Form';\n"
],
"file_path": "docs/site/src/demos/selection-controls/RadioButtonsGroup.js",
"type": "replace",
"edit_start_line_idx": 5
} | // @flow weak
import React, { Component, PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import { LabelRadio, RadioGroup } from 'material-ui/Radio';
import { FormLabel } from 'material-ui/Form';
const styleSheet = createStyleSheet('RadioButtonsGroup', () => ({
group: {
margin: '8px 0',
},
}));
export default class RadioButtonsGroup extends Component {
static contextTypes = {
styleManager: PropTypes.object.isRequired,
};
state = {
selectedValue: undefined,
};
handleChange = (event, value) => {
this.setState({ selectedValue: value });
};
render() {
const classes = this.context.styleManager.render(styleSheet);
return (
<div>
<FormLabel required>Gender</FormLabel>
<RadioGroup
aria-label="Gender"
name="gender"
className={classes.group}
selectedValue={this.state.selectedValue}
onChange={this.handleChange}
>
<LabelRadio label="Male" value="male" />
<LabelRadio label="Female" value="female" />
<LabelRadio label="Other" value="other" />
<LabelRadio label="Disabled" value="disabled" disabled />
</RadioGroup>
</div>
);
}
}
| docs/site/src/demos/selection-controls/RadioButtonsGroup.js | 1 | https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846 | [
0.9986653327941895,
0.3998287320137024,
0.00016702996799722314,
0.0017988525796681643,
0.4887984097003937
] |
{
"id": 0,
"code_window": [
"import React, { Component, PropTypes } from 'react';\n",
"import { createStyleSheet } from 'jss-theme-reactor';\n",
"import { LabelRadio, RadioGroup } from 'material-ui/Radio';\n",
"import { FormLabel } from 'material-ui/Form';\n",
"\n",
"const styleSheet = createStyleSheet('RadioButtonsGroup', () => ({\n",
" group: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { FormLabel, FormControl } from 'material-ui/Form';\n"
],
"file_path": "docs/site/src/demos/selection-controls/RadioButtonsGroup.js",
"type": "replace",
"edit_start_line_idx": 5
} | /* eslint-disable flowtype/require-valid-file-annotation */
import React, { Component, PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import { createStyleSheet } from 'jss-theme-reactor';
import classNames from 'classnames';
import keycode from 'keycode';
import { listenForFocusKeys, detectKeyboardFocus, focusKeyPressed } from '../utils/keyboardFocus';
import { TouchRipple, createRippleHandler } from '../Ripple';
export const styleSheet = createStyleSheet('ButtonBase', () => {
return {
buttonBase: {
position: 'relative',
WebkitTapHighlightColor: 'rgba(0,0,0,0.0)',
outline: 'none',
border: 0,
cursor: 'pointer',
userSelect: 'none',
appearance: 'none',
textDecoration: 'none',
},
disabled: {
cursor: 'not-allowed',
},
};
});
export default class ButtonBase extends Component {
static propTypes = {
centerRipple: PropTypes.bool,
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* The element or component used for the root node.
*/
component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
/**
* If `true`, the base button will be disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the base button will have a keyboard focus ripple.
* `ripple` must also be true.
*/
focusRipple: PropTypes.bool,
keyboardFocusedClassName: PropTypes.string,
onBlur: PropTypes.func,
onClick: PropTypes.func,
onFocus: PropTypes.func,
onKeyboardFocus: PropTypes.func,
onKeyDown: PropTypes.func,
onKeyUp: PropTypes.func,
onMouseDown: PropTypes.func,
onMouseLeave: PropTypes.func,
onMouseUp: PropTypes.func,
onTouchEnd: PropTypes.func,
onTouchStart: PropTypes.func,
/**
* If `true`, the base button will have a ripple.
*/
ripple: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
role: PropTypes.string,
tabIndex: PropTypes.string,
type: PropTypes.string,
};
static defaultProps = {
centerRipple: false,
component: 'button',
focusRipple: false,
ripple: true,
tabIndex: '0',
type: 'button',
};
static contextTypes = {
styleManager: PropTypes.object.isRequired,
};
state = {
keyboardFocused: false,
};
componentDidMount() {
listenForFocusKeys();
}
componentWillUpdate(nextProps, nextState) {
if (this.props.focusRipple) {
if (nextState.keyboardFocused && !this.state.keyboardFocused) {
this.ripple.pulsate();
}
}
}
componentWillUnmount() {
clearTimeout(this.keyboardFocusTimeout);
}
ripple = undefined;
keyDown = false; // Used to help track keyboard activation keyDown
button = null;
keyboardFocusTimeout = undefined;
focus = () => this.button.focus();
handleKeyDown = (event) => {
const { component, focusRipple, onKeyDown, onClick } = this.props;
const key = keycode(event);
// Check if key is already down to avoid repeats being counted as multiple activations
if (focusRipple && !this.keyDown && this.state.keyboardFocused && key === 'space') {
this.keyDown = true;
event.persist();
this.ripple.stop(event, () => {
this.ripple.start(event);
});
}
if (onKeyDown) {
onKeyDown(event);
}
// Keyboard accessibility for non interactive elements
if (
event.target === this.button &&
onClick &&
component !== 'a' &&
component !== 'button' &&
(key === 'space' || key === 'enter')
) {
event.preventDefault();
onClick(event);
}
};
handleKeyUp = (event) => {
if (this.props.focusRipple && keycode(event) === 'space' && this.state.keyboardFocused) {
this.keyDown = false;
event.persist();
this.ripple.stop(event, () => this.ripple.pulsate(event));
}
if (this.props.onKeyUp) {
this.props.onKeyUp(event);
}
};
handleMouseDown = createRippleHandler(this, 'MouseDown', 'start', () => {
clearTimeout(this.keyboardFocusTimeout);
focusKeyPressed(false);
if (this.state.keyboardFocused) {
this.setState({ keyboardFocused: false });
}
});
handleMouseUp = createRippleHandler(this, 'MouseUp', 'stop');
handleMouseLeave = createRippleHandler(this, 'MouseLeave', 'stop', (event) => {
if (this.state.keyboardFocused) {
event.preventDefault();
}
});
handleTouchStart = createRippleHandler(this, 'TouchStart', 'start');
handleTouchEnd = createRippleHandler(this, 'TouchEnd', 'stop');
handleBlur = createRippleHandler(this, 'Blur', 'stop', () => {
this.setState({ keyboardFocused: false });
});
handleFocus = (event) => {
if (this.props.disabled) {
return;
}
event.persist();
detectKeyboardFocus(this, findDOMNode(this.button), () => {
this.keyDown = false;
this.setState({ keyboardFocused: true });
if (this.props.onKeyboardFocus) {
this.props.onKeyboardFocus(event);
}
});
if (this.props.onFocus) {
this.props.onFocus(event);
}
};
renderRipple(ripple, center) {
if (ripple === true && !this.props.disabled) {
return <TouchRipple ref={(c) => { this.ripple = c; }} center={center} />;
}
return null;
}
render() {
const {
centerRipple,
children,
className: classNameProp,
component,
disabled,
focusRipple, // eslint-disable-line no-unused-vars
keyboardFocusedClassName,
onBlur, // eslint-disable-line no-unused-vars
onFocus, // eslint-disable-line no-unused-vars
onKeyDown, // eslint-disable-line no-unused-vars
onKeyUp, // eslint-disable-line no-unused-vars
onMouseDown, // eslint-disable-line no-unused-vars
onMouseLeave, // eslint-disable-line no-unused-vars
onMouseUp, // eslint-disable-line no-unused-vars
onTouchEnd, // eslint-disable-line no-unused-vars
onTouchStart, // eslint-disable-line no-unused-vars
ripple,
tabIndex,
type,
...other
} = this.props;
const classes = this.context.styleManager.render(styleSheet);
const className = classNames(classes.buttonBase, {
[classes.disabled]: disabled,
[keyboardFocusedClassName]: keyboardFocusedClassName && this.state.keyboardFocused,
}, classNameProp);
const buttonProps = {
ref: (c) => { this.button = c; },
onBlur: this.handleBlur,
onFocus: this.handleFocus,
onKeyDown: this.handleKeyDown,
onKeyUp: this.handleKeyUp,
onMouseDown: this.handleMouseDown,
onMouseLeave: this.handleMouseLeave,
onMouseUp: this.handleMouseUp,
onTouchEnd: this.handleTouchEnd,
onTouchStart: this.handleTouchStart,
tabIndex: disabled ? '-1' : tabIndex,
className,
...other,
};
let Element = component;
if (other.href) {
Element = 'a';
}
if (Element === 'button') {
buttonProps.type = type;
buttonProps.disabled = disabled;
} else if (Element !== 'a') {
buttonProps.role = this.props.hasOwnProperty('role') ? this.props.role : 'button';
}
return (
<Element {...buttonProps}>
{children}
{this.renderRipple(ripple, centerRipple)}
</Element>
);
}
}
| src/internal/ButtonBase.js | 0 | https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846 | [
0.9986433386802673,
0.07228293269872665,
0.00016437657177448273,
0.00017060196842066944,
0.253124475479126
] |
{
"id": 0,
"code_window": [
"import React, { Component, PropTypes } from 'react';\n",
"import { createStyleSheet } from 'jss-theme-reactor';\n",
"import { LabelRadio, RadioGroup } from 'material-ui/Radio';\n",
"import { FormLabel } from 'material-ui/Form';\n",
"\n",
"const styleSheet = createStyleSheet('RadioButtonsGroup', () => ({\n",
" group: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { FormLabel, FormControl } from 'material-ui/Form';\n"
],
"file_path": "docs/site/src/demos/selection-controls/RadioButtonsGroup.js",
"type": "replace",
"edit_start_line_idx": 5
} | // @flow weak
import React from 'react';
import {
ListItem,
ListItemText,
ListItemSecondaryAction,
} from 'material-ui/List';
import Checkbox from 'material-ui/Checkbox';
export default function SecondaryActionCheckboxListItem() {
return (
<div style={{ background: '#fff', width: 300 }}>
<ListItem button dense>
<ListItemText primary="Primary" />
<ListItemSecondaryAction>
<Checkbox />
</ListItemSecondaryAction>
</ListItem>
</div>
);
}
| test/regressions/site/src/tests/ListItem/SecondaryActionCheckboxListItem.js | 0 | https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846 | [
0.00017492787446826696,
0.00017155522073153406,
0.0001654344523558393,
0.00017430334992241114,
0.000004335543508204864
] |
{
"id": 0,
"code_window": [
"import React, { Component, PropTypes } from 'react';\n",
"import { createStyleSheet } from 'jss-theme-reactor';\n",
"import { LabelRadio, RadioGroup } from 'material-ui/Radio';\n",
"import { FormLabel } from 'material-ui/Form';\n",
"\n",
"const styleSheet = createStyleSheet('RadioButtonsGroup', () => ({\n",
" group: {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { FormLabel, FormControl } from 'material-ui/Form';\n"
],
"file_path": "docs/site/src/demos/selection-controls/RadioButtonsGroup.js",
"type": "replace",
"edit_start_line_idx": 5
} | // @flow weak
import React from 'react';
import IconButton from 'material-ui/IconButton';
export default function AccentIconButton() {
return (
<IconButton accent>home</IconButton>
);
}
| test/regressions/site/src/tests/IconButton/AccentIconButton.js | 0 | https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846 | [
0.00017585889145266265,
0.00017261947505176067,
0.0001693800586508587,
0.00017261947505176067,
0.0000032394164009019732
] |
{
"id": 1,
"code_window": [
" const classes = this.context.styleManager.render(styleSheet);\n",
"\n",
" return (\n",
" <div>\n",
" <FormLabel required>Gender</FormLabel>\n",
" <RadioGroup\n",
" aria-label=\"Gender\"\n",
" name=\"gender\"\n",
" className={classes.group}\n",
" selectedValue={this.state.selectedValue}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <FormControl required>\n",
" <FormLabel>Gender</FormLabel>\n"
],
"file_path": "docs/site/src/demos/selection-controls/RadioButtonsGroup.js",
"type": "replace",
"edit_start_line_idx": 30
} | // @flow weak
import React, { Component, PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import { LabelRadio, RadioGroup } from 'material-ui/Radio';
import { FormLabel } from 'material-ui/Form';
const styleSheet = createStyleSheet('RadioButtonsGroup', () => ({
group: {
margin: '8px 0',
},
}));
export default class RadioButtonsGroup extends Component {
static contextTypes = {
styleManager: PropTypes.object.isRequired,
};
state = {
selectedValue: undefined,
};
handleChange = (event, value) => {
this.setState({ selectedValue: value });
};
render() {
const classes = this.context.styleManager.render(styleSheet);
return (
<div>
<FormLabel required>Gender</FormLabel>
<RadioGroup
aria-label="Gender"
name="gender"
className={classes.group}
selectedValue={this.state.selectedValue}
onChange={this.handleChange}
>
<LabelRadio label="Male" value="male" />
<LabelRadio label="Female" value="female" />
<LabelRadio label="Other" value="other" />
<LabelRadio label="Disabled" value="disabled" disabled />
</RadioGroup>
</div>
);
}
}
| docs/site/src/demos/selection-controls/RadioButtonsGroup.js | 1 | https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846 | [
0.996360719203949,
0.4198031425476074,
0.00026656375848688185,
0.10878218710422516,
0.47074928879737854
] |
{
"id": 1,
"code_window": [
" const classes = this.context.styleManager.render(styleSheet);\n",
"\n",
" return (\n",
" <div>\n",
" <FormLabel required>Gender</FormLabel>\n",
" <RadioGroup\n",
" aria-label=\"Gender\"\n",
" name=\"gender\"\n",
" className={classes.group}\n",
" selectedValue={this.state.selectedValue}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <FormControl required>\n",
" <FormLabel>Gender</FormLabel>\n"
],
"file_path": "docs/site/src/demos/selection-controls/RadioButtonsGroup.js",
"type": "replace",
"edit_start_line_idx": 30
} | // @flow weak
/* eslint-disable no-console */
const WebpackDevServer = require('webpack-dev-server');
const webpack = require('webpack');
const webpackConfig = require('./webpack.dev.config');
const serverOptions = {
publicPath: webpackConfig.output.publicPath,
hot: true,
historyApiFallback: true,
stats: {
// Remove built modules information.
modules: false,
// Remove built modules information to chunk information.
chunkModules: false,
colors: true,
},
};
const PORT = 3000;
new WebpackDevServer(webpack(webpackConfig), serverOptions)
.listen(PORT, '0.0.0.0', (err) => {
if (err) {
return console.log(err);
}
return console.info(`Webpack dev server listening at http://0.0.0.0:${PORT}/`);
});
| docs/site/webpack.dev.server.js | 0 | https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846 | [
0.00017467603902332485,
0.00017221042071469128,
0.00016961585788521916,
0.00017227490025106817,
0.000001898542677736259
] |
{
"id": 1,
"code_window": [
" const classes = this.context.styleManager.render(styleSheet);\n",
"\n",
" return (\n",
" <div>\n",
" <FormLabel required>Gender</FormLabel>\n",
" <RadioGroup\n",
" aria-label=\"Gender\"\n",
" name=\"gender\"\n",
" className={classes.group}\n",
" selectedValue={this.state.selectedValue}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <FormControl required>\n",
" <FormLabel>Gender</FormLabel>\n"
],
"file_path": "docs/site/src/demos/selection-controls/RadioButtonsGroup.js",
"type": "replace",
"edit_start_line_idx": 30
} | /* eslint-disable flowtype/require-valid-file-annotation */
export default from './Text';
| src/Text/index.js | 0 | https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846 | [
0.00017200809088535607,
0.00017200809088535607,
0.00017200809088535607,
0.00017200809088535607,
0
] |
{
"id": 1,
"code_window": [
" const classes = this.context.styleManager.render(styleSheet);\n",
"\n",
" return (\n",
" <div>\n",
" <FormLabel required>Gender</FormLabel>\n",
" <RadioGroup\n",
" aria-label=\"Gender\"\n",
" name=\"gender\"\n",
" className={classes.group}\n",
" selectedValue={this.state.selectedValue}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <FormControl required>\n",
" <FormLabel>Gender</FormLabel>\n"
],
"file_path": "docs/site/src/demos/selection-controls/RadioButtonsGroup.js",
"type": "replace",
"edit_start_line_idx": 30
} | <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M8 20v14h6V20H8zm12 0v14h6V20h-6zM4 44h38v-6H4v6zm28-24v14h6V20h-6zM23 2L4 12v4h38v-4L23 2z"/></svg> | packages/icon-builder/test/fixtures/material-design-icons/svg/action/svg/production/ic_account_balance_48px.svg | 0 | https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846 | [
0.00017136505630332977,
0.00017136505630332977,
0.00017136505630332977,
0.00017136505630332977,
0
] |
{
"id": 2,
"code_window": [
" <LabelRadio label=\"Other\" value=\"other\" />\n",
" <LabelRadio label=\"Disabled\" value=\"disabled\" disabled />\n",
" </RadioGroup>\n",
" </div>\n",
" );\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" </FormControl>\n"
],
"file_path": "docs/site/src/demos/selection-controls/RadioButtonsGroup.js",
"type": "replace",
"edit_start_line_idx": 44
} | // @flow weak
import React, { Component, PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import { LabelRadio, RadioGroup } from 'material-ui/Radio';
import { FormLabel } from 'material-ui/Form';
const styleSheet = createStyleSheet('RadioButtonsGroup', () => ({
group: {
margin: '8px 0',
},
}));
export default class RadioButtonsGroup extends Component {
static contextTypes = {
styleManager: PropTypes.object.isRequired,
};
state = {
selectedValue: undefined,
};
handleChange = (event, value) => {
this.setState({ selectedValue: value });
};
render() {
const classes = this.context.styleManager.render(styleSheet);
return (
<div>
<FormLabel required>Gender</FormLabel>
<RadioGroup
aria-label="Gender"
name="gender"
className={classes.group}
selectedValue={this.state.selectedValue}
onChange={this.handleChange}
>
<LabelRadio label="Male" value="male" />
<LabelRadio label="Female" value="female" />
<LabelRadio label="Other" value="other" />
<LabelRadio label="Disabled" value="disabled" disabled />
</RadioGroup>
</div>
);
}
}
| docs/site/src/demos/selection-controls/RadioButtonsGroup.js | 1 | https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846 | [
0.20925141870975494,
0.05769212916493416,
0.0001696071121841669,
0.0008252354455180466,
0.08148358017206192
] |
{
"id": 2,
"code_window": [
" <LabelRadio label=\"Other\" value=\"other\" />\n",
" <LabelRadio label=\"Disabled\" value=\"disabled\" disabled />\n",
" </RadioGroup>\n",
" </div>\n",
" );\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" </FormControl>\n"
],
"file_path": "docs/site/src/demos/selection-controls/RadioButtonsGroup.js",
"type": "replace",
"edit_start_line_idx": 44
} | Tabs
====
Props
-----
| Name | Type | Default | Description |
|:-----|:-----|:--------|:------------|
| centered | bool | false | If `true`, the tabs will be centered. This property is intended for large views. |
| children | node | | The content of the `Tabs`. |
| className | string | | The CSS class name of the root element. |
| fullWidth | bool | false | If `true`, the tabs will grow to use all the available space. This property is intended for small views. |
| index | number | | The index of the currently selected `BottomNavigation`. |
| indicatorClassName | string | | The CSS class name of the indicator element. |
| indicatorColor | union | 'accent' | Determines the color of the indicator. |
| onChange | function | | Function called when the index change. |
| textColor | union | 'inherit' | Determines the color of the `Tab`. |
Other properties (not documented) are applied to the root element.
| docs/api/Tabs/Tabs.md | 0 | https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846 | [
0.00023902504472061992,
0.00019222522678319365,
0.00016820420569274575,
0.00016944645904004574,
0.00003309634848847054
] |
{
"id": 2,
"code_window": [
" <LabelRadio label=\"Other\" value=\"other\" />\n",
" <LabelRadio label=\"Disabled\" value=\"disabled\" disabled />\n",
" </RadioGroup>\n",
" </div>\n",
" );\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" </FormControl>\n"
],
"file_path": "docs/site/src/demos/selection-controls/RadioButtonsGroup.js",
"type": "replace",
"edit_start_line_idx": 44
} | DialogContent
=============
Props
-----
| Name | Type | Default | Description |
|:-----|:-----|:--------|:------------|
| children | node | | The content of the component. |
| className | string | | The CSS class name of the root element. |
Other properties (not documented) are applied to the root element.
| docs/api/Dialog/DialogContent.md | 0 | https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846 | [
0.00016525630780961365,
0.00016451551346108317,
0.00016377470456063747,
0.00016451551346108317,
7.408016244880855e-7
] |
{
"id": 2,
"code_window": [
" <LabelRadio label=\"Other\" value=\"other\" />\n",
" <LabelRadio label=\"Disabled\" value=\"disabled\" disabled />\n",
" </RadioGroup>\n",
" </div>\n",
" );\n",
" }\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" </FormControl>\n"
],
"file_path": "docs/site/src/demos/selection-controls/RadioButtonsGroup.js",
"type": "replace",
"edit_start_line_idx": 44
} | {
"name": "eslint-plugin-material-ui",
"version": "1.0.0",
"private": "true",
"description": "Custom eslint rules for Material-UI",
"repository": "https://github.com/callemall/material-ui/packages/eslint-plugin-material-ui",
"main": "lib/index.js",
"scripts": {
"test": "../../node_modules/mocha/bin/_mocha -- tests/lib/**/*.js",
"lint": "../../node_modules/eslint/bin/eslint.js --rulesdir ../.. --ext .js lib tests && echo \"eslint: no lint errors\""
},
"engines": {
"node": ">=0.10.0"
},
"license": "MIT"
}
| packages/eslint-plugin-material-ui/package.json | 0 | https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846 | [
0.0001727964699966833,
0.00017257433501072228,
0.00017235218547284603,
0.00017257433501072228,
2.2214226191863418e-7
] |
{
"id": 3,
"code_window": [
"\n",
"export FormGroup from './FormGroup';\n",
"export FormLabel from './FormLabel';\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"export FormControl from './FormControl';"
],
"file_path": "src/Form/index.js",
"type": "add",
"edit_start_line_idx": 4
} | // @flow weak
import React, { Component, PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import { LabelRadio, RadioGroup } from 'material-ui/Radio';
import { FormLabel } from 'material-ui/Form';
const styleSheet = createStyleSheet('RadioButtonsGroup', () => ({
group: {
margin: '8px 0',
},
}));
export default class RadioButtonsGroup extends Component {
static contextTypes = {
styleManager: PropTypes.object.isRequired,
};
state = {
selectedValue: undefined,
};
handleChange = (event, value) => {
this.setState({ selectedValue: value });
};
render() {
const classes = this.context.styleManager.render(styleSheet);
return (
<div>
<FormLabel required>Gender</FormLabel>
<RadioGroup
aria-label="Gender"
name="gender"
className={classes.group}
selectedValue={this.state.selectedValue}
onChange={this.handleChange}
>
<LabelRadio label="Male" value="male" />
<LabelRadio label="Female" value="female" />
<LabelRadio label="Other" value="other" />
<LabelRadio label="Disabled" value="disabled" disabled />
</RadioGroup>
</div>
);
}
}
| docs/site/src/demos/selection-controls/RadioButtonsGroup.js | 1 | https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846 | [
0.9842349886894226,
0.1971728354692459,
0.0001686117466306314,
0.00038996097282506526,
0.3935311734676361
] |
{
"id": 3,
"code_window": [
"\n",
"export FormGroup from './FormGroup';\n",
"export FormLabel from './FormLabel';\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"export FormControl from './FormControl';"
],
"file_path": "src/Form/index.js",
"type": "add",
"edit_start_line_idx": 4
} | // @flow weak
import React, { PropTypes } from 'react';
import { createStyleSheet } from 'jss-theme-reactor';
import classNames from 'classnames';
export const styleSheet = createStyleSheet('CardContent', () => ({
cardContent: {
padding: 16,
'&:last-child': {
paddingBottom: 24,
},
},
}));
export default function CardContent(props, context) {
const {
className: classNameProp,
...other
} = props;
const classes = context.styleManager.render(styleSheet);
const className = classNames(classes.cardContent, classNameProp);
return (
<div className={className} {...other} />
);
}
CardContent.propTypes = {
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
};
CardContent.contextTypes = {
styleManager: PropTypes.object.isRequired,
};
| src/Card/CardContent.js | 0 | https://github.com/mui/material-ui/commit/2d6ca998076cf8300683165867c615c34cb76846 | [
0.00017197248234879225,
0.00017103349091485143,
0.00016866899386513978,
0.0001717462728265673,
0.0000013687529190065106
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.