hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
listlengths 5
5
|
---|---|---|---|---|---|
{
"id": 7,
"code_window": [
"import {SpyLocation} from '@angular/common/testing';\n",
"import {Location} from '@angular/common';\n",
"import {Router, RouterOutletMap} from '../src/router';\n",
"import {RouterUrlSerializer, DefaultRouterUrlSerializer} from '../src/router_url_serializer';\n",
"import {Component, ComponentResolver} from '@angular/core';\n",
"\n",
"@Component({selector: 'fake-app-root-comp', template: `<span></span>`})\n",
"class FakeAppRootCmp {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {RouteSegment} from '../src/segments';\n"
],
"file_path": "modules/@angular/router/testing/router_testing_providers.ts",
"type": "add",
"edit_start_line_idx": 3
} | {
"angularCompilerOptions": {
"skipTemplateCodegen": true
},
"compilerOptions": {
"baseUrl": ".",
"declaration": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "es2015",
"moduleResolution": "node",
"outDir": "../../../dist/packages-dist/platform-browser-dynamic/esm",
"paths": {
"@angular/common": ["../../../dist/packages-dist/common/"],
"@angular/compiler": ["../../../dist/packages-dist/compiler/"],
"@angular/compiler/testing": ["../../../dist/packages-dist/compiler/testing"],
"@angular/core": ["../../../dist/packages-dist/core/"],
"@angular/platform-browser": ["../../../dist/packages-dist/platform-browser"],
"@angular/platform-browser/testing": ["../../../dist/packages-dist/platform-browser/testing"]
},
"rootDir": ".",
"sourceMap": true,
"inlineSources": true,
"target": "es2015"
},
"files": [
"index.ts",
"testing.ts",
"../typings/hammerjs/hammerjs.d.ts",
"../typings/jasmine/jasmine.d.ts",
"../../../node_modules/zone.js/dist/zone.js.d.ts"
]
}
| modules/@angular/platform-browser-dynamic/tsconfig-es2015.json | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.0001711724908091128,
0.00016967624833341688,
0.00016797819989733398,
0.0001697771658655256,
0.0000013436349490802968
]
|
{
"id": 7,
"code_window": [
"import {SpyLocation} from '@angular/common/testing';\n",
"import {Location} from '@angular/common';\n",
"import {Router, RouterOutletMap} from '../src/router';\n",
"import {RouterUrlSerializer, DefaultRouterUrlSerializer} from '../src/router_url_serializer';\n",
"import {Component, ComponentResolver} from '@angular/core';\n",
"\n",
"@Component({selector: 'fake-app-root-comp', template: `<span></span>`})\n",
"class FakeAppRootCmp {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {RouteSegment} from '../src/segments';\n"
],
"file_path": "modules/@angular/router/testing/router_testing_providers.ts",
"type": "add",
"edit_start_line_idx": 3
} | library angular2.transform.common.code.parameter_code;
import 'package:analyzer/analyzer.dart';
import 'package:analyzer/src/generated/ast.dart';
import 'package:angular2/src/transform/common/logging.dart';
import 'package:angular2/src/transform/common/model/parameter_model.pb.dart';
import 'constify.dart';
/// Visitor responsible for parsing [FormalParameter]s into
/// [ParameterModel]s.
class ParameterVisitor extends SimpleAstVisitor<ParameterModel> {
/// Maps field names to their declared types. See `_populateFieldMap`
final Map<String, TypeName> _fieldNameToType = {};
final Set<AstNode> _seen = new Set();
void _populateFieldMap(AstNode node) {
ClassDeclaration clazz =
node.getAncestor((node) => node is ClassDeclaration);
if (_seen.contains(clazz)) return;
_seen.add(clazz);
clazz.members
.where((member) => member is FieldDeclaration)
.forEach((FieldDeclaration field) {
var type = field.fields.type;
if (type != null) {
field.fields.variables.forEach((VariableDeclaration decl) {
var key = '${decl.name}';
if (_fieldNameToType.containsKey(key)) {
// Need to clear our `seen` list as the type for a var name has
// changed and could be incorrect.
_seen.clear();
}
_fieldNameToType[key] = type;
});
}
});
}
ParameterModel _visitNormalFormalParameter(
NodeList<Annotation> metadata, TypeName type, SimpleIdentifier name) {
var model = new ParameterModel();
if (name != null && name.name != null && name.name.isNotEmpty) {
model.paramName = '$name';
}
if (type != null) {
var sTypeName = '${type.name}';
if (sTypeName.isNotEmpty) {
model.typeName = sTypeName;
}
if (type.typeArguments != null) {
model.typeArgs = '${type.typeArguments}';
}
}
if (metadata != null) {
model.metadata.addAll(metadata.map(constify));
}
return model;
}
@override
ParameterModel visitSimpleFormalParameter(SimpleFormalParameter node) {
return _visitNormalFormalParameter(
node.metadata, node.type, node.identifier);
}
@override
ParameterModel visitFieldFormalParameter(FieldFormalParameter node) {
if (node.parameters != null) {
log.error('Parameters in ctor not supported '
'(${node.toSource()})');
}
var type = node.type;
if (type == null) {
_populateFieldMap(node);
type = _fieldNameToType[node.identifier.toString()];
}
return _visitNormalFormalParameter(node.metadata, type, node.identifier);
}
@override
ParameterModel visitFunctionTypedFormalParameter(
FunctionTypedFormalParameter node) {
log.error('Function typed formal parameters not supported '
'(${node.toSource()})');
return _visitNormalFormalParameter(node.metadata, null, node.identifier);
}
@override
ParameterModel visitDefaultFormalParameter(DefaultFormalParameter node) {
// Ignore the declared default value.
return node.parameter != null ? node.parameter.accept(this) : null;
}
}
/// Defines the format in which a [ParameterModel] is expressed as Dart code
/// when registered with the reflector.
abstract class ParameterWriterMixin {
StringBuffer get buffer;
void writeParameterModelForList(ParameterModel model) {
buffer.write('const [');
var first = true;
if (model.typeName != null && model.typeName.isNotEmpty) {
if (!first) {
buffer.write(', ');
}
first = false;
buffer.write('${model.typeName}');
}
for (var meta in model.metadata) {
if (!first) {
buffer.write(', ');
}
first = false;
buffer.write('$meta');
}
buffer.write(']');
}
void writeParameterModelForDeclaration(ParameterModel model) {
if (model.typeName != null && model.typeName.isNotEmpty) {
buffer.write(model.typeName);
if (model.typeArgs != null && model.typeArgs.isNotEmpty) {
buffer.write(model.typeArgs);
}
buffer.write(' ');
}
if (model.paramName != null && model.paramName.isNotEmpty) {
buffer.write(model.paramName);
}
}
void writeParameterModelForImpl(ParameterModel model) {
buffer.write(model.paramName);
}
}
| modules_dart/transform/lib/src/transform/common/code/parameter_code.dart | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00017683548503555357,
0.00017303483036812395,
0.00016618687368463725,
0.00017367771943099797,
0.000002395220690232236
]
|
{
"id": 8,
"code_window": [
" useFactory: routerFactory,\n",
" deps: /*@ts2dart_const*/\n",
" [ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]\n",
" },\n",
"];"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" /*@ts2dart_Provider*/ {provide: RouteSegment, useFactory: (r) => r.routeTree.root, deps: [Router]}\n"
],
"file_path": "modules/@angular/router/testing/router_testing_providers.ts",
"type": "add",
"edit_start_line_idx": 26
} | import {
AsyncTestCompleter,
beforeEach,
ddescribe,
xdescribe,
describe,
expect,
iit,
inject,
beforeEachProviders,
it,
xit
} from '@angular/core/testing/testing_internal';
import {fakeAsync, tick} from '@angular/core/testing';
import {ComponentFixture, TestComponentBuilder} from '@angular/compiler/testing';
import {provide, Component, ComponentResolver} from '@angular/core';
import {PromiseWrapper} from '../src/facade/async';
import {
Router,
RouterOutletMap,
RouteSegment,
Route,
ROUTER_DIRECTIVES,
Routes,
RouterUrlSerializer,
DefaultRouterUrlSerializer,
OnActivate,
CanDeactivate
} from '@angular/router';
import {SpyLocation} from '@angular/common/testing';
import {Location} from '@angular/common';
import {getDOM} from '../platform_browser_private';
export function main() {
describe('navigation', () => {
beforeEachProviders(() => [
provide(RouterUrlSerializer, {useClass: DefaultRouterUrlSerializer}),
RouterOutletMap,
provide(Location, {useClass: SpyLocation}),
provide(Router,
{
useFactory: (resolver, urlParser, outletMap, location) => new Router(
"RootComponent", RootCmp, resolver, urlParser, outletMap, location),
deps: [ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]
})
]);
it('should update location when navigating',
fakeAsync(inject([Router, TestComponentBuilder, Location], (router, tcb, location) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
expect(location.path()).toEqual('/team/22/user/victor');
router.navigateByUrl('/team/33/simple');
advance(fixture);
expect(location.path()).toEqual('/team/33/simple');
})));
it('should navigate when locations changes',
fakeAsync(inject([Router, TestComponentBuilder, Location], (router, tcb, location) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
location.simulateHashChange("/team/22/user/fedor");
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello fedor, aux: }');
})));
it('should support nested routes',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello victor, aux: }');
})));
it('should support aux routes',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor(/simple)');
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { hello victor, aux: simple }');
})));
it('should deactivate outlets', fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor(/simple)');
advance(fixture);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello victor, aux: }');
})));
it('should deactivate nested outlets',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor(/simple)');
advance(fixture);
router.navigateByUrl('/');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('');
})));
it('should update nested routes when url changes',
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
let team1 = fixture.debugElement.children[1].componentInstance;
router.navigateByUrl('/team/22/user/fedor');
advance(fixture);
let team2 = fixture.debugElement.children[1].componentInstance;
expect(team1).toBe(team2);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello fedor, aux: }');
})));
it('should not deactivate the route if can deactivate returns false',
fakeAsync(inject([Router, TestComponentBuilder, Location], (router, tcb, location) => {
let fixture = tcb.createFakeAsync(RootCmp);
router.navigateByUrl('/team/22/cannotDeactivate');
advance(fixture);
router.navigateByUrl('/team/22/user/fedor');
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { cannotDeactivate, aux: }');
expect(location.path()).toEqual('/team/22/cannotDeactivate');
})));
if (getDOM().supportsDOMEvents()) {
it("should support absolute router links",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22/link');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { link, aux: }');
let native = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
expect(getDOM().getAttribute(native, "href")).toEqual("/team/33/simple");
getDOM().dispatchEvent(native, getDOM().createMouseEvent('click'));
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 33 { simple, aux: }');
})));
it("should support relative router links",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22/relativelink');
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { relativelink { }, aux: }');
let native = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
expect(getDOM().getAttribute(native, "href")).toEqual("/team/22/relativelink/simple");
getDOM().dispatchEvent(native, getDOM().createMouseEvent('click'));
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { relativelink { simple }, aux: }');
})));
it("should set the router-link-active class",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22/relativelink');
advance(fixture);
expect(fixture.debugElement.nativeElement)
.toHaveText('team 22 { relativelink { }, aux: }');
let link = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
expect(getDOM().hasClass(link, "router-link-active")).toEqual(false);
getDOM().dispatchEvent(link, getDOM().createMouseEvent('click'));
advance(fixture);
expect(getDOM().hasClass(link, "router-link-active")).toEqual(true);
})));
it("should update router links when router changes",
fakeAsync(inject([Router, TestComponentBuilder], (router, tcb) => {
let fixture = tcb.createFakeAsync(RootCmp);
advance(fixture);
router.navigateByUrl('/team/22/link(simple)');
advance(fixture);
expect(fixture.debugElement.nativeElement).toHaveText('team 22 { link, aux: simple }');
let native = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
expect(getDOM().getAttribute(native, "href")).toEqual("/team/33/simple(aux:simple)");
router.navigateByUrl('/team/22/link(simple2)');
advance(fixture);
expect(getDOM().getAttribute(native, "href")).toEqual("/team/33/simple(aux:simple2)");
})));
}
});
}
function advance(fixture: ComponentFixture<any>): void {
tick();
fixture.detectChanges();
}
function compileRoot(tcb: TestComponentBuilder): Promise<ComponentFixture<any>> {
return tcb.createAsync(RootCmp);
}
@Component({selector: 'user-cmp', template: `hello {{user}}`})
class UserCmp implements OnActivate {
user: string;
routerOnActivate(s: RouteSegment, a?, b?, c?) { this.user = s.getParam('name'); }
}
@Component({selector: 'cannot-deactivate', template: `cannotDeactivate`})
class CanDeactivateCmp implements CanDeactivate {
routerCanDeactivate(a?, b?): Promise<boolean> { return PromiseWrapper.resolve(false); }
}
@Component({selector: 'simple-cmp', template: `simple`})
class SimpleCmp {
}
@Component({selector: 'simple2-cmp', template: `simple2`})
class Simple2Cmp {
}
@Component({
selector: 'link-cmp',
template: `<a [routerLink]="['/team', '33', 'simple']">link</a>`,
directives: ROUTER_DIRECTIVES
})
class LinkCmp {
}
@Component({
selector: 'link-cmp',
template: `<a [routerLink]="['./simple']">relativelink</a> { <router-outlet></router-outlet> }`,
directives: ROUTER_DIRECTIVES
})
@Routes([new Route({path: 'simple', component: SimpleCmp})])
class RelativeLinkCmp {
}
@Component({
selector: 'team-cmp',
template: `team {{id}} { <router-outlet></router-outlet>, aux: <router-outlet name="aux"></router-outlet> }`,
directives: [ROUTER_DIRECTIVES]
})
@Routes([
new Route({path: 'user/:name', component: UserCmp}),
new Route({path: 'simple', component: SimpleCmp}),
new Route({path: 'simple2', component: Simple2Cmp}),
new Route({path: 'link', component: LinkCmp}),
new Route({path: 'relativelink', component: RelativeLinkCmp}),
new Route({path: 'cannotDeactivate', component: CanDeactivateCmp})
])
class TeamCmp implements OnActivate {
id: string;
routerOnActivate(s: RouteSegment, a?, b?, c?) { this.id = s.getParam('id'); }
}
@Component({
selector: 'root-cmp',
template: `<router-outlet></router-outlet>`,
directives: [ROUTER_DIRECTIVES]
})
@Routes([new Route({path: 'team/:id', component: TeamCmp})])
class RootCmp {
}
| modules/@angular/router/test/integration_spec.ts | 1 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.009506061673164368,
0.0005791910225525498,
0.00016518746269866824,
0.00020104421128053218,
0.0016429192619398236
]
|
{
"id": 8,
"code_window": [
" useFactory: routerFactory,\n",
" deps: /*@ts2dart_const*/\n",
" [ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]\n",
" },\n",
"];"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" /*@ts2dart_Provider*/ {provide: RouteSegment, useFactory: (r) => r.routeTree.root, deps: [Router]}\n"
],
"file_path": "modules/@angular/router/testing/router_testing_providers.ts",
"type": "add",
"edit_start_line_idx": 26
} | library web_foo;
import 'package:angular2/platform/browser.dart';
import 'package:angular2/src/core/reflection/reflection.dart';
import 'package:angular2/src/core/reflection/reflection_capabilities.dart';
void main() {
reflector.reflectionCapabilities = new ReflectionCapabilities();
bootstrap(MyComponent);
}
| modules_dart/transform/test/transform/reflection_remover/index.dart | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00017360188940074295,
0.00017319992184638977,
0.0001727979542920366,
0.00017319992184638977,
4.0196755435317755e-7
]
|
{
"id": 8,
"code_window": [
" useFactory: routerFactory,\n",
" deps: /*@ts2dart_const*/\n",
" [ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]\n",
" },\n",
"];"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" /*@ts2dart_Provider*/ {provide: RouteSegment, useFactory: (r) => r.routeTree.root, deps: [Router]}\n"
],
"file_path": "modules/@angular/router/testing/router_testing_providers.ts",
"type": "add",
"edit_start_line_idx": 26
} | library playground.hello_world.index_common_dart.ng_deps.dart;
import 'hello.ngfactory.dart' as _templates;
import 'hello.dart';
import 'package:angular2/angular2.dart'
show Component, Directive, View, NgElement;
var _visited = false;
void initReflector(reflector) {
if (_visited) return;
_visited = true;
reflector
..registerType(
HelloCmp,
new ReflectionInfo(const [
const Component(selector: 'hello-app', outputs: const ['eventName']),
const View(template: '<button>go</button>'),
_templates.HostHelloCmpTemplate
], const [
const []
], () => new HelloCmp()));
}
| modules_dart/transform/test/transform/template_compiler/event_files/expected/hello.ng_deps.dart | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.0006462279125116765,
0.000328099267790094,
0.00016896406305022538,
0.0001691058714641258,
0.00022495091252494603
]
|
{
"id": 8,
"code_window": [
" useFactory: routerFactory,\n",
" deps: /*@ts2dart_const*/\n",
" [ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]\n",
" },\n",
"];"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
" /*@ts2dart_Provider*/ {provide: RouteSegment, useFactory: (r) => r.routeTree.root, deps: [Router]}\n"
],
"file_path": "modules/@angular/router/testing/router_testing_providers.ts",
"type": "add",
"edit_start_line_idx": 26
} | #!/bin/bash
set -e
MODE=$1
echo =============================================================================
# go to project dir
SCRIPT_DIR=$(dirname $0)
cd $SCRIPT_DIR/../..
./scripts/browserstack/start_tunnel.sh
./scripts/browserstack/waitfor_tunnel.sh
./node_modules/.bin/gulp build.js.dev
./node_modules/.bin/gulp test.unit.js.browserstack/ci --mode=$MODE
| scripts/ci/test_browserstack.sh | 0 | https://github.com/angular/angular/commit/b8136cc26e006c087ef59aa7ae41eb57b2310a7a | [
0.00017063946870621294,
0.0001700247812550515,
0.00016941009380389005,
0.0001700247812550515,
6.146874511614442e-7
]
|
{
"id": 0,
"code_window": [
"\n",
"\tregisterView(contextProvider: IExplorerView): void {\n",
"\t\tthis.view = contextProvider;\n",
"\t}\n",
"\n",
"\tgetContext(respectMultiSelection: boolean): ExplorerItem[] {\n",
"\t\tif (!this.view) {\n",
"\t\t\treturn [];\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tgetContext(respectMultiSelection: boolean, ignoreNestedChildren: boolean = false): ExplorerItem[] {\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/explorerService.ts",
"type": "replace",
"edit_start_line_idx": 149
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import { IListService } from 'vs/platform/list/browser/listService';
import { OpenEditor, ISortOrderConfiguration } from 'vs/workbench/contrib/files/common/files';
import { EditorResourceAccessor, SideBySideEditor, IEditorIdentifier } from 'vs/workbench/common/editor';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ExplorerItem } from 'vs/workbench/contrib/files/common/explorerModel';
import { coalesce } from 'vs/base/common/arrays';
import { AsyncDataTree } from 'vs/base/browser/ui/tree/asyncDataTree';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IEditableData } from 'vs/workbench/common/views';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ResourceFileEdit } from 'vs/editor/browser/services/bulkEditService';
import { ProgressLocation } from 'vs/platform/progress/common/progress';
export interface IExplorerService {
readonly _serviceBrand: undefined;
readonly roots: ExplorerItem[];
readonly sortOrderConfiguration: ISortOrderConfiguration;
getContext(respectMultiSelection: boolean): ExplorerItem[];
hasViewFocus(): boolean;
setEditable(stat: ExplorerItem, data: IEditableData | null): Promise<void>;
getEditable(): { stat: ExplorerItem; data: IEditableData } | undefined;
getEditableData(stat: ExplorerItem): IEditableData | undefined;
// If undefined is passed checks if any element is currently being edited.
isEditable(stat: ExplorerItem | undefined): boolean;
findClosest(resource: URI): ExplorerItem | null;
findClosestRoot(resource: URI): ExplorerItem | null;
refresh(): Promise<void>;
setToCopy(stats: ExplorerItem[], cut: boolean): Promise<void>;
isCut(stat: ExplorerItem): boolean;
applyBulkEdit(edit: ResourceFileEdit[], options: { undoLabel: string; progressLabel: string; confirmBeforeUndo?: boolean; progressLocation?: ProgressLocation.Explorer | ProgressLocation.Window }): Promise<void>;
/**
* Selects and reveal the file element provided by the given resource if its found in the explorer.
* Will try to resolve the path in case the explorer is not yet expanded to the file yet.
*/
select(resource: URI, reveal?: boolean | string): Promise<void>;
registerView(contextAndRefreshProvider: IExplorerView): void;
}
export const IExplorerService = createDecorator<IExplorerService>('explorerService');
export interface IExplorerView {
getContext(respectMultiSelection: boolean): ExplorerItem[];
refresh(recursive: boolean, item?: ExplorerItem): Promise<void>;
selectResource(resource: URI | undefined, reveal?: boolean | string): Promise<void>;
setTreeInput(): Promise<void>;
itemsCopied(tats: ExplorerItem[], cut: boolean, previousCut: ExplorerItem[] | undefined): void;
setEditable(stat: ExplorerItem, isEditing: boolean): Promise<void>;
isItemVisible(item: ExplorerItem): boolean;
isItemCollapsed(item: ExplorerItem): boolean;
hasFocus(): boolean;
}
function getFocus(listService: IListService): unknown | undefined {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
let focus: unknown;
if (list instanceof List) {
const focused = list.getFocusedElements();
if (focused.length) {
focus = focused[0];
}
} else if (list instanceof AsyncDataTree) {
const focused = list.getFocus();
if (focused.length) {
focus = focused[0];
}
}
return focus;
}
return undefined;
}
// Commands can get executed from a command palette, from a context menu or from some list using a keybinding
// To cover all these cases we need to properly compute the resource on which the command is being executed
export function getResourceForCommand(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): URI | undefined {
if (URI.isUri(resource)) {
return resource;
}
const focus = getFocus(listService);
if (focus instanceof ExplorerItem) {
return focus.resource;
} else if (focus instanceof OpenEditor) {
return focus.getResource();
}
return EditorResourceAccessor.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
}
export function getMultiSelectedResources(resource: URI | object | undefined, listService: IListService, editorService: IEditorService, explorerService: IExplorerService): Array<URI> {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
// Explorer
if (list instanceof AsyncDataTree && list.getFocus().every(item => item instanceof ExplorerItem)) {
// Explorer
const context = explorerService.getContext(true);
if (context.length) {
return context.map(c => c.resource);
}
}
// Open editors view
if (list instanceof List) {
const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor).map((oe: OpenEditor) => oe.getResource()));
const focusedElements = list.getFocusedElements();
const focus = focusedElements.length ? focusedElements[0] : undefined;
let mainUriStr: string | undefined = undefined;
if (URI.isUri(resource)) {
mainUriStr = resource.toString();
} else if (focus instanceof OpenEditor) {
const focusedResource = focus.getResource();
mainUriStr = focusedResource ? focusedResource.toString() : undefined;
}
// We only respect the selection if it contains the main element.
if (selection.some(s => s.toString() === mainUriStr)) {
return selection;
}
}
}
const result = getResourceForCommand(resource, listService, editorService);
return !!result ? [result] : [];
}
export function getOpenEditorsViewMultiSelection(listService: IListService, editorGroupService: IEditorGroupsService): Array<IEditorIdentifier> | undefined {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
// Open editors view
if (list instanceof List) {
const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor));
const focusedElements = list.getFocusedElements();
const focus = focusedElements.length ? focusedElements[0] : undefined;
let mainEditor: IEditorIdentifier | undefined = undefined;
if (focus instanceof OpenEditor) {
mainEditor = focus;
}
// We only respect the selection if it contains the main element.
if (selection.some(s => s === mainEditor)) {
return selection;
}
}
}
return undefined;
}
| src/vs/workbench/contrib/files/browser/files.ts | 1 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.010313205420970917,
0.0015542120672762394,
0.00016602389223407954,
0.00017369611305184662,
0.00305801909416914
]
|
{
"id": 0,
"code_window": [
"\n",
"\tregisterView(contextProvider: IExplorerView): void {\n",
"\t\tthis.view = contextProvider;\n",
"\t}\n",
"\n",
"\tgetContext(respectMultiSelection: boolean): ExplorerItem[] {\n",
"\t\tif (!this.view) {\n",
"\t\t\treturn [];\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tgetContext(respectMultiSelection: boolean, ignoreNestedChildren: boolean = false): ExplorerItem[] {\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/explorerService.ts",
"type": "replace",
"edit_start_line_idx": 149
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* Part Element */
.monaco-workbench .part.titlebar {
display: flex;
flex-direction: row;
}
.monaco-workbench.mac .part.titlebar {
flex-direction: row-reverse;
}
/* Root Container */
.monaco-workbench .part.titlebar>.titlebar-container {
box-sizing: border-box;
overflow: hidden;
flex-shrink: 1;
flex-grow: 1;
align-items: center;
justify-content: center;
user-select: none;
-webkit-user-select: none;
display: flex;
height: 100%;
width: 100%;
}
/* Account for zooming */
.monaco-workbench .part.titlebar>.titlebar-container.counter-zoom {
zoom: calc(1.0 / var(--zoom-factor));
}
/* Platform specific root element */
.monaco-workbench.mac .part.titlebar>.titlebar-container {
line-height: 22px;
}
.monaco-workbench.web .part.titlebar>.titlebar-container,
.monaco-workbench.windows .part.titlebar>.titlebar-container,
.monaco-workbench.linux .part.titlebar>.titlebar-container {
line-height: 22px;
justify-content: left;
}
.monaco-workbench.web.safari .part.titlebar,
.monaco-workbench.web.safari .part.titlebar>.titlebar-container {
/* Must be scoped to safari due to #148851 */
/* Is required in safari due to #149476 */
overflow: visible;
}
/* Draggable region */
.monaco-workbench .part.titlebar>.titlebar-container>.titlebar-drag-region {
top: 0;
left: 0;
display: block;
position: absolute;
width: 100%;
height: 100%;
-webkit-app-region: drag;
}
/* Window title text */
.monaco-workbench .part.titlebar>.titlebar-container>.window-title {
flex: 0 1 auto;
font-size: 12px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
margin-left: auto;
margin-right: auto;
}
.monaco-workbench.web .part.titlebar>.titlebar-container>.window-title,
.monaco-workbench.windows .part.titlebar>.titlebar-container>.window-title,
.monaco-workbench.linux .part.titlebar>.titlebar-container>.window-title {
cursor: default;
}
.monaco-workbench.linux .part.titlebar>.titlebar-container>.window-title {
font-size: inherit;
/* see #55435 */
}
/* Window Title Menu */
.monaco-workbench .part.titlebar>.titlebar-container>.window-title>.command-center {
z-index: 2500;
-webkit-app-region: no-drag;
padding: 0 8px;
}
.monaco-workbench .part.titlebar>.titlebar-container>.window-title>.command-center.hide {
display: none;
}
.monaco-workbench .part.titlebar>.titlebar-container>.window-title>.command-center .action-item.quickopen {
display: flex;
color: var(--vscode-commandCenter-foreground);
background-color: var(--vscode-commandCenter-background);
border: 1px solid var(--vscode-commandCenter-border);
flex-direction: row;
justify-content: center;
overflow: hidden;
}
.monaco-workbench .part.titlebar>.titlebar-container>.window-title>.command-center .action-item.quickopen:HOVER {
color: var(--vscode-commandCenter-activeForeground);
background-color: var(--vscode-commandCenter-activeBackground);
}
.monaco-workbench .part.titlebar>.titlebar-container>.window-title>.command-center .action-item.quickopen.left {
/* border,margin tricks */
margin-left: 6px;
border-top-left-radius: 6px;
border-bottom-left-radius: 6px;
border-right: none;
/* width */
width: 38vw;
max-width: 600px;
min-width: 32px;
}
.monaco-workbench .part.titlebar>.titlebar-container>.window-title>.command-center .action-item.quickopen.right {
/* border,margin tricks */
margin-right: 6px;
border-top-right-radius: 6px;
border-bottom-right-radius: 6px;
border-left: none;
/* width */
width: 16px;
flex-shrink: 0;
}
.monaco-workbench .part.titlebar>.titlebar-container>.window-title>.command-center .action-item.quickopen>.action-label {
height: 22px;
line-height: 22px;
padding: 0;
background-color: transparent;
display: inline-flex;
text-align: center;
font-size: 12px;
justify-content: center;
width: 100%;
}
.monaco-workbench .part.titlebar>.titlebar-container>.window-title>.command-center .action-item.quickopen.left>.action-label.search>.search-icon {
font-size: 14px;
opacity: .8;
margin: auto 3px;
}
.monaco-workbench .part.titlebar>.titlebar-container>.window-title>.command-center .action-item.quickopen.left>.action-label.search>.search-label {
overflow: hidden;
text-overflow: ellipsis;
}
/* Menubar */
.monaco-workbench .part.titlebar>.titlebar-container>.menubar {
/* move menubar above drag region as negative z-index on drag region cause greyscale AA */
z-index: 2500;
min-width: 36px;
flex-wrap: nowrap;
}
.monaco-workbench .part.titlebar>.titlebar-container.counter-zoom > .menubar .menubar-menu-button > .menubar-menu-items-holder.monaco-menu-container {
zoom: var(--zoom-factor);
}
/* Resizer */
.monaco-workbench.windows .part.titlebar>.titlebar-container>.resizer,
.monaco-workbench.linux .part.titlebar>.titlebar-container>.resizer {
-webkit-app-region: no-drag;
position: absolute;
top: 0;
width: 100%;
height: 4px;
}
.monaco-workbench.windows.fullscreen .part.titlebar>.titlebar-container>.resizer,
.monaco-workbench.linux.fullscreen .part.titlebar>.titlebar-container>.resizer {
display: none;
}
/* App Icon */
.monaco-workbench .part.titlebar>.titlebar-container>.window-appicon {
width: 35px;
height: 100%;
position: relative;
z-index: 2500;
flex-shrink: 0;
}
.monaco-workbench .part.titlebar>.titlebar-container>.window-appicon:not(.codicon) {
background-image: url('../../../media/code-icon.svg');
background-repeat: no-repeat;
background-position: center center;
background-size: 16px;
}
.monaco-workbench .part.titlebar>.titlebar-container>.window-appicon.codicon {
line-height: 30px;
}
.monaco-workbench.fullscreen .part.titlebar>.titlebar-container>.window-appicon {
display: none;
}
.monaco-workbench .part.titlebar>.titlebar-container .window-appicon>.home-bar-icon-badge {
position: absolute;
right: 9px;
bottom: 6px;
width: 8px;
height: 8px;
z-index: 1;
/* on top of home indicator */
background-image: url('../../../media/code-icon.svg');
background-repeat: no-repeat;
background-position: center center;
background-size: 8px;
pointer-events: none;
border-top: 1px solid transparent;
border-left: 1px solid transparent;
}
/* Window Controls (Minimize, Max/Restore, Close) */
.monaco-workbench .part.titlebar>.window-controls-container {
display: flex;
flex-grow: 0;
flex-shrink: 0;
text-align: center;
z-index: 3000;
-webkit-app-region: no-drag;
height: 100%;
width: 138px;
zoom: calc(1 / var(--zoom-factor));
}
.monaco-workbench.mac .part.titlebar>.window-controls-container {
width: 70px;
height: env(titlebar-area-width, 28px);
}
.monaco-workbench.web .part.titlebar>.window-controls-container,
.monaco-workbench.fullscreen .part.titlebar>.window-controls-container {
display: none;
background-color: transparent;
}
/* Window Control Icons */
.monaco-workbench .part.titlebar>.window-controls-container>.window-icon {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
width: 46px;
font-size: 16px;
}
.monaco-workbench .part.titlebar>.window-controls-container>.window-icon::before {
height: 16px;
line-height: 16px;
}
.monaco-workbench .part.titlebar>.window-controls-container>.window-icon:hover {
background-color: rgba(255, 255, 255, 0.1);
}
.monaco-workbench .part.titlebar.light>.window-controls-container>.window-icon:hover {
background-color: rgba(0, 0, 0, 0.1);
}
.monaco-workbench .part.titlebar>.window-controls-container>.window-icon.window-close:hover {
background-color: rgba(232, 17, 35, 0.9);
}
.monaco-workbench .part.titlebar>.window-controls-container .window-icon.window-close:hover {
color: white;
}
/* Layout Controls */
.monaco-workbench .part.titlebar>.titlebar-container>.layout-controls-container {
display: none;
padding-right: 2px;
flex-grow: 0;
flex-shrink: 0;
text-align: center;
position: relative;
z-index: 2500;
-webkit-app-region: no-drag;
height: 100%;
margin-left: auto;
min-width: 28px;
}
.monaco-workbench.mac:not(.web) .part.titlebar>.titlebar-container>.layout-controls-container {
right: 8px;
}
.monaco-workbench .part.titlebar>.titlebar-container>.layout-controls-container.show-layout-control {
display: flex;
justify-content: center;
}
.monaco-workbench .part.titlebar>.titlebar-container>.layout-controls-container .codicon {
color: inherit;
}
| src/vs/workbench/browser/parts/titlebar/media/titlebarpart.css | 0 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.00017947045853361487,
0.00017230448429472744,
0.0001655534579185769,
0.00017256641876883805,
0.0000030389835501409834
]
|
{
"id": 0,
"code_window": [
"\n",
"\tregisterView(contextProvider: IExplorerView): void {\n",
"\t\tthis.view = contextProvider;\n",
"\t}\n",
"\n",
"\tgetContext(respectMultiSelection: boolean): ExplorerItem[] {\n",
"\t\tif (!this.view) {\n",
"\t\t\treturn [];\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tgetContext(respectMultiSelection: boolean, ignoreNestedChildren: boolean = false): ExplorerItem[] {\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/explorerService.ts",
"type": "replace",
"edit_start_line_idx": 149
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
var updateGrammar = require('vscode-grammar-updater');
updateGrammar.update('textmate/git.tmbundle', 'Syntaxes/Git%20Commit%20Message.tmLanguage', './syntaxes/git-commit.tmLanguage.json');
updateGrammar.update('textmate/git.tmbundle', 'Syntaxes/Git%20Rebase%20Message.tmLanguage', './syntaxes/git-rebase.tmLanguage.json');
| extensions/git-base/build/update-grammars.js | 0 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.00017933000344783068,
0.00017701691831462085,
0.00017470383318141103,
0.00017701691831462085,
0.0000023130851332098246
]
|
{
"id": 0,
"code_window": [
"\n",
"\tregisterView(contextProvider: IExplorerView): void {\n",
"\t\tthis.view = contextProvider;\n",
"\t}\n",
"\n",
"\tgetContext(respectMultiSelection: boolean): ExplorerItem[] {\n",
"\t\tif (!this.view) {\n",
"\t\t\treturn [];\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tgetContext(respectMultiSelection: boolean, ignoreNestedChildren: boolean = false): ExplorerItem[] {\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/explorerService.ts",
"type": "replace",
"edit_start_line_idx": 149
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { Part } from 'vs/workbench/browser/part';
import { isEmptyObject } from 'vs/base/common/types';
import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService';
import { append, $, hide } from 'vs/base/browser/dom';
import { TestLayoutService } from 'vs/workbench/test/browser/workbenchTestServices';
import { StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { TestStorageService } from 'vs/workbench/test/common/workbenchTestServices';
suite('Workbench parts', () => {
class SimplePart extends Part {
minimumWidth: number = 50;
maximumWidth: number = 50;
minimumHeight: number = 50;
maximumHeight: number = 50;
override layout(width: number, height: number): void {
throw new Error('Method not implemented.');
}
toJSON(): object {
throw new Error('Method not implemented.');
}
}
class MyPart extends SimplePart {
constructor(private expectedParent: HTMLElement) {
super('myPart', { hasTitle: true }, new TestThemeService(), new TestStorageService(), new TestLayoutService());
}
override createTitleArea(parent: HTMLElement): HTMLElement {
assert.strictEqual(parent, this.expectedParent);
return super.createTitleArea(parent)!;
}
override createContentArea(parent: HTMLElement): HTMLElement {
assert.strictEqual(parent, this.expectedParent);
return super.createContentArea(parent)!;
}
override getMemento(scope: StorageScope, target: StorageTarget) {
return super.getMemento(scope, target);
}
override saveState(): void {
return super.saveState();
}
}
class MyPart2 extends SimplePart {
constructor() {
super('myPart2', { hasTitle: true }, new TestThemeService(), new TestStorageService(), new TestLayoutService());
}
override createTitleArea(parent: HTMLElement): HTMLElement {
const titleContainer = append(parent, $('div'));
const titleLabel = append(titleContainer, $('span'));
titleLabel.id = 'myPart.title';
titleLabel.innerText = 'Title';
return titleContainer;
}
override createContentArea(parent: HTMLElement): HTMLElement {
const contentContainer = append(parent, $('div'));
const contentSpan = append(contentContainer, $('span'));
contentSpan.id = 'myPart.content';
contentSpan.innerText = 'Content';
return contentContainer;
}
}
class MyPart3 extends SimplePart {
constructor() {
super('myPart2', { hasTitle: false }, new TestThemeService(), new TestStorageService(), new TestLayoutService());
}
override createTitleArea(parent: HTMLElement): HTMLElement {
return null!;
}
override createContentArea(parent: HTMLElement): HTMLElement {
const contentContainer = append(parent, $('div'));
const contentSpan = append(contentContainer, $('span'));
contentSpan.id = 'myPart.content';
contentSpan.innerText = 'Content';
return contentContainer;
}
}
let fixture: HTMLElement;
const fixtureId = 'workbench-part-fixture';
setup(() => {
fixture = document.createElement('div');
fixture.id = fixtureId;
document.body.appendChild(fixture);
});
teardown(() => {
document.body.removeChild(fixture);
});
test('Creation', () => {
const b = document.createElement('div');
document.getElementById(fixtureId)!.appendChild(b);
hide(b);
let part = new MyPart(b);
part.create(b);
assert.strictEqual(part.getId(), 'myPart');
// Memento
let memento = part.getMemento(StorageScope.PROFILE, StorageTarget.MACHINE) as any;
assert(memento);
memento.foo = 'bar';
memento.bar = [1, 2, 3];
part.saveState();
// Re-Create to assert memento contents
part = new MyPart(b);
memento = part.getMemento(StorageScope.PROFILE, StorageTarget.MACHINE);
assert(memento);
assert.strictEqual(memento.foo, 'bar');
assert.strictEqual(memento.bar.length, 3);
// Empty Memento stores empty object
delete memento.foo;
delete memento.bar;
part.saveState();
part = new MyPart(b);
memento = part.getMemento(StorageScope.PROFILE, StorageTarget.MACHINE);
assert(memento);
assert.strictEqual(isEmptyObject(memento), true);
});
test('Part Layout with Title and Content', function () {
const b = document.createElement('div');
document.getElementById(fixtureId)!.appendChild(b);
hide(b);
const part = new MyPart2();
part.create(b);
assert(document.getElementById('myPart.title'));
assert(document.getElementById('myPart.content'));
});
test('Part Layout with Content only', function () {
const b = document.createElement('div');
document.getElementById(fixtureId)!.appendChild(b);
hide(b);
const part = new MyPart3();
part.create(b);
assert(!document.getElementById('myPart.title'));
assert(document.getElementById('myPart.content'));
});
});
| src/vs/workbench/test/browser/part.test.ts | 0 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.00017930625472217798,
0.00017567648319527507,
0.0001705405447864905,
0.00017603371816221625,
0.0000024624580419185804
]
|
{
"id": 1,
"code_window": [
"\n",
"\t\tconst items = new Set<ExplorerItem>(this.view.getContext(respectMultiSelection));\n",
"\t\titems.forEach(item => {\n",
"\t\t\ttry {\n",
"\t\t\t\tif (respectMultiSelection && this.view?.isItemCollapsed(item) && item.nestedChildren) {\n",
"\t\t\t\t\tfor (const child of item.nestedChildren) {\n",
"\t\t\t\t\t\titems.add(child);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (respectMultiSelection && !ignoreNestedChildren && this.view?.isItemCollapsed(item) && item.nestedChildren) {\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/explorerService.ts",
"type": "replace",
"edit_start_line_idx": 157
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import { IListService } from 'vs/platform/list/browser/listService';
import { OpenEditor, ISortOrderConfiguration } from 'vs/workbench/contrib/files/common/files';
import { EditorResourceAccessor, SideBySideEditor, IEditorIdentifier } from 'vs/workbench/common/editor';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ExplorerItem } from 'vs/workbench/contrib/files/common/explorerModel';
import { coalesce } from 'vs/base/common/arrays';
import { AsyncDataTree } from 'vs/base/browser/ui/tree/asyncDataTree';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IEditableData } from 'vs/workbench/common/views';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ResourceFileEdit } from 'vs/editor/browser/services/bulkEditService';
import { ProgressLocation } from 'vs/platform/progress/common/progress';
export interface IExplorerService {
readonly _serviceBrand: undefined;
readonly roots: ExplorerItem[];
readonly sortOrderConfiguration: ISortOrderConfiguration;
getContext(respectMultiSelection: boolean): ExplorerItem[];
hasViewFocus(): boolean;
setEditable(stat: ExplorerItem, data: IEditableData | null): Promise<void>;
getEditable(): { stat: ExplorerItem; data: IEditableData } | undefined;
getEditableData(stat: ExplorerItem): IEditableData | undefined;
// If undefined is passed checks if any element is currently being edited.
isEditable(stat: ExplorerItem | undefined): boolean;
findClosest(resource: URI): ExplorerItem | null;
findClosestRoot(resource: URI): ExplorerItem | null;
refresh(): Promise<void>;
setToCopy(stats: ExplorerItem[], cut: boolean): Promise<void>;
isCut(stat: ExplorerItem): boolean;
applyBulkEdit(edit: ResourceFileEdit[], options: { undoLabel: string; progressLabel: string; confirmBeforeUndo?: boolean; progressLocation?: ProgressLocation.Explorer | ProgressLocation.Window }): Promise<void>;
/**
* Selects and reveal the file element provided by the given resource if its found in the explorer.
* Will try to resolve the path in case the explorer is not yet expanded to the file yet.
*/
select(resource: URI, reveal?: boolean | string): Promise<void>;
registerView(contextAndRefreshProvider: IExplorerView): void;
}
export const IExplorerService = createDecorator<IExplorerService>('explorerService');
export interface IExplorerView {
getContext(respectMultiSelection: boolean): ExplorerItem[];
refresh(recursive: boolean, item?: ExplorerItem): Promise<void>;
selectResource(resource: URI | undefined, reveal?: boolean | string): Promise<void>;
setTreeInput(): Promise<void>;
itemsCopied(tats: ExplorerItem[], cut: boolean, previousCut: ExplorerItem[] | undefined): void;
setEditable(stat: ExplorerItem, isEditing: boolean): Promise<void>;
isItemVisible(item: ExplorerItem): boolean;
isItemCollapsed(item: ExplorerItem): boolean;
hasFocus(): boolean;
}
function getFocus(listService: IListService): unknown | undefined {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
let focus: unknown;
if (list instanceof List) {
const focused = list.getFocusedElements();
if (focused.length) {
focus = focused[0];
}
} else if (list instanceof AsyncDataTree) {
const focused = list.getFocus();
if (focused.length) {
focus = focused[0];
}
}
return focus;
}
return undefined;
}
// Commands can get executed from a command palette, from a context menu or from some list using a keybinding
// To cover all these cases we need to properly compute the resource on which the command is being executed
export function getResourceForCommand(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): URI | undefined {
if (URI.isUri(resource)) {
return resource;
}
const focus = getFocus(listService);
if (focus instanceof ExplorerItem) {
return focus.resource;
} else if (focus instanceof OpenEditor) {
return focus.getResource();
}
return EditorResourceAccessor.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
}
export function getMultiSelectedResources(resource: URI | object | undefined, listService: IListService, editorService: IEditorService, explorerService: IExplorerService): Array<URI> {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
// Explorer
if (list instanceof AsyncDataTree && list.getFocus().every(item => item instanceof ExplorerItem)) {
// Explorer
const context = explorerService.getContext(true);
if (context.length) {
return context.map(c => c.resource);
}
}
// Open editors view
if (list instanceof List) {
const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor).map((oe: OpenEditor) => oe.getResource()));
const focusedElements = list.getFocusedElements();
const focus = focusedElements.length ? focusedElements[0] : undefined;
let mainUriStr: string | undefined = undefined;
if (URI.isUri(resource)) {
mainUriStr = resource.toString();
} else if (focus instanceof OpenEditor) {
const focusedResource = focus.getResource();
mainUriStr = focusedResource ? focusedResource.toString() : undefined;
}
// We only respect the selection if it contains the main element.
if (selection.some(s => s.toString() === mainUriStr)) {
return selection;
}
}
}
const result = getResourceForCommand(resource, listService, editorService);
return !!result ? [result] : [];
}
export function getOpenEditorsViewMultiSelection(listService: IListService, editorGroupService: IEditorGroupsService): Array<IEditorIdentifier> | undefined {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
// Open editors view
if (list instanceof List) {
const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor));
const focusedElements = list.getFocusedElements();
const focus = focusedElements.length ? focusedElements[0] : undefined;
let mainEditor: IEditorIdentifier | undefined = undefined;
if (focus instanceof OpenEditor) {
mainEditor = focus;
}
// We only respect the selection if it contains the main element.
if (selection.some(s => s === mainEditor)) {
return selection;
}
}
}
return undefined;
}
| src/vs/workbench/contrib/files/browser/files.ts | 1 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.0036681529600173235,
0.00046279843081720173,
0.0001608843303984031,
0.00017161399591714144,
0.00084608921315521
]
|
{
"id": 1,
"code_window": [
"\n",
"\t\tconst items = new Set<ExplorerItem>(this.view.getContext(respectMultiSelection));\n",
"\t\titems.forEach(item => {\n",
"\t\t\ttry {\n",
"\t\t\t\tif (respectMultiSelection && this.view?.isItemCollapsed(item) && item.nestedChildren) {\n",
"\t\t\t\t\tfor (const child of item.nestedChildren) {\n",
"\t\t\t\t\t\titems.add(child);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (respectMultiSelection && !ignoreNestedChildren && this.view?.isItemCollapsed(item) && item.nestedChildren) {\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/explorerService.ts",
"type": "replace",
"edit_start_line_idx": 157
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { getErrorMessage } from 'vs/base/common/errors';
import { mark } from 'vs/base/common/performance';
class MissingStoresError extends Error {
constructor(readonly db: IDBDatabase) {
super('Missing stores');
}
}
export class DBClosedError extends Error {
readonly code = 'DBClosed';
constructor(dbName: string) {
super(`IndexedDB database '${dbName}' is closed.`);
}
}
export class IndexedDB {
static async create(name: string, version: number | undefined, stores: string[]): Promise<IndexedDB> {
const database = await IndexedDB.openDatabase(name, version, stores);
return new IndexedDB(database, name);
}
private static async openDatabase(name: string, version: number | undefined, stores: string[]): Promise<IDBDatabase> {
mark(`code/willOpenDatabase/${name}`);
try {
return await IndexedDB.doOpenDatabase(name, version, stores);
} catch (err) {
if (err instanceof MissingStoresError) {
console.info(`Attempting to recreate the IndexedDB once.`, name);
try {
// Try to delete the db
await IndexedDB.deleteDatabase(err.db);
} catch (error) {
console.error(`Error while deleting the IndexedDB`, getErrorMessage(error));
throw error;
}
return await IndexedDB.doOpenDatabase(name, version, stores);
}
throw err;
} finally {
mark(`code/didOpenDatabase/${name}`);
}
}
private static doOpenDatabase(name: string, version: number | undefined, stores: string[]): Promise<IDBDatabase> {
return new Promise((c, e) => {
const request = window.indexedDB.open(name, version);
request.onerror = () => e(request.error);
request.onsuccess = () => {
const db = request.result;
for (const store of stores) {
if (!db.objectStoreNames.contains(store)) {
console.error(`Error while opening IndexedDB. Could not find '${store}'' object store`);
e(new MissingStoresError(db));
return;
}
}
c(db);
};
request.onupgradeneeded = () => {
const db = request.result;
for (const store of stores) {
if (!db.objectStoreNames.contains(store)) {
db.createObjectStore(store);
}
}
};
});
}
private static deleteDatabase(indexedDB: IDBDatabase): Promise<void> {
return new Promise((c, e) => {
// Close any opened connections
indexedDB.close();
// Delete the db
const deleteRequest = window.indexedDB.deleteDatabase(indexedDB.name);
deleteRequest.onerror = (err) => e(deleteRequest.error);
deleteRequest.onsuccess = () => c();
});
}
private database: IDBDatabase | null = null;
private readonly pendingTransactions: IDBTransaction[] = [];
constructor(database: IDBDatabase, private readonly name: string) {
this.database = database;
}
hasPendingTransactions(): boolean {
return this.pendingTransactions.length > 0;
}
close(): void {
if (this.pendingTransactions.length) {
this.pendingTransactions.splice(0, this.pendingTransactions.length).forEach(transaction => transaction.abort());
}
this.database?.close();
this.database = null;
}
runInTransaction<T>(store: string, transactionMode: IDBTransactionMode, dbRequestFn: (store: IDBObjectStore) => IDBRequest<T>[]): Promise<T[]>;
runInTransaction<T>(store: string, transactionMode: IDBTransactionMode, dbRequestFn: (store: IDBObjectStore) => IDBRequest<T>): Promise<T>;
async runInTransaction<T>(store: string, transactionMode: IDBTransactionMode, dbRequestFn: (store: IDBObjectStore) => IDBRequest<T> | IDBRequest<T>[]): Promise<T | T[]> {
if (!this.database) {
throw new DBClosedError(this.name);
}
const transaction = this.database.transaction(store, transactionMode);
this.pendingTransactions.push(transaction);
return new Promise<T | T[]>((c, e) => {
transaction.oncomplete = () => {
if (Array.isArray(request)) {
c(request.map(r => r.result));
} else {
c(request.result);
}
};
transaction.onerror = () => e(transaction.error);
const request = dbRequestFn(transaction.objectStore(store));
}).finally(() => this.pendingTransactions.splice(this.pendingTransactions.indexOf(transaction), 1));
}
async getKeyValues<V>(store: string, isValid: (value: unknown) => value is V): Promise<Map<string, V>> {
if (!this.database) {
throw new DBClosedError(this.name);
}
const transaction = this.database.transaction(store, 'readonly');
this.pendingTransactions.push(transaction);
return new Promise<Map<string, V>>(resolve => {
const items = new Map<string, V>();
const objectStore = transaction.objectStore(store);
// Open a IndexedDB Cursor to iterate over key/values
const cursor = objectStore.openCursor();
if (!cursor) {
return resolve(items); // this means the `ItemTable` was empty
}
// Iterate over rows of `ItemTable` until the end
cursor.onsuccess = () => {
if (cursor.result) {
// Keep cursor key/value in our map
if (isValid(cursor.result.value)) {
items.set(cursor.result.key.toString(), cursor.result.value);
}
// Advance cursor to next row
cursor.result.continue();
} else {
resolve(items); // reached end of table
}
};
// Error handlers
const onError = (error: Error | null) => {
console.error(`IndexedDB getKeyValues(): ${toErrorMessage(error, true)}`);
resolve(items);
};
cursor.onerror = () => onError(cursor.error);
transaction.onerror = () => onError(transaction.error);
}).finally(() => this.pendingTransactions.splice(this.pendingTransactions.indexOf(transaction), 1));
}
}
| src/vs/base/browser/indexedDB.ts | 0 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.00020656205015257,
0.00017285963986068964,
0.0001654675870668143,
0.00017181145085487515,
0.000008757539944781456
]
|
{
"id": 1,
"code_window": [
"\n",
"\t\tconst items = new Set<ExplorerItem>(this.view.getContext(respectMultiSelection));\n",
"\t\titems.forEach(item => {\n",
"\t\t\ttry {\n",
"\t\t\t\tif (respectMultiSelection && this.view?.isItemCollapsed(item) && item.nestedChildren) {\n",
"\t\t\t\t\tfor (const child of item.nestedChildren) {\n",
"\t\t\t\t\t\titems.add(child);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (respectMultiSelection && !ignoreNestedChildren && this.view?.isItemCollapsed(item) && item.nestedChildren) {\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/explorerService.ts",
"type": "replace",
"edit_start_line_idx": 157
} | #!/bin/sh
PAGESIZE=`getconf PAGESIZE`;
TOTAL_MEMORY=`cat /proc/meminfo | head -n 1 | awk '{print $2}'`;
# Mimic the output of ps -ax -o pid=,ppid=,pcpu=,pmem=,command=
# Read all numeric subdirectories in /proc
for pid in `cd /proc && ls -d [0-9]*`
do {
if [ -e /proc/$pid/stat ]
then
echo $pid;
# ppid is the word at index 4 in the stat file for the process
awk '{print $4}' /proc/$pid/stat;
# pcpu - calculation will be done later, this is a placeholder value
echo "0.0"
# pmem - ratio of the process's working set size to total memory.
# use the page size to convert to bytes, total memory is in KB
# multiplied by 100 to get percentage, extra 10 to be able to move
# the decimal over by one place
RESIDENT_SET_SIZE=`awk '{print $24}' /proc/$pid/stat`;
PERCENT_MEMORY=$(((1000 * $PAGESIZE * $RESIDENT_SET_SIZE) / ($TOTAL_MEMORY * 1024)));
if [ $PERCENT_MEMORY -lt 10 ]
then
# replace the last character with 0. the last character
echo $PERCENT_MEMORY | sed 's/.$/0.&/'; #pmem
else
# insert . before the last character
echo $PERCENT_MEMORY | sed 's/.$/.&/';
fi
# cmdline
xargs -0 < /proc/$pid/cmdline;
fi
} | tr "\n" "\t"; # Replace newlines with tab so that all info for a process is shown on one line
echo; # But add new lines between processes
done
| src/vs/base/node/ps.sh | 0 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.00017539267719257623,
0.00017119935364462435,
0.00016516479081474245,
0.00017211996600963175,
0.0000037333475120249204
]
|
{
"id": 1,
"code_window": [
"\n",
"\t\tconst items = new Set<ExplorerItem>(this.view.getContext(respectMultiSelection));\n",
"\t\titems.forEach(item => {\n",
"\t\t\ttry {\n",
"\t\t\t\tif (respectMultiSelection && this.view?.isItemCollapsed(item) && item.nestedChildren) {\n",
"\t\t\t\t\tfor (const child of item.nestedChildren) {\n",
"\t\t\t\t\t\titems.add(child);\n",
"\t\t\t\t\t}\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\tif (respectMultiSelection && !ignoreNestedChildren && this.view?.isItemCollapsed(item) && item.nestedChildren) {\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/explorerService.ts",
"type": "replace",
"edit_start_line_idx": 157
} | {
"information_for_contributors": [
"This file has been converted from https://github.com/jlelong/vscode-latex-basics/blob/master/syntaxes/Bibtex.tmLanguage.json",
"If you want to provide a fix or improvement, please create a pull request against the original repository.",
"Once accepted there, we are happy to receive an update request."
],
"version": "https://github.com/jlelong/vscode-latex-basics/commit/b98c2d4911652824fc990f4b26c9c30be59b78a2",
"name": "BibTeX",
"scopeName": "text.bibtex",
"comment": "Grammar based on description from http://artis.imag.fr/~Xavier.Decoret/resources/xdkbibtex/bibtex_summary.html#comment\n\t\n\tTODO: Does not support @preamble\n\t",
"patterns": [
{
"begin": "@Comment",
"beginCaptures": {
"0": {
"name": "punctuation.definition.comment.bibtex"
}
},
"end": "$\\n?",
"name": "comment.line.at-sign.bibtex"
},
{
"begin": "((@)(?i:string))\\s*(\\{)\\s*([a-zA-Z]*)",
"beginCaptures": {
"1": {
"name": "keyword.other.string-constant.bibtex"
},
"2": {
"name": "punctuation.definition.keyword.bibtex"
},
"3": {
"name": "punctuation.section.string-constant.begin.bibtex"
},
"4": {
"name": "variable.other.bibtex"
}
},
"end": "\\}",
"endCaptures": {
"0": {
"name": "punctuation.section.string-constant.end.bibtex"
}
},
"name": "meta.string-constant.braces.bibtex",
"patterns": [
{
"include": "#string_content"
}
]
},
{
"begin": "((@)i(?i::string))\\s*(\\()\\s*([a-zA-Z]*)",
"beginCaptures": {
"1": {
"name": "keyword.other.string-constant.bibtex"
},
"2": {
"name": "punctuation.definition.keyword.bibtex"
},
"3": {
"name": "punctuation.section.string-constant.begin.bibtex"
},
"4": {
"name": "variable.other.bibtex"
}
},
"end": "\\)",
"endCaptures": {
"0": {
"name": "punctuation.section.string-constant.end.bibtex"
}
},
"name": "meta.string-constant.parenthesis.bibtex",
"patterns": [
{
"include": "#string_content"
}
]
},
{
"begin": "((@)[a-zA-Z]+)\\s*(\\{)\\s*([^\\s,]*)",
"beginCaptures": {
"1": {
"name": "keyword.other.entry-type.bibtex"
},
"2": {
"name": "punctuation.definition.keyword.bibtex"
},
"3": {
"name": "punctuation.section.entry.begin.bibtex"
},
"4": {
"name": "entity.name.type.entry-key.bibtex"
}
},
"end": "\\}",
"endCaptures": {
"0": {
"name": "punctuation.section.entry.end.bibtex"
}
},
"name": "meta.entry.braces.bibtex",
"patterns": [
{
"begin": "([a-zA-Z0-9\\!\\$\\&\\*\\+\\-\\.\\/\\:\\;\\<\\>\\?\\[\\]\\^\\_\\`\\|]+)\\s*(\\=)",
"beginCaptures": {
"1": {
"name": "support.function.key.bibtex"
},
"2": {
"name": "punctuation.separator.key-value.bibtex"
}
},
"end": "(?=[,}])",
"name": "meta.key-assignment.bibtex",
"patterns": [
{
"include": "#string_var"
},
{
"include": "#string_content"
},
{
"include": "#integer"
}
]
}
]
},
{
"begin": "((@)[a-zA-Z]+)\\s*(\\()\\s*([^\\s,]*)",
"beginCaptures": {
"1": {
"name": "keyword.other.entry-type.bibtex"
},
"2": {
"name": "punctuation.definition.keyword.bibtex"
},
"3": {
"name": "punctuation.section.entry.begin.bibtex"
},
"4": {
"name": "entity.name.type.entry-key.bibtex"
}
},
"end": "\\)",
"endCaptures": {
"0": {
"name": "punctuation.section.entry.end.bibtex"
}
},
"name": "meta.entry.parenthesis.bibtex",
"patterns": [
{
"begin": "([a-zA-Z0-9\\!\\$\\&\\*\\+\\-\\.\\/\\:\\;\\<\\>\\?\\[\\]\\^\\_\\`\\|]+)\\s*(\\=)",
"beginCaptures": {
"1": {
"name": "support.function.key.bibtex"
},
"2": {
"name": "punctuation.separator.key-value.bibtex"
}
},
"end": "(?=[,)])",
"name": "meta.key-assignment.bibtex",
"patterns": [
{
"include": "#string_var"
},
{
"include": "#string_content"
},
{
"include": "#integer"
}
]
}
]
},
{
"begin": "[^@\\n]",
"end": "(?=@)",
"name": "comment.block.bibtex"
}
],
"repository": {
"integer": {
"match": "\\d+",
"name": "constant.numeric.bibtex"
},
"nested_braces": {
"begin": "(?<!\\\\)\\{",
"beginCaptures": {
"0": {
"name": "punctuation.definition.group.begin.bibtex"
}
},
"end": "(?<!\\\\)\\}",
"endCaptures": {
"0": {
"name": "punctuation.definition.group.end.bibtex"
}
},
"patterns": [
{
"include": "#nested_braces"
}
]
},
"string_var": {
"match": "(#)?\\s*([a-zA-Z]+)\\s*(#)?",
"captures": {
"1": {
"name": "keyword.operator.bibtex"
},
"2": {
"name": "support.variable.bibtex"
},
"3": {
"name": "keyword.operator.bibtex"
}
}
},
"string_content": {
"patterns": [
{
"begin": "\\{",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.bibtex"
}
},
"end": "(\\})(?=(?:,?\\s*\\}?\\s*\\n)|(?:\\s*#))",
"endCaptures": {
"1": {
"name": "punctuation.definition.string.end.bibtex"
}
},
"patterns": [
{
"match": "@",
"name": "invalid.illegal.at-sign.bibtex"
},
{
"include": "#nested_braces"
}
]
},
{
"begin": "\"",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.bibtex"
}
},
"end": "\"(?=(?:,?\\s*\\}?\\s*\\n)|(?:\\s*#))",
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.bibtex"
}
},
"patterns": [
{
"match": "@",
"name": "invalid.illegal.at-sign.bibtex"
}
]
}
]
}
}
} | extensions/latex/syntaxes/Bibtex.tmLanguage.json | 0 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.00017641932936385274,
0.00017422383825760335,
0.00017167151963803917,
0.00017425764235667884,
0.0000012695560371867032
]
|
{
"id": 2,
"code_window": [
"\treadonly roots: ExplorerItem[];\n",
"\treadonly sortOrderConfiguration: ISortOrderConfiguration;\n",
"\n",
"\tgetContext(respectMultiSelection: boolean): ExplorerItem[];\n",
"\thasViewFocus(): boolean;\n",
"\tsetEditable(stat: ExplorerItem, data: IEditableData | null): Promise<void>;\n",
"\tgetEditable(): { stat: ExplorerItem; data: IEditableData } | undefined;\n",
"\tgetEditableData(stat: ExplorerItem): IEditableData | undefined;\n",
"\t// If undefined is passed checks if any element is currently being edited.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tgetContext(respectMultiSelection: boolean, ignoreNestedChildren?: boolean): ExplorerItem[];\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/files.ts",
"type": "replace",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import { IListService } from 'vs/platform/list/browser/listService';
import { OpenEditor, ISortOrderConfiguration } from 'vs/workbench/contrib/files/common/files';
import { EditorResourceAccessor, SideBySideEditor, IEditorIdentifier } from 'vs/workbench/common/editor';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ExplorerItem } from 'vs/workbench/contrib/files/common/explorerModel';
import { coalesce } from 'vs/base/common/arrays';
import { AsyncDataTree } from 'vs/base/browser/ui/tree/asyncDataTree';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IEditableData } from 'vs/workbench/common/views';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ResourceFileEdit } from 'vs/editor/browser/services/bulkEditService';
import { ProgressLocation } from 'vs/platform/progress/common/progress';
export interface IExplorerService {
readonly _serviceBrand: undefined;
readonly roots: ExplorerItem[];
readonly sortOrderConfiguration: ISortOrderConfiguration;
getContext(respectMultiSelection: boolean): ExplorerItem[];
hasViewFocus(): boolean;
setEditable(stat: ExplorerItem, data: IEditableData | null): Promise<void>;
getEditable(): { stat: ExplorerItem; data: IEditableData } | undefined;
getEditableData(stat: ExplorerItem): IEditableData | undefined;
// If undefined is passed checks if any element is currently being edited.
isEditable(stat: ExplorerItem | undefined): boolean;
findClosest(resource: URI): ExplorerItem | null;
findClosestRoot(resource: URI): ExplorerItem | null;
refresh(): Promise<void>;
setToCopy(stats: ExplorerItem[], cut: boolean): Promise<void>;
isCut(stat: ExplorerItem): boolean;
applyBulkEdit(edit: ResourceFileEdit[], options: { undoLabel: string; progressLabel: string; confirmBeforeUndo?: boolean; progressLocation?: ProgressLocation.Explorer | ProgressLocation.Window }): Promise<void>;
/**
* Selects and reveal the file element provided by the given resource if its found in the explorer.
* Will try to resolve the path in case the explorer is not yet expanded to the file yet.
*/
select(resource: URI, reveal?: boolean | string): Promise<void>;
registerView(contextAndRefreshProvider: IExplorerView): void;
}
export const IExplorerService = createDecorator<IExplorerService>('explorerService');
export interface IExplorerView {
getContext(respectMultiSelection: boolean): ExplorerItem[];
refresh(recursive: boolean, item?: ExplorerItem): Promise<void>;
selectResource(resource: URI | undefined, reveal?: boolean | string): Promise<void>;
setTreeInput(): Promise<void>;
itemsCopied(tats: ExplorerItem[], cut: boolean, previousCut: ExplorerItem[] | undefined): void;
setEditable(stat: ExplorerItem, isEditing: boolean): Promise<void>;
isItemVisible(item: ExplorerItem): boolean;
isItemCollapsed(item: ExplorerItem): boolean;
hasFocus(): boolean;
}
function getFocus(listService: IListService): unknown | undefined {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
let focus: unknown;
if (list instanceof List) {
const focused = list.getFocusedElements();
if (focused.length) {
focus = focused[0];
}
} else if (list instanceof AsyncDataTree) {
const focused = list.getFocus();
if (focused.length) {
focus = focused[0];
}
}
return focus;
}
return undefined;
}
// Commands can get executed from a command palette, from a context menu or from some list using a keybinding
// To cover all these cases we need to properly compute the resource on which the command is being executed
export function getResourceForCommand(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): URI | undefined {
if (URI.isUri(resource)) {
return resource;
}
const focus = getFocus(listService);
if (focus instanceof ExplorerItem) {
return focus.resource;
} else if (focus instanceof OpenEditor) {
return focus.getResource();
}
return EditorResourceAccessor.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
}
export function getMultiSelectedResources(resource: URI | object | undefined, listService: IListService, editorService: IEditorService, explorerService: IExplorerService): Array<URI> {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
// Explorer
if (list instanceof AsyncDataTree && list.getFocus().every(item => item instanceof ExplorerItem)) {
// Explorer
const context = explorerService.getContext(true);
if (context.length) {
return context.map(c => c.resource);
}
}
// Open editors view
if (list instanceof List) {
const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor).map((oe: OpenEditor) => oe.getResource()));
const focusedElements = list.getFocusedElements();
const focus = focusedElements.length ? focusedElements[0] : undefined;
let mainUriStr: string | undefined = undefined;
if (URI.isUri(resource)) {
mainUriStr = resource.toString();
} else if (focus instanceof OpenEditor) {
const focusedResource = focus.getResource();
mainUriStr = focusedResource ? focusedResource.toString() : undefined;
}
// We only respect the selection if it contains the main element.
if (selection.some(s => s.toString() === mainUriStr)) {
return selection;
}
}
}
const result = getResourceForCommand(resource, listService, editorService);
return !!result ? [result] : [];
}
export function getOpenEditorsViewMultiSelection(listService: IListService, editorGroupService: IEditorGroupsService): Array<IEditorIdentifier> | undefined {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
// Open editors view
if (list instanceof List) {
const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor));
const focusedElements = list.getFocusedElements();
const focus = focusedElements.length ? focusedElements[0] : undefined;
let mainEditor: IEditorIdentifier | undefined = undefined;
if (focus instanceof OpenEditor) {
mainEditor = focus;
}
// We only respect the selection if it contains the main element.
if (selection.some(s => s === mainEditor)) {
return selection;
}
}
}
return undefined;
}
| src/vs/workbench/contrib/files/browser/files.ts | 1 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.9970382452011108,
0.15287023782730103,
0.00016408905503340065,
0.0001727087947074324,
0.3222711980342865
]
|
{
"id": 2,
"code_window": [
"\treadonly roots: ExplorerItem[];\n",
"\treadonly sortOrderConfiguration: ISortOrderConfiguration;\n",
"\n",
"\tgetContext(respectMultiSelection: boolean): ExplorerItem[];\n",
"\thasViewFocus(): boolean;\n",
"\tsetEditable(stat: ExplorerItem, data: IEditableData | null): Promise<void>;\n",
"\tgetEditable(): { stat: ExplorerItem; data: IEditableData } | undefined;\n",
"\tgetEditableData(stat: ExplorerItem): IEditableData | undefined;\n",
"\t// If undefined is passed checks if any element is currently being edited.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tgetContext(respectMultiSelection: boolean, ignoreNestedChildren?: boolean): ExplorerItem[];\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/files.ts",
"type": "replace",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CharCode } from 'vs/base/common/charCode';
/**
* Returns:
* - -1 => the line consists of whitespace
* - otherwise => the indent level is returned value
*/
export function computeIndentLevel(line: string, tabSize: number): number {
let indent = 0;
let i = 0;
const len = line.length;
while (i < len) {
const chCode = line.charCodeAt(i);
if (chCode === CharCode.Space) {
indent++;
} else if (chCode === CharCode.Tab) {
indent = indent - indent % tabSize + tabSize;
} else {
break;
}
i++;
}
if (i === len) {
return -1; // line only consists of whitespace
}
return indent;
}
| src/vs/editor/common/model/utils.ts | 0 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.00017667638894636184,
0.0001750954834278673,
0.00017241119348909706,
0.00017564717563800514,
0.0000016297029787892825
]
|
{
"id": 2,
"code_window": [
"\treadonly roots: ExplorerItem[];\n",
"\treadonly sortOrderConfiguration: ISortOrderConfiguration;\n",
"\n",
"\tgetContext(respectMultiSelection: boolean): ExplorerItem[];\n",
"\thasViewFocus(): boolean;\n",
"\tsetEditable(stat: ExplorerItem, data: IEditableData | null): Promise<void>;\n",
"\tgetEditable(): { stat: ExplorerItem; data: IEditableData } | undefined;\n",
"\tgetEditableData(stat: ExplorerItem): IEditableData | undefined;\n",
"\t// If undefined is passed checks if any element is currently being edited.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tgetContext(respectMultiSelection: boolean, ignoreNestedChildren?: boolean): ExplorerItem[];\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/files.ts",
"type": "replace",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as dom from 'vs/base/browser/dom';
import { Disposable, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import * as strings from 'vs/base/common/strings';
import 'vs/css!./ghostText';
import { applyFontInfo } from 'vs/editor/browser/config/domFontInfo';
import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser';
import { EditorFontLigatures, EditorOption, IComputedEditorOptions } from 'vs/editor/common/config/editorOptions';
import { LineTokens } from 'vs/editor/common/tokens/lineTokens';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { StringBuilder } from 'vs/editor/common/core/stringBuilder';
import { IModelDeltaDecoration, InjectedTextCursorStops, PositionAffinity } from 'vs/editor/common/model';
import { ILanguageIdCodec } from 'vs/editor/common/languages';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { ghostTextBackground, ghostTextBorder, ghostTextForeground } from 'vs/editor/common/core/editorColorRegistry';
import { LineDecoration } from 'vs/editor/common/viewLayout/lineDecorations';
import { RenderLineInput, renderViewLine } from 'vs/editor/common/viewLayout/viewLineRenderer';
import { InlineDecorationType } from 'vs/editor/common/viewModel';
import { GhostTextReplacement, GhostTextWidgetModel } from 'vs/editor/contrib/inlineCompletions/browser/ghostText';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
const ttPolicy = window.trustedTypes?.createPolicy('editorGhostText', { createHTML: value => value });
export class GhostTextWidget extends Disposable {
private disposed = false;
private readonly partsWidget = this._register(this.instantiationService.createInstance(DecorationsWidget, this.editor));
private readonly additionalLinesWidget = this._register(new AdditionalLinesWidget(this.editor, this.languageService.languageIdCodec));
private viewMoreContentWidget: ViewMoreLinesContentWidget | undefined = undefined;
constructor(
private readonly editor: ICodeEditor,
private readonly model: GhostTextWidgetModel,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@ILanguageService private readonly languageService: ILanguageService,
) {
super();
this._register(this.editor.onDidChangeConfiguration((e) => {
if (
e.hasChanged(EditorOption.disableMonospaceOptimizations)
|| e.hasChanged(EditorOption.stopRenderingLineAfter)
|| e.hasChanged(EditorOption.renderWhitespace)
|| e.hasChanged(EditorOption.renderControlCharacters)
|| e.hasChanged(EditorOption.fontLigatures)
|| e.hasChanged(EditorOption.fontInfo)
|| e.hasChanged(EditorOption.lineHeight)
) {
this.update();
}
}));
this._register(toDisposable(() => {
this.disposed = true;
this.update();
this.viewMoreContentWidget?.dispose();
this.viewMoreContentWidget = undefined;
}));
this._register(model.onDidChange(() => {
this.update();
}));
this.update();
}
public shouldShowHoverAtViewZone(viewZoneId: string): boolean {
return (this.additionalLinesWidget.viewZoneId === viewZoneId);
}
private readonly replacementDecoration = this._register(new DisposableDecorations(this.editor));
private update(): void {
const ghostText = this.model.ghostText;
if (!this.editor.hasModel() || !ghostText || this.disposed) {
this.partsWidget.clear();
this.additionalLinesWidget.clear();
this.replacementDecoration.clear();
return;
}
const inlineTexts = new Array<InsertedInlineText>();
const additionalLines = new Array<LineData>();
function addToAdditionalLines(lines: readonly string[], className: string | undefined) {
if (additionalLines.length > 0) {
const lastLine = additionalLines[additionalLines.length - 1];
if (className) {
lastLine.decorations.push(new LineDecoration(lastLine.content.length + 1, lastLine.content.length + 1 + lines[0].length, className, InlineDecorationType.Regular));
}
lastLine.content += lines[0];
lines = lines.slice(1);
}
for (const line of lines) {
additionalLines.push({
content: line,
decorations: className ? [new LineDecoration(1, line.length + 1, className, InlineDecorationType.Regular)] : []
});
}
}
if (ghostText instanceof GhostTextReplacement) {
this.replacementDecoration.setDecorations([
{
range: new Range(
ghostText.lineNumber,
ghostText.columnStart,
ghostText.lineNumber,
ghostText.columnStart + ghostText.length
),
options: {
inlineClassName: 'inline-completion-text-to-replace',
description: 'GhostTextReplacement'
}
},
]);
} else {
this.replacementDecoration.setDecorations([]);
}
const textBufferLine = this.editor.getModel().getLineContent(ghostText.lineNumber);
let hiddenTextStartColumn: number | undefined = undefined;
let lastIdx = 0;
for (const part of ghostText.parts) {
let lines = part.lines;
if (hiddenTextStartColumn === undefined) {
inlineTexts.push({
column: part.column,
text: lines[0],
preview: part.preview,
});
lines = lines.slice(1);
} else {
addToAdditionalLines([textBufferLine.substring(lastIdx, part.column - 1)], undefined);
}
if (lines.length > 0) {
addToAdditionalLines(lines, 'ghost-text');
if (hiddenTextStartColumn === undefined && part.column <= textBufferLine.length) {
hiddenTextStartColumn = part.column;
}
}
lastIdx = part.column - 1;
}
if (hiddenTextStartColumn !== undefined) {
addToAdditionalLines([textBufferLine.substring(lastIdx)], undefined);
}
this.partsWidget.setParts(ghostText.lineNumber, inlineTexts,
hiddenTextStartColumn !== undefined ? { column: hiddenTextStartColumn, length: textBufferLine.length + 1 - hiddenTextStartColumn } : undefined);
this.additionalLinesWidget.updateLines(ghostText.lineNumber, additionalLines, ghostText.additionalReservedLineCount);
if (0 < 0) {
// Not supported at the moment, condition is always false.
this.viewMoreContentWidget = this.renderViewMoreLines(
new Position(ghostText.lineNumber, this.editor.getModel()!.getLineMaxColumn(ghostText.lineNumber)),
'', 0
);
} else {
this.viewMoreContentWidget?.dispose();
this.viewMoreContentWidget = undefined;
}
}
private renderViewMoreLines(position: Position, firstLineText: string, remainingLinesLength: number): ViewMoreLinesContentWidget {
const fontInfo = this.editor.getOption(EditorOption.fontInfo);
const domNode = document.createElement('div');
domNode.className = 'suggest-preview-additional-widget';
applyFontInfo(domNode, fontInfo);
const spacer = document.createElement('span');
spacer.className = 'content-spacer';
spacer.append(firstLineText);
domNode.append(spacer);
const newline = document.createElement('span');
newline.className = 'content-newline suggest-preview-text';
newline.append('⏎ ');
domNode.append(newline);
const disposableStore = new DisposableStore();
const button = document.createElement('div');
button.className = 'button suggest-preview-text';
button.append(`+${remainingLinesLength} lines…`);
disposableStore.add(dom.addStandardDisposableListener(button, 'mousedown', (e) => {
this.model?.setExpanded(true);
e.preventDefault();
this.editor.focus();
}));
domNode.append(button);
return new ViewMoreLinesContentWidget(this.editor, position, domNode, disposableStore);
}
}
class DisposableDecorations {
private decorationIds: string[] = [];
constructor(private readonly editor: ICodeEditor) {
}
public setDecorations(decorations: IModelDeltaDecoration[]): void {
// Using change decorations ensures that we update the id's before some event handler is called.
this.editor.changeDecorations(accessor => {
this.decorationIds = accessor.deltaDecorations(this.decorationIds, decorations);
});
}
public clear(): void {
this.setDecorations([]);
}
public dispose(): void {
this.clear();
}
}
interface HiddenText {
column: number;
length: number;
}
interface InsertedInlineText {
column: number;
text: string;
preview: boolean;
}
class DecorationsWidget implements IDisposable {
private decorationIds: string[] = [];
constructor(
private readonly editor: ICodeEditor
) {
}
public dispose(): void {
this.clear();
}
public clear(): void {
// Using change decorations ensures that we update the id's before some event handler is called.
this.editor.changeDecorations(accessor => {
this.decorationIds = accessor.deltaDecorations(this.decorationIds, []);
});
}
public setParts(lineNumber: number, parts: InsertedInlineText[], hiddenText?: HiddenText): void {
const textModel = this.editor.getModel();
if (!textModel) {
return;
}
const hiddenTextDecorations = new Array<IModelDeltaDecoration>();
if (hiddenText) {
hiddenTextDecorations.push({
range: Range.fromPositions(new Position(lineNumber, hiddenText.column), new Position(lineNumber, hiddenText.column + hiddenText.length)),
options: {
inlineClassName: 'ghost-text-hidden',
description: 'ghost-text-hidden',
}
});
}
// Using change decorations ensures that we update the id's before some event handler is called.
this.editor.changeDecorations(accessor => {
this.decorationIds = accessor.deltaDecorations(this.decorationIds, parts.map<IModelDeltaDecoration>(p => {
return ({
range: Range.fromPositions(new Position(lineNumber, p.column)),
options: {
description: 'ghost-text',
after: { content: p.text, inlineClassName: p.preview ? 'ghost-text-decoration-preview' : 'ghost-text-decoration', cursorStops: InjectedTextCursorStops.Left },
showIfCollapsed: true,
}
});
}).concat(hiddenTextDecorations));
});
}
}
class AdditionalLinesWidget implements IDisposable {
private _viewZoneId: string | undefined = undefined;
public get viewZoneId(): string | undefined { return this._viewZoneId; }
constructor(
private readonly editor: ICodeEditor,
private readonly languageIdCodec: ILanguageIdCodec
) { }
public dispose(): void {
this.clear();
}
public clear(): void {
this.editor.changeViewZones((changeAccessor) => {
if (this._viewZoneId) {
changeAccessor.removeZone(this._viewZoneId);
this._viewZoneId = undefined;
}
});
}
public updateLines(lineNumber: number, additionalLines: LineData[], minReservedLineCount: number): void {
const textModel = this.editor.getModel();
if (!textModel) {
return;
}
const { tabSize } = textModel.getOptions();
this.editor.changeViewZones((changeAccessor) => {
if (this._viewZoneId) {
changeAccessor.removeZone(this._viewZoneId);
this._viewZoneId = undefined;
}
const heightInLines = Math.max(additionalLines.length, minReservedLineCount);
if (heightInLines > 0) {
const domNode = document.createElement('div');
renderLines(domNode, tabSize, additionalLines, this.editor.getOptions(), this.languageIdCodec);
this._viewZoneId = changeAccessor.addZone({
afterLineNumber: lineNumber,
heightInLines: heightInLines,
domNode,
afterColumnAffinity: PositionAffinity.Right
});
}
});
}
}
interface LineData {
content: string;
decorations: LineDecoration[];
}
function renderLines(domNode: HTMLElement, tabSize: number, lines: LineData[], opts: IComputedEditorOptions, languageIdCodec: ILanguageIdCodec): void {
const disableMonospaceOptimizations = opts.get(EditorOption.disableMonospaceOptimizations);
const stopRenderingLineAfter = opts.get(EditorOption.stopRenderingLineAfter);
// To avoid visual confusion, we don't want to render visible whitespace
const renderWhitespace = 'none';
const renderControlCharacters = opts.get(EditorOption.renderControlCharacters);
const fontLigatures = opts.get(EditorOption.fontLigatures);
const fontInfo = opts.get(EditorOption.fontInfo);
const lineHeight = opts.get(EditorOption.lineHeight);
const sb = new StringBuilder(10000);
sb.appendASCIIString('<div class="suggest-preview-text">');
for (let i = 0, len = lines.length; i < len; i++) {
const lineData = lines[i];
const line = lineData.content;
sb.appendASCIIString('<div class="view-line');
sb.appendASCIIString('" style="top:');
sb.appendASCIIString(String(i * lineHeight));
sb.appendASCIIString('px;width:1000000px;">');
const isBasicASCII = strings.isBasicASCII(line);
const containsRTL = strings.containsRTL(line);
const lineTokens = LineTokens.createEmpty(line, languageIdCodec);
renderViewLine(new RenderLineInput(
(fontInfo.isMonospace && !disableMonospaceOptimizations),
fontInfo.canUseHalfwidthRightwardsArrow,
line,
false,
isBasicASCII,
containsRTL,
0,
lineTokens,
lineData.decorations,
tabSize,
0,
fontInfo.spaceWidth,
fontInfo.middotWidth,
fontInfo.wsmiddotWidth,
stopRenderingLineAfter,
renderWhitespace,
renderControlCharacters,
fontLigatures !== EditorFontLigatures.OFF,
null
), sb);
sb.appendASCIIString('</div>');
}
sb.appendASCIIString('</div>');
applyFontInfo(domNode, fontInfo);
const html = sb.build();
const trustedhtml = ttPolicy ? ttPolicy.createHTML(html) : html;
domNode.innerHTML = trustedhtml as string;
}
class ViewMoreLinesContentWidget extends Disposable implements IContentWidget {
readonly allowEditorOverflow = false;
readonly suppressMouseDown = false;
constructor(
private editor: ICodeEditor,
private position: Position,
private domNode: HTMLElement,
disposableStore: DisposableStore
) {
super();
this._register(disposableStore);
this._register(toDisposable(() => {
this.editor.removeContentWidget(this);
}));
this.editor.addContentWidget(this);
}
getId(): string {
return 'editor.widget.viewMoreLinesWidget';
}
getDomNode(): HTMLElement {
return this.domNode;
}
getPosition(): IContentWidgetPosition | null {
return {
position: this.position,
preference: [ContentWidgetPositionPreference.EXACT]
};
}
}
registerThemingParticipant((theme, collector) => {
const foreground = theme.getColor(ghostTextForeground);
if (foreground) {
// `!important` ensures that other decorations don't cause a style conflict (#132017).
collector.addRule(`.monaco-editor .ghost-text-decoration { color: ${foreground.toString()} !important; }`);
collector.addRule(`.monaco-editor .ghost-text-decoration-preview { color: ${foreground.toString()} !important; }`);
collector.addRule(`.monaco-editor .suggest-preview-text .ghost-text { color: ${foreground.toString()} !important; }`);
}
const background = theme.getColor(ghostTextBackground);
if (background) {
collector.addRule(`.monaco-editor .ghost-text-decoration { background-color: ${background.toString()}; }`);
collector.addRule(`.monaco-editor .ghost-text-decoration-preview { background-color: ${background.toString()}; }`);
collector.addRule(`.monaco-editor .suggest-preview-text .ghost-text { background-color: ${background.toString()}; }`);
}
const border = theme.getColor(ghostTextBorder);
if (border) {
collector.addRule(`.monaco-editor .suggest-preview-text .ghost-text { border: 1px solid ${border}; }`);
collector.addRule(`.monaco-editor .ghost-text-decoration { border: 1px solid ${border}; }`);
collector.addRule(`.monaco-editor .ghost-text-decoration-preview { border: 1px solid ${border}; }`);
}
});
| src/vs/editor/contrib/inlineCompletions/browser/ghostTextWidget.ts | 0 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.0001779873127816245,
0.00017214751278515905,
0.00016495012096129358,
0.00017265616043005139,
0.00000384746181225637
]
|
{
"id": 2,
"code_window": [
"\treadonly roots: ExplorerItem[];\n",
"\treadonly sortOrderConfiguration: ISortOrderConfiguration;\n",
"\n",
"\tgetContext(respectMultiSelection: boolean): ExplorerItem[];\n",
"\thasViewFocus(): boolean;\n",
"\tsetEditable(stat: ExplorerItem, data: IEditableData | null): Promise<void>;\n",
"\tgetEditable(): { stat: ExplorerItem; data: IEditableData } | undefined;\n",
"\tgetEditableData(stat: ExplorerItem): IEditableData | undefined;\n",
"\t// If undefined is passed checks if any element is currently being edited.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tgetContext(respectMultiSelection: boolean, ignoreNestedChildren?: boolean): ExplorerItem[];\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/files.ts",
"type": "replace",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { GroupIdentifier, IWorkbenchEditorConfiguration, IEditorIdentifier, IEditorCloseEvent, IEditorPartOptions, IEditorPartOptionsChangeEvent, SideBySideEditor, EditorCloseContext } from 'vs/workbench/common/editor';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { IEditorGroup, GroupDirection, IAddGroupOptions, IMergeGroupOptions, GroupsOrder, GroupsArrangement } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IDisposable } from 'vs/base/common/lifecycle';
import { Dimension } from 'vs/base/browser/dom';
import { Event } from 'vs/base/common/event';
import { IConfigurationChangeEvent, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { ISerializableView } from 'vs/base/browser/ui/grid/grid';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { isObject } from 'vs/base/common/types';
import { IEditorOptions } from 'vs/platform/editor/common/editor';
export interface IEditorPartCreationOptions {
restorePreviousState: boolean;
}
export const DEFAULT_EDITOR_MIN_DIMENSIONS = new Dimension(220, 70);
export const DEFAULT_EDITOR_MAX_DIMENSIONS = new Dimension(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
export const DEFAULT_EDITOR_PART_OPTIONS: IEditorPartOptions = {
showTabs: true,
highlightModifiedTabs: false,
tabCloseButton: 'right',
tabSizing: 'fit',
pinnedTabSizing: 'normal',
titleScrollbarSizing: 'default',
focusRecentEditorAfterClose: true,
showIcons: true,
hasIcons: true, // 'vs-seti' is our default icon theme
enablePreview: true,
openPositioning: 'right',
openSideBySideDirection: 'right',
closeEmptyGroups: true,
labelFormat: 'default',
splitSizing: 'distribute',
splitOnDragAndDrop: true
};
export function impactsEditorPartOptions(event: IConfigurationChangeEvent): boolean {
return event.affectsConfiguration('workbench.editor') || event.affectsConfiguration('workbench.iconTheme');
}
export function getEditorPartOptions(configurationService: IConfigurationService, themeService: IThemeService): IEditorPartOptions {
const options = {
...DEFAULT_EDITOR_PART_OPTIONS,
hasIcons: themeService.getFileIconTheme().hasFileIcons
};
const config = configurationService.getValue<IWorkbenchEditorConfiguration>();
if (config?.workbench?.editor) {
// Assign all primitive configuration over
Object.assign(options, config.workbench.editor);
// Special handle array types and convert to Set
if (isObject(config.workbench.editor.autoLockGroups)) {
options.autoLockGroups = new Set();
for (const [editorId, enablement] of Object.entries(config.workbench.editor.autoLockGroups)) {
if (enablement === true) {
options.autoLockGroups.add(editorId);
}
}
} else {
options.autoLockGroups = undefined;
}
}
return options;
}
export interface IEditorGroupsAccessor {
readonly groups: IEditorGroupView[];
readonly activeGroup: IEditorGroupView;
readonly partOptions: IEditorPartOptions;
readonly onDidChangeEditorPartOptions: Event<IEditorPartOptionsChangeEvent>;
readonly onDidVisibilityChange: Event<boolean>;
getGroup(identifier: GroupIdentifier): IEditorGroupView | undefined;
getGroups(order: GroupsOrder): IEditorGroupView[];
activateGroup(identifier: IEditorGroupView | GroupIdentifier): IEditorGroupView;
restoreGroup(identifier: IEditorGroupView | GroupIdentifier): IEditorGroupView;
addGroup(location: IEditorGroupView | GroupIdentifier, direction: GroupDirection, options?: IAddGroupOptions): IEditorGroupView;
mergeGroup(group: IEditorGroupView | GroupIdentifier, target: IEditorGroupView | GroupIdentifier, options?: IMergeGroupOptions): IEditorGroupView;
moveGroup(group: IEditorGroupView | GroupIdentifier, location: IEditorGroupView | GroupIdentifier, direction: GroupDirection): IEditorGroupView;
copyGroup(group: IEditorGroupView | GroupIdentifier, location: IEditorGroupView | GroupIdentifier, direction: GroupDirection): IEditorGroupView;
removeGroup(group: IEditorGroupView | GroupIdentifier): void;
arrangeGroups(arrangement: GroupsArrangement, target?: IEditorGroupView | GroupIdentifier): void;
}
export interface IEditorGroupTitleHeight {
/**
* The overall height of the editor group title control.
*/
total: number;
/**
* The height offset to e.g. use when drawing drop overlays.
* This number may be smaller than `height` if the title control
* decides to have an `offset` that is within the title area
* (e.g. when breadcrumbs are enabled).
*/
offset: number;
}
export interface IEditorGroupView extends IDisposable, ISerializableView, IEditorGroup {
readonly onDidFocus: Event<void>;
readonly onDidOpenEditorFail: Event<EditorInput>;
readonly onDidCloseEditor: Event<IEditorCloseEvent>;
/**
* A promise that resolves when the group has been restored.
*
* For a group with active editor, the promise will resolve
* when the active editor has finished to resolve.
*/
readonly whenRestored: Promise<void>;
readonly titleHeight: IEditorGroupTitleHeight;
readonly disposed: boolean;
setActive(isActive: boolean): void;
notifyIndexChanged(newIndex: number): void;
relayout(): void;
}
export function fillActiveEditorViewState(group: IEditorGroup, expectedActiveEditor?: EditorInput, presetOptions?: IEditorOptions): IEditorOptions {
if (!expectedActiveEditor || !group.activeEditor || expectedActiveEditor.matches(group.activeEditor)) {
const options: IEditorOptions = {
...presetOptions,
viewState: group.activeEditorPane?.getViewState()
};
return options;
}
return presetOptions || Object.create(null);
}
/**
* A sub-interface of IEditorService to hide some workbench-core specific
* events from clients.
*/
export interface EditorServiceImpl extends IEditorService {
/**
* Emitted when an editor failed to open.
*/
readonly onDidOpenEditorFail: Event<IEditorIdentifier>;
/**
* Emitted when the list of most recently active editors change.
*/
readonly onDidMostRecentlyActiveEditorsChange: Event<void>;
}
export interface IInternalEditorTitleControlOptions {
/**
* A hint to defer updating the title control for perf reasons.
* The caller must ensure to update the title control then.
*/
skipTitleUpdate?: boolean;
}
export interface IInternalEditorOpenOptions extends IInternalEditorTitleControlOptions {
/**
* Whether to consider a side by side editor as matching
* when figuring out if the editor to open is already
* opened or not. By default, side by side editors will
* not be considered as matching, even if the editor is
* opened in one of the sides.
*/
supportSideBySide?: SideBySideEditor.ANY | SideBySideEditor.BOTH;
}
export interface IInternalEditorCloseOptions extends IInternalEditorTitleControlOptions {
/**
* A hint that the editor is closed due to an error opening. This can be
* used to optimize how error toasts are appearing if any.
*/
fromError?: boolean;
/**
* Additional context as to why an editor is closed.
*/
context?: EditorCloseContext;
}
export interface IInternalMoveCopyOptions extends IInternalEditorTitleControlOptions {
/**
* Whether to close the editor at the source or keep it.
*/
keepCopy?: boolean;
}
| src/vs/workbench/browser/parts/editor/editor.ts | 0 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.0001971231831703335,
0.00017458941147197038,
0.00016405712813138962,
0.00017222293536178768,
0.000009395606866746675
]
|
{
"id": 3,
"code_window": [
"\t\t// Explorer\n",
"\t\tif (list instanceof AsyncDataTree && list.getFocus().every(item => item instanceof ExplorerItem)) {\n",
"\t\t\t// Explorer\n",
"\t\t\tconst context = explorerService.getContext(true);\n",
"\t\t\tif (context.length) {\n",
"\t\t\t\treturn context.map(c => c.resource);\n",
"\t\t\t}\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst context = explorerService.getContext(true, true);\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/files.ts",
"type": "replace",
"edit_start_line_idx": 107
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import { IListService } from 'vs/platform/list/browser/listService';
import { OpenEditor, ISortOrderConfiguration } from 'vs/workbench/contrib/files/common/files';
import { EditorResourceAccessor, SideBySideEditor, IEditorIdentifier } from 'vs/workbench/common/editor';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ExplorerItem } from 'vs/workbench/contrib/files/common/explorerModel';
import { coalesce } from 'vs/base/common/arrays';
import { AsyncDataTree } from 'vs/base/browser/ui/tree/asyncDataTree';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IEditableData } from 'vs/workbench/common/views';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { ResourceFileEdit } from 'vs/editor/browser/services/bulkEditService';
import { ProgressLocation } from 'vs/platform/progress/common/progress';
export interface IExplorerService {
readonly _serviceBrand: undefined;
readonly roots: ExplorerItem[];
readonly sortOrderConfiguration: ISortOrderConfiguration;
getContext(respectMultiSelection: boolean): ExplorerItem[];
hasViewFocus(): boolean;
setEditable(stat: ExplorerItem, data: IEditableData | null): Promise<void>;
getEditable(): { stat: ExplorerItem; data: IEditableData } | undefined;
getEditableData(stat: ExplorerItem): IEditableData | undefined;
// If undefined is passed checks if any element is currently being edited.
isEditable(stat: ExplorerItem | undefined): boolean;
findClosest(resource: URI): ExplorerItem | null;
findClosestRoot(resource: URI): ExplorerItem | null;
refresh(): Promise<void>;
setToCopy(stats: ExplorerItem[], cut: boolean): Promise<void>;
isCut(stat: ExplorerItem): boolean;
applyBulkEdit(edit: ResourceFileEdit[], options: { undoLabel: string; progressLabel: string; confirmBeforeUndo?: boolean; progressLocation?: ProgressLocation.Explorer | ProgressLocation.Window }): Promise<void>;
/**
* Selects and reveal the file element provided by the given resource if its found in the explorer.
* Will try to resolve the path in case the explorer is not yet expanded to the file yet.
*/
select(resource: URI, reveal?: boolean | string): Promise<void>;
registerView(contextAndRefreshProvider: IExplorerView): void;
}
export const IExplorerService = createDecorator<IExplorerService>('explorerService');
export interface IExplorerView {
getContext(respectMultiSelection: boolean): ExplorerItem[];
refresh(recursive: boolean, item?: ExplorerItem): Promise<void>;
selectResource(resource: URI | undefined, reveal?: boolean | string): Promise<void>;
setTreeInput(): Promise<void>;
itemsCopied(tats: ExplorerItem[], cut: boolean, previousCut: ExplorerItem[] | undefined): void;
setEditable(stat: ExplorerItem, isEditing: boolean): Promise<void>;
isItemVisible(item: ExplorerItem): boolean;
isItemCollapsed(item: ExplorerItem): boolean;
hasFocus(): boolean;
}
function getFocus(listService: IListService): unknown | undefined {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
let focus: unknown;
if (list instanceof List) {
const focused = list.getFocusedElements();
if (focused.length) {
focus = focused[0];
}
} else if (list instanceof AsyncDataTree) {
const focused = list.getFocus();
if (focused.length) {
focus = focused[0];
}
}
return focus;
}
return undefined;
}
// Commands can get executed from a command palette, from a context menu or from some list using a keybinding
// To cover all these cases we need to properly compute the resource on which the command is being executed
export function getResourceForCommand(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): URI | undefined {
if (URI.isUri(resource)) {
return resource;
}
const focus = getFocus(listService);
if (focus instanceof ExplorerItem) {
return focus.resource;
} else if (focus instanceof OpenEditor) {
return focus.getResource();
}
return EditorResourceAccessor.getOriginalUri(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
}
export function getMultiSelectedResources(resource: URI | object | undefined, listService: IListService, editorService: IEditorService, explorerService: IExplorerService): Array<URI> {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
// Explorer
if (list instanceof AsyncDataTree && list.getFocus().every(item => item instanceof ExplorerItem)) {
// Explorer
const context = explorerService.getContext(true);
if (context.length) {
return context.map(c => c.resource);
}
}
// Open editors view
if (list instanceof List) {
const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor).map((oe: OpenEditor) => oe.getResource()));
const focusedElements = list.getFocusedElements();
const focus = focusedElements.length ? focusedElements[0] : undefined;
let mainUriStr: string | undefined = undefined;
if (URI.isUri(resource)) {
mainUriStr = resource.toString();
} else if (focus instanceof OpenEditor) {
const focusedResource = focus.getResource();
mainUriStr = focusedResource ? focusedResource.toString() : undefined;
}
// We only respect the selection if it contains the main element.
if (selection.some(s => s.toString() === mainUriStr)) {
return selection;
}
}
}
const result = getResourceForCommand(resource, listService, editorService);
return !!result ? [result] : [];
}
export function getOpenEditorsViewMultiSelection(listService: IListService, editorGroupService: IEditorGroupsService): Array<IEditorIdentifier> | undefined {
const list = listService.lastFocusedList;
if (list?.getHTMLElement() === document.activeElement) {
// Open editors view
if (list instanceof List) {
const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor));
const focusedElements = list.getFocusedElements();
const focus = focusedElements.length ? focusedElements[0] : undefined;
let mainEditor: IEditorIdentifier | undefined = undefined;
if (focus instanceof OpenEditor) {
mainEditor = focus;
}
// We only respect the selection if it contains the main element.
if (selection.some(s => s === mainEditor)) {
return selection;
}
}
}
return undefined;
}
| src/vs/workbench/contrib/files/browser/files.ts | 1 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.9962940812110901,
0.06406624615192413,
0.00016421581676695496,
0.0010980875231325626,
0.2407171130180359
]
|
{
"id": 3,
"code_window": [
"\t\t// Explorer\n",
"\t\tif (list instanceof AsyncDataTree && list.getFocus().every(item => item instanceof ExplorerItem)) {\n",
"\t\t\t// Explorer\n",
"\t\t\tconst context = explorerService.getContext(true);\n",
"\t\t\tif (context.length) {\n",
"\t\t\t\treturn context.map(c => c.resource);\n",
"\t\t\t}\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst context = explorerService.getContext(true, true);\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/files.ts",
"type": "replace",
"edit_start_line_idx": 107
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/**
* Represents information about a specific difference between two sequences.
*/
export class DiffChange {
/**
* The position of the first element in the original sequence which
* this change affects.
*/
public originalStart: number;
/**
* The number of elements from the original sequence which were
* affected.
*/
public originalLength: number;
/**
* The position of the first element in the modified sequence which
* this change affects.
*/
public modifiedStart: number;
/**
* The number of elements from the modified sequence which were
* affected (added).
*/
public modifiedLength: number;
/**
* Constructs a new DiffChange with the given sequence information
* and content.
*/
constructor(originalStart: number, originalLength: number, modifiedStart: number, modifiedLength: number) {
//Debug.Assert(originalLength > 0 || modifiedLength > 0, "originalLength and modifiedLength cannot both be <= 0");
this.originalStart = originalStart;
this.originalLength = originalLength;
this.modifiedStart = modifiedStart;
this.modifiedLength = modifiedLength;
}
/**
* The end point (exclusive) of the change in the original sequence.
*/
public getOriginalEnd() {
return this.originalStart + this.originalLength;
}
/**
* The end point (exclusive) of the change in the modified sequence.
*/
public getModifiedEnd() {
return this.modifiedStart + this.modifiedLength;
}
}
| src/vs/base/common/diff/diffChange.ts | 0 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.00017874414334073663,
0.00017332412244286388,
0.00016382372996304184,
0.0001746893540257588,
0.000004655846623791149
]
|
{
"id": 3,
"code_window": [
"\t\t// Explorer\n",
"\t\tif (list instanceof AsyncDataTree && list.getFocus().every(item => item instanceof ExplorerItem)) {\n",
"\t\t\t// Explorer\n",
"\t\t\tconst context = explorerService.getContext(true);\n",
"\t\t\tif (context.length) {\n",
"\t\t\t\treturn context.map(c => c.resource);\n",
"\t\t\t}\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst context = explorerService.getContext(true, true);\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/files.ts",
"type": "replace",
"edit_start_line_idx": 107
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { IMenuService, MenuId, IMenu, SubmenuItemAction, registerAction2, Action2, MenuItemAction, MenuRegistry } from 'vs/platform/actions/common/actions';
import { registerThemingParticipant, IThemeService } from 'vs/platform/theme/common/themeService';
import { MenuBarVisibility, getTitleBarStyle, IWindowOpenable, getMenuBarVisibility } from 'vs/platform/window/common/window';
import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IAction, Action, SubmenuAction, Separator, IActionRunner, ActionRunner, WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification } from 'vs/base/common/actions';
import { addDisposableListener, Dimension, EventType } from 'vs/base/browser/dom';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { isMacintosh, isWeb, isIOS, isNative } from 'vs/base/common/platform';
import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
import { Event, Emitter } from 'vs/base/common/event';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { IRecentlyOpened, isRecentFolder, IRecent, isRecentWorkspace, IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
import { RunOnceScheduler } from 'vs/base/common/async';
import { MENUBAR_SELECTION_FOREGROUND, MENUBAR_SELECTION_BACKGROUND, MENUBAR_SELECTION_BORDER, TITLE_BAR_ACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_FOREGROUND, ACTIVITY_BAR_FOREGROUND, ACTIVITY_BAR_INACTIVE_FOREGROUND } from 'vs/workbench/common/theme';
import { URI } from 'vs/base/common/uri';
import { ILabelService } from 'vs/platform/label/common/label';
import { IUpdateService, StateType } from 'vs/platform/update/common/update';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { MenuBar, IMenuBarOptions } from 'vs/base/browser/ui/menu/menubar';
import { Direction } from 'vs/base/browser/ui/menu/menu';
import { attachMenuStyler } from 'vs/platform/theme/common/styler';
import { mnemonicMenuLabel, unmnemonicLabel } from 'vs/base/common/labels';
import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { isFullscreen } from 'vs/base/browser/browser';
import { IHostService } from 'vs/workbench/services/host/browser/host';
import { BrowserFeatures } from 'vs/base/browser/canIUse';
import { KeyCode } from 'vs/base/common/keyCodes';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { IsMacNativeContext, IsWebContext } from 'vs/platform/contextkey/common/contextkeys';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { OpenRecentAction } from 'vs/workbench/browser/actions/windowActions';
export type IOpenRecentAction = IAction & { uri: URI; remoteAuthority?: string };
MenuRegistry.appendMenuItem(MenuId.MenubarMainMenu, {
submenu: MenuId.MenubarFileMenu,
title: {
value: 'File',
original: 'File',
mnemonicTitle: localize({ key: 'mFile', comment: ['&& denotes a mnemonic'] }, "&&File"),
},
order: 1
});
MenuRegistry.appendMenuItem(MenuId.MenubarMainMenu, {
submenu: MenuId.MenubarEditMenu,
title: {
value: 'Edit',
original: 'Edit',
mnemonicTitle: localize({ key: 'mEdit', comment: ['&& denotes a mnemonic'] }, "&&Edit")
},
order: 2
});
MenuRegistry.appendMenuItem(MenuId.MenubarMainMenu, {
submenu: MenuId.MenubarSelectionMenu,
title: {
value: 'Selection',
original: 'Selection',
mnemonicTitle: localize({ key: 'mSelection', comment: ['&& denotes a mnemonic'] }, "&&Selection")
},
order: 3
});
MenuRegistry.appendMenuItem(MenuId.MenubarMainMenu, {
submenu: MenuId.MenubarViewMenu,
title: {
value: 'View',
original: 'View',
mnemonicTitle: localize({ key: 'mView', comment: ['&& denotes a mnemonic'] }, "&&View")
},
order: 4
});
MenuRegistry.appendMenuItem(MenuId.MenubarMainMenu, {
submenu: MenuId.MenubarGoMenu,
title: {
value: 'Go',
original: 'Go',
mnemonicTitle: localize({ key: 'mGoto', comment: ['&& denotes a mnemonic'] }, "&&Go")
},
order: 5
});
MenuRegistry.appendMenuItem(MenuId.MenubarMainMenu, {
submenu: MenuId.MenubarTerminalMenu,
title: {
value: 'Terminal',
original: 'Terminal',
mnemonicTitle: localize({ key: 'mTerminal', comment: ['&& denotes a mnemonic'] }, "&&Terminal")
},
order: 7,
when: ContextKeyExpr.has('terminalProcessSupported')
});
MenuRegistry.appendMenuItem(MenuId.MenubarMainMenu, {
submenu: MenuId.MenubarHelpMenu,
title: {
value: 'Help',
original: 'Help',
mnemonicTitle: localize({ key: 'mHelp', comment: ['&& denotes a mnemonic'] }, "&&Help")
},
order: 8
});
MenuRegistry.appendMenuItem(MenuId.MenubarMainMenu, {
submenu: MenuId.MenubarPreferencesMenu,
title: {
value: 'Preferences',
original: 'Preferences',
mnemonicTitle: localize('mPreferences', "Preferences")
},
when: IsMacNativeContext,
order: 9
});
export abstract class MenubarControl extends Disposable {
protected keys = [
'window.menuBarVisibility',
'window.enableMenuBarMnemonics',
'window.customMenuBarAltFocus',
'workbench.sideBar.location',
'window.nativeTabs'
];
protected mainMenu: IMenu;
protected menus: {
[index: string]: IMenu | undefined;
} = {};
protected topLevelTitles: { [menu: string]: string } = {};
protected mainMenuDisposables: DisposableStore;
protected recentlyOpened: IRecentlyOpened = { files: [], workspaces: [] };
protected menuUpdater: RunOnceScheduler;
protected static readonly MAX_MENU_RECENT_ENTRIES = 10;
constructor(
protected readonly menuService: IMenuService,
protected readonly workspacesService: IWorkspacesService,
protected readonly contextKeyService: IContextKeyService,
protected readonly keybindingService: IKeybindingService,
protected readonly configurationService: IConfigurationService,
protected readonly labelService: ILabelService,
protected readonly updateService: IUpdateService,
protected readonly storageService: IStorageService,
protected readonly notificationService: INotificationService,
protected readonly preferencesService: IPreferencesService,
protected readonly environmentService: IWorkbenchEnvironmentService,
protected readonly accessibilityService: IAccessibilityService,
protected readonly hostService: IHostService,
protected readonly commandService: ICommandService
) {
super();
this.mainMenu = this._register(this.menuService.createMenu(MenuId.MenubarMainMenu, this.contextKeyService));
this.mainMenuDisposables = this._register(new DisposableStore());
this.setupMainMenu();
this.menuUpdater = this._register(new RunOnceScheduler(() => this.doUpdateMenubar(false), 200));
this.notifyUserOfCustomMenubarAccessibility();
}
protected abstract doUpdateMenubar(firstTime: boolean): void;
protected registerListeners(): void {
// Listen for window focus changes
this._register(this.hostService.onDidChangeFocus(e => this.onDidChangeWindowFocus(e)));
// Update when config changes
this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(e)));
// Listen to update service
this.updateService.onStateChange(() => this.onUpdateStateChange());
// Listen for changes in recently opened menu
this._register(this.workspacesService.onDidChangeRecentlyOpened(() => { this.onDidChangeRecentlyOpened(); }));
// Listen to keybindings change
this._register(this.keybindingService.onDidUpdateKeybindings(() => this.updateMenubar()));
// Update recent menu items on formatter registration
this._register(this.labelService.onDidChangeFormatters(() => { this.onDidChangeRecentlyOpened(); }));
// Listen for changes on the main menu
this._register(this.mainMenu.onDidChange(() => { this.setupMainMenu(); this.doUpdateMenubar(true); }));
}
protected setupMainMenu(): void {
this.mainMenuDisposables.clear();
this.menus = {};
this.topLevelTitles = {};
const [, mainMenuActions] = this.mainMenu.getActions()[0];
for (const mainMenuAction of mainMenuActions) {
if (mainMenuAction instanceof SubmenuItemAction && typeof mainMenuAction.item.title !== 'string') {
this.menus[mainMenuAction.item.title.original] = this.mainMenuDisposables.add(this.menuService.createMenu(mainMenuAction.item.submenu, this.contextKeyService));
this.topLevelTitles[mainMenuAction.item.title.original] = mainMenuAction.item.title.mnemonicTitle ?? mainMenuAction.item.title.value;
}
}
}
protected updateMenubar(): void {
this.menuUpdater.schedule();
}
protected calculateActionLabel(action: { id: string; label: string }): string {
const label = action.label;
switch (action.id) {
default:
break;
}
return label;
}
protected onUpdateStateChange(): void {
this.updateMenubar();
}
protected onUpdateKeybindings(): void {
this.updateMenubar();
}
protected getOpenRecentActions(): (Separator | IOpenRecentAction)[] {
if (!this.recentlyOpened) {
return [];
}
const { workspaces, files } = this.recentlyOpened;
const result = [];
if (workspaces.length > 0) {
for (let i = 0; i < MenubarControl.MAX_MENU_RECENT_ENTRIES && i < workspaces.length; i++) {
result.push(this.createOpenRecentMenuAction(workspaces[i]));
}
result.push(new Separator());
}
if (files.length > 0) {
for (let i = 0; i < MenubarControl.MAX_MENU_RECENT_ENTRIES && i < files.length; i++) {
result.push(this.createOpenRecentMenuAction(files[i]));
}
result.push(new Separator());
}
return result;
}
protected onDidChangeWindowFocus(hasFocus: boolean): void {
// When we regain focus, update the recent menu items
if (hasFocus) {
this.onDidChangeRecentlyOpened();
}
}
private onConfigurationUpdated(event: IConfigurationChangeEvent): void {
if (this.keys.some(key => event.affectsConfiguration(key))) {
this.updateMenubar();
}
if (event.affectsConfiguration('editor.accessibilitySupport')) {
this.notifyUserOfCustomMenubarAccessibility();
}
// Since we try not update when hidden, we should
// try to update the recently opened list on visibility changes
if (event.affectsConfiguration('window.menuBarVisibility')) {
this.onDidChangeRecentlyOpened();
}
}
private get menubarHidden(): boolean {
return isMacintosh && isNative ? false : getMenuBarVisibility(this.configurationService) === 'hidden';
}
protected onDidChangeRecentlyOpened(): void {
// Do not update recently opened when the menubar is hidden #108712
if (!this.menubarHidden) {
this.workspacesService.getRecentlyOpened().then(recentlyOpened => {
this.recentlyOpened = recentlyOpened;
this.updateMenubar();
});
}
}
private createOpenRecentMenuAction(recent: IRecent): IOpenRecentAction {
let label: string;
let uri: URI;
let commandId: string;
let openable: IWindowOpenable;
const remoteAuthority = recent.remoteAuthority;
if (isRecentFolder(recent)) {
uri = recent.folderUri;
label = recent.label || this.labelService.getWorkspaceLabel(uri, { verbose: true });
commandId = 'openRecentFolder';
openable = { folderUri: uri };
} else if (isRecentWorkspace(recent)) {
uri = recent.workspace.configPath;
label = recent.label || this.labelService.getWorkspaceLabel(recent.workspace, { verbose: true });
commandId = 'openRecentWorkspace';
openable = { workspaceUri: uri };
} else {
uri = recent.fileUri;
label = recent.label || this.labelService.getUriLabel(uri);
commandId = 'openRecentFile';
openable = { fileUri: uri };
}
const ret: IAction = new Action(commandId, unmnemonicLabel(label), undefined, undefined, event => {
const browserEvent = event as KeyboardEvent;
const openInNewWindow = event && ((!isMacintosh && (browserEvent.ctrlKey || browserEvent.shiftKey)) || (isMacintosh && (browserEvent.metaKey || browserEvent.altKey)));
return this.hostService.openWindow([openable], {
forceNewWindow: !!openInNewWindow,
remoteAuthority: remoteAuthority || null // local window if remoteAuthority is not set or can not be deducted from the openable
});
});
return Object.assign(ret, { uri, remoteAuthority });
}
private notifyUserOfCustomMenubarAccessibility(): void {
if (isWeb || isMacintosh) {
return;
}
const hasBeenNotified = this.storageService.getBoolean('menubar/accessibleMenubarNotified', StorageScope.APPLICATION, false);
const usingCustomMenubar = getTitleBarStyle(this.configurationService) === 'custom';
if (hasBeenNotified || usingCustomMenubar || !this.accessibilityService.isScreenReaderOptimized()) {
return;
}
const message = localize('menubar.customTitlebarAccessibilityNotification', "Accessibility support is enabled for you. For the most accessible experience, we recommend the custom title bar style.");
this.notificationService.prompt(Severity.Info, message, [
{
label: localize('goToSetting', "Open Settings"),
run: () => {
return this.preferencesService.openUserSettings({ query: 'window.titleBarStyle' });
}
}
]);
this.storageService.store('menubar/accessibleMenubarNotified', true, StorageScope.APPLICATION, StorageTarget.USER);
}
}
export class CustomMenubarControl extends MenubarControl {
private menubar: MenuBar | undefined;
private container: HTMLElement | undefined;
private alwaysOnMnemonics: boolean = false;
private focusInsideMenubar: boolean = false;
private visible: boolean = true;
private actionRunner: IActionRunner;
private readonly webNavigationMenu = this._register(this.menuService.createMenu(MenuId.MenubarHomeMenu, this.contextKeyService));
private readonly _onVisibilityChange: Emitter<boolean>;
private readonly _onFocusStateChange: Emitter<boolean>;
constructor(
@IMenuService menuService: IMenuService,
@IWorkspacesService workspacesService: IWorkspacesService,
@IContextKeyService contextKeyService: IContextKeyService,
@IKeybindingService keybindingService: IKeybindingService,
@IConfigurationService configurationService: IConfigurationService,
@ILabelService labelService: ILabelService,
@IUpdateService updateService: IUpdateService,
@IStorageService storageService: IStorageService,
@INotificationService notificationService: INotificationService,
@IPreferencesService preferencesService: IPreferencesService,
@IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService,
@IAccessibilityService accessibilityService: IAccessibilityService,
@IThemeService private readonly themeService: IThemeService,
@IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IHostService hostService: IHostService,
@ICommandService commandService: ICommandService
) {
super(menuService, workspacesService, contextKeyService, keybindingService, configurationService, labelService, updateService, storageService, notificationService, preferencesService, environmentService, accessibilityService, hostService, commandService);
this._onVisibilityChange = this._register(new Emitter<boolean>());
this._onFocusStateChange = this._register(new Emitter<boolean>());
this.actionRunner = this._register(new ActionRunner());
this.actionRunner.onDidRun(e => {
this.telemetryService.publicLog2<WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification>('workbenchActionExecuted', { id: e.action.id, from: 'menu' });
});
this.workspacesService.getRecentlyOpened().then((recentlyOpened) => {
this.recentlyOpened = recentlyOpened;
});
this.registerListeners();
this.registerActions();
registerThemingParticipant((theme, collector) => {
const menubarActiveWindowFgColor = theme.getColor(TITLE_BAR_ACTIVE_FOREGROUND);
if (menubarActiveWindowFgColor) {
collector.addRule(`
.monaco-workbench .menubar > .menubar-menu-button,
.monaco-workbench .menubar .toolbar-toggle-more {
color: ${menubarActiveWindowFgColor};
}
`);
}
const activityBarInactiveFgColor = theme.getColor(ACTIVITY_BAR_INACTIVE_FOREGROUND);
if (activityBarInactiveFgColor) {
collector.addRule(`
.monaco-workbench .activitybar .menubar.compact > .menubar-menu-button,
.monaco-workbench .activitybar .menubar.compact .toolbar-toggle-more {
color: ${activityBarInactiveFgColor};
}
`);
}
const activityBarFgColor = theme.getColor(ACTIVITY_BAR_FOREGROUND);
if (activityBarFgColor) {
collector.addRule(`
.monaco-workbench .activitybar .menubar.compact > .menubar-menu-button.open,
.monaco-workbench .activitybar .menubar.compact > .menubar-menu-button:focus,
.monaco-workbench .activitybar .menubar.compact:not(:focus-within) > .menubar-menu-button:hover,
.monaco-workbench .activitybar .menubar.compact > .menubar-menu-button.open .toolbar-toggle-more,
.monaco-workbench .activitybar .menubar.compact > .menubar-menu-button:focus .toolbar-toggle-more,
.monaco-workbench .activitybar .menubar.compact:not(:focus-within) > .menubar-menu-button:hover .toolbar-toggle-more {
color: ${activityBarFgColor};
}
`);
}
const menubarInactiveWindowFgColor = theme.getColor(TITLE_BAR_INACTIVE_FOREGROUND);
if (menubarInactiveWindowFgColor) {
collector.addRule(`
.monaco-workbench .menubar.inactive:not(.compact) > .menubar-menu-button,
.monaco-workbench .menubar.inactive:not(.compact) > .menubar-menu-button .toolbar-toggle-more {
color: ${menubarInactiveWindowFgColor};
}
`);
}
const menubarSelectedFgColor = theme.getColor(MENUBAR_SELECTION_FOREGROUND);
if (menubarSelectedFgColor) {
collector.addRule(`
.monaco-workbench .menubar:not(.compact) > .menubar-menu-button.open,
.monaco-workbench .menubar:not(.compact) > .menubar-menu-button:focus,
.monaco-workbench .menubar:not(:focus-within):not(.compact) > .menubar-menu-button:hover,
.monaco-workbench .menubar:not(.compact) > .menubar-menu-button.open .toolbar-toggle-more,
.monaco-workbench .menubar:not(.compact) > .menubar-menu-button:focus .toolbar-toggle-more,
.monaco-workbench .menubar:not(:focus-within):not(.compact) > .menubar-menu-button:hover .toolbar-toggle-more {
color: ${menubarSelectedFgColor};
}
`);
}
const menubarSelectedBgColor = theme.getColor(MENUBAR_SELECTION_BACKGROUND);
if (menubarSelectedBgColor) {
collector.addRule(`
.monaco-workbench .menubar:not(.compact) > .menubar-menu-button.open .menubar-menu-title,
.monaco-workbench .menubar:not(.compact) > .menubar-menu-button:focus .menubar-menu-title,
.monaco-workbench .menubar:not(:focus-within):not(.compact) > .menubar-menu-button:hover .menubar-menu-title {
background-color: ${menubarSelectedBgColor};
}
`);
}
const menubarSelectedBorderColor = theme.getColor(MENUBAR_SELECTION_BORDER);
if (menubarSelectedBorderColor) {
collector.addRule(`
.monaco-workbench .menubar > .menubar-menu-button:hover .menubar-menu-title {
outline: dashed 1px;
}
.monaco-workbench .menubar > .menubar-menu-button.open .menubar-menu-title,
.monaco-workbench .menubar > .menubar-menu-button:focus .menubar-menu-title {
outline: solid 1px;
}
.monaco-workbench .menubar > .menubar-menu-button.open .menubar-menu-title,
.monaco-workbench .menubar > .menubar-menu-button:focus .menubar-menu-title,
.monaco-workbench .menubar > .menubar-menu-button:hover .menubar-menu-title {
outline-color: ${menubarSelectedBorderColor};
outline-offset: -1px;
}
`);
}
});
}
protected doUpdateMenubar(firstTime: boolean): void {
this.setupCustomMenubar(firstTime);
}
private registerActions(): void {
const that = this;
if (isWeb) {
this._register(registerAction2(class extends Action2 {
constructor() {
super({
id: `workbench.actions.menubar.focus`,
title: { value: localize('focusMenu', "Focus Application Menu"), original: 'Focus Application Menu' },
keybinding: {
primary: KeyCode.F10,
weight: KeybindingWeight.WorkbenchContrib,
when: IsWebContext
},
f1: true
});
}
async run(): Promise<void> {
that.menubar?.toggleFocus();
}
}));
}
}
private getUpdateAction(): IAction | null {
const state = this.updateService.state;
switch (state.type) {
case StateType.Uninitialized:
return null;
case StateType.Idle:
return new Action('update.check', localize({ key: 'checkForUpdates', comment: ['&& denotes a mnemonic'] }, "Check for &&Updates..."), undefined, true, () =>
this.updateService.checkForUpdates(true));
case StateType.CheckingForUpdates:
return new Action('update.checking', localize('checkingForUpdates', "Checking for Updates..."), undefined, false);
case StateType.AvailableForDownload:
return new Action('update.downloadNow', localize({ key: 'download now', comment: ['&& denotes a mnemonic'] }, "D&&ownload Update"), undefined, true, () =>
this.updateService.downloadUpdate());
case StateType.Downloading:
return new Action('update.downloading', localize('DownloadingUpdate', "Downloading Update..."), undefined, false);
case StateType.Downloaded:
return new Action('update.install', localize({ key: 'installUpdate...', comment: ['&& denotes a mnemonic'] }, "Install &&Update..."), undefined, true, () =>
this.updateService.applyUpdate());
case StateType.Updating:
return new Action('update.updating', localize('installingUpdate', "Installing Update..."), undefined, false);
case StateType.Ready:
return new Action('update.restart', localize({ key: 'restartToUpdate', comment: ['&& denotes a mnemonic'] }, "Restart to &&Update"), undefined, true, () =>
this.updateService.quitAndInstall());
}
}
private get currentMenubarVisibility(): MenuBarVisibility {
return getMenuBarVisibility(this.configurationService);
}
private get currentDisableMenuBarAltFocus(): boolean {
const settingValue = this.configurationService.getValue<boolean>('window.customMenuBarAltFocus');
let disableMenuBarAltBehavior = false;
if (typeof settingValue === 'boolean') {
disableMenuBarAltBehavior = !settingValue;
}
return disableMenuBarAltBehavior;
}
private insertActionsBefore(nextAction: IAction, target: IAction[]): void {
switch (nextAction.id) {
case OpenRecentAction.ID:
target.push(...this.getOpenRecentActions());
break;
case 'workbench.action.showAboutDialog':
if (!isMacintosh && !isWeb) {
const updateAction = this.getUpdateAction();
if (updateAction) {
updateAction.label = mnemonicMenuLabel(updateAction.label);
target.push(updateAction);
target.push(new Separator());
}
}
break;
default:
break;
}
}
private get currentEnableMenuBarMnemonics(): boolean {
let enableMenuBarMnemonics = this.configurationService.getValue<boolean>('window.enableMenuBarMnemonics');
if (typeof enableMenuBarMnemonics !== 'boolean') {
enableMenuBarMnemonics = true;
}
return enableMenuBarMnemonics && (!isWeb || isFullscreen());
}
private get currentCompactMenuMode(): Direction | undefined {
if (this.currentMenubarVisibility !== 'compact') {
return undefined;
}
// Menu bar lives in activity bar and should flow based on its location
const currentSidebarLocation = this.configurationService.getValue<string>('workbench.sideBar.location');
return currentSidebarLocation === 'right' ? Direction.Left : Direction.Right;
}
private onDidVisibilityChange(visible: boolean): void {
this.visible = visible;
this.onDidChangeRecentlyOpened();
this._onVisibilityChange.fire(visible);
}
private reinstallDisposables = this._register(new DisposableStore());
private setupCustomMenubar(firstTime: boolean): void {
// If there is no container, we cannot setup the menubar
if (!this.container) {
return;
}
if (firstTime) {
// Reset and create new menubar
if (this.menubar) {
this.reinstallDisposables.clear();
}
this.menubar = this.reinstallDisposables.add(new MenuBar(this.container, this.getMenuBarOptions()));
this.accessibilityService.alwaysUnderlineAccessKeys().then(val => {
this.alwaysOnMnemonics = val;
this.menubar?.update(this.getMenuBarOptions());
});
this.reinstallDisposables.add(this.menubar.onFocusStateChange(focused => {
this._onFocusStateChange.fire(focused);
// When the menubar loses focus, update it to clear any pending updates
if (!focused) {
this.updateMenubar();
this.focusInsideMenubar = false;
}
}));
this.reinstallDisposables.add(this.menubar.onVisibilityChange(e => this.onDidVisibilityChange(e)));
// Before we focus the menubar, stop updates to it so that focus-related context keys will work
this.reinstallDisposables.add(addDisposableListener(this.container, EventType.FOCUS_IN, () => {
this.focusInsideMenubar = true;
}));
this.reinstallDisposables.add(addDisposableListener(this.container, EventType.FOCUS_OUT, () => {
this.focusInsideMenubar = false;
}));
this.reinstallDisposables.add(attachMenuStyler(this.menubar, this.themeService));
// Fire visibility change for the first install if menu is shown
if (this.menubar.isVisible) {
this.onDidVisibilityChange(true);
}
} else {
this.menubar?.update(this.getMenuBarOptions());
}
// Update the menu actions
const updateActions = (menu: IMenu, target: IAction[], topLevelTitle: string) => {
target.splice(0);
const groups = menu.getActions();
for (const group of groups) {
const [, actions] = group;
for (const action of actions) {
this.insertActionsBefore(action, target);
// use mnemonicTitle whenever possible
const title = typeof action.item.title === 'string'
? action.item.title
: action.item.title.mnemonicTitle ?? action.item.title.value;
if (action instanceof SubmenuItemAction) {
let submenu = this.menus[action.item.submenu.id];
if (!submenu) {
submenu = this._register(this.menus[action.item.submenu.id] = this.menuService.createMenu(action.item.submenu, this.contextKeyService));
this._register(submenu.onDidChange(() => {
if (!this.focusInsideMenubar) {
const actions: IAction[] = [];
updateActions(menu, actions, topLevelTitle);
if (this.menubar && this.topLevelTitles[topLevelTitle]) {
this.menubar.updateMenu({ actions: actions, label: mnemonicMenuLabel(this.topLevelTitles[topLevelTitle]) });
}
}
}, this));
}
const submenuActions: SubmenuAction[] = [];
updateActions(submenu, submenuActions, topLevelTitle);
if (submenuActions.length > 0) {
target.push(new SubmenuAction(action.id, mnemonicMenuLabel(title), submenuActions));
}
} else {
const newAction = new Action(action.id, mnemonicMenuLabel(title), action.class, action.enabled, () => this.commandService.executeCommand(action.id));
newAction.tooltip = action.tooltip;
newAction.checked = action.checked;
target.push(newAction);
}
}
target.push(new Separator());
}
// Append web navigation menu items to the file menu when not compact
if (menu === this.menus.File && this.currentCompactMenuMode === undefined) {
const webActions = this.getWebNavigationActions();
if (webActions.length) {
target.push(...webActions);
target.push(new Separator()); // to account for pop below
}
}
target.pop();
};
for (const title of Object.keys(this.topLevelTitles)) {
const menu = this.menus[title];
if (firstTime && menu) {
this.reinstallDisposables.add(menu.onDidChange(() => {
if (!this.focusInsideMenubar) {
const actions: IAction[] = [];
updateActions(menu, actions, title);
this.menubar?.updateMenu({ actions: actions, label: mnemonicMenuLabel(this.topLevelTitles[title]) });
}
}));
// For the file menu, we need to update if the web nav menu updates as well
if (menu === this.menus.File) {
this.reinstallDisposables.add(this.webNavigationMenu.onDidChange(() => {
if (!this.focusInsideMenubar) {
const actions: IAction[] = [];
updateActions(menu, actions, title);
this.menubar?.updateMenu({ actions: actions, label: mnemonicMenuLabel(this.topLevelTitles[title]) });
}
}));
}
}
const actions: IAction[] = [];
if (menu) {
updateActions(menu, actions, title);
}
if (this.menubar) {
if (!firstTime) {
this.menubar.updateMenu({ actions: actions, label: mnemonicMenuLabel(this.topLevelTitles[title]) });
} else {
this.menubar.push({ actions: actions, label: mnemonicMenuLabel(this.topLevelTitles[title]) });
}
}
}
}
private getWebNavigationActions(): IAction[] {
if (!isWeb) {
return []; // only for web
}
const webNavigationActions = [];
for (const groups of this.webNavigationMenu.getActions()) {
const [, actions] = groups;
for (const action of actions) {
if (action instanceof MenuItemAction) {
const title = typeof action.item.title === 'string'
? action.item.title
: action.item.title.mnemonicTitle ?? action.item.title.value;
webNavigationActions.push(new Action(action.id, mnemonicMenuLabel(title), action.class, action.enabled, async (event?: any) => {
this.commandService.executeCommand(action.id, event);
}));
}
}
webNavigationActions.push(new Separator());
}
if (webNavigationActions.length) {
webNavigationActions.pop();
}
return webNavigationActions;
}
private getMenuBarOptions(): IMenuBarOptions {
return {
enableMnemonics: this.currentEnableMenuBarMnemonics,
disableAltFocus: this.currentDisableMenuBarAltFocus,
visibility: this.currentMenubarVisibility,
actionRunner: this.actionRunner,
getKeybinding: (action) => this.keybindingService.lookupKeybinding(action.id),
alwaysOnMnemonics: this.alwaysOnMnemonics,
compactMode: this.currentCompactMenuMode,
getCompactMenuActions: () => {
if (!isWeb) {
return []; // only for web
}
return this.getWebNavigationActions();
}
};
}
protected override onDidChangeWindowFocus(hasFocus: boolean): void {
if (!this.visible) {
return;
}
super.onDidChangeWindowFocus(hasFocus);
if (this.container) {
if (hasFocus) {
this.container.classList.remove('inactive');
} else {
this.container.classList.add('inactive');
this.menubar?.blur();
}
}
}
protected override onUpdateStateChange(): void {
if (!this.visible) {
return;
}
super.onUpdateStateChange();
}
protected override onDidChangeRecentlyOpened(): void {
if (!this.visible) {
return;
}
super.onDidChangeRecentlyOpened();
}
protected override onUpdateKeybindings(): void {
if (!this.visible) {
return;
}
super.onUpdateKeybindings();
}
protected override registerListeners(): void {
super.registerListeners();
this._register(addDisposableListener(window, EventType.RESIZE, () => {
if (this.menubar && !(isIOS && BrowserFeatures.pointerEvents)) {
this.menubar.blur();
}
}));
// Mnemonics require fullscreen in web
if (isWeb) {
this._register(this.layoutService.onDidChangeFullscreen(e => this.updateMenubar()));
this._register(this.webNavigationMenu.onDidChange(() => this.updateMenubar()));
}
}
get onVisibilityChange(): Event<boolean> {
return this._onVisibilityChange.event;
}
get onFocusStateChange(): Event<boolean> {
return this._onFocusStateChange.event;
}
getMenubarItemsDimensions(): Dimension {
if (this.menubar) {
return new Dimension(this.menubar.getWidth(), this.menubar.getHeight());
}
return new Dimension(0, 0);
}
create(parent: HTMLElement): HTMLElement {
this.container = parent;
// Build the menubar
if (this.container) {
this.doUpdateMenubar(true);
}
return this.container;
}
layout(dimension: Dimension) {
this.menubar?.update(this.getMenuBarOptions());
}
toggleFocus() {
this.menubar?.toggleFocus();
}
}
| src/vs/workbench/browser/parts/titlebar/menubarControl.ts | 0 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.0001900623319670558,
0.00017477800429333001,
0.00016362486348953098,
0.00017502698756288737,
0.0000036674045986728743
]
|
{
"id": 3,
"code_window": [
"\t\t// Explorer\n",
"\t\tif (list instanceof AsyncDataTree && list.getFocus().every(item => item instanceof ExplorerItem)) {\n",
"\t\t\t// Explorer\n",
"\t\t\tconst context = explorerService.getContext(true);\n",
"\t\t\tif (context.length) {\n",
"\t\t\t\treturn context.map(c => c.resource);\n",
"\t\t\t}\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\tconst context = explorerService.getContext(true, true);\n"
],
"file_path": "src/vs/workbench/contrib/files/browser/files.ts",
"type": "replace",
"edit_start_line_idx": 107
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IDisposable } from 'vs/base/common/lifecycle';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IMenuService, MenuId, IMenu } from 'vs/platform/actions/common/actions';
import { IAction } from 'vs/base/common/actions';
import { Comment } from 'vs/editor/common/languages';
import { createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
export class CommentMenus implements IDisposable {
constructor(
@IMenuService private readonly menuService: IMenuService
) { }
getCommentThreadTitleActions(contextKeyService: IContextKeyService): IMenu {
return this.getMenu(MenuId.CommentThreadTitle, contextKeyService);
}
getCommentThreadActions(contextKeyService: IContextKeyService): IMenu {
return this.getMenu(MenuId.CommentThreadActions, contextKeyService);
}
getCommentTitleActions(comment: Comment, contextKeyService: IContextKeyService): IMenu {
return this.getMenu(MenuId.CommentTitle, contextKeyService);
}
getCommentActions(comment: Comment, contextKeyService: IContextKeyService): IMenu {
return this.getMenu(MenuId.CommentActions, contextKeyService);
}
getCommentThreadTitleContextActions(contextKeyService: IContextKeyService): IMenu {
return this.getMenu(MenuId.CommentThreadTitleContext, contextKeyService);
}
getCommentThreadCommentContextActions(contextKeyService: IContextKeyService): IMenu {
return this.getMenu(MenuId.CommentThreadCommentContext, contextKeyService);
}
private getMenu(menuId: MenuId, contextKeyService: IContextKeyService): IMenu {
const menu = this.menuService.createMenu(menuId, contextKeyService);
const primary: IAction[] = [];
const secondary: IAction[] = [];
const result = { primary, secondary };
createAndFillInContextMenuActions(menu, { shouldForwardArgs: true }, result, 'inline');
return menu;
}
dispose(): void {
}
}
| src/vs/workbench/contrib/comments/browser/commentMenus.ts | 0 | https://github.com/microsoft/vscode/commit/0ccec43747162cfcebf727fc255a2296f0801fbb | [
0.0001776299177436158,
0.00017394375754520297,
0.00017053306510206312,
0.00017290847608819604,
0.0000026600675937515916
]
|
{
"id": 0,
"code_window": [
"import { HttpStatus } from '../enums/http-status.enum';\n",
"import { HttpException } from './http.exception';\n",
"\n",
"/**\n",
" * Defines an HTTP exception for *Forbidden* type errors.\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { HttpException, HttpExceptionOptions } from './http.exception';\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 1
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Forbidden* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class ForbiddenException extends HttpException {
/**
* Instantiate a `ForbiddenException` Exception.
*
* @example
* `throw new ForbiddenException()`
*
* @usageNotes
* The HTTP response status code will be 403.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 403.
* - `message`: the string `'Forbidden'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Forbidden',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.FORBIDDEN,
),
HttpStatus.FORBIDDEN,
);
}
}
| packages/common/exceptions/forbidden.exception.ts | 1 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.0007771264063194394,
0.00031264283461496234,
0.00016990350559353828,
0.00017653241229709238,
0.00023507236619479954
]
|
{
"id": 0,
"code_window": [
"import { HttpStatus } from '../enums/http-status.enum';\n",
"import { HttpException } from './http.exception';\n",
"\n",
"/**\n",
" * Defines an HTTP exception for *Forbidden* type errors.\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { HttpException, HttpExceptionOptions } from './http.exception';\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 1
} | import { CONNECT_EVENT, MESSAGE_EVENT } from '../../constants';
import { JsonSocket } from '../../helpers/json-socket';
import * as helpers from './helpers';
import { expect } from 'chai';
describe('JsonSocket chaining', () => {
it('should return the instance when subscribing to event', done => {
helpers.createServerAndClient((err, server, clientSocket, serverSocket) => {
if (err) {
return done(err);
}
expect(clientSocket.on(MESSAGE_EVENT, () => {})).to.be.instanceof(
JsonSocket,
);
expect(clientSocket.on(CONNECT_EVENT, () => {})).to.deep.equal(
clientSocket,
);
expect(
clientSocket.on(MESSAGE_EVENT, () => {}).on('end', () => {}),
).to.deep.equal(clientSocket);
clientSocket.end();
server.close(done);
});
});
});
| packages/microservices/test/json-socket/listener-chaining.spec.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.00016850953397806734,
0.00016817908908706158,
0.00016783892351668328,
0.00016818880976643413,
2.738618434250384e-7
]
|
{
"id": 0,
"code_window": [
"import { HttpStatus } from '../enums/http-status.enum';\n",
"import { HttpException } from './http.exception';\n",
"\n",
"/**\n",
" * Defines an HTTP exception for *Forbidden* type errors.\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { HttpException, HttpExceptionOptions } from './http.exception';\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 1
} | {
"extends": "./tsconfig.json",
"exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
}
| sample/29-file-upload/tsconfig.build.json | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.00016701851563993841,
0.00016701851563993841,
0.00016701851563993841,
0.00016701851563993841,
0
]
|
{
"id": 0,
"code_window": [
"import { HttpStatus } from '../enums/http-status.enum';\n",
"import { HttpException } from './http.exception';\n",
"\n",
"/**\n",
" * Defines an HTTP exception for *Forbidden* type errors.\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { HttpException, HttpExceptionOptions } from './http.exception';\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 1
} | import { Injectable, forwardRef, Inject } from '@nestjs/common';
import { InputService } from './input.service';
@Injectable()
export class CircularService {
constructor(
@Inject(forwardRef(() => InputService))
public readonly service: InputService,
) {}
}
| integration/injector/src/circular-modules/circular.service.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.00016971227887552232,
0.00016933944425545633,
0.00016896662418730557,
0.00016933944425545633,
3.7282734410837293e-7
]
|
{
"id": 1,
"code_window": [
" *\n",
" * @usageNotes\n",
" * The HTTP response status code will be 403.\n",
" * - The `objectOrError` argument defines the JSON response body or the message string.\n",
" * - The `description` argument contains a short description of the HTTP error.\n",
" *\n",
" * By default, the JSON response body contains two properties:\n",
" * - `statusCode`: this will be the value 403.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause.\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 20
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Forbidden* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class ForbiddenException extends HttpException {
/**
* Instantiate a `ForbiddenException` Exception.
*
* @example
* `throw new ForbiddenException()`
*
* @usageNotes
* The HTTP response status code will be 403.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 403.
* - `message`: the string `'Forbidden'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Forbidden',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.FORBIDDEN,
),
HttpStatus.FORBIDDEN,
);
}
}
| packages/common/exceptions/forbidden.exception.ts | 1 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.001850056811235845,
0.0007620965479873121,
0.00017145558376796544,
0.0006595992017537355,
0.0006169368280097842
]
|
{
"id": 1,
"code_window": [
" *\n",
" * @usageNotes\n",
" * The HTTP response status code will be 403.\n",
" * - The `objectOrError` argument defines the JSON response body or the message string.\n",
" * - The `description` argument contains a short description of the HTTP error.\n",
" *\n",
" * By default, the JSON response body contains two properties:\n",
" * - `statusCode`: this will be the value 403.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause.\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 20
} | import { Controller, Get, VERSION_NEUTRAL } from '@nestjs/common';
@Controller({
version: VERSION_NEUTRAL,
})
export class VersionNeutralController {
@Get('/neutral')
neutral() {
return 'Neutral';
}
}
| integration/versioning/src/neutral.controller.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.0001701406727079302,
0.00016951192810665816,
0.00016888318350538611,
0.00016951192810665816,
6.287446012720466e-7
]
|
{
"id": 1,
"code_window": [
" *\n",
" * @usageNotes\n",
" * The HTTP response status code will be 403.\n",
" * - The `objectOrError` argument defines the JSON response body or the message string.\n",
" * - The `description` argument contains a short description of the HTTP error.\n",
" *\n",
" * By default, the JSON response body contains two properties:\n",
" * - `statusCode`: this will be the value 403.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause.\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 20
} | import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
declare const module: any;
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
console.log(`Application is running on: ${await app.getUrl()}`);
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => app.close());
}
}
bootstrap();
| sample/08-webpack/src/main.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.00017126261082012206,
0.00017121290147770196,
0.00017116319213528186,
0.00017121290147770196,
4.9709342420101166e-8
]
|
{
"id": 1,
"code_window": [
" *\n",
" * @usageNotes\n",
" * The HTTP response status code will be 403.\n",
" * - The `objectOrError` argument defines the JSON response body or the message string.\n",
" * - The `description` argument contains a short description of the HTTP error.\n",
" *\n",
" * By default, the JSON response body contains two properties:\n",
" * - `statusCode`: this will be the value 403.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause.\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 20
} | import { expect } from 'chai';
import * as sinon from 'sinon';
import { SelectReplFn } from '../../../repl/native-functions';
import { ReplContext } from '../../../repl/repl-context';
import { NestContainer } from '../../../injector/container';
describe('SelectReplFn', () => {
let selectReplFn: SelectReplFn;
let replContext: ReplContext;
let mockApp: {
container: NestContainer;
get: sinon.SinonStub;
resolve: sinon.SinonSpy;
select: sinon.SinonSpy;
};
before(async () => {
const container = new NestContainer();
mockApp = {
container,
get: sinon.stub(),
resolve: sinon.spy(),
select: sinon.spy(),
};
replContext = new ReplContext(mockApp as any);
});
beforeEach(() => {
selectReplFn = replContext.nativeFunctions.get('select') as SelectReplFn;
});
afterEach(() => sinon.restore());
it('the function name should be "select"', () => {
expect(selectReplFn).to.not.be.undefined;
expect(selectReplFn.fnDefinition.name).to.eql('select');
});
describe('action', () => {
it('should pass arguments down to the application context', () => {
const moduleCls = class TestModule {};
selectReplFn.action(moduleCls);
expect(mockApp.select.calledWith(moduleCls)).to.be.true;
});
});
});
| packages/core/test/repl/native-functions/select-repl-fn.spec.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.00017268265946768224,
0.00017059585661627352,
0.000168472426594235,
0.00017060301615856588,
0.0000015038341416584444
]
|
{
"id": 2,
"code_window": [
" * and return it as the JSON response body.\n",
" *\n",
" * @param objectOrError string or object describing the error condition.\n",
" * @param description a short description of the HTTP error.\n",
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 33
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Forbidden* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class ForbiddenException extends HttpException {
/**
* Instantiate a `ForbiddenException` Exception.
*
* @example
* `throw new ForbiddenException()`
*
* @usageNotes
* The HTTP response status code will be 403.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 403.
* - `message`: the string `'Forbidden'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Forbidden',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.FORBIDDEN,
),
HttpStatus.FORBIDDEN,
);
}
}
| packages/common/exceptions/forbidden.exception.ts | 1 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.9545547366142273,
0.47280946373939514,
0.00016708142356947064,
0.488624632358551,
0.41156333684921265
]
|
{
"id": 2,
"code_window": [
" * and return it as the JSON response body.\n",
" *\n",
" * @param objectOrError string or object describing the error condition.\n",
" * @param description a short description of the HTTP error.\n",
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 33
} | import { ContextId } from './instance-wrapper';
export const CONTROLLER_ID_KEY = 'CONTROLLER_ID';
const STATIC_CONTEXT_ID = 1;
export const STATIC_CONTEXT: ContextId = Object.freeze({
id: STATIC_CONTEXT_ID,
});
| packages/core/injector/constants.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.000176029177964665,
0.000176029177964665,
0.000176029177964665,
0.000176029177964665,
0
]
|
{
"id": 2,
"code_window": [
" * and return it as the JSON response body.\n",
" *\n",
" * @param objectOrError string or object describing the error condition.\n",
" * @param description a short description of the HTTP error.\n",
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 33
} | # dependencies
/node_modules
# IDE
/.idea
/.awcache
/.vscode
# misc
npm-debug.log
# example
/quick-start
# tests
/test
/coverage
/.nyc_output
# dist
/dist | sample/20-cache/.gitignore | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.0001802487240638584,
0.00017689673404674977,
0.00017472317267674953,
0.00017571827629581094,
0.0000024047847091424046
]
|
{
"id": 2,
"code_window": [
" * and return it as the JSON response body.\n",
" *\n",
" * @param objectOrError string or object describing the error condition.\n",
" * @param description a short description of the HTTP error.\n",
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 33
} | import { Module } from '@nestjs/common';
import { DependencyService } from './dependency.service';
import { PropertiesService, SYMBOL_TOKEN } from './properties.service';
@Module({
providers: [
DependencyService,
PropertiesService,
{
provide: 'token',
useValue: true,
},
{
provide: SYMBOL_TOKEN,
useValue: true,
},
],
})
export class PropertiesModule {}
| integration/injector/src/properties/properties.module.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.00017339146870654076,
0.00017105942242778838,
0.000168727376149036,
0.00017105942242778838,
0.0000023320462787523866
]
|
{
"id": 3,
"code_window": [
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n",
" description = 'Forbidden',\n",
" ) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" descriptionOrOptions: string | HttpExceptionOptions = 'Forbidden',\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 37
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Forbidden* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class ForbiddenException extends HttpException {
/**
* Instantiate a `ForbiddenException` Exception.
*
* @example
* `throw new ForbiddenException()`
*
* @usageNotes
* The HTTP response status code will be 403.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 403.
* - `message`: the string `'Forbidden'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Forbidden',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.FORBIDDEN,
),
HttpStatus.FORBIDDEN,
);
}
}
| packages/common/exceptions/forbidden.exception.ts | 1 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.9916629791259766,
0.2698357403278351,
0.0001801229373086244,
0.0018542485777288675,
0.38605642318725586
]
|
{
"id": 3,
"code_window": [
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n",
" description = 'Forbidden',\n",
" ) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" descriptionOrOptions: string | HttpExceptionOptions = 'Forbidden',\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 37
} | import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { AsyncOptionsExistingModule } from '../src/async-existing-options.module';
describe('TypeOrm (async configuration)', () => {
let server;
let app: INestApplication;
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [AsyncOptionsExistingModule],
}).compile();
app = module.createNestApplication();
server = app.getHttpServer();
await app.init();
});
it(`should return created entity`, () => {
return request(server)
.post('/photo')
.expect(201, { name: 'Nest', description: 'Is great!', views: 6000 });
});
afterEach(async () => {
await app.close();
});
});
| integration/typeorm/e2e/typeorm-async-existing.spec.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.00017458529327996075,
0.00017187574121635407,
0.00016851162945386022,
0.00017253025725949556,
0.0000025223871489288285
]
|
{
"id": 3,
"code_window": [
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n",
" description = 'Forbidden',\n",
" ) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" descriptionOrOptions: string | HttpExceptionOptions = 'Forbidden',\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 37
} | import { Injectable } from '@nestjs/common';
@Injectable()
export class UsersService {
findById(id: string) {
return { id };
}
}
| integration/hello-world/src/hello/users/users.service.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.0001693857047939673,
0.0001693857047939673,
0.0001693857047939673,
0.0001693857047939673,
0
]
|
{
"id": 3,
"code_window": [
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n",
" description = 'Forbidden',\n",
" ) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" descriptionOrOptions: string | HttpExceptionOptions = 'Forbidden',\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "replace",
"edit_start_line_idx": 37
} | import {
AddressInfo,
createServer as netCreateServer,
Server,
Socket,
} from 'net';
import { ERROR_EVENT } from '../../constants';
import { JsonSocket } from '../../helpers/json-socket';
export const ip = '127.0.0.1';
export function createServer(callback: (err?: any, server?: Server) => void) {
const server = netCreateServer();
server.listen();
server.on('listening', () => {
callback(null, server);
});
server.on(ERROR_EVENT, (err: any) => {
callback(err);
});
}
export function createClient(
server: Server,
callback: (
err?: any,
clientSocket?: JsonSocket,
serverSocket?: JsonSocket,
) => void,
) {
const clientSocket = new JsonSocket(new Socket());
const address = server.address();
if (!address) {
throw new Error('server.address() returned null');
}
const port = (address as AddressInfo).port;
clientSocket.connect(port, ip);
clientSocket.on(ERROR_EVENT, (err: any) => {
callback(err);
});
server.once('connection', socket => {
const serverSocket = new JsonSocket(socket);
callback(null, clientSocket, serverSocket);
});
}
export function createServerAndClient(
callback: (
err?: any,
server?: Server,
clientSocket?: JsonSocket,
serverSocket?: JsonSocket,
) => void,
) {
createServer((serverErr, server) => {
if (serverErr) {
return callback(serverErr);
}
createClient(server, (clientErr, clientSocket, serverSocket) => {
if (clientErr) {
return callback(clientErr);
}
callback(null, server, clientSocket, serverSocket);
});
});
}
export function range(start: number, end: number) {
const r = [];
for (let i = start; i <= end; i++) {
r.push(i);
}
return r;
}
| packages/microservices/test/json-socket/helpers.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.00020922192197758704,
0.0001812724076444283,
0.000166300218552351,
0.00017278279119636863,
0.000015003789485490415
]
|
{
"id": 4,
"code_window": [
" ) {\n",
" super(\n",
" HttpException.createBody(\n",
" objectOrError,\n",
" description,\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { description, httpExceptionOptions } =\n",
" HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions);\n",
"\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "add",
"edit_start_line_idx": 39
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Forbidden* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class ForbiddenException extends HttpException {
/**
* Instantiate a `ForbiddenException` Exception.
*
* @example
* `throw new ForbiddenException()`
*
* @usageNotes
* The HTTP response status code will be 403.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 403.
* - `message`: the string `'Forbidden'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Forbidden',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.FORBIDDEN,
),
HttpStatus.FORBIDDEN,
);
}
}
| packages/common/exceptions/forbidden.exception.ts | 1 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.020848754793405533,
0.005179464817047119,
0.00018244782404508442,
0.000697514449711889,
0.007924729026854038
]
|
{
"id": 4,
"code_window": [
" ) {\n",
" super(\n",
" HttpException.createBody(\n",
" objectOrError,\n",
" description,\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { description, httpExceptionOptions } =\n",
" HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions);\n",
"\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "add",
"edit_start_line_idx": 39
} | // This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
datasource db {
provider = "sqlite"
url = "file:./dev.db"
}
generator client {
provider = "prisma-client-js"
}
model Post {
id String @id @default(uuid())
title String
text String
isPublished Boolean @default(false)
}
| sample/22-graphql-prisma/prisma/schema.prisma | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.00017221469897776842,
0.00017117087554652244,
0.00017012705211527646,
0.00017117087554652244,
0.0000010438234312459826
]
|
{
"id": 4,
"code_window": [
" ) {\n",
" super(\n",
" HttpException.createBody(\n",
" objectOrError,\n",
" description,\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { description, httpExceptionOptions } =\n",
" HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions);\n",
"\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "add",
"edit_start_line_idx": 39
} | import { Inject, Injectable, Scope } from '@nestjs/common';
@Injectable({ scope: Scope.REQUEST })
export class UsersService {
static COUNTER = 0;
constructor(@Inject('META') private readonly meta) {
UsersService.COUNTER++;
}
findById(id: string) {
return { id };
}
}
| integration/scopes/src/msvc/users/users.service.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.0001718929852358997,
0.00017107801977545023,
0.00017026303976308554,
0.00017107801977545023,
8.149727364070714e-7
]
|
{
"id": 4,
"code_window": [
" ) {\n",
" super(\n",
" HttpException.createBody(\n",
" objectOrError,\n",
" description,\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { description, httpExceptionOptions } =\n",
" HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions);\n",
"\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "add",
"edit_start_line_idx": 39
} | import { expect } from 'chai';
import { RmqContext } from '../../ctx-host';
describe('RmqContext', () => {
const args = [{ test: true }, 'test', 'pattern'];
let context: RmqContext;
beforeEach(() => {
context = new RmqContext(args as [Record<string, any>, any, string]);
});
describe('getMessage', () => {
it('should return original message', () => {
expect(context.getMessage()).to.be.eql(args[0]);
});
});
describe('getChannelRef', () => {
it('should return channel reference', () => {
expect(context.getChannelRef()).to.be.eql(args[1]);
});
});
describe('getPattern', () => {
it('should return pattern', () => {
expect(context.getPattern()).to.be.eql(args[2]);
});
});
});
| packages/microservices/test/ctx-host/rmq.context.spec.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.0001719977444736287,
0.00017168530030176044,
0.0001713009987724945,
0.00017175717221107334,
2.8894902470710804e-7
]
|
{
"id": 5,
"code_window": [
" objectOrError,\n",
" description,\n",
" HttpStatus.FORBIDDEN,\n",
" ),\n",
" HttpStatus.FORBIDDEN,\n",
" );\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" httpExceptionOptions,\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "add",
"edit_start_line_idx": 46
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Forbidden* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class ForbiddenException extends HttpException {
/**
* Instantiate a `ForbiddenException` Exception.
*
* @example
* `throw new ForbiddenException()`
*
* @usageNotes
* The HTTP response status code will be 403.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 403.
* - `message`: the string `'Forbidden'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Forbidden',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.FORBIDDEN,
),
HttpStatus.FORBIDDEN,
);
}
}
| packages/common/exceptions/forbidden.exception.ts | 1 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.8703163862228394,
0.17524172365665436,
0.00016566792328376323,
0.0020849481225013733,
0.34753817319869995
]
|
{
"id": 5,
"code_window": [
" objectOrError,\n",
" description,\n",
" HttpStatus.FORBIDDEN,\n",
" ),\n",
" HttpStatus.FORBIDDEN,\n",
" );\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" httpExceptionOptions,\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "add",
"edit_start_line_idx": 46
} | import { expect } from 'chai';
import { METHOD_METADATA, PATH_METADATA, SSE_METADATA } from '../../constants';
import { Sse } from '../../decorators/http/sse.decorator';
import { RequestMethod } from '../../enums/request-method.enum';
describe('@Sse', () => {
const prefix = '/prefix';
class Test {
@Sse(prefix)
public static test() {}
}
it('should enhance method with expected http status code', () => {
const path = Reflect.getMetadata(PATH_METADATA, Test.test);
expect(path).to.be.eql('/prefix');
const method = Reflect.getMetadata(METHOD_METADATA, Test.test);
expect(method).to.be.eql(RequestMethod.GET);
const metadata = Reflect.getMetadata(SSE_METADATA, Test.test);
expect(metadata).to.be.eql(true);
});
});
| packages/common/test/decorators/sse.decorator.spec.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.00017594041128177196,
0.00017351638234686106,
0.0001699976419331506,
0.00017461109382566065,
0.00000254662154475227
]
|
{
"id": 5,
"code_window": [
" objectOrError,\n",
" description,\n",
" HttpStatus.FORBIDDEN,\n",
" ),\n",
" HttpStatus.FORBIDDEN,\n",
" );\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" httpExceptionOptions,\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "add",
"edit_start_line_idx": 46
} | {
"name": "@nestjs/testing",
"version": "9.1.6",
"description": "Nest - modern, fast, powerful node.js web framework (@testing)",
"author": "Kamil Mysliwiec",
"license": "MIT",
"homepage": "https://nestjs.com",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/nest"
},
"repository": {
"type": "git",
"url": "https://github.com/nestjs/nest"
},
"publishConfig": {
"access": "public"
},
"dependencies": {
"tslib": "2.4.0"
},
"peerDependencies": {
"@nestjs/common": "^9.0.0",
"@nestjs/core": "^9.0.0",
"@nestjs/microservices": "^9.0.0",
"@nestjs/platform-express": "^9.0.0"
},
"peerDependenciesMeta": {
"@nestjs/microservices": {
"optional": true
},
"@nestjs/platform-express": {
"optional": true
}
}
}
| packages/testing/package.json | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.00017466588178649545,
0.00017311562260147184,
0.0001714997342787683,
0.0001731484371703118,
0.0000011389029168640263
]
|
{
"id": 5,
"code_window": [
" objectOrError,\n",
" description,\n",
" HttpStatus.FORBIDDEN,\n",
" ),\n",
" HttpStatus.FORBIDDEN,\n",
" );\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" httpExceptionOptions,\n"
],
"file_path": "packages/common/exceptions/forbidden.exception.ts",
"type": "add",
"edit_start_line_idx": 46
} | import { Injectable, StreamableFile } from '@nestjs/common';
import { randomBytes } from 'crypto';
import { createReadStream, readFileSync } from 'fs';
import { join } from 'path';
import { Observable, of } from 'rxjs';
import { Readable } from 'stream';
import { NonFile } from './non-file';
@Injectable()
export class AppService {
// `randomBytes` has a max value of 2^31 -1. That's all this is
private readonly MAX_BITES = Math.pow(2, 31) - 1;
getReadStream(): StreamableFile {
return new StreamableFile(
createReadStream(join(process.cwd(), 'Readme.md')),
);
}
getBuffer(): StreamableFile {
return new StreamableFile(readFileSync(join(process.cwd(), 'Readme.md')));
}
getNonFile(): NonFile {
return new NonFile('Hello world');
}
getRxJSFile(): Observable<StreamableFile> {
return of(this.getReadStream());
}
getFileWithHeaders(): StreamableFile {
const file = readFileSync(join(process.cwd(), 'Readme.md'));
return new StreamableFile(
createReadStream(join(process.cwd(), 'Readme.md')),
{
type: 'text/markdown',
disposition: 'attachment; filename="Readme.md"',
length: file.byteLength,
},
);
}
getFileThatDoesNotExist(): StreamableFile {
return new StreamableFile(createReadStream('does-not-exist.txt'));
}
getSlowStream(): StreamableFile {
const stream = new Readable();
stream.push(Buffer.from(randomBytes(this.MAX_BITES)));
// necessary for a `new Readable()`. Doesn't do anything
stream._read = () => {};
return new StreamableFile(stream);
}
}
| integration/send-files/src/app.service.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.00017483199189882725,
0.00017268805822823197,
0.00016978479106910527,
0.00017273396952077746,
0.0000017450786344852531
]
|
{
"id": 6,
"code_window": [
" BadGatewayException,\n",
" BadRequestException,\n",
" ConflictException,\n",
" HttpException,\n",
" NotFoundException,\n",
"} from '../../exceptions';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" ForbiddenException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 5
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Forbidden* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class ForbiddenException extends HttpException {
/**
* Instantiate a `ForbiddenException` Exception.
*
* @example
* `throw new ForbiddenException()`
*
* @usageNotes
* The HTTP response status code will be 403.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 403.
* - `message`: the string `'Forbidden'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Forbidden',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.FORBIDDEN,
),
HttpStatus.FORBIDDEN,
);
}
}
| packages/common/exceptions/forbidden.exception.ts | 1 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.7287808656692505,
0.14612379670143127,
0.00017556520469952375,
0.0005536618991754949,
0.2913285791873932
]
|
{
"id": 6,
"code_window": [
" BadGatewayException,\n",
" BadRequestException,\n",
" ConflictException,\n",
" HttpException,\n",
" NotFoundException,\n",
"} from '../../exceptions';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" ForbiddenException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 5
} | import {
ArgumentMetadata,
BadRequestException,
Injectable,
PipeTransform,
Type,
} from '@nestjs/common';
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, metadata: ArgumentMetadata) {
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
throw new BadRequestException('Validation failed');
}
return value;
}
private toValidate(metatype: Type<any>): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find(type => metatype === type);
}
}
| sample/10-fastify/src/common/pipes/validation.pipe.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.2603673040866852,
0.0653948113322258,
0.00017209436919074506,
0.0005199150182306767,
0.11256776750087738
]
|
{
"id": 6,
"code_window": [
" BadGatewayException,\n",
" BadRequestException,\n",
" ConflictException,\n",
" HttpException,\n",
" NotFoundException,\n",
"} from '../../exceptions';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" ForbiddenException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 5
} | import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions } from '@nestjs/microservices';
import { AppModule } from './app.module';
import { grpcClientOptions } from './grpc-client.options';
async function bootstrap() {
/**
* This example contains a hybrid application (HTTP + gRPC)
* You can switch to a microservice with NestFactory.createMicroservice() as follows:
*
* const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
* transport: Transport.GRPC,
* options: {
* package: 'hero',
* protoPath: join(__dirname, './hero/hero.proto'),
* }
* });
* await app.listen();
*
*/
const app = await NestFactory.create(AppModule);
app.connectMicroservice<MicroserviceOptions>(grpcClientOptions);
await app.startAllMicroservices();
await app.listen(3001);
console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();
| sample/04-grpc/src/main.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.0001730908261379227,
0.0001706910115899518,
0.00016794170369394124,
0.00017104051948990673,
0.000002116597897838801
]
|
{
"id": 6,
"code_window": [
" BadGatewayException,\n",
" BadRequestException,\n",
" ConflictException,\n",
" HttpException,\n",
" NotFoundException,\n",
"} from '../../exceptions';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" ForbiddenException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 5
} | export * from './http-server.interface';
export * from './message-event.interface';
export * from './raw-body-request.interface';
| packages/common/interfaces/http/index.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.00017035835480783135,
0.00017035835480783135,
0.00017035835480783135,
0.00017035835480783135,
0
]
|
{
"id": 7,
"code_window": [
" BadGatewayException,\n",
" BadRequestException,\n",
" ConflictException,\n",
" ];\n",
"\n",
" builInErrorClasses.forEach(ExceptionClass => {\n",
" const error = new ExceptionClass(customDescription, {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ForbiddenException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 183
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Forbidden* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class ForbiddenException extends HttpException {
/**
* Instantiate a `ForbiddenException` Exception.
*
* @example
* `throw new ForbiddenException()`
*
* @usageNotes
* The HTTP response status code will be 403.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 403.
* - `message`: the string `'Forbidden'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Forbidden',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.FORBIDDEN,
),
HttpStatus.FORBIDDEN,
);
}
}
| packages/common/exceptions/forbidden.exception.ts | 1 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.0014576355461031199,
0.0004257087712176144,
0.00016447047528345138,
0.00016997575585264713,
0.0005159706925041974
]
|
{
"id": 7,
"code_window": [
" BadGatewayException,\n",
" BadRequestException,\n",
" ConflictException,\n",
" ];\n",
"\n",
" builInErrorClasses.forEach(ExceptionClass => {\n",
" const error = new ExceptionClass(customDescription, {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ForbiddenException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 183
} | import {
CanActivate,
ForbiddenException,
HttpServer,
ParamData,
PipeTransform,
RequestMethod,
} from '@nestjs/common';
import {
CUSTOM_ROUTE_ARGS_METADATA,
HEADERS_METADATA,
HTTP_CODE_METADATA,
REDIRECT_METADATA,
RENDER_METADATA,
ROUTE_ARGS_METADATA,
SSE_METADATA,
} from '@nestjs/common/constants';
import { RouteParamMetadata } from '@nestjs/common/decorators';
import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum';
import { ContextType, Controller } from '@nestjs/common/interfaces';
import { isEmpty, isString } from '@nestjs/common/utils/shared.utils';
import { IncomingMessage } from 'http';
import { Observable } from 'rxjs';
import {
FORBIDDEN_MESSAGE,
GuardsConsumer,
GuardsContextCreator,
} from '../guards';
import { ContextUtils } from '../helpers/context-utils';
import { ExecutionContextHost } from '../helpers/execution-context-host';
import {
HandleResponseFn,
HandlerMetadata,
HandlerMetadataStorage,
HandlerResponseBasicFn,
} from '../helpers/handler-metadata-storage';
import { STATIC_CONTEXT } from '../injector/constants';
import { InterceptorsConsumer } from '../interceptors/interceptors-consumer';
import { InterceptorsContextCreator } from '../interceptors/interceptors-context-creator';
import { PipesConsumer } from '../pipes/pipes-consumer';
import { PipesContextCreator } from '../pipes/pipes-context-creator';
import { IRouteParamsFactory } from './interfaces/route-params-factory.interface';
import {
CustomHeader,
RedirectResponse,
RouterResponseController,
} from './router-response-controller';
import { HeaderStream } from './sse-stream';
export interface ParamProperties {
index: number;
type: RouteParamtypes | string;
data: ParamData;
pipes: PipeTransform[];
extractValue: <TRequest, TResponse>(
req: TRequest,
res: TResponse,
next: Function,
) => any;
}
export class RouterExecutionContext {
private readonly handlerMetadataStorage = new HandlerMetadataStorage();
private readonly contextUtils = new ContextUtils();
private readonly responseController: RouterResponseController;
constructor(
private readonly paramsFactory: IRouteParamsFactory,
private readonly pipesContextCreator: PipesContextCreator,
private readonly pipesConsumer: PipesConsumer,
private readonly guardsContextCreator: GuardsContextCreator,
private readonly guardsConsumer: GuardsConsumer,
private readonly interceptorsContextCreator: InterceptorsContextCreator,
private readonly interceptorsConsumer: InterceptorsConsumer,
readonly applicationRef: HttpServer,
) {
this.responseController = new RouterResponseController(applicationRef);
}
public create(
instance: Controller,
callback: (...args: any[]) => unknown,
methodName: string,
moduleKey: string,
requestMethod: RequestMethod,
contextId = STATIC_CONTEXT,
inquirerId?: string,
) {
const contextType: ContextType = 'http';
const {
argsLength,
fnHandleResponse,
paramtypes,
getParamsMetadata,
httpStatusCode,
responseHeaders,
hasCustomHeaders,
} = this.getMetadata(
instance,
callback,
methodName,
moduleKey,
requestMethod,
contextType,
);
const paramsOptions = this.contextUtils.mergeParamsMetatypes(
getParamsMetadata(moduleKey, contextId, inquirerId),
paramtypes,
);
const pipes = this.pipesContextCreator.create(
instance,
callback,
moduleKey,
contextId,
inquirerId,
);
const guards = this.guardsContextCreator.create(
instance,
callback,
moduleKey,
contextId,
inquirerId,
);
const interceptors = this.interceptorsContextCreator.create(
instance,
callback,
moduleKey,
contextId,
inquirerId,
);
const fnCanActivate = this.createGuardsFn(
guards,
instance,
callback,
contextType,
);
const fnApplyPipes = this.createPipesFn(pipes, paramsOptions);
const handler =
<TRequest, TResponse>(
args: any[],
req: TRequest,
res: TResponse,
next: Function,
) =>
async () => {
fnApplyPipes && (await fnApplyPipes(args, req, res, next));
return callback.apply(instance, args);
};
return async <TRequest, TResponse>(
req: TRequest,
res: TResponse,
next: Function,
) => {
const args = this.contextUtils.createNullArray(argsLength);
fnCanActivate && (await fnCanActivate([req, res, next]));
this.responseController.setStatus(res, httpStatusCode);
hasCustomHeaders &&
this.responseController.setHeaders(res, responseHeaders);
const result = await this.interceptorsConsumer.intercept(
interceptors,
[req, res, next],
instance,
callback,
handler(args, req, res, next),
contextType,
);
await (fnHandleResponse as HandlerResponseBasicFn)(result, res, req);
};
}
public getMetadata<TContext extends ContextType = ContextType>(
instance: Controller,
callback: (...args: any[]) => any,
methodName: string,
moduleKey: string,
requestMethod: RequestMethod,
contextType: TContext,
): HandlerMetadata {
const cacheMetadata = this.handlerMetadataStorage.get(instance, methodName);
if (cacheMetadata) {
return cacheMetadata;
}
const metadata =
this.contextUtils.reflectCallbackMetadata(
instance,
methodName,
ROUTE_ARGS_METADATA,
) || {};
const keys = Object.keys(metadata);
const argsLength = this.contextUtils.getArgumentsLength(keys, metadata);
const paramtypes = this.contextUtils.reflectCallbackParamtypes(
instance,
methodName,
);
const contextFactory = this.contextUtils.getContextFactory(
contextType,
instance,
callback,
);
const getParamsMetadata = (
moduleKey: string,
contextId = STATIC_CONTEXT,
inquirerId?: string,
) =>
this.exchangeKeysForValues(
keys,
metadata,
moduleKey,
contextId,
inquirerId,
contextFactory,
);
const paramsMetadata = getParamsMetadata(moduleKey);
const isResponseHandled = this.isResponseHandled(
instance,
methodName,
paramsMetadata,
);
const httpRedirectResponse = this.reflectRedirect(callback);
const fnHandleResponse = this.createHandleResponseFn(
callback,
isResponseHandled,
httpRedirectResponse,
);
const httpCode = this.reflectHttpStatusCode(callback);
const httpStatusCode = httpCode
? httpCode
: this.responseController.getStatusByMethod(requestMethod);
const responseHeaders = this.reflectResponseHeaders(callback);
const hasCustomHeaders = !isEmpty(responseHeaders);
const handlerMetadata: HandlerMetadata = {
argsLength,
fnHandleResponse,
paramtypes,
getParamsMetadata,
httpStatusCode,
hasCustomHeaders,
responseHeaders,
};
this.handlerMetadataStorage.set(instance, methodName, handlerMetadata);
return handlerMetadata;
}
public reflectRedirect(
callback: (...args: unknown[]) => unknown,
): RedirectResponse {
return Reflect.getMetadata(REDIRECT_METADATA, callback);
}
public reflectHttpStatusCode(
callback: (...args: unknown[]) => unknown,
): number {
return Reflect.getMetadata(HTTP_CODE_METADATA, callback);
}
public reflectRenderTemplate(
callback: (...args: unknown[]) => unknown,
): string {
return Reflect.getMetadata(RENDER_METADATA, callback);
}
public reflectResponseHeaders(
callback: (...args: unknown[]) => unknown,
): CustomHeader[] {
return Reflect.getMetadata(HEADERS_METADATA, callback) || [];
}
public reflectSse(callback: (...args: unknown[]) => unknown): string {
return Reflect.getMetadata(SSE_METADATA, callback);
}
public exchangeKeysForValues(
keys: string[],
metadata: Record<number, RouteParamMetadata>,
moduleContext: string,
contextId = STATIC_CONTEXT,
inquirerId?: string,
contextFactory?: (args: unknown[]) => ExecutionContextHost,
): ParamProperties[] {
this.pipesContextCreator.setModuleContext(moduleContext);
return keys.map(key => {
const { index, data, pipes: pipesCollection } = metadata[key];
const pipes = this.pipesContextCreator.createConcreteContext(
pipesCollection,
contextId,
inquirerId,
);
const type = this.contextUtils.mapParamType(key);
if (key.includes(CUSTOM_ROUTE_ARGS_METADATA)) {
const { factory } = metadata[key];
const customExtractValue = this.contextUtils.getCustomFactory(
factory,
data,
contextFactory,
);
return { index, extractValue: customExtractValue, type, data, pipes };
}
const numericType = Number(type);
const extractValue = <TRequest, TResponse>(
req: TRequest,
res: TResponse,
next: Function,
) =>
this.paramsFactory.exchangeKeyForValue(numericType, data, {
req,
res,
next,
});
return { index, extractValue, type: numericType, data, pipes };
});
}
public async getParamValue<T>(
value: T,
{
metatype,
type,
data,
}: { metatype: unknown; type: RouteParamtypes; data: unknown },
pipes: PipeTransform[],
): Promise<unknown> {
if (!isEmpty(pipes)) {
return this.pipesConsumer.apply(
value,
{ metatype, type, data } as any,
pipes,
);
}
return value;
}
public isPipeable(type: number | string): boolean {
return (
type === RouteParamtypes.BODY ||
type === RouteParamtypes.QUERY ||
type === RouteParamtypes.PARAM ||
type === RouteParamtypes.FILE ||
type === RouteParamtypes.FILES ||
isString(type)
);
}
public createGuardsFn<TContext extends string = ContextType>(
guards: CanActivate[],
instance: Controller,
callback: (...args: any[]) => any,
contextType?: TContext,
): (args: any[]) => Promise<void> | null {
const canActivateFn = async (args: any[]) => {
const canActivate = await this.guardsConsumer.tryActivate<TContext>(
guards,
args,
instance,
callback,
contextType,
);
if (!canActivate) {
throw new ForbiddenException(FORBIDDEN_MESSAGE);
}
};
return guards.length ? canActivateFn : null;
}
public createPipesFn(
pipes: PipeTransform[],
paramsOptions: (ParamProperties & { metatype?: any })[],
) {
const pipesFn = async <TRequest, TResponse>(
args: any[],
req: TRequest,
res: TResponse,
next: Function,
) => {
const resolveParamValue = async (
param: ParamProperties & { metatype?: any },
) => {
const {
index,
extractValue,
type,
data,
metatype,
pipes: paramPipes,
} = param;
const value = extractValue(req, res, next);
args[index] = this.isPipeable(type)
? await this.getParamValue(
value,
{ metatype, type, data } as any,
pipes.concat(paramPipes),
)
: value;
};
await Promise.all(paramsOptions.map(resolveParamValue));
};
return paramsOptions.length ? pipesFn : null;
}
public createHandleResponseFn(
callback: (...args: unknown[]) => unknown,
isResponseHandled: boolean,
redirectResponse?: RedirectResponse,
httpStatusCode?: number,
): HandleResponseFn {
const renderTemplate = this.reflectRenderTemplate(callback);
if (renderTemplate) {
return async <TResult, TResponse>(result: TResult, res: TResponse) => {
return await this.responseController.render(
result,
res,
renderTemplate,
);
};
}
if (redirectResponse && isString(redirectResponse.url)) {
return async <TResult, TResponse>(result: TResult, res: TResponse) => {
await this.responseController.redirect(result, res, redirectResponse);
};
}
const isSseHandler = !!this.reflectSse(callback);
if (isSseHandler) {
return <
TResult extends Observable<unknown> = any,
TResponse extends HeaderStream = any,
TRequest extends IncomingMessage = any,
>(
result: TResult,
res: TResponse,
req: TRequest,
) => {
this.responseController.sse(
result,
(res as any).raw || res,
(req as any).raw || req,
{ additionalHeaders: res.getHeaders?.() },
);
};
}
return async <TResult, TResponse>(result: TResult, res: TResponse) => {
result = await this.responseController.transformToResult(result);
!isResponseHandled &&
(await this.responseController.apply(result, res, httpStatusCode));
};
}
private isResponseHandled(
instance: Controller,
methodName: string,
paramsMetadata: ParamProperties[],
): boolean {
const hasResponseOrNextDecorator = paramsMetadata.some(
({ type }) =>
type === RouteParamtypes.RESPONSE || type === RouteParamtypes.NEXT,
);
const isPassthroughEnabled = this.contextUtils.reflectPassthrough(
instance,
methodName,
);
return hasResponseOrNextDecorator && !isPassthroughEnabled;
}
}
| packages/core/router/router-execution-context.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.0006395616219379008,
0.00018373322382103652,
0.00016397799481637776,
0.0001736757403705269,
0.00006670814036624506
]
|
{
"id": 7,
"code_window": [
" BadGatewayException,\n",
" BadRequestException,\n",
" ConflictException,\n",
" ];\n",
"\n",
" builInErrorClasses.forEach(ExceptionClass => {\n",
" const error = new ExceptionClass(customDescription, {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ForbiddenException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 183
} | import { expect } from 'chai';
import { PARAM_ARGS_METADATA } from '../../constants';
import { ConnectedSocket } from '../../decorators';
import { WsParamtype } from '../../enums/ws-paramtype.enum';
class ConnectedSocketTest {
public test(@ConnectedSocket() socket: any) {}
}
describe('@ConnectedSocket', () => {
it('should enhance class with expected request metadata', () => {
const argsMetadata = Reflect.getMetadata(
PARAM_ARGS_METADATA,
ConnectedSocketTest,
'test',
);
const expectedMetadata = {
[`${WsParamtype.SOCKET}:0`]: {
data: undefined,
index: 0,
pipes: [],
},
};
expect(argsMetadata).to.be.eql(expectedMetadata);
});
});
| packages/websockets/test/decorators/connected-socket.decorator.spec.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.00017751342966221273,
0.00017395248869434,
0.00016761741426307708,
0.00017672660760581493,
0.000004491072559176246
]
|
{
"id": 7,
"code_window": [
" BadGatewayException,\n",
" BadRequestException,\n",
" ConflictException,\n",
" ];\n",
"\n",
" builInErrorClasses.forEach(ExceptionClass => {\n",
" const error = new ExceptionClass(customDescription, {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" ForbiddenException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 183
} | import { BadRequestException, Controller, Get } from '@nestjs/common';
@Controller()
export class ErrorsController {
@Get('sync')
synchronous() {
this.throwError();
}
@Get('async')
async asynchronous() {
this.throwError();
}
throwError() {
throw new BadRequestException({
statusCode: 400,
error: 'Bad Request',
message: 'Integration test',
});
}
}
| integration/hello-world/src/errors/errors.controller.ts | 0 | https://github.com/nestjs/nest/commit/c3ced1d17e7a02ca2aa98a01bb7c02805e12c088 | [
0.0015709147555753589,
0.0008757682517170906,
0.0001797598961275071,
0.0008766300743445754,
0.0005679369205608964
]
|
{
"id": 0,
"code_window": [
"require('source-map-support').install();\n",
"\n",
"import * as Koa from 'koa';\n",
"import * as fs from 'fs-extra';\n",
"import Logger, { LoggerWrapper, TargetType } from '@joplin/utils/Logger';\n",
"import config, { fullVersionString, initConfig, runningInDocker } from './config';\n",
"import { migrateLatest, waitForConnection, sqliteDefaultDir, latestMigration, needsMigration, migrateList } from './db';\n",
"import { AppContext, Env, KoaNext } from './utils/types';\n",
"import FsDriverNode from '@joplin/lib/fs-driver-node';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import Logger, { LogLevel, LoggerWrapper, TargetType } from '@joplin/utils/Logger';\n"
],
"file_path": "packages/server/src/app.ts",
"type": "replace",
"edit_start_line_idx": 5
} | const moment = require('moment');
const { sprintf } = require('sprintf-js');
const Mutex = require('async-mutex').Mutex;
const writeToFileMutex_ = new Mutex();
export enum TargetType {
Database = 'database',
File = 'file',
Console = 'console',
}
export enum LogLevel {
None = 0,
Error = 10,
Warn = 20,
Info = 30,
Debug = 40,
}
interface TargetOptions {
level?: LogLevel;
database?: any;
console?: any;
prefix?: string;
path?: string;
source?: string;
// Default message format
format?: string;
// If specified, will use this as format if it's an info message
formatInfo?: string;
}
interface Target extends TargetOptions {
type: TargetType;
}
export interface LoggerWrapper {
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
debug: Function;
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
info: Function;
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
warn: Function;
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
error: Function;
}
interface FsDriver {
appendFile: (path: string, content: string, encoding: string)=> Promise<void>;
}
const dummyFsDriver: FsDriver = {
appendFile: async (_path: string, _content: string, _encoding: string) => {},
};
class Logger {
// For backward compatibility
public static LEVEL_NONE = LogLevel.None;
public static LEVEL_ERROR = LogLevel.Error;
public static LEVEL_WARN = LogLevel.Warn;
public static LEVEL_INFO = LogLevel.Info;
public static LEVEL_DEBUG = LogLevel.Debug;
public static fsDriver_: FsDriver|null = null;
private static globalLogger_: Logger|null = null;
private targets_: Target[] = [];
private level_: LogLevel = LogLevel.Info;
private lastDbCleanup_: number = Date.now();
private enabled_ = true;
public static fsDriver() {
if (!Logger.fsDriver_) Logger.fsDriver_ = dummyFsDriver;
return Logger.fsDriver_;
}
public get enabled(): boolean {
return this.enabled_;
}
public set enabled(v: boolean) {
this.enabled_ = v;
}
public static initializeGlobalLogger(logger: Logger) {
this.globalLogger_ = logger;
}
public static get globalLogger(): Logger {
if (!this.globalLogger_) {
// The global logger normally is initialized early, so we shouldn't
// end up here. However due to early event handlers, it might happen
// and in this case we want to know about it. So we print this
// warning, and also flag the log statements using `[UNINITIALIZED
// GLOBAL LOGGER]` so that we know from where the incorrect log
// statement comes from.
console.warn('Logger: Trying to access globalLogger, but it has not been initialized. Make sure that initializeGlobalLogger() has been called before logging. Will use the console as fallback.');
const output: any = {
log: (level: LogLevel, prefix: string, ...object: any[]) => {
// eslint-disable-next-line no-console
console.info(`[UNINITIALIZED GLOBAL LOGGER] ${this.levelIdToString(level)}: ${prefix}:`, object);
},
};
return output;
// throw new Error('Global logger has not been initialized!!');
}
return this.globalLogger_;
}
public static create(prefix: string): LoggerWrapper {
return {
debug: (...object: any[]) => this.globalLogger.log(LogLevel.Debug, prefix, ...object),
info: (...object: any[]) => this.globalLogger.log(LogLevel.Info, prefix, ...object),
warn: (...object: any[]) => this.globalLogger.log(LogLevel.Warn, prefix, ...object),
error: (...object: any[]) => this.globalLogger.log(LogLevel.Error, prefix, ...object),
};
}
public setLevel(level: LogLevel) {
const previous = this.level_;
this.level_ = level;
return previous;
}
public level() {
return this.level_;
}
public targets() {
return this.targets_;
}
public addTarget(type: TargetType, options: TargetOptions|null = null) {
const target = { type: type };
for (const n in options) {
if (!options.hasOwnProperty(n)) continue;
(target as any)[n] = (options as any)[n];
}
this.targets_.push(target);
}
public objectToString(object: any) {
let output = '';
if (typeof object === 'object') {
if (object instanceof Error) {
object = object as any;
output = object.toString();
if (object.code) output += `\nCode: ${object.code}`;
if (object.headers) output += `\nHeader: ${JSON.stringify(object.headers)}`;
if (object.request) output += `\nRequest: ${object.request.substr ? object.request.substr(0, 1024) : ''}`;
if (object.stack) output += `\n${object.stack}`;
} else {
output = JSON.stringify(object);
}
} else {
output = object;
}
return output;
}
public objectsToString(...object: any[]) {
const output = [];
for (let i = 0; i < object.length; i++) {
output.push(`"${this.objectToString(object[i])}"`);
}
return output.join(', ');
}
public static databaseCreateTableSql() {
const output = `
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY,
source TEXT,
level INT NOT NULL,
message TEXT NOT NULL,
\`timestamp\` INT NOT NULL
);
`;
return output.split('\n').join(' ');
}
// Only for database at the moment
public async lastEntries(limit = 100, options: any = null) {
if (options === null) options = {};
if (!options.levels) options.levels = [LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error];
if (!options.levels.length) return [];
for (let i = 0; i < this.targets_.length; i++) {
const target = this.targets_[i];
if (target.type === 'database') {
let sql = `SELECT * FROM logs WHERE level IN (${options.levels.join(',')}) ORDER BY timestamp DESC`;
if (limit !== null) sql += ` LIMIT ${limit}`;
return await target.database.selectAll(sql);
}
}
return [];
}
public targetLevel(target: Target): LogLevel {
if ('level' in target) return target.level as LogLevel;
return this.level();
}
public log(level: LogLevel, prefix: string | null, ...object: any[]) {
if (!this.targets_.length || !this.enabled) return;
for (let i = 0; i < this.targets_.length; i++) {
const target = this.targets_[i];
const targetPrefix = prefix ? prefix : target.prefix;
if (this.targetLevel(target) < level) continue;
if (target.type === 'console') {
let fn = 'log';
if (level === LogLevel.Error) fn = 'error';
if (level === LogLevel.Warn) fn = 'warn';
if (level === LogLevel.Info) fn = 'info';
const consoleObj = target.console ? target.console : console;
let items: any[] = [];
if (target.format) {
const format = level === LogLevel.Info && target.formatInfo ? target.formatInfo : target.format;
const s = sprintf(format, {
date_time: moment().format('YYYY-MM-DD HH:mm:ss'),
level: Logger.levelIdToString(level),
prefix: targetPrefix || '',
message: '',
});
items = [s.trim()].concat(...object);
} else {
const prefixItems = [moment().format('HH:mm:ss')];
if (targetPrefix) prefixItems.push(targetPrefix);
items = [`${prefixItems.join(': ')}:`].concat(...object);
}
consoleObj[fn](...items);
} else if (target.type === 'file') {
const timestamp = moment().format('YYYY-MM-DD HH:mm:ss');
const line = [timestamp];
if (targetPrefix) line.push(targetPrefix);
line.push(this.objectsToString(...object));
// Write to file using a mutex so that log entries appear in the
// correct order (otherwise, since the async call is not awaited
// by caller, multiple log call in a row are not guaranteed to
// appear in the right order). We also can't use a sync call
// because that would slow down the main process, especially
// when many log operations are being done (eg. during sync in
// dev mode).
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
let release: Function|null = null;
/* eslint-disable-next-line promise/prefer-await-to-then, @typescript-eslint/ban-types -- Old code before rule was applied, Old code before rule was applied */
writeToFileMutex_.acquire().then((r: Function) => {
release = r;
return Logger.fsDriver().appendFile(target.path as string, `${line.join(': ')}\n`, 'utf8');
// eslint-disable-next-line promise/prefer-await-to-then -- Old code before rule was applied
}).catch((error: any) => {
console.error('Cannot write to log file:', error);
// eslint-disable-next-line promise/prefer-await-to-then -- Old code before rule was applied
}).finally(() => {
if (release) release();
});
} else if (target.type === 'database') {
const msg = [];
if (targetPrefix) msg.push(targetPrefix);
msg.push(this.objectsToString(...object));
const queries = [
{
sql: 'INSERT INTO logs (`source`, `level`, `message`, `timestamp`) VALUES (?, ?, ?, ?)',
params: [target.source, level, msg.join(': '), Date.now()],
},
];
const now = Date.now();
if (now - this.lastDbCleanup_ > 1000 * 60 * 60) {
this.lastDbCleanup_ = now;
const dayKeep = 14;
queries.push({
sql: 'DELETE FROM logs WHERE `timestamp` < ?',
params: [now - 1000 * 60 * 60 * 24 * dayKeep],
});
}
target.database.transactionExecBatch(queries);
}
}
}
public error(...object: any[]) {
return this.log(LogLevel.Error, null, ...object);
}
public warn(...object: any[]) {
return this.log(LogLevel.Warn, null, ...object);
}
public info(...object: any[]) {
return this.log(LogLevel.Info, null, ...object);
}
public debug(...object: any[]) {
return this.log(LogLevel.Debug, null, ...object);
}
public static levelStringToId(s: string) {
if (s === 'none') return LogLevel.None;
if (s === 'error') return LogLevel.Error;
if (s === 'warn') return LogLevel.Warn;
if (s === 'info') return LogLevel.Info;
if (s === 'debug') return LogLevel.Debug;
throw new Error(`Unknown log level: ${s}`);
}
public static levelIdToString(id: LogLevel) {
if (id === LogLevel.None) return 'none';
if (id === LogLevel.Error) return 'error';
if (id === LogLevel.Warn) return 'warn';
if (id === LogLevel.Info) return 'info';
if (id === LogLevel.Debug) return 'debug';
throw new Error(`Unknown level ID: ${id}`);
}
public static levelIds() {
return [LogLevel.None, LogLevel.Error, LogLevel.Warn, LogLevel.Info, LogLevel.Debug];
}
}
export default Logger;
| packages/utils/Logger.ts | 1 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.0041366759687662125,
0.00044172751950100064,
0.0001600110699655488,
0.00017390906577929854,
0.000793610408436507
]
|
{
"id": 0,
"code_window": [
"require('source-map-support').install();\n",
"\n",
"import * as Koa from 'koa';\n",
"import * as fs from 'fs-extra';\n",
"import Logger, { LoggerWrapper, TargetType } from '@joplin/utils/Logger';\n",
"import config, { fullVersionString, initConfig, runningInDocker } from './config';\n",
"import { migrateLatest, waitForConnection, sqliteDefaultDir, latestMigration, needsMigration, migrateList } from './db';\n",
"import { AppContext, Env, KoaNext } from './utils/types';\n",
"import FsDriverNode from '@joplin/lib/fs-driver-node';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import Logger, { LogLevel, LoggerWrapper, TargetType } from '@joplin/utils/Logger';\n"
],
"file_path": "packages/server/src/app.ts",
"type": "replace",
"edit_start_line_idx": 5
} | Some text, not an image, so it should remain escaped:
<img src="http://test.com/image.png" />
<p class="testing">Paragraph example</p>
But this is code so it can be unescaped:
```
<img src="http://test.com/image.png" />
``` | packages/app-cli/tests/html_to_md/text_with_escaped_html.md | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.00017682350880932063,
0.0001754268305376172,
0.000174030166817829,
0.0001754268305376172,
0.0000013966709957458079
]
|
{
"id": 0,
"code_window": [
"require('source-map-support').install();\n",
"\n",
"import * as Koa from 'koa';\n",
"import * as fs from 'fs-extra';\n",
"import Logger, { LoggerWrapper, TargetType } from '@joplin/utils/Logger';\n",
"import config, { fullVersionString, initConfig, runningInDocker } from './config';\n",
"import { migrateLatest, waitForConnection, sqliteDefaultDir, latestMigration, needsMigration, migrateList } from './db';\n",
"import { AppContext, Env, KoaNext } from './utils/types';\n",
"import FsDriverNode from '@joplin/lib/fs-driver-node';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import Logger, { LogLevel, LoggerWrapper, TargetType } from '@joplin/utils/Logger';\n"
],
"file_path": "packages/server/src/app.ts",
"type": "replace",
"edit_start_line_idx": 5
} | id: 8897f538ba4343cfba78eafd6c71a29c
created_time:
updated_time: 2021-08-07T17:03:37.161Z
user_created_time:
user_updated_time:
encryption_cipher_text: JED01000022051f3b6b71948c4f5d909d1af6588c78bb000298{"iv":"hC0Y3d2VM7c49TbONsnUVA==","v":1,"iter":101,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"tVgmTCWSasM=","ct":"1gD9XcIdebdX5jVkdBVqM8Sf/5ms4d8D4t61Va8BxakyO+xCdZtKUNzPpSDvu+B6lJozt9knQNC2EouuJ0itfWUSmSI+1OVL2lbt8/MJHrhQQFG5JPGcJ06aeuL1dntfRJPpxX4KeDB0Dzh6Zv8qfuosYRjwOfAFf7J+w61Q6eQTBoSi1jfLx12mXEru3JfLOCMzRHtZH+xhghA0+LofM4J2q6Pr9XwIHQ8JMaaDCYV2jhpNUQlEHKlQo1M1ftHDSq0vb7m028c6KH/p0XvqH5rNx0M77nM1FRRmoj1pUgOfzszn0VNbKWi+OmBMWPS0yEruUKznneR35/0ZDFR+eRSHeEsJNbw/uz2NddC1q2Jdj26x/Gl3Sg6fpk2jUrXCNXidyVYWXBnYbK9jNJqIQz3uUQtCxe+lFH7ezZxX2b2gp60gXMluCbUomc8zbmaZHqM6kSAil+P6QUcpUhpMkfS5tjJRvLQ0Gj0/nbRiYjLWaCT5eA/IETU6DDZtrgUFsU1LCCmW5i0EzbU="}
encryption_applied: 1
parent_id:
is_shared:
share_id:
type_: 2 | packages/app-cli/tests/support/syncTargetSnapshots/3/e2ee/8897f538ba4343cfba78eafd6c71a29c.md | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.0010284093441441655,
0.0005999408895149827,
0.00017147242033388466,
0.0005999408895149827,
0.0004284684546291828
]
|
{
"id": 0,
"code_window": [
"require('source-map-support').install();\n",
"\n",
"import * as Koa from 'koa';\n",
"import * as fs from 'fs-extra';\n",
"import Logger, { LoggerWrapper, TargetType } from '@joplin/utils/Logger';\n",
"import config, { fullVersionString, initConfig, runningInDocker } from './config';\n",
"import { migrateLatest, waitForConnection, sqliteDefaultDir, latestMigration, needsMigration, migrateList } from './db';\n",
"import { AppContext, Env, KoaNext } from './utils/types';\n",
"import FsDriverNode from '@joplin/lib/fs-driver-node';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import Logger, { LogLevel, LoggerWrapper, TargetType } from '@joplin/utils/Logger';\n"
],
"file_path": "packages/server/src/app.ts",
"type": "replace",
"edit_start_line_idx": 5
} | id: aa7dca873bdc47beaa9465e04610619d
created_time:
updated_time: 2020-07-25T10:55:20.635Z
user_created_time:
user_updated_time:
encryption_cipher_text: JED0100002205a1a0987e82cc400c90582492f814c23c0002b0{"iv":"/hdpjX6UaArAOXSsk6W8eg==","v":1,"iter":101,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"Gyo7bQeqz2w=","ct":"7qX8Fym/M6iCMLeN1M1NuTgPzBKFlleRtwTdGAJCNR6s88rgC4XYlT0AA/mAJ28FDw61JO29ZnVQTLulyuAhmsNtxY6Bar005sLHlEhX/s+/LRyfdLKhzVWVMuKvGeg9F8omkDVDjE9oOcx2DqM+wV9kQe7d2sDWYpu/fEk7T9MNBWI+vodqfw3iNLOiQWzQq5Xrqy7lpb/fj4sSgtKGZouSkbhcckjaKYl5IpblfZffnRF5T770Our6ufID3kTFAorqD4Zg6lY4SUKLrWWAptPv4/wQtBa4J5mQ0XUy3OSSjh4EP70H2js2NrDouKFsaRB2KyKk0/JuMmnMhuajyb9ozIDGwWEmi9zKZZ5FrvqLCKY53hhqxyQ8BMOrrHm8T/GVmfFMKN2ZkO8eLdoTETx8qqyErB9oHg6FsKCJS+943BcsrEuDHaSKUFTV+y5JNiEHIg+hBqMwc53z5mNgylP5eYqvje+t8zo0ZCXPJaMArlSohSQOE2pga9b2k8pwtczIQk1ZL36CX0WcDJVe5ir+c8NtMHG7omHolaU="}
encryption_applied: 1
parent_id: 3d675395b5cd4d1e9d7ca4f045f41493
is_shared:
type_: 2 | packages/app-cli/tests/support/syncTargetSnapshots/2/e2ee/aa7dca873bdc47beaa9465e04610619d.md | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.0002717991010285914,
0.0002216571883764118,
0.00017151526117231697,
0.0002216571883764118,
0.00005014191992813721
]
|
{
"id": 1,
"code_window": [
"\n",
"\tLogger.fsDriver_ = new FsDriverNode();\n",
"\tconst globalLogger = new Logger();\n",
"\tconst instancePrefix = config().INSTANCE_NAME ? `${config().INSTANCE_NAME}: ` : '';\n",
"\tglobalLogger.addTarget(TargetType.Console, {\n",
"\t\tformat: `%(date_time)s: ${instancePrefix}[%(level)s] %(prefix)s: %(message)s`,\n",
"\t\tformatInfo: `%(date_time)s: ${instancePrefix}%(prefix)s: %(message)s`,\n",
"\t});\n",
"\tLogger.initializeGlobalLogger(globalLogger);\n",
"\tinitLib(globalLogger);\n",
"\n",
"\tif (envFilePath) appLogger().info(`Env variables were loaded from: ${envFilePath}`);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tformat: (level: LogLevel, _prefix: string) => {\n",
"\t\t\tif (level === LogLevel.Info) return `%(date_time)s: ${instancePrefix}%(prefix)s: %(message)s`;\n",
"\t\t\treturn `%(date_time)s: ${instancePrefix}[%(level)s] %(prefix)s: %(message)s`;\n",
"\t\t},\n"
],
"file_path": "packages/server/src/app.ts",
"type": "replace",
"edit_start_line_idx": 226
} | // Allows displaying error stack traces with TypeScript file paths
require('source-map-support').install();
import * as Koa from 'koa';
import * as fs from 'fs-extra';
import Logger, { LoggerWrapper, TargetType } from '@joplin/utils/Logger';
import config, { fullVersionString, initConfig, runningInDocker } from './config';
import { migrateLatest, waitForConnection, sqliteDefaultDir, latestMigration, needsMigration, migrateList } from './db';
import { AppContext, Env, KoaNext } from './utils/types';
import FsDriverNode from '@joplin/lib/fs-driver-node';
import { getDeviceTimeDrift } from '@joplin/lib/ntp';
import routeHandler from './middleware/routeHandler';
import notificationHandler from './middleware/notificationHandler';
import ownerHandler from './middleware/ownerHandler';
import setupAppContext from './utils/setupAppContext';
import { initializeJoplinUtils } from './utils/joplinUtils';
import startServices from './utils/startServices';
import { credentialFile } from './utils/testing/testUtils';
import apiVersionHandler from './middleware/apiVersionHandler';
import clickJackingHandler from './middleware/clickJackingHandler';
import newModelFactory from './models/factory';
import setupCommands from './utils/setupCommands';
import { RouteResponseFormat, routeResponseFormat } from './utils/routeUtils';
import { parseEnv } from './env';
import { parseEnvFile } from '@joplin/utils/env';
import storageConnectionCheck from './utils/storageConnectionCheck';
import { setLocale } from '@joplin/lib/locale';
import initLib from '@joplin/lib/initLib';
import checkAdminHandler from './middleware/checkAdminHandler';
interface Argv {
env?: Env;
pidfile?: string;
envFile?: string;
}
const nodeSqlite = require('sqlite3');
const cors = require('@koa/cors');
const { shimInit } = require('@joplin/lib/shim-init-node.js');
shimInit({ nodeSqlite });
const defaultEnvVariables: Record<Env, any> = {
dev: {
// To test with the Postgres database, uncomment DB_CLIENT below and
// comment out SQLITE_DATABASE. Then start the Postgres server using
// `docker-compose --file docker-compose.db-dev.yml up`
// DB_CLIENT: 'pg',
SQLITE_DATABASE: `${sqliteDefaultDir}/db-dev.sqlite`,
},
buildTypes: {
SQLITE_DATABASE: `${sqliteDefaultDir}/db-buildTypes.sqlite`,
},
prod: {
SQLITE_DATABASE: `${sqliteDefaultDir}/db-prod.sqlite`,
},
};
let appLogger_: LoggerWrapper = null;
function appLogger(): LoggerWrapper {
if (!appLogger_) {
appLogger_ = Logger.create('App');
}
return appLogger_;
}
function markPasswords(o: Record<string, any>): Record<string, any> {
if (!o) return o;
const output: Record<string, any> = {};
for (const k of Object.keys(o)) {
if (k.toLowerCase().includes('password') || k.toLowerCase().includes('secret') || k.toLowerCase().includes('connectionstring')) {
output[k] = '********';
} else {
output[k] = o[k];
}
}
return output;
}
async function getEnvFilePath(env: Env, argv: any): Promise<string> {
if (argv.envFile) return argv.envFile;
if (env === Env.Dev) {
return credentialFile('server.env');
}
return '';
}
async function main() {
const { selectedCommand, argv: yargsArgv } = await setupCommands();
const argv: Argv = yargsArgv as any;
const env: Env = argv.env as Env || Env.Prod;
const envFilePath = await getEnvFilePath(env, argv);
let envFromFile: Record<string, string> = {};
try {
if (envFilePath) envFromFile = parseEnvFile(envFilePath);
} catch (error) {
error.message = `Could not parse env file at ${envFilePath}: ${error.message}`;
throw error;
}
const fullEnv = {
...envFromFile,
...process.env,
};
if (!defaultEnvVariables[env]) throw new Error(`Invalid env: ${env}`);
const envVariables = parseEnv(fullEnv, defaultEnvVariables[env]);
const app = new Koa();
// Note: the order of middlewares is important. For example, ownerHandler
// loads the user, which is then used by notificationHandler. And finally
// routeHandler uses data from both previous middlewares. It would be good to
// layout these dependencies in code but not clear how to do this.
const corsAllowedDomains = [
'https://joplinapp.org',
];
if (env === Env.Dev) {
corsAllowedDomains.push('http://localhost:8077');
}
function acceptOrigin(origin: string): boolean {
const hostname = (new URL(origin)).hostname;
const userContentDomain = envVariables.USER_CONTENT_BASE_URL ? (new URL(envVariables.USER_CONTENT_BASE_URL)).hostname : '';
if (hostname === userContentDomain) return true;
const hostnameNoSub = hostname.split('.').slice(1).join('.');
// console.info('CORS check for origin', origin, 'Allowed domains', corsAllowedDomains);
if (hostnameNoSub === userContentDomain) return true;
if (corsAllowedDomains.includes(origin)) return true;
return false;
}
// This is used to catch any low level error thrown from a middleware. It
// won't deal with errors from routeHandler, which catches and handles its
// own errors.
app.use(async (ctx: AppContext, next: KoaNext) => {
try {
await next();
} catch (error) {
ctx.status = error.httpCode || 500;
appLogger().error(`Middleware error on ${ctx.path}:`, error);
const responseFormat = routeResponseFormat(ctx);
if (responseFormat === RouteResponseFormat.Html) {
// Since this is a low level error, rendering a view might fail too,
// so catch this and default to rendering JSON.
try {
ctx.response.set('Content-Type', 'text/html');
ctx.body = await ctx.joplin.services.mustache.renderView({
name: 'error',
title: 'Error',
path: 'index/error',
content: { error },
});
} catch (anotherError) {
ctx.response.set('Content-Type', 'application/json');
ctx.body = JSON.stringify({ error: `${error.message} (Check the server log for more information)` });
}
} else {
ctx.response.set('Content-Type', 'application/json');
ctx.body = JSON.stringify({ error: error.message });
}
}
});
// Creates the request-specific "joplin" context property.
app.use(async (ctx: AppContext, next: KoaNext) => {
ctx.joplin = {
...ctx.joplinBase,
owner: null,
notifications: [],
};
return next();
});
app.use(cors({
// https://github.com/koajs/cors/issues/52#issuecomment-413887382
origin: (ctx: AppContext) => {
const origin = ctx.request.header.origin;
if (acceptOrigin(origin)) {
return origin;
} else {
// we can't return void, so let's return one of the valid domains
return corsAllowedDomains[0];
}
},
}));
app.use(apiVersionHandler);
app.use(ownerHandler);
app.use(checkAdminHandler);
app.use(notificationHandler);
app.use(clickJackingHandler);
app.use(routeHandler);
await initConfig(env, envVariables);
await fs.mkdirp(config().logDir);
await fs.mkdirp(config().tempDir);
Logger.fsDriver_ = new FsDriverNode();
const globalLogger = new Logger();
const instancePrefix = config().INSTANCE_NAME ? `${config().INSTANCE_NAME}: ` : '';
globalLogger.addTarget(TargetType.Console, {
format: `%(date_time)s: ${instancePrefix}[%(level)s] %(prefix)s: %(message)s`,
formatInfo: `%(date_time)s: ${instancePrefix}%(prefix)s: %(message)s`,
});
Logger.initializeGlobalLogger(globalLogger);
initLib(globalLogger);
if (envFilePath) appLogger().info(`Env variables were loaded from: ${envFilePath}`);
const pidFile = argv.pidfile as string;
if (pidFile) {
appLogger().info(`Writing PID to ${pidFile}...`);
fs.removeSync(pidFile as string);
fs.writeFileSync(pidFile, `${process.pid}`);
}
let runCommandAndExitApp = true;
if (selectedCommand) {
const commandArgv = {
...argv,
_: (argv as any)._.slice(),
};
commandArgv._.splice(0, 1);
if (selectedCommand.commandName() === 'db') {
await selectedCommand.run(commandArgv, {
db: null,
models: null,
});
} else {
const connectionCheck = await waitForConnection(config().database);
const models = newModelFactory(connectionCheck.connection, config());
await selectedCommand.run(commandArgv, {
db: connectionCheck.connection,
models,
});
}
} else {
runCommandAndExitApp = false;
appLogger().info(`Starting server ${fullVersionString(config())} (${env}) on port ${config().port} and PID ${process.pid}...`);
if (config().maxTimeDrift) {
appLogger().info(`Checking for time drift using NTP server: ${config().NTP_SERVER}`);
const timeDrift = await getDeviceTimeDrift(config().NTP_SERVER);
if (Math.abs(timeDrift) > config().maxTimeDrift) {
throw new Error(`The device time drift is ${timeDrift}ms (Max allowed: ${config().maxTimeDrift}ms) - cannot continue as it could cause data loss and conflicts on the sync clients. You may increase env var MAX_TIME_DRIFT to pass the check, or set to 0 to disabled the check.`);
}
appLogger().info(`NTP time offset: ${timeDrift}ms`);
} else {
appLogger().info('Skipping NTP time check because MAX_TIME_DRIFT is 0.');
}
setLocale('en_GB');
appLogger().info('Running in Docker:', runningInDocker());
appLogger().info('Public base URL:', config().baseUrl);
appLogger().info('API base URL:', config().apiBaseUrl);
appLogger().info('User content base URL:', config().userContentBaseUrl);
appLogger().info('Log dir:', config().logDir);
appLogger().info('DB Config:', markPasswords(config().database));
appLogger().info('Mailer Config:', markPasswords(config().mailer));
appLogger().info('Content driver:', markPasswords(config().storageDriver));
appLogger().info('Content driver (fallback):', markPasswords(config().storageDriverFallback));
appLogger().info('Trying to connect to database...');
const connectionCheck = await waitForConnection(config().database);
const connectionCheckLogInfo = { ...connectionCheck };
delete connectionCheckLogInfo.connection;
appLogger().info('Connection check:', connectionCheckLogInfo);
const ctx = app.context as AppContext;
if (config().database.autoMigration) {
appLogger().info('Auto-migrating database...');
await migrateLatest(connectionCheck.connection);
appLogger().info('Latest migration:', await latestMigration(connectionCheck.connection));
} else {
if (!config().DB_ALLOW_INCOMPLETE_MIGRATIONS && (await needsMigration(connectionCheck.connection))) {
const list = await migrateList(connectionCheck.connection, true);
throw new Error(`One or more migrations need to be applied:\n\n${list}`);
}
appLogger().info('Skipped database auto-migration.');
}
await setupAppContext(ctx, env, connectionCheck.connection, appLogger);
await initializeJoplinUtils(config(), ctx.joplinBase.models, ctx.joplinBase.services.mustache);
appLogger().info('Performing main storage check...');
appLogger().info(await storageConnectionCheck(config().storageDriver, ctx.joplinBase.db, ctx.joplinBase.models));
if (config().storageDriverFallback) {
appLogger().info('Performing fallback storage check...');
appLogger().info(await storageConnectionCheck(config().storageDriverFallback, ctx.joplinBase.db, ctx.joplinBase.models));
}
appLogger().info('Starting services...');
await startServices(config(), ctx.joplinBase.services);
appLogger().info(`Call this for testing: \`curl ${config().apiBaseUrl}/api/ping\``);
app.listen(config().port);
}
if (runCommandAndExitApp) process.exit(0);
}
main().catch((error: any) => {
console.error(error);
process.exit(1);
});
| packages/server/src/app.ts | 1 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.9976379871368408,
0.03020508587360382,
0.00016397987201344222,
0.00017245345225092024,
0.16601502895355225
]
|
{
"id": 1,
"code_window": [
"\n",
"\tLogger.fsDriver_ = new FsDriverNode();\n",
"\tconst globalLogger = new Logger();\n",
"\tconst instancePrefix = config().INSTANCE_NAME ? `${config().INSTANCE_NAME}: ` : '';\n",
"\tglobalLogger.addTarget(TargetType.Console, {\n",
"\t\tformat: `%(date_time)s: ${instancePrefix}[%(level)s] %(prefix)s: %(message)s`,\n",
"\t\tformatInfo: `%(date_time)s: ${instancePrefix}%(prefix)s: %(message)s`,\n",
"\t});\n",
"\tLogger.initializeGlobalLogger(globalLogger);\n",
"\tinitLib(globalLogger);\n",
"\n",
"\tif (envFilePath) appLogger().info(`Env variables were loaded from: ${envFilePath}`);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tformat: (level: LogLevel, _prefix: string) => {\n",
"\t\t\tif (level === LogLevel.Info) return `%(date_time)s: ${instancePrefix}%(prefix)s: %(message)s`;\n",
"\t\t\treturn `%(date_time)s: ${instancePrefix}[%(level)s] %(prefix)s: %(message)s`;\n",
"\t\t},\n"
],
"file_path": "packages/server/src/app.ts",
"type": "replace",
"edit_start_line_idx": 226
} | {
"manifest_version": 1,
"id": "org.joplinapp.plugins.NativeModuleTest",
"app_min_version": "1.7",
"version": "1.0.0",
"name": "Native Module Test",
"description": "",
"author": "",
"homepage_url": "",
"repository_url": "",
"keywords": []
} | packages/app-cli/tests/support/plugins/nativeModule/src/manifest.json | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.00017353867588099092,
0.00017034137272275984,
0.00016714405501261353,
0.00017034137272275984,
0.0000031973104341886938
]
|
{
"id": 1,
"code_window": [
"\n",
"\tLogger.fsDriver_ = new FsDriverNode();\n",
"\tconst globalLogger = new Logger();\n",
"\tconst instancePrefix = config().INSTANCE_NAME ? `${config().INSTANCE_NAME}: ` : '';\n",
"\tglobalLogger.addTarget(TargetType.Console, {\n",
"\t\tformat: `%(date_time)s: ${instancePrefix}[%(level)s] %(prefix)s: %(message)s`,\n",
"\t\tformatInfo: `%(date_time)s: ${instancePrefix}%(prefix)s: %(message)s`,\n",
"\t});\n",
"\tLogger.initializeGlobalLogger(globalLogger);\n",
"\tinitLib(globalLogger);\n",
"\n",
"\tif (envFilePath) appLogger().info(`Env variables were loaded from: ${envFilePath}`);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tformat: (level: LogLevel, _prefix: string) => {\n",
"\t\t\tif (level === LogLevel.Info) return `%(date_time)s: ${instancePrefix}%(prefix)s: %(message)s`;\n",
"\t\t\treturn `%(date_time)s: ${instancePrefix}[%(level)s] %(prefix)s: %(message)s`;\n",
"\t\t},\n"
],
"file_path": "packages/server/src/app.ts",
"type": "replace",
"edit_start_line_idx": 226
} | #!/bin/bash
npm version patch
npm publish | packages/turndown/publish.sh | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.0001654605002840981,
0.0001654605002840981,
0.0001654605002840981,
0.0001654605002840981,
0
]
|
{
"id": 1,
"code_window": [
"\n",
"\tLogger.fsDriver_ = new FsDriverNode();\n",
"\tconst globalLogger = new Logger();\n",
"\tconst instancePrefix = config().INSTANCE_NAME ? `${config().INSTANCE_NAME}: ` : '';\n",
"\tglobalLogger.addTarget(TargetType.Console, {\n",
"\t\tformat: `%(date_time)s: ${instancePrefix}[%(level)s] %(prefix)s: %(message)s`,\n",
"\t\tformatInfo: `%(date_time)s: ${instancePrefix}%(prefix)s: %(message)s`,\n",
"\t});\n",
"\tLogger.initializeGlobalLogger(globalLogger);\n",
"\tinitLib(globalLogger);\n",
"\n",
"\tif (envFilePath) appLogger().info(`Env variables were loaded from: ${envFilePath}`);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tformat: (level: LogLevel, _prefix: string) => {\n",
"\t\t\tif (level === LogLevel.Info) return `%(date_time)s: ${instancePrefix}%(prefix)s: %(message)s`;\n",
"\t\t\treturn `%(date_time)s: ${instancePrefix}[%(level)s] %(prefix)s: %(message)s`;\n",
"\t\t},\n"
],
"file_path": "packages/server/src/app.ts",
"type": "replace",
"edit_start_line_idx": 226
} | import { afterAllTests, beforeAllDb, beforeEachDb, createUserAndSession, expectThrow, koaAppContext, models } from '../../../../utils/testing/testUtils';
import { cookieGet, cookieSet } from '../../../../utils/cookies';
import { startImpersonating, stopImpersonating } from './impersonate';
describe('users/impersonate', () => {
beforeAll(async () => {
await beforeAllDb('users/impersonate');
});
afterAll(async () => {
await afterAllTests();
});
beforeEach(async () => {
await beforeEachDb();
});
test('should impersonate a user', async () => {
const ctx = await koaAppContext();
const { user: adminUser, session: adminSession } = await createUserAndSession(1, true);
const { user } = await createUserAndSession(2);
cookieSet(ctx, 'sessionId', adminSession.id);
await startImpersonating(ctx, user.id);
{
expect(cookieGet(ctx, 'adminSessionId')).toBe(adminSession.id);
const sessionUser = await models().session().sessionUser(cookieGet(ctx, 'sessionId'));
expect(sessionUser.id).toBe(user.id);
}
await stopImpersonating(ctx);
{
expect(cookieGet(ctx, 'adminSessionId')).toBeFalsy();
const sessionUser = await models().session().sessionUser(cookieGet(ctx, 'sessionId'));
expect(sessionUser.id).toBe(adminUser.id);
}
});
test('should not impersonate if not admin', async () => {
const ctx = await koaAppContext();
const { user: adminUser } = await createUserAndSession(1, true);
const { session } = await createUserAndSession(2);
cookieSet(ctx, 'sessionId', session.id);
await expectThrow(async () => startImpersonating(ctx, adminUser.id));
});
// test('should not stop impersonating if not admin', async function() {
// const ctx = await koaAppContext();
// await createUserAndSession(1, true);
// const { session } = await createUserAndSession(2);
// cookieSet(ctx, 'adminSessionId', session.id);
// await expectThrow(async () => stopImpersonating(ctx));
// });
});
| packages/server/src/routes/admin/utils/users/impersonate.test.ts | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.00017457529611419886,
0.0001710932847345248,
0.00016808684449642897,
0.0001717119594104588,
0.0000020733400560857262
]
|
{
"id": 2,
"code_window": [
"\tInfo = 30,\n",
"\tDebug = 40,\n",
"}\n",
"\n",
"interface TargetOptions {\n",
"\tlevel?: LogLevel;\n",
"\tdatabase?: any;\n",
"\tconsole?: any;\n",
"\tprefix?: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"type FormatFunction = (level: LogLevel, targetPrefix?: string)=> string;\n",
"\n"
],
"file_path": "packages/utils/Logger.ts",
"type": "add",
"edit_start_line_idx": 20
} | const moment = require('moment');
const { sprintf } = require('sprintf-js');
const Mutex = require('async-mutex').Mutex;
const writeToFileMutex_ = new Mutex();
export enum TargetType {
Database = 'database',
File = 'file',
Console = 'console',
}
export enum LogLevel {
None = 0,
Error = 10,
Warn = 20,
Info = 30,
Debug = 40,
}
interface TargetOptions {
level?: LogLevel;
database?: any;
console?: any;
prefix?: string;
path?: string;
source?: string;
// Default message format
format?: string;
// If specified, will use this as format if it's an info message
formatInfo?: string;
}
interface Target extends TargetOptions {
type: TargetType;
}
export interface LoggerWrapper {
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
debug: Function;
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
info: Function;
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
warn: Function;
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
error: Function;
}
interface FsDriver {
appendFile: (path: string, content: string, encoding: string)=> Promise<void>;
}
const dummyFsDriver: FsDriver = {
appendFile: async (_path: string, _content: string, _encoding: string) => {},
};
class Logger {
// For backward compatibility
public static LEVEL_NONE = LogLevel.None;
public static LEVEL_ERROR = LogLevel.Error;
public static LEVEL_WARN = LogLevel.Warn;
public static LEVEL_INFO = LogLevel.Info;
public static LEVEL_DEBUG = LogLevel.Debug;
public static fsDriver_: FsDriver|null = null;
private static globalLogger_: Logger|null = null;
private targets_: Target[] = [];
private level_: LogLevel = LogLevel.Info;
private lastDbCleanup_: number = Date.now();
private enabled_ = true;
public static fsDriver() {
if (!Logger.fsDriver_) Logger.fsDriver_ = dummyFsDriver;
return Logger.fsDriver_;
}
public get enabled(): boolean {
return this.enabled_;
}
public set enabled(v: boolean) {
this.enabled_ = v;
}
public static initializeGlobalLogger(logger: Logger) {
this.globalLogger_ = logger;
}
public static get globalLogger(): Logger {
if (!this.globalLogger_) {
// The global logger normally is initialized early, so we shouldn't
// end up here. However due to early event handlers, it might happen
// and in this case we want to know about it. So we print this
// warning, and also flag the log statements using `[UNINITIALIZED
// GLOBAL LOGGER]` so that we know from where the incorrect log
// statement comes from.
console.warn('Logger: Trying to access globalLogger, but it has not been initialized. Make sure that initializeGlobalLogger() has been called before logging. Will use the console as fallback.');
const output: any = {
log: (level: LogLevel, prefix: string, ...object: any[]) => {
// eslint-disable-next-line no-console
console.info(`[UNINITIALIZED GLOBAL LOGGER] ${this.levelIdToString(level)}: ${prefix}:`, object);
},
};
return output;
// throw new Error('Global logger has not been initialized!!');
}
return this.globalLogger_;
}
public static create(prefix: string): LoggerWrapper {
return {
debug: (...object: any[]) => this.globalLogger.log(LogLevel.Debug, prefix, ...object),
info: (...object: any[]) => this.globalLogger.log(LogLevel.Info, prefix, ...object),
warn: (...object: any[]) => this.globalLogger.log(LogLevel.Warn, prefix, ...object),
error: (...object: any[]) => this.globalLogger.log(LogLevel.Error, prefix, ...object),
};
}
public setLevel(level: LogLevel) {
const previous = this.level_;
this.level_ = level;
return previous;
}
public level() {
return this.level_;
}
public targets() {
return this.targets_;
}
public addTarget(type: TargetType, options: TargetOptions|null = null) {
const target = { type: type };
for (const n in options) {
if (!options.hasOwnProperty(n)) continue;
(target as any)[n] = (options as any)[n];
}
this.targets_.push(target);
}
public objectToString(object: any) {
let output = '';
if (typeof object === 'object') {
if (object instanceof Error) {
object = object as any;
output = object.toString();
if (object.code) output += `\nCode: ${object.code}`;
if (object.headers) output += `\nHeader: ${JSON.stringify(object.headers)}`;
if (object.request) output += `\nRequest: ${object.request.substr ? object.request.substr(0, 1024) : ''}`;
if (object.stack) output += `\n${object.stack}`;
} else {
output = JSON.stringify(object);
}
} else {
output = object;
}
return output;
}
public objectsToString(...object: any[]) {
const output = [];
for (let i = 0; i < object.length; i++) {
output.push(`"${this.objectToString(object[i])}"`);
}
return output.join(', ');
}
public static databaseCreateTableSql() {
const output = `
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY,
source TEXT,
level INT NOT NULL,
message TEXT NOT NULL,
\`timestamp\` INT NOT NULL
);
`;
return output.split('\n').join(' ');
}
// Only for database at the moment
public async lastEntries(limit = 100, options: any = null) {
if (options === null) options = {};
if (!options.levels) options.levels = [LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error];
if (!options.levels.length) return [];
for (let i = 0; i < this.targets_.length; i++) {
const target = this.targets_[i];
if (target.type === 'database') {
let sql = `SELECT * FROM logs WHERE level IN (${options.levels.join(',')}) ORDER BY timestamp DESC`;
if (limit !== null) sql += ` LIMIT ${limit}`;
return await target.database.selectAll(sql);
}
}
return [];
}
public targetLevel(target: Target): LogLevel {
if ('level' in target) return target.level as LogLevel;
return this.level();
}
public log(level: LogLevel, prefix: string | null, ...object: any[]) {
if (!this.targets_.length || !this.enabled) return;
for (let i = 0; i < this.targets_.length; i++) {
const target = this.targets_[i];
const targetPrefix = prefix ? prefix : target.prefix;
if (this.targetLevel(target) < level) continue;
if (target.type === 'console') {
let fn = 'log';
if (level === LogLevel.Error) fn = 'error';
if (level === LogLevel.Warn) fn = 'warn';
if (level === LogLevel.Info) fn = 'info';
const consoleObj = target.console ? target.console : console;
let items: any[] = [];
if (target.format) {
const format = level === LogLevel.Info && target.formatInfo ? target.formatInfo : target.format;
const s = sprintf(format, {
date_time: moment().format('YYYY-MM-DD HH:mm:ss'),
level: Logger.levelIdToString(level),
prefix: targetPrefix || '',
message: '',
});
items = [s.trim()].concat(...object);
} else {
const prefixItems = [moment().format('HH:mm:ss')];
if (targetPrefix) prefixItems.push(targetPrefix);
items = [`${prefixItems.join(': ')}:`].concat(...object);
}
consoleObj[fn](...items);
} else if (target.type === 'file') {
const timestamp = moment().format('YYYY-MM-DD HH:mm:ss');
const line = [timestamp];
if (targetPrefix) line.push(targetPrefix);
line.push(this.objectsToString(...object));
// Write to file using a mutex so that log entries appear in the
// correct order (otherwise, since the async call is not awaited
// by caller, multiple log call in a row are not guaranteed to
// appear in the right order). We also can't use a sync call
// because that would slow down the main process, especially
// when many log operations are being done (eg. during sync in
// dev mode).
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
let release: Function|null = null;
/* eslint-disable-next-line promise/prefer-await-to-then, @typescript-eslint/ban-types -- Old code before rule was applied, Old code before rule was applied */
writeToFileMutex_.acquire().then((r: Function) => {
release = r;
return Logger.fsDriver().appendFile(target.path as string, `${line.join(': ')}\n`, 'utf8');
// eslint-disable-next-line promise/prefer-await-to-then -- Old code before rule was applied
}).catch((error: any) => {
console.error('Cannot write to log file:', error);
// eslint-disable-next-line promise/prefer-await-to-then -- Old code before rule was applied
}).finally(() => {
if (release) release();
});
} else if (target.type === 'database') {
const msg = [];
if (targetPrefix) msg.push(targetPrefix);
msg.push(this.objectsToString(...object));
const queries = [
{
sql: 'INSERT INTO logs (`source`, `level`, `message`, `timestamp`) VALUES (?, ?, ?, ?)',
params: [target.source, level, msg.join(': '), Date.now()],
},
];
const now = Date.now();
if (now - this.lastDbCleanup_ > 1000 * 60 * 60) {
this.lastDbCleanup_ = now;
const dayKeep = 14;
queries.push({
sql: 'DELETE FROM logs WHERE `timestamp` < ?',
params: [now - 1000 * 60 * 60 * 24 * dayKeep],
});
}
target.database.transactionExecBatch(queries);
}
}
}
public error(...object: any[]) {
return this.log(LogLevel.Error, null, ...object);
}
public warn(...object: any[]) {
return this.log(LogLevel.Warn, null, ...object);
}
public info(...object: any[]) {
return this.log(LogLevel.Info, null, ...object);
}
public debug(...object: any[]) {
return this.log(LogLevel.Debug, null, ...object);
}
public static levelStringToId(s: string) {
if (s === 'none') return LogLevel.None;
if (s === 'error') return LogLevel.Error;
if (s === 'warn') return LogLevel.Warn;
if (s === 'info') return LogLevel.Info;
if (s === 'debug') return LogLevel.Debug;
throw new Error(`Unknown log level: ${s}`);
}
public static levelIdToString(id: LogLevel) {
if (id === LogLevel.None) return 'none';
if (id === LogLevel.Error) return 'error';
if (id === LogLevel.Warn) return 'warn';
if (id === LogLevel.Info) return 'info';
if (id === LogLevel.Debug) return 'debug';
throw new Error(`Unknown level ID: ${id}`);
}
public static levelIds() {
return [LogLevel.None, LogLevel.Error, LogLevel.Warn, LogLevel.Info, LogLevel.Debug];
}
}
export default Logger;
| packages/utils/Logger.ts | 1 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.9992203712463379,
0.24011752009391785,
0.00016854713612701744,
0.007214929908514023,
0.3726988136768341
]
|
{
"id": 2,
"code_window": [
"\tInfo = 30,\n",
"\tDebug = 40,\n",
"}\n",
"\n",
"interface TargetOptions {\n",
"\tlevel?: LogLevel;\n",
"\tdatabase?: any;\n",
"\tconsole?: any;\n",
"\tprefix?: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"type FormatFunction = (level: LogLevel, targetPrefix?: string)=> string;\n",
"\n"
],
"file_path": "packages/utils/Logger.ts",
"type": "add",
"edit_start_line_idx": 20
} | import { AppContext, KoaNext, NotificationView } from '../utils/types';
import { isApiRequest } from '../utils/requestUtils';
import { NotificationLevel } from '../services/database/types';
import { defaultAdminEmail, defaultAdminPassword } from '../db';
import { _ } from '@joplin/lib/locale';
import Logger from '@joplin/utils/Logger';
import { NotificationKey } from '../models/NotificationModel';
import { helpUrl, profileUrl } from '../utils/urlUtils';
import { userFlagToString } from '../models/UserFlagModel';
import renderMarkdown from '../utils/renderMarkdown';
const logger = Logger.create('notificationHandler');
async function handleChangeAdminPasswordNotification(ctx: AppContext) {
if (!ctx.joplin.owner.is_admin) return;
const defaultAdmin = await ctx.joplin.models.user().login(defaultAdminEmail, defaultAdminPassword);
const notificationModel = ctx.joplin.models.notification();
if (defaultAdmin) {
await notificationModel.add(
ctx.joplin.owner.id,
NotificationKey.ChangeAdminPassword,
NotificationLevel.Important,
_('The default admin password is insecure and has not been changed! [Change it now](%s)', profileUrl()),
);
} else {
await notificationModel.setRead(ctx.joplin.owner.id, NotificationKey.ChangeAdminPassword);
}
}
// Special notification that cannot be dismissed.
async function handleUserFlags(ctx: AppContext): Promise<NotificationView> {
const user = ctx.joplin.owner;
const flags = await ctx.joplin.models.userFlag().allByUserId(ctx.joplin.owner.id);
const flagStrings = flags.map(f => `- ${userFlagToString(f)}`).join('\n');
if (!user.enabled || !user.can_upload) {
return {
id: 'accountDisabled',
messageHtml: renderMarkdown(`Your account is disabled for the following reason(s):\n\n${flagStrings}\n\nPlease check the [help section](${helpUrl()}) for further information or contact support.`),
levelClassName: levelClassName(NotificationLevel.Error),
closeUrl: '',
};
} else if (flags.length) {
// Actually currently all flags result in either disabled upload or
// disabled account, but keeping that here anyway just in case.
return {
id: 'accountFlags',
messageHtml: renderMarkdown(`The following issues have been detected on your account:\n\n${flagStrings}\n\nPlease check the [help section](${helpUrl()}) for further information or contact support.`),
levelClassName: levelClassName(NotificationLevel.Important),
closeUrl: '',
};
}
return null;
}
async function handleConfirmEmailNotification(ctx: AppContext): Promise<NotificationView> {
if (!ctx.joplin.owner) return null;
if (!ctx.joplin.owner.email_confirmed) {
return {
id: 'confirmEmail',
messageHtml: renderMarkdown(`An email has been sent to you containing an activation link to complete your registration. If you did not receive it, you may send it again from [your profile page](${profileUrl()}).\n\nMake sure you click it to secure your account and keep access to it.`),
levelClassName: levelClassName(NotificationLevel.Important),
closeUrl: '',
};
}
return null;
}
// async function handleSqliteInProdNotification(ctx: AppContext) {
// if (!ctx.joplin.owner.is_admin) return;
// const notificationModel = ctx.joplin.models.notification();
// if (config().database.client === 'sqlite3' && ctx.joplin.env === 'prod') {
// await notificationModel.add(
// ctx.joplin.owner.id,
// NotificationKey.UsingSqliteInProd
// );
// }
// }
function levelClassName(level: NotificationLevel): string {
if (level === NotificationLevel.Important) return 'is-warning';
if (level === NotificationLevel.Normal) return 'is-info';
if (level === NotificationLevel.Error) return 'is-danger';
throw new Error(`Unknown level: ${level}`);
}
async function makeNotificationViews(ctx: AppContext): Promise<NotificationView[]> {
const notificationModel = ctx.joplin.models.notification();
const notifications = await notificationModel.allUnreadByUserId(ctx.joplin.owner.id);
const views: NotificationView[] = [];
for (const n of notifications) {
views.push({
id: n.id,
messageHtml: renderMarkdown(n.message),
levelClassName: levelClassName(n.level),
closeUrl: notificationModel.closeUrl(n.id),
});
}
return views;
}
// The role of this middleware is to inspect the system and to generate
// notifications for any issue it finds. It is only active for logged in users
// on the website. It is inactive for API calls.
export default async function(ctx: AppContext, next: KoaNext): Promise<void> {
ctx.joplin.notifications = [];
try {
if (isApiRequest(ctx)) return next();
if (!ctx.joplin.owner) return next();
await handleChangeAdminPasswordNotification(ctx);
await handleConfirmEmailNotification(ctx);
// await handleSqliteInProdNotification(ctx);
const notificationViews = await makeNotificationViews(ctx);
const nonDismisableViews = [
await handleUserFlags(ctx),
await handleConfirmEmailNotification(ctx),
];
for (const nonDismisableView of nonDismisableViews) {
if (nonDismisableView) notificationViews.push(nonDismisableView);
}
ctx.joplin.notifications = notificationViews;
} catch (error) {
logger.error(error);
}
return next();
}
| packages/server/src/middleware/notificationHandler.ts | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.00044564492418430746,
0.00020908127771690488,
0.00016658809909131378,
0.00017045909771695733,
0.0000910111193661578
]
|
{
"id": 2,
"code_window": [
"\tInfo = 30,\n",
"\tDebug = 40,\n",
"}\n",
"\n",
"interface TargetOptions {\n",
"\tlevel?: LogLevel;\n",
"\tdatabase?: any;\n",
"\tconsole?: any;\n",
"\tprefix?: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"type FormatFunction = (level: LogLevel, targetPrefix?: string)=> string;\n",
"\n"
],
"file_path": "packages/utils/Logger.ts",
"type": "add",
"edit_start_line_idx": 20
} | <en-note>
<div>
<audio controls="" preload="none" style="width:480px;">
<source src=":/9168ee833d03c5ea7c730ac6673978c1" type="audio/mp4">
<p>Your browser does not support HTML5 audio.</p>
</audio>
<p><a href=":/9168ee833d03c5ea7c730ac6673978c1">audio test</a></p>
</div>
<div>
<br>
</div>
</en-note> | packages/app-cli/tests/enex_to_html/en-media--audio.html | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.00017209174984600395,
0.0001699231652310118,
0.00016775458061601967,
0.0001699231652310118,
0.0000021685846149921417
]
|
{
"id": 2,
"code_window": [
"\tInfo = 30,\n",
"\tDebug = 40,\n",
"}\n",
"\n",
"interface TargetOptions {\n",
"\tlevel?: LogLevel;\n",
"\tdatabase?: any;\n",
"\tconsole?: any;\n",
"\tprefix?: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"type FormatFunction = (level: LogLevel, targetPrefix?: string)=> string;\n",
"\n"
],
"file_path": "packages/utils/Logger.ts",
"type": "add",
"edit_start_line_idx": 20
} | id: 702aeb4225844c19b85bfbd661e7a298
note_id: f0aabe7de88d47c2ad4ce26d8d5ce70c
tag_id: acbba73d7a1a46848ddc96b96c64ec8b
created_time:
updated_time: 2020-07-25T10:37:00.297Z
user_created_time:
user_updated_time:
encryption_cipher_text: JED0100002205c24138199f5b403fa3e9b8b4f22685c50002d8{"iv":"GyiqQTZ3ifi1IQ6X9FwzUg==","v":1,"iter":101,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"O2duAuTVjV4=","ct":"dhwC/A+NRxH2ol++8l/08RXGm/yuspLrMrXgjkaU/E+Twa0szoc4+bOgyTfV5gWpw9zoxHVDW0sq9R8NeS+nYQiIHNdWJuH8Dq2Qz5BIGca4uK+3InOI9zyD4F7YeP9MPZAPT4Kzj2QPbyschS6YaT1D8nYD2ruBZC9rMUY2o3wnjtDjgIV+vFlbbMQ6PlOQ0dmT76ooGUuq+dc1eWmWgKtXynLQoHg4uuBMfAbd5+o08Tkd1OJReW6He1nSOlmEr25ZzXJoC4BrgeY+BAB+jlYR3wENFzX1fdll6JkETRayuOEqpKPRuKhbgu9xeqzOsIoFGiBbmbANt14s8Vrj9OiazCvzQ9XywGQ3dMpKJZn9uLlDuxb8f9TFREuqXJVGcCK0P0xsmffnR8mfqAYOJHF1i6xDl3frSixghgg3giOHeaG14a9dL/acd1QwSia9ufWMMxxz8ZZPjP0z8edVmg/ItsdbQlt8fGwC0XqHAz5r3eRI3CwiFF1iVfzza5aLqXkyFbctJ5frMiMagpS0iRDPZ9srIVAElrHyYIYm4vTjA39H1BaGyNxb2twpT9T0yGOWyeLDNbdG5A=="}
encryption_applied: 1
is_shared:
type_: 6 | packages/app-cli/tests/support/syncTargetSnapshots/1/e2ee/702aeb4225844c19b85bfbd661e7a298.md | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.001932506449520588,
0.0010534035973250866,
0.00017430067237000912,
0.0010534035973250866,
0.0008791028521955013
]
|
{
"id": 3,
"code_window": [
"\tpath?: string;\n",
"\tsource?: string;\n",
"\n",
"\t// Default message format\n",
"\tformat?: string;\n",
"\n",
"\t// If specified, will use this as format if it's an info message\n",
"\tformatInfo?: string;\n",
"}\n",
"\n",
"interface Target extends TargetOptions {\n",
"\ttype: TargetType;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tformat?: string | FormatFunction;\n"
],
"file_path": "packages/utils/Logger.ts",
"type": "replace",
"edit_start_line_idx": 29
} | const moment = require('moment');
const { sprintf } = require('sprintf-js');
const Mutex = require('async-mutex').Mutex;
const writeToFileMutex_ = new Mutex();
export enum TargetType {
Database = 'database',
File = 'file',
Console = 'console',
}
export enum LogLevel {
None = 0,
Error = 10,
Warn = 20,
Info = 30,
Debug = 40,
}
interface TargetOptions {
level?: LogLevel;
database?: any;
console?: any;
prefix?: string;
path?: string;
source?: string;
// Default message format
format?: string;
// If specified, will use this as format if it's an info message
formatInfo?: string;
}
interface Target extends TargetOptions {
type: TargetType;
}
export interface LoggerWrapper {
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
debug: Function;
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
info: Function;
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
warn: Function;
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
error: Function;
}
interface FsDriver {
appendFile: (path: string, content: string, encoding: string)=> Promise<void>;
}
const dummyFsDriver: FsDriver = {
appendFile: async (_path: string, _content: string, _encoding: string) => {},
};
class Logger {
// For backward compatibility
public static LEVEL_NONE = LogLevel.None;
public static LEVEL_ERROR = LogLevel.Error;
public static LEVEL_WARN = LogLevel.Warn;
public static LEVEL_INFO = LogLevel.Info;
public static LEVEL_DEBUG = LogLevel.Debug;
public static fsDriver_: FsDriver|null = null;
private static globalLogger_: Logger|null = null;
private targets_: Target[] = [];
private level_: LogLevel = LogLevel.Info;
private lastDbCleanup_: number = Date.now();
private enabled_ = true;
public static fsDriver() {
if (!Logger.fsDriver_) Logger.fsDriver_ = dummyFsDriver;
return Logger.fsDriver_;
}
public get enabled(): boolean {
return this.enabled_;
}
public set enabled(v: boolean) {
this.enabled_ = v;
}
public static initializeGlobalLogger(logger: Logger) {
this.globalLogger_ = logger;
}
public static get globalLogger(): Logger {
if (!this.globalLogger_) {
// The global logger normally is initialized early, so we shouldn't
// end up here. However due to early event handlers, it might happen
// and in this case we want to know about it. So we print this
// warning, and also flag the log statements using `[UNINITIALIZED
// GLOBAL LOGGER]` so that we know from where the incorrect log
// statement comes from.
console.warn('Logger: Trying to access globalLogger, but it has not been initialized. Make sure that initializeGlobalLogger() has been called before logging. Will use the console as fallback.');
const output: any = {
log: (level: LogLevel, prefix: string, ...object: any[]) => {
// eslint-disable-next-line no-console
console.info(`[UNINITIALIZED GLOBAL LOGGER] ${this.levelIdToString(level)}: ${prefix}:`, object);
},
};
return output;
// throw new Error('Global logger has not been initialized!!');
}
return this.globalLogger_;
}
public static create(prefix: string): LoggerWrapper {
return {
debug: (...object: any[]) => this.globalLogger.log(LogLevel.Debug, prefix, ...object),
info: (...object: any[]) => this.globalLogger.log(LogLevel.Info, prefix, ...object),
warn: (...object: any[]) => this.globalLogger.log(LogLevel.Warn, prefix, ...object),
error: (...object: any[]) => this.globalLogger.log(LogLevel.Error, prefix, ...object),
};
}
public setLevel(level: LogLevel) {
const previous = this.level_;
this.level_ = level;
return previous;
}
public level() {
return this.level_;
}
public targets() {
return this.targets_;
}
public addTarget(type: TargetType, options: TargetOptions|null = null) {
const target = { type: type };
for (const n in options) {
if (!options.hasOwnProperty(n)) continue;
(target as any)[n] = (options as any)[n];
}
this.targets_.push(target);
}
public objectToString(object: any) {
let output = '';
if (typeof object === 'object') {
if (object instanceof Error) {
object = object as any;
output = object.toString();
if (object.code) output += `\nCode: ${object.code}`;
if (object.headers) output += `\nHeader: ${JSON.stringify(object.headers)}`;
if (object.request) output += `\nRequest: ${object.request.substr ? object.request.substr(0, 1024) : ''}`;
if (object.stack) output += `\n${object.stack}`;
} else {
output = JSON.stringify(object);
}
} else {
output = object;
}
return output;
}
public objectsToString(...object: any[]) {
const output = [];
for (let i = 0; i < object.length; i++) {
output.push(`"${this.objectToString(object[i])}"`);
}
return output.join(', ');
}
public static databaseCreateTableSql() {
const output = `
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY,
source TEXT,
level INT NOT NULL,
message TEXT NOT NULL,
\`timestamp\` INT NOT NULL
);
`;
return output.split('\n').join(' ');
}
// Only for database at the moment
public async lastEntries(limit = 100, options: any = null) {
if (options === null) options = {};
if (!options.levels) options.levels = [LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error];
if (!options.levels.length) return [];
for (let i = 0; i < this.targets_.length; i++) {
const target = this.targets_[i];
if (target.type === 'database') {
let sql = `SELECT * FROM logs WHERE level IN (${options.levels.join(',')}) ORDER BY timestamp DESC`;
if (limit !== null) sql += ` LIMIT ${limit}`;
return await target.database.selectAll(sql);
}
}
return [];
}
public targetLevel(target: Target): LogLevel {
if ('level' in target) return target.level as LogLevel;
return this.level();
}
public log(level: LogLevel, prefix: string | null, ...object: any[]) {
if (!this.targets_.length || !this.enabled) return;
for (let i = 0; i < this.targets_.length; i++) {
const target = this.targets_[i];
const targetPrefix = prefix ? prefix : target.prefix;
if (this.targetLevel(target) < level) continue;
if (target.type === 'console') {
let fn = 'log';
if (level === LogLevel.Error) fn = 'error';
if (level === LogLevel.Warn) fn = 'warn';
if (level === LogLevel.Info) fn = 'info';
const consoleObj = target.console ? target.console : console;
let items: any[] = [];
if (target.format) {
const format = level === LogLevel.Info && target.formatInfo ? target.formatInfo : target.format;
const s = sprintf(format, {
date_time: moment().format('YYYY-MM-DD HH:mm:ss'),
level: Logger.levelIdToString(level),
prefix: targetPrefix || '',
message: '',
});
items = [s.trim()].concat(...object);
} else {
const prefixItems = [moment().format('HH:mm:ss')];
if (targetPrefix) prefixItems.push(targetPrefix);
items = [`${prefixItems.join(': ')}:`].concat(...object);
}
consoleObj[fn](...items);
} else if (target.type === 'file') {
const timestamp = moment().format('YYYY-MM-DD HH:mm:ss');
const line = [timestamp];
if (targetPrefix) line.push(targetPrefix);
line.push(this.objectsToString(...object));
// Write to file using a mutex so that log entries appear in the
// correct order (otherwise, since the async call is not awaited
// by caller, multiple log call in a row are not guaranteed to
// appear in the right order). We also can't use a sync call
// because that would slow down the main process, especially
// when many log operations are being done (eg. during sync in
// dev mode).
// eslint-disable-next-line @typescript-eslint/ban-types -- Old code before rule was applied
let release: Function|null = null;
/* eslint-disable-next-line promise/prefer-await-to-then, @typescript-eslint/ban-types -- Old code before rule was applied, Old code before rule was applied */
writeToFileMutex_.acquire().then((r: Function) => {
release = r;
return Logger.fsDriver().appendFile(target.path as string, `${line.join(': ')}\n`, 'utf8');
// eslint-disable-next-line promise/prefer-await-to-then -- Old code before rule was applied
}).catch((error: any) => {
console.error('Cannot write to log file:', error);
// eslint-disable-next-line promise/prefer-await-to-then -- Old code before rule was applied
}).finally(() => {
if (release) release();
});
} else if (target.type === 'database') {
const msg = [];
if (targetPrefix) msg.push(targetPrefix);
msg.push(this.objectsToString(...object));
const queries = [
{
sql: 'INSERT INTO logs (`source`, `level`, `message`, `timestamp`) VALUES (?, ?, ?, ?)',
params: [target.source, level, msg.join(': '), Date.now()],
},
];
const now = Date.now();
if (now - this.lastDbCleanup_ > 1000 * 60 * 60) {
this.lastDbCleanup_ = now;
const dayKeep = 14;
queries.push({
sql: 'DELETE FROM logs WHERE `timestamp` < ?',
params: [now - 1000 * 60 * 60 * 24 * dayKeep],
});
}
target.database.transactionExecBatch(queries);
}
}
}
public error(...object: any[]) {
return this.log(LogLevel.Error, null, ...object);
}
public warn(...object: any[]) {
return this.log(LogLevel.Warn, null, ...object);
}
public info(...object: any[]) {
return this.log(LogLevel.Info, null, ...object);
}
public debug(...object: any[]) {
return this.log(LogLevel.Debug, null, ...object);
}
public static levelStringToId(s: string) {
if (s === 'none') return LogLevel.None;
if (s === 'error') return LogLevel.Error;
if (s === 'warn') return LogLevel.Warn;
if (s === 'info') return LogLevel.Info;
if (s === 'debug') return LogLevel.Debug;
throw new Error(`Unknown log level: ${s}`);
}
public static levelIdToString(id: LogLevel) {
if (id === LogLevel.None) return 'none';
if (id === LogLevel.Error) return 'error';
if (id === LogLevel.Warn) return 'warn';
if (id === LogLevel.Info) return 'info';
if (id === LogLevel.Debug) return 'debug';
throw new Error(`Unknown level ID: ${id}`);
}
public static levelIds() {
return [LogLevel.None, LogLevel.Error, LogLevel.Warn, LogLevel.Info, LogLevel.Debug];
}
}
export default Logger;
| packages/utils/Logger.ts | 1 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.9989042282104492,
0.2683289051055908,
0.00016647251322865486,
0.00017621059669181705,
0.42850008606910706
]
|
{
"id": 3,
"code_window": [
"\tpath?: string;\n",
"\tsource?: string;\n",
"\n",
"\t// Default message format\n",
"\tformat?: string;\n",
"\n",
"\t// If specified, will use this as format if it's an info message\n",
"\tformatInfo?: string;\n",
"}\n",
"\n",
"interface Target extends TargetOptions {\n",
"\ttype: TargetType;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tformat?: string | FormatFunction;\n"
],
"file_path": "packages/utils/Logger.ts",
"type": "replace",
"edit_start_line_idx": 29
} | // AUTO-GENERATED using `gulp buildCommandIndex`
import * as focusElementSideBar from './focusElementSideBar';
const index:any[] = [
focusElementSideBar,
];
export default index;
// AUTO-GENERATED using `gulp buildCommandIndex`
| packages/app-desktop/gui/Sidebar/commands/index.ts | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.00017734729044605047,
0.00017734729044605047,
0.00017734729044605047,
0.00017734729044605047,
0
]
|
{
"id": 3,
"code_window": [
"\tpath?: string;\n",
"\tsource?: string;\n",
"\n",
"\t// Default message format\n",
"\tformat?: string;\n",
"\n",
"\t// If specified, will use this as format if it's an info message\n",
"\tformatInfo?: string;\n",
"}\n",
"\n",
"interface Target extends TargetOptions {\n",
"\ttype: TargetType;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tformat?: string | FormatFunction;\n"
],
"file_path": "packages/utils/Logger.ts",
"type": "replace",
"edit_start_line_idx": 29
} | import * as fs from 'fs-extra';
import { fileExtension } from '@joplin/lib/path-utils';
import { gitHubLatestRelease, GitHubRelease } from './tool-utils';
const readmePath = `${__dirname}/../../README.md`;
async function msleep(ms: number) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(null);
}, ms);
});
}
export enum OS {
MacOs = 'macos',
Windows = 'windows',
Android = 'android',
Android32 = 'android32',
Linux = 'linux',
}
export const downloadUrl = (release: GitHubRelease, os: OS, portable = false) => {
if (!release || !release.assets || !release.assets.length) return null;
for (let i = 0; i < release.assets.length; i++) {
const asset = release.assets[i];
const name = asset.name;
const ext = fileExtension(name);
const githubAndroidUrl = 'github.com/laurent22/joplin-android/releases/download/android-';
const githubUrl = 'github.com/laurent22/joplin/releases/download/';
const joplinDomain = 'objects.joplinusercontent.com/';
if (ext === 'dmg' && os === OS.MacOs) return asset.browser_download_url.replace(githubUrl, joplinDomain);
if (ext === 'exe' && os === OS.Windows) {
if (portable) {
if (name === 'JoplinPortable.exe') return asset.browser_download_url.replace(githubUrl, joplinDomain);
} else {
if (name.match(/^Joplin-Setup-[\d.]+\.exe$/)) return asset.browser_download_url.replace(githubUrl, joplinDomain);
}
}
if (ext === 'AppImage' && os === OS.Linux) return asset.browser_download_url.replace(githubUrl, joplinDomain);
if (os === OS.Android32 && name.endsWith('32bit.apk')) return asset.browser_download_url.replace(githubAndroidUrl, joplinDomain);
if (os === OS.Android && ext === 'apk' && !name.endsWith('32bit.apk')) return asset.browser_download_url.replace(githubAndroidUrl, joplinDomain);
}
throw new Error(`Could not find download URL for: ${os}`);
};
function readmeContent() {
if (!fs.existsSync(readmePath)) throw new Error(`Cannot find ${readmePath}`);
return fs.readFileSync(readmePath, 'utf8');
}
function setReadmeContent(content: string) {
if (!fs.existsSync(readmePath)) throw new Error(`Cannot find ${readmePath}`);
return fs.writeFileSync(readmePath, content);
}
async function main(argv: any) {
const waitForVersion = argv.length === 3 ? argv[2] : null;
if (waitForVersion) console.info(`Waiting for version ${waitForVersion} to be released before updating readme...`);
let release = null;
while (true) {
release = await gitHubLatestRelease('joplin');
if (!waitForVersion) break;
if (release.tag_name !== waitForVersion) {
await msleep(60000 * 5);
} else {
console.info(`Got version ${waitForVersion}`);
break;
}
}
const androidRelease = await gitHubLatestRelease('joplin-android');
// const android32Url = downloadUrl(androidRelease, OS.Android32);
const androidUrl = downloadUrl(androidRelease, OS.Android);
const winUrl = downloadUrl(release, OS.Windows);
const winPortableUrl = downloadUrl(release, OS.Windows, true);
const macOsUrl = downloadUrl(release, OS.MacOs);
const linuxUrl = downloadUrl(release, OS.Linux);
console.info('Windows: ', winUrl);
console.info('Windows Portable: ', winPortableUrl);
console.info('macOS: ', macOsUrl);
console.info('Linux: ', linuxUrl);
console.info('Android: ', androidUrl);
// console.info('Android 32: ', android32Url);
let content = readmeContent();
if (winUrl) content = content.replace(/(https:\/\/objects.joplinusercontent.com\/v\d+\.\d+\.\d+\/Joplin-Setup-.*?\.exe)/, winUrl);
if (winPortableUrl) content = content.replace(/(https:\/\/objects.joplinusercontent.com\/v\d+\.\d+\.\d+\/JoplinPortable.exe)/, winPortableUrl);
if (macOsUrl) content = content.replace(/(https:\/\/objects.joplinusercontent.com\/v\d+\.\d+\.\d+\/Joplin-.*?\.dmg)/, macOsUrl);
if (linuxUrl) content = content.replace(/(https:\/\/objects.joplinusercontent.com\/v\d+\.\d+\.\d+\/Joplin-.*?\.AppImage)/, linuxUrl);
if (androidUrl) content = content.replace(/(https:\/\/objects.joplinusercontent.com\/v\d+\.\d+\.\d+\/joplin-v\d+\.\d+\.\d+\.apk)/, androidUrl);
// if (android32Url) content = content.replace(/(https:\/\/objects.joplinusercontent.com\/v\d+\.\d+\.\d+\/joplin-v\d+\.\d+\.\d+-32bit\.apk)/, android32Url);
setReadmeContent(content);
}
if (require.main === module) {
// eslint-disable-next-line promise/prefer-await-to-then
main(process.argv).catch((error) => {
console.error('Fatal error');
console.error(error);
process.exit(1);
});
}
| packages/tools/update-readme-download.ts | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.00017701700562611222,
0.000174203552887775,
0.00016785459592938423,
0.00017498337547294796,
0.0000026501497814024333
]
|
{
"id": 3,
"code_window": [
"\tpath?: string;\n",
"\tsource?: string;\n",
"\n",
"\t// Default message format\n",
"\tformat?: string;\n",
"\n",
"\t// If specified, will use this as format if it's an info message\n",
"\tformatInfo?: string;\n",
"}\n",
"\n",
"interface Target extends TargetOptions {\n",
"\ttype: TargetType;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tformat?: string | FormatFunction;\n"
],
"file_path": "packages/utils/Logger.ts",
"type": "replace",
"edit_start_line_idx": 29
} | import { CreateMenuItemOptions, MenuItemLocation } from './types';
import Plugin from '../Plugin';
/**
* Allows creating and managing menu items.
*
* [View the demo plugin](https://github.com/laurent22/joplin/tree/dev/packages/app-cli/tests/support/plugins/register_command)
*/
export default class JoplinViewsMenuItems {
private store;
private plugin;
constructor(plugin: Plugin, store: any);
/**
* Creates a new menu item and associate it with the given command. You can specify under which menu the item should appear using the `location` parameter.
*/
create(id: string, commandName: string, location?: MenuItemLocation, options?: CreateMenuItemOptions): Promise<void>;
}
| packages/app-cli/tests/support/plugins/settings/api/JoplinViewsMenuItems.d.ts | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.00017039102385751903,
0.00016812565445434302,
0.000165860285051167,
0.00016812565445434302,
0.0000022653694031760097
]
|
{
"id": 4,
"code_window": [
"\t\t\t\tlet items: any[] = [];\n",
"\n",
"\t\t\t\tif (target.format) {\n",
"\t\t\t\t\tconst format = level === LogLevel.Info && target.formatInfo ? target.formatInfo : target.format;\n",
"\n",
"\t\t\t\t\tconst s = sprintf(format, {\n",
"\t\t\t\t\t\tdate_time: moment().format('YYYY-MM-DD HH:mm:ss'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst format = typeof target.format === 'string' ? target.format : target.format(level, targetPrefix);\n"
],
"file_path": "packages/utils/Logger.ts",
"type": "replace",
"edit_start_line_idx": 230
} | // Allows displaying error stack traces with TypeScript file paths
require('source-map-support').install();
import * as Koa from 'koa';
import * as fs from 'fs-extra';
import Logger, { LoggerWrapper, TargetType } from '@joplin/utils/Logger';
import config, { fullVersionString, initConfig, runningInDocker } from './config';
import { migrateLatest, waitForConnection, sqliteDefaultDir, latestMigration, needsMigration, migrateList } from './db';
import { AppContext, Env, KoaNext } from './utils/types';
import FsDriverNode from '@joplin/lib/fs-driver-node';
import { getDeviceTimeDrift } from '@joplin/lib/ntp';
import routeHandler from './middleware/routeHandler';
import notificationHandler from './middleware/notificationHandler';
import ownerHandler from './middleware/ownerHandler';
import setupAppContext from './utils/setupAppContext';
import { initializeJoplinUtils } from './utils/joplinUtils';
import startServices from './utils/startServices';
import { credentialFile } from './utils/testing/testUtils';
import apiVersionHandler from './middleware/apiVersionHandler';
import clickJackingHandler from './middleware/clickJackingHandler';
import newModelFactory from './models/factory';
import setupCommands from './utils/setupCommands';
import { RouteResponseFormat, routeResponseFormat } from './utils/routeUtils';
import { parseEnv } from './env';
import { parseEnvFile } from '@joplin/utils/env';
import storageConnectionCheck from './utils/storageConnectionCheck';
import { setLocale } from '@joplin/lib/locale';
import initLib from '@joplin/lib/initLib';
import checkAdminHandler from './middleware/checkAdminHandler';
interface Argv {
env?: Env;
pidfile?: string;
envFile?: string;
}
const nodeSqlite = require('sqlite3');
const cors = require('@koa/cors');
const { shimInit } = require('@joplin/lib/shim-init-node.js');
shimInit({ nodeSqlite });
const defaultEnvVariables: Record<Env, any> = {
dev: {
// To test with the Postgres database, uncomment DB_CLIENT below and
// comment out SQLITE_DATABASE. Then start the Postgres server using
// `docker-compose --file docker-compose.db-dev.yml up`
// DB_CLIENT: 'pg',
SQLITE_DATABASE: `${sqliteDefaultDir}/db-dev.sqlite`,
},
buildTypes: {
SQLITE_DATABASE: `${sqliteDefaultDir}/db-buildTypes.sqlite`,
},
prod: {
SQLITE_DATABASE: `${sqliteDefaultDir}/db-prod.sqlite`,
},
};
let appLogger_: LoggerWrapper = null;
function appLogger(): LoggerWrapper {
if (!appLogger_) {
appLogger_ = Logger.create('App');
}
return appLogger_;
}
function markPasswords(o: Record<string, any>): Record<string, any> {
if (!o) return o;
const output: Record<string, any> = {};
for (const k of Object.keys(o)) {
if (k.toLowerCase().includes('password') || k.toLowerCase().includes('secret') || k.toLowerCase().includes('connectionstring')) {
output[k] = '********';
} else {
output[k] = o[k];
}
}
return output;
}
async function getEnvFilePath(env: Env, argv: any): Promise<string> {
if (argv.envFile) return argv.envFile;
if (env === Env.Dev) {
return credentialFile('server.env');
}
return '';
}
async function main() {
const { selectedCommand, argv: yargsArgv } = await setupCommands();
const argv: Argv = yargsArgv as any;
const env: Env = argv.env as Env || Env.Prod;
const envFilePath = await getEnvFilePath(env, argv);
let envFromFile: Record<string, string> = {};
try {
if (envFilePath) envFromFile = parseEnvFile(envFilePath);
} catch (error) {
error.message = `Could not parse env file at ${envFilePath}: ${error.message}`;
throw error;
}
const fullEnv = {
...envFromFile,
...process.env,
};
if (!defaultEnvVariables[env]) throw new Error(`Invalid env: ${env}`);
const envVariables = parseEnv(fullEnv, defaultEnvVariables[env]);
const app = new Koa();
// Note: the order of middlewares is important. For example, ownerHandler
// loads the user, which is then used by notificationHandler. And finally
// routeHandler uses data from both previous middlewares. It would be good to
// layout these dependencies in code but not clear how to do this.
const corsAllowedDomains = [
'https://joplinapp.org',
];
if (env === Env.Dev) {
corsAllowedDomains.push('http://localhost:8077');
}
function acceptOrigin(origin: string): boolean {
const hostname = (new URL(origin)).hostname;
const userContentDomain = envVariables.USER_CONTENT_BASE_URL ? (new URL(envVariables.USER_CONTENT_BASE_URL)).hostname : '';
if (hostname === userContentDomain) return true;
const hostnameNoSub = hostname.split('.').slice(1).join('.');
// console.info('CORS check for origin', origin, 'Allowed domains', corsAllowedDomains);
if (hostnameNoSub === userContentDomain) return true;
if (corsAllowedDomains.includes(origin)) return true;
return false;
}
// This is used to catch any low level error thrown from a middleware. It
// won't deal with errors from routeHandler, which catches and handles its
// own errors.
app.use(async (ctx: AppContext, next: KoaNext) => {
try {
await next();
} catch (error) {
ctx.status = error.httpCode || 500;
appLogger().error(`Middleware error on ${ctx.path}:`, error);
const responseFormat = routeResponseFormat(ctx);
if (responseFormat === RouteResponseFormat.Html) {
// Since this is a low level error, rendering a view might fail too,
// so catch this and default to rendering JSON.
try {
ctx.response.set('Content-Type', 'text/html');
ctx.body = await ctx.joplin.services.mustache.renderView({
name: 'error',
title: 'Error',
path: 'index/error',
content: { error },
});
} catch (anotherError) {
ctx.response.set('Content-Type', 'application/json');
ctx.body = JSON.stringify({ error: `${error.message} (Check the server log for more information)` });
}
} else {
ctx.response.set('Content-Type', 'application/json');
ctx.body = JSON.stringify({ error: error.message });
}
}
});
// Creates the request-specific "joplin" context property.
app.use(async (ctx: AppContext, next: KoaNext) => {
ctx.joplin = {
...ctx.joplinBase,
owner: null,
notifications: [],
};
return next();
});
app.use(cors({
// https://github.com/koajs/cors/issues/52#issuecomment-413887382
origin: (ctx: AppContext) => {
const origin = ctx.request.header.origin;
if (acceptOrigin(origin)) {
return origin;
} else {
// we can't return void, so let's return one of the valid domains
return corsAllowedDomains[0];
}
},
}));
app.use(apiVersionHandler);
app.use(ownerHandler);
app.use(checkAdminHandler);
app.use(notificationHandler);
app.use(clickJackingHandler);
app.use(routeHandler);
await initConfig(env, envVariables);
await fs.mkdirp(config().logDir);
await fs.mkdirp(config().tempDir);
Logger.fsDriver_ = new FsDriverNode();
const globalLogger = new Logger();
const instancePrefix = config().INSTANCE_NAME ? `${config().INSTANCE_NAME}: ` : '';
globalLogger.addTarget(TargetType.Console, {
format: `%(date_time)s: ${instancePrefix}[%(level)s] %(prefix)s: %(message)s`,
formatInfo: `%(date_time)s: ${instancePrefix}%(prefix)s: %(message)s`,
});
Logger.initializeGlobalLogger(globalLogger);
initLib(globalLogger);
if (envFilePath) appLogger().info(`Env variables were loaded from: ${envFilePath}`);
const pidFile = argv.pidfile as string;
if (pidFile) {
appLogger().info(`Writing PID to ${pidFile}...`);
fs.removeSync(pidFile as string);
fs.writeFileSync(pidFile, `${process.pid}`);
}
let runCommandAndExitApp = true;
if (selectedCommand) {
const commandArgv = {
...argv,
_: (argv as any)._.slice(),
};
commandArgv._.splice(0, 1);
if (selectedCommand.commandName() === 'db') {
await selectedCommand.run(commandArgv, {
db: null,
models: null,
});
} else {
const connectionCheck = await waitForConnection(config().database);
const models = newModelFactory(connectionCheck.connection, config());
await selectedCommand.run(commandArgv, {
db: connectionCheck.connection,
models,
});
}
} else {
runCommandAndExitApp = false;
appLogger().info(`Starting server ${fullVersionString(config())} (${env}) on port ${config().port} and PID ${process.pid}...`);
if (config().maxTimeDrift) {
appLogger().info(`Checking for time drift using NTP server: ${config().NTP_SERVER}`);
const timeDrift = await getDeviceTimeDrift(config().NTP_SERVER);
if (Math.abs(timeDrift) > config().maxTimeDrift) {
throw new Error(`The device time drift is ${timeDrift}ms (Max allowed: ${config().maxTimeDrift}ms) - cannot continue as it could cause data loss and conflicts on the sync clients. You may increase env var MAX_TIME_DRIFT to pass the check, or set to 0 to disabled the check.`);
}
appLogger().info(`NTP time offset: ${timeDrift}ms`);
} else {
appLogger().info('Skipping NTP time check because MAX_TIME_DRIFT is 0.');
}
setLocale('en_GB');
appLogger().info('Running in Docker:', runningInDocker());
appLogger().info('Public base URL:', config().baseUrl);
appLogger().info('API base URL:', config().apiBaseUrl);
appLogger().info('User content base URL:', config().userContentBaseUrl);
appLogger().info('Log dir:', config().logDir);
appLogger().info('DB Config:', markPasswords(config().database));
appLogger().info('Mailer Config:', markPasswords(config().mailer));
appLogger().info('Content driver:', markPasswords(config().storageDriver));
appLogger().info('Content driver (fallback):', markPasswords(config().storageDriverFallback));
appLogger().info('Trying to connect to database...');
const connectionCheck = await waitForConnection(config().database);
const connectionCheckLogInfo = { ...connectionCheck };
delete connectionCheckLogInfo.connection;
appLogger().info('Connection check:', connectionCheckLogInfo);
const ctx = app.context as AppContext;
if (config().database.autoMigration) {
appLogger().info('Auto-migrating database...');
await migrateLatest(connectionCheck.connection);
appLogger().info('Latest migration:', await latestMigration(connectionCheck.connection));
} else {
if (!config().DB_ALLOW_INCOMPLETE_MIGRATIONS && (await needsMigration(connectionCheck.connection))) {
const list = await migrateList(connectionCheck.connection, true);
throw new Error(`One or more migrations need to be applied:\n\n${list}`);
}
appLogger().info('Skipped database auto-migration.');
}
await setupAppContext(ctx, env, connectionCheck.connection, appLogger);
await initializeJoplinUtils(config(), ctx.joplinBase.models, ctx.joplinBase.services.mustache);
appLogger().info('Performing main storage check...');
appLogger().info(await storageConnectionCheck(config().storageDriver, ctx.joplinBase.db, ctx.joplinBase.models));
if (config().storageDriverFallback) {
appLogger().info('Performing fallback storage check...');
appLogger().info(await storageConnectionCheck(config().storageDriverFallback, ctx.joplinBase.db, ctx.joplinBase.models));
}
appLogger().info('Starting services...');
await startServices(config(), ctx.joplinBase.services);
appLogger().info(`Call this for testing: \`curl ${config().apiBaseUrl}/api/ping\``);
app.listen(config().port);
}
if (runCommandAndExitApp) process.exit(0);
}
main().catch((error: any) => {
console.error(error);
process.exit(1);
});
| packages/server/src/app.ts | 1 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.9786903858184814,
0.028437435626983643,
0.00016271606727968901,
0.00017147666949313134,
0.16296879947185516
]
|
{
"id": 4,
"code_window": [
"\t\t\t\tlet items: any[] = [];\n",
"\n",
"\t\t\t\tif (target.format) {\n",
"\t\t\t\t\tconst format = level === LogLevel.Info && target.formatInfo ? target.formatInfo : target.format;\n",
"\n",
"\t\t\t\t\tconst s = sprintf(format, {\n",
"\t\t\t\t\t\tdate_time: moment().format('YYYY-MM-DD HH:mm:ss'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst format = typeof target.format === 'string' ? target.format : target.format(level, targetPrefix);\n"
],
"file_path": "packages/utils/Logger.ts",
"type": "replace",
"edit_start_line_idx": 230
} | import DomHandler, { DomHandlerOptions, Element } from "domhandler";
import * as DomUtils from "domutils";
import { Parser, ParserOptions } from "./Parser";
interface FeedItem {
id?: string;
title?: string;
link?: string;
description?: string;
pubDate?: Date;
}
interface Feed {
type?: string;
id?: string;
title?: string;
link?: string;
description?: string;
updated?: Date;
author?: string;
items?: FeedItem[];
}
//TODO: Consume data as it is coming in
export class FeedHandler extends DomHandler {
feed?: Feed;
/**
*
* @param callback
* @param options
*/
constructor(
callback?: ((error: Error | null) => void) | DomHandlerOptions,
options?: DomHandlerOptions
) {
if (typeof callback === "object" && callback !== null) {
callback = undefined;
options = callback;
}
super(callback, options);
}
onend() {
const feed: Feed = {};
const feedRoot = getOneElement(isValidFeed, this.dom);
if (feedRoot) {
if (feedRoot.name === "feed") {
const childs = feedRoot.children;
feed.type = "atom";
addConditionally(feed, "id", "id", childs);
addConditionally(feed, "title", "title", childs);
const href = getAttribute(
"href",
getOneElement("link", childs)
);
if (href) {
feed.link = href;
}
addConditionally(feed, "description", "subtitle", childs);
const updated = fetch("updated", childs);
if (updated) {
feed.updated = new Date(updated);
}
addConditionally(feed, "author", "email", childs, true);
feed.items = getElements("entry", childs).map(item => {
const entry: FeedItem = {};
const { children } = item;
addConditionally(entry, "id", "id", children);
addConditionally(entry, "title", "title", children);
const href = getAttribute(
"href",
getOneElement("link", children)
);
if (href) {
entry.link = href;
}
const description =
fetch("summary", children) ||
fetch("content", children);
if (description) {
entry.description = description;
}
const pubDate = fetch("updated", children);
if (pubDate) {
entry.pubDate = new Date(pubDate);
}
return entry;
});
} else {
const childs = getOneElement("channel", feedRoot.children)
.children;
feed.type = feedRoot.name.substr(0, 3);
feed.id = "";
addConditionally(feed, "title", "title", childs);
addConditionally(feed, "link", "link", childs);
addConditionally(feed, "description", "description", childs);
const updated = fetch("lastBuildDate", childs);
if (updated) {
feed.updated = new Date(updated);
}
addConditionally(
feed,
"author",
"managingEditor",
childs,
true
);
feed.items = getElements("item", feedRoot.children).map(
(item: Element) => {
const entry: FeedItem = {};
const { children } = item;
addConditionally(entry, "id", "guid", children);
addConditionally(entry, "title", "title", children);
addConditionally(entry, "link", "link", children);
addConditionally(
entry,
"description",
"description",
children
);
const pubDate = fetch("pubDate", children);
if (pubDate) entry.pubDate = new Date(pubDate);
return entry;
}
);
}
}
this.feed = feed;
this.handleCallback(
feedRoot ? null : Error("couldn't find root of feed")
);
}
}
function getElements(what: string, where: any) {
return DomUtils.getElementsByTagName(what, where, true);
}
function getOneElement(
what: string | ((name: string) => boolean),
where: any
) {
return DomUtils.getElementsByTagName(what, where, true, 1)[0];
}
function fetch(what: string, where: any, recurse = false): string {
return DomUtils.getText(
DomUtils.getElementsByTagName(what, where, recurse, 1)
).trim();
}
function getAttribute(name: string, elem: Element | null): string | null {
if (!elem) {
return null;
}
const { attribs } = elem;
return attribs[name];
}
function addConditionally<T>(
obj: T,
prop: keyof T,
what: string,
where: any,
recurse = false
) {
const tmp = fetch(what, where, recurse);
if (tmp) (obj as any)[prop] = tmp;
}
function isValidFeed(value: string) {
return value === "rss" || value === "feed" || value === "rdf:RDF";
}
const defaultOptions = { xmlMode: true };
/**
* Parse a feed.
*
* @param feed The feed that should be parsed, as a string.
* @param options Optionally, options for parsing. When using this option, you probably want to set `xmlMode` to `true`.
*/
export function parseFeed(
feed: string,
options: ParserOptions & DomHandlerOptions = defaultOptions
): Feed | undefined {
const handler = new FeedHandler(options);
new Parser(handler, options).end(feed);
return handler.feed;
}
| packages/fork-htmlparser2/src/FeedHandler.ts | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.9484091997146606,
0.04666899889707565,
0.00016557176422793418,
0.00017241893510799855,
0.20172037184238434
]
|
{
"id": 4,
"code_window": [
"\t\t\t\tlet items: any[] = [];\n",
"\n",
"\t\t\t\tif (target.format) {\n",
"\t\t\t\t\tconst format = level === LogLevel.Info && target.formatInfo ? target.formatInfo : target.format;\n",
"\n",
"\t\t\t\t\tconst s = sprintf(format, {\n",
"\t\t\t\t\t\tdate_time: moment().format('YYYY-MM-DD HH:mm:ss'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst format = typeof target.format === 'string' ? target.format : target.format(level, targetPrefix);\n"
],
"file_path": "packages/utils/Logger.ts",
"type": "replace",
"edit_start_line_idx": 230
} | *.md
!README.md
/*.jpl
/api
/src
/dist
tsconfig.json
webpack.config.js
| packages/app-cli/tests/support/plugins/codemirror_content_script/.npmignore | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.00017246563220396638,
0.00017246563220396638,
0.00017246563220396638,
0.00017246563220396638,
0
]
|
{
"id": 4,
"code_window": [
"\t\t\t\tlet items: any[] = [];\n",
"\n",
"\t\t\t\tif (target.format) {\n",
"\t\t\t\t\tconst format = level === LogLevel.Info && target.formatInfo ? target.formatInfo : target.format;\n",
"\n",
"\t\t\t\t\tconst s = sprintf(format, {\n",
"\t\t\t\t\t\tdate_time: moment().format('YYYY-MM-DD HH:mm:ss'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst format = typeof target.format === 'string' ? target.format : target.format(level, targetPrefix);\n"
],
"file_path": "packages/utils/Logger.ts",
"type": "replace",
"edit_start_line_idx": 230
} | {
"lockfileVersion": 1
}
| packages/app-cli/tests/support/plugins/simple/package-lock.json | 0 | https://github.com/laurent22/joplin/commit/ddc74af3d1ec8940dc20b54f9ed1fa3c47eccdbc | [
0.00017152279906440526,
0.00017152279906440526,
0.00017152279906440526,
0.00017152279906440526,
0
]
|
{
"id": 0,
"code_window": [
" compilerOptions.noUnusedLocals = false;\n",
" compilerOptions.preserveConstEnums = false;\n",
" compilerOptions.declaration = false;\n",
" compilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;\n",
" options.compilerOptions = compilerOptions;\n",
" let result = tss.shake(options);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" compilerOptions.noImplicitAny = false;\n"
],
"file_path": "build/lib/standalone.js",
"type": "add",
"edit_start_line_idx": 42
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as ts from 'typescript';
import * as fs from 'fs';
import * as path from 'path';
import * as tss from './treeshaking';
const REPO_ROOT = path.join(__dirname, '../../');
const SRC_DIR = path.join(REPO_ROOT, 'src');
let dirCache: { [dir: string]: boolean; } = {};
function writeFile(filePath: string, contents: Buffer | string): void {
function ensureDirs(dirPath: string): void {
if (dirCache[dirPath]) {
return;
}
dirCache[dirPath] = true;
ensureDirs(path.dirname(dirPath));
if (fs.existsSync(dirPath)) {
return;
}
fs.mkdirSync(dirPath);
}
ensureDirs(path.dirname(filePath));
fs.writeFileSync(filePath, contents);
}
export function extractEditor(options: tss.ITreeShakingOptions & { destRoot: string }): void {
const tsConfig = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.monaco.json')).toString());
let compilerOptions: { [key: string]: any };
if (tsConfig.extends) {
compilerOptions = Object.assign({}, require(path.join(options.sourcesRoot, tsConfig.extends)).compilerOptions, tsConfig.compilerOptions);
} else {
compilerOptions = tsConfig.compilerOptions;
}
tsConfig.compilerOptions = compilerOptions;
compilerOptions.noEmit = false;
compilerOptions.noUnusedLocals = false;
compilerOptions.preserveConstEnums = false;
compilerOptions.declaration = false;
compilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;
options.compilerOptions = compilerOptions;
let result = tss.shake(options);
for (let fileName in result) {
if (result.hasOwnProperty(fileName)) {
writeFile(path.join(options.destRoot, fileName), result[fileName]);
}
}
let copied: { [fileName: string]: boolean; } = {};
const copyFile = (fileName: string) => {
if (copied[fileName]) {
return;
}
copied[fileName] = true;
const srcPath = path.join(options.sourcesRoot, fileName);
const dstPath = path.join(options.destRoot, fileName);
writeFile(dstPath, fs.readFileSync(srcPath));
};
const writeOutputFile = (fileName: string, contents: string | Buffer) => {
writeFile(path.join(options.destRoot, fileName), contents);
};
for (let fileName in result) {
if (result.hasOwnProperty(fileName)) {
const fileContents = result[fileName];
const info = ts.preProcessFile(fileContents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFileName = info.importedFiles[i].fileName;
let importedFilePath: string;
if (/^vs\/css!/.test(importedFileName)) {
importedFilePath = importedFileName.substr('vs/css!'.length) + '.css';
} else {
importedFilePath = importedFileName;
}
if (/(^\.\/)|(^\.\.\/)/.test(importedFilePath)) {
importedFilePath = path.join(path.dirname(fileName), importedFilePath);
}
if (/\.css$/.test(importedFilePath)) {
transportCSS(importedFilePath, copyFile, writeOutputFile);
} else {
if (fs.existsSync(path.join(options.sourcesRoot, importedFilePath + '.js'))) {
copyFile(importedFilePath + '.js');
}
}
}
}
}
delete tsConfig.compilerOptions.moduleResolution;
writeOutputFile('tsconfig.json', JSON.stringify(tsConfig, null, '\t'));
[
'vs/css.build.js',
'vs/css.d.ts',
'vs/css.js',
'vs/loader.js',
'vs/nls.build.js',
'vs/nls.d.ts',
'vs/nls.js',
'vs/nls.mock.ts',
].forEach(copyFile);
}
export interface IOptions2 {
srcFolder: string;
outFolder: string;
outResourcesFolder: string;
ignores: string[];
renames: { [filename: string]: string; };
}
export function createESMSourcesAndResources2(options: IOptions2): void {
const SRC_FOLDER = path.join(REPO_ROOT, options.srcFolder);
const OUT_FOLDER = path.join(REPO_ROOT, options.outFolder);
const OUT_RESOURCES_FOLDER = path.join(REPO_ROOT, options.outResourcesFolder);
const getDestAbsoluteFilePath = (file: string): string => {
let dest = options.renames[file.replace(/\\/g, '/')] || file;
if (dest === 'tsconfig.json') {
return path.join(OUT_FOLDER, `tsconfig.json`);
}
if (/\.ts$/.test(dest)) {
return path.join(OUT_FOLDER, dest);
}
return path.join(OUT_RESOURCES_FOLDER, dest);
};
const allFiles = walkDirRecursive(SRC_FOLDER);
for (const file of allFiles) {
if (options.ignores.indexOf(file.replace(/\\/g, '/')) >= 0) {
continue;
}
if (file === 'tsconfig.json') {
const tsConfig = JSON.parse(fs.readFileSync(path.join(SRC_FOLDER, file)).toString());
tsConfig.compilerOptions.module = 'es6';
tsConfig.compilerOptions.outDir = path.join(path.relative(OUT_FOLDER, OUT_RESOURCES_FOLDER), 'vs').replace(/\\/g, '/');
write(getDestAbsoluteFilePath(file), JSON.stringify(tsConfig, null, '\t'));
continue;
}
if (/\.d\.ts$/.test(file) || /\.css$/.test(file) || /\.js$/.test(file)) {
// Transport the files directly
write(getDestAbsoluteFilePath(file), fs.readFileSync(path.join(SRC_FOLDER, file)));
continue;
}
if (/\.ts$/.test(file)) {
// Transform the .ts file
let fileContents = fs.readFileSync(path.join(SRC_FOLDER, file)).toString();
const info = ts.preProcessFile(fileContents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFilename = info.importedFiles[i].fileName;
const pos = info.importedFiles[i].pos;
const end = info.importedFiles[i].end;
let importedFilepath: string;
if (/^vs\/css!/.test(importedFilename)) {
importedFilepath = importedFilename.substr('vs/css!'.length) + '.css';
} else {
importedFilepath = importedFilename;
}
if (/(^\.\/)|(^\.\.\/)/.test(importedFilepath)) {
importedFilepath = path.join(path.dirname(file), importedFilepath);
}
let relativePath: string;
if (importedFilepath === path.dirname(file).replace(/\\/g, '/')) {
relativePath = '../' + path.basename(path.dirname(file));
} else if (importedFilepath === path.dirname(path.dirname(file)).replace(/\\/g, '/')) {
relativePath = '../../' + path.basename(path.dirname(path.dirname(file)));
} else {
relativePath = path.relative(path.dirname(file), importedFilepath);
}
relativePath = relativePath.replace(/\\/g, '/');
if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
relativePath = './' + relativePath;
}
fileContents = (
fileContents.substring(0, pos + 1)
+ relativePath
+ fileContents.substring(end + 1)
);
}
fileContents = fileContents.replace(/import ([a-zA-z0-9]+) = require\(('[^']+')\);/g, function (_, m1, m2) {
return `import * as ${m1} from ${m2};`;
});
write(getDestAbsoluteFilePath(file), fileContents);
continue;
}
console.log(`UNKNOWN FILE: ${file}`);
}
function walkDirRecursive(dir: string): string[] {
if (dir.charAt(dir.length - 1) !== '/' || dir.charAt(dir.length - 1) !== '\\') {
dir += '/';
}
let result: string[] = [];
_walkDirRecursive(dir, result, dir.length);
return result;
}
function _walkDirRecursive(dir: string, result: string[], trimPos: number): void {
const files = fs.readdirSync(dir);
for (let i = 0; i < files.length; i++) {
const file = path.join(dir, files[i]);
if (fs.statSync(file).isDirectory()) {
_walkDirRecursive(file, result, trimPos);
} else {
result.push(file.substr(trimPos));
}
}
}
function write(absoluteFilePath: string, contents: string | Buffer): void {
if (/(\.ts$)|(\.js$)/.test(absoluteFilePath)) {
contents = toggleComments(contents.toString());
}
writeFile(absoluteFilePath, contents);
function toggleComments(fileContents: string): string {
let lines = fileContents.split(/\r\n|\r|\n/);
let mode = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (mode === 0) {
if (/\/\/ ESM-comment-begin/.test(line)) {
mode = 1;
continue;
}
if (/\/\/ ESM-uncomment-begin/.test(line)) {
mode = 2;
continue;
}
continue;
}
if (mode === 1) {
if (/\/\/ ESM-comment-end/.test(line)) {
mode = 0;
continue;
}
lines[i] = '// ' + line;
continue;
}
if (mode === 2) {
if (/\/\/ ESM-uncomment-end/.test(line)) {
mode = 0;
continue;
}
lines[i] = line.replace(/^(\s*)\/\/ ?/, function (_, indent) {
return indent;
});
}
}
return lines.join('\n');
}
}
}
function transportCSS(module: string, enqueue: (module: string) => void, write: (path: string, contents: string | Buffer) => void): boolean {
if (!/\.css/.test(module)) {
return false;
}
const filename = path.join(SRC_DIR, module);
const fileContents = fs.readFileSync(filename).toString();
const inlineResources = 'base64'; // see https://github.com/Microsoft/monaco-editor/issues/148
const inlineResourcesLimit = 300000;//3000; // see https://github.com/Microsoft/monaco-editor/issues/336
const newContents = _rewriteOrInlineUrls(fileContents, inlineResources === 'base64', inlineResourcesLimit);
write(module, newContents);
return true;
function _rewriteOrInlineUrls(contents: string, forceBase64: boolean, inlineByteLimit: number): string {
return _replaceURL(contents, (url) => {
let imagePath = path.join(path.dirname(module), url);
let fileContents = fs.readFileSync(path.join(SRC_DIR, imagePath));
if (fileContents.length < inlineByteLimit) {
const MIME = /\.svg$/.test(url) ? 'image/svg+xml' : 'image/png';
let DATA = ';base64,' + fileContents.toString('base64');
if (!forceBase64 && /\.svg$/.test(url)) {
// .svg => url encode as explained at https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
let newText = fileContents.toString()
.replace(/"/g, '\'')
.replace(/</g, '%3C')
.replace(/>/g, '%3E')
.replace(/&/g, '%26')
.replace(/#/g, '%23')
.replace(/\s+/g, ' ');
let encodedData = ',' + newText;
if (encodedData.length < DATA.length) {
DATA = encodedData;
}
}
return '"data:' + MIME + DATA + '"';
}
enqueue(imagePath);
return url;
});
}
function _replaceURL(contents: string, replacer: (url: string) => string): string {
// Use ")" as the terminator as quotes are oftentimes not used at all
return contents.replace(/url\(\s*([^\)]+)\s*\)?/g, (_: string, ...matches: string[]) => {
let url = matches[0];
// Eliminate starting quotes (the initial whitespace is not captured)
if (url.charAt(0) === '"' || url.charAt(0) === '\'') {
url = url.substring(1);
}
// The ending whitespace is captured
while (url.length > 0 && (url.charAt(url.length - 1) === ' ' || url.charAt(url.length - 1) === '\t')) {
url = url.substring(0, url.length - 1);
}
// Eliminate ending quotes
if (url.charAt(url.length - 1) === '"' || url.charAt(url.length - 1) === '\'') {
url = url.substring(0, url.length - 1);
}
if (!_startsWith(url, 'data:') && !_startsWith(url, 'http://') && !_startsWith(url, 'https://')) {
url = replacer(url);
}
return 'url(' + url + ')';
});
}
function _startsWith(haystack: string, needle: string): boolean {
return haystack.length >= needle.length && haystack.substr(0, needle.length) === needle;
}
}
| build/lib/standalone.ts | 1 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.9937006235122681,
0.07835818827152252,
0.00016279180999845266,
0.0001754606782924384,
0.2592063546180725
]
|
{
"id": 0,
"code_window": [
" compilerOptions.noUnusedLocals = false;\n",
" compilerOptions.preserveConstEnums = false;\n",
" compilerOptions.declaration = false;\n",
" compilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;\n",
" options.compilerOptions = compilerOptions;\n",
" let result = tss.shake(options);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" compilerOptions.noImplicitAny = false;\n"
],
"file_path": "build/lib/standalone.js",
"type": "add",
"edit_start_line_idx": 42
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import Messages from 'vs/workbench/contrib/markers/browser/messages';
import { IFilter, matchesPrefix, matchesFuzzy, matchesFuzzy2 } from 'vs/base/common/filters';
import { IExpression, splitGlobAware, getEmptyExpression } from 'vs/base/common/glob';
import * as strings from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { ResourceGlobMatcher } from 'vs/base/common/resources';
export class FilterOptions {
static readonly _filter: IFilter = matchesFuzzy2;
static readonly _messageFilter: IFilter = matchesFuzzy;
readonly filterErrors: boolean = false;
readonly filterWarnings: boolean = false;
readonly filterInfos: boolean = false;
readonly textFilter: string = '';
readonly excludesMatcher: ResourceGlobMatcher;
readonly includesMatcher: ResourceGlobMatcher;
constructor(readonly filter: string = '', filesExclude: { root: URI, expression: IExpression }[] | IExpression = []) {
filter = filter.trim();
const filesExcludeByRoot = Array.isArray(filesExclude) ? filesExclude : [];
const excludesExpression: IExpression = Array.isArray(filesExclude) ? getEmptyExpression() : filesExclude;
const includeExpression: IExpression = getEmptyExpression();
if (filter) {
const filters = splitGlobAware(filter, ',').map(s => s.trim()).filter(s => !!s.length);
for (const f of filters) {
this.filterErrors = this.filterErrors || this.matches(f, Messages.MARKERS_PANEL_FILTER_ERRORS);
this.filterWarnings = this.filterWarnings || this.matches(f, Messages.MARKERS_PANEL_FILTER_WARNINGS);
this.filterInfos = this.filterInfos || this.matches(f, Messages.MARKERS_PANEL_FILTER_INFOS);
if (strings.startsWith(f, '!')) {
this.setPattern(excludesExpression, strings.ltrim(f, '!'));
} else {
this.setPattern(includeExpression, f);
this.textFilter += ` ${f}`;
}
}
}
this.excludesMatcher = new ResourceGlobMatcher(excludesExpression, filesExcludeByRoot);
this.includesMatcher = new ResourceGlobMatcher(includeExpression, []);
this.textFilter = this.textFilter.trim();
}
private setPattern(expression: IExpression, pattern: string) {
if (pattern[0] === '.') {
pattern = '*' + pattern; // convert ".js" to "*.js"
}
expression[`**/${pattern}/**`] = true;
expression[`**/${pattern}`] = true;
}
private matches(prefix: string, word: string): boolean {
const result = matchesPrefix(prefix, word);
return !!(result && result.length > 0);
}
}
| src/vs/workbench/contrib/markers/browser/markersFilterOptions.ts | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.0004840340407099575,
0.00022807825007475913,
0.00017344190564472228,
0.00017781446513254195,
0.00010600590758258477
]
|
{
"id": 0,
"code_window": [
" compilerOptions.noUnusedLocals = false;\n",
" compilerOptions.preserveConstEnums = false;\n",
" compilerOptions.declaration = false;\n",
" compilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;\n",
" options.compilerOptions = compilerOptions;\n",
" let result = tss.shake(options);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" compilerOptions.noImplicitAny = false;\n"
],
"file_path": "build/lib/standalone.js",
"type": "add",
"edit_start_line_idx": 42
} |
// Hello World
println "Hello world!"
/*
Variables:
You can assign values to variables for later use
*/
def x = 1
println x
x = new java.util.Date()
println x
x = -3.1499392
println x
x = false
println x
x = "Groovy!"
println x
/*
Collections and maps
*/
//Creating an empty list
def technologies = []
/*** Adding a elements to the list ***/
// As with Java
technologies.add("Grails")
// Left shift adds, and returns the list
technologies << "Groovy"
// Add multiple elements
technologies.addAll(["Gradle","Griffon"])
/*** Removing elements from the list ***/
// As with Java
technologies.remove("Griffon")
// Subtraction works also
technologies = technologies - 'Grails'
/*** Iterating Lists ***/
// Iterate over elements of a list
technologies.each { println "Technology: $it"}
technologies.eachWithIndex { it, i -> println "$i: $it"}
/*** Checking List contents ***/
//Evaluate if a list contains element(s) (boolean)
contained = technologies.contains( 'Groovy' )
// Or
contained = 'Groovy' in technologies
// To sort without mutating original, you can do:
sortedTechnologies = technologies.sort( false )
//Replace all elements in the list
Collections.replaceAll(technologies, 'Gradle', 'gradle')
//Shuffle a list
Collections.shuffle(technologies, new Random())
//Clear a list
technologies.clear()
//Creating an empty map
def devMap = [:]
//Add values
devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
devMap.put('lastName','Perez')
//Iterate over elements of a map
devMap.each { println "$it.key: $it.value" }
devMap.eachWithIndex { it, i -> println "$i: $it"}
//Evaluate if a map contains a key
assert devMap.containsKey('name')
//Get the keys of a map
println devMap.keySet()
class Foo {
// read only property
final String name = "Roberto"
// read only property with public getter and protected setter
String language
protected void setLanguage(String language) { this.language = language }
// dynamically typed property
def lastName
}
/*
Logical Branching and Looping
*/
//Groovy supports the usual if - else syntax
def x = 3
if(x==1) {
println "One"
} else if(x==2) {
println "Two"
} else {
println "X greater than Two"
}
//Groovy also supports the ternary operator:
def y = 10
def x = (y > 1) ? "worked" : "failed"
assert x == "worked"
//Groovy supports 'The Elvis Operator' too!
//Instead of using the ternary operator:
displayName = user.name ? user.name : 'Anonymous'
//We can write it:
displayName = user.name ?: 'Anonymous'
//For loop
//Iterate over a range
def x = 0
for (i in 0 .. 30) {
x += i
}
//Iterate over a list
x = 0
for( i in [5,3,2,1] ) {
x += i
}
//Iterate over an array
array = (0..20).toArray()
x = 0
for (i in array) {
x += i
}
//Iterate over a map
def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
x = 0
for ( e in map ) {
x += e.value
}
def technologies = ['Groovy','Grails','Gradle']
technologies*.toUpperCase() // = to technologies.collect { it?.toUpperCase() }
def user = User.get(1)
def username = user?.username
def clos = { println "Hello World!" }
def sum = { a, b -> println a+b }
sum(2,4)
def x = 5
def multiplyBy = { num -> num * x }
println multiplyBy(10)
def clos = { print it }
clos( "hi" )
def cl = {a, b ->
sleep(3000) // simulate some time consuming processing
a + b
}
mem = cl.memoize()
def callClosure(a, b) {
def start = System.currentTimeMillis()
mem(a, b)
println "Inputs(a = $a, b = $b) - took ${System.currentTimeMillis() - start} msecs."
}
callClosure(1, 2)
//Another example:
import groovy.transform.TypeChecked
@TypeChecked
Integer test() {
Integer num = "1"
Integer[] numbers = [1,2,3,4]
Date date = numbers[1]
return "Test"
}
//CompileStatic example:
import groovy.transform.CompileStatic
@CompileStatic
int sum(int x, int y) {
x + y
}
assert sum(2,5) == 7
| extensions/groovy/test/colorize-fixtures/test.groovy | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.0001806242944439873,
0.000176442859810777,
0.00016458060417789966,
0.00017741590272635221,
0.000003706532197611523
]
|
{
"id": 0,
"code_window": [
" compilerOptions.noUnusedLocals = false;\n",
" compilerOptions.preserveConstEnums = false;\n",
" compilerOptions.declaration = false;\n",
" compilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;\n",
" options.compilerOptions = compilerOptions;\n",
" let result = tss.shake(options);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" compilerOptions.noImplicitAny = false;\n"
],
"file_path": "build/lib/standalone.js",
"type": "add",
"edit_start_line_idx": 42
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const fs = require('mz/fs');
const path = require('path');
const Koa = require('koa');
const _ = require('koa-route');
const serve = require('koa-static');
const mount = require('koa-mount');
const app = new Koa();
const root = path.dirname(path.dirname(__dirname));
async function getTree(fsPath, level) {
const element = path.basename(fsPath);
const stat = await fs.stat(fsPath);
if (!stat.isDirectory() || element === '.git' || element === '.build' || level >= 4) {
return { element };
}
const childNames = await fs.readdir(fsPath);
const children = await Promise.all(childNames.map(async childName => await getTree(path.join(fsPath, childName), level + 1)));
return { element, collapsible: true, collapsed: false, children };
}
async function readdir(relativePath) {
const absolutePath = relativePath ? path.join(root, relativePath) : root;
const childNames = await fs.readdir(absolutePath);
const childStats = await Promise.all(childNames.map(async name => await fs.stat(path.join(absolutePath, name))));
const result = [];
for (let i = 0; i < childNames.length; i++) {
const name = childNames[i];
const path = relativePath ? `${relativePath}/${name}` : name;
const stat = childStats[i];
if (stat.isFile()) {
result.push({ type: 'file', name, path });
} else if (!stat.isDirectory() || name === '.git' || name === '.build') {
continue;
} else {
result.push({ type: 'dir', name, path });
}
}
return result;
}
app.use(serve('public'));
app.use(mount('/static', serve('../../out')));
app.use(_.get('/api/ls', async ctx => {
const relativePath = ctx.query.path;
const absolutePath = path.join(root, relativePath);
ctx.body = await getTree(absolutePath, 0);
}));
app.use(_.get('/api/readdir', async ctx => {
const relativePath = ctx.query.path;
ctx.body = await readdir(relativePath);
}));
app.listen(3000);
console.log('http://localhost:3000'); | test/tree/server.js | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.0004132885078433901,
0.00021600606851279736,
0.0001746237394399941,
0.00017801531066652387,
0.00008160475408658385
]
|
{
"id": 1,
"code_window": [
" }\n",
" delete tsConfig.compilerOptions.moduleResolution;\n",
" writeOutputFile('tsconfig.json', JSON.stringify(tsConfig, null, '\\t'));\n",
" [\n",
" 'vs/css.build.js',\n",
" 'vs/css.d.ts',\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const tsConfigBase = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.base.json')).toString());\n",
" writeOutputFile('tsconfig.base.json', JSON.stringify(tsConfigBase, null, '\\t'));\n"
],
"file_path": "build/lib/standalone.js",
"type": "add",
"edit_start_line_idx": 92
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as ts from 'typescript';
import * as fs from 'fs';
import * as path from 'path';
import * as tss from './treeshaking';
const REPO_ROOT = path.join(__dirname, '../../');
const SRC_DIR = path.join(REPO_ROOT, 'src');
let dirCache: { [dir: string]: boolean; } = {};
function writeFile(filePath: string, contents: Buffer | string): void {
function ensureDirs(dirPath: string): void {
if (dirCache[dirPath]) {
return;
}
dirCache[dirPath] = true;
ensureDirs(path.dirname(dirPath));
if (fs.existsSync(dirPath)) {
return;
}
fs.mkdirSync(dirPath);
}
ensureDirs(path.dirname(filePath));
fs.writeFileSync(filePath, contents);
}
export function extractEditor(options: tss.ITreeShakingOptions & { destRoot: string }): void {
const tsConfig = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.monaco.json')).toString());
let compilerOptions: { [key: string]: any };
if (tsConfig.extends) {
compilerOptions = Object.assign({}, require(path.join(options.sourcesRoot, tsConfig.extends)).compilerOptions, tsConfig.compilerOptions);
} else {
compilerOptions = tsConfig.compilerOptions;
}
tsConfig.compilerOptions = compilerOptions;
compilerOptions.noEmit = false;
compilerOptions.noUnusedLocals = false;
compilerOptions.preserveConstEnums = false;
compilerOptions.declaration = false;
compilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;
options.compilerOptions = compilerOptions;
let result = tss.shake(options);
for (let fileName in result) {
if (result.hasOwnProperty(fileName)) {
writeFile(path.join(options.destRoot, fileName), result[fileName]);
}
}
let copied: { [fileName: string]: boolean; } = {};
const copyFile = (fileName: string) => {
if (copied[fileName]) {
return;
}
copied[fileName] = true;
const srcPath = path.join(options.sourcesRoot, fileName);
const dstPath = path.join(options.destRoot, fileName);
writeFile(dstPath, fs.readFileSync(srcPath));
};
const writeOutputFile = (fileName: string, contents: string | Buffer) => {
writeFile(path.join(options.destRoot, fileName), contents);
};
for (let fileName in result) {
if (result.hasOwnProperty(fileName)) {
const fileContents = result[fileName];
const info = ts.preProcessFile(fileContents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFileName = info.importedFiles[i].fileName;
let importedFilePath: string;
if (/^vs\/css!/.test(importedFileName)) {
importedFilePath = importedFileName.substr('vs/css!'.length) + '.css';
} else {
importedFilePath = importedFileName;
}
if (/(^\.\/)|(^\.\.\/)/.test(importedFilePath)) {
importedFilePath = path.join(path.dirname(fileName), importedFilePath);
}
if (/\.css$/.test(importedFilePath)) {
transportCSS(importedFilePath, copyFile, writeOutputFile);
} else {
if (fs.existsSync(path.join(options.sourcesRoot, importedFilePath + '.js'))) {
copyFile(importedFilePath + '.js');
}
}
}
}
}
delete tsConfig.compilerOptions.moduleResolution;
writeOutputFile('tsconfig.json', JSON.stringify(tsConfig, null, '\t'));
[
'vs/css.build.js',
'vs/css.d.ts',
'vs/css.js',
'vs/loader.js',
'vs/nls.build.js',
'vs/nls.d.ts',
'vs/nls.js',
'vs/nls.mock.ts',
].forEach(copyFile);
}
export interface IOptions2 {
srcFolder: string;
outFolder: string;
outResourcesFolder: string;
ignores: string[];
renames: { [filename: string]: string; };
}
export function createESMSourcesAndResources2(options: IOptions2): void {
const SRC_FOLDER = path.join(REPO_ROOT, options.srcFolder);
const OUT_FOLDER = path.join(REPO_ROOT, options.outFolder);
const OUT_RESOURCES_FOLDER = path.join(REPO_ROOT, options.outResourcesFolder);
const getDestAbsoluteFilePath = (file: string): string => {
let dest = options.renames[file.replace(/\\/g, '/')] || file;
if (dest === 'tsconfig.json') {
return path.join(OUT_FOLDER, `tsconfig.json`);
}
if (/\.ts$/.test(dest)) {
return path.join(OUT_FOLDER, dest);
}
return path.join(OUT_RESOURCES_FOLDER, dest);
};
const allFiles = walkDirRecursive(SRC_FOLDER);
for (const file of allFiles) {
if (options.ignores.indexOf(file.replace(/\\/g, '/')) >= 0) {
continue;
}
if (file === 'tsconfig.json') {
const tsConfig = JSON.parse(fs.readFileSync(path.join(SRC_FOLDER, file)).toString());
tsConfig.compilerOptions.module = 'es6';
tsConfig.compilerOptions.outDir = path.join(path.relative(OUT_FOLDER, OUT_RESOURCES_FOLDER), 'vs').replace(/\\/g, '/');
write(getDestAbsoluteFilePath(file), JSON.stringify(tsConfig, null, '\t'));
continue;
}
if (/\.d\.ts$/.test(file) || /\.css$/.test(file) || /\.js$/.test(file)) {
// Transport the files directly
write(getDestAbsoluteFilePath(file), fs.readFileSync(path.join(SRC_FOLDER, file)));
continue;
}
if (/\.ts$/.test(file)) {
// Transform the .ts file
let fileContents = fs.readFileSync(path.join(SRC_FOLDER, file)).toString();
const info = ts.preProcessFile(fileContents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFilename = info.importedFiles[i].fileName;
const pos = info.importedFiles[i].pos;
const end = info.importedFiles[i].end;
let importedFilepath: string;
if (/^vs\/css!/.test(importedFilename)) {
importedFilepath = importedFilename.substr('vs/css!'.length) + '.css';
} else {
importedFilepath = importedFilename;
}
if (/(^\.\/)|(^\.\.\/)/.test(importedFilepath)) {
importedFilepath = path.join(path.dirname(file), importedFilepath);
}
let relativePath: string;
if (importedFilepath === path.dirname(file).replace(/\\/g, '/')) {
relativePath = '../' + path.basename(path.dirname(file));
} else if (importedFilepath === path.dirname(path.dirname(file)).replace(/\\/g, '/')) {
relativePath = '../../' + path.basename(path.dirname(path.dirname(file)));
} else {
relativePath = path.relative(path.dirname(file), importedFilepath);
}
relativePath = relativePath.replace(/\\/g, '/');
if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
relativePath = './' + relativePath;
}
fileContents = (
fileContents.substring(0, pos + 1)
+ relativePath
+ fileContents.substring(end + 1)
);
}
fileContents = fileContents.replace(/import ([a-zA-z0-9]+) = require\(('[^']+')\);/g, function (_, m1, m2) {
return `import * as ${m1} from ${m2};`;
});
write(getDestAbsoluteFilePath(file), fileContents);
continue;
}
console.log(`UNKNOWN FILE: ${file}`);
}
function walkDirRecursive(dir: string): string[] {
if (dir.charAt(dir.length - 1) !== '/' || dir.charAt(dir.length - 1) !== '\\') {
dir += '/';
}
let result: string[] = [];
_walkDirRecursive(dir, result, dir.length);
return result;
}
function _walkDirRecursive(dir: string, result: string[], trimPos: number): void {
const files = fs.readdirSync(dir);
for (let i = 0; i < files.length; i++) {
const file = path.join(dir, files[i]);
if (fs.statSync(file).isDirectory()) {
_walkDirRecursive(file, result, trimPos);
} else {
result.push(file.substr(trimPos));
}
}
}
function write(absoluteFilePath: string, contents: string | Buffer): void {
if (/(\.ts$)|(\.js$)/.test(absoluteFilePath)) {
contents = toggleComments(contents.toString());
}
writeFile(absoluteFilePath, contents);
function toggleComments(fileContents: string): string {
let lines = fileContents.split(/\r\n|\r|\n/);
let mode = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (mode === 0) {
if (/\/\/ ESM-comment-begin/.test(line)) {
mode = 1;
continue;
}
if (/\/\/ ESM-uncomment-begin/.test(line)) {
mode = 2;
continue;
}
continue;
}
if (mode === 1) {
if (/\/\/ ESM-comment-end/.test(line)) {
mode = 0;
continue;
}
lines[i] = '// ' + line;
continue;
}
if (mode === 2) {
if (/\/\/ ESM-uncomment-end/.test(line)) {
mode = 0;
continue;
}
lines[i] = line.replace(/^(\s*)\/\/ ?/, function (_, indent) {
return indent;
});
}
}
return lines.join('\n');
}
}
}
function transportCSS(module: string, enqueue: (module: string) => void, write: (path: string, contents: string | Buffer) => void): boolean {
if (!/\.css/.test(module)) {
return false;
}
const filename = path.join(SRC_DIR, module);
const fileContents = fs.readFileSync(filename).toString();
const inlineResources = 'base64'; // see https://github.com/Microsoft/monaco-editor/issues/148
const inlineResourcesLimit = 300000;//3000; // see https://github.com/Microsoft/monaco-editor/issues/336
const newContents = _rewriteOrInlineUrls(fileContents, inlineResources === 'base64', inlineResourcesLimit);
write(module, newContents);
return true;
function _rewriteOrInlineUrls(contents: string, forceBase64: boolean, inlineByteLimit: number): string {
return _replaceURL(contents, (url) => {
let imagePath = path.join(path.dirname(module), url);
let fileContents = fs.readFileSync(path.join(SRC_DIR, imagePath));
if (fileContents.length < inlineByteLimit) {
const MIME = /\.svg$/.test(url) ? 'image/svg+xml' : 'image/png';
let DATA = ';base64,' + fileContents.toString('base64');
if (!forceBase64 && /\.svg$/.test(url)) {
// .svg => url encode as explained at https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
let newText = fileContents.toString()
.replace(/"/g, '\'')
.replace(/</g, '%3C')
.replace(/>/g, '%3E')
.replace(/&/g, '%26')
.replace(/#/g, '%23')
.replace(/\s+/g, ' ');
let encodedData = ',' + newText;
if (encodedData.length < DATA.length) {
DATA = encodedData;
}
}
return '"data:' + MIME + DATA + '"';
}
enqueue(imagePath);
return url;
});
}
function _replaceURL(contents: string, replacer: (url: string) => string): string {
// Use ")" as the terminator as quotes are oftentimes not used at all
return contents.replace(/url\(\s*([^\)]+)\s*\)?/g, (_: string, ...matches: string[]) => {
let url = matches[0];
// Eliminate starting quotes (the initial whitespace is not captured)
if (url.charAt(0) === '"' || url.charAt(0) === '\'') {
url = url.substring(1);
}
// The ending whitespace is captured
while (url.length > 0 && (url.charAt(url.length - 1) === ' ' || url.charAt(url.length - 1) === '\t')) {
url = url.substring(0, url.length - 1);
}
// Eliminate ending quotes
if (url.charAt(url.length - 1) === '"' || url.charAt(url.length - 1) === '\'') {
url = url.substring(0, url.length - 1);
}
if (!_startsWith(url, 'data:') && !_startsWith(url, 'http://') && !_startsWith(url, 'https://')) {
url = replacer(url);
}
return 'url(' + url + ')';
});
}
function _startsWith(haystack: string, needle: string): boolean {
return haystack.length >= needle.length && haystack.substr(0, needle.length) === needle;
}
}
| build/lib/standalone.ts | 1 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.44017311930656433,
0.014406138099730015,
0.00016382077592425048,
0.0001732566743157804,
0.0725599005818367
]
|
{
"id": 1,
"code_window": [
" }\n",
" delete tsConfig.compilerOptions.moduleResolution;\n",
" writeOutputFile('tsconfig.json', JSON.stringify(tsConfig, null, '\\t'));\n",
" [\n",
" 'vs/css.build.js',\n",
" 'vs/css.d.ts',\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const tsConfigBase = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.base.json')).toString());\n",
" writeOutputFile('tsconfig.base.json', JSON.stringify(tsConfigBase, null, '\\t'));\n"
],
"file_path": "build/lib/standalone.js",
"type": "add",
"edit_start_line_idx": 92
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.st0{fill:#f6f6f6;fill-opacity:0}.st1{display:none}.st2{display:inline;fill:#f6f6f6}.st3{fill:#388a34}</style><title>restart</title><path class="st0" d="M16 0v16H0V0h16z" id="canvas"/><g id="outline" class="st1" style="display: none;"><path class="st2" d="M8.5 1C6.9 1 5.3 1.5 4 2.5V1H0v8h3.1L1 9.6l.3 1c1.1 4 5.3 6.3 9.3 5.2s6.3-5.3 5.2-9.3C14.8 3.2 11.9 1 8.5 1zm0 11c-1.6 0-2.9-1-3.4-2.5L5 9h3V5h.5C10.4 5 12 6.6 12 8.5S10.4 12 8.5 12z"/></g><path class="st3" d="M15 8c0 3.6-2.9 6.5-6.5 6.5-2.9 0-5.5-1.9-6.3-4.7l1.9-.5c.7 2.4 3.2 3.8 5.6 3.1 2.4-.7 3.8-3.2 3.1-5.6S9.7 3 7.3 3.7c-1 .3-1.9.9-2.5 1.8H7v2H1v-6h2v3.1c1.9-3 5.9-4 8.9-2.1C13.8 3.7 15 5.7 15 8z" id="iconBg"/></svg> | src/vs/workbench/contrib/debug/browser/media/restart.svg | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.00028632208704948425,
0.00028632208704948425,
0.00028632208704948425,
0.00028632208704948425,
0
]
|
{
"id": 1,
"code_window": [
" }\n",
" delete tsConfig.compilerOptions.moduleResolution;\n",
" writeOutputFile('tsconfig.json', JSON.stringify(tsConfig, null, '\\t'));\n",
" [\n",
" 'vs/css.build.js',\n",
" 'vs/css.d.ts',\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const tsConfigBase = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.base.json')).toString());\n",
" writeOutputFile('tsconfig.base.json', JSON.stringify(tsConfigBase, null, '\\t'));\n"
],
"file_path": "build/lib/standalone.js",
"type": "add",
"edit_start_line_idx": 92
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
const bootstrapWindow = require('../../../../bootstrap-window');
bootstrapWindow.load(['vs/code/electron-browser/issue/issueReporterMain'], function (issueReporter, configuration) {
issueReporter.startup(configuration);
}, { forceEnableDeveloperKeybindings: true }); | src/vs/code/electron-browser/issue/issueReporter.js | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.0001718123530736193,
0.00016875688743311912,
0.00016570142179261893,
0.00016875688743311912,
0.000003055465640500188
]
|
{
"id": 1,
"code_window": [
" }\n",
" delete tsConfig.compilerOptions.moduleResolution;\n",
" writeOutputFile('tsconfig.json', JSON.stringify(tsConfig, null, '\\t'));\n",
" [\n",
" 'vs/css.build.js',\n",
" 'vs/css.d.ts',\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" const tsConfigBase = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.base.json')).toString());\n",
" writeOutputFile('tsconfig.base.json', JSON.stringify(tsConfigBase, null, '\\t'));\n"
],
"file_path": "build/lib/standalone.js",
"type": "add",
"edit_start_line_idx": 92
} | /*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/////////////////////////////
/// WorkerGlobalScope APIs
/////////////////////////////
// These are only available in a Web Worker
declare function importScripts(...urls: string[]): void;
| src/typings/lib.webworker.importscripts.d.ts | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.00017623271560296416,
0.00017229498189408332,
0.00016478396719321609,
0.00017586827743798494,
0.000005313176188792568
]
|
{
"id": 2,
"code_window": [
"\tcompilerOptions.noUnusedLocals = false;\n",
"\tcompilerOptions.preserveConstEnums = false;\n",
"\tcompilerOptions.declaration = false;\n",
"\tcompilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;\n",
"\n",
"\n",
"\toptions.compilerOptions = compilerOptions;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcompilerOptions.noImplicitAny = false;\n"
],
"file_path": "build/lib/standalone.ts",
"type": "add",
"edit_start_line_idx": 46
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as ts from 'typescript';
import * as fs from 'fs';
import * as path from 'path';
import * as tss from './treeshaking';
const REPO_ROOT = path.join(__dirname, '../../');
const SRC_DIR = path.join(REPO_ROOT, 'src');
let dirCache: { [dir: string]: boolean; } = {};
function writeFile(filePath: string, contents: Buffer | string): void {
function ensureDirs(dirPath: string): void {
if (dirCache[dirPath]) {
return;
}
dirCache[dirPath] = true;
ensureDirs(path.dirname(dirPath));
if (fs.existsSync(dirPath)) {
return;
}
fs.mkdirSync(dirPath);
}
ensureDirs(path.dirname(filePath));
fs.writeFileSync(filePath, contents);
}
export function extractEditor(options: tss.ITreeShakingOptions & { destRoot: string }): void {
const tsConfig = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.monaco.json')).toString());
let compilerOptions: { [key: string]: any };
if (tsConfig.extends) {
compilerOptions = Object.assign({}, require(path.join(options.sourcesRoot, tsConfig.extends)).compilerOptions, tsConfig.compilerOptions);
} else {
compilerOptions = tsConfig.compilerOptions;
}
tsConfig.compilerOptions = compilerOptions;
compilerOptions.noEmit = false;
compilerOptions.noUnusedLocals = false;
compilerOptions.preserveConstEnums = false;
compilerOptions.declaration = false;
compilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;
options.compilerOptions = compilerOptions;
let result = tss.shake(options);
for (let fileName in result) {
if (result.hasOwnProperty(fileName)) {
writeFile(path.join(options.destRoot, fileName), result[fileName]);
}
}
let copied: { [fileName: string]: boolean; } = {};
const copyFile = (fileName: string) => {
if (copied[fileName]) {
return;
}
copied[fileName] = true;
const srcPath = path.join(options.sourcesRoot, fileName);
const dstPath = path.join(options.destRoot, fileName);
writeFile(dstPath, fs.readFileSync(srcPath));
};
const writeOutputFile = (fileName: string, contents: string | Buffer) => {
writeFile(path.join(options.destRoot, fileName), contents);
};
for (let fileName in result) {
if (result.hasOwnProperty(fileName)) {
const fileContents = result[fileName];
const info = ts.preProcessFile(fileContents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFileName = info.importedFiles[i].fileName;
let importedFilePath: string;
if (/^vs\/css!/.test(importedFileName)) {
importedFilePath = importedFileName.substr('vs/css!'.length) + '.css';
} else {
importedFilePath = importedFileName;
}
if (/(^\.\/)|(^\.\.\/)/.test(importedFilePath)) {
importedFilePath = path.join(path.dirname(fileName), importedFilePath);
}
if (/\.css$/.test(importedFilePath)) {
transportCSS(importedFilePath, copyFile, writeOutputFile);
} else {
if (fs.existsSync(path.join(options.sourcesRoot, importedFilePath + '.js'))) {
copyFile(importedFilePath + '.js');
}
}
}
}
}
delete tsConfig.compilerOptions.moduleResolution;
writeOutputFile('tsconfig.json', JSON.stringify(tsConfig, null, '\t'));
[
'vs/css.build.js',
'vs/css.d.ts',
'vs/css.js',
'vs/loader.js',
'vs/nls.build.js',
'vs/nls.d.ts',
'vs/nls.js',
'vs/nls.mock.ts',
].forEach(copyFile);
}
export interface IOptions2 {
srcFolder: string;
outFolder: string;
outResourcesFolder: string;
ignores: string[];
renames: { [filename: string]: string; };
}
export function createESMSourcesAndResources2(options: IOptions2): void {
const SRC_FOLDER = path.join(REPO_ROOT, options.srcFolder);
const OUT_FOLDER = path.join(REPO_ROOT, options.outFolder);
const OUT_RESOURCES_FOLDER = path.join(REPO_ROOT, options.outResourcesFolder);
const getDestAbsoluteFilePath = (file: string): string => {
let dest = options.renames[file.replace(/\\/g, '/')] || file;
if (dest === 'tsconfig.json') {
return path.join(OUT_FOLDER, `tsconfig.json`);
}
if (/\.ts$/.test(dest)) {
return path.join(OUT_FOLDER, dest);
}
return path.join(OUT_RESOURCES_FOLDER, dest);
};
const allFiles = walkDirRecursive(SRC_FOLDER);
for (const file of allFiles) {
if (options.ignores.indexOf(file.replace(/\\/g, '/')) >= 0) {
continue;
}
if (file === 'tsconfig.json') {
const tsConfig = JSON.parse(fs.readFileSync(path.join(SRC_FOLDER, file)).toString());
tsConfig.compilerOptions.module = 'es6';
tsConfig.compilerOptions.outDir = path.join(path.relative(OUT_FOLDER, OUT_RESOURCES_FOLDER), 'vs').replace(/\\/g, '/');
write(getDestAbsoluteFilePath(file), JSON.stringify(tsConfig, null, '\t'));
continue;
}
if (/\.d\.ts$/.test(file) || /\.css$/.test(file) || /\.js$/.test(file)) {
// Transport the files directly
write(getDestAbsoluteFilePath(file), fs.readFileSync(path.join(SRC_FOLDER, file)));
continue;
}
if (/\.ts$/.test(file)) {
// Transform the .ts file
let fileContents = fs.readFileSync(path.join(SRC_FOLDER, file)).toString();
const info = ts.preProcessFile(fileContents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFilename = info.importedFiles[i].fileName;
const pos = info.importedFiles[i].pos;
const end = info.importedFiles[i].end;
let importedFilepath: string;
if (/^vs\/css!/.test(importedFilename)) {
importedFilepath = importedFilename.substr('vs/css!'.length) + '.css';
} else {
importedFilepath = importedFilename;
}
if (/(^\.\/)|(^\.\.\/)/.test(importedFilepath)) {
importedFilepath = path.join(path.dirname(file), importedFilepath);
}
let relativePath: string;
if (importedFilepath === path.dirname(file).replace(/\\/g, '/')) {
relativePath = '../' + path.basename(path.dirname(file));
} else if (importedFilepath === path.dirname(path.dirname(file)).replace(/\\/g, '/')) {
relativePath = '../../' + path.basename(path.dirname(path.dirname(file)));
} else {
relativePath = path.relative(path.dirname(file), importedFilepath);
}
relativePath = relativePath.replace(/\\/g, '/');
if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
relativePath = './' + relativePath;
}
fileContents = (
fileContents.substring(0, pos + 1)
+ relativePath
+ fileContents.substring(end + 1)
);
}
fileContents = fileContents.replace(/import ([a-zA-z0-9]+) = require\(('[^']+')\);/g, function (_, m1, m2) {
return `import * as ${m1} from ${m2};`;
});
write(getDestAbsoluteFilePath(file), fileContents);
continue;
}
console.log(`UNKNOWN FILE: ${file}`);
}
function walkDirRecursive(dir: string): string[] {
if (dir.charAt(dir.length - 1) !== '/' || dir.charAt(dir.length - 1) !== '\\') {
dir += '/';
}
let result: string[] = [];
_walkDirRecursive(dir, result, dir.length);
return result;
}
function _walkDirRecursive(dir: string, result: string[], trimPos: number): void {
const files = fs.readdirSync(dir);
for (let i = 0; i < files.length; i++) {
const file = path.join(dir, files[i]);
if (fs.statSync(file).isDirectory()) {
_walkDirRecursive(file, result, trimPos);
} else {
result.push(file.substr(trimPos));
}
}
}
function write(absoluteFilePath: string, contents: string | Buffer): void {
if (/(\.ts$)|(\.js$)/.test(absoluteFilePath)) {
contents = toggleComments(contents.toString());
}
writeFile(absoluteFilePath, contents);
function toggleComments(fileContents: string): string {
let lines = fileContents.split(/\r\n|\r|\n/);
let mode = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (mode === 0) {
if (/\/\/ ESM-comment-begin/.test(line)) {
mode = 1;
continue;
}
if (/\/\/ ESM-uncomment-begin/.test(line)) {
mode = 2;
continue;
}
continue;
}
if (mode === 1) {
if (/\/\/ ESM-comment-end/.test(line)) {
mode = 0;
continue;
}
lines[i] = '// ' + line;
continue;
}
if (mode === 2) {
if (/\/\/ ESM-uncomment-end/.test(line)) {
mode = 0;
continue;
}
lines[i] = line.replace(/^(\s*)\/\/ ?/, function (_, indent) {
return indent;
});
}
}
return lines.join('\n');
}
}
}
function transportCSS(module: string, enqueue: (module: string) => void, write: (path: string, contents: string | Buffer) => void): boolean {
if (!/\.css/.test(module)) {
return false;
}
const filename = path.join(SRC_DIR, module);
const fileContents = fs.readFileSync(filename).toString();
const inlineResources = 'base64'; // see https://github.com/Microsoft/monaco-editor/issues/148
const inlineResourcesLimit = 300000;//3000; // see https://github.com/Microsoft/monaco-editor/issues/336
const newContents = _rewriteOrInlineUrls(fileContents, inlineResources === 'base64', inlineResourcesLimit);
write(module, newContents);
return true;
function _rewriteOrInlineUrls(contents: string, forceBase64: boolean, inlineByteLimit: number): string {
return _replaceURL(contents, (url) => {
let imagePath = path.join(path.dirname(module), url);
let fileContents = fs.readFileSync(path.join(SRC_DIR, imagePath));
if (fileContents.length < inlineByteLimit) {
const MIME = /\.svg$/.test(url) ? 'image/svg+xml' : 'image/png';
let DATA = ';base64,' + fileContents.toString('base64');
if (!forceBase64 && /\.svg$/.test(url)) {
// .svg => url encode as explained at https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
let newText = fileContents.toString()
.replace(/"/g, '\'')
.replace(/</g, '%3C')
.replace(/>/g, '%3E')
.replace(/&/g, '%26')
.replace(/#/g, '%23')
.replace(/\s+/g, ' ');
let encodedData = ',' + newText;
if (encodedData.length < DATA.length) {
DATA = encodedData;
}
}
return '"data:' + MIME + DATA + '"';
}
enqueue(imagePath);
return url;
});
}
function _replaceURL(contents: string, replacer: (url: string) => string): string {
// Use ")" as the terminator as quotes are oftentimes not used at all
return contents.replace(/url\(\s*([^\)]+)\s*\)?/g, (_: string, ...matches: string[]) => {
let url = matches[0];
// Eliminate starting quotes (the initial whitespace is not captured)
if (url.charAt(0) === '"' || url.charAt(0) === '\'') {
url = url.substring(1);
}
// The ending whitespace is captured
while (url.length > 0 && (url.charAt(url.length - 1) === ' ' || url.charAt(url.length - 1) === '\t')) {
url = url.substring(0, url.length - 1);
}
// Eliminate ending quotes
if (url.charAt(url.length - 1) === '"' || url.charAt(url.length - 1) === '\'') {
url = url.substring(0, url.length - 1);
}
if (!_startsWith(url, 'data:') && !_startsWith(url, 'http://') && !_startsWith(url, 'https://')) {
url = replacer(url);
}
return 'url(' + url + ')';
});
}
function _startsWith(haystack: string, needle: string): boolean {
return haystack.length >= needle.length && haystack.substr(0, needle.length) === needle;
}
}
| build/lib/standalone.ts | 1 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.9977508187294006,
0.028473185375332832,
0.0001661911519477144,
0.00017524047871120274,
0.1638621985912323
]
|
{
"id": 2,
"code_window": [
"\tcompilerOptions.noUnusedLocals = false;\n",
"\tcompilerOptions.preserveConstEnums = false;\n",
"\tcompilerOptions.declaration = false;\n",
"\tcompilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;\n",
"\n",
"\n",
"\toptions.compilerOptions = compilerOptions;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcompilerOptions.noImplicitAny = false;\n"
],
"file_path": "build/lib/standalone.ts",
"type": "add",
"edit_start_line_idx": 46
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IOutputChannelModelService, AsbtractOutputChannelModelService } from 'vs/workbench/services/output/common/outputChannelModel';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
export class OutputChannelModelService extends AsbtractOutputChannelModelService implements IOutputChannelModelService {
_serviceBrand: any;
}
registerSingleton(IOutputChannelModelService, OutputChannelModelService);
| src/vs/workbench/services/output/common/outputChannelModelService.ts | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.0001756846031639725,
0.0001740813604556024,
0.00017247811774723232,
0.0001740813604556024,
0.0000016032427083700895
]
|
{
"id": 2,
"code_window": [
"\tcompilerOptions.noUnusedLocals = false;\n",
"\tcompilerOptions.preserveConstEnums = false;\n",
"\tcompilerOptions.declaration = false;\n",
"\tcompilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;\n",
"\n",
"\n",
"\toptions.compilerOptions = compilerOptions;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcompilerOptions.noImplicitAny = false;\n"
],
"file_path": "build/lib/standalone.ts",
"type": "add",
"edit_start_line_idx": 46
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ExtHostHeapServiceShape } from './extHost.protocol';
export class ExtHostHeapService implements ExtHostHeapServiceShape {
private static _idPool = 0;
private _data = new Map<number, any>();
keep(obj: any): number {
const id = ExtHostHeapService._idPool++;
this._data.set(id, obj);
return id;
}
delete(id: number): boolean {
return this._data.delete(id);
}
get<T>(id: number): T {
return this._data.get(id);
}
$onGarbageCollection(ids: number[]): void {
for (const id of ids) {
this.delete(id);
}
}
}
| src/vs/workbench/api/common/extHostHeapService.ts | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.00018155653378926218,
0.0001775068521965295,
0.00017471201135776937,
0.00017687943181954324,
0.0000025413776256755227
]
|
{
"id": 2,
"code_window": [
"\tcompilerOptions.noUnusedLocals = false;\n",
"\tcompilerOptions.preserveConstEnums = false;\n",
"\tcompilerOptions.declaration = false;\n",
"\tcompilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;\n",
"\n",
"\n",
"\toptions.compilerOptions = compilerOptions;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcompilerOptions.noImplicitAny = false;\n"
],
"file_path": "build/lib/standalone.ts",
"type": "add",
"edit_start_line_idx": 46
} | {
"name": "theme-monokai-dimmed",
"displayName": "%displayName%",
"description": "%description%",
"version": "1.0.0",
"publisher": "vscode",
"engines": {
"vscode": "*"
},
"contributes": {
"themes": [
{
"label": "Monokai Dimmed",
"uiTheme": "vs-dark",
"path": "./themes/dimmed-monokai-color-theme.json"
}
]
}
} | extensions/theme-monokai-dimmed/package.json | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.0001770433591445908,
0.0001765224151313305,
0.00017600147111807019,
0.0001765224151313305,
5.209440132603049e-7
]
|
{
"id": 3,
"code_window": [
"\t\t}\n",
"\t}\n",
"\n",
"\tdelete tsConfig.compilerOptions.moduleResolution;\n",
"\twriteOutputFile('tsconfig.json', JSON.stringify(tsConfig, null, '\\t'));\n",
"\n",
"\t[\n",
"\t\t'vs/css.build.js',\n",
"\t\t'vs/css.d.ts',\n",
"\t\t'vs/css.js',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconst tsConfigBase = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.base.json')).toString());\n",
"\twriteOutputFile('tsconfig.base.json', JSON.stringify(tsConfigBase, null, '\\t'));\n"
],
"file_path": "build/lib/standalone.ts",
"type": "add",
"edit_start_line_idx": 101
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as ts from 'typescript';
import * as fs from 'fs';
import * as path from 'path';
import * as tss from './treeshaking';
const REPO_ROOT = path.join(__dirname, '../../');
const SRC_DIR = path.join(REPO_ROOT, 'src');
let dirCache: { [dir: string]: boolean; } = {};
function writeFile(filePath: string, contents: Buffer | string): void {
function ensureDirs(dirPath: string): void {
if (dirCache[dirPath]) {
return;
}
dirCache[dirPath] = true;
ensureDirs(path.dirname(dirPath));
if (fs.existsSync(dirPath)) {
return;
}
fs.mkdirSync(dirPath);
}
ensureDirs(path.dirname(filePath));
fs.writeFileSync(filePath, contents);
}
export function extractEditor(options: tss.ITreeShakingOptions & { destRoot: string }): void {
const tsConfig = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.monaco.json')).toString());
let compilerOptions: { [key: string]: any };
if (tsConfig.extends) {
compilerOptions = Object.assign({}, require(path.join(options.sourcesRoot, tsConfig.extends)).compilerOptions, tsConfig.compilerOptions);
} else {
compilerOptions = tsConfig.compilerOptions;
}
tsConfig.compilerOptions = compilerOptions;
compilerOptions.noEmit = false;
compilerOptions.noUnusedLocals = false;
compilerOptions.preserveConstEnums = false;
compilerOptions.declaration = false;
compilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;
options.compilerOptions = compilerOptions;
let result = tss.shake(options);
for (let fileName in result) {
if (result.hasOwnProperty(fileName)) {
writeFile(path.join(options.destRoot, fileName), result[fileName]);
}
}
let copied: { [fileName: string]: boolean; } = {};
const copyFile = (fileName: string) => {
if (copied[fileName]) {
return;
}
copied[fileName] = true;
const srcPath = path.join(options.sourcesRoot, fileName);
const dstPath = path.join(options.destRoot, fileName);
writeFile(dstPath, fs.readFileSync(srcPath));
};
const writeOutputFile = (fileName: string, contents: string | Buffer) => {
writeFile(path.join(options.destRoot, fileName), contents);
};
for (let fileName in result) {
if (result.hasOwnProperty(fileName)) {
const fileContents = result[fileName];
const info = ts.preProcessFile(fileContents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFileName = info.importedFiles[i].fileName;
let importedFilePath: string;
if (/^vs\/css!/.test(importedFileName)) {
importedFilePath = importedFileName.substr('vs/css!'.length) + '.css';
} else {
importedFilePath = importedFileName;
}
if (/(^\.\/)|(^\.\.\/)/.test(importedFilePath)) {
importedFilePath = path.join(path.dirname(fileName), importedFilePath);
}
if (/\.css$/.test(importedFilePath)) {
transportCSS(importedFilePath, copyFile, writeOutputFile);
} else {
if (fs.existsSync(path.join(options.sourcesRoot, importedFilePath + '.js'))) {
copyFile(importedFilePath + '.js');
}
}
}
}
}
delete tsConfig.compilerOptions.moduleResolution;
writeOutputFile('tsconfig.json', JSON.stringify(tsConfig, null, '\t'));
[
'vs/css.build.js',
'vs/css.d.ts',
'vs/css.js',
'vs/loader.js',
'vs/nls.build.js',
'vs/nls.d.ts',
'vs/nls.js',
'vs/nls.mock.ts',
].forEach(copyFile);
}
export interface IOptions2 {
srcFolder: string;
outFolder: string;
outResourcesFolder: string;
ignores: string[];
renames: { [filename: string]: string; };
}
export function createESMSourcesAndResources2(options: IOptions2): void {
const SRC_FOLDER = path.join(REPO_ROOT, options.srcFolder);
const OUT_FOLDER = path.join(REPO_ROOT, options.outFolder);
const OUT_RESOURCES_FOLDER = path.join(REPO_ROOT, options.outResourcesFolder);
const getDestAbsoluteFilePath = (file: string): string => {
let dest = options.renames[file.replace(/\\/g, '/')] || file;
if (dest === 'tsconfig.json') {
return path.join(OUT_FOLDER, `tsconfig.json`);
}
if (/\.ts$/.test(dest)) {
return path.join(OUT_FOLDER, dest);
}
return path.join(OUT_RESOURCES_FOLDER, dest);
};
const allFiles = walkDirRecursive(SRC_FOLDER);
for (const file of allFiles) {
if (options.ignores.indexOf(file.replace(/\\/g, '/')) >= 0) {
continue;
}
if (file === 'tsconfig.json') {
const tsConfig = JSON.parse(fs.readFileSync(path.join(SRC_FOLDER, file)).toString());
tsConfig.compilerOptions.module = 'es6';
tsConfig.compilerOptions.outDir = path.join(path.relative(OUT_FOLDER, OUT_RESOURCES_FOLDER), 'vs').replace(/\\/g, '/');
write(getDestAbsoluteFilePath(file), JSON.stringify(tsConfig, null, '\t'));
continue;
}
if (/\.d\.ts$/.test(file) || /\.css$/.test(file) || /\.js$/.test(file)) {
// Transport the files directly
write(getDestAbsoluteFilePath(file), fs.readFileSync(path.join(SRC_FOLDER, file)));
continue;
}
if (/\.ts$/.test(file)) {
// Transform the .ts file
let fileContents = fs.readFileSync(path.join(SRC_FOLDER, file)).toString();
const info = ts.preProcessFile(fileContents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFilename = info.importedFiles[i].fileName;
const pos = info.importedFiles[i].pos;
const end = info.importedFiles[i].end;
let importedFilepath: string;
if (/^vs\/css!/.test(importedFilename)) {
importedFilepath = importedFilename.substr('vs/css!'.length) + '.css';
} else {
importedFilepath = importedFilename;
}
if (/(^\.\/)|(^\.\.\/)/.test(importedFilepath)) {
importedFilepath = path.join(path.dirname(file), importedFilepath);
}
let relativePath: string;
if (importedFilepath === path.dirname(file).replace(/\\/g, '/')) {
relativePath = '../' + path.basename(path.dirname(file));
} else if (importedFilepath === path.dirname(path.dirname(file)).replace(/\\/g, '/')) {
relativePath = '../../' + path.basename(path.dirname(path.dirname(file)));
} else {
relativePath = path.relative(path.dirname(file), importedFilepath);
}
relativePath = relativePath.replace(/\\/g, '/');
if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
relativePath = './' + relativePath;
}
fileContents = (
fileContents.substring(0, pos + 1)
+ relativePath
+ fileContents.substring(end + 1)
);
}
fileContents = fileContents.replace(/import ([a-zA-z0-9]+) = require\(('[^']+')\);/g, function (_, m1, m2) {
return `import * as ${m1} from ${m2};`;
});
write(getDestAbsoluteFilePath(file), fileContents);
continue;
}
console.log(`UNKNOWN FILE: ${file}`);
}
function walkDirRecursive(dir: string): string[] {
if (dir.charAt(dir.length - 1) !== '/' || dir.charAt(dir.length - 1) !== '\\') {
dir += '/';
}
let result: string[] = [];
_walkDirRecursive(dir, result, dir.length);
return result;
}
function _walkDirRecursive(dir: string, result: string[], trimPos: number): void {
const files = fs.readdirSync(dir);
for (let i = 0; i < files.length; i++) {
const file = path.join(dir, files[i]);
if (fs.statSync(file).isDirectory()) {
_walkDirRecursive(file, result, trimPos);
} else {
result.push(file.substr(trimPos));
}
}
}
function write(absoluteFilePath: string, contents: string | Buffer): void {
if (/(\.ts$)|(\.js$)/.test(absoluteFilePath)) {
contents = toggleComments(contents.toString());
}
writeFile(absoluteFilePath, contents);
function toggleComments(fileContents: string): string {
let lines = fileContents.split(/\r\n|\r|\n/);
let mode = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (mode === 0) {
if (/\/\/ ESM-comment-begin/.test(line)) {
mode = 1;
continue;
}
if (/\/\/ ESM-uncomment-begin/.test(line)) {
mode = 2;
continue;
}
continue;
}
if (mode === 1) {
if (/\/\/ ESM-comment-end/.test(line)) {
mode = 0;
continue;
}
lines[i] = '// ' + line;
continue;
}
if (mode === 2) {
if (/\/\/ ESM-uncomment-end/.test(line)) {
mode = 0;
continue;
}
lines[i] = line.replace(/^(\s*)\/\/ ?/, function (_, indent) {
return indent;
});
}
}
return lines.join('\n');
}
}
}
function transportCSS(module: string, enqueue: (module: string) => void, write: (path: string, contents: string | Buffer) => void): boolean {
if (!/\.css/.test(module)) {
return false;
}
const filename = path.join(SRC_DIR, module);
const fileContents = fs.readFileSync(filename).toString();
const inlineResources = 'base64'; // see https://github.com/Microsoft/monaco-editor/issues/148
const inlineResourcesLimit = 300000;//3000; // see https://github.com/Microsoft/monaco-editor/issues/336
const newContents = _rewriteOrInlineUrls(fileContents, inlineResources === 'base64', inlineResourcesLimit);
write(module, newContents);
return true;
function _rewriteOrInlineUrls(contents: string, forceBase64: boolean, inlineByteLimit: number): string {
return _replaceURL(contents, (url) => {
let imagePath = path.join(path.dirname(module), url);
let fileContents = fs.readFileSync(path.join(SRC_DIR, imagePath));
if (fileContents.length < inlineByteLimit) {
const MIME = /\.svg$/.test(url) ? 'image/svg+xml' : 'image/png';
let DATA = ';base64,' + fileContents.toString('base64');
if (!forceBase64 && /\.svg$/.test(url)) {
// .svg => url encode as explained at https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
let newText = fileContents.toString()
.replace(/"/g, '\'')
.replace(/</g, '%3C')
.replace(/>/g, '%3E')
.replace(/&/g, '%26')
.replace(/#/g, '%23')
.replace(/\s+/g, ' ');
let encodedData = ',' + newText;
if (encodedData.length < DATA.length) {
DATA = encodedData;
}
}
return '"data:' + MIME + DATA + '"';
}
enqueue(imagePath);
return url;
});
}
function _replaceURL(contents: string, replacer: (url: string) => string): string {
// Use ")" as the terminator as quotes are oftentimes not used at all
return contents.replace(/url\(\s*([^\)]+)\s*\)?/g, (_: string, ...matches: string[]) => {
let url = matches[0];
// Eliminate starting quotes (the initial whitespace is not captured)
if (url.charAt(0) === '"' || url.charAt(0) === '\'') {
url = url.substring(1);
}
// The ending whitespace is captured
while (url.length > 0 && (url.charAt(url.length - 1) === ' ' || url.charAt(url.length - 1) === '\t')) {
url = url.substring(0, url.length - 1);
}
// Eliminate ending quotes
if (url.charAt(url.length - 1) === '"' || url.charAt(url.length - 1) === '\'') {
url = url.substring(0, url.length - 1);
}
if (!_startsWith(url, 'data:') && !_startsWith(url, 'http://') && !_startsWith(url, 'https://')) {
url = replacer(url);
}
return 'url(' + url + ')';
});
}
function _startsWith(haystack: string, needle: string): boolean {
return haystack.length >= needle.length && haystack.substr(0, needle.length) === needle;
}
}
| build/lib/standalone.ts | 1 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.23904430866241455,
0.00803037453442812,
0.00016165644046850502,
0.00017339504847768694,
0.03938338905572891
]
|
{
"id": 3,
"code_window": [
"\t\t}\n",
"\t}\n",
"\n",
"\tdelete tsConfig.compilerOptions.moduleResolution;\n",
"\twriteOutputFile('tsconfig.json', JSON.stringify(tsConfig, null, '\\t'));\n",
"\n",
"\t[\n",
"\t\t'vs/css.build.js',\n",
"\t\t'vs/css.d.ts',\n",
"\t\t'vs/css.js',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconst tsConfigBase = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.base.json')).toString());\n",
"\twriteOutputFile('tsconfig.base.json', JSON.stringify(tsConfigBase, null, '\\t'));\n"
],
"file_path": "build/lib/standalone.ts",
"type": "add",
"edit_start_line_idx": 101
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { CommandManager } from './commandManager';
import * as commands from './commands/index';
import LinkProvider from './features/documentLinkProvider';
import MDDocumentSymbolProvider from './features/documentSymbolProvider';
import MarkdownFoldingProvider from './features/foldingProvider';
import { MarkdownContentProvider } from './features/previewContentProvider';
import { MarkdownPreviewManager } from './features/previewManager';
import MarkdownWorkspaceSymbolProvider from './features/workspaceSymbolProvider';
import { Logger } from './logger';
import { MarkdownEngine } from './markdownEngine';
import { getMarkdownExtensionContributions } from './markdownExtensions';
import { ExtensionContentSecurityPolicyArbiter, PreviewSecuritySelector, ContentSecurityPolicyArbiter } from './security';
import { loadDefaultTelemetryReporter, TelemetryReporter } from './telemetryReporter';
import { githubSlugifier } from './slugify';
export function activate(context: vscode.ExtensionContext) {
const telemetryReporter = loadDefaultTelemetryReporter();
context.subscriptions.push(telemetryReporter);
const contributions = getMarkdownExtensionContributions(context);
context.subscriptions.push(contributions);
const cspArbiter = new ExtensionContentSecurityPolicyArbiter(context.globalState, context.workspaceState);
const engine = new MarkdownEngine(contributions, githubSlugifier);
const logger = new Logger();
const contentProvider = new MarkdownContentProvider(engine, context, cspArbiter, contributions, logger);
const symbolProvider = new MDDocumentSymbolProvider(engine);
const previewManager = new MarkdownPreviewManager(contentProvider, logger, contributions);
context.subscriptions.push(previewManager);
context.subscriptions.push(registerMarkdownLanguageFeatures(symbolProvider, engine));
context.subscriptions.push(registerMarkdownCommands(previewManager, telemetryReporter, cspArbiter, engine));
context.subscriptions.push(vscode.workspace.onDidChangeConfiguration(() => {
logger.updateConfiguration();
previewManager.updateConfiguration();
}));
}
function registerMarkdownLanguageFeatures(
symbolProvider: MDDocumentSymbolProvider,
engine: MarkdownEngine
): vscode.Disposable {
const selector: vscode.DocumentSelector = [
{ language: 'markdown', scheme: 'file' },
{ language: 'markdown', scheme: 'untitled' }
];
return vscode.Disposable.from(
vscode.languages.setLanguageConfiguration('markdown', {
wordPattern: new RegExp('(\\p{Alphabetic}|\\p{Number})+', 'ug'),
}),
vscode.languages.registerDocumentSymbolProvider(selector, symbolProvider),
vscode.languages.registerDocumentLinkProvider(selector, new LinkProvider()),
vscode.languages.registerFoldingRangeProvider(selector, new MarkdownFoldingProvider(engine)),
vscode.languages.registerWorkspaceSymbolProvider(new MarkdownWorkspaceSymbolProvider(symbolProvider))
);
}
function registerMarkdownCommands(
previewManager: MarkdownPreviewManager,
telemetryReporter: TelemetryReporter,
cspArbiter: ContentSecurityPolicyArbiter,
engine: MarkdownEngine
): vscode.Disposable {
const previewSecuritySelector = new PreviewSecuritySelector(cspArbiter, previewManager);
const commandManager = new CommandManager();
commandManager.register(new commands.ShowPreviewCommand(previewManager, telemetryReporter));
commandManager.register(new commands.ShowPreviewToSideCommand(previewManager, telemetryReporter));
commandManager.register(new commands.ShowLockedPreviewToSideCommand(previewManager, telemetryReporter));
commandManager.register(new commands.ShowSourceCommand(previewManager));
commandManager.register(new commands.RefreshPreviewCommand(previewManager, engine));
commandManager.register(new commands.MoveCursorToPositionCommand());
commandManager.register(new commands.ShowPreviewSecuritySelectorCommand(previewSecuritySelector, previewManager));
commandManager.register(new commands.OpenDocumentLinkCommand(engine));
commandManager.register(new commands.ToggleLockCommand(previewManager));
return commandManager;
}
| extensions/markdown-language-features/src/extension.ts | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.00017856646445579827,
0.0001751697127474472,
0.00016805398627184331,
0.00017554426449351013,
0.0000032030302463681437
]
|
{
"id": 3,
"code_window": [
"\t\t}\n",
"\t}\n",
"\n",
"\tdelete tsConfig.compilerOptions.moduleResolution;\n",
"\twriteOutputFile('tsconfig.json', JSON.stringify(tsConfig, null, '\\t'));\n",
"\n",
"\t[\n",
"\t\t'vs/css.build.js',\n",
"\t\t'vs/css.d.ts',\n",
"\t\t'vs/css.js',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconst tsConfigBase = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.base.json')).toString());\n",
"\twriteOutputFile('tsconfig.base.json', JSON.stringify(tsConfigBase, null, '\\t'));\n"
],
"file_path": "build/lib/standalone.ts",
"type": "add",
"edit_start_line_idx": 101
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as Formatter from 'vs/base/common/jsonFormatter';
import * as assert from 'assert';
suite('JSON - formatter', () => {
function format(content: string, expected: string, insertSpaces = true) {
let range: Formatter.Range | undefined = undefined;
const rangeStart = content.indexOf('|');
const rangeEnd = content.lastIndexOf('|');
if (rangeStart !== -1 && rangeEnd !== -1) {
content = content.substring(0, rangeStart) + content.substring(rangeStart + 1, rangeEnd) + content.substring(rangeEnd + 1);
range = { offset: rangeStart, length: rangeEnd - rangeStart };
}
const edits = Formatter.format(content, range, { tabSize: 2, insertSpaces: insertSpaces, eol: '\n' });
let lastEditOffset = content.length;
for (let i = edits.length - 1; i >= 0; i--) {
let edit = edits[i];
assert(edit.offset >= 0 && edit.length >= 0 && edit.offset + edit.length <= content.length);
assert(typeof edit.content === 'string');
assert(lastEditOffset >= edit.offset + edit.length); // make sure all edits are ordered
lastEditOffset = edit.offset;
content = content.substring(0, edit.offset) + edit.content + content.substring(edit.offset + edit.length);
}
assert.equal(content, expected);
}
test('object - single property', () => {
const content = [
'{"x" : 1}'
].join('\n');
const expected = [
'{',
' "x": 1',
'}'
].join('\n');
format(content, expected);
});
test('object - multiple properties', () => {
const content = [
'{"x" : 1, "y" : "foo", "z" : true}'
].join('\n');
const expected = [
'{',
' "x": 1,',
' "y": "foo",',
' "z": true',
'}'
].join('\n');
format(content, expected);
});
test('object - no properties ', () => {
const content = [
'{"x" : { }, "y" : {}}'
].join('\n');
const expected = [
'{',
' "x": {},',
' "y": {}',
'}'
].join('\n');
format(content, expected);
});
test('object - nesting', () => {
const content = [
'{"x" : { "y" : { "z" : { }}, "a": true}}'
].join('\n');
const expected = [
'{',
' "x": {',
' "y": {',
' "z": {}',
' },',
' "a": true',
' }',
'}'
].join('\n');
format(content, expected);
});
test('array - single items', () => {
const content = [
'["[]"]'
].join('\n');
const expected = [
'[',
' "[]"',
']'
].join('\n');
format(content, expected);
});
test('array - multiple items', () => {
const content = [
'[true,null,1.2]'
].join('\n');
const expected = [
'[',
' true,',
' null,',
' 1.2',
']'
].join('\n');
format(content, expected);
});
test('array - no items', () => {
const content = [
'[ ]'
].join('\n');
const expected = [
'[]'
].join('\n');
format(content, expected);
});
test('array - nesting', () => {
const content = [
'[ [], [ [ {} ], "a" ] ]'
].join('\n');
const expected = [
'[',
' [],',
' [',
' [',
' {}',
' ],',
' "a"',
' ]',
']',
].join('\n');
format(content, expected);
});
test('syntax errors', () => {
const content = [
'[ null 1.2 ]'
].join('\n');
const expected = [
'[',
' null 1.2',
']',
].join('\n');
format(content, expected);
});
test('empty lines', () => {
const content = [
'{',
'"a": true,',
'',
'"b": true',
'}',
].join('\n');
const expected = [
'{',
'\t"a": true,',
'\t"b": true',
'}',
].join('\n');
format(content, expected, false);
});
test('single line comment', () => {
const content = [
'[ ',
'//comment',
'"foo", "bar"',
'] '
].join('\n');
const expected = [
'[',
' //comment',
' "foo",',
' "bar"',
']',
].join('\n');
format(content, expected);
});
test('block line comment', () => {
const content = [
'[{',
' /*comment*/ ',
'"foo" : true',
'}] '
].join('\n');
const expected = [
'[',
' {',
' /*comment*/',
' "foo": true',
' }',
']',
].join('\n');
format(content, expected);
});
test('single line comment on same line', () => {
const content = [
' { ',
' "a": {}// comment ',
' } '
].join('\n');
const expected = [
'{',
' "a": {} // comment ',
'}',
].join('\n');
format(content, expected);
});
test('single line comment on same line 2', () => {
const content = [
'{ //comment',
'}'
].join('\n');
const expected = [
'{ //comment',
'}'
].join('\n');
format(content, expected);
});
test('block comment on same line', () => {
const content = [
'{ "a": {}, /*comment*/ ',
' /*comment*/ "b": {}, ',
' "c": {/*comment*/} } ',
].join('\n');
const expected = [
'{',
' "a": {}, /*comment*/',
' /*comment*/ "b": {},',
' "c": { /*comment*/}',
'}',
].join('\n');
format(content, expected);
});
test('block comment on same line advanced', () => {
const content = [
' { "d": [',
' null',
' ] /*comment*/',
' ,"e": /*comment*/ [null] }',
].join('\n');
const expected = [
'{',
' "d": [',
' null',
' ] /*comment*/,',
' "e": /*comment*/ [',
' null',
' ]',
'}',
].join('\n');
format(content, expected);
});
test('multiple block comments on same line', () => {
const content = [
'{ "a": {} /*comment*/, /*comment*/ ',
' /*comment*/ "b": {} /*comment*/ } '
].join('\n');
const expected = [
'{',
' "a": {} /*comment*/, /*comment*/',
' /*comment*/ "b": {} /*comment*/',
'}',
].join('\n');
format(content, expected);
});
test('multiple mixed comments on same line', () => {
const content = [
'[ /*comment*/ /*comment*/ // comment ',
']'
].join('\n');
const expected = [
'[ /*comment*/ /*comment*/ // comment ',
']'
].join('\n');
format(content, expected);
});
test('range', () => {
const content = [
'{ "a": {},',
'|"b": [null, null]|',
'} '
].join('\n');
const expected = [
'{ "a": {},',
'"b": [',
' null,',
' null',
']',
'} ',
].join('\n');
format(content, expected);
});
test('range with existing indent', () => {
const content = [
'{ "a": {},',
' |"b": [null],',
'"c": {}',
'}|'
].join('\n');
const expected = [
'{ "a": {},',
' "b": [',
' null',
' ],',
' "c": {}',
'}',
].join('\n');
format(content, expected);
});
test('range with existing indent - tabs', () => {
const content = [
'{ "a": {},',
'| "b": [null], ',
'"c": {}',
'} | '
].join('\n');
const expected = [
'{ "a": {},',
'\t"b": [',
'\t\tnull',
'\t],',
'\t"c": {}',
'}',
].join('\n');
format(content, expected, false);
});
test('block comment none-line breaking symbols', () => {
const content = [
'{ "a": [ 1',
'/* comment */',
', 2',
'/* comment */',
']',
'/* comment */',
',',
' "b": true',
'/* comment */',
'}'
].join('\n');
const expected = [
'{',
' "a": [',
' 1',
' /* comment */',
' ,',
' 2',
' /* comment */',
' ]',
' /* comment */',
' ,',
' "b": true',
' /* comment */',
'}',
].join('\n');
format(content, expected);
});
test('line comment after none-line breaking symbols', () => {
const content = [
'{ "a":',
'// comment',
'null,',
' "b"',
'// comment',
': null',
'// comment',
'}'
].join('\n');
const expected = [
'{',
' "a":',
' // comment',
' null,',
' "b"',
' // comment',
' : null',
' // comment',
'}',
].join('\n');
format(content, expected);
});
}); | src/vs/base/test/common/jsonFormatter.test.ts | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.0001745381741784513,
0.00017111925990320742,
0.00016717750986572355,
0.00017083482816815376,
0.0000016563204781050445
]
|
{
"id": 3,
"code_window": [
"\t\t}\n",
"\t}\n",
"\n",
"\tdelete tsConfig.compilerOptions.moduleResolution;\n",
"\twriteOutputFile('tsconfig.json', JSON.stringify(tsConfig, null, '\\t'));\n",
"\n",
"\t[\n",
"\t\t'vs/css.build.js',\n",
"\t\t'vs/css.d.ts',\n",
"\t\t'vs/css.js',\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tconst tsConfigBase = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.base.json')).toString());\n",
"\twriteOutputFile('tsconfig.base.json', JSON.stringify(tsConfigBase, null, '\\t'));\n"
],
"file_path": "build/lib/standalone.ts",
"type": "add",
"edit_start_line_idx": 101
} | {
"title": "JSON schema for the TypeScript compiler's configuration file",
"type": "object",
"default": {
"compilerOptions": {
"module": "commonjs"
},
"exclude": [
"node_modules"
]
}
}
| extensions/typescript-basics/schemas/tsconfig.schema.json | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.00018255101167596877,
0.00017770464182831347,
0.00017285825742874295,
0.00017770464182831347,
0.0000048463771236129105
]
|
{
"id": 4,
"code_window": [
"\t\t\"removeComments\": false,\n",
"\t\t\"preserveConstEnums\": true,\n",
"\t\t\"target\": \"es5\",\n",
"\t\t\"sourceMap\": false,\n",
"\t\t\"declaration\": true,\n",
"\t},\n",
"\t\"include\": [\n",
"\t\t\"typings/require.d.ts\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"declaration\": true\n"
],
"file_path": "src/tsconfig.monaco.json",
"type": "replace",
"edit_start_line_idx": 12
} | "use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
const ts = require("typescript");
const fs = require("fs");
const path = require("path");
const tss = require("./treeshaking");
const REPO_ROOT = path.join(__dirname, '../../');
const SRC_DIR = path.join(REPO_ROOT, 'src');
let dirCache = {};
function writeFile(filePath, contents) {
function ensureDirs(dirPath) {
if (dirCache[dirPath]) {
return;
}
dirCache[dirPath] = true;
ensureDirs(path.dirname(dirPath));
if (fs.existsSync(dirPath)) {
return;
}
fs.mkdirSync(dirPath);
}
ensureDirs(path.dirname(filePath));
fs.writeFileSync(filePath, contents);
}
function extractEditor(options) {
const tsConfig = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.monaco.json')).toString());
let compilerOptions;
if (tsConfig.extends) {
compilerOptions = Object.assign({}, require(path.join(options.sourcesRoot, tsConfig.extends)).compilerOptions, tsConfig.compilerOptions);
}
else {
compilerOptions = tsConfig.compilerOptions;
}
tsConfig.compilerOptions = compilerOptions;
compilerOptions.noEmit = false;
compilerOptions.noUnusedLocals = false;
compilerOptions.preserveConstEnums = false;
compilerOptions.declaration = false;
compilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;
options.compilerOptions = compilerOptions;
let result = tss.shake(options);
for (let fileName in result) {
if (result.hasOwnProperty(fileName)) {
writeFile(path.join(options.destRoot, fileName), result[fileName]);
}
}
let copied = {};
const copyFile = (fileName) => {
if (copied[fileName]) {
return;
}
copied[fileName] = true;
const srcPath = path.join(options.sourcesRoot, fileName);
const dstPath = path.join(options.destRoot, fileName);
writeFile(dstPath, fs.readFileSync(srcPath));
};
const writeOutputFile = (fileName, contents) => {
writeFile(path.join(options.destRoot, fileName), contents);
};
for (let fileName in result) {
if (result.hasOwnProperty(fileName)) {
const fileContents = result[fileName];
const info = ts.preProcessFile(fileContents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFileName = info.importedFiles[i].fileName;
let importedFilePath;
if (/^vs\/css!/.test(importedFileName)) {
importedFilePath = importedFileName.substr('vs/css!'.length) + '.css';
}
else {
importedFilePath = importedFileName;
}
if (/(^\.\/)|(^\.\.\/)/.test(importedFilePath)) {
importedFilePath = path.join(path.dirname(fileName), importedFilePath);
}
if (/\.css$/.test(importedFilePath)) {
transportCSS(importedFilePath, copyFile, writeOutputFile);
}
else {
if (fs.existsSync(path.join(options.sourcesRoot, importedFilePath + '.js'))) {
copyFile(importedFilePath + '.js');
}
}
}
}
}
delete tsConfig.compilerOptions.moduleResolution;
writeOutputFile('tsconfig.json', JSON.stringify(tsConfig, null, '\t'));
[
'vs/css.build.js',
'vs/css.d.ts',
'vs/css.js',
'vs/loader.js',
'vs/nls.build.js',
'vs/nls.d.ts',
'vs/nls.js',
'vs/nls.mock.ts',
].forEach(copyFile);
}
exports.extractEditor = extractEditor;
function createESMSourcesAndResources2(options) {
const SRC_FOLDER = path.join(REPO_ROOT, options.srcFolder);
const OUT_FOLDER = path.join(REPO_ROOT, options.outFolder);
const OUT_RESOURCES_FOLDER = path.join(REPO_ROOT, options.outResourcesFolder);
const getDestAbsoluteFilePath = (file) => {
let dest = options.renames[file.replace(/\\/g, '/')] || file;
if (dest === 'tsconfig.json') {
return path.join(OUT_FOLDER, `tsconfig.json`);
}
if (/\.ts$/.test(dest)) {
return path.join(OUT_FOLDER, dest);
}
return path.join(OUT_RESOURCES_FOLDER, dest);
};
const allFiles = walkDirRecursive(SRC_FOLDER);
for (const file of allFiles) {
if (options.ignores.indexOf(file.replace(/\\/g, '/')) >= 0) {
continue;
}
if (file === 'tsconfig.json') {
const tsConfig = JSON.parse(fs.readFileSync(path.join(SRC_FOLDER, file)).toString());
tsConfig.compilerOptions.module = 'es6';
tsConfig.compilerOptions.outDir = path.join(path.relative(OUT_FOLDER, OUT_RESOURCES_FOLDER), 'vs').replace(/\\/g, '/');
write(getDestAbsoluteFilePath(file), JSON.stringify(tsConfig, null, '\t'));
continue;
}
if (/\.d\.ts$/.test(file) || /\.css$/.test(file) || /\.js$/.test(file)) {
// Transport the files directly
write(getDestAbsoluteFilePath(file), fs.readFileSync(path.join(SRC_FOLDER, file)));
continue;
}
if (/\.ts$/.test(file)) {
// Transform the .ts file
let fileContents = fs.readFileSync(path.join(SRC_FOLDER, file)).toString();
const info = ts.preProcessFile(fileContents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFilename = info.importedFiles[i].fileName;
const pos = info.importedFiles[i].pos;
const end = info.importedFiles[i].end;
let importedFilepath;
if (/^vs\/css!/.test(importedFilename)) {
importedFilepath = importedFilename.substr('vs/css!'.length) + '.css';
}
else {
importedFilepath = importedFilename;
}
if (/(^\.\/)|(^\.\.\/)/.test(importedFilepath)) {
importedFilepath = path.join(path.dirname(file), importedFilepath);
}
let relativePath;
if (importedFilepath === path.dirname(file).replace(/\\/g, '/')) {
relativePath = '../' + path.basename(path.dirname(file));
}
else if (importedFilepath === path.dirname(path.dirname(file)).replace(/\\/g, '/')) {
relativePath = '../../' + path.basename(path.dirname(path.dirname(file)));
}
else {
relativePath = path.relative(path.dirname(file), importedFilepath);
}
relativePath = relativePath.replace(/\\/g, '/');
if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
relativePath = './' + relativePath;
}
fileContents = (fileContents.substring(0, pos + 1)
+ relativePath
+ fileContents.substring(end + 1));
}
fileContents = fileContents.replace(/import ([a-zA-z0-9]+) = require\(('[^']+')\);/g, function (_, m1, m2) {
return `import * as ${m1} from ${m2};`;
});
write(getDestAbsoluteFilePath(file), fileContents);
continue;
}
console.log(`UNKNOWN FILE: ${file}`);
}
function walkDirRecursive(dir) {
if (dir.charAt(dir.length - 1) !== '/' || dir.charAt(dir.length - 1) !== '\\') {
dir += '/';
}
let result = [];
_walkDirRecursive(dir, result, dir.length);
return result;
}
function _walkDirRecursive(dir, result, trimPos) {
const files = fs.readdirSync(dir);
for (let i = 0; i < files.length; i++) {
const file = path.join(dir, files[i]);
if (fs.statSync(file).isDirectory()) {
_walkDirRecursive(file, result, trimPos);
}
else {
result.push(file.substr(trimPos));
}
}
}
function write(absoluteFilePath, contents) {
if (/(\.ts$)|(\.js$)/.test(absoluteFilePath)) {
contents = toggleComments(contents.toString());
}
writeFile(absoluteFilePath, contents);
function toggleComments(fileContents) {
let lines = fileContents.split(/\r\n|\r|\n/);
let mode = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (mode === 0) {
if (/\/\/ ESM-comment-begin/.test(line)) {
mode = 1;
continue;
}
if (/\/\/ ESM-uncomment-begin/.test(line)) {
mode = 2;
continue;
}
continue;
}
if (mode === 1) {
if (/\/\/ ESM-comment-end/.test(line)) {
mode = 0;
continue;
}
lines[i] = '// ' + line;
continue;
}
if (mode === 2) {
if (/\/\/ ESM-uncomment-end/.test(line)) {
mode = 0;
continue;
}
lines[i] = line.replace(/^(\s*)\/\/ ?/, function (_, indent) {
return indent;
});
}
}
return lines.join('\n');
}
}
}
exports.createESMSourcesAndResources2 = createESMSourcesAndResources2;
function transportCSS(module, enqueue, write) {
if (!/\.css/.test(module)) {
return false;
}
const filename = path.join(SRC_DIR, module);
const fileContents = fs.readFileSync(filename).toString();
const inlineResources = 'base64'; // see https://github.com/Microsoft/monaco-editor/issues/148
const inlineResourcesLimit = 300000; //3000; // see https://github.com/Microsoft/monaco-editor/issues/336
const newContents = _rewriteOrInlineUrls(fileContents, inlineResources === 'base64', inlineResourcesLimit);
write(module, newContents);
return true;
function _rewriteOrInlineUrls(contents, forceBase64, inlineByteLimit) {
return _replaceURL(contents, (url) => {
let imagePath = path.join(path.dirname(module), url);
let fileContents = fs.readFileSync(path.join(SRC_DIR, imagePath));
if (fileContents.length < inlineByteLimit) {
const MIME = /\.svg$/.test(url) ? 'image/svg+xml' : 'image/png';
let DATA = ';base64,' + fileContents.toString('base64');
if (!forceBase64 && /\.svg$/.test(url)) {
// .svg => url encode as explained at https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
let newText = fileContents.toString()
.replace(/"/g, '\'')
.replace(/</g, '%3C')
.replace(/>/g, '%3E')
.replace(/&/g, '%26')
.replace(/#/g, '%23')
.replace(/\s+/g, ' ');
let encodedData = ',' + newText;
if (encodedData.length < DATA.length) {
DATA = encodedData;
}
}
return '"data:' + MIME + DATA + '"';
}
enqueue(imagePath);
return url;
});
}
function _replaceURL(contents, replacer) {
// Use ")" as the terminator as quotes are oftentimes not used at all
return contents.replace(/url\(\s*([^\)]+)\s*\)?/g, (_, ...matches) => {
let url = matches[0];
// Eliminate starting quotes (the initial whitespace is not captured)
if (url.charAt(0) === '"' || url.charAt(0) === '\'') {
url = url.substring(1);
}
// The ending whitespace is captured
while (url.length > 0 && (url.charAt(url.length - 1) === ' ' || url.charAt(url.length - 1) === '\t')) {
url = url.substring(0, url.length - 1);
}
// Eliminate ending quotes
if (url.charAt(url.length - 1) === '"' || url.charAt(url.length - 1) === '\'') {
url = url.substring(0, url.length - 1);
}
if (!_startsWith(url, 'data:') && !_startsWith(url, 'http://') && !_startsWith(url, 'https://')) {
url = replacer(url);
}
return 'url(' + url + ')';
});
}
function _startsWith(haystack, needle) {
return haystack.length >= needle.length && haystack.substr(0, needle.length) === needle;
}
}
| build/lib/standalone.js | 1 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.0044256397522985935,
0.0003201551444362849,
0.000164296172442846,
0.00017168429621960968,
0.0007516630575992167
]
|
{
"id": 4,
"code_window": [
"\t\t\"removeComments\": false,\n",
"\t\t\"preserveConstEnums\": true,\n",
"\t\t\"target\": \"es5\",\n",
"\t\t\"sourceMap\": false,\n",
"\t\t\"declaration\": true,\n",
"\t},\n",
"\t\"include\": [\n",
"\t\t\"typings/require.d.ts\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"declaration\": true\n"
],
"file_path": "src/tsconfig.monaco.json",
"type": "replace",
"edit_start_line_idx": 12
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { MainContext, IMainContext, ExtHostUrlsShape, MainThreadUrlsShape } from './extHost.protocol';
import { URI, UriComponents } from 'vs/base/common/uri';
import { toDisposable } from 'vs/base/common/lifecycle';
import { onUnexpectedError } from 'vs/base/common/errors';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
export class ExtHostUrls implements ExtHostUrlsShape {
private static HandlePool = 0;
private readonly _proxy: MainThreadUrlsShape;
private handles = new Set<string>();
private handlers = new Map<number, vscode.UriHandler>();
constructor(
mainContext: IMainContext
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadUrls);
}
registerUriHandler(extensionId: ExtensionIdentifier, handler: vscode.UriHandler): vscode.Disposable {
if (this.handles.has(ExtensionIdentifier.toKey(extensionId))) {
throw new Error(`Protocol handler already registered for extension ${extensionId}`);
}
const handle = ExtHostUrls.HandlePool++;
this.handles.add(ExtensionIdentifier.toKey(extensionId));
this.handlers.set(handle, handler);
this._proxy.$registerUriHandler(handle, extensionId);
return toDisposable(() => {
this.handles.delete(ExtensionIdentifier.toKey(extensionId));
this.handlers.delete(handle);
this._proxy.$unregisterUriHandler(handle);
});
}
$handleExternalUri(handle: number, uri: UriComponents): Promise<void> {
const handler = this.handlers.get(handle);
if (!handler) {
return Promise.resolve(undefined);
}
try {
handler.handleUri(URI.revive(uri));
} catch (err) {
onUnexpectedError(err);
}
return Promise.resolve(undefined);
}
}
| src/vs/workbench/api/common/extHostUrls.ts | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.00017488050798419863,
0.00017165100143756717,
0.00016677199164405465,
0.00017146996106021106,
0.0000027553071504371474
]
|
{
"id": 4,
"code_window": [
"\t\t\"removeComments\": false,\n",
"\t\t\"preserveConstEnums\": true,\n",
"\t\t\"target\": \"es5\",\n",
"\t\t\"sourceMap\": false,\n",
"\t\t\"declaration\": true,\n",
"\t},\n",
"\t\"include\": [\n",
"\t\t\"typings/require.d.ts\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"declaration\": true\n"
],
"file_path": "src/tsconfig.monaco.json",
"type": "replace",
"edit_start_line_idx": 12
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { dispose } from 'vs/base/common/lifecycle';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { registerEditorAction, registerEditorContribution, ServicesAccessor, EditorAction, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { ParameterHintsWidget } from './parameterHintsWidget';
import { Context } from 'vs/editor/contrib/parameterHints/provideSignatureHelp';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import * as modes from 'vs/editor/common/modes';
import { TriggerContext } from 'vs/editor/contrib/parameterHints/parameterHintsModel';
class ParameterHintsController implements IEditorContribution {
private static readonly ID = 'editor.controller.parameterHints';
public static get(editor: ICodeEditor): ParameterHintsController {
return editor.getContribution<ParameterHintsController>(ParameterHintsController.ID);
}
private readonly editor: ICodeEditor;
private readonly widget: ParameterHintsWidget;
constructor(editor: ICodeEditor, @IInstantiationService instantiationService: IInstantiationService) {
this.editor = editor;
this.widget = instantiationService.createInstance(ParameterHintsWidget, this.editor);
}
getId(): string {
return ParameterHintsController.ID;
}
cancel(): void {
this.widget.cancel();
}
previous(): void {
this.widget.previous();
}
next(): void {
this.widget.next();
}
trigger(context: TriggerContext): void {
this.widget.trigger(context);
}
dispose(): void {
dispose(this.widget);
}
}
export class TriggerParameterHintsAction extends EditorAction {
constructor() {
super({
id: 'editor.action.triggerParameterHints',
label: nls.localize('parameterHints.trigger.label', "Trigger Parameter Hints"),
alias: 'Trigger Parameter Hints',
precondition: EditorContextKeys.hasSignatureHelpProvider,
kbOpts: {
kbExpr: EditorContextKeys.editorTextFocus,
primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Space,
weight: KeybindingWeight.EditorContrib
}
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
let controller = ParameterHintsController.get(editor);
if (controller) {
controller.trigger({
triggerKind: modes.SignatureHelpTriggerKind.Invoke
});
}
}
}
registerEditorContribution(ParameterHintsController);
registerEditorAction(TriggerParameterHintsAction);
const weight = KeybindingWeight.EditorContrib + 75;
const ParameterHintsCommand = EditorCommand.bindToContribution<ParameterHintsController>(ParameterHintsController.get);
registerEditorCommand(new ParameterHintsCommand({
id: 'closeParameterHints',
precondition: Context.Visible,
handler: x => x.cancel(),
kbOpts: {
weight: weight,
kbExpr: EditorContextKeys.focus,
primary: KeyCode.Escape,
secondary: [KeyMod.Shift | KeyCode.Escape]
}
}));
registerEditorCommand(new ParameterHintsCommand({
id: 'showPrevParameterHint',
precondition: ContextKeyExpr.and(Context.Visible, Context.MultipleSignatures),
handler: x => x.previous(),
kbOpts: {
weight: weight,
kbExpr: EditorContextKeys.focus,
primary: KeyCode.UpArrow,
secondary: [KeyMod.Alt | KeyCode.UpArrow],
mac: { primary: KeyCode.UpArrow, secondary: [KeyMod.Alt | KeyCode.UpArrow, KeyMod.WinCtrl | KeyCode.KEY_P] }
}
}));
registerEditorCommand(new ParameterHintsCommand({
id: 'showNextParameterHint',
precondition: ContextKeyExpr.and(Context.Visible, Context.MultipleSignatures),
handler: x => x.next(),
kbOpts: {
weight: weight,
kbExpr: EditorContextKeys.focus,
primary: KeyCode.DownArrow,
secondary: [KeyMod.Alt | KeyCode.DownArrow],
mac: { primary: KeyCode.DownArrow, secondary: [KeyMod.Alt | KeyCode.DownArrow, KeyMod.WinCtrl | KeyCode.KEY_N] }
}
}));
| src/vs/editor/contrib/parameterHints/parameterHints.ts | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.0001785523199941963,
0.00017299542378168553,
0.0001678059488767758,
0.00017352246504742652,
0.00000286286467598984
]
|
{
"id": 4,
"code_window": [
"\t\t\"removeComments\": false,\n",
"\t\t\"preserveConstEnums\": true,\n",
"\t\t\"target\": \"es5\",\n",
"\t\t\"sourceMap\": false,\n",
"\t\t\"declaration\": true,\n",
"\t},\n",
"\t\"include\": [\n",
"\t\t\"typings/require.d.ts\",\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\"declaration\": true\n"
],
"file_path": "src/tsconfig.monaco.json",
"type": "replace",
"edit_start_line_idx": 12
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./accessibility';
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode';
import { renderFormattedText } from 'vs/base/browser/htmlContentRenderer';
import { alert } from 'vs/base/browser/ui/aria/aria';
import { Widget } from 'vs/base/browser/ui/widget';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { Disposable } from 'vs/base/common/lifecycle';
import * as platform from 'vs/base/common/platform';
import * as strings from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { ICodeEditor, IOverlayWidget, IOverlayWidgetPosition } from 'vs/editor/browser/editorBrowser';
import { EditorAction, EditorCommand, registerEditorAction, registerEditorCommand, registerEditorContribution } from 'vs/editor/browser/editorExtensions';
import * as editorOptions from 'vs/editor/common/config/editorOptions';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { ToggleTabFocusModeAction } from 'vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode';
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { contrastBorder, editorWidgetBackground, widgetShadow } from 'vs/platform/theme/common/colorRegistry';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility';
const CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE = new RawContextKey<boolean>('accessibilityHelpWidgetVisible', false);
class AccessibilityHelpController extends Disposable implements IEditorContribution {
private static readonly ID = 'editor.contrib.accessibilityHelpController';
public static get(editor: ICodeEditor): AccessibilityHelpController {
return editor.getContribution<AccessibilityHelpController>(AccessibilityHelpController.ID);
}
private _editor: ICodeEditor;
private _widget: AccessibilityHelpWidget;
constructor(
editor: ICodeEditor,
@IInstantiationService instantiationService: IInstantiationService
) {
super();
this._editor = editor;
this._widget = this._register(instantiationService.createInstance(AccessibilityHelpWidget, this._editor));
}
public getId(): string {
return AccessibilityHelpController.ID;
}
public show(): void {
this._widget.show();
}
public hide(): void {
this._widget.hide();
}
}
class AccessibilityHelpWidget extends Widget implements IOverlayWidget {
private static readonly ID = 'editor.contrib.accessibilityHelpWidget';
private static readonly WIDTH = 500;
private static readonly HEIGHT = 300;
private _editor: ICodeEditor;
private _domNode: FastDomNode<HTMLElement>;
private _contentDomNode: FastDomNode<HTMLElement>;
private _isVisible: boolean;
private _isVisibleKey: IContextKey<boolean>;
constructor(
editor: ICodeEditor,
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
@IKeybindingService private readonly _keybindingService: IKeybindingService,
@IConfigurationService private readonly _configurationService: IConfigurationService,
@IOpenerService private readonly _openerService: IOpenerService
) {
super();
this._editor = editor;
this._isVisibleKey = CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE.bindTo(this._contextKeyService);
this._domNode = createFastDomNode(document.createElement('div'));
this._domNode.setClassName('accessibilityHelpWidget');
this._domNode.setWidth(AccessibilityHelpWidget.WIDTH);
this._domNode.setHeight(AccessibilityHelpWidget.HEIGHT);
this._domNode.setDisplay('none');
this._domNode.setAttribute('role', 'dialog');
this._domNode.setAttribute('aria-hidden', 'true');
this._contentDomNode = createFastDomNode(document.createElement('div'));
this._contentDomNode.setAttribute('role', 'document');
this._domNode.appendChild(this._contentDomNode);
this._isVisible = false;
this._register(this._editor.onDidLayoutChange(() => {
if (this._isVisible) {
this._layout();
}
}));
// Intentionally not configurable!
this._register(dom.addStandardDisposableListener(this._contentDomNode.domNode, 'keydown', (e) => {
if (!this._isVisible) {
return;
}
if (e.equals(KeyMod.CtrlCmd | KeyCode.KEY_E)) {
alert(nls.localize('emergencyConfOn', "Now changing the setting `editor.accessibilitySupport` to 'on'."));
this._configurationService.updateValue('editor.accessibilitySupport', 'on', ConfigurationTarget.USER);
e.preventDefault();
e.stopPropagation();
}
if (e.equals(KeyMod.CtrlCmd | KeyCode.KEY_H)) {
alert(nls.localize('openingDocs', "Now opening the VS Code Accessibility documentation page."));
this._openerService.open(URI.parse('https://go.microsoft.com/fwlink/?linkid=851010'));
e.preventDefault();
e.stopPropagation();
}
}));
this.onblur(this._contentDomNode.domNode, () => {
this.hide();
});
this._editor.addOverlayWidget(this);
}
public dispose(): void {
this._editor.removeOverlayWidget(this);
super.dispose();
}
public getId(): string {
return AccessibilityHelpWidget.ID;
}
public getDomNode(): HTMLElement {
return this._domNode.domNode;
}
public getPosition(): IOverlayWidgetPosition {
return {
preference: null
};
}
public show(): void {
if (this._isVisible) {
return;
}
this._isVisible = true;
this._isVisibleKey.set(true);
this._layout();
this._domNode.setDisplay('block');
this._domNode.setAttribute('aria-hidden', 'false');
this._contentDomNode.domNode.tabIndex = 0;
this._buildContent();
this._contentDomNode.domNode.focus();
}
private _descriptionForCommand(commandId: string, msg: string, noKbMsg: string): string {
let kb = this._keybindingService.lookupKeybinding(commandId);
if (kb) {
return strings.format(msg, kb.getAriaLabel());
}
return strings.format(noKbMsg, commandId);
}
private _buildContent() {
let opts = this._editor.getConfiguration();
let text = nls.localize('introMsg', "Thank you for trying out VS Code's accessibility options.");
text += '\n\n' + nls.localize('status', "Status:");
const configuredValue = this._configurationService.getValue<editorOptions.IEditorOptions>('editor').accessibilitySupport;
const actualValue = opts.accessibilitySupport;
const emergencyTurnOnMessage = (
platform.isMacintosh
? nls.localize('changeConfigToOnMac', "To configure the editor to be permanently optimized for usage with a Screen Reader press Command+E now.")
: nls.localize('changeConfigToOnWinLinux', "To configure the editor to be permanently optimized for usage with a Screen Reader press Control+E now.")
);
switch (configuredValue) {
case 'auto':
switch (actualValue) {
case AccessibilitySupport.Unknown:
// Should never happen in VS Code
text += '\n\n - ' + nls.localize('auto_unknown', "The editor is configured to use platform APIs to detect when a Screen Reader is attached, but the current runtime does not support this.");
break;
case AccessibilitySupport.Enabled:
text += '\n\n - ' + nls.localize('auto_on', "The editor has automatically detected a Screen Reader is attached.");
break;
case AccessibilitySupport.Disabled:
text += '\n\n - ' + nls.localize('auto_off', "The editor is configured to automatically detect when a Screen Reader is attached, which is not the case at this time.");
text += ' ' + emergencyTurnOnMessage;
break;
}
break;
case 'on':
text += '\n\n - ' + nls.localize('configuredOn', "The editor is configured to be permanently optimized for usage with a Screen Reader - you can change this by editing the setting `editor.accessibilitySupport`.");
break;
case 'off':
text += '\n\n - ' + nls.localize('configuredOff', "The editor is configured to never be optimized for usage with a Screen Reader.");
text += ' ' + emergencyTurnOnMessage;
break;
}
const NLS_TAB_FOCUS_MODE_ON = nls.localize('tabFocusModeOnMsg', "Pressing Tab in the current editor will move focus to the next focusable element. Toggle this behavior by pressing {0}.");
const NLS_TAB_FOCUS_MODE_ON_NO_KB = nls.localize('tabFocusModeOnMsgNoKb', "Pressing Tab in the current editor will move focus to the next focusable element. The command {0} is currently not triggerable by a keybinding.");
const NLS_TAB_FOCUS_MODE_OFF = nls.localize('tabFocusModeOffMsg', "Pressing Tab in the current editor will insert the tab character. Toggle this behavior by pressing {0}.");
const NLS_TAB_FOCUS_MODE_OFF_NO_KB = nls.localize('tabFocusModeOffMsgNoKb', "Pressing Tab in the current editor will insert the tab character. The command {0} is currently not triggerable by a keybinding.");
if (opts.tabFocusMode) {
text += '\n\n - ' + this._descriptionForCommand(ToggleTabFocusModeAction.ID, NLS_TAB_FOCUS_MODE_ON, NLS_TAB_FOCUS_MODE_ON_NO_KB);
} else {
text += '\n\n - ' + this._descriptionForCommand(ToggleTabFocusModeAction.ID, NLS_TAB_FOCUS_MODE_OFF, NLS_TAB_FOCUS_MODE_OFF_NO_KB);
}
const openDocMessage = (
platform.isMacintosh
? nls.localize('openDocMac', "Press Command+H now to open a browser window with more VS Code information related to Accessibility.")
: nls.localize('openDocWinLinux', "Press Control+H now to open a browser window with more VS Code information related to Accessibility.")
);
text += '\n\n' + openDocMessage;
text += '\n\n' + nls.localize('outroMsg', "You can dismiss this tooltip and return to the editor by pressing Escape or Shift+Escape.");
this._contentDomNode.domNode.appendChild(renderFormattedText(text));
// Per https://www.w3.org/TR/wai-aria/roles#document, Authors SHOULD provide a title or label for documents
this._contentDomNode.domNode.setAttribute('aria-label', text);
}
public hide(): void {
if (!this._isVisible) {
return;
}
this._isVisible = false;
this._isVisibleKey.reset();
this._domNode.setDisplay('none');
this._domNode.setAttribute('aria-hidden', 'true');
this._contentDomNode.domNode.tabIndex = -1;
dom.clearNode(this._contentDomNode.domNode);
this._editor.focus();
}
private _layout(): void {
let editorLayout = this._editor.getLayoutInfo();
let top = Math.round((editorLayout.height - AccessibilityHelpWidget.HEIGHT) / 2);
this._domNode.setTop(top);
let left = Math.round((editorLayout.width - AccessibilityHelpWidget.WIDTH) / 2);
this._domNode.setLeft(left);
}
}
class ShowAccessibilityHelpAction extends EditorAction {
constructor() {
super({
id: 'editor.action.showAccessibilityHelp',
label: nls.localize('ShowAccessibilityHelpAction', "Show Accessibility Help"),
alias: 'Show Accessibility Help',
precondition: null,
kbOpts: {
kbExpr: EditorContextKeys.focus,
primary: KeyMod.Alt | KeyCode.F1,
weight: KeybindingWeight.EditorContrib
}
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
let controller = AccessibilityHelpController.get(editor);
if (controller) {
controller.show();
}
}
}
registerEditorContribution(AccessibilityHelpController);
registerEditorAction(ShowAccessibilityHelpAction);
const AccessibilityHelpCommand = EditorCommand.bindToContribution<AccessibilityHelpController>(AccessibilityHelpController.get);
registerEditorCommand(new AccessibilityHelpCommand({
id: 'closeAccessibilityHelp',
precondition: CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE,
handler: x => x.hide(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 100,
kbExpr: EditorContextKeys.focus,
primary: KeyCode.Escape, secondary: [KeyMod.Shift | KeyCode.Escape]
}
}));
registerThemingParticipant((theme, collector) => {
const widgetBackground = theme.getColor(editorWidgetBackground);
if (widgetBackground) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { background-color: ${widgetBackground}; }`);
}
const widgetShadowColor = theme.getColor(widgetShadow);
if (widgetShadowColor) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { box-shadow: 0 2px 8px ${widgetShadowColor}; }`);
}
const hcBorder = theme.getColor(contrastBorder);
if (hcBorder) {
collector.addRule(`.monaco-editor .accessibilityHelpWidget { border: 2px solid ${hcBorder}; }`);
}
});
| src/vs/workbench/contrib/codeEditor/browser/accessibility/accessibility.ts | 0 | https://github.com/microsoft/vscode/commit/b72fba1a56d5632d8215291e8bfb4304a6d2e5a9 | [
0.0001788230729289353,
0.0001725697220535949,
0.00016793017857708037,
0.00017263676272705197,
0.0000022219139736989746
]
|
{
"id": 0,
"code_window": [
" if (/\\.d\\.ts$/.test(fileName)) {\n",
" // if it's already a d.ts file just emit it signature\n",
" const snapshot = host.getScriptSnapshot(fileName);\n",
" const signature = crypto.createHash('md5')\n",
" .update(snapshot.getText(0, snapshot.getLength()))\n",
" .digest('base64');\n",
" return resolve({\n",
" fileName,\n",
" signature,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const signature = crypto.createHash('sha256')\n"
],
"file_path": "build/lib/tsb/builder.js",
"type": "replace",
"edit_start_line_idx": 91
} | "use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTypeScriptBuilder = exports.CancellationToken = void 0;
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const utils = require("./utils");
const colors = require("ansi-colors");
const ts = require("typescript");
const Vinyl = require("vinyl");
const source_map_1 = require("source-map");
var CancellationToken;
(function (CancellationToken) {
CancellationToken.None = {
isCancellationRequested() { return false; }
};
})(CancellationToken || (exports.CancellationToken = CancellationToken = {}));
function normalize(path) {
return path.replace(/\\/g, '/');
}
function createTypeScriptBuilder(config, projectFile, cmd) {
const _log = config.logFn;
const host = new LanguageServiceHost(cmd, projectFile, _log);
const service = ts.createLanguageService(host, ts.createDocumentRegistry());
const lastBuildVersion = Object.create(null);
const lastDtsHash = Object.create(null);
const userWantsDeclarations = cmd.options.declaration;
let oldErrors = Object.create(null);
let headUsed = process.memoryUsage().heapUsed;
let emitSourceMapsInStream = true;
// always emit declaraction files
host.getCompilationSettings().declaration = true;
function file(file) {
// support gulp-sourcemaps
if (file.sourceMap) {
emitSourceMapsInStream = false;
}
if (!file.contents) {
host.removeScriptSnapshot(file.path);
}
else {
host.addScriptSnapshot(file.path, new VinylScriptSnapshot(file));
}
}
function baseFor(snapshot) {
if (snapshot instanceof VinylScriptSnapshot) {
return cmd.options.outDir || snapshot.getBase();
}
else {
return '';
}
}
function isExternalModule(sourceFile) {
return sourceFile.externalModuleIndicator
|| /declare\s+module\s+('|")(.+)\1/.test(sourceFile.getText());
}
function build(out, onError, token = CancellationToken.None) {
function checkSyntaxSoon(fileName) {
return new Promise(resolve => {
process.nextTick(function () {
if (!host.getScriptSnapshot(fileName, false)) {
resolve([]); // no script, no problems
}
else {
resolve(service.getSyntacticDiagnostics(fileName));
}
});
});
}
function checkSemanticsSoon(fileName) {
return new Promise(resolve => {
process.nextTick(function () {
if (!host.getScriptSnapshot(fileName, false)) {
resolve([]); // no script, no problems
}
else {
resolve(service.getSemanticDiagnostics(fileName));
}
});
});
}
function emitSoon(fileName) {
return new Promise(resolve => {
process.nextTick(function () {
if (/\.d\.ts$/.test(fileName)) {
// if it's already a d.ts file just emit it signature
const snapshot = host.getScriptSnapshot(fileName);
const signature = crypto.createHash('md5')
.update(snapshot.getText(0, snapshot.getLength()))
.digest('base64');
return resolve({
fileName,
signature,
files: []
});
}
const output = service.getEmitOutput(fileName);
const files = [];
let signature;
for (const file of output.outputFiles) {
if (!emitSourceMapsInStream && /\.js\.map$/.test(file.name)) {
continue;
}
if (/\.d\.ts$/.test(file.name)) {
signature = crypto.createHash('md5')
.update(file.text)
.digest('base64');
if (!userWantsDeclarations) {
// don't leak .d.ts files if users don't want them
continue;
}
}
const vinyl = new Vinyl({
path: file.name,
contents: Buffer.from(file.text),
base: !config._emitWithoutBasePath && baseFor(host.getScriptSnapshot(fileName)) || undefined
});
if (!emitSourceMapsInStream && /\.js$/.test(file.name)) {
const sourcemapFile = output.outputFiles.filter(f => /\.js\.map$/.test(f.name))[0];
if (sourcemapFile) {
const extname = path.extname(vinyl.relative);
const basename = path.basename(vinyl.relative, extname);
const dirname = path.dirname(vinyl.relative);
const tsname = (dirname === '.' ? '' : dirname + '/') + basename + '.ts';
let sourceMap = JSON.parse(sourcemapFile.text);
sourceMap.sources[0] = tsname.replace(/\\/g, '/');
// check for an "input source" map and combine them
// in step 1 we extract all line edit from the input source map, and
// in step 2 we apply the line edits to the typescript source map
const snapshot = host.getScriptSnapshot(fileName);
if (snapshot instanceof VinylScriptSnapshot && snapshot.sourceMap) {
const inputSMC = new source_map_1.SourceMapConsumer(snapshot.sourceMap);
const tsSMC = new source_map_1.SourceMapConsumer(sourceMap);
let didChange = false;
const smg = new source_map_1.SourceMapGenerator({
file: sourceMap.file,
sourceRoot: sourceMap.sourceRoot
});
// step 1
const lineEdits = new Map();
inputSMC.eachMapping(m => {
if (m.originalLine === m.generatedLine) {
// same line mapping
let array = lineEdits.get(m.originalLine);
if (!array) {
array = [];
lineEdits.set(m.originalLine, array);
}
array.push([m.originalColumn, m.generatedColumn]);
}
else {
// NOT SUPPORTED
}
});
// step 2
tsSMC.eachMapping(m => {
didChange = true;
const edits = lineEdits.get(m.originalLine);
let originalColumnDelta = 0;
if (edits) {
for (const [from, to] of edits) {
if (to >= m.originalColumn) {
break;
}
originalColumnDelta = from - to;
}
}
smg.addMapping({
source: m.source,
name: m.name,
generated: { line: m.generatedLine, column: m.generatedColumn },
original: { line: m.originalLine, column: m.originalColumn + originalColumnDelta }
});
});
if (didChange) {
[tsSMC, inputSMC].forEach((consumer) => {
consumer.sources.forEach((sourceFile) => {
smg._sources.add(sourceFile);
const sourceContent = consumer.sourceContentFor(sourceFile);
if (sourceContent !== null) {
smg.setSourceContent(sourceFile, sourceContent);
}
});
});
sourceMap = JSON.parse(smg.toString());
// const filename = '/Users/jrieken/Code/vscode/src2/' + vinyl.relative + '.map';
// fs.promises.mkdir(path.dirname(filename), { recursive: true }).then(async () => {
// await fs.promises.writeFile(filename, smg.toString());
// await fs.promises.writeFile('/Users/jrieken/Code/vscode/src2/' + vinyl.relative, vinyl.contents);
// });
}
}
vinyl.sourceMap = sourceMap;
}
}
files.push(vinyl);
}
resolve({
fileName,
signature,
files
});
});
});
}
const newErrors = Object.create(null);
const t1 = Date.now();
const toBeEmitted = [];
const toBeCheckedSyntactically = [];
const toBeCheckedSemantically = [];
const filesWithChangedSignature = [];
const dependentFiles = [];
const newLastBuildVersion = new Map();
for (const fileName of host.getScriptFileNames()) {
if (lastBuildVersion[fileName] !== host.getScriptVersion(fileName)) {
toBeEmitted.push(fileName);
toBeCheckedSyntactically.push(fileName);
toBeCheckedSemantically.push(fileName);
}
}
return new Promise(resolve => {
const semanticCheckInfo = new Map();
const seenAsDependentFile = new Set();
function workOnNext() {
let promise;
// let fileName: string;
// someone told us to stop this
if (token.isCancellationRequested()) {
_log('[CANCEL]', '>>This compile run was cancelled<<');
newLastBuildVersion.clear();
resolve();
return;
}
// (1st) emit code
else if (toBeEmitted.length) {
const fileName = toBeEmitted.pop();
promise = emitSoon(fileName).then(value => {
for (const file of value.files) {
_log('[emit code]', file.path);
out(file);
}
// remember when this was build
newLastBuildVersion.set(fileName, host.getScriptVersion(fileName));
// remeber the signature
if (value.signature && lastDtsHash[fileName] !== value.signature) {
lastDtsHash[fileName] = value.signature;
filesWithChangedSignature.push(fileName);
}
}).catch(e => {
// can't just skip this or make a result up..
host.error(`ERROR emitting ${fileName}`);
host.error(e);
});
}
// (2nd) check syntax
else if (toBeCheckedSyntactically.length) {
const fileName = toBeCheckedSyntactically.pop();
_log('[check syntax]', fileName);
promise = checkSyntaxSoon(fileName).then(diagnostics => {
delete oldErrors[fileName];
if (diagnostics.length > 0) {
diagnostics.forEach(d => onError(d));
newErrors[fileName] = diagnostics;
// stop the world when there are syntax errors
toBeCheckedSyntactically.length = 0;
toBeCheckedSemantically.length = 0;
filesWithChangedSignature.length = 0;
}
});
}
// (3rd) check semantics
else if (toBeCheckedSemantically.length) {
let fileName = toBeCheckedSemantically.pop();
while (fileName && semanticCheckInfo.has(fileName)) {
fileName = toBeCheckedSemantically.pop();
}
if (fileName) {
_log('[check semantics]', fileName);
promise = checkSemanticsSoon(fileName).then(diagnostics => {
delete oldErrors[fileName];
semanticCheckInfo.set(fileName, diagnostics.length);
if (diagnostics.length > 0) {
diagnostics.forEach(d => onError(d));
newErrors[fileName] = diagnostics;
}
});
}
}
// (4th) check dependents
else if (filesWithChangedSignature.length) {
while (filesWithChangedSignature.length) {
const fileName = filesWithChangedSignature.pop();
if (!isExternalModule(service.getProgram().getSourceFile(fileName))) {
_log('[check semantics*]', fileName + ' is an internal module and it has changed shape -> check whatever hasn\'t been checked yet');
toBeCheckedSemantically.push(...host.getScriptFileNames());
filesWithChangedSignature.length = 0;
dependentFiles.length = 0;
break;
}
host.collectDependents(fileName, dependentFiles);
}
}
// (5th) dependents contd
else if (dependentFiles.length) {
let fileName = dependentFiles.pop();
while (fileName && seenAsDependentFile.has(fileName)) {
fileName = dependentFiles.pop();
}
if (fileName) {
seenAsDependentFile.add(fileName);
const value = semanticCheckInfo.get(fileName);
if (value === 0) {
// already validated successfully -> look at dependents next
host.collectDependents(fileName, dependentFiles);
}
else if (typeof value === 'undefined') {
// first validate -> look at dependents next
dependentFiles.push(fileName);
toBeCheckedSemantically.push(fileName);
}
}
}
// (last) done
else {
resolve();
return;
}
if (!promise) {
promise = Promise.resolve();
}
promise.then(function () {
// change to change
process.nextTick(workOnNext);
}).catch(err => {
console.error(err);
});
}
workOnNext();
}).then(() => {
// store the build versions to not rebuilt the next time
newLastBuildVersion.forEach((value, key) => {
lastBuildVersion[key] = value;
});
// print old errors and keep them
utils.collections.forEach(oldErrors, entry => {
entry.value.forEach(diag => onError(diag));
newErrors[entry.key] = entry.value;
});
oldErrors = newErrors;
// print stats
const headNow = process.memoryUsage().heapUsed;
const MB = 1024 * 1024;
_log('[tsb]', `time: ${colors.yellow((Date.now() - t1) + 'ms')} + \nmem: ${colors.cyan(Math.ceil(headNow / MB) + 'MB')} ${colors.bgCyan('delta: ' + Math.ceil((headNow - headUsed) / MB))}`);
headUsed = headNow;
});
}
return {
file,
build,
languageService: service
};
}
exports.createTypeScriptBuilder = createTypeScriptBuilder;
class ScriptSnapshot {
_text;
_mtime;
constructor(text, mtime) {
this._text = text;
this._mtime = mtime;
}
getVersion() {
return this._mtime.toUTCString();
}
getText(start, end) {
return this._text.substring(start, end);
}
getLength() {
return this._text.length;
}
getChangeRange(_oldSnapshot) {
return undefined;
}
}
class VinylScriptSnapshot extends ScriptSnapshot {
_base;
sourceMap;
constructor(file) {
super(file.contents.toString(), file.stat.mtime);
this._base = file.base;
this.sourceMap = file.sourceMap;
}
getBase() {
return this._base;
}
}
class LanguageServiceHost {
_cmdLine;
_projectPath;
_log;
_snapshots;
_filesInProject;
_filesAdded;
_dependencies;
_dependenciesRecomputeList;
_fileNameToDeclaredModule;
_projectVersion;
constructor(_cmdLine, _projectPath, _log) {
this._cmdLine = _cmdLine;
this._projectPath = _projectPath;
this._log = _log;
this._snapshots = Object.create(null);
this._filesInProject = new Set(_cmdLine.fileNames);
this._filesAdded = new Set();
this._dependencies = new utils.graph.Graph(s => s);
this._dependenciesRecomputeList = [];
this._fileNameToDeclaredModule = Object.create(null);
this._projectVersion = 1;
}
log(_s) {
// console.log(s);
}
trace(_s) {
// console.log(s);
}
error(s) {
console.error(s);
}
getCompilationSettings() {
return this._cmdLine.options;
}
getProjectVersion() {
return String(this._projectVersion);
}
getScriptFileNames() {
const res = Object.keys(this._snapshots).filter(path => this._filesInProject.has(path) || this._filesAdded.has(path));
return res;
}
getScriptVersion(filename) {
filename = normalize(filename);
const result = this._snapshots[filename];
if (result) {
return result.getVersion();
}
return 'UNKNWON_FILE_' + Math.random().toString(16).slice(2);
}
getScriptSnapshot(filename, resolve = true) {
filename = normalize(filename);
let result = this._snapshots[filename];
if (!result && resolve) {
try {
result = new VinylScriptSnapshot(new Vinyl({
path: filename,
contents: fs.readFileSync(filename),
base: this.getCompilationSettings().outDir,
stat: fs.statSync(filename)
}));
this.addScriptSnapshot(filename, result);
}
catch (e) {
// ignore
}
}
return result;
}
static _declareModule = /declare\s+module\s+('|")(.+)\1/g;
addScriptSnapshot(filename, snapshot) {
this._projectVersion++;
filename = normalize(filename);
const old = this._snapshots[filename];
if (!old && !this._filesInProject.has(filename) && !filename.endsWith('.d.ts')) {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
// not very proper!
this._filesAdded.add(filename);
}
if (!old || old.getVersion() !== snapshot.getVersion()) {
this._dependenciesRecomputeList.push(filename);
const node = this._dependencies.lookup(filename);
if (node) {
node.outgoing = Object.create(null);
}
// (cheap) check for declare module
LanguageServiceHost._declareModule.lastIndex = 0;
let match;
while ((match = LanguageServiceHost._declareModule.exec(snapshot.getText(0, snapshot.getLength())))) {
let declaredModules = this._fileNameToDeclaredModule[filename];
if (!declaredModules) {
this._fileNameToDeclaredModule[filename] = declaredModules = [];
}
declaredModules.push(match[2]);
}
}
this._snapshots[filename] = snapshot;
return old;
}
removeScriptSnapshot(filename) {
this._filesInProject.delete(filename);
this._filesAdded.delete(filename);
this._projectVersion++;
filename = normalize(filename);
delete this._fileNameToDeclaredModule[filename];
return delete this._snapshots[filename];
}
getCurrentDirectory() {
return path.dirname(this._projectPath);
}
getDefaultLibFileName(options) {
return ts.getDefaultLibFilePath(options);
}
directoryExists = ts.sys.directoryExists;
getDirectories = ts.sys.getDirectories;
fileExists = ts.sys.fileExists;
readFile = ts.sys.readFile;
readDirectory = ts.sys.readDirectory;
// ---- dependency management
collectDependents(filename, target) {
while (this._dependenciesRecomputeList.length) {
this._processFile(this._dependenciesRecomputeList.pop());
}
filename = normalize(filename);
const node = this._dependencies.lookup(filename);
if (node) {
utils.collections.forEach(node.incoming, entry => target.push(entry.key));
}
}
_processFile(filename) {
if (filename.match(/.*\.d\.ts$/)) {
return;
}
filename = normalize(filename);
const snapshot = this.getScriptSnapshot(filename);
if (!snapshot) {
this._log('processFile', `Missing snapshot for: ${filename}`);
return;
}
const info = ts.preProcessFile(snapshot.getText(0, snapshot.getLength()), true);
// (1) ///-references
info.referencedFiles.forEach(ref => {
const resolvedPath = path.resolve(path.dirname(filename), ref.fileName);
const normalizedPath = normalize(resolvedPath);
this._dependencies.inertEdge(filename, normalizedPath);
});
// (2) import-require statements
info.importedFiles.forEach(ref => {
const stopDirname = normalize(this.getCurrentDirectory());
let dirname = filename;
let found = false;
while (!found && dirname.indexOf(stopDirname) === 0) {
dirname = path.dirname(dirname);
const resolvedPath = path.resolve(dirname, ref.fileName);
const normalizedPath = normalize(resolvedPath);
if (this.getScriptSnapshot(normalizedPath + '.ts')) {
this._dependencies.inertEdge(filename, normalizedPath + '.ts');
found = true;
}
else if (this.getScriptSnapshot(normalizedPath + '.d.ts')) {
this._dependencies.inertEdge(filename, normalizedPath + '.d.ts');
found = true;
}
}
if (!found) {
for (const key in this._fileNameToDeclaredModule) {
if (this._fileNameToDeclaredModule[key] && ~this._fileNameToDeclaredModule[key].indexOf(ref.fileName)) {
this._dependencies.inertEdge(filename, key);
}
}
}
});
}
}
//# sourceMappingURL=builder.js.map | build/lib/tsb/builder.js | 1 | https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467 | [
0.9986293315887451,
0.1401161551475525,
0.00016464118380099535,
0.0021142715122550726,
0.32358092069625854
]
|
{
"id": 0,
"code_window": [
" if (/\\.d\\.ts$/.test(fileName)) {\n",
" // if it's already a d.ts file just emit it signature\n",
" const snapshot = host.getScriptSnapshot(fileName);\n",
" const signature = crypto.createHash('md5')\n",
" .update(snapshot.getText(0, snapshot.getLength()))\n",
" .digest('base64');\n",
" return resolve({\n",
" fileName,\n",
" signature,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const signature = crypto.createHash('sha256')\n"
],
"file_path": "build/lib/tsb/builder.js",
"type": "replace",
"edit_start_line_idx": 91
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Disposable } from 'vs/base/common/lifecycle';
import { IDimension } from 'vs/editor/common/core/dimension';
import { Emitter, Event } from 'vs/base/common/event';
import { getWindow, scheduleAtNextAnimationFrame } from 'vs/base/browser/dom';
export class ElementSizeObserver extends Disposable {
private _onDidChange = this._register(new Emitter<void>());
public readonly onDidChange: Event<void> = this._onDidChange.event;
private readonly _referenceDomElement: HTMLElement | null;
private _width: number;
private _height: number;
private _resizeObserver: ResizeObserver | null;
constructor(referenceDomElement: HTMLElement | null, dimension: IDimension | undefined) {
super();
this._referenceDomElement = referenceDomElement;
this._width = -1;
this._height = -1;
this._resizeObserver = null;
this.measureReferenceDomElement(false, dimension);
}
public override dispose(): void {
this.stopObserving();
super.dispose();
}
public getWidth(): number {
return this._width;
}
public getHeight(): number {
return this._height;
}
public startObserving(): void {
if (!this._resizeObserver && this._referenceDomElement) {
// We want to react to the resize observer only once per animation frame
// The first time the resize observer fires, we will react to it immediately.
// Otherwise we will postpone to the next animation frame.
// We'll use `observeContentRect` to store the content rect we received.
let observedDimenstion: IDimension | null = null;
const observeNow = () => {
if (observedDimenstion) {
this.observe({ width: observedDimenstion.width, height: observedDimenstion.height });
} else {
this.observe();
}
};
let shouldObserve = false;
let alreadyObservedThisAnimationFrame = false;
const update = () => {
if (shouldObserve && !alreadyObservedThisAnimationFrame) {
try {
shouldObserve = false;
alreadyObservedThisAnimationFrame = true;
observeNow();
} finally {
scheduleAtNextAnimationFrame(getWindow(this._referenceDomElement), () => {
alreadyObservedThisAnimationFrame = false;
update();
});
}
}
};
this._resizeObserver = new ResizeObserver((entries) => {
if (entries && entries[0] && entries[0].contentRect) {
observedDimenstion = { width: entries[0].contentRect.width, height: entries[0].contentRect.height };
} else {
observedDimenstion = null;
}
shouldObserve = true;
update();
});
this._resizeObserver.observe(this._referenceDomElement);
}
}
public stopObserving(): void {
if (this._resizeObserver) {
this._resizeObserver.disconnect();
this._resizeObserver = null;
}
}
public observe(dimension?: IDimension): void {
this.measureReferenceDomElement(true, dimension);
}
private measureReferenceDomElement(emitEvent: boolean, dimension?: IDimension): void {
let observedWidth = 0;
let observedHeight = 0;
if (dimension) {
observedWidth = dimension.width;
observedHeight = dimension.height;
} else if (this._referenceDomElement) {
observedWidth = this._referenceDomElement.clientWidth;
observedHeight = this._referenceDomElement.clientHeight;
}
observedWidth = Math.max(5, observedWidth);
observedHeight = Math.max(5, observedHeight);
if (this._width !== observedWidth || this._height !== observedHeight) {
this._width = observedWidth;
this._height = observedHeight;
if (emitEvent) {
this._onDidChange.fire();
}
}
}
}
| src/vs/editor/browser/config/elementSizeObserver.ts | 0 | https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467 | [
0.0025956907775253057,
0.00035602774005383253,
0.00016171702009160072,
0.00017067574663087726,
0.0006465491023845971
]
|
{
"id": 0,
"code_window": [
" if (/\\.d\\.ts$/.test(fileName)) {\n",
" // if it's already a d.ts file just emit it signature\n",
" const snapshot = host.getScriptSnapshot(fileName);\n",
" const signature = crypto.createHash('md5')\n",
" .update(snapshot.getText(0, snapshot.getLength()))\n",
" .digest('base64');\n",
" return resolve({\n",
" fileName,\n",
" signature,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const signature = crypto.createHash('sha256')\n"
],
"file_path": "build/lib/tsb/builder.js",
"type": "replace",
"edit_start_line_idx": 91
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { RawContextKey } from 'vs/platform/contextkey/common/contextkey';
export namespace EditorContextKeys {
export const editorSimpleInput = new RawContextKey<boolean>('editorSimpleInput', false, true);
/**
* A context key that is set when the editor's text has focus (cursor is blinking).
* Is false when focus is in simple editor widgets (repl input, scm commit input).
*/
export const editorTextFocus = new RawContextKey<boolean>('editorTextFocus', false, nls.localize('editorTextFocus', "Whether the editor text has focus (cursor is blinking)"));
/**
* A context key that is set when the editor's text or an editor's widget has focus.
*/
export const focus = new RawContextKey<boolean>('editorFocus', false, nls.localize('editorFocus', "Whether the editor or an editor widget has focus (e.g. focus is in the find widget)"));
/**
* A context key that is set when any editor input has focus (regular editor, repl input...).
*/
export const textInputFocus = new RawContextKey<boolean>('textInputFocus', false, nls.localize('textInputFocus', "Whether an editor or a rich text input has focus (cursor is blinking)"));
export const readOnly = new RawContextKey<boolean>('editorReadonly', false, nls.localize('editorReadonly', "Whether the editor is read-only"));
export const inDiffEditor = new RawContextKey<boolean>('inDiffEditor', false, nls.localize('inDiffEditor', "Whether the context is a diff editor"));
export const isEmbeddedDiffEditor = new RawContextKey<boolean>('isEmbeddedDiffEditor', false, nls.localize('isEmbeddedDiffEditor', "Whether the context is an embedded diff editor"));
export const inMultiDiffEditor = new RawContextKey<boolean>('inMultiDiffEditor', false, nls.localize('inMultiDiffEditor', "Whether the context is a multi diff editor"));
export const multiDiffEditorAllCollapsed = new RawContextKey<boolean>('multiDiffEditorAllCollapsed', undefined, nls.localize('multiDiffEditorAllCollapsed', "Whether all files in multi diff editor are collapsed"));
export const hasChanges = new RawContextKey<boolean>('diffEditorHasChanges', false, nls.localize('diffEditorHasChanges', "Whether the diff editor has changes"));
export const comparingMovedCode = new RawContextKey<boolean>('comparingMovedCode', false, nls.localize('comparingMovedCode', "Whether a moved code block is selected for comparison"));
export const accessibleDiffViewerVisible = new RawContextKey<boolean>('accessibleDiffViewerVisible', false, nls.localize('accessibleDiffViewerVisible', "Whether the accessible diff viewer is visible"));
export const diffEditorRenderSideBySideInlineBreakpointReached = new RawContextKey<boolean>('diffEditorRenderSideBySideInlineBreakpointReached', false, nls.localize('diffEditorRenderSideBySideInlineBreakpointReached', "Whether the diff editor render side by side inline breakpoint is reached"));
export const columnSelection = new RawContextKey<boolean>('editorColumnSelection', false, nls.localize('editorColumnSelection', "Whether `editor.columnSelection` is enabled"));
export const writable = readOnly.toNegated();
export const hasNonEmptySelection = new RawContextKey<boolean>('editorHasSelection', false, nls.localize('editorHasSelection', "Whether the editor has text selected"));
export const hasOnlyEmptySelection = hasNonEmptySelection.toNegated();
export const hasMultipleSelections = new RawContextKey<boolean>('editorHasMultipleSelections', false, nls.localize('editorHasMultipleSelections', "Whether the editor has multiple selections"));
export const hasSingleSelection = hasMultipleSelections.toNegated();
export const tabMovesFocus = new RawContextKey<boolean>('editorTabMovesFocus', false, nls.localize('editorTabMovesFocus', "Whether `Tab` will move focus out of the editor"));
export const tabDoesNotMoveFocus = tabMovesFocus.toNegated();
export const isInWalkThroughSnippet = new RawContextKey<boolean>('isInEmbeddedEditor', false, true);
export const canUndo = new RawContextKey<boolean>('canUndo', false, true);
export const canRedo = new RawContextKey<boolean>('canRedo', false, true);
export const hoverVisible = new RawContextKey<boolean>('editorHoverVisible', false, nls.localize('editorHoverVisible', "Whether the editor hover is visible"));
export const hoverFocused = new RawContextKey<boolean>('editorHoverFocused', false, nls.localize('editorHoverFocused', "Whether the editor hover is focused"));
export const stickyScrollFocused = new RawContextKey<boolean>('stickyScrollFocused', false, nls.localize('stickyScrollFocused', "Whether the sticky scroll is focused"));
export const stickyScrollVisible = new RawContextKey<boolean>('stickyScrollVisible', false, nls.localize('stickyScrollVisible', "Whether the sticky scroll is visible"));
export const standaloneColorPickerVisible = new RawContextKey<boolean>('standaloneColorPickerVisible', false, nls.localize('standaloneColorPickerVisible', "Whether the standalone color picker is visible"));
export const standaloneColorPickerFocused = new RawContextKey<boolean>('standaloneColorPickerFocused', false, nls.localize('standaloneColorPickerFocused', "Whether the standalone color picker is focused"));
/**
* A context key that is set when an editor is part of a larger editor, like notebooks or
* (future) a diff editor
*/
export const inCompositeEditor = new RawContextKey<boolean>('inCompositeEditor', undefined, nls.localize('inCompositeEditor', "Whether the editor is part of a larger editor (e.g. notebooks)"));
export const notInCompositeEditor = inCompositeEditor.toNegated();
// -- mode context keys
export const languageId = new RawContextKey<string>('editorLangId', '', nls.localize('editorLangId', "The language identifier of the editor"));
export const hasCompletionItemProvider = new RawContextKey<boolean>('editorHasCompletionItemProvider', false, nls.localize('editorHasCompletionItemProvider', "Whether the editor has a completion item provider"));
export const hasCodeActionsProvider = new RawContextKey<boolean>('editorHasCodeActionsProvider', false, nls.localize('editorHasCodeActionsProvider', "Whether the editor has a code actions provider"));
export const hasCodeLensProvider = new RawContextKey<boolean>('editorHasCodeLensProvider', false, nls.localize('editorHasCodeLensProvider', "Whether the editor has a code lens provider"));
export const hasDefinitionProvider = new RawContextKey<boolean>('editorHasDefinitionProvider', false, nls.localize('editorHasDefinitionProvider', "Whether the editor has a definition provider"));
export const hasDeclarationProvider = new RawContextKey<boolean>('editorHasDeclarationProvider', false, nls.localize('editorHasDeclarationProvider', "Whether the editor has a declaration provider"));
export const hasImplementationProvider = new RawContextKey<boolean>('editorHasImplementationProvider', false, nls.localize('editorHasImplementationProvider', "Whether the editor has an implementation provider"));
export const hasTypeDefinitionProvider = new RawContextKey<boolean>('editorHasTypeDefinitionProvider', false, nls.localize('editorHasTypeDefinitionProvider', "Whether the editor has a type definition provider"));
export const hasHoverProvider = new RawContextKey<boolean>('editorHasHoverProvider', false, nls.localize('editorHasHoverProvider', "Whether the editor has a hover provider"));
export const hasDocumentHighlightProvider = new RawContextKey<boolean>('editorHasDocumentHighlightProvider', false, nls.localize('editorHasDocumentHighlightProvider', "Whether the editor has a document highlight provider"));
export const hasDocumentSymbolProvider = new RawContextKey<boolean>('editorHasDocumentSymbolProvider', false, nls.localize('editorHasDocumentSymbolProvider', "Whether the editor has a document symbol provider"));
export const hasReferenceProvider = new RawContextKey<boolean>('editorHasReferenceProvider', false, nls.localize('editorHasReferenceProvider', "Whether the editor has a reference provider"));
export const hasRenameProvider = new RawContextKey<boolean>('editorHasRenameProvider', false, nls.localize('editorHasRenameProvider', "Whether the editor has a rename provider"));
export const hasSignatureHelpProvider = new RawContextKey<boolean>('editorHasSignatureHelpProvider', false, nls.localize('editorHasSignatureHelpProvider', "Whether the editor has a signature help provider"));
export const hasInlayHintsProvider = new RawContextKey<boolean>('editorHasInlayHintsProvider', false, nls.localize('editorHasInlayHintsProvider', "Whether the editor has an inline hints provider"));
// -- mode context keys: formatting
export const hasDocumentFormattingProvider = new RawContextKey<boolean>('editorHasDocumentFormattingProvider', false, nls.localize('editorHasDocumentFormattingProvider', "Whether the editor has a document formatting provider"));
export const hasDocumentSelectionFormattingProvider = new RawContextKey<boolean>('editorHasDocumentSelectionFormattingProvider', false, nls.localize('editorHasDocumentSelectionFormattingProvider', "Whether the editor has a document selection formatting provider"));
export const hasMultipleDocumentFormattingProvider = new RawContextKey<boolean>('editorHasMultipleDocumentFormattingProvider', false, nls.localize('editorHasMultipleDocumentFormattingProvider', "Whether the editor has multiple document formatting providers"));
export const hasMultipleDocumentSelectionFormattingProvider = new RawContextKey<boolean>('editorHasMultipleDocumentSelectionFormattingProvider', false, nls.localize('editorHasMultipleDocumentSelectionFormattingProvider', "Whether the editor has multiple document selection formatting providers"));
}
| src/vs/editor/common/editorContextKeys.ts | 0 | https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467 | [
0.00017780717462301254,
0.00017122295685112476,
0.00016798445722088218,
0.0001702091540209949,
0.0000026176355731877265
]
|
{
"id": 0,
"code_window": [
" if (/\\.d\\.ts$/.test(fileName)) {\n",
" // if it's already a d.ts file just emit it signature\n",
" const snapshot = host.getScriptSnapshot(fileName);\n",
" const signature = crypto.createHash('md5')\n",
" .update(snapshot.getText(0, snapshot.getLength()))\n",
" .digest('base64');\n",
" return resolve({\n",
" fileName,\n",
" signature,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const signature = crypto.createHash('sha256')\n"
],
"file_path": "build/lib/tsb/builder.js",
"type": "replace",
"edit_start_line_idx": 91
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { mainWindow } from 'vs/base/browser/window';
import { getErrorMessage } from 'vs/base/common/errors';
import { Emitter } from 'vs/base/common/event';
import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
export class BroadcastDataChannel<T> extends Disposable {
private broadcastChannel: BroadcastChannel | undefined;
private readonly _onDidReceiveData = this._register(new Emitter<T>());
readonly onDidReceiveData = this._onDidReceiveData.event;
constructor(private readonly channelName: string) {
super();
// Use BroadcastChannel
if ('BroadcastChannel' in mainWindow) {
try {
this.broadcastChannel = new BroadcastChannel(channelName);
const listener = (event: MessageEvent) => {
this._onDidReceiveData.fire(event.data);
};
this.broadcastChannel.addEventListener('message', listener);
this._register(toDisposable(() => {
if (this.broadcastChannel) {
this.broadcastChannel.removeEventListener('message', listener);
this.broadcastChannel.close();
}
}));
} catch (error) {
console.warn('Error while creating broadcast channel. Falling back to localStorage.', getErrorMessage(error));
}
}
// BroadcastChannel is not supported. Use storage.
if (!this.broadcastChannel) {
this.channelName = `BroadcastDataChannel.${channelName}`;
this.createBroadcastChannel();
}
}
private createBroadcastChannel(): void {
const listener = (event: StorageEvent) => {
if (event.key === this.channelName && event.newValue) {
this._onDidReceiveData.fire(JSON.parse(event.newValue));
}
};
mainWindow.addEventListener('storage', listener);
this._register(toDisposable(() => mainWindow.removeEventListener('storage', listener)));
}
/**
* Sends the data to other BroadcastChannel objects set up for this channel. Data can be structured objects, e.g. nested objects and arrays.
* @param data data to broadcast
*/
postData(data: T): void {
if (this.broadcastChannel) {
this.broadcastChannel.postMessage(data);
} else {
// remove previous changes so that event is triggered even if new changes are same as old changes
localStorage.removeItem(this.channelName);
localStorage.setItem(this.channelName, JSON.stringify(data));
}
}
}
| src/vs/base/browser/broadcast.ts | 0 | https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467 | [
0.00017771124839782715,
0.00016899852198548615,
0.0001636034867260605,
0.0001683961454546079,
0.000003969850695284549
]
|
{
"id": 1,
"code_window": [
" if (!emitSourceMapsInStream && /\\.js\\.map$/.test(file.name)) {\n",
" continue;\n",
" }\n",
" if (/\\.d\\.ts$/.test(file.name)) {\n",
" signature = crypto.createHash('md5')\n",
" .update(file.text)\n",
" .digest('base64');\n",
" if (!userWantsDeclarations) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" signature = crypto.createHash('sha256')\n"
],
"file_path": "build/lib/tsb/builder.js",
"type": "replace",
"edit_start_line_idx": 108
} | "use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTypeScriptBuilder = exports.CancellationToken = void 0;
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const utils = require("./utils");
const colors = require("ansi-colors");
const ts = require("typescript");
const Vinyl = require("vinyl");
const source_map_1 = require("source-map");
var CancellationToken;
(function (CancellationToken) {
CancellationToken.None = {
isCancellationRequested() { return false; }
};
})(CancellationToken || (exports.CancellationToken = CancellationToken = {}));
function normalize(path) {
return path.replace(/\\/g, '/');
}
function createTypeScriptBuilder(config, projectFile, cmd) {
const _log = config.logFn;
const host = new LanguageServiceHost(cmd, projectFile, _log);
const service = ts.createLanguageService(host, ts.createDocumentRegistry());
const lastBuildVersion = Object.create(null);
const lastDtsHash = Object.create(null);
const userWantsDeclarations = cmd.options.declaration;
let oldErrors = Object.create(null);
let headUsed = process.memoryUsage().heapUsed;
let emitSourceMapsInStream = true;
// always emit declaraction files
host.getCompilationSettings().declaration = true;
function file(file) {
// support gulp-sourcemaps
if (file.sourceMap) {
emitSourceMapsInStream = false;
}
if (!file.contents) {
host.removeScriptSnapshot(file.path);
}
else {
host.addScriptSnapshot(file.path, new VinylScriptSnapshot(file));
}
}
function baseFor(snapshot) {
if (snapshot instanceof VinylScriptSnapshot) {
return cmd.options.outDir || snapshot.getBase();
}
else {
return '';
}
}
function isExternalModule(sourceFile) {
return sourceFile.externalModuleIndicator
|| /declare\s+module\s+('|")(.+)\1/.test(sourceFile.getText());
}
function build(out, onError, token = CancellationToken.None) {
function checkSyntaxSoon(fileName) {
return new Promise(resolve => {
process.nextTick(function () {
if (!host.getScriptSnapshot(fileName, false)) {
resolve([]); // no script, no problems
}
else {
resolve(service.getSyntacticDiagnostics(fileName));
}
});
});
}
function checkSemanticsSoon(fileName) {
return new Promise(resolve => {
process.nextTick(function () {
if (!host.getScriptSnapshot(fileName, false)) {
resolve([]); // no script, no problems
}
else {
resolve(service.getSemanticDiagnostics(fileName));
}
});
});
}
function emitSoon(fileName) {
return new Promise(resolve => {
process.nextTick(function () {
if (/\.d\.ts$/.test(fileName)) {
// if it's already a d.ts file just emit it signature
const snapshot = host.getScriptSnapshot(fileName);
const signature = crypto.createHash('md5')
.update(snapshot.getText(0, snapshot.getLength()))
.digest('base64');
return resolve({
fileName,
signature,
files: []
});
}
const output = service.getEmitOutput(fileName);
const files = [];
let signature;
for (const file of output.outputFiles) {
if (!emitSourceMapsInStream && /\.js\.map$/.test(file.name)) {
continue;
}
if (/\.d\.ts$/.test(file.name)) {
signature = crypto.createHash('md5')
.update(file.text)
.digest('base64');
if (!userWantsDeclarations) {
// don't leak .d.ts files if users don't want them
continue;
}
}
const vinyl = new Vinyl({
path: file.name,
contents: Buffer.from(file.text),
base: !config._emitWithoutBasePath && baseFor(host.getScriptSnapshot(fileName)) || undefined
});
if (!emitSourceMapsInStream && /\.js$/.test(file.name)) {
const sourcemapFile = output.outputFiles.filter(f => /\.js\.map$/.test(f.name))[0];
if (sourcemapFile) {
const extname = path.extname(vinyl.relative);
const basename = path.basename(vinyl.relative, extname);
const dirname = path.dirname(vinyl.relative);
const tsname = (dirname === '.' ? '' : dirname + '/') + basename + '.ts';
let sourceMap = JSON.parse(sourcemapFile.text);
sourceMap.sources[0] = tsname.replace(/\\/g, '/');
// check for an "input source" map and combine them
// in step 1 we extract all line edit from the input source map, and
// in step 2 we apply the line edits to the typescript source map
const snapshot = host.getScriptSnapshot(fileName);
if (snapshot instanceof VinylScriptSnapshot && snapshot.sourceMap) {
const inputSMC = new source_map_1.SourceMapConsumer(snapshot.sourceMap);
const tsSMC = new source_map_1.SourceMapConsumer(sourceMap);
let didChange = false;
const smg = new source_map_1.SourceMapGenerator({
file: sourceMap.file,
sourceRoot: sourceMap.sourceRoot
});
// step 1
const lineEdits = new Map();
inputSMC.eachMapping(m => {
if (m.originalLine === m.generatedLine) {
// same line mapping
let array = lineEdits.get(m.originalLine);
if (!array) {
array = [];
lineEdits.set(m.originalLine, array);
}
array.push([m.originalColumn, m.generatedColumn]);
}
else {
// NOT SUPPORTED
}
});
// step 2
tsSMC.eachMapping(m => {
didChange = true;
const edits = lineEdits.get(m.originalLine);
let originalColumnDelta = 0;
if (edits) {
for (const [from, to] of edits) {
if (to >= m.originalColumn) {
break;
}
originalColumnDelta = from - to;
}
}
smg.addMapping({
source: m.source,
name: m.name,
generated: { line: m.generatedLine, column: m.generatedColumn },
original: { line: m.originalLine, column: m.originalColumn + originalColumnDelta }
});
});
if (didChange) {
[tsSMC, inputSMC].forEach((consumer) => {
consumer.sources.forEach((sourceFile) => {
smg._sources.add(sourceFile);
const sourceContent = consumer.sourceContentFor(sourceFile);
if (sourceContent !== null) {
smg.setSourceContent(sourceFile, sourceContent);
}
});
});
sourceMap = JSON.parse(smg.toString());
// const filename = '/Users/jrieken/Code/vscode/src2/' + vinyl.relative + '.map';
// fs.promises.mkdir(path.dirname(filename), { recursive: true }).then(async () => {
// await fs.promises.writeFile(filename, smg.toString());
// await fs.promises.writeFile('/Users/jrieken/Code/vscode/src2/' + vinyl.relative, vinyl.contents);
// });
}
}
vinyl.sourceMap = sourceMap;
}
}
files.push(vinyl);
}
resolve({
fileName,
signature,
files
});
});
});
}
const newErrors = Object.create(null);
const t1 = Date.now();
const toBeEmitted = [];
const toBeCheckedSyntactically = [];
const toBeCheckedSemantically = [];
const filesWithChangedSignature = [];
const dependentFiles = [];
const newLastBuildVersion = new Map();
for (const fileName of host.getScriptFileNames()) {
if (lastBuildVersion[fileName] !== host.getScriptVersion(fileName)) {
toBeEmitted.push(fileName);
toBeCheckedSyntactically.push(fileName);
toBeCheckedSemantically.push(fileName);
}
}
return new Promise(resolve => {
const semanticCheckInfo = new Map();
const seenAsDependentFile = new Set();
function workOnNext() {
let promise;
// let fileName: string;
// someone told us to stop this
if (token.isCancellationRequested()) {
_log('[CANCEL]', '>>This compile run was cancelled<<');
newLastBuildVersion.clear();
resolve();
return;
}
// (1st) emit code
else if (toBeEmitted.length) {
const fileName = toBeEmitted.pop();
promise = emitSoon(fileName).then(value => {
for (const file of value.files) {
_log('[emit code]', file.path);
out(file);
}
// remember when this was build
newLastBuildVersion.set(fileName, host.getScriptVersion(fileName));
// remeber the signature
if (value.signature && lastDtsHash[fileName] !== value.signature) {
lastDtsHash[fileName] = value.signature;
filesWithChangedSignature.push(fileName);
}
}).catch(e => {
// can't just skip this or make a result up..
host.error(`ERROR emitting ${fileName}`);
host.error(e);
});
}
// (2nd) check syntax
else if (toBeCheckedSyntactically.length) {
const fileName = toBeCheckedSyntactically.pop();
_log('[check syntax]', fileName);
promise = checkSyntaxSoon(fileName).then(diagnostics => {
delete oldErrors[fileName];
if (diagnostics.length > 0) {
diagnostics.forEach(d => onError(d));
newErrors[fileName] = diagnostics;
// stop the world when there are syntax errors
toBeCheckedSyntactically.length = 0;
toBeCheckedSemantically.length = 0;
filesWithChangedSignature.length = 0;
}
});
}
// (3rd) check semantics
else if (toBeCheckedSemantically.length) {
let fileName = toBeCheckedSemantically.pop();
while (fileName && semanticCheckInfo.has(fileName)) {
fileName = toBeCheckedSemantically.pop();
}
if (fileName) {
_log('[check semantics]', fileName);
promise = checkSemanticsSoon(fileName).then(diagnostics => {
delete oldErrors[fileName];
semanticCheckInfo.set(fileName, diagnostics.length);
if (diagnostics.length > 0) {
diagnostics.forEach(d => onError(d));
newErrors[fileName] = diagnostics;
}
});
}
}
// (4th) check dependents
else if (filesWithChangedSignature.length) {
while (filesWithChangedSignature.length) {
const fileName = filesWithChangedSignature.pop();
if (!isExternalModule(service.getProgram().getSourceFile(fileName))) {
_log('[check semantics*]', fileName + ' is an internal module and it has changed shape -> check whatever hasn\'t been checked yet');
toBeCheckedSemantically.push(...host.getScriptFileNames());
filesWithChangedSignature.length = 0;
dependentFiles.length = 0;
break;
}
host.collectDependents(fileName, dependentFiles);
}
}
// (5th) dependents contd
else if (dependentFiles.length) {
let fileName = dependentFiles.pop();
while (fileName && seenAsDependentFile.has(fileName)) {
fileName = dependentFiles.pop();
}
if (fileName) {
seenAsDependentFile.add(fileName);
const value = semanticCheckInfo.get(fileName);
if (value === 0) {
// already validated successfully -> look at dependents next
host.collectDependents(fileName, dependentFiles);
}
else if (typeof value === 'undefined') {
// first validate -> look at dependents next
dependentFiles.push(fileName);
toBeCheckedSemantically.push(fileName);
}
}
}
// (last) done
else {
resolve();
return;
}
if (!promise) {
promise = Promise.resolve();
}
promise.then(function () {
// change to change
process.nextTick(workOnNext);
}).catch(err => {
console.error(err);
});
}
workOnNext();
}).then(() => {
// store the build versions to not rebuilt the next time
newLastBuildVersion.forEach((value, key) => {
lastBuildVersion[key] = value;
});
// print old errors and keep them
utils.collections.forEach(oldErrors, entry => {
entry.value.forEach(diag => onError(diag));
newErrors[entry.key] = entry.value;
});
oldErrors = newErrors;
// print stats
const headNow = process.memoryUsage().heapUsed;
const MB = 1024 * 1024;
_log('[tsb]', `time: ${colors.yellow((Date.now() - t1) + 'ms')} + \nmem: ${colors.cyan(Math.ceil(headNow / MB) + 'MB')} ${colors.bgCyan('delta: ' + Math.ceil((headNow - headUsed) / MB))}`);
headUsed = headNow;
});
}
return {
file,
build,
languageService: service
};
}
exports.createTypeScriptBuilder = createTypeScriptBuilder;
class ScriptSnapshot {
_text;
_mtime;
constructor(text, mtime) {
this._text = text;
this._mtime = mtime;
}
getVersion() {
return this._mtime.toUTCString();
}
getText(start, end) {
return this._text.substring(start, end);
}
getLength() {
return this._text.length;
}
getChangeRange(_oldSnapshot) {
return undefined;
}
}
class VinylScriptSnapshot extends ScriptSnapshot {
_base;
sourceMap;
constructor(file) {
super(file.contents.toString(), file.stat.mtime);
this._base = file.base;
this.sourceMap = file.sourceMap;
}
getBase() {
return this._base;
}
}
class LanguageServiceHost {
_cmdLine;
_projectPath;
_log;
_snapshots;
_filesInProject;
_filesAdded;
_dependencies;
_dependenciesRecomputeList;
_fileNameToDeclaredModule;
_projectVersion;
constructor(_cmdLine, _projectPath, _log) {
this._cmdLine = _cmdLine;
this._projectPath = _projectPath;
this._log = _log;
this._snapshots = Object.create(null);
this._filesInProject = new Set(_cmdLine.fileNames);
this._filesAdded = new Set();
this._dependencies = new utils.graph.Graph(s => s);
this._dependenciesRecomputeList = [];
this._fileNameToDeclaredModule = Object.create(null);
this._projectVersion = 1;
}
log(_s) {
// console.log(s);
}
trace(_s) {
// console.log(s);
}
error(s) {
console.error(s);
}
getCompilationSettings() {
return this._cmdLine.options;
}
getProjectVersion() {
return String(this._projectVersion);
}
getScriptFileNames() {
const res = Object.keys(this._snapshots).filter(path => this._filesInProject.has(path) || this._filesAdded.has(path));
return res;
}
getScriptVersion(filename) {
filename = normalize(filename);
const result = this._snapshots[filename];
if (result) {
return result.getVersion();
}
return 'UNKNWON_FILE_' + Math.random().toString(16).slice(2);
}
getScriptSnapshot(filename, resolve = true) {
filename = normalize(filename);
let result = this._snapshots[filename];
if (!result && resolve) {
try {
result = new VinylScriptSnapshot(new Vinyl({
path: filename,
contents: fs.readFileSync(filename),
base: this.getCompilationSettings().outDir,
stat: fs.statSync(filename)
}));
this.addScriptSnapshot(filename, result);
}
catch (e) {
// ignore
}
}
return result;
}
static _declareModule = /declare\s+module\s+('|")(.+)\1/g;
addScriptSnapshot(filename, snapshot) {
this._projectVersion++;
filename = normalize(filename);
const old = this._snapshots[filename];
if (!old && !this._filesInProject.has(filename) && !filename.endsWith('.d.ts')) {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
// not very proper!
this._filesAdded.add(filename);
}
if (!old || old.getVersion() !== snapshot.getVersion()) {
this._dependenciesRecomputeList.push(filename);
const node = this._dependencies.lookup(filename);
if (node) {
node.outgoing = Object.create(null);
}
// (cheap) check for declare module
LanguageServiceHost._declareModule.lastIndex = 0;
let match;
while ((match = LanguageServiceHost._declareModule.exec(snapshot.getText(0, snapshot.getLength())))) {
let declaredModules = this._fileNameToDeclaredModule[filename];
if (!declaredModules) {
this._fileNameToDeclaredModule[filename] = declaredModules = [];
}
declaredModules.push(match[2]);
}
}
this._snapshots[filename] = snapshot;
return old;
}
removeScriptSnapshot(filename) {
this._filesInProject.delete(filename);
this._filesAdded.delete(filename);
this._projectVersion++;
filename = normalize(filename);
delete this._fileNameToDeclaredModule[filename];
return delete this._snapshots[filename];
}
getCurrentDirectory() {
return path.dirname(this._projectPath);
}
getDefaultLibFileName(options) {
return ts.getDefaultLibFilePath(options);
}
directoryExists = ts.sys.directoryExists;
getDirectories = ts.sys.getDirectories;
fileExists = ts.sys.fileExists;
readFile = ts.sys.readFile;
readDirectory = ts.sys.readDirectory;
// ---- dependency management
collectDependents(filename, target) {
while (this._dependenciesRecomputeList.length) {
this._processFile(this._dependenciesRecomputeList.pop());
}
filename = normalize(filename);
const node = this._dependencies.lookup(filename);
if (node) {
utils.collections.forEach(node.incoming, entry => target.push(entry.key));
}
}
_processFile(filename) {
if (filename.match(/.*\.d\.ts$/)) {
return;
}
filename = normalize(filename);
const snapshot = this.getScriptSnapshot(filename);
if (!snapshot) {
this._log('processFile', `Missing snapshot for: ${filename}`);
return;
}
const info = ts.preProcessFile(snapshot.getText(0, snapshot.getLength()), true);
// (1) ///-references
info.referencedFiles.forEach(ref => {
const resolvedPath = path.resolve(path.dirname(filename), ref.fileName);
const normalizedPath = normalize(resolvedPath);
this._dependencies.inertEdge(filename, normalizedPath);
});
// (2) import-require statements
info.importedFiles.forEach(ref => {
const stopDirname = normalize(this.getCurrentDirectory());
let dirname = filename;
let found = false;
while (!found && dirname.indexOf(stopDirname) === 0) {
dirname = path.dirname(dirname);
const resolvedPath = path.resolve(dirname, ref.fileName);
const normalizedPath = normalize(resolvedPath);
if (this.getScriptSnapshot(normalizedPath + '.ts')) {
this._dependencies.inertEdge(filename, normalizedPath + '.ts');
found = true;
}
else if (this.getScriptSnapshot(normalizedPath + '.d.ts')) {
this._dependencies.inertEdge(filename, normalizedPath + '.d.ts');
found = true;
}
}
if (!found) {
for (const key in this._fileNameToDeclaredModule) {
if (this._fileNameToDeclaredModule[key] && ~this._fileNameToDeclaredModule[key].indexOf(ref.fileName)) {
this._dependencies.inertEdge(filename, key);
}
}
}
});
}
}
//# sourceMappingURL=builder.js.map | build/lib/tsb/builder.js | 1 | https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467 | [
0.9979462027549744,
0.10052923858165741,
0.00016132921155076474,
0.00017290233517996967,
0.2928273677825928
]
|
{
"id": 1,
"code_window": [
" if (!emitSourceMapsInStream && /\\.js\\.map$/.test(file.name)) {\n",
" continue;\n",
" }\n",
" if (/\\.d\\.ts$/.test(file.name)) {\n",
" signature = crypto.createHash('md5')\n",
" .update(file.text)\n",
" .digest('base64');\n",
" if (!userWantsDeclarations) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" signature = crypto.createHash('sha256')\n"
],
"file_path": "build/lib/tsb/builder.js",
"type": "replace",
"edit_start_line_idx": 108
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { IReference, dispose, Disposable } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import { URI, UriComponents } from 'vs/base/common/uri';
import { ITextModel, shouldSynchronizeModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { IFileService, FileOperation } from 'vs/platform/files/common/files';
import { ExtHostContext, ExtHostDocumentsShape, MainThreadDocumentsShape } from 'vs/workbench/api/common/extHost.protocol';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { toLocalResource, extUri, IExtUri } from 'vs/base/common/resources';
import { IWorkingCopyFileService } from 'vs/workbench/services/workingCopy/common/workingCopyFileService';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { Emitter, Event } from 'vs/base/common/event';
import { IPathService } from 'vs/workbench/services/path/common/pathService';
import { ResourceMap } from 'vs/base/common/map';
import { IExtHostContext } from 'vs/workbench/services/extensions/common/extHostCustomers';
import { ErrorNoTelemetry } from 'vs/base/common/errors';
export class BoundModelReferenceCollection {
private _data = new Array<{ uri: URI; length: number; dispose(): void }>();
private _length = 0;
constructor(
private readonly _extUri: IExtUri,
private readonly _maxAge: number = 1000 * 60 * 3, // auto-dispse by age
private readonly _maxLength: number = 1024 * 1024 * 80, // auto-dispose by total length
private readonly _maxSize: number = 50 // auto-dispose by number of references
) {
//
}
dispose(): void {
this._data = dispose(this._data);
}
remove(uri: URI): void {
for (const entry of [...this._data] /* copy array because dispose will modify it */) {
if (this._extUri.isEqualOrParent(entry.uri, uri)) {
entry.dispose();
}
}
}
add(uri: URI, ref: IReference<any>, length: number = 0): void {
// const length = ref.object.textEditorModel.getValueLength();
const dispose = () => {
const idx = this._data.indexOf(entry);
if (idx >= 0) {
this._length -= length;
ref.dispose();
clearTimeout(handle);
this._data.splice(idx, 1);
}
};
const handle = setTimeout(dispose, this._maxAge);
const entry = { uri, length, dispose };
this._data.push(entry);
this._length += length;
this._cleanup();
}
private _cleanup(): void {
// clean-up wrt total length
while (this._length > this._maxLength) {
this._data[0].dispose();
}
// clean-up wrt number of documents
const extraSize = Math.ceil(this._maxSize * 1.2);
if (this._data.length >= extraSize) {
dispose(this._data.slice(0, extraSize - this._maxSize));
}
}
}
class ModelTracker extends Disposable {
private _knownVersionId: number;
constructor(
private readonly _model: ITextModel,
private readonly _onIsCaughtUpWithContentChanges: Emitter<URI>,
private readonly _proxy: ExtHostDocumentsShape,
private readonly _textFileService: ITextFileService,
) {
super();
this._knownVersionId = this._model.getVersionId();
this._store.add(this._model.onDidChangeContent((e) => {
this._knownVersionId = e.versionId;
this._proxy.$acceptModelChanged(this._model.uri, e, this._textFileService.isDirty(this._model.uri));
if (this.isCaughtUpWithContentChanges()) {
this._onIsCaughtUpWithContentChanges.fire(this._model.uri);
}
}));
}
isCaughtUpWithContentChanges(): boolean {
return (this._model.getVersionId() === this._knownVersionId);
}
}
export class MainThreadDocuments extends Disposable implements MainThreadDocumentsShape {
private _onIsCaughtUpWithContentChanges = this._store.add(new Emitter<URI>());
readonly onIsCaughtUpWithContentChanges = this._onIsCaughtUpWithContentChanges.event;
private readonly _proxy: ExtHostDocumentsShape;
private readonly _modelTrackers = new ResourceMap<ModelTracker>();
private readonly _modelReferenceCollection: BoundModelReferenceCollection;
constructor(
extHostContext: IExtHostContext,
@IModelService private readonly _modelService: IModelService,
@ITextFileService private readonly _textFileService: ITextFileService,
@IFileService private readonly _fileService: IFileService,
@ITextModelService private readonly _textModelResolverService: ITextModelService,
@IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService,
@IUriIdentityService private readonly _uriIdentityService: IUriIdentityService,
@IWorkingCopyFileService workingCopyFileService: IWorkingCopyFileService,
@IPathService private readonly _pathService: IPathService
) {
super();
this._modelReferenceCollection = this._store.add(new BoundModelReferenceCollection(_uriIdentityService.extUri));
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostDocuments);
this._store.add(_modelService.onModelLanguageChanged(this._onModelModeChanged, this));
this._store.add(_textFileService.files.onDidSave(e => {
if (this._shouldHandleFileEvent(e.model.resource)) {
this._proxy.$acceptModelSaved(e.model.resource);
}
}));
this._store.add(_textFileService.files.onDidChangeDirty(m => {
if (this._shouldHandleFileEvent(m.resource)) {
this._proxy.$acceptDirtyStateChanged(m.resource, m.isDirty());
}
}));
this._store.add(workingCopyFileService.onDidRunWorkingCopyFileOperation(e => {
const isMove = e.operation === FileOperation.MOVE;
if (isMove || e.operation === FileOperation.DELETE) {
for (const pair of e.files) {
const removed = isMove ? pair.source : pair.target;
if (removed) {
this._modelReferenceCollection.remove(removed);
}
}
}
}));
}
override dispose(): void {
dispose(this._modelTrackers.values());
this._modelTrackers.clear();
super.dispose();
}
isCaughtUpWithContentChanges(resource: URI): boolean {
const tracker = this._modelTrackers.get(resource);
if (tracker) {
return tracker.isCaughtUpWithContentChanges();
}
return true;
}
private _shouldHandleFileEvent(resource: URI): boolean {
const model = this._modelService.getModel(resource);
return !!model && shouldSynchronizeModel(model);
}
handleModelAdded(model: ITextModel): void {
// Same filter as in mainThreadEditorsTracker
if (!shouldSynchronizeModel(model)) {
// don't synchronize too large models
return;
}
this._modelTrackers.set(model.uri, new ModelTracker(model, this._onIsCaughtUpWithContentChanges, this._proxy, this._textFileService));
}
private _onModelModeChanged(event: { model: ITextModel; oldLanguageId: string }): void {
const { model } = event;
if (!this._modelTrackers.has(model.uri)) {
return;
}
this._proxy.$acceptModelLanguageChanged(model.uri, model.getLanguageId());
}
handleModelRemoved(modelUrl: URI): void {
if (!this._modelTrackers.has(modelUrl)) {
return;
}
this._modelTrackers.get(modelUrl)!.dispose();
this._modelTrackers.delete(modelUrl);
}
// --- from extension host process
async $trySaveDocument(uri: UriComponents): Promise<boolean> {
const target = await this._textFileService.save(URI.revive(uri));
return Boolean(target);
}
async $tryOpenDocument(uriData: UriComponents): Promise<URI> {
const inputUri = URI.revive(uriData);
if (!inputUri.scheme || !(inputUri.fsPath || inputUri.authority)) {
throw new ErrorNoTelemetry(`Invalid uri. Scheme and authority or path must be set.`);
}
const canonicalUri = this._uriIdentityService.asCanonicalUri(inputUri);
let promise: Promise<URI>;
switch (canonicalUri.scheme) {
case Schemas.untitled:
promise = this._handleUntitledScheme(canonicalUri);
break;
case Schemas.file:
default:
promise = this._handleAsResourceInput(canonicalUri);
break;
}
let documentUri: URI | undefined;
try {
documentUri = await promise;
} catch (err) {
throw new ErrorNoTelemetry(`cannot open ${canonicalUri.toString()}. Detail: ${toErrorMessage(err)}`);
}
if (!documentUri) {
throw new ErrorNoTelemetry(`cannot open ${canonicalUri.toString()}`);
} else if (!extUri.isEqual(documentUri, canonicalUri)) {
throw new ErrorNoTelemetry(`cannot open ${canonicalUri.toString()}. Detail: Actual document opened as ${documentUri.toString()}`);
} else if (!this._modelTrackers.has(canonicalUri)) {
throw new ErrorNoTelemetry(`cannot open ${canonicalUri.toString()}. Detail: Files above 50MB cannot be synchronized with extensions.`);
} else {
return canonicalUri;
}
}
$tryCreateDocument(options?: { language?: string; content?: string }): Promise<URI> {
return this._doCreateUntitled(undefined, options ? options.language : undefined, options ? options.content : undefined);
}
private async _handleAsResourceInput(uri: URI): Promise<URI> {
const ref = await this._textModelResolverService.createModelReference(uri);
this._modelReferenceCollection.add(uri, ref, ref.object.textEditorModel.getValueLength());
return ref.object.textEditorModel.uri;
}
private async _handleUntitledScheme(uri: URI): Promise<URI> {
const asLocalUri = toLocalResource(uri, this._environmentService.remoteAuthority, this._pathService.defaultUriScheme);
const exists = await this._fileService.exists(asLocalUri);
if (exists) {
// don't create a new file ontop of an existing file
return Promise.reject(new Error('file already exists'));
}
return await this._doCreateUntitled(Boolean(uri.path) ? uri : undefined);
}
private async _doCreateUntitled(associatedResource?: URI, languageId?: string, initialValue?: string): Promise<URI> {
const model = this._textFileService.untitled.create({
associatedResource,
languageId,
initialValue
});
const resource = model.resource;
const ref = await this._textModelResolverService.createModelReference(resource);
if (!this._modelTrackers.has(resource)) {
ref.dispose();
throw new Error(`expected URI ${resource.toString()} to have come to LIFE`);
}
this._modelReferenceCollection.add(resource, ref, ref.object.textEditorModel.getValueLength());
Event.once(model.onDidRevert)(() => this._modelReferenceCollection.remove(resource));
this._proxy.$acceptDirtyStateChanged(resource, true); // mark as dirty
return resource;
}
}
| src/vs/workbench/api/browser/mainThreadDocuments.ts | 0 | https://github.com/microsoft/vscode/commit/236d5dc072622d511e2f8f6ddd83fd24a7165467 | [
0.00017404874961357564,
0.00016926010721363127,
0.0001631436316529289,
0.0001694970269454643,
0.000002702979372770642
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.