hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 0, "code_window": [ "export interface IGalleryExtensionProperties {\n", "\tdependencies?: string[];\n", "\textensionPack?: string[];\n", "\tengine?: string;\n", "}\n", "\n", "export interface IGalleryExtensionAsset {\n", "\turi: string;\n", "\tfallbackUri: string;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tlocalizedLanguages?: string[];\n" ], "file_path": "src/vs/platform/extensionManagement/common/extensionManagement.ts", "type": "add", "edit_start_line_idx": 142 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { localize } from 'vs/nls'; import { basename } from 'vs/base/common/paths'; import { IDisposable, dispose, Disposable, combinedDisposable } from 'vs/base/common/lifecycle'; import { filterEvent, anyEvent as anyEvent } from 'vs/base/common/event'; import { VIEWLET_ID } from 'vs/workbench/parts/scm/common/scm'; import { ISCMService, ISCMRepository } from 'vs/workbench/services/scm/common/scm'; import { IActivityService, NumberBadge } from 'vs/workbench/services/activity/common/activity'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IStatusbarService, StatusbarAlignment as MainThreadStatusBarAlignment } from 'vs/platform/statusbar/common/statusbar'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { commonPrefixLength } from 'vs/base/common/strings'; export class StatusUpdater implements IWorkbenchContribution { private badgeDisposable: IDisposable = Disposable.None; private disposables: IDisposable[] = []; constructor( @ISCMService private scmService: ISCMService, @IActivityService private activityService: IActivityService ) { this.scmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables); this.render(); } private onDidAddRepository(repository: ISCMRepository): void { const provider = repository.provider; const onDidChange = anyEvent(provider.onDidChange, provider.onDidChangeResources); const changeDisposable = onDidChange(() => this.render()); const onDidRemove = filterEvent(this.scmService.onDidRemoveRepository, e => e === repository); const removeDisposable = onDidRemove(() => { disposable.dispose(); this.disposables = this.disposables.filter(d => d !== removeDisposable); this.render(); }); const disposable = combinedDisposable([changeDisposable, removeDisposable]); this.disposables.push(disposable); } private render(): void { this.badgeDisposable.dispose(); const count = this.scmService.repositories.reduce((r, repository) => { if (typeof repository.provider.count === 'number') { return r + repository.provider.count; } else { return r + repository.provider.groups.elements.reduce<number>((r, g) => r + g.elements.length, 0); } }, 0); if (count > 0) { const badge = new NumberBadge(count, num => localize('scmPendingChangesBadge', '{0} pending changes', num)); this.badgeDisposable = this.activityService.showActivity(VIEWLET_ID, badge, 'scm-viewlet-label'); } else { this.badgeDisposable = Disposable.None; } } dispose(): void { this.badgeDisposable.dispose(); this.disposables = dispose(this.disposables); } } export class StatusBarController implements IWorkbenchContribution { private statusBarDisposable: IDisposable = Disposable.None; private focusDisposable: IDisposable = Disposable.None; private focusedRepository: ISCMRepository | undefined = undefined; private focusedProviderContextKey: IContextKey<string | undefined>; private disposables: IDisposable[] = []; constructor( @ISCMService private scmService: ISCMService, @IStatusbarService private statusbarService: IStatusbarService, @IContextKeyService contextKeyService: IContextKeyService, @IEditorService private editorService: IEditorService ) { this.focusedProviderContextKey = contextKeyService.createKey<string | undefined>('scmProvider', void 0); this.scmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables); for (const repository of this.scmService.repositories) { this.onDidAddRepository(repository); } editorService.onDidActiveEditorChange(this.onDidActiveEditorChange, this, this.disposables); } private onDidActiveEditorChange(): void { if (!this.editorService.activeEditor) { return; } const resource = this.editorService.activeEditor.getResource(); if (!resource || resource.scheme !== 'file') { return; } let bestRepository: ISCMRepository | null = null; let bestMatchLength = Number.NEGATIVE_INFINITY; for (const repository of this.scmService.repositories) { const root = repository.provider.rootUri; if (!root) { continue; } const rootFSPath = root.fsPath; const prefixLength = commonPrefixLength(rootFSPath, resource.fsPath); if (prefixLength === rootFSPath.length && prefixLength > bestMatchLength) { bestRepository = repository; bestMatchLength = prefixLength; } } if (bestRepository) { this.onDidFocusRepository(bestRepository); } } private onDidAddRepository(repository: ISCMRepository): void { const changeDisposable = repository.onDidFocus(() => this.onDidFocusRepository(repository)); const onDidRemove = filterEvent(this.scmService.onDidRemoveRepository, e => e === repository); const removeDisposable = onDidRemove(() => { disposable.dispose(); this.disposables = this.disposables.filter(d => d !== removeDisposable); if (this.scmService.repositories.length === 0) { this.onDidFocusRepository(undefined); } else if (this.focusedRepository === repository) { this.scmService.repositories[0].focus(); } }); const disposable = combinedDisposable([changeDisposable, removeDisposable]); this.disposables.push(disposable); if (!this.focusedRepository) { this.onDidFocusRepository(repository); } } private onDidFocusRepository(repository: ISCMRepository | undefined): void { if (this.focusedRepository === repository) { return; } this.focusedRepository = repository; this.focusedProviderContextKey.set(repository && repository.provider.id); this.focusDisposable.dispose(); if (repository) { this.focusDisposable = repository.provider.onDidChange(() => this.render(repository)); } this.render(repository); } private render(repository: ISCMRepository | undefined): void { this.statusBarDisposable.dispose(); if (!repository) { return; } const commands = repository.provider.statusBarCommands || []; const label = repository.provider.rootUri ? `${basename(repository.provider.rootUri.fsPath)} (${repository.provider.label})` : repository.provider.label; const disposables = commands.map(c => this.statusbarService.addEntry({ text: c.title, tooltip: `${label} - ${c.tooltip}`, command: c.id, arguments: c.arguments }, MainThreadStatusBarAlignment.LEFT, 10000)); this.statusBarDisposable = combinedDisposable(disposables); } dispose(): void { this.focusDisposable.dispose(); this.statusBarDisposable.dispose(); this.disposables = dispose(this.disposables); } }
src/vs/workbench/parts/scm/electron-browser/scmActivity.ts
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017474133346695453, 0.000171495572431013, 0.00016712427895981818, 0.00017185686738230288, 0.000002203971916969749 ]
{ "id": 0, "code_window": [ "export interface IGalleryExtensionProperties {\n", "\tdependencies?: string[];\n", "\textensionPack?: string[];\n", "\tengine?: string;\n", "}\n", "\n", "export interface IGalleryExtensionAsset {\n", "\turi: string;\n", "\tfallbackUri: string;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tlocalizedLanguages?: string[];\n" ], "file_path": "src/vs/platform/extensionManagement/common/extensionManagement.ts", "type": "add", "edit_start_line_idx": 142 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as nativeKeymap from 'native-keymap'; import { IDisposable } from 'vs/base/common/lifecycle'; import { IStateService } from 'vs/platform/state/common/state'; import { Event, Emitter, once } from 'vs/base/common/event'; import { ConfigWatcher } from 'vs/base/node/config'; import { IUserFriendlyKeybinding } from 'vs/platform/keybinding/common/keybinding'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ipcMain as ipc } from 'electron'; import { IWindowsMainService } from 'vs/platform/windows/electron-main/windows'; import { ILogService } from 'vs/platform/log/common/log'; export class KeyboardLayoutMonitor { public static readonly INSTANCE = new KeyboardLayoutMonitor(); private readonly _emitter: Emitter<void>; private _registered: boolean; private constructor() { this._emitter = new Emitter<void>(); this._registered = false; } public onDidChangeKeyboardLayout(callback: () => void): IDisposable { if (!this._registered) { this._registered = true; nativeKeymap.onDidChangeKeyboardLayout(() => { this._emitter.fire(); }); } return this._emitter.event(callback); } } export interface IKeybinding { id: string; label: string; isNative: boolean; } export class KeybindingsResolver { private static readonly lastKnownKeybindingsMapStorageKey = 'lastKnownKeybindings'; private commandIds: Set<string>; private keybindings: { [commandId: string]: IKeybinding }; private keybindingsWatcher: ConfigWatcher<IUserFriendlyKeybinding[]>; private _onKeybindingsChanged = new Emitter<void>(); onKeybindingsChanged: Event<void> = this._onKeybindingsChanged.event; constructor( @IStateService private stateService: IStateService, @IEnvironmentService environmentService: IEnvironmentService, @IWindowsMainService private windowsMainService: IWindowsMainService, @ILogService private logService: ILogService ) { this.commandIds = new Set<string>(); this.keybindings = this.stateService.getItem<{ [id: string]: string; }>(KeybindingsResolver.lastKnownKeybindingsMapStorageKey) || Object.create(null); this.keybindingsWatcher = new ConfigWatcher<IUserFriendlyKeybinding[]>(environmentService.appKeybindingsPath, { changeBufferDelay: 100, onError: error => this.logService.error(error) }); this.registerListeners(); } private registerListeners(): void { // Listen to resolved keybindings from window ipc.on('vscode:keybindingsResolved', (event, rawKeybindings: string) => { let keybindings: IKeybinding[] = []; try { keybindings = JSON.parse(rawKeybindings); } catch (error) { // Should not happen } // Fill hash map of resolved keybindings and check for changes let keybindingsChanged = false; let keybindingsCount = 0; const resolvedKeybindings: { [commandId: string]: IKeybinding } = Object.create(null); keybindings.forEach(keybinding => { keybindingsCount++; resolvedKeybindings[keybinding.id] = keybinding; if (!this.keybindings[keybinding.id] || keybinding.label !== this.keybindings[keybinding.id].label) { keybindingsChanged = true; } }); // A keybinding might have been unassigned, so we have to account for that too if (Object.keys(this.keybindings).length !== keybindingsCount) { keybindingsChanged = true; } if (keybindingsChanged) { this.keybindings = resolvedKeybindings; this.stateService.setItem(KeybindingsResolver.lastKnownKeybindingsMapStorageKey, this.keybindings); // keep to restore instantly after restart this._onKeybindingsChanged.fire(); } }); // Resolve keybindings when any first window is loaded const onceOnWindowReady = once(this.windowsMainService.onWindowReady); onceOnWindowReady(win => this.resolveKeybindings(win)); // Resolve keybindings again when keybindings.json changes this.keybindingsWatcher.onDidUpdateConfiguration(() => this.resolveKeybindings()); // Resolve keybindings when window reloads because an installed extension could have an impact this.windowsMainService.onWindowReload(() => this.resolveKeybindings()); } private resolveKeybindings(win = this.windowsMainService.getLastActiveWindow()): void { if (this.commandIds.size && win) { const commandIds: string[] = []; this.commandIds.forEach(id => commandIds.push(id)); win.sendWhenReady('vscode:resolveKeybindings', JSON.stringify(commandIds)); } } public getKeybinding(commandId: string): IKeybinding { if (!commandId) { return void 0; } if (!this.commandIds.has(commandId)) { this.commandIds.add(commandId); } return this.keybindings[commandId]; } public dispose(): void { this._onKeybindingsChanged.dispose(); this.keybindingsWatcher.dispose(); } }
src/vs/code/electron-main/keyboard.ts
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.0006713280454277992, 0.00020390795543789864, 0.00016522101941518486, 0.0001710938522592187, 0.00012495122791733593 ]
{ "id": 1, "code_window": [ "};\n", "\n", "const PropertyType = {\n", "\tDependency: 'Microsoft.VisualStudio.Code.ExtensionDependencies',\n", "\tExtensionPack: 'Microsoft.VisualStudio.Code.ExtensionPack',\n", "\tEngine: 'Microsoft.VisualStudio.Code.Engine'\n", "};\n", "\n", "interface ICriterium {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tEngine: 'Microsoft.VisualStudio.Code.Engine',\n", "\tLocalizedLanguages: 'Microsoft.VisualStudio.Code.LocalizedLanguages'\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "replace", "edit_start_line_idx": 118 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { tmpdir } from 'os'; import * as path from 'path'; import { TPromise } from 'vs/base/common/winjs.base'; import { distinct } from 'vs/base/common/arrays'; import { getErrorMessage, isPromiseCanceledError, canceled } from 'vs/base/common/errors'; import { StatisticType, IGalleryExtension, IExtensionGalleryService, IGalleryExtensionAsset, IQueryOptions, SortBy, SortOrder, IExtensionManifest, IExtensionIdentifier, IReportedExtension, InstallOperation, ITranslation } from 'vs/platform/extensionManagement/common/extensionManagement'; import { getGalleryExtensionId, getGalleryExtensionTelemetryData, adoptToGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { assign, getOrDefault } from 'vs/base/common/objects'; import { IRequestService } from 'vs/platform/request/node/request'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IPager } from 'vs/base/common/paging'; import { IRequestOptions, IRequestContext, download, asJson, asText } from 'vs/base/node/request'; import pkg from 'vs/platform/node/package'; import product from 'vs/platform/node/product'; import { isEngineValid } from 'vs/platform/extensions/node/extensionValidator'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { readFile } from 'vs/base/node/pfs'; import { writeFileAndFlushSync } from 'vs/base/node/extfs'; import { generateUuid, isUUID } from 'vs/base/common/uuid'; import { values } from 'vs/base/common/map'; import { CancellationToken } from 'vs/base/common/cancellation'; interface IRawGalleryExtensionFile { assetType: string; source: string; } interface IRawGalleryExtensionProperty { key: string; value: string; } interface IRawGalleryExtensionVersion { version: string; lastUpdated: string; assetUri: string; fallbackAssetUri: string; files: IRawGalleryExtensionFile[]; properties?: IRawGalleryExtensionProperty[]; } interface IRawGalleryExtensionStatistics { statisticName: string; value: number; } interface IRawGalleryExtension { extensionId: string; extensionName: string; displayName: string; shortDescription: string; publisher: { displayName: string, publisherId: string, publisherName: string; }; versions: IRawGalleryExtensionVersion[]; statistics: IRawGalleryExtensionStatistics[]; flags: string; } interface IRawGalleryQueryResult { results: { extensions: IRawGalleryExtension[]; resultMetadata: { metadataType: string; metadataItems: { name: string; count: number; }[]; }[] }[]; } enum Flags { None = 0x0, IncludeVersions = 0x1, IncludeFiles = 0x2, IncludeCategoryAndTags = 0x4, IncludeSharedAccounts = 0x8, IncludeVersionProperties = 0x10, ExcludeNonValidated = 0x20, IncludeInstallationTargets = 0x40, IncludeAssetUri = 0x80, IncludeStatistics = 0x100, IncludeLatestVersionOnly = 0x200, Unpublished = 0x1000 } function flagsToString(...flags: Flags[]): string { return String(flags.reduce((r, f) => r | f, 0)); } enum FilterType { Tag = 1, ExtensionId = 4, Category = 5, ExtensionName = 7, Target = 8, Featured = 9, SearchText = 10, ExcludeWithFlags = 12 } const AssetType = { Icon: 'Microsoft.VisualStudio.Services.Icons.Default', Details: 'Microsoft.VisualStudio.Services.Content.Details', Changelog: 'Microsoft.VisualStudio.Services.Content.Changelog', Manifest: 'Microsoft.VisualStudio.Code.Manifest', VSIX: 'Microsoft.VisualStudio.Services.VSIXPackage', License: 'Microsoft.VisualStudio.Services.Content.License', Repository: 'Microsoft.VisualStudio.Services.Links.Source' }; const PropertyType = { Dependency: 'Microsoft.VisualStudio.Code.ExtensionDependencies', ExtensionPack: 'Microsoft.VisualStudio.Code.ExtensionPack', Engine: 'Microsoft.VisualStudio.Code.Engine' }; interface ICriterium { filterType: FilterType; value?: string; } const DefaultPageSize = 10; interface IQueryState { pageNumber: number; pageSize: number; sortBy: SortBy; sortOrder: SortOrder; flags: Flags; criteria: ICriterium[]; assetTypes: string[]; } const DefaultQueryState: IQueryState = { pageNumber: 1, pageSize: DefaultPageSize, sortBy: SortBy.NoneOrRelevance, sortOrder: SortOrder.Default, flags: Flags.None, criteria: [], assetTypes: [] }; class Query { constructor(private state = DefaultQueryState) { } get pageNumber(): number { return this.state.pageNumber; } get pageSize(): number { return this.state.pageSize; } get sortBy(): number { return this.state.sortBy; } get sortOrder(): number { return this.state.sortOrder; } get flags(): number { return this.state.flags; } withPage(pageNumber: number, pageSize: number = this.state.pageSize): Query { return new Query(assign({}, this.state, { pageNumber, pageSize })); } withFilter(filterType: FilterType, ...values: string[]): Query { const criteria = [ ...this.state.criteria, ...values.map(value => ({ filterType, value })) ]; return new Query(assign({}, this.state, { criteria })); } withSortBy(sortBy: SortBy): Query { return new Query(assign({}, this.state, { sortBy })); } withSortOrder(sortOrder: SortOrder): Query { return new Query(assign({}, this.state, { sortOrder })); } withFlags(...flags: Flags[]): Query { return new Query(assign({}, this.state, { flags: flags.reduce((r, f) => r | f, 0) })); } withAssetTypes(...assetTypes: string[]): Query { return new Query(assign({}, this.state, { assetTypes })); } get raw(): any { const { criteria, pageNumber, pageSize, sortBy, sortOrder, flags, assetTypes } = this.state; const filters = [{ criteria, pageNumber, pageSize, sortBy, sortOrder }]; return { filters, assetTypes, flags }; } get searchText(): string { const criterium = this.state.criteria.filter(criterium => criterium.filterType === FilterType.SearchText)[0]; return criterium ? criterium.value : ''; } } function getStatistic(statistics: IRawGalleryExtensionStatistics[], name: string): number { const result = (statistics || []).filter(s => s.statisticName === name)[0]; return result ? result.value : 0; } function getCoreTranslationAssets(version: IRawGalleryExtensionVersion): { [languageId: string]: IGalleryExtensionAsset } { const coreTranslationAssetPrefix = 'Microsoft.VisualStudio.Code.Translation.'; const result = version.files.filter(f => f.assetType.indexOf(coreTranslationAssetPrefix) === 0); return result.reduce((result, file) => { result[file.assetType.substring(coreTranslationAssetPrefix.length)] = getVersionAsset(version, file.assetType); return result; }, {}); } function getVersionAsset(version: IRawGalleryExtensionVersion, type: string): IGalleryExtensionAsset { const result = version.files.filter(f => f.assetType === type)[0]; if (type === AssetType.Repository) { if (version.properties) { const results = version.properties.filter(p => p.key === type); const gitRegExp = new RegExp('((git|ssh|http(s)?)|(git@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(\.git)(/)?'); const uri = results.filter(r => gitRegExp.test(r.value))[0]; if (!uri) { return { uri: null, fallbackUri: null }; } return { uri: uri.value, fallbackUri: uri.value, }; } } if (!result) { if (type === AssetType.Icon) { const uri = require.toUrl('./media/defaultIcon.png'); return { uri, fallbackUri: uri }; } if (type === AssetType.Repository) { return { uri: null, fallbackUri: null }; } return null; } if (type === AssetType.VSIX) { return { uri: `${version.fallbackAssetUri}/${type}?redirect=true`, fallbackUri: `${version.fallbackAssetUri}/${type}` }; } return { uri: `${version.assetUri}/${type}`, fallbackUri: `${version.fallbackAssetUri}/${type}` }; } function getExtensions(version: IRawGalleryExtensionVersion, property: string): string[] { const values = version.properties ? version.properties.filter(p => p.key === property) : []; const value = values.length > 0 && values[0].value; return value ? value.split(',').map(v => adoptToGalleryExtensionId(v)) : []; } function getEngine(version: IRawGalleryExtensionVersion): string { const values = version.properties ? version.properties.filter(p => p.key === PropertyType.Engine) : []; return (values.length > 0 && values[0].value) || ''; } function getIsPreview(flags: string): boolean { return flags.indexOf('preview') !== -1; } function toExtension(galleryExtension: IRawGalleryExtension, version: IRawGalleryExtensionVersion, index: number, query: Query, querySource?: string): IGalleryExtension { const assets = { manifest: getVersionAsset(version, AssetType.Manifest), readme: getVersionAsset(version, AssetType.Details), changelog: getVersionAsset(version, AssetType.Changelog), download: getVersionAsset(version, AssetType.VSIX), icon: getVersionAsset(version, AssetType.Icon), license: getVersionAsset(version, AssetType.License), repository: getVersionAsset(version, AssetType.Repository), coreTranslations: getCoreTranslationAssets(version) }; return { identifier: { id: getGalleryExtensionId(galleryExtension.publisher.publisherName, galleryExtension.extensionName), uuid: galleryExtension.extensionId }, name: galleryExtension.extensionName, version: version.version, date: version.lastUpdated, displayName: galleryExtension.displayName, publisherId: galleryExtension.publisher.publisherId, publisher: galleryExtension.publisher.publisherName, publisherDisplayName: galleryExtension.publisher.displayName, description: galleryExtension.shortDescription || '', installCount: getStatistic(galleryExtension.statistics, 'install') + getStatistic(galleryExtension.statistics, 'updateCount'), rating: getStatistic(galleryExtension.statistics, 'averagerating'), ratingCount: getStatistic(galleryExtension.statistics, 'ratingcount'), assets, properties: { dependencies: getExtensions(version, PropertyType.Dependency), extensionPack: getExtensions(version, PropertyType.ExtensionPack), engine: getEngine(version) }, /* __GDPR__FRAGMENT__ "GalleryExtensionTelemetryData2" : { "index" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "searchText": { "classification": "CustomerContent", "purpose": "FeatureInsight" }, "querySource": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ telemetryData: { index: ((query.pageNumber - 1) * query.pageSize) + index, searchText: query.searchText, querySource }, preview: getIsPreview(galleryExtension.flags) }; } interface IRawExtensionsReport { malicious: string[]; slow: string[]; } export class ExtensionGalleryService implements IExtensionGalleryService { _serviceBrand: any; private extensionsGalleryUrl: string; private extensionsControlUrl: string; private readonly commonHeadersPromise: TPromise<{ [key: string]: string; }>; constructor( @IRequestService private requestService: IRequestService, @IEnvironmentService private environmentService: IEnvironmentService, @ITelemetryService private telemetryService: ITelemetryService ) { const config = product.extensionsGallery; this.extensionsGalleryUrl = config && config.serviceUrl; this.extensionsControlUrl = config && config.controlUrl; this.commonHeadersPromise = resolveMarketplaceHeaders(this.environmentService); } private api(path = ''): string { return `${this.extensionsGalleryUrl}${path}`; } isEnabled(): boolean { return !!this.extensionsGalleryUrl; } getExtension({ id, uuid }: IExtensionIdentifier, version?: string): TPromise<IGalleryExtension> { let query = new Query() .withFlags(Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, 1) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)); if (uuid) { query = query.withFilter(FilterType.ExtensionId, uuid); } else { query = query.withFilter(FilterType.ExtensionName, id); } return this.queryGallery(query, CancellationToken.None).then(({ galleryExtensions }) => { if (galleryExtensions.length) { const galleryExtension = galleryExtensions[0]; const versionAsset = version ? galleryExtension.versions.filter(v => v.version === version)[0] : galleryExtension.versions[0]; if (versionAsset) { return toExtension(galleryExtension, versionAsset, 0, query); } } return null; }); } query(options: IQueryOptions = {}): TPromise<IPager<IGalleryExtension>> { if (!this.isEnabled()) { return TPromise.wrapError<IPager<IGalleryExtension>>(new Error('No extension gallery service configured.')); } const type = options.names ? 'ids' : (options.text ? 'text' : 'all'); let text = options.text || ''; const pageSize = getOrDefault(options, o => o.pageSize, 50); /* __GDPR__ "galleryService:query" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "text": { "classification": "CustomerContent", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:query', { type, text }); let query = new Query() .withFlags(Flags.IncludeLatestVersionOnly, Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, pageSize) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)); if (text) { // Use category filter instead of "category:themes" text = text.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedCategory, category) => { query = query.withFilter(FilterType.Category, category || quotedCategory); return ''; }); // Use tag filter instead of "tag:debuggers" text = text.replace(/\btag:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedTag, tag) => { query = query.withFilter(FilterType.Tag, tag || quotedTag); return ''; }); text = text.trim(); if (text) { text = text.length < 200 ? text : text.substring(0, 200); query = query.withFilter(FilterType.SearchText, text); } query = query.withSortBy(SortBy.NoneOrRelevance); } else if (options.ids) { query = query.withFilter(FilterType.ExtensionId, ...options.ids); } else if (options.names) { query = query.withFilter(FilterType.ExtensionName, ...options.names); } else { query = query.withSortBy(SortBy.InstallCount); } if (typeof options.sortBy === 'number') { query = query.withSortBy(options.sortBy); } if (typeof options.sortOrder === 'number') { query = query.withSortOrder(options.sortOrder); } return this.queryGallery(query, CancellationToken.None).then(({ galleryExtensions, total }) => { const extensions = galleryExtensions.map((e, index) => toExtension(e, e.versions[0], index, query, options.source)); const pageSize = query.pageSize; const getPage = (pageIndex: number, ct: CancellationToken) => { if (ct.isCancellationRequested) { return TPromise.wrapError(canceled()); } const nextPageQuery = query.withPage(pageIndex + 1); return this.queryGallery(nextPageQuery, ct) .then(({ galleryExtensions }) => galleryExtensions.map((e, index) => toExtension(e, e.versions[0], index, nextPageQuery, options.source))); }; return { firstPage: extensions, total, pageSize, getPage } as IPager<IGalleryExtension>; }); } private queryGallery(query: Query, token: CancellationToken): TPromise<{ galleryExtensions: IRawGalleryExtension[], total: number; }> { return this.commonHeadersPromise.then(commonHeaders => { const data = JSON.stringify(query.raw); const headers = assign({}, commonHeaders, { 'Content-Type': 'application/json', 'Accept': 'application/json;api-version=3.0-preview.1', 'Accept-Encoding': 'gzip', 'Content-Length': data.length }); return this.requestService.request({ type: 'POST', url: this.api('/extensionquery'), data, headers }, token).then(context => { if (context.res.statusCode >= 400 && context.res.statusCode < 500) { return { galleryExtensions: [], total: 0 }; } return asJson<IRawGalleryQueryResult>(context).then(result => { const r = result.results[0]; const galleryExtensions = r.extensions; const resultCount = r.resultMetadata && r.resultMetadata.filter(m => m.metadataType === 'ResultCount')[0]; const total = resultCount && resultCount.metadataItems.filter(i => i.name === 'TotalCount')[0].count || 0; return { galleryExtensions, total }; }); }); }); } reportStatistic(publisher: string, name: string, version: string, type: StatisticType): TPromise<void> { if (!this.isEnabled()) { return TPromise.as(null); } return this.commonHeadersPromise.then(commonHeaders => { const headers = { ...commonHeaders, Accept: '*/*;api-version=4.0-preview.1' }; return this.requestService.request({ type: 'POST', url: this.api(`/publishers/${publisher}/extensions/${name}/${version}/stats?statType=${type}`), headers }, CancellationToken.None).then(null, () => null); }); } download(extension: IGalleryExtension, operation: InstallOperation): TPromise<string> { const zipPath = path.join(tmpdir(), generateUuid()); const data = getGalleryExtensionTelemetryData(extension); const startTime = new Date().getTime(); /* __GDPR__ "galleryService:downloadVSIX" : { "duration": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true }, "${include}": [ "${GalleryExtensionTelemetryData}" ] } */ const log = (duration: number) => this.telemetryService.publicLog('galleryService:downloadVSIX', assign(data, { duration })); const operationParam = operation === InstallOperation.Install ? 'install' : operation === InstallOperation.Update ? 'update' : ''; const downloadAsset = operationParam ? { uri: `${extension.assets.download.uri}&${operationParam}=true`, fallbackUri: `${extension.assets.download.fallbackUri}?${operationParam}=true` } : extension.assets.download; return this.getAsset(downloadAsset) .then(context => download(zipPath, context)) .then(() => log(new Date().getTime() - startTime)) .then(() => zipPath); } getReadme(extension: IGalleryExtension, token: CancellationToken): TPromise<string> { return this.getAsset(extension.assets.readme, {}, token) .then(asText); } getManifest(extension: IGalleryExtension, token: CancellationToken): TPromise<IExtensionManifest> { return this.getAsset(extension.assets.manifest, {}, token) .then(asText) .then(JSON.parse); } getCoreTranslation(extension: IGalleryExtension, languageId: string): TPromise<ITranslation> { const asset = extension.assets.coreTranslations[languageId.toUpperCase()]; if (asset) { return this.getAsset(asset) .then(asText) .then(JSON.parse); } return TPromise.as(null); } getChangelog(extension: IGalleryExtension, token: CancellationToken): TPromise<string> { return this.getAsset(extension.assets.changelog, {}, token) .then(asText); } loadAllDependencies(extensions: IExtensionIdentifier[], token: CancellationToken): TPromise<IGalleryExtension[]> { return this.getDependenciesReccursively(extensions.map(e => e.id), [], token); } loadCompatibleVersion(extension: IGalleryExtension): TPromise<IGalleryExtension> { if (extension.properties.engine && isEngineValid(extension.properties.engine)) { return TPromise.wrap(extension); } const query = new Query() .withFlags(Flags.IncludeVersions, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, 1) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)) .withAssetTypes(AssetType.Manifest, AssetType.VSIX) .withFilter(FilterType.ExtensionId, extension.identifier.uuid); return this.queryGallery(query, CancellationToken.None) .then(({ galleryExtensions }) => { const [rawExtension] = galleryExtensions; if (!rawExtension) { return null; } return this.getLastValidExtensionVersion(rawExtension, rawExtension.versions) .then(rawVersion => { if (rawVersion) { extension.properties.dependencies = getExtensions(rawVersion, PropertyType.Dependency); extension.properties.engine = getEngine(rawVersion); extension.assets.download = getVersionAsset(rawVersion, AssetType.VSIX); extension.version = rawVersion.version; return extension; } return null; }); }); } private loadDependencies(extensionNames: string[], token: CancellationToken): TPromise<IGalleryExtension[]> { if (!extensionNames || extensionNames.length === 0) { return TPromise.as([]); } let query = new Query() .withFlags(Flags.IncludeLatestVersionOnly, Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, extensionNames.length) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)) .withAssetTypes(AssetType.Icon, AssetType.License, AssetType.Details, AssetType.Manifest, AssetType.VSIX) .withFilter(FilterType.ExtensionName, ...extensionNames); return this.queryGallery(query, token).then(result => { const dependencies = []; const ids = []; for (let index = 0; index < result.galleryExtensions.length; index++) { const rawExtension = result.galleryExtensions[index]; if (ids.indexOf(rawExtension.extensionId) === -1) { dependencies.push(toExtension(rawExtension, rawExtension.versions[0], index, query, 'dependencies')); ids.push(rawExtension.extensionId); } } return dependencies; }); } private getDependenciesReccursively(toGet: string[], result: IGalleryExtension[], token: CancellationToken): TPromise<IGalleryExtension[]> { if (!toGet || !toGet.length) { return TPromise.wrap(result); } toGet = result.length ? toGet.filter(e => !ExtensionGalleryService.hasExtensionByName(result, e)) : toGet; if (!toGet.length) { return TPromise.wrap(result); } return this.loadDependencies(toGet, token) .then(loadedDependencies => { const dependenciesSet = new Set<string>(); for (const dep of loadedDependencies) { if (dep.properties.dependencies) { dep.properties.dependencies.forEach(d => dependenciesSet.add(d)); } } result = distinct(result.concat(loadedDependencies), d => d.identifier.uuid); const dependencies: string[] = []; dependenciesSet.forEach(d => !ExtensionGalleryService.hasExtensionByName(result, d) && dependencies.push(d)); return this.getDependenciesReccursively(dependencies, result, token); }); } private getAsset(asset: IGalleryExtensionAsset, options: IRequestOptions = {}, token: CancellationToken = CancellationToken.None): TPromise<IRequestContext> { return this.commonHeadersPromise.then(commonHeaders => { const baseOptions = { type: 'GET' }; const headers = assign({}, commonHeaders, options.headers || {}); options = assign({}, options, baseOptions, { headers }); const url = asset.uri; const fallbackUrl = asset.fallbackUri; const firstOptions = assign({}, options, { url }); return this.requestService.request(firstOptions, token) .then(context => { if (context.res.statusCode === 200) { return TPromise.as(context); } return asText(context) .then(message => TPromise.wrapError<IRequestContext>(new Error(`Expected 200, got back ${context.res.statusCode} instead.\n\n${message}`))); }) .then(null, err => { if (isPromiseCanceledError(err)) { return TPromise.wrapError<IRequestContext>(err); } const message = getErrorMessage(err); /* __GDPR__ "galleryService:requestError" : { "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "cdn": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:requestError', { url, cdn: true, message }); /* __GDPR__ "galleryService:cdnFallback" : { "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "message": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:cdnFallback', { url, message }); const fallbackOptions = assign({}, options, { url: fallbackUrl }); return this.requestService.request(fallbackOptions, token).then(null, err => { if (isPromiseCanceledError(err)) { return TPromise.wrapError<IRequestContext>(err); } const message = getErrorMessage(err); /* __GDPR__ "galleryService:requestError" : { "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "cdn": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:requestError', { url: fallbackUrl, cdn: false, message }); return TPromise.wrapError<IRequestContext>(err); }); }); }); } private getLastValidExtensionVersion(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> { const version = this.getLastValidExtensionVersionFromProperties(extension, versions); if (version) { return version; } return this.getLastValidExtensionVersionReccursively(extension, versions); } private getLastValidExtensionVersionFromProperties(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> { for (const version of versions) { const engine = getEngine(version); if (!engine) { return null; } if (isEngineValid(engine)) { return TPromise.wrap(version); } } return null; } private getLastValidExtensionVersionReccursively(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> { if (!versions.length) { return null; } const version = versions[0]; const asset = getVersionAsset(version, AssetType.Manifest); const headers = { 'Accept-Encoding': 'gzip' }; return this.getAsset(asset, { headers }) .then(context => asJson<IExtensionManifest>(context)) .then(manifest => { const engine = manifest.engines.vscode; if (!isEngineValid(engine)) { return this.getLastValidExtensionVersionReccursively(extension, versions.slice(1)); } version.properties = version.properties || []; version.properties.push({ key: PropertyType.Engine, value: manifest.engines.vscode }); return version; }); } private static hasExtensionByName(extensions: IGalleryExtension[], name: string): boolean { for (const extension of extensions) { if (`${extension.publisher}.${extension.name}` === name) { return true; } } return false; } getExtensionsReport(): TPromise<IReportedExtension[]> { if (!this.isEnabled()) { return TPromise.wrapError(new Error('No extension gallery service configured.')); } if (!this.extensionsControlUrl) { return TPromise.as([]); } return this.requestService.request({ type: 'GET', url: this.extensionsControlUrl }, CancellationToken.None).then(context => { if (context.res.statusCode !== 200) { return TPromise.wrapError(new Error('Could not get extensions report.')); } return asJson<IRawExtensionsReport>(context).then(result => { const map = new Map<string, IReportedExtension>(); for (const id of result.malicious) { const ext = map.get(id) || { id: { id }, malicious: true, slow: false }; ext.malicious = true; map.set(id, ext); } return TPromise.as(values(map)); }); }); } } export function resolveMarketplaceHeaders(environmentService: IEnvironmentService): TPromise<{ [key: string]: string; }> { const marketplaceMachineIdFile = path.join(environmentService.userDataPath, 'machineid'); return readFile(marketplaceMachineIdFile, 'utf8').then(contents => { if (isUUID(contents)) { return contents; } return TPromise.wrap(null); // invalid marketplace UUID }, error => { return TPromise.wrap(null); // error reading ID file }).then(uuid => { if (!uuid) { uuid = generateUuid(); try { writeFileAndFlushSync(marketplaceMachineIdFile, uuid); } catch (error) { //noop } } return { 'X-Market-Client-Id': `VSCode ${pkg.version}`, 'User-Agent': `VSCode ${pkg.version}`, 'X-Market-User-Id': uuid }; }); }
src/vs/platform/extensionManagement/node/extensionGalleryService.ts
1
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.9992566704750061, 0.08205264806747437, 0.00016194584895856678, 0.00017196644330397248, 0.27169013023376465 ]
{ "id": 1, "code_window": [ "};\n", "\n", "const PropertyType = {\n", "\tDependency: 'Microsoft.VisualStudio.Code.ExtensionDependencies',\n", "\tExtensionPack: 'Microsoft.VisualStudio.Code.ExtensionPack',\n", "\tEngine: 'Microsoft.VisualStudio.Code.Engine'\n", "};\n", "\n", "interface ICriterium {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tEngine: 'Microsoft.VisualStudio.Code.Engine',\n", "\tLocalizedLanguages: 'Microsoft.VisualStudio.Code.LocalizedLanguages'\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "replace", "edit_start_line_idx": 118 }
:root { --spacing-unit: 6px; --cell-padding: (4 * var(--spacing-unit)); } body { padding-left: calc(4 * var(--spacing-unit, 5px)); }
extensions/scss/test/colorize-fixtures/test-cssvariables.scss
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017175814718939364, 0.00017175814718939364, 0.00017175814718939364, 0.00017175814718939364, 0 ]
{ "id": 1, "code_window": [ "};\n", "\n", "const PropertyType = {\n", "\tDependency: 'Microsoft.VisualStudio.Code.ExtensionDependencies',\n", "\tExtensionPack: 'Microsoft.VisualStudio.Code.ExtensionPack',\n", "\tEngine: 'Microsoft.VisualStudio.Code.Engine'\n", "};\n", "\n", "interface ICriterium {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tEngine: 'Microsoft.VisualStudio.Code.Engine',\n", "\tLocalizedLanguages: 'Microsoft.VisualStudio.Code.LocalizedLanguages'\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "replace", "edit_start_line_idx": 118 }
{ "name": "theme-defaults", "displayName": "%displayName%", "description": "%description%", "categories": [ "Themes" ], "version": "1.0.0", "publisher": "vscode", "engines": { "vscode": "*" }, "contributes": { "themes": [ { "id": "Default Dark+", "label": "Dark+ (default dark)", "uiTheme": "vs-dark", "path": "./themes/dark_plus.json" }, { "id": "Default Light+", "label": "Light+ (default light)", "uiTheme": "vs", "path": "./themes/light_plus.json" }, { "id": "Visual Studio Dark", "label": "Dark (Visual Studio)", "uiTheme": "vs-dark", "path": "./themes/dark_vs.json" }, { "id": "Visual Studio Light", "label": "Light (Visual Studio)", "uiTheme": "vs", "path": "./themes/light_vs.json" }, { "id": "Default High Contrast", "label": "High Contrast", "uiTheme": "hc-black", "path": "./themes/hc_black.json" } ], "iconThemes": [ { "id": "vs-minimal", "label": "Minimal (Visual Studio Code)", "path": "./fileicons/vs_minimal-icon-theme.json" } ] } }
extensions/theme-defaults/package.json
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.000179158931132406, 0.00017245458730030805, 0.0001661217538639903, 0.0001723409804981202, 0.000004158521733188536 ]
{ "id": 1, "code_window": [ "};\n", "\n", "const PropertyType = {\n", "\tDependency: 'Microsoft.VisualStudio.Code.ExtensionDependencies',\n", "\tExtensionPack: 'Microsoft.VisualStudio.Code.ExtensionPack',\n", "\tEngine: 'Microsoft.VisualStudio.Code.Engine'\n", "};\n", "\n", "interface ICriterium {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tEngine: 'Microsoft.VisualStudio.Code.Engine',\n", "\tLocalizedLanguages: 'Microsoft.VisualStudio.Code.LocalizedLanguages'\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "replace", "edit_start_line_idx": 118 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as modes from 'vs/editor/common/modes'; import { LineTokens } from 'vs/editor/common/core/lineTokens'; export function createScopedLineTokens(context: LineTokens, offset: number): ScopedLineTokens { let tokenCount = context.getCount(); let tokenIndex = context.findTokenIndexAtOffset(offset); let desiredLanguageId = context.getLanguageId(tokenIndex); let lastTokenIndex = tokenIndex; while (lastTokenIndex + 1 < tokenCount && context.getLanguageId(lastTokenIndex + 1) === desiredLanguageId) { lastTokenIndex++; } let firstTokenIndex = tokenIndex; while (firstTokenIndex > 0 && context.getLanguageId(firstTokenIndex - 1) === desiredLanguageId) { firstTokenIndex--; } return new ScopedLineTokens( context, desiredLanguageId, firstTokenIndex, lastTokenIndex + 1, context.getStartOffset(firstTokenIndex), context.getEndOffset(lastTokenIndex) ); } export class ScopedLineTokens { _scopedLineTokensBrand: void; public readonly languageId: modes.LanguageId; private readonly _actual: LineTokens; private readonly _firstTokenIndex: number; private readonly _lastTokenIndex: number; public readonly firstCharOffset: number; private readonly _lastCharOffset: number; constructor( actual: LineTokens, languageId: modes.LanguageId, firstTokenIndex: number, lastTokenIndex: number, firstCharOffset: number, lastCharOffset: number ) { this._actual = actual; this.languageId = languageId; this._firstTokenIndex = firstTokenIndex; this._lastTokenIndex = lastTokenIndex; this.firstCharOffset = firstCharOffset; this._lastCharOffset = lastCharOffset; } public getLineContent(): string { const actualLineContent = this._actual.getLineContent(); return actualLineContent.substring(this.firstCharOffset, this._lastCharOffset); } public getTokenCount(): number { return this._lastTokenIndex - this._firstTokenIndex; } public findTokenIndexAtOffset(offset: number): number { return this._actual.findTokenIndexAtOffset(offset + this.firstCharOffset) - this._firstTokenIndex; } public getStandardTokenType(tokenIndex: number): modes.StandardTokenType { return this._actual.getStandardTokenType(tokenIndex + this._firstTokenIndex); } } const enum IgnoreBracketsInTokens { value = modes.StandardTokenType.Comment | modes.StandardTokenType.String | modes.StandardTokenType.RegEx } export function ignoreBracketsInToken(standardTokenType: modes.StandardTokenType): boolean { return (standardTokenType & IgnoreBracketsInTokens.value) !== 0; }
src/vs/editor/common/modes/supports.ts
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017498241504654288, 0.0001720101572573185, 0.00016607044381089509, 0.00017348391702398658, 0.000003006572114827577 ]
{ "id": 2, "code_window": [ "\tconst values = version.properties ? version.properties.filter(p => p.key === PropertyType.Engine) : [];\n", "\treturn (values.length > 0 && values[0].value) || '';\n", "}\n", "\n", "function getIsPreview(flags: string): boolean {\n", "\treturn flags.indexOf('preview') !== -1;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "function getLocalizedLanguages(version: IRawGalleryExtensionVersion): string[] {\n", "\tconst values = version.properties ? version.properties.filter(p => p.key === PropertyType.LocalizedLanguages) : [];\n", "\tconst value = (values.length > 0 && values[0].value) || '';\n", "\treturn value ? value.split(',') : [];\n", "}\n", "\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "add", "edit_start_line_idx": 276 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { localize } from 'vs/nls'; import { append, $, addClass, removeClass, toggleClass } from 'vs/base/browser/dom'; import { IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle'; import { Action } from 'vs/base/common/actions'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { IPagedRenderer } from 'vs/base/browser/ui/list/listPaging'; import { once } from 'vs/base/common/event'; import { domEvent } from 'vs/base/browser/event'; import { IExtension, IExtensionsWorkbenchService } from 'vs/workbench/parts/extensions/common/extensions'; import { InstallAction, UpdateAction, ManageExtensionAction, ReloadAction, extensionButtonProminentBackground, extensionButtonProminentForeground, MaliciousStatusLabelAction, DisabledStatusLabelAction } from 'vs/workbench/parts/extensions/electron-browser/extensionsActions'; import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { Label, RatingsWidget, InstallCountWidget } from 'vs/workbench/parts/extensions/browser/extensionsWidgets'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IExtensionTipsService, IExtensionManagementServerService } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { createCancelablePromise } from 'vs/base/common/async'; export interface ITemplateData { root: HTMLElement; element: HTMLElement; icon: HTMLImageElement; name: HTMLElement; installCount: HTMLElement; ratings: HTMLElement; author: HTMLElement; description: HTMLElement; extension: IExtension; disposables: IDisposable[]; extensionDisposables: IDisposable[]; } export class Delegate implements IVirtualDelegate<IExtension> { getHeight() { return 62; } getTemplateId() { return 'extension'; } } const actionOptions = { icon: true, label: true }; export class Renderer implements IPagedRenderer<IExtension, ITemplateData> { constructor( @IInstantiationService private instantiationService: IInstantiationService, @INotificationService private notificationService: INotificationService, @IExtensionsWorkbenchService private extensionsWorkbenchService: IExtensionsWorkbenchService, @IExtensionService private extensionService: IExtensionService, @IExtensionTipsService private extensionTipsService: IExtensionTipsService, @IThemeService private themeService: IThemeService, @IExtensionManagementServerService private extensionManagementServerService: IExtensionManagementServerService ) { } get templateId() { return 'extension'; } renderTemplate(root: HTMLElement): ITemplateData { const bookmark = append(root, $('span.bookmark')); append(bookmark, $('span.octicon.octicon-star')); const applyBookmarkStyle = (theme) => { const bgColor = theme.getColor(extensionButtonProminentBackground); const fgColor = theme.getColor(extensionButtonProminentForeground); bookmark.style.borderTopColor = bgColor ? bgColor.toString() : 'transparent'; bookmark.style.color = fgColor ? fgColor.toString() : 'white'; }; applyBookmarkStyle(this.themeService.getTheme()); const bookmarkStyler = this.themeService.onThemeChange(applyBookmarkStyle.bind(this)); const element = append(root, $('.extension')); const icon = append(element, $<HTMLImageElement>('img.icon')); const details = append(element, $('.details')); const headerContainer = append(details, $('.header-container')); const header = append(headerContainer, $('.header')); const name = append(header, $('span.name')); const version = append(header, $('span.version')); const installCount = append(header, $('span.install-count')); const ratings = append(header, $('span.ratings')); const description = append(details, $('.description.ellipsis')); const footer = append(details, $('.footer')); const author = append(footer, $('.author.ellipsis')); const actionbar = new ActionBar(footer, { animated: false, actionItemProvider: (action: Action) => { if (action.id === ManageExtensionAction.ID) { return (<ManageExtensionAction>action).actionItem; } return null; } }); actionbar.onDidRun(({ error }) => error && this.notificationService.error(error)); const versionWidget = this.instantiationService.createInstance(Label, version, (e: IExtension) => e.version); const installCountWidget = this.instantiationService.createInstance(InstallCountWidget, installCount, { small: true }); const ratingsWidget = this.instantiationService.createInstance(RatingsWidget, ratings, { small: true }); const maliciousStatusAction = this.instantiationService.createInstance(MaliciousStatusLabelAction, false); const disabledStatusAction = this.instantiationService.createInstance(DisabledStatusLabelAction); const installAction = this.instantiationService.createInstance(InstallAction); const updateAction = this.instantiationService.createInstance(UpdateAction); const reloadAction = this.instantiationService.createInstance(ReloadAction); const manageAction = this.instantiationService.createInstance(ManageExtensionAction); actionbar.push([updateAction, reloadAction, installAction, disabledStatusAction, maliciousStatusAction, manageAction], actionOptions); const disposables = [versionWidget, installCountWidget, ratingsWidget, maliciousStatusAction, disabledStatusAction, updateAction, installAction, reloadAction, manageAction, actionbar, bookmarkStyler]; return { root, element, icon, name, installCount, ratings, author, description, disposables, extensionDisposables: [], set extension(extension: IExtension) { versionWidget.extension = extension; installCountWidget.extension = extension; ratingsWidget.extension = extension; maliciousStatusAction.extension = extension; disabledStatusAction.extension = extension; installAction.extension = extension; updateAction.extension = extension; reloadAction.extension = extension; manageAction.extension = extension; } }; } renderPlaceholder(index: number, data: ITemplateData): void { addClass(data.element, 'loading'); data.root.removeAttribute('aria-label'); data.extensionDisposables = dispose(data.extensionDisposables); data.icon.src = ''; data.name.textContent = ''; data.author.textContent = ''; data.description.textContent = ''; data.installCount.style.display = 'none'; data.ratings.style.display = 'none'; data.extension = null; } renderElement(extension: IExtension, index: number, data: ITemplateData): void { removeClass(data.element, 'loading'); data.extensionDisposables = dispose(data.extensionDisposables); const installed = this.extensionsWorkbenchService.local.filter(e => e.id === extension.id)[0]; this.extensionService.getExtensions().then(runningExtensions => { if (installed && installed.local) { const installedExtensionServer = this.extensionManagementServerService.getExtensionManagementServer(installed.local.location); const isSameExtensionRunning = runningExtensions.some(e => areSameExtensions(e, extension) && installedExtensionServer.authority === this.extensionManagementServerService.getExtensionManagementServer(e.extensionLocation).authority); toggleClass(data.root, 'disabled', !isSameExtensionRunning); } else { removeClass(data.root, 'disabled'); } }); const onError = once(domEvent(data.icon, 'error')); onError(() => data.icon.src = extension.iconUrlFallback, null, data.extensionDisposables); data.icon.src = extension.iconUrl; if (!data.icon.complete) { data.icon.style.visibility = 'hidden'; data.icon.onload = () => data.icon.style.visibility = 'inherit'; } else { data.icon.style.visibility = 'inherit'; } this.updateRecommendationStatus(extension, data); data.extensionDisposables.push(this.extensionTipsService.onRecommendationChange(change => { if (change.extensionId.toLowerCase() === extension.id.toLowerCase()) { this.updateRecommendationStatus(extension, data); } })); data.name.textContent = extension.displayName; data.author.textContent = extension.publisherDisplayName; data.description.textContent = extension.description; data.installCount.style.display = ''; data.ratings.style.display = ''; data.extension = extension; const manifestPromise = createCancelablePromise(token => extension.getManifest(token).then(manifest => { if (manifest) { const name = manifest && manifest.contributes && manifest.contributes.localizations && manifest.contributes.localizations.length > 0 && manifest.contributes.localizations[0].localizedLanguageName; if (name) { data.description.textContent = name[0].toLocaleUpperCase() + name.slice(1); } } })); data.disposables.push(toDisposable(() => manifestPromise.cancel())); } disposeElement(): void { // noop } private updateRecommendationStatus(extension: IExtension, data: ITemplateData) { const extRecommendations = this.extensionTipsService.getAllRecommendationsWithReason(); let ariaLabel = extension.displayName + '. '; if (!extRecommendations[extension.id.toLowerCase()]) { removeClass(data.root, 'recommended'); data.root.title = ''; } else { addClass(data.root, 'recommended'); ariaLabel += extRecommendations[extension.id.toLowerCase()].reasonText + ' '; data.root.title = extRecommendations[extension.id.toLowerCase()].reasonText; } ariaLabel += localize('viewExtensionDetailsAria', "Press enter for extension details."); data.root.setAttribute('aria-label', ariaLabel); } disposeTemplate(data: ITemplateData): void { data.disposables = dispose(data.disposables); } }
src/vs/workbench/parts/extensions/electron-browser/extensionsList.ts
1
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.0016552646411582828, 0.00024675895110704005, 0.0001699540443951264, 0.0001751264207996428, 0.0003080290916841477 ]
{ "id": 2, "code_window": [ "\tconst values = version.properties ? version.properties.filter(p => p.key === PropertyType.Engine) : [];\n", "\treturn (values.length > 0 && values[0].value) || '';\n", "}\n", "\n", "function getIsPreview(flags: string): boolean {\n", "\treturn flags.indexOf('preview') !== -1;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "function getLocalizedLanguages(version: IRawGalleryExtensionVersion): string[] {\n", "\tconst values = version.properties ? version.properties.filter(p => p.key === PropertyType.LocalizedLanguages) : [];\n", "\tconst value = (values.length > 0 && values[0].value) || '';\n", "\treturn value ? value.split(',') : [];\n", "}\n", "\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "add", "edit_start_line_idx": 276 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><polygon points="9,3 8,5 8,2 6,2 6,0 2,0 2,2 0,2 0,6 2,6 2,8 2,15 16,15 16,3" fill="#F6F6F6"/><path d="M14 4h-4.382l-1 2h-2.618v2h-3v6h12v-10h-1zm0 2h-3.882l.5-1h3.382v1z" fill="#656565"/><polygon points="7,3.018 5,3.018 5,1 3.019,1 3.019,3.018 1,3.018 1,5 3.019,5 3.019,7 5,7 5,5 7,5" fill="#388A34"/><polygon points="14,5 14,6 10.118,6 10.618,5" fill="#F0EFF1"/></svg>
src/vs/workbench/parts/files/electron-browser/media/AddFolder.svg
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017606727487873286, 0.00017606727487873286, 0.00017606727487873286, 0.00017606727487873286, 0 ]
{ "id": 2, "code_window": [ "\tconst values = version.properties ? version.properties.filter(p => p.key === PropertyType.Engine) : [];\n", "\treturn (values.length > 0 && values[0].value) || '';\n", "}\n", "\n", "function getIsPreview(flags: string): boolean {\n", "\treturn flags.indexOf('preview') !== -1;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "function getLocalizedLanguages(version: IRawGalleryExtensionVersion): string[] {\n", "\tconst values = version.properties ? version.properties.filter(p => p.key === PropertyType.LocalizedLanguages) : [];\n", "\tconst value = (values.length > 0 && values[0].value) || '';\n", "\treturn value ? value.split(',') : [];\n", "}\n", "\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "add", "edit_start_line_idx": 276 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { Registry } from 'vs/platform/registry/common/platform'; import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { HistoryNavigationKeybindingsChangedContribution } from 'vs/workbench/parts/navigation/common/removedKeybindingsContribution'; Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(HistoryNavigationKeybindingsChangedContribution, LifecyclePhase.Eventually);
src/vs/workbench/parts/navigation/common/navigation.contribution.ts
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.0001777407160261646, 0.0001766324567142874, 0.00017552418285049498, 0.0001766324567142874, 0.0000011082665878348053 ]
{ "id": 2, "code_window": [ "\tconst values = version.properties ? version.properties.filter(p => p.key === PropertyType.Engine) : [];\n", "\treturn (values.length > 0 && values[0].value) || '';\n", "}\n", "\n", "function getIsPreview(flags: string): boolean {\n", "\treturn flags.indexOf('preview') !== -1;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "function getLocalizedLanguages(version: IRawGalleryExtensionVersion): string[] {\n", "\tconst values = version.properties ? version.properties.filter(p => p.key === PropertyType.LocalizedLanguages) : [];\n", "\tconst value = (values.length > 0 && values[0].value) || '';\n", "\treturn value ? value.split(',') : [];\n", "}\n", "\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "add", "edit_start_line_idx": 276 }
/*--------------------------------------------------------------------------------------------- * 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 { TPromise } from 'vs/base/common/winjs.base'; import { List } from 'vs/base/browser/ui/list/listWidget'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { IListService } from 'vs/platform/list/browser/listService'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IDebugService, IEnablement, CONTEXT_BREAKPOINTS_FOCUSED, CONTEXT_WATCH_EXPRESSIONS_FOCUSED, CONTEXT_VARIABLES_FOCUSED, EDITOR_CONTRIBUTION_ID, IDebugEditorContribution, CONTEXT_IN_DEBUG_MODE, CONTEXT_EXPRESSION_SELECTED, CONTEXT_BREAKPOINT_SELECTED } from 'vs/workbench/parts/debug/common/debug'; import { Expression, Variable, Breakpoint, FunctionBreakpoint } from 'vs/workbench/parts/debug/common/debugModel'; import { IExtensionsViewlet, VIEWLET_ID as EXTENSIONS_VIEWLET_ID } from 'vs/workbench/parts/extensions/common/extensions'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { ICodeEditor, isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { openBreakpointSource } from 'vs/workbench/parts/debug/browser/breakpointsView'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { InputFocusedContext } from 'vs/platform/workbench/common/contextkeys'; import { ServicesAccessor } from 'vs/editor/browser/editorExtensions'; export const ADD_CONFIGURATION_ID = 'debug.addConfiguration'; export const TOGGLE_INLINE_BREAKPOINT_ID = 'editor.debug.action.toggleInlineBreakpoint'; export function registerCommands(): void { KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'debug.toggleBreakpoint', weight: KeybindingWeight.WorkbenchContrib + 5, when: ContextKeyExpr.and(CONTEXT_BREAKPOINTS_FOCUSED, InputFocusedContext.toNegated()), primary: KeyCode.Space, handler: (accessor) => { const listService = accessor.get(IListService); const debugService = accessor.get(IDebugService); const list = listService.lastFocusedList; if (list instanceof List) { const focused = <IEnablement[]>list.getFocusedElements(); if (focused && focused.length) { debugService.enableOrDisableBreakpoints(!focused[0].enabled, focused[0]); } } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'debug.enableOrDisableBreakpoint', weight: KeybindingWeight.WorkbenchContrib, primary: undefined, when: EditorContextKeys.editorTextFocus, handler: (accessor) => { const debugService = accessor.get(IDebugService); const editorService = accessor.get(IEditorService); const widget = editorService.activeTextEditorWidget; if (isCodeEditor(widget)) { const model = widget.getModel(); if (model) { const position = widget.getPosition(); const bps = debugService.getModel().getBreakpoints({ uri: model.uri, lineNumber: position.lineNumber }); if (bps.length) { debugService.enableOrDisableBreakpoints(!bps[0].enabled, bps[0]); } } } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'debug.renameWatchExpression', weight: KeybindingWeight.WorkbenchContrib + 5, when: CONTEXT_WATCH_EXPRESSIONS_FOCUSED, primary: KeyCode.F2, mac: { primary: KeyCode.Enter }, handler: (accessor) => { const listService = accessor.get(IListService); const debugService = accessor.get(IDebugService); const focused = listService.lastFocusedList; // Tree only if (!(focused instanceof List)) { const element = focused.getFocus(); if (element instanceof Expression) { debugService.getViewModel().setSelectedExpression(element); } } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'debug.setVariable', weight: KeybindingWeight.WorkbenchContrib + 5, when: CONTEXT_VARIABLES_FOCUSED, primary: KeyCode.F2, mac: { primary: KeyCode.Enter }, handler: (accessor) => { const listService = accessor.get(IListService); const debugService = accessor.get(IDebugService); const focused = listService.lastFocusedList; // Tree only if (!(focused instanceof List)) { const element = focused.getFocus(); if (element instanceof Variable) { debugService.getViewModel().setSelectedExpression(element); } } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'debug.removeWatchExpression', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(CONTEXT_WATCH_EXPRESSIONS_FOCUSED, CONTEXT_EXPRESSION_SELECTED.toNegated()), primary: KeyCode.Delete, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace }, handler: (accessor) => { const listService = accessor.get(IListService); const debugService = accessor.get(IDebugService); const focused = listService.lastFocusedList; // Tree only if (!(focused instanceof List)) { const element = focused.getFocus(); if (element instanceof Expression) { debugService.removeWatchExpressions(element.getId()); } } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'debug.removeBreakpoint', weight: KeybindingWeight.WorkbenchContrib, when: ContextKeyExpr.and(CONTEXT_BREAKPOINTS_FOCUSED, CONTEXT_BREAKPOINT_SELECTED.toNegated()), primary: KeyCode.Delete, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace }, handler: (accessor) => { const listService = accessor.get(IListService); const debugService = accessor.get(IDebugService); const list = listService.lastFocusedList; // Tree only if (list instanceof List) { const focused = list.getFocusedElements(); const element = focused.length ? focused[0] : undefined; if (element instanceof Breakpoint) { debugService.removeBreakpoints(element.getId()); } else if (element instanceof FunctionBreakpoint) { debugService.removeFunctionBreakpoints(element.getId()); } } } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'debug.installAdditionalDebuggers', weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: undefined, handler: (accessor) => { const viewletService = accessor.get(IViewletService); return viewletService.openViewlet(EXTENSIONS_VIEWLET_ID, true) .then(viewlet => viewlet as IExtensionsViewlet) .then(viewlet => { viewlet.search('tag:debuggers @sort:installs'); viewlet.focus(); }); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: ADD_CONFIGURATION_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: undefined, handler: (accessor, launchUri: string) => { const manager = accessor.get(IDebugService).getConfigurationManager(); if (accessor.get(IWorkspaceContextService).getWorkbenchState() === WorkbenchState.EMPTY) { accessor.get(INotificationService).info(nls.localize('noFolderDebugConfig', "Please first open a folder in order to do advanced debug configuration.")); return TPromise.as(null); } const launch = manager.getLaunches().filter(l => l.uri.toString() === launchUri).pop() || manager.selectedConfiguration.launch; return launch.openConfigFile(false, false).then(({ editor, created }) => { if (editor && !created) { const codeEditor = <ICodeEditor>editor.getControl(); if (codeEditor) { return codeEditor.getContribution<IDebugEditorContribution>(EDITOR_CONTRIBUTION_ID).addLaunchConfiguration(); } } return undefined; }); } }); const inlineBreakpointHandler = (accessor: ServicesAccessor) => { const debugService = accessor.get(IDebugService); const editorService = accessor.get(IEditorService); const widget = editorService.activeTextEditorWidget; if (isCodeEditor(widget)) { const position = widget.getPosition(); const modelUri = widget.getModel().uri; const bp = debugService.getModel().getBreakpoints({ lineNumber: position.lineNumber, uri: modelUri }) .filter(bp => (bp.column === position.column || !bp.column && position.column <= 1)).pop(); if (bp) { return TPromise.as(null); } if (debugService.getConfigurationManager().canSetBreakpointsIn(widget.getModel())) { return debugService.addBreakpoints(modelUri, [{ lineNumber: position.lineNumber, column: position.column > 1 ? position.column : undefined }]); } } return TPromise.as(null); }; KeybindingsRegistry.registerCommandAndKeybindingRule({ weight: KeybindingWeight.WorkbenchContrib, primary: KeyMod.Shift | KeyCode.F9, when: EditorContextKeys.editorTextFocus, id: TOGGLE_INLINE_BREAKPOINT_ID, handler: inlineBreakpointHandler }); MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command: { id: TOGGLE_INLINE_BREAKPOINT_ID, title: { value: nls.localize('inlineBreakpoint', "Inline Breakpoint"), original: 'Debug: Inline Breakpoint' }, category: nls.localize('debug', "Debug") } }); MenuRegistry.appendMenuItem(MenuId.EditorContext, { command: { id: TOGGLE_INLINE_BREAKPOINT_ID, title: nls.localize('addInlineBreakpoint', "Add Inline Breakpoint") }, when: ContextKeyExpr.and(CONTEXT_IN_DEBUG_MODE, EditorContextKeys.writable, EditorContextKeys.editorTextFocus), group: 'debug', order: 1 }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'debug.openBreakpointToSide', weight: KeybindingWeight.WorkbenchContrib, when: CONTEXT_BREAKPOINTS_FOCUSED, primary: KeyMod.CtrlCmd | KeyCode.Enter, secondary: [KeyMod.Alt | KeyCode.Enter], handler: (accessor) => { const listService = accessor.get(IListService); const list = listService.lastFocusedList; if (list instanceof List) { const focus = list.getFocusedElements(); if (focus.length && focus[0] instanceof Breakpoint) { return openBreakpointSource(focus[0], true, false, accessor.get(IDebugService), accessor.get(IEditorService)); } } return TPromise.as(undefined); } }); }
src/vs/workbench/parts/debug/browser/debugCommands.ts
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017826126713771373, 0.00017515542276669294, 0.000172195810591802, 0.00017540925182402134, 0.0000016877056623343378 ]
{ "id": 3, "code_window": [ "\t\tratingCount: getStatistic(galleryExtension.statistics, 'ratingcount'),\n", "\t\tassets,\n", "\t\tproperties: {\n", "\t\t\tdependencies: getExtensions(version, PropertyType.Dependency),\n", "\t\t\textensionPack: getExtensions(version, PropertyType.ExtensionPack),\n", "\t\t\tengine: getEngine(version)\n", "\t\t},\n", "\t\t/* __GDPR__FRAGMENT__\n", "\t\t\t\"GalleryExtensionTelemetryData2\" : {\n", "\t\t\t\t\"index\" : { \"classification\": \"SystemMetaData\", \"purpose\": \"FeatureInsight\", \"isMeasurement\": true },\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tengine: getEngine(version),\n", "\t\t\tlocalizedLanguages: getLocalizedLanguages(version)\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "replace", "edit_start_line_idx": 312 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { tmpdir } from 'os'; import * as path from 'path'; import { TPromise } from 'vs/base/common/winjs.base'; import { distinct } from 'vs/base/common/arrays'; import { getErrorMessage, isPromiseCanceledError, canceled } from 'vs/base/common/errors'; import { StatisticType, IGalleryExtension, IExtensionGalleryService, IGalleryExtensionAsset, IQueryOptions, SortBy, SortOrder, IExtensionManifest, IExtensionIdentifier, IReportedExtension, InstallOperation, ITranslation } from 'vs/platform/extensionManagement/common/extensionManagement'; import { getGalleryExtensionId, getGalleryExtensionTelemetryData, adoptToGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { assign, getOrDefault } from 'vs/base/common/objects'; import { IRequestService } from 'vs/platform/request/node/request'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IPager } from 'vs/base/common/paging'; import { IRequestOptions, IRequestContext, download, asJson, asText } from 'vs/base/node/request'; import pkg from 'vs/platform/node/package'; import product from 'vs/platform/node/product'; import { isEngineValid } from 'vs/platform/extensions/node/extensionValidator'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { readFile } from 'vs/base/node/pfs'; import { writeFileAndFlushSync } from 'vs/base/node/extfs'; import { generateUuid, isUUID } from 'vs/base/common/uuid'; import { values } from 'vs/base/common/map'; import { CancellationToken } from 'vs/base/common/cancellation'; interface IRawGalleryExtensionFile { assetType: string; source: string; } interface IRawGalleryExtensionProperty { key: string; value: string; } interface IRawGalleryExtensionVersion { version: string; lastUpdated: string; assetUri: string; fallbackAssetUri: string; files: IRawGalleryExtensionFile[]; properties?: IRawGalleryExtensionProperty[]; } interface IRawGalleryExtensionStatistics { statisticName: string; value: number; } interface IRawGalleryExtension { extensionId: string; extensionName: string; displayName: string; shortDescription: string; publisher: { displayName: string, publisherId: string, publisherName: string; }; versions: IRawGalleryExtensionVersion[]; statistics: IRawGalleryExtensionStatistics[]; flags: string; } interface IRawGalleryQueryResult { results: { extensions: IRawGalleryExtension[]; resultMetadata: { metadataType: string; metadataItems: { name: string; count: number; }[]; }[] }[]; } enum Flags { None = 0x0, IncludeVersions = 0x1, IncludeFiles = 0x2, IncludeCategoryAndTags = 0x4, IncludeSharedAccounts = 0x8, IncludeVersionProperties = 0x10, ExcludeNonValidated = 0x20, IncludeInstallationTargets = 0x40, IncludeAssetUri = 0x80, IncludeStatistics = 0x100, IncludeLatestVersionOnly = 0x200, Unpublished = 0x1000 } function flagsToString(...flags: Flags[]): string { return String(flags.reduce((r, f) => r | f, 0)); } enum FilterType { Tag = 1, ExtensionId = 4, Category = 5, ExtensionName = 7, Target = 8, Featured = 9, SearchText = 10, ExcludeWithFlags = 12 } const AssetType = { Icon: 'Microsoft.VisualStudio.Services.Icons.Default', Details: 'Microsoft.VisualStudio.Services.Content.Details', Changelog: 'Microsoft.VisualStudio.Services.Content.Changelog', Manifest: 'Microsoft.VisualStudio.Code.Manifest', VSIX: 'Microsoft.VisualStudio.Services.VSIXPackage', License: 'Microsoft.VisualStudio.Services.Content.License', Repository: 'Microsoft.VisualStudio.Services.Links.Source' }; const PropertyType = { Dependency: 'Microsoft.VisualStudio.Code.ExtensionDependencies', ExtensionPack: 'Microsoft.VisualStudio.Code.ExtensionPack', Engine: 'Microsoft.VisualStudio.Code.Engine' }; interface ICriterium { filterType: FilterType; value?: string; } const DefaultPageSize = 10; interface IQueryState { pageNumber: number; pageSize: number; sortBy: SortBy; sortOrder: SortOrder; flags: Flags; criteria: ICriterium[]; assetTypes: string[]; } const DefaultQueryState: IQueryState = { pageNumber: 1, pageSize: DefaultPageSize, sortBy: SortBy.NoneOrRelevance, sortOrder: SortOrder.Default, flags: Flags.None, criteria: [], assetTypes: [] }; class Query { constructor(private state = DefaultQueryState) { } get pageNumber(): number { return this.state.pageNumber; } get pageSize(): number { return this.state.pageSize; } get sortBy(): number { return this.state.sortBy; } get sortOrder(): number { return this.state.sortOrder; } get flags(): number { return this.state.flags; } withPage(pageNumber: number, pageSize: number = this.state.pageSize): Query { return new Query(assign({}, this.state, { pageNumber, pageSize })); } withFilter(filterType: FilterType, ...values: string[]): Query { const criteria = [ ...this.state.criteria, ...values.map(value => ({ filterType, value })) ]; return new Query(assign({}, this.state, { criteria })); } withSortBy(sortBy: SortBy): Query { return new Query(assign({}, this.state, { sortBy })); } withSortOrder(sortOrder: SortOrder): Query { return new Query(assign({}, this.state, { sortOrder })); } withFlags(...flags: Flags[]): Query { return new Query(assign({}, this.state, { flags: flags.reduce((r, f) => r | f, 0) })); } withAssetTypes(...assetTypes: string[]): Query { return new Query(assign({}, this.state, { assetTypes })); } get raw(): any { const { criteria, pageNumber, pageSize, sortBy, sortOrder, flags, assetTypes } = this.state; const filters = [{ criteria, pageNumber, pageSize, sortBy, sortOrder }]; return { filters, assetTypes, flags }; } get searchText(): string { const criterium = this.state.criteria.filter(criterium => criterium.filterType === FilterType.SearchText)[0]; return criterium ? criterium.value : ''; } } function getStatistic(statistics: IRawGalleryExtensionStatistics[], name: string): number { const result = (statistics || []).filter(s => s.statisticName === name)[0]; return result ? result.value : 0; } function getCoreTranslationAssets(version: IRawGalleryExtensionVersion): { [languageId: string]: IGalleryExtensionAsset } { const coreTranslationAssetPrefix = 'Microsoft.VisualStudio.Code.Translation.'; const result = version.files.filter(f => f.assetType.indexOf(coreTranslationAssetPrefix) === 0); return result.reduce((result, file) => { result[file.assetType.substring(coreTranslationAssetPrefix.length)] = getVersionAsset(version, file.assetType); return result; }, {}); } function getVersionAsset(version: IRawGalleryExtensionVersion, type: string): IGalleryExtensionAsset { const result = version.files.filter(f => f.assetType === type)[0]; if (type === AssetType.Repository) { if (version.properties) { const results = version.properties.filter(p => p.key === type); const gitRegExp = new RegExp('((git|ssh|http(s)?)|(git@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(\.git)(/)?'); const uri = results.filter(r => gitRegExp.test(r.value))[0]; if (!uri) { return { uri: null, fallbackUri: null }; } return { uri: uri.value, fallbackUri: uri.value, }; } } if (!result) { if (type === AssetType.Icon) { const uri = require.toUrl('./media/defaultIcon.png'); return { uri, fallbackUri: uri }; } if (type === AssetType.Repository) { return { uri: null, fallbackUri: null }; } return null; } if (type === AssetType.VSIX) { return { uri: `${version.fallbackAssetUri}/${type}?redirect=true`, fallbackUri: `${version.fallbackAssetUri}/${type}` }; } return { uri: `${version.assetUri}/${type}`, fallbackUri: `${version.fallbackAssetUri}/${type}` }; } function getExtensions(version: IRawGalleryExtensionVersion, property: string): string[] { const values = version.properties ? version.properties.filter(p => p.key === property) : []; const value = values.length > 0 && values[0].value; return value ? value.split(',').map(v => adoptToGalleryExtensionId(v)) : []; } function getEngine(version: IRawGalleryExtensionVersion): string { const values = version.properties ? version.properties.filter(p => p.key === PropertyType.Engine) : []; return (values.length > 0 && values[0].value) || ''; } function getIsPreview(flags: string): boolean { return flags.indexOf('preview') !== -1; } function toExtension(galleryExtension: IRawGalleryExtension, version: IRawGalleryExtensionVersion, index: number, query: Query, querySource?: string): IGalleryExtension { const assets = { manifest: getVersionAsset(version, AssetType.Manifest), readme: getVersionAsset(version, AssetType.Details), changelog: getVersionAsset(version, AssetType.Changelog), download: getVersionAsset(version, AssetType.VSIX), icon: getVersionAsset(version, AssetType.Icon), license: getVersionAsset(version, AssetType.License), repository: getVersionAsset(version, AssetType.Repository), coreTranslations: getCoreTranslationAssets(version) }; return { identifier: { id: getGalleryExtensionId(galleryExtension.publisher.publisherName, galleryExtension.extensionName), uuid: galleryExtension.extensionId }, name: galleryExtension.extensionName, version: version.version, date: version.lastUpdated, displayName: galleryExtension.displayName, publisherId: galleryExtension.publisher.publisherId, publisher: galleryExtension.publisher.publisherName, publisherDisplayName: galleryExtension.publisher.displayName, description: galleryExtension.shortDescription || '', installCount: getStatistic(galleryExtension.statistics, 'install') + getStatistic(galleryExtension.statistics, 'updateCount'), rating: getStatistic(galleryExtension.statistics, 'averagerating'), ratingCount: getStatistic(galleryExtension.statistics, 'ratingcount'), assets, properties: { dependencies: getExtensions(version, PropertyType.Dependency), extensionPack: getExtensions(version, PropertyType.ExtensionPack), engine: getEngine(version) }, /* __GDPR__FRAGMENT__ "GalleryExtensionTelemetryData2" : { "index" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "searchText": { "classification": "CustomerContent", "purpose": "FeatureInsight" }, "querySource": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ telemetryData: { index: ((query.pageNumber - 1) * query.pageSize) + index, searchText: query.searchText, querySource }, preview: getIsPreview(galleryExtension.flags) }; } interface IRawExtensionsReport { malicious: string[]; slow: string[]; } export class ExtensionGalleryService implements IExtensionGalleryService { _serviceBrand: any; private extensionsGalleryUrl: string; private extensionsControlUrl: string; private readonly commonHeadersPromise: TPromise<{ [key: string]: string; }>; constructor( @IRequestService private requestService: IRequestService, @IEnvironmentService private environmentService: IEnvironmentService, @ITelemetryService private telemetryService: ITelemetryService ) { const config = product.extensionsGallery; this.extensionsGalleryUrl = config && config.serviceUrl; this.extensionsControlUrl = config && config.controlUrl; this.commonHeadersPromise = resolveMarketplaceHeaders(this.environmentService); } private api(path = ''): string { return `${this.extensionsGalleryUrl}${path}`; } isEnabled(): boolean { return !!this.extensionsGalleryUrl; } getExtension({ id, uuid }: IExtensionIdentifier, version?: string): TPromise<IGalleryExtension> { let query = new Query() .withFlags(Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, 1) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)); if (uuid) { query = query.withFilter(FilterType.ExtensionId, uuid); } else { query = query.withFilter(FilterType.ExtensionName, id); } return this.queryGallery(query, CancellationToken.None).then(({ galleryExtensions }) => { if (galleryExtensions.length) { const galleryExtension = galleryExtensions[0]; const versionAsset = version ? galleryExtension.versions.filter(v => v.version === version)[0] : galleryExtension.versions[0]; if (versionAsset) { return toExtension(galleryExtension, versionAsset, 0, query); } } return null; }); } query(options: IQueryOptions = {}): TPromise<IPager<IGalleryExtension>> { if (!this.isEnabled()) { return TPromise.wrapError<IPager<IGalleryExtension>>(new Error('No extension gallery service configured.')); } const type = options.names ? 'ids' : (options.text ? 'text' : 'all'); let text = options.text || ''; const pageSize = getOrDefault(options, o => o.pageSize, 50); /* __GDPR__ "galleryService:query" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "text": { "classification": "CustomerContent", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:query', { type, text }); let query = new Query() .withFlags(Flags.IncludeLatestVersionOnly, Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, pageSize) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)); if (text) { // Use category filter instead of "category:themes" text = text.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedCategory, category) => { query = query.withFilter(FilterType.Category, category || quotedCategory); return ''; }); // Use tag filter instead of "tag:debuggers" text = text.replace(/\btag:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedTag, tag) => { query = query.withFilter(FilterType.Tag, tag || quotedTag); return ''; }); text = text.trim(); if (text) { text = text.length < 200 ? text : text.substring(0, 200); query = query.withFilter(FilterType.SearchText, text); } query = query.withSortBy(SortBy.NoneOrRelevance); } else if (options.ids) { query = query.withFilter(FilterType.ExtensionId, ...options.ids); } else if (options.names) { query = query.withFilter(FilterType.ExtensionName, ...options.names); } else { query = query.withSortBy(SortBy.InstallCount); } if (typeof options.sortBy === 'number') { query = query.withSortBy(options.sortBy); } if (typeof options.sortOrder === 'number') { query = query.withSortOrder(options.sortOrder); } return this.queryGallery(query, CancellationToken.None).then(({ galleryExtensions, total }) => { const extensions = galleryExtensions.map((e, index) => toExtension(e, e.versions[0], index, query, options.source)); const pageSize = query.pageSize; const getPage = (pageIndex: number, ct: CancellationToken) => { if (ct.isCancellationRequested) { return TPromise.wrapError(canceled()); } const nextPageQuery = query.withPage(pageIndex + 1); return this.queryGallery(nextPageQuery, ct) .then(({ galleryExtensions }) => galleryExtensions.map((e, index) => toExtension(e, e.versions[0], index, nextPageQuery, options.source))); }; return { firstPage: extensions, total, pageSize, getPage } as IPager<IGalleryExtension>; }); } private queryGallery(query: Query, token: CancellationToken): TPromise<{ galleryExtensions: IRawGalleryExtension[], total: number; }> { return this.commonHeadersPromise.then(commonHeaders => { const data = JSON.stringify(query.raw); const headers = assign({}, commonHeaders, { 'Content-Type': 'application/json', 'Accept': 'application/json;api-version=3.0-preview.1', 'Accept-Encoding': 'gzip', 'Content-Length': data.length }); return this.requestService.request({ type: 'POST', url: this.api('/extensionquery'), data, headers }, token).then(context => { if (context.res.statusCode >= 400 && context.res.statusCode < 500) { return { galleryExtensions: [], total: 0 }; } return asJson<IRawGalleryQueryResult>(context).then(result => { const r = result.results[0]; const galleryExtensions = r.extensions; const resultCount = r.resultMetadata && r.resultMetadata.filter(m => m.metadataType === 'ResultCount')[0]; const total = resultCount && resultCount.metadataItems.filter(i => i.name === 'TotalCount')[0].count || 0; return { galleryExtensions, total }; }); }); }); } reportStatistic(publisher: string, name: string, version: string, type: StatisticType): TPromise<void> { if (!this.isEnabled()) { return TPromise.as(null); } return this.commonHeadersPromise.then(commonHeaders => { const headers = { ...commonHeaders, Accept: '*/*;api-version=4.0-preview.1' }; return this.requestService.request({ type: 'POST', url: this.api(`/publishers/${publisher}/extensions/${name}/${version}/stats?statType=${type}`), headers }, CancellationToken.None).then(null, () => null); }); } download(extension: IGalleryExtension, operation: InstallOperation): TPromise<string> { const zipPath = path.join(tmpdir(), generateUuid()); const data = getGalleryExtensionTelemetryData(extension); const startTime = new Date().getTime(); /* __GDPR__ "galleryService:downloadVSIX" : { "duration": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true }, "${include}": [ "${GalleryExtensionTelemetryData}" ] } */ const log = (duration: number) => this.telemetryService.publicLog('galleryService:downloadVSIX', assign(data, { duration })); const operationParam = operation === InstallOperation.Install ? 'install' : operation === InstallOperation.Update ? 'update' : ''; const downloadAsset = operationParam ? { uri: `${extension.assets.download.uri}&${operationParam}=true`, fallbackUri: `${extension.assets.download.fallbackUri}?${operationParam}=true` } : extension.assets.download; return this.getAsset(downloadAsset) .then(context => download(zipPath, context)) .then(() => log(new Date().getTime() - startTime)) .then(() => zipPath); } getReadme(extension: IGalleryExtension, token: CancellationToken): TPromise<string> { return this.getAsset(extension.assets.readme, {}, token) .then(asText); } getManifest(extension: IGalleryExtension, token: CancellationToken): TPromise<IExtensionManifest> { return this.getAsset(extension.assets.manifest, {}, token) .then(asText) .then(JSON.parse); } getCoreTranslation(extension: IGalleryExtension, languageId: string): TPromise<ITranslation> { const asset = extension.assets.coreTranslations[languageId.toUpperCase()]; if (asset) { return this.getAsset(asset) .then(asText) .then(JSON.parse); } return TPromise.as(null); } getChangelog(extension: IGalleryExtension, token: CancellationToken): TPromise<string> { return this.getAsset(extension.assets.changelog, {}, token) .then(asText); } loadAllDependencies(extensions: IExtensionIdentifier[], token: CancellationToken): TPromise<IGalleryExtension[]> { return this.getDependenciesReccursively(extensions.map(e => e.id), [], token); } loadCompatibleVersion(extension: IGalleryExtension): TPromise<IGalleryExtension> { if (extension.properties.engine && isEngineValid(extension.properties.engine)) { return TPromise.wrap(extension); } const query = new Query() .withFlags(Flags.IncludeVersions, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, 1) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)) .withAssetTypes(AssetType.Manifest, AssetType.VSIX) .withFilter(FilterType.ExtensionId, extension.identifier.uuid); return this.queryGallery(query, CancellationToken.None) .then(({ galleryExtensions }) => { const [rawExtension] = galleryExtensions; if (!rawExtension) { return null; } return this.getLastValidExtensionVersion(rawExtension, rawExtension.versions) .then(rawVersion => { if (rawVersion) { extension.properties.dependencies = getExtensions(rawVersion, PropertyType.Dependency); extension.properties.engine = getEngine(rawVersion); extension.assets.download = getVersionAsset(rawVersion, AssetType.VSIX); extension.version = rawVersion.version; return extension; } return null; }); }); } private loadDependencies(extensionNames: string[], token: CancellationToken): TPromise<IGalleryExtension[]> { if (!extensionNames || extensionNames.length === 0) { return TPromise.as([]); } let query = new Query() .withFlags(Flags.IncludeLatestVersionOnly, Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, extensionNames.length) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)) .withAssetTypes(AssetType.Icon, AssetType.License, AssetType.Details, AssetType.Manifest, AssetType.VSIX) .withFilter(FilterType.ExtensionName, ...extensionNames); return this.queryGallery(query, token).then(result => { const dependencies = []; const ids = []; for (let index = 0; index < result.galleryExtensions.length; index++) { const rawExtension = result.galleryExtensions[index]; if (ids.indexOf(rawExtension.extensionId) === -1) { dependencies.push(toExtension(rawExtension, rawExtension.versions[0], index, query, 'dependencies')); ids.push(rawExtension.extensionId); } } return dependencies; }); } private getDependenciesReccursively(toGet: string[], result: IGalleryExtension[], token: CancellationToken): TPromise<IGalleryExtension[]> { if (!toGet || !toGet.length) { return TPromise.wrap(result); } toGet = result.length ? toGet.filter(e => !ExtensionGalleryService.hasExtensionByName(result, e)) : toGet; if (!toGet.length) { return TPromise.wrap(result); } return this.loadDependencies(toGet, token) .then(loadedDependencies => { const dependenciesSet = new Set<string>(); for (const dep of loadedDependencies) { if (dep.properties.dependencies) { dep.properties.dependencies.forEach(d => dependenciesSet.add(d)); } } result = distinct(result.concat(loadedDependencies), d => d.identifier.uuid); const dependencies: string[] = []; dependenciesSet.forEach(d => !ExtensionGalleryService.hasExtensionByName(result, d) && dependencies.push(d)); return this.getDependenciesReccursively(dependencies, result, token); }); } private getAsset(asset: IGalleryExtensionAsset, options: IRequestOptions = {}, token: CancellationToken = CancellationToken.None): TPromise<IRequestContext> { return this.commonHeadersPromise.then(commonHeaders => { const baseOptions = { type: 'GET' }; const headers = assign({}, commonHeaders, options.headers || {}); options = assign({}, options, baseOptions, { headers }); const url = asset.uri; const fallbackUrl = asset.fallbackUri; const firstOptions = assign({}, options, { url }); return this.requestService.request(firstOptions, token) .then(context => { if (context.res.statusCode === 200) { return TPromise.as(context); } return asText(context) .then(message => TPromise.wrapError<IRequestContext>(new Error(`Expected 200, got back ${context.res.statusCode} instead.\n\n${message}`))); }) .then(null, err => { if (isPromiseCanceledError(err)) { return TPromise.wrapError<IRequestContext>(err); } const message = getErrorMessage(err); /* __GDPR__ "galleryService:requestError" : { "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "cdn": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:requestError', { url, cdn: true, message }); /* __GDPR__ "galleryService:cdnFallback" : { "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "message": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:cdnFallback', { url, message }); const fallbackOptions = assign({}, options, { url: fallbackUrl }); return this.requestService.request(fallbackOptions, token).then(null, err => { if (isPromiseCanceledError(err)) { return TPromise.wrapError<IRequestContext>(err); } const message = getErrorMessage(err); /* __GDPR__ "galleryService:requestError" : { "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "cdn": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:requestError', { url: fallbackUrl, cdn: false, message }); return TPromise.wrapError<IRequestContext>(err); }); }); }); } private getLastValidExtensionVersion(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> { const version = this.getLastValidExtensionVersionFromProperties(extension, versions); if (version) { return version; } return this.getLastValidExtensionVersionReccursively(extension, versions); } private getLastValidExtensionVersionFromProperties(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> { for (const version of versions) { const engine = getEngine(version); if (!engine) { return null; } if (isEngineValid(engine)) { return TPromise.wrap(version); } } return null; } private getLastValidExtensionVersionReccursively(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> { if (!versions.length) { return null; } const version = versions[0]; const asset = getVersionAsset(version, AssetType.Manifest); const headers = { 'Accept-Encoding': 'gzip' }; return this.getAsset(asset, { headers }) .then(context => asJson<IExtensionManifest>(context)) .then(manifest => { const engine = manifest.engines.vscode; if (!isEngineValid(engine)) { return this.getLastValidExtensionVersionReccursively(extension, versions.slice(1)); } version.properties = version.properties || []; version.properties.push({ key: PropertyType.Engine, value: manifest.engines.vscode }); return version; }); } private static hasExtensionByName(extensions: IGalleryExtension[], name: string): boolean { for (const extension of extensions) { if (`${extension.publisher}.${extension.name}` === name) { return true; } } return false; } getExtensionsReport(): TPromise<IReportedExtension[]> { if (!this.isEnabled()) { return TPromise.wrapError(new Error('No extension gallery service configured.')); } if (!this.extensionsControlUrl) { return TPromise.as([]); } return this.requestService.request({ type: 'GET', url: this.extensionsControlUrl }, CancellationToken.None).then(context => { if (context.res.statusCode !== 200) { return TPromise.wrapError(new Error('Could not get extensions report.')); } return asJson<IRawExtensionsReport>(context).then(result => { const map = new Map<string, IReportedExtension>(); for (const id of result.malicious) { const ext = map.get(id) || { id: { id }, malicious: true, slow: false }; ext.malicious = true; map.set(id, ext); } return TPromise.as(values(map)); }); }); } } export function resolveMarketplaceHeaders(environmentService: IEnvironmentService): TPromise<{ [key: string]: string; }> { const marketplaceMachineIdFile = path.join(environmentService.userDataPath, 'machineid'); return readFile(marketplaceMachineIdFile, 'utf8').then(contents => { if (isUUID(contents)) { return contents; } return TPromise.wrap(null); // invalid marketplace UUID }, error => { return TPromise.wrap(null); // error reading ID file }).then(uuid => { if (!uuid) { uuid = generateUuid(); try { writeFileAndFlushSync(marketplaceMachineIdFile, uuid); } catch (error) { //noop } } return { 'X-Market-Client-Id': `VSCode ${pkg.version}`, 'User-Agent': `VSCode ${pkg.version}`, 'X-Market-User-Id': uuid }; }); }
src/vs/platform/extensionManagement/node/extensionGalleryService.ts
1
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.17101140320301056, 0.0026072694454342127, 0.00016320742724929005, 0.00017926849250216037, 0.018514536321163177 ]
{ "id": 3, "code_window": [ "\t\tratingCount: getStatistic(galleryExtension.statistics, 'ratingcount'),\n", "\t\tassets,\n", "\t\tproperties: {\n", "\t\t\tdependencies: getExtensions(version, PropertyType.Dependency),\n", "\t\t\textensionPack: getExtensions(version, PropertyType.ExtensionPack),\n", "\t\t\tengine: getEngine(version)\n", "\t\t},\n", "\t\t/* __GDPR__FRAGMENT__\n", "\t\t\t\"GalleryExtensionTelemetryData2\" : {\n", "\t\t\t\t\"index\" : { \"classification\": \"SystemMetaData\", \"purpose\": \"FeatureInsight\", \"isMeasurement\": true },\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tengine: getEngine(version),\n", "\t\t\tlocalizedLanguages: getLocalizedLanguages(version)\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "replace", "edit_start_line_idx": 312 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as nls from 'vs/nls'; import { TPromise } from 'vs/base/common/winjs.base'; import { Action } from 'vs/base/common/actions'; import * as platform from 'vs/base/common/platform'; import * as touch from 'vs/base/browser/touch'; import * as errors from 'vs/base/common/errors'; import * as dom from 'vs/base/browser/dom'; import * as mouse from 'vs/base/browser/mouseEvent'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import * as _ from 'vs/base/parts/tree/browser/tree'; import { KeyCode, KeyMod, Keybinding, createKeybinding, SimpleKeybinding, createSimpleKeybinding } from 'vs/base/common/keyCodes'; export interface IKeyBindingCallback { (tree: _.ITree, event: IKeyboardEvent): void; } export interface ICancelableEvent { preventDefault(): void; stopPropagation(): void; } export const enum ClickBehavior { /** * Handle the click when the mouse button is pressed but not released yet. */ ON_MOUSE_DOWN, /** * Handle the click when the mouse button is released. */ ON_MOUSE_UP } export const enum OpenMode { SINGLE_CLICK, DOUBLE_CLICK } export interface IControllerOptions { clickBehavior?: ClickBehavior; openMode?: OpenMode; keyboardSupport?: boolean; } interface IKeybindingDispatcherItem { keybinding: Keybinding; callback: IKeyBindingCallback; } export class KeybindingDispatcher { private _arr: IKeybindingDispatcherItem[]; constructor() { this._arr = []; } public has(keybinding: KeyCode): boolean { let target = createSimpleKeybinding(keybinding, platform.OS); for (const a of this._arr) { if (target.equals(a.keybinding)) { return true; } } return false; } public set(keybinding: KeyCode, callback: IKeyBindingCallback) { this._arr.push({ keybinding: createKeybinding(keybinding, platform.OS), callback: callback }); } public dispatch(keybinding: SimpleKeybinding): IKeyBindingCallback { // Loop from the last to the first to handle overwrites for (let i = this._arr.length - 1; i >= 0; i--) { let item = this._arr[i]; if (keybinding.equals(item.keybinding)) { return item.callback; } } return null; } } export class DefaultController implements _.IController { protected downKeyBindingDispatcher: KeybindingDispatcher; protected upKeyBindingDispatcher: KeybindingDispatcher; private options: IControllerOptions; constructor(options: IControllerOptions = { clickBehavior: ClickBehavior.ON_MOUSE_DOWN, keyboardSupport: true, openMode: OpenMode.SINGLE_CLICK }) { this.options = options; this.downKeyBindingDispatcher = new KeybindingDispatcher(); this.upKeyBindingDispatcher = new KeybindingDispatcher(); if (typeof options.keyboardSupport !== 'boolean' || options.keyboardSupport) { this.downKeyBindingDispatcher.set(KeyCode.UpArrow, (t, e) => this.onUp(t, e)); this.downKeyBindingDispatcher.set(KeyCode.DownArrow, (t, e) => this.onDown(t, e)); this.downKeyBindingDispatcher.set(KeyCode.LeftArrow, (t, e) => this.onLeft(t, e)); this.downKeyBindingDispatcher.set(KeyCode.RightArrow, (t, e) => this.onRight(t, e)); if (platform.isMacintosh) { this.downKeyBindingDispatcher.set(KeyMod.CtrlCmd | KeyCode.UpArrow, (t, e) => this.onLeft(t, e)); this.downKeyBindingDispatcher.set(KeyMod.WinCtrl | KeyCode.KEY_N, (t, e) => this.onDown(t, e)); this.downKeyBindingDispatcher.set(KeyMod.WinCtrl | KeyCode.KEY_P, (t, e) => this.onUp(t, e)); } this.downKeyBindingDispatcher.set(KeyCode.PageUp, (t, e) => this.onPageUp(t, e)); this.downKeyBindingDispatcher.set(KeyCode.PageDown, (t, e) => this.onPageDown(t, e)); this.downKeyBindingDispatcher.set(KeyCode.Home, (t, e) => this.onHome(t, e)); this.downKeyBindingDispatcher.set(KeyCode.End, (t, e) => this.onEnd(t, e)); this.downKeyBindingDispatcher.set(KeyCode.Space, (t, e) => this.onSpace(t, e)); this.downKeyBindingDispatcher.set(KeyCode.Escape, (t, e) => this.onEscape(t, e)); this.upKeyBindingDispatcher.set(KeyCode.Enter, this.onEnter.bind(this)); this.upKeyBindingDispatcher.set(KeyMod.CtrlCmd | KeyCode.Enter, this.onEnter.bind(this)); } } public onMouseDown(tree: _.ITree, element: any, event: mouse.IMouseEvent, origin: string = 'mouse'): boolean { if (this.options.clickBehavior === ClickBehavior.ON_MOUSE_DOWN && (event.leftButton || event.middleButton)) { if (event.target) { if (event.target.tagName && event.target.tagName.toLowerCase() === 'input') { return false; // Ignore event if target is a form input field (avoids browser specific issues) } if (dom.findParentWithClass(event.target, 'scrollbar', 'monaco-tree')) { return false; } if (dom.findParentWithClass(event.target, 'monaco-action-bar', 'row')) { // TODO@Joao not very nice way of checking for the action bar (implicit knowledge) return false; // Ignore event if target is over an action bar of the row } } // Propagate to onLeftClick now return this.onLeftClick(tree, element, event, origin); } return false; } public onClick(tree: _.ITree, element: any, event: mouse.IMouseEvent): boolean { const isMac = platform.isMacintosh; // A Ctrl click on the Mac is a context menu event if (isMac && event.ctrlKey) { event.preventDefault(); event.stopPropagation(); return false; } if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') { return false; // Ignore event if target is a form input field (avoids browser specific issues) } if (this.options.clickBehavior === ClickBehavior.ON_MOUSE_DOWN && (event.leftButton || event.middleButton)) { return false; // Already handled by onMouseDown } return this.onLeftClick(tree, element, event); } protected onLeftClick(tree: _.ITree, element: any, eventish: ICancelableEvent, origin: string = 'mouse'): boolean { const event = <mouse.IMouseEvent>eventish; const payload = { origin: origin, originalEvent: eventish, didClickOnTwistie: this.isClickOnTwistie(event) }; if (tree.getInput() === element) { tree.clearFocus(payload); tree.clearSelection(payload); } else { const isSingleMouseDown = eventish && event.browserEvent && event.browserEvent.type === 'mousedown' && event.browserEvent.detail === 1; if (!isSingleMouseDown) { eventish.preventDefault(); // we cannot preventDefault onMouseDown with single click because this would break DND otherwise } eventish.stopPropagation(); tree.domFocus(); tree.setSelection([element], payload); tree.setFocus(element, payload); if (this.shouldToggleExpansion(element, event, origin)) { if (tree.isExpanded(element)) { tree.collapse(element).then(null, errors.onUnexpectedError); } else { tree.expand(element).then(null, errors.onUnexpectedError); } } } return true; } protected shouldToggleExpansion(element: any, event: mouse.IMouseEvent, origin: string): boolean { const isDoubleClick = (origin === 'mouse' && event.detail === 2); return this.openOnSingleClick || isDoubleClick || this.isClickOnTwistie(event); } protected setOpenMode(openMode: OpenMode) { this.options.openMode = openMode; } protected get openOnSingleClick(): boolean { return this.options.openMode === OpenMode.SINGLE_CLICK; } protected isClickOnTwistie(event: mouse.IMouseEvent): boolean { let element = event.target as HTMLElement; if (!dom.hasClass(element, 'content')) { return false; } const twistieStyle = window.getComputedStyle(element, ':before'); if (twistieStyle.backgroundImage === 'none' || twistieStyle.display === 'none') { return false; } const twistieWidth = parseInt(twistieStyle.width) + parseInt(twistieStyle.paddingRight); return event.browserEvent.offsetX <= twistieWidth; } public onContextMenu(tree: _.ITree, element: any, event: _.ContextMenuEvent): boolean { if (event.target && event.target.tagName && event.target.tagName.toLowerCase() === 'input') { return false; // allow context menu on input fields } // Prevent native context menu from showing up if (event) { event.preventDefault(); event.stopPropagation(); } return false; } public onTap(tree: _.ITree, element: any, event: touch.GestureEvent): boolean { const target = <HTMLElement>event.initialTarget; if (target && target.tagName && target.tagName.toLowerCase() === 'input') { return false; // Ignore event if target is a form input field (avoids browser specific issues) } return this.onLeftClick(tree, element, event, 'touch'); } public onKeyDown(tree: _.ITree, event: IKeyboardEvent): boolean { return this.onKey(this.downKeyBindingDispatcher, tree, event); } public onKeyUp(tree: _.ITree, event: IKeyboardEvent): boolean { return this.onKey(this.upKeyBindingDispatcher, tree, event); } private onKey(bindings: KeybindingDispatcher, tree: _.ITree, event: IKeyboardEvent): boolean { const handler = bindings.dispatch(event.toKeybinding()); if (handler) { if (handler(tree, event)) { event.preventDefault(); event.stopPropagation(); return true; } } return false; } protected onUp(tree: _.ITree, event: IKeyboardEvent): boolean { const payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { tree.focusPrevious(1, payload); tree.reveal(tree.getFocus()).then(null, errors.onUnexpectedError); } return true; } protected onPageUp(tree: _.ITree, event: IKeyboardEvent): boolean { const payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { tree.focusPreviousPage(payload); tree.reveal(tree.getFocus()).then(null, errors.onUnexpectedError); } return true; } protected onDown(tree: _.ITree, event: IKeyboardEvent): boolean { const payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { tree.focusNext(1, payload); tree.reveal(tree.getFocus()).then(null, errors.onUnexpectedError); } return true; } protected onPageDown(tree: _.ITree, event: IKeyboardEvent): boolean { const payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { tree.focusNextPage(payload); tree.reveal(tree.getFocus()).then(null, errors.onUnexpectedError); } return true; } protected onHome(tree: _.ITree, event: IKeyboardEvent): boolean { const payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { tree.focusFirst(payload); tree.reveal(tree.getFocus()).then(null, errors.onUnexpectedError); } return true; } protected onEnd(tree: _.ITree, event: IKeyboardEvent): boolean { const payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { tree.focusLast(payload); tree.reveal(tree.getFocus()).then(null, errors.onUnexpectedError); } return true; } protected onLeft(tree: _.ITree, event: IKeyboardEvent): boolean { const payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { const focus = tree.getFocus(); tree.collapse(focus).then(didCollapse => { if (focus && !didCollapse) { tree.focusParent(payload); return tree.reveal(tree.getFocus()); } return undefined; }).then(null, errors.onUnexpectedError); } return true; } protected onRight(tree: _.ITree, event: IKeyboardEvent): boolean { const payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); } else { const focus = tree.getFocus(); tree.expand(focus).then(didExpand => { if (focus && !didExpand) { tree.focusFirstChild(payload); return tree.reveal(tree.getFocus()); } return undefined; }).then(null, errors.onUnexpectedError); } return true; } protected onEnter(tree: _.ITree, event: IKeyboardEvent): boolean { const payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { return false; } const focus = tree.getFocus(); if (focus) { tree.setSelection([focus], payload); } return true; } protected onSpace(tree: _.ITree, event: IKeyboardEvent): boolean { if (tree.getHighlight()) { return false; } const focus = tree.getFocus(); if (focus) { tree.toggleExpansion(focus); } return true; } protected onEscape(tree: _.ITree, event: IKeyboardEvent): boolean { const payload = { origin: 'keyboard', originalEvent: event }; if (tree.getHighlight()) { tree.clearHighlight(payload); return true; } if (tree.getSelection().length) { tree.clearSelection(payload); return true; } if (tree.getFocus()) { tree.clearFocus(payload); return true; } return false; } } export class DefaultDragAndDrop implements _.IDragAndDrop { public getDragURI(tree: _.ITree, element: any): string { return null; } public onDragStart(tree: _.ITree, data: _.IDragAndDropData, originalEvent: mouse.DragMouseEvent): void { return; } public onDragOver(tree: _.ITree, data: _.IDragAndDropData, targetElement: any, originalEvent: mouse.DragMouseEvent): _.IDragOverReaction { return null; } public drop(tree: _.ITree, data: _.IDragAndDropData, targetElement: any, originalEvent: mouse.DragMouseEvent): void { return; } } export class DefaultFilter implements _.IFilter { public isVisible(tree: _.ITree, element: any): boolean { return true; } } export class DefaultSorter implements _.ISorter { public compare(tree: _.ITree, element: any, otherElement: any): number { return 0; } } export class DefaultAccessibilityProvider implements _.IAccessibilityProvider { getAriaLabel(tree: _.ITree, element: any): string { return null; } } export class DefaultTreestyler implements _.ITreeStyler { constructor(private styleElement: HTMLStyleElement, private selectorSuffix?: string) { } style(styles: _.ITreeStyles): void { const suffix = this.selectorSuffix ? `.${this.selectorSuffix}` : ''; const content: string[] = []; if (styles.listFocusBackground) { content.push(`.monaco-tree${suffix}.focused .monaco-tree-rows > .monaco-tree-row.focused:not(.highlighted) { background-color: ${styles.listFocusBackground}; }`); } if (styles.listFocusForeground) { content.push(`.monaco-tree${suffix}.focused .monaco-tree-rows > .monaco-tree-row.focused:not(.highlighted) { color: ${styles.listFocusForeground}; }`); } if (styles.listActiveSelectionBackground) { content.push(`.monaco-tree${suffix}.focused .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { background-color: ${styles.listActiveSelectionBackground}; }`); } if (styles.listActiveSelectionForeground) { content.push(`.monaco-tree${suffix}.focused .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { color: ${styles.listActiveSelectionForeground}; }`); } if (styles.listFocusAndSelectionBackground) { content.push(` .monaco-tree-drag-image, .monaco-tree${suffix}.focused .monaco-tree-rows > .monaco-tree-row.focused.selected:not(.highlighted) { background-color: ${styles.listFocusAndSelectionBackground}; } `); } if (styles.listFocusAndSelectionForeground) { content.push(` .monaco-tree-drag-image, .monaco-tree${suffix}.focused .monaco-tree-rows > .monaco-tree-row.focused.selected:not(.highlighted) { color: ${styles.listFocusAndSelectionForeground}; } `); } if (styles.listInactiveSelectionBackground) { content.push(`.monaco-tree${suffix} .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { background-color: ${styles.listInactiveSelectionBackground}; }`); } if (styles.listInactiveSelectionForeground) { content.push(`.monaco-tree${suffix} .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { color: ${styles.listInactiveSelectionForeground}; }`); } if (styles.listHoverBackground) { content.push(`.monaco-tree${suffix} .monaco-tree-rows > .monaco-tree-row:hover:not(.highlighted):not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`); } if (styles.listHoverForeground) { content.push(`.monaco-tree${suffix} .monaco-tree-rows > .monaco-tree-row:hover:not(.highlighted):not(.selected):not(.focused) { color: ${styles.listHoverForeground}; }`); } if (styles.listDropBackground) { content.push(` .monaco-tree${suffix} .monaco-tree-wrapper.drop-target, .monaco-tree${suffix} .monaco-tree-rows > .monaco-tree-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; } `); } if (styles.listFocusOutline) { content.push(` .monaco-tree-drag-image { border: 1px solid ${styles.listFocusOutline}; background: #000; } .monaco-tree${suffix} .monaco-tree-rows > .monaco-tree-row { border: 1px solid transparent; } .monaco-tree${suffix}.focused .monaco-tree-rows > .monaco-tree-row.focused:not(.highlighted) { border: 1px dotted ${styles.listFocusOutline}; } .monaco-tree${suffix}.focused .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { border: 1px solid ${styles.listFocusOutline}; } .monaco-tree${suffix} .monaco-tree-rows > .monaco-tree-row.selected:not(.highlighted) { border: 1px solid ${styles.listFocusOutline}; } .monaco-tree${suffix} .monaco-tree-rows > .monaco-tree-row:hover:not(.highlighted):not(.selected):not(.focused) { border: 1px dashed ${styles.listFocusOutline}; } .monaco-tree${suffix} .monaco-tree-wrapper.drop-target, .monaco-tree${suffix} .monaco-tree-rows > .monaco-tree-row.drop-target { border: 1px dashed ${styles.listFocusOutline}; } `); } const newStyles = content.join('\n'); if (newStyles !== this.styleElement.innerHTML) { this.styleElement.innerHTML = newStyles; } } } export class CollapseAllAction extends Action { constructor(private viewer: _.ITree, enabled: boolean) { super('vs.tree.collapse', nls.localize('collapse', "Collapse"), 'monaco-tree-action collapse-all', enabled); } public run(context?: any): TPromise<any> { if (this.viewer.getHighlight()) { return TPromise.as(null); // Global action disabled if user is in edit mode from another action } this.viewer.collapseAll(); this.viewer.clearSelection(); this.viewer.clearFocus(); this.viewer.domFocus(); this.viewer.focusFirst(); return TPromise.as(null); } }
src/vs/base/parts/tree/browser/treeDefaults.ts
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017775512242224067, 0.00017315111472271383, 0.00016783314640633762, 0.00017339378246106207, 0.000002085672122120741 ]
{ "id": 3, "code_window": [ "\t\tratingCount: getStatistic(galleryExtension.statistics, 'ratingcount'),\n", "\t\tassets,\n", "\t\tproperties: {\n", "\t\t\tdependencies: getExtensions(version, PropertyType.Dependency),\n", "\t\t\textensionPack: getExtensions(version, PropertyType.ExtensionPack),\n", "\t\t\tengine: getEngine(version)\n", "\t\t},\n", "\t\t/* __GDPR__FRAGMENT__\n", "\t\t\t\"GalleryExtensionTelemetryData2\" : {\n", "\t\t\t\t\"index\" : { \"classification\": \"SystemMetaData\", \"purpose\": \"FeatureInsight\", \"isMeasurement\": true },\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tengine: getEngine(version),\n", "\t\t\tlocalizedLanguages: getLocalizedLanguages(version)\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "replace", "edit_start_line_idx": 312 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { CharCode } from 'vs/base/common/charCode'; /** * The empty string. */ export const empty = ''; export function isFalsyOrWhitespace(str: string): boolean { if (!str || typeof str !== 'string') { return true; } return str.trim().length === 0; } /** * @returns the provided number with the given number of preceding zeros. */ export function pad(n: number, l: number, char: string = '0'): string { let str = '' + n; let r = [str]; for (let i = str.length; i < l; i++) { r.push(char); } return r.reverse().join(''); } const _formatRegexp = /{(\d+)}/g; /** * Helper to produce a string with a variable number of arguments. Insert variable segments * into the string using the {n} notation where N is the index of the argument following the string. * @param value string to which formatting is applied * @param args replacements for {n}-entries */ export function format(value: string, ...args: any[]): string { if (args.length === 0) { return value; } return value.replace(_formatRegexp, function (match, group) { let idx = parseInt(group, 10); return isNaN(idx) || idx < 0 || idx >= args.length ? match : args[idx]; }); } /** * Converts HTML characters inside the string to use entities instead. Makes the string safe from * being used e.g. in HTMLElement.innerHTML. */ export function escape(html: string): string { return html.replace(/[<|>|&]/g, function (match) { switch (match) { case '<': return '&lt;'; case '>': return '&gt;'; case '&': return '&amp;'; default: return match; } }); } /** * Escapes regular expression characters in a given string */ export function escapeRegExpCharacters(value: string): string { return value.replace(/[\-\\\{\}\*\+\?\|\^\$\.\[\]\(\)\#]/g, '\\$&'); } /** * Removes all occurrences of needle from the beginning and end of haystack. * @param haystack string to trim * @param needle the thing to trim (default is a blank) */ export function trim(haystack: string, needle: string = ' '): string { let trimmed = ltrim(haystack, needle); return rtrim(trimmed, needle); } /** * Removes all occurrences of needle from the beginning of haystack. * @param haystack string to trim * @param needle the thing to trim */ export function ltrim(haystack?: string, needle?: string): string { if (!haystack || !needle) { return haystack; } let needleLen = needle.length; if (needleLen === 0 || haystack.length === 0) { return haystack; } let offset = 0, idx = -1; while ((idx = haystack.indexOf(needle, offset)) === offset) { offset = offset + needleLen; } return haystack.substring(offset); } /** * Removes all occurrences of needle from the end of haystack. * @param haystack string to trim * @param needle the thing to trim */ export function rtrim(haystack?: string, needle?: string): string { if (!haystack || !needle) { return haystack; } let needleLen = needle.length, haystackLen = haystack.length; if (needleLen === 0 || haystackLen === 0) { return haystack; } let offset = haystackLen, idx = -1; while (true) { idx = haystack.lastIndexOf(needle, offset - 1); if (idx === -1 || idx + needleLen !== offset) { break; } if (idx === 0) { return ''; } offset = idx; } return haystack.substring(0, offset); } export function convertSimple2RegExpPattern(pattern: string): string { return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*'); } export function stripWildcards(pattern: string): string { return pattern.replace(/\*/g, ''); } /** * Determines if haystack starts with needle. */ export function startsWith(haystack: string, needle: string): boolean { if (haystack.length < needle.length) { return false; } if (haystack === needle) { return true; } for (let i = 0; i < needle.length; i++) { if (haystack[i] !== needle[i]) { return false; } } return true; } /** * Determines if haystack ends with needle. */ export function endsWith(haystack: string, needle: string): boolean { let diff = haystack.length - needle.length; if (diff > 0) { return haystack.indexOf(needle, diff) === diff; } else if (diff === 0) { return haystack === needle; } else { return false; } } export interface RegExpOptions { matchCase?: boolean; wholeWord?: boolean; multiline?: boolean; global?: boolean; } export function createRegExp(searchString: string, isRegex: boolean, options: RegExpOptions = {}): RegExp { if (!searchString) { throw new Error('Cannot create regex from empty string'); } if (!isRegex) { searchString = escapeRegExpCharacters(searchString); } if (options.wholeWord) { if (!/\B/.test(searchString.charAt(0))) { searchString = '\\b' + searchString; } if (!/\B/.test(searchString.charAt(searchString.length - 1))) { searchString = searchString + '\\b'; } } let modifiers = ''; if (options.global) { modifiers += 'g'; } if (!options.matchCase) { modifiers += 'i'; } if (options.multiline) { modifiers += 'm'; } return new RegExp(searchString, modifiers); } export function regExpLeadsToEndlessLoop(regexp: RegExp): boolean { // Exit early if it's one of these special cases which are meant to match // against an empty string if (regexp.source === '^' || regexp.source === '^$' || regexp.source === '$' || regexp.source === '^\\s*$') { return false; } // We check against an empty string. If the regular expression doesn't advance // (e.g. ends in an endless loop) it will match an empty string. let match = regexp.exec(''); return (match && <any>regexp.lastIndex === 0); } export function regExpContainsBackreference(regexpValue: string): boolean { return !!regexpValue.match(/([^\\]|^)(\\\\)*\\\d+/); } /** * Returns first index of the string that is not whitespace. * If string is empty or contains only whitespaces, returns -1 */ export function firstNonWhitespaceIndex(str: string): number { for (let i = 0, len = str.length; i < len; i++) { let chCode = str.charCodeAt(i); if (chCode !== CharCode.Space && chCode !== CharCode.Tab) { return i; } } return -1; } /** * Returns the leading whitespace of the string. * If the string contains only whitespaces, returns entire string */ export function getLeadingWhitespace(str: string, start: number = 0, end: number = str.length): string { for (let i = start; i < end; i++) { let chCode = str.charCodeAt(i); if (chCode !== CharCode.Space && chCode !== CharCode.Tab) { return str.substring(start, i); } } return str.substring(start, end); } /** * Returns last index of the string that is not whitespace. * If string is empty or contains only whitespaces, returns -1 */ export function lastNonWhitespaceIndex(str: string, startIndex: number = str.length - 1): number { for (let i = startIndex; i >= 0; i--) { let chCode = str.charCodeAt(i); if (chCode !== CharCode.Space && chCode !== CharCode.Tab) { return i; } } return -1; } export function compare(a: string, b: string): number { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; } } export function compareIgnoreCase(a: string, b: string): number { const len = Math.min(a.length, b.length); for (let i = 0; i < len; i++) { let codeA = a.charCodeAt(i); let codeB = b.charCodeAt(i); if (codeA === codeB) { // equal continue; } if (isUpperAsciiLetter(codeA)) { codeA += 32; } if (isUpperAsciiLetter(codeB)) { codeB += 32; } const diff = codeA - codeB; if (diff === 0) { // equal -> ignoreCase continue; } else if (isLowerAsciiLetter(codeA) && isLowerAsciiLetter(codeB)) { // return diff; } else { return compare(a.toLowerCase(), b.toLowerCase()); } } if (a.length < b.length) { return -1; } else if (a.length > b.length) { return 1; } else { return 0; } } export function isLowerAsciiLetter(code: number): boolean { return code >= CharCode.a && code <= CharCode.z; } export function isUpperAsciiLetter(code: number): boolean { return code >= CharCode.A && code <= CharCode.Z; } function isAsciiLetter(code: number): boolean { return isLowerAsciiLetter(code) || isUpperAsciiLetter(code); } export function equalsIgnoreCase(a: string, b: string): boolean { const len1 = a ? a.length : 0; const len2 = b ? b.length : 0; if (len1 !== len2) { return false; } return doEqualsIgnoreCase(a, b); } function doEqualsIgnoreCase(a: string, b: string, stopAt = a.length): boolean { if (typeof a !== 'string' || typeof b !== 'string') { return false; } for (let i = 0; i < stopAt; i++) { const codeA = a.charCodeAt(i); const codeB = b.charCodeAt(i); if (codeA === codeB) { continue; } // a-z A-Z if (isAsciiLetter(codeA) && isAsciiLetter(codeB)) { let diff = Math.abs(codeA - codeB); if (diff !== 0 && diff !== 32) { return false; } } // Any other charcode else { if (String.fromCharCode(codeA).toLowerCase() !== String.fromCharCode(codeB).toLowerCase()) { return false; } } } return true; } export function startsWithIgnoreCase(str: string, candidate: string): boolean { const candidateLength = candidate.length; if (candidate.length > str.length) { return false; } return doEqualsIgnoreCase(str, candidate, candidateLength); } /** * @returns the length of the common prefix of the two strings. */ export function commonPrefixLength(a: string, b: string): number { let i: number, len = Math.min(a.length, b.length); for (i = 0; i < len; i++) { if (a.charCodeAt(i) !== b.charCodeAt(i)) { return i; } } return len; } /** * @returns the length of the common suffix of the two strings. */ export function commonSuffixLength(a: string, b: string): number { let i: number, len = Math.min(a.length, b.length); let aLastIndex = a.length - 1; let bLastIndex = b.length - 1; for (i = 0; i < len; i++) { if (a.charCodeAt(aLastIndex - i) !== b.charCodeAt(bLastIndex - i)) { return i; } } return len; } function substrEquals(a: string, aStart: number, aEnd: number, b: string, bStart: number, bEnd: number): boolean { while (aStart < aEnd && bStart < bEnd) { if (a[aStart] !== b[bStart]) { return false; } aStart += 1; bStart += 1; } return true; } /** * Return the overlap between the suffix of `a` and the prefix of `b`. * For instance `overlap("foobar", "arr, I'm a pirate") === 2`. */ export function overlap(a: string, b: string): number { let aEnd = a.length; let bEnd = b.length; let aStart = aEnd - bEnd; if (aStart === 0) { return a === b ? aEnd : 0; } else if (aStart < 0) { bEnd += aStart; aStart = 0; } while (aStart < aEnd && bEnd > 0) { if (substrEquals(a, aStart, aEnd, b, 0, bEnd)) { return bEnd; } bEnd -= 1; aStart += 1; } return 0; } // --- unicode // http://en.wikipedia.org/wiki/Surrogate_pair // Returns the code point starting at a specified index in a string // Code points U+0000 to U+D7FF and U+E000 to U+FFFF are represented on a single character // Code points U+10000 to U+10FFFF are represented on two consecutive characters //export function getUnicodePoint(str:string, index:number, len:number):number { // let chrCode = str.charCodeAt(index); // if (0xD800 <= chrCode && chrCode <= 0xDBFF && index + 1 < len) { // let nextChrCode = str.charCodeAt(index + 1); // if (0xDC00 <= nextChrCode && nextChrCode <= 0xDFFF) { // return (chrCode - 0xD800) << 10 + (nextChrCode - 0xDC00) + 0x10000; // } // } // return chrCode; //} export function isHighSurrogate(charCode: number): boolean { return (0xD800 <= charCode && charCode <= 0xDBFF); } export function isLowSurrogate(charCode: number): boolean { return (0xDC00 <= charCode && charCode <= 0xDFFF); } /** * Generated using https://github.com/alexandrudima/unicode-utils/blob/master/generate-rtl-test.js */ const CONTAINS_RTL = /(?:[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u0710\u0712-\u072F\u074D-\u07A5\u07B1-\u07EA\u07F4\u07F5\u07FA-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E-\u08BD\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFD3D\uFD50-\uFDFC\uFE70-\uFEFC]|\uD802[\uDC00-\uDD1B\uDD20-\uDE00\uDE10-\uDE33\uDE40-\uDEE4\uDEEB-\uDF35\uDF40-\uDFFF]|\uD803[\uDC00-\uDCFF]|\uD83A[\uDC00-\uDCCF\uDD00-\uDD43\uDD50-\uDFFF]|\uD83B[\uDC00-\uDEBB])/; /** * Returns true if `str` contains any Unicode character that is classified as "R" or "AL". */ export function containsRTL(str: string): boolean { return CONTAINS_RTL.test(str); } /** * Generated using https://github.com/alexandrudima/unicode-utils/blob/master/generate-emoji-test.js */ const CONTAINS_EMOJI = /(?:[\u231A\u231B\u23F0\u23F3\u2600-\u27BF\u2B50\u2B55]|\uD83C[\uDDE6-\uDDFF\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F\uDE80-\uDEF8]|\uD83E[\uDD00-\uDDE6])/; export function containsEmoji(str: string): boolean { return CONTAINS_EMOJI.test(str); } const IS_BASIC_ASCII = /^[\t\n\r\x20-\x7E]*$/; /** * Returns true if `str` contains only basic ASCII characters in the range 32 - 126 (including 32 and 126) or \n, \r, \t */ export function isBasicASCII(str: string): boolean { return IS_BASIC_ASCII.test(str); } export function containsFullWidthCharacter(str: string): boolean { for (let i = 0, len = str.length; i < len; i++) { if (isFullWidthCharacter(str.charCodeAt(i))) { return true; } } return false; } export function isFullWidthCharacter(charCode: number): boolean { // Do a cheap trick to better support wrapping of wide characters, treat them as 2 columns // http://jrgraphix.net/research/unicode_blocks.php // 2E80 — 2EFF CJK Radicals Supplement // 2F00 — 2FDF Kangxi Radicals // 2FF0 — 2FFF Ideographic Description Characters // 3000 — 303F CJK Symbols and Punctuation // 3040 — 309F Hiragana // 30A0 — 30FF Katakana // 3100 — 312F Bopomofo // 3130 — 318F Hangul Compatibility Jamo // 3190 — 319F Kanbun // 31A0 — 31BF Bopomofo Extended // 31F0 — 31FF Katakana Phonetic Extensions // 3200 — 32FF Enclosed CJK Letters and Months // 3300 — 33FF CJK Compatibility // 3400 — 4DBF CJK Unified Ideographs Extension A // 4DC0 — 4DFF Yijing Hexagram Symbols // 4E00 — 9FFF CJK Unified Ideographs // A000 — A48F Yi Syllables // A490 — A4CF Yi Radicals // AC00 — D7AF Hangul Syllables // [IGNORE] D800 — DB7F High Surrogates // [IGNORE] DB80 — DBFF High Private Use Surrogates // [IGNORE] DC00 — DFFF Low Surrogates // [IGNORE] E000 — F8FF Private Use Area // F900 — FAFF CJK Compatibility Ideographs // [IGNORE] FB00 — FB4F Alphabetic Presentation Forms // [IGNORE] FB50 — FDFF Arabic Presentation Forms-A // [IGNORE] FE00 — FE0F Variation Selectors // [IGNORE] FE20 — FE2F Combining Half Marks // [IGNORE] FE30 — FE4F CJK Compatibility Forms // [IGNORE] FE50 — FE6F Small Form Variants // [IGNORE] FE70 — FEFF Arabic Presentation Forms-B // FF00 — FFEF Halfwidth and Fullwidth Forms // [https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms] // of which FF01 - FF5E fullwidth ASCII of 21 to 7E // [IGNORE] and FF65 - FFDC halfwidth of Katakana and Hangul // [IGNORE] FFF0 — FFFF Specials charCode = +charCode; // @perf return ( (charCode >= 0x2E80 && charCode <= 0xD7AF) || (charCode >= 0xF900 && charCode <= 0xFAFF) || (charCode >= 0xFF01 && charCode <= 0xFF5E) ); } /** * Given a string and a max length returns a shorted version. Shorting * happens at favorable positions - such as whitespace or punctuation characters. */ export function lcut(text: string, n: number) { if (text.length < n) { return text; } const re = /\b/g; let i = 0; while (re.test(text)) { if (text.length - re.lastIndex < n) { break; } i = re.lastIndex; re.lastIndex += 1; } return text.substring(i).replace(/^\s/, empty); } // Escape codes // http://en.wikipedia.org/wiki/ANSI_escape_code const EL = /\x1B\x5B[12]?K/g; // Erase in line const COLOR_START = /\x1b\[\d+m/g; // Color const COLOR_END = /\x1b\[0?m/g; // Color export function removeAnsiEscapeCodes(str: string): string { if (str) { str = str.replace(EL, ''); str = str.replace(COLOR_START, ''); str = str.replace(COLOR_END, ''); } return str; } // -- UTF-8 BOM export const UTF8_BOM_CHARACTER = String.fromCharCode(CharCode.UTF8_BOM); export function startsWithUTF8BOM(str: string): boolean { return (str && str.length > 0 && str.charCodeAt(0) === CharCode.UTF8_BOM); } export function stripUTF8BOM(str: string): string { return startsWithUTF8BOM(str) ? str.substr(1) : str; } export function safeBtoa(str: string): string { return btoa(encodeURIComponent(str)); // we use encodeURIComponent because btoa fails for non Latin 1 values } export function repeat(s: string, count: number): string { let result = ''; for (let i = 0; i < count; i++) { result += s; } return result; } /** * Checks if the characters of the provided query string are included in the * target string. The characters do not have to be contiguous within the string. */ export function fuzzyContains(target: string, query: string): boolean { if (!target || !query) { return false; // return early if target or query are undefined } if (target.length < query.length) { return false; // impossible for query to be contained in target } const queryLen = query.length; const targetLower = target.toLowerCase(); let index = 0; let lastIndexOf = -1; while (index < queryLen) { let indexOf = targetLower.indexOf(query[index], lastIndexOf + 1); if (indexOf < 0) { return false; } lastIndexOf = indexOf; index++; } return true; } export function containsUppercaseCharacter(target: string, ignoreEscapedChars = false): boolean { if (!target) { return false; } if (ignoreEscapedChars) { target = target.replace(/\\./g, ''); } return target.toLowerCase() !== target; } export function uppercaseFirstLetter(str: string): string { return str.charAt(0).toUpperCase() + str.slice(1); }
src/vs/base/common/strings.ts
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00018342077964916825, 0.0001712713565211743, 0.00016265960584860295, 0.0001721309672575444, 0.000003603544428187888 ]
{ "id": 3, "code_window": [ "\t\tratingCount: getStatistic(galleryExtension.statistics, 'ratingcount'),\n", "\t\tassets,\n", "\t\tproperties: {\n", "\t\t\tdependencies: getExtensions(version, PropertyType.Dependency),\n", "\t\t\textensionPack: getExtensions(version, PropertyType.ExtensionPack),\n", "\t\t\tengine: getEngine(version)\n", "\t\t},\n", "\t\t/* __GDPR__FRAGMENT__\n", "\t\t\t\"GalleryExtensionTelemetryData2\" : {\n", "\t\t\t\t\"index\" : { \"classification\": \"SystemMetaData\", \"purpose\": \"FeatureInsight\", \"isMeasurement\": true },\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tengine: getEngine(version),\n", "\t\t\tlocalizedLanguages: getLocalizedLanguages(version)\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "replace", "edit_start_line_idx": 312 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { Registry } from 'vs/platform/registry/common/platform'; import { Extensions as PanelExtensions, PanelDescriptor, PanelRegistry } from 'vs/workbench/browser/panel'; import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { COMMENTS_PANEL_ID, COMMENTS_PANEL_TITLE, CommentsPanel } from './commentsPanel'; import 'vs/workbench/parts/comments/electron-browser/commentsEditorContribution'; import { ICommentService, CommentService } from 'vs/workbench/parts/comments/electron-browser/commentService'; export class CommentPanelVisibilityUpdater implements IWorkbenchContribution { constructor( @IPanelService panelService: IPanelService ) { // commentsProviderRegistry.onChange const updateCommentPanelVisibility = () => { panelService.setPanelEnablement(COMMENTS_PANEL_ID, false); }; updateCommentPanelVisibility(); } } Registry.as<PanelRegistry>(PanelExtensions.Panels).registerPanel(new PanelDescriptor( CommentsPanel, COMMENTS_PANEL_ID, COMMENTS_PANEL_TITLE, 'commentsPanel', 10 )); // Register view location updater Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(CommentPanelVisibilityUpdater, LifecyclePhase.Restoring); registerSingleton(ICommentService, CommentService);
src/vs/workbench/parts/comments/electron-browser/comments.contribution.ts
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017505601863376796, 0.000172507599927485, 0.00016757378762122244, 0.0001732694945530966, 0.0000026854368115891702 ]
{ "id": 4, "code_window": [ "\t\t\t\t\t.then(rawVersion => {\n", "\t\t\t\t\t\tif (rawVersion) {\n", "\t\t\t\t\t\t\textension.properties.dependencies = getExtensions(rawVersion, PropertyType.Dependency);\n", "\t\t\t\t\t\t\textension.properties.engine = getEngine(rawVersion);\n", "\t\t\t\t\t\t\textension.assets.download = getVersionAsset(rawVersion, AssetType.VSIX);\n", "\t\t\t\t\t\t\textension.version = rawVersion.version;\n", "\t\t\t\t\t\t\treturn extension;\n", "\t\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\textension.properties.localizedLanguages = getLocalizedLanguages(rawVersion);\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "add", "edit_start_line_idx": 596 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { tmpdir } from 'os'; import * as path from 'path'; import { TPromise } from 'vs/base/common/winjs.base'; import { distinct } from 'vs/base/common/arrays'; import { getErrorMessage, isPromiseCanceledError, canceled } from 'vs/base/common/errors'; import { StatisticType, IGalleryExtension, IExtensionGalleryService, IGalleryExtensionAsset, IQueryOptions, SortBy, SortOrder, IExtensionManifest, IExtensionIdentifier, IReportedExtension, InstallOperation, ITranslation } from 'vs/platform/extensionManagement/common/extensionManagement'; import { getGalleryExtensionId, getGalleryExtensionTelemetryData, adoptToGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { assign, getOrDefault } from 'vs/base/common/objects'; import { IRequestService } from 'vs/platform/request/node/request'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IPager } from 'vs/base/common/paging'; import { IRequestOptions, IRequestContext, download, asJson, asText } from 'vs/base/node/request'; import pkg from 'vs/platform/node/package'; import product from 'vs/platform/node/product'; import { isEngineValid } from 'vs/platform/extensions/node/extensionValidator'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { readFile } from 'vs/base/node/pfs'; import { writeFileAndFlushSync } from 'vs/base/node/extfs'; import { generateUuid, isUUID } from 'vs/base/common/uuid'; import { values } from 'vs/base/common/map'; import { CancellationToken } from 'vs/base/common/cancellation'; interface IRawGalleryExtensionFile { assetType: string; source: string; } interface IRawGalleryExtensionProperty { key: string; value: string; } interface IRawGalleryExtensionVersion { version: string; lastUpdated: string; assetUri: string; fallbackAssetUri: string; files: IRawGalleryExtensionFile[]; properties?: IRawGalleryExtensionProperty[]; } interface IRawGalleryExtensionStatistics { statisticName: string; value: number; } interface IRawGalleryExtension { extensionId: string; extensionName: string; displayName: string; shortDescription: string; publisher: { displayName: string, publisherId: string, publisherName: string; }; versions: IRawGalleryExtensionVersion[]; statistics: IRawGalleryExtensionStatistics[]; flags: string; } interface IRawGalleryQueryResult { results: { extensions: IRawGalleryExtension[]; resultMetadata: { metadataType: string; metadataItems: { name: string; count: number; }[]; }[] }[]; } enum Flags { None = 0x0, IncludeVersions = 0x1, IncludeFiles = 0x2, IncludeCategoryAndTags = 0x4, IncludeSharedAccounts = 0x8, IncludeVersionProperties = 0x10, ExcludeNonValidated = 0x20, IncludeInstallationTargets = 0x40, IncludeAssetUri = 0x80, IncludeStatistics = 0x100, IncludeLatestVersionOnly = 0x200, Unpublished = 0x1000 } function flagsToString(...flags: Flags[]): string { return String(flags.reduce((r, f) => r | f, 0)); } enum FilterType { Tag = 1, ExtensionId = 4, Category = 5, ExtensionName = 7, Target = 8, Featured = 9, SearchText = 10, ExcludeWithFlags = 12 } const AssetType = { Icon: 'Microsoft.VisualStudio.Services.Icons.Default', Details: 'Microsoft.VisualStudio.Services.Content.Details', Changelog: 'Microsoft.VisualStudio.Services.Content.Changelog', Manifest: 'Microsoft.VisualStudio.Code.Manifest', VSIX: 'Microsoft.VisualStudio.Services.VSIXPackage', License: 'Microsoft.VisualStudio.Services.Content.License', Repository: 'Microsoft.VisualStudio.Services.Links.Source' }; const PropertyType = { Dependency: 'Microsoft.VisualStudio.Code.ExtensionDependencies', ExtensionPack: 'Microsoft.VisualStudio.Code.ExtensionPack', Engine: 'Microsoft.VisualStudio.Code.Engine' }; interface ICriterium { filterType: FilterType; value?: string; } const DefaultPageSize = 10; interface IQueryState { pageNumber: number; pageSize: number; sortBy: SortBy; sortOrder: SortOrder; flags: Flags; criteria: ICriterium[]; assetTypes: string[]; } const DefaultQueryState: IQueryState = { pageNumber: 1, pageSize: DefaultPageSize, sortBy: SortBy.NoneOrRelevance, sortOrder: SortOrder.Default, flags: Flags.None, criteria: [], assetTypes: [] }; class Query { constructor(private state = DefaultQueryState) { } get pageNumber(): number { return this.state.pageNumber; } get pageSize(): number { return this.state.pageSize; } get sortBy(): number { return this.state.sortBy; } get sortOrder(): number { return this.state.sortOrder; } get flags(): number { return this.state.flags; } withPage(pageNumber: number, pageSize: number = this.state.pageSize): Query { return new Query(assign({}, this.state, { pageNumber, pageSize })); } withFilter(filterType: FilterType, ...values: string[]): Query { const criteria = [ ...this.state.criteria, ...values.map(value => ({ filterType, value })) ]; return new Query(assign({}, this.state, { criteria })); } withSortBy(sortBy: SortBy): Query { return new Query(assign({}, this.state, { sortBy })); } withSortOrder(sortOrder: SortOrder): Query { return new Query(assign({}, this.state, { sortOrder })); } withFlags(...flags: Flags[]): Query { return new Query(assign({}, this.state, { flags: flags.reduce((r, f) => r | f, 0) })); } withAssetTypes(...assetTypes: string[]): Query { return new Query(assign({}, this.state, { assetTypes })); } get raw(): any { const { criteria, pageNumber, pageSize, sortBy, sortOrder, flags, assetTypes } = this.state; const filters = [{ criteria, pageNumber, pageSize, sortBy, sortOrder }]; return { filters, assetTypes, flags }; } get searchText(): string { const criterium = this.state.criteria.filter(criterium => criterium.filterType === FilterType.SearchText)[0]; return criterium ? criterium.value : ''; } } function getStatistic(statistics: IRawGalleryExtensionStatistics[], name: string): number { const result = (statistics || []).filter(s => s.statisticName === name)[0]; return result ? result.value : 0; } function getCoreTranslationAssets(version: IRawGalleryExtensionVersion): { [languageId: string]: IGalleryExtensionAsset } { const coreTranslationAssetPrefix = 'Microsoft.VisualStudio.Code.Translation.'; const result = version.files.filter(f => f.assetType.indexOf(coreTranslationAssetPrefix) === 0); return result.reduce((result, file) => { result[file.assetType.substring(coreTranslationAssetPrefix.length)] = getVersionAsset(version, file.assetType); return result; }, {}); } function getVersionAsset(version: IRawGalleryExtensionVersion, type: string): IGalleryExtensionAsset { const result = version.files.filter(f => f.assetType === type)[0]; if (type === AssetType.Repository) { if (version.properties) { const results = version.properties.filter(p => p.key === type); const gitRegExp = new RegExp('((git|ssh|http(s)?)|(git@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(\.git)(/)?'); const uri = results.filter(r => gitRegExp.test(r.value))[0]; if (!uri) { return { uri: null, fallbackUri: null }; } return { uri: uri.value, fallbackUri: uri.value, }; } } if (!result) { if (type === AssetType.Icon) { const uri = require.toUrl('./media/defaultIcon.png'); return { uri, fallbackUri: uri }; } if (type === AssetType.Repository) { return { uri: null, fallbackUri: null }; } return null; } if (type === AssetType.VSIX) { return { uri: `${version.fallbackAssetUri}/${type}?redirect=true`, fallbackUri: `${version.fallbackAssetUri}/${type}` }; } return { uri: `${version.assetUri}/${type}`, fallbackUri: `${version.fallbackAssetUri}/${type}` }; } function getExtensions(version: IRawGalleryExtensionVersion, property: string): string[] { const values = version.properties ? version.properties.filter(p => p.key === property) : []; const value = values.length > 0 && values[0].value; return value ? value.split(',').map(v => adoptToGalleryExtensionId(v)) : []; } function getEngine(version: IRawGalleryExtensionVersion): string { const values = version.properties ? version.properties.filter(p => p.key === PropertyType.Engine) : []; return (values.length > 0 && values[0].value) || ''; } function getIsPreview(flags: string): boolean { return flags.indexOf('preview') !== -1; } function toExtension(galleryExtension: IRawGalleryExtension, version: IRawGalleryExtensionVersion, index: number, query: Query, querySource?: string): IGalleryExtension { const assets = { manifest: getVersionAsset(version, AssetType.Manifest), readme: getVersionAsset(version, AssetType.Details), changelog: getVersionAsset(version, AssetType.Changelog), download: getVersionAsset(version, AssetType.VSIX), icon: getVersionAsset(version, AssetType.Icon), license: getVersionAsset(version, AssetType.License), repository: getVersionAsset(version, AssetType.Repository), coreTranslations: getCoreTranslationAssets(version) }; return { identifier: { id: getGalleryExtensionId(galleryExtension.publisher.publisherName, galleryExtension.extensionName), uuid: galleryExtension.extensionId }, name: galleryExtension.extensionName, version: version.version, date: version.lastUpdated, displayName: galleryExtension.displayName, publisherId: galleryExtension.publisher.publisherId, publisher: galleryExtension.publisher.publisherName, publisherDisplayName: galleryExtension.publisher.displayName, description: galleryExtension.shortDescription || '', installCount: getStatistic(galleryExtension.statistics, 'install') + getStatistic(galleryExtension.statistics, 'updateCount'), rating: getStatistic(galleryExtension.statistics, 'averagerating'), ratingCount: getStatistic(galleryExtension.statistics, 'ratingcount'), assets, properties: { dependencies: getExtensions(version, PropertyType.Dependency), extensionPack: getExtensions(version, PropertyType.ExtensionPack), engine: getEngine(version) }, /* __GDPR__FRAGMENT__ "GalleryExtensionTelemetryData2" : { "index" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "searchText": { "classification": "CustomerContent", "purpose": "FeatureInsight" }, "querySource": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ telemetryData: { index: ((query.pageNumber - 1) * query.pageSize) + index, searchText: query.searchText, querySource }, preview: getIsPreview(galleryExtension.flags) }; } interface IRawExtensionsReport { malicious: string[]; slow: string[]; } export class ExtensionGalleryService implements IExtensionGalleryService { _serviceBrand: any; private extensionsGalleryUrl: string; private extensionsControlUrl: string; private readonly commonHeadersPromise: TPromise<{ [key: string]: string; }>; constructor( @IRequestService private requestService: IRequestService, @IEnvironmentService private environmentService: IEnvironmentService, @ITelemetryService private telemetryService: ITelemetryService ) { const config = product.extensionsGallery; this.extensionsGalleryUrl = config && config.serviceUrl; this.extensionsControlUrl = config && config.controlUrl; this.commonHeadersPromise = resolveMarketplaceHeaders(this.environmentService); } private api(path = ''): string { return `${this.extensionsGalleryUrl}${path}`; } isEnabled(): boolean { return !!this.extensionsGalleryUrl; } getExtension({ id, uuid }: IExtensionIdentifier, version?: string): TPromise<IGalleryExtension> { let query = new Query() .withFlags(Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, 1) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)); if (uuid) { query = query.withFilter(FilterType.ExtensionId, uuid); } else { query = query.withFilter(FilterType.ExtensionName, id); } return this.queryGallery(query, CancellationToken.None).then(({ galleryExtensions }) => { if (galleryExtensions.length) { const galleryExtension = galleryExtensions[0]; const versionAsset = version ? galleryExtension.versions.filter(v => v.version === version)[0] : galleryExtension.versions[0]; if (versionAsset) { return toExtension(galleryExtension, versionAsset, 0, query); } } return null; }); } query(options: IQueryOptions = {}): TPromise<IPager<IGalleryExtension>> { if (!this.isEnabled()) { return TPromise.wrapError<IPager<IGalleryExtension>>(new Error('No extension gallery service configured.')); } const type = options.names ? 'ids' : (options.text ? 'text' : 'all'); let text = options.text || ''; const pageSize = getOrDefault(options, o => o.pageSize, 50); /* __GDPR__ "galleryService:query" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "text": { "classification": "CustomerContent", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:query', { type, text }); let query = new Query() .withFlags(Flags.IncludeLatestVersionOnly, Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, pageSize) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)); if (text) { // Use category filter instead of "category:themes" text = text.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedCategory, category) => { query = query.withFilter(FilterType.Category, category || quotedCategory); return ''; }); // Use tag filter instead of "tag:debuggers" text = text.replace(/\btag:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedTag, tag) => { query = query.withFilter(FilterType.Tag, tag || quotedTag); return ''; }); text = text.trim(); if (text) { text = text.length < 200 ? text : text.substring(0, 200); query = query.withFilter(FilterType.SearchText, text); } query = query.withSortBy(SortBy.NoneOrRelevance); } else if (options.ids) { query = query.withFilter(FilterType.ExtensionId, ...options.ids); } else if (options.names) { query = query.withFilter(FilterType.ExtensionName, ...options.names); } else { query = query.withSortBy(SortBy.InstallCount); } if (typeof options.sortBy === 'number') { query = query.withSortBy(options.sortBy); } if (typeof options.sortOrder === 'number') { query = query.withSortOrder(options.sortOrder); } return this.queryGallery(query, CancellationToken.None).then(({ galleryExtensions, total }) => { const extensions = galleryExtensions.map((e, index) => toExtension(e, e.versions[0], index, query, options.source)); const pageSize = query.pageSize; const getPage = (pageIndex: number, ct: CancellationToken) => { if (ct.isCancellationRequested) { return TPromise.wrapError(canceled()); } const nextPageQuery = query.withPage(pageIndex + 1); return this.queryGallery(nextPageQuery, ct) .then(({ galleryExtensions }) => galleryExtensions.map((e, index) => toExtension(e, e.versions[0], index, nextPageQuery, options.source))); }; return { firstPage: extensions, total, pageSize, getPage } as IPager<IGalleryExtension>; }); } private queryGallery(query: Query, token: CancellationToken): TPromise<{ galleryExtensions: IRawGalleryExtension[], total: number; }> { return this.commonHeadersPromise.then(commonHeaders => { const data = JSON.stringify(query.raw); const headers = assign({}, commonHeaders, { 'Content-Type': 'application/json', 'Accept': 'application/json;api-version=3.0-preview.1', 'Accept-Encoding': 'gzip', 'Content-Length': data.length }); return this.requestService.request({ type: 'POST', url: this.api('/extensionquery'), data, headers }, token).then(context => { if (context.res.statusCode >= 400 && context.res.statusCode < 500) { return { galleryExtensions: [], total: 0 }; } return asJson<IRawGalleryQueryResult>(context).then(result => { const r = result.results[0]; const galleryExtensions = r.extensions; const resultCount = r.resultMetadata && r.resultMetadata.filter(m => m.metadataType === 'ResultCount')[0]; const total = resultCount && resultCount.metadataItems.filter(i => i.name === 'TotalCount')[0].count || 0; return { galleryExtensions, total }; }); }); }); } reportStatistic(publisher: string, name: string, version: string, type: StatisticType): TPromise<void> { if (!this.isEnabled()) { return TPromise.as(null); } return this.commonHeadersPromise.then(commonHeaders => { const headers = { ...commonHeaders, Accept: '*/*;api-version=4.0-preview.1' }; return this.requestService.request({ type: 'POST', url: this.api(`/publishers/${publisher}/extensions/${name}/${version}/stats?statType=${type}`), headers }, CancellationToken.None).then(null, () => null); }); } download(extension: IGalleryExtension, operation: InstallOperation): TPromise<string> { const zipPath = path.join(tmpdir(), generateUuid()); const data = getGalleryExtensionTelemetryData(extension); const startTime = new Date().getTime(); /* __GDPR__ "galleryService:downloadVSIX" : { "duration": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true }, "${include}": [ "${GalleryExtensionTelemetryData}" ] } */ const log = (duration: number) => this.telemetryService.publicLog('galleryService:downloadVSIX', assign(data, { duration })); const operationParam = operation === InstallOperation.Install ? 'install' : operation === InstallOperation.Update ? 'update' : ''; const downloadAsset = operationParam ? { uri: `${extension.assets.download.uri}&${operationParam}=true`, fallbackUri: `${extension.assets.download.fallbackUri}?${operationParam}=true` } : extension.assets.download; return this.getAsset(downloadAsset) .then(context => download(zipPath, context)) .then(() => log(new Date().getTime() - startTime)) .then(() => zipPath); } getReadme(extension: IGalleryExtension, token: CancellationToken): TPromise<string> { return this.getAsset(extension.assets.readme, {}, token) .then(asText); } getManifest(extension: IGalleryExtension, token: CancellationToken): TPromise<IExtensionManifest> { return this.getAsset(extension.assets.manifest, {}, token) .then(asText) .then(JSON.parse); } getCoreTranslation(extension: IGalleryExtension, languageId: string): TPromise<ITranslation> { const asset = extension.assets.coreTranslations[languageId.toUpperCase()]; if (asset) { return this.getAsset(asset) .then(asText) .then(JSON.parse); } return TPromise.as(null); } getChangelog(extension: IGalleryExtension, token: CancellationToken): TPromise<string> { return this.getAsset(extension.assets.changelog, {}, token) .then(asText); } loadAllDependencies(extensions: IExtensionIdentifier[], token: CancellationToken): TPromise<IGalleryExtension[]> { return this.getDependenciesReccursively(extensions.map(e => e.id), [], token); } loadCompatibleVersion(extension: IGalleryExtension): TPromise<IGalleryExtension> { if (extension.properties.engine && isEngineValid(extension.properties.engine)) { return TPromise.wrap(extension); } const query = new Query() .withFlags(Flags.IncludeVersions, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, 1) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)) .withAssetTypes(AssetType.Manifest, AssetType.VSIX) .withFilter(FilterType.ExtensionId, extension.identifier.uuid); return this.queryGallery(query, CancellationToken.None) .then(({ galleryExtensions }) => { const [rawExtension] = galleryExtensions; if (!rawExtension) { return null; } return this.getLastValidExtensionVersion(rawExtension, rawExtension.versions) .then(rawVersion => { if (rawVersion) { extension.properties.dependencies = getExtensions(rawVersion, PropertyType.Dependency); extension.properties.engine = getEngine(rawVersion); extension.assets.download = getVersionAsset(rawVersion, AssetType.VSIX); extension.version = rawVersion.version; return extension; } return null; }); }); } private loadDependencies(extensionNames: string[], token: CancellationToken): TPromise<IGalleryExtension[]> { if (!extensionNames || extensionNames.length === 0) { return TPromise.as([]); } let query = new Query() .withFlags(Flags.IncludeLatestVersionOnly, Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, extensionNames.length) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)) .withAssetTypes(AssetType.Icon, AssetType.License, AssetType.Details, AssetType.Manifest, AssetType.VSIX) .withFilter(FilterType.ExtensionName, ...extensionNames); return this.queryGallery(query, token).then(result => { const dependencies = []; const ids = []; for (let index = 0; index < result.galleryExtensions.length; index++) { const rawExtension = result.galleryExtensions[index]; if (ids.indexOf(rawExtension.extensionId) === -1) { dependencies.push(toExtension(rawExtension, rawExtension.versions[0], index, query, 'dependencies')); ids.push(rawExtension.extensionId); } } return dependencies; }); } private getDependenciesReccursively(toGet: string[], result: IGalleryExtension[], token: CancellationToken): TPromise<IGalleryExtension[]> { if (!toGet || !toGet.length) { return TPromise.wrap(result); } toGet = result.length ? toGet.filter(e => !ExtensionGalleryService.hasExtensionByName(result, e)) : toGet; if (!toGet.length) { return TPromise.wrap(result); } return this.loadDependencies(toGet, token) .then(loadedDependencies => { const dependenciesSet = new Set<string>(); for (const dep of loadedDependencies) { if (dep.properties.dependencies) { dep.properties.dependencies.forEach(d => dependenciesSet.add(d)); } } result = distinct(result.concat(loadedDependencies), d => d.identifier.uuid); const dependencies: string[] = []; dependenciesSet.forEach(d => !ExtensionGalleryService.hasExtensionByName(result, d) && dependencies.push(d)); return this.getDependenciesReccursively(dependencies, result, token); }); } private getAsset(asset: IGalleryExtensionAsset, options: IRequestOptions = {}, token: CancellationToken = CancellationToken.None): TPromise<IRequestContext> { return this.commonHeadersPromise.then(commonHeaders => { const baseOptions = { type: 'GET' }; const headers = assign({}, commonHeaders, options.headers || {}); options = assign({}, options, baseOptions, { headers }); const url = asset.uri; const fallbackUrl = asset.fallbackUri; const firstOptions = assign({}, options, { url }); return this.requestService.request(firstOptions, token) .then(context => { if (context.res.statusCode === 200) { return TPromise.as(context); } return asText(context) .then(message => TPromise.wrapError<IRequestContext>(new Error(`Expected 200, got back ${context.res.statusCode} instead.\n\n${message}`))); }) .then(null, err => { if (isPromiseCanceledError(err)) { return TPromise.wrapError<IRequestContext>(err); } const message = getErrorMessage(err); /* __GDPR__ "galleryService:requestError" : { "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "cdn": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:requestError', { url, cdn: true, message }); /* __GDPR__ "galleryService:cdnFallback" : { "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "message": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:cdnFallback', { url, message }); const fallbackOptions = assign({}, options, { url: fallbackUrl }); return this.requestService.request(fallbackOptions, token).then(null, err => { if (isPromiseCanceledError(err)) { return TPromise.wrapError<IRequestContext>(err); } const message = getErrorMessage(err); /* __GDPR__ "galleryService:requestError" : { "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "cdn": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:requestError', { url: fallbackUrl, cdn: false, message }); return TPromise.wrapError<IRequestContext>(err); }); }); }); } private getLastValidExtensionVersion(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> { const version = this.getLastValidExtensionVersionFromProperties(extension, versions); if (version) { return version; } return this.getLastValidExtensionVersionReccursively(extension, versions); } private getLastValidExtensionVersionFromProperties(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> { for (const version of versions) { const engine = getEngine(version); if (!engine) { return null; } if (isEngineValid(engine)) { return TPromise.wrap(version); } } return null; } private getLastValidExtensionVersionReccursively(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> { if (!versions.length) { return null; } const version = versions[0]; const asset = getVersionAsset(version, AssetType.Manifest); const headers = { 'Accept-Encoding': 'gzip' }; return this.getAsset(asset, { headers }) .then(context => asJson<IExtensionManifest>(context)) .then(manifest => { const engine = manifest.engines.vscode; if (!isEngineValid(engine)) { return this.getLastValidExtensionVersionReccursively(extension, versions.slice(1)); } version.properties = version.properties || []; version.properties.push({ key: PropertyType.Engine, value: manifest.engines.vscode }); return version; }); } private static hasExtensionByName(extensions: IGalleryExtension[], name: string): boolean { for (const extension of extensions) { if (`${extension.publisher}.${extension.name}` === name) { return true; } } return false; } getExtensionsReport(): TPromise<IReportedExtension[]> { if (!this.isEnabled()) { return TPromise.wrapError(new Error('No extension gallery service configured.')); } if (!this.extensionsControlUrl) { return TPromise.as([]); } return this.requestService.request({ type: 'GET', url: this.extensionsControlUrl }, CancellationToken.None).then(context => { if (context.res.statusCode !== 200) { return TPromise.wrapError(new Error('Could not get extensions report.')); } return asJson<IRawExtensionsReport>(context).then(result => { const map = new Map<string, IReportedExtension>(); for (const id of result.malicious) { const ext = map.get(id) || { id: { id }, malicious: true, slow: false }; ext.malicious = true; map.set(id, ext); } return TPromise.as(values(map)); }); }); } } export function resolveMarketplaceHeaders(environmentService: IEnvironmentService): TPromise<{ [key: string]: string; }> { const marketplaceMachineIdFile = path.join(environmentService.userDataPath, 'machineid'); return readFile(marketplaceMachineIdFile, 'utf8').then(contents => { if (isUUID(contents)) { return contents; } return TPromise.wrap(null); // invalid marketplace UUID }, error => { return TPromise.wrap(null); // error reading ID file }).then(uuid => { if (!uuid) { uuid = generateUuid(); try { writeFileAndFlushSync(marketplaceMachineIdFile, uuid); } catch (error) { //noop } } return { 'X-Market-Client-Id': `VSCode ${pkg.version}`, 'User-Agent': `VSCode ${pkg.version}`, 'X-Market-User-Id': uuid }; }); }
src/vs/platform/extensionManagement/node/extensionGalleryService.ts
1
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.9980759620666504, 0.012540416792035103, 0.00016127893468365073, 0.00017259508604183793, 0.10819029062986374 ]
{ "id": 4, "code_window": [ "\t\t\t\t\t.then(rawVersion => {\n", "\t\t\t\t\t\tif (rawVersion) {\n", "\t\t\t\t\t\t\textension.properties.dependencies = getExtensions(rawVersion, PropertyType.Dependency);\n", "\t\t\t\t\t\t\textension.properties.engine = getEngine(rawVersion);\n", "\t\t\t\t\t\t\textension.assets.download = getVersionAsset(rawVersion, AssetType.VSIX);\n", "\t\t\t\t\t\t\textension.version = rawVersion.version;\n", "\t\t\t\t\t\t\treturn extension;\n", "\t\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\textension.properties.localizedLanguages = getLocalizedLanguages(rawVersion);\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "add", "edit_start_line_idx": 596 }
/*--------------------------------------------------------------------------------------------- * 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!./media/views'; import { Disposable } from 'vs/base/common/lifecycle'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { TPromise } from 'vs/base/common/winjs.base'; import { IViewsService, ViewsRegistry, IViewsViewlet, ViewContainer, IViewDescriptor, IViewContainersRegistry, Extensions as ViewContainerExtensions, TEST_VIEW_CONTAINER_ID, IView } from 'vs/workbench/common/views'; import { Registry } from 'vs/platform/registry/common/platform'; import { ViewletRegistry, Extensions as ViewletExtensions } from 'vs/workbench/browser/viewlet'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { ILifecycleService, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IContextKeyService, IContextKeyChangeEvent, IReadableSet } from 'vs/platform/contextkey/common/contextkey'; import { Event, chain, filterEvent, Emitter } from 'vs/base/common/event'; import { sortedDiff, firstIndex, move } from 'vs/base/common/arrays'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { isUndefinedOrNull } from 'vs/base/common/types'; function filterViewEvent(container: ViewContainer, event: Event<IViewDescriptor[]>): Event<IViewDescriptor[]> { return chain(event) .map(views => views.filter(view => view.container === container)) .filter(views => views.length > 0) .event; } class CounterSet<T> implements IReadableSet<T> { private map = new Map<T, number>(); add(value: T): CounterSet<T> { this.map.set(value, (this.map.get(value) || 0) + 1); return this; } delete(value: T): boolean { let counter = this.map.get(value) || 0; if (counter === 0) { return false; } counter--; if (counter === 0) { this.map.delete(value); } else { this.map.set(value, counter); } return true; } has(value: T): boolean { return this.map.has(value); } } interface IViewItem { viewDescriptor: IViewDescriptor; active: boolean; } class ViewDescriptorCollection extends Disposable { private contextKeys = new CounterSet<string>(); private items: IViewItem[] = []; private _onDidChange = this._register(new Emitter<void>()); readonly onDidChange: Event<void> = this._onDidChange.event; get viewDescriptors(): IViewDescriptor[] { return this.items .filter(i => i.active) .map(i => i.viewDescriptor); } constructor( container: ViewContainer, @IContextKeyService private contextKeyService: IContextKeyService ) { super(); const onRelevantViewsRegistered = filterViewEvent(container, ViewsRegistry.onViewsRegistered); this._register(onRelevantViewsRegistered(this.onViewsRegistered, this)); const onRelevantViewsDeregistered = filterViewEvent(container, ViewsRegistry.onViewsDeregistered); this._register(onRelevantViewsDeregistered(this.onViewsDeregistered, this)); const onRelevantContextChange = filterEvent(contextKeyService.onDidChangeContext, e => e.affectsSome(this.contextKeys)); this._register(onRelevantContextChange(this.onContextChanged, this)); this.onViewsRegistered(ViewsRegistry.getViews(container)); } private onViewsRegistered(viewDescriptors: IViewDescriptor[]): any { let fireChangeEvent = false; for (const viewDescriptor of viewDescriptors) { const item = { viewDescriptor, active: this.isViewDescriptorActive(viewDescriptor) // TODO: should read from some state? }; this.items.push(item); if (viewDescriptor.when) { for (const key of viewDescriptor.when.keys()) { this.contextKeys.add(key); } } if (item.active) { fireChangeEvent = true; } } if (fireChangeEvent) { this._onDidChange.fire(); } } private onViewsDeregistered(viewDescriptors: IViewDescriptor[]): any { let fireChangeEvent = false; for (const viewDescriptor of viewDescriptors) { const index = firstIndex(this.items, i => i.viewDescriptor.id === viewDescriptor.id); if (index === -1) { continue; } const item = this.items[index]; this.items.splice(index, 1); if (viewDescriptor.when) { for (const key of viewDescriptor.when.keys()) { this.contextKeys.delete(key); } } if (item.active) { fireChangeEvent = true; } } if (fireChangeEvent) { this._onDidChange.fire(); } } private onContextChanged(event: IContextKeyChangeEvent): any { let fireChangeEvent = false; for (const item of this.items) { const active = this.isViewDescriptorActive(item.viewDescriptor); if (item.active !== active) { fireChangeEvent = true; } item.active = active; } if (fireChangeEvent) { this._onDidChange.fire(); } } private isViewDescriptorActive(viewDescriptor: IViewDescriptor): boolean { return !viewDescriptor.when || this.contextKeyService.contextMatchesRules(viewDescriptor.when); } } export interface IViewState { visible: boolean; collapsed: boolean; order?: number; size?: number; } export interface IViewDescriptorRef { viewDescriptor: IViewDescriptor; index: number; } export interface IAddedViewDescriptorRef extends IViewDescriptorRef { collapsed: boolean; size?: number; } export class ContributableViewsModel extends Disposable { readonly viewDescriptors: IViewDescriptor[] = []; get visibleViewDescriptors(): IViewDescriptor[] { return this.viewDescriptors.filter(v => this.viewStates.get(v.id).visible); } private _onDidAdd = this._register(new Emitter<IAddedViewDescriptorRef[]>()); readonly onDidAdd: Event<IAddedViewDescriptorRef[]> = this._onDidAdd.event; private _onDidRemove = this._register(new Emitter<IViewDescriptorRef[]>()); readonly onDidRemove: Event<IViewDescriptorRef[]> = this._onDidRemove.event; private _onDidMove = this._register(new Emitter<{ from: IViewDescriptorRef; to: IViewDescriptorRef; }>()); readonly onDidMove: Event<{ from: IViewDescriptorRef; to: IViewDescriptorRef; }> = this._onDidMove.event; constructor( container: ViewContainer, contextKeyService: IContextKeyService, protected viewStates = new Map<string, IViewState>(), ) { super(); const viewDescriptorCollection = this._register(new ViewDescriptorCollection(container, contextKeyService)); this._register(viewDescriptorCollection.onDidChange(() => this.onDidChangeViewDescriptors(viewDescriptorCollection.viewDescriptors))); this.onDidChangeViewDescriptors(viewDescriptorCollection.viewDescriptors); } isVisible(id: string): boolean { const state = this.viewStates.get(id); if (!state) { throw new Error(`Unknown view ${id}`); } return state.visible; } setVisible(id: string, visible: boolean): void { const { visibleIndex, viewDescriptor, state } = this.find(id); if (!viewDescriptor.canToggleVisibility) { throw new Error(`Can't toggle this view's visibility`); } if (state.visible === visible) { return; } state.visible = visible; if (visible) { this._onDidAdd.fire([{ index: visibleIndex, viewDescriptor, size: state.size, collapsed: state.collapsed }]); } else { this._onDidRemove.fire([{ index: visibleIndex, viewDescriptor }]); } } isCollapsed(id: string): boolean { const state = this.viewStates.get(id); if (!state) { throw new Error(`Unknown view ${id}`); } return state.collapsed; } setCollapsed(id: string, collapsed: boolean): void { const { state } = this.find(id); state.collapsed = collapsed; } getSize(id: string): number | undefined { const state = this.viewStates.get(id); if (!state) { throw new Error(`Unknown view ${id}`); } return state.size; } setSize(id: string, size: number): void { const { state } = this.find(id); state.size = size; } move(from: string, to: string): void { const fromIndex = firstIndex(this.viewDescriptors, v => v.id === from); const toIndex = firstIndex(this.viewDescriptors, v => v.id === to); const fromViewDescriptor = this.viewDescriptors[fromIndex]; const toViewDescriptor = this.viewDescriptors[toIndex]; move(this.viewDescriptors, fromIndex, toIndex); for (let index = 0; index < this.viewDescriptors.length; index++) { const state = this.viewStates.get(this.viewDescriptors[index].id); state.order = index; } this._onDidMove.fire({ from: { index: fromIndex, viewDescriptor: fromViewDescriptor }, to: { index: toIndex, viewDescriptor: toViewDescriptor } }); } private find(id: string): { index: number, visibleIndex: number, viewDescriptor: IViewDescriptor, state: IViewState } { for (let i = 0, visibleIndex = 0; i < this.viewDescriptors.length; i++) { const viewDescriptor = this.viewDescriptors[i]; const state = this.viewStates.get(viewDescriptor.id); if (viewDescriptor.id === id) { return { index: i, visibleIndex, viewDescriptor, state }; } if (state.visible) { visibleIndex++; } } throw new Error(`view descriptor ${id} not found`); } private compareViewDescriptors(a: IViewDescriptor, b: IViewDescriptor): number { if (a.id === b.id) { return 0; } return (this.getViewOrder(a) - this.getViewOrder(b)) || (a.id < b.id ? -1 : 1); } private getViewOrder(viewDescriptor: IViewDescriptor): number { const viewState = this.viewStates.get(viewDescriptor.id); const viewOrder = viewState && typeof viewState.order === 'number' ? viewState.order : viewDescriptor.order; return typeof viewOrder === 'number' ? viewOrder : Number.MAX_VALUE; } private onDidChangeViewDescriptors(viewDescriptors: IViewDescriptor[]): void { const ids = new Set<string>(); for (const viewDescriptor of this.viewDescriptors) { ids.add(viewDescriptor.id); } viewDescriptors = viewDescriptors.sort(this.compareViewDescriptors.bind(this)); for (const viewDescriptor of viewDescriptors) { const viewState = this.viewStates.get(viewDescriptor.id); if (viewState) { // set defaults if not set viewState.visible = isUndefinedOrNull(viewState.visible) ? !viewDescriptor.hideByDefault : viewState.visible; viewState.collapsed = isUndefinedOrNull(viewState.collapsed) ? !!viewDescriptor.collapsed : viewState.collapsed; } else { this.viewStates.set(viewDescriptor.id, { visible: !viewDescriptor.hideByDefault, collapsed: viewDescriptor.collapsed }); } } const splices = sortedDiff<IViewDescriptor>( this.viewDescriptors, viewDescriptors, this.compareViewDescriptors.bind(this) ).reverse(); const toRemove: { index: number, viewDescriptor: IViewDescriptor }[] = []; const toAdd: { index: number, viewDescriptor: IViewDescriptor, size: number, collapsed: boolean }[] = []; for (const splice of splices) { const startViewDescriptor = this.viewDescriptors[splice.start]; let startIndex = startViewDescriptor ? this.find(startViewDescriptor.id).visibleIndex : this.viewDescriptors.length; for (let i = 0; i < splice.deleteCount; i++) { const viewDescriptor = this.viewDescriptors[splice.start + i]; const { state } = this.find(viewDescriptor.id); if (state.visible) { toRemove.push({ index: startIndex++, viewDescriptor }); } } for (let i = 0; i < splice.toInsert.length; i++) { const viewDescriptor = splice.toInsert[i]; const state = this.viewStates.get(viewDescriptor.id); if (state.visible) { toAdd.push({ index: startIndex++, viewDescriptor, size: state.size, collapsed: state.collapsed }); } } } this.viewDescriptors.splice(0, this.viewDescriptors.length, ...viewDescriptors); if (toRemove.length) { this._onDidRemove.fire(toRemove); } if (toAdd.length) { this._onDidAdd.fire(toAdd); } } } export class PersistentContributableViewsModel extends ContributableViewsModel { private viewletStateStorageId: string; private readonly hiddenViewsStorageId: string; private storageService: IStorageService; private contextService: IWorkspaceContextService; constructor( container: ViewContainer, viewletStateStorageId: string, @IContextKeyService contextKeyService: IContextKeyService, @IStorageService storageService: IStorageService, @IWorkspaceContextService contextService: IWorkspaceContextService ) { const hiddenViewsStorageId = `${viewletStateStorageId}.hidden`; const viewStates = PersistentContributableViewsModel.loadViewsStates(viewletStateStorageId, hiddenViewsStorageId, storageService, contextService); super(container, contextKeyService, viewStates); this.viewletStateStorageId = viewletStateStorageId; this.hiddenViewsStorageId = hiddenViewsStorageId; this.storageService = storageService; this.contextService = contextService; this._register(this.onDidAdd(viewDescriptorRefs => this.saveVisibilityStates(viewDescriptorRefs.map(r => r.viewDescriptor)))); this._register(this.onDidRemove(viewDescriptorRefs => this.saveVisibilityStates(viewDescriptorRefs.map(r => r.viewDescriptor)))); } saveViewsStates(): void { const storedViewsStates: { [id: string]: { collapsed: boolean, size: number, order: number } } = {}; for (const viewDescriptor of this.viewDescriptors) { const viewState = this.viewStates.get(viewDescriptor.id); if (viewState) { storedViewsStates[viewDescriptor.id] = { collapsed: viewState.collapsed, size: viewState.size, order: viewState.order }; } } this.storageService.store(this.viewletStateStorageId, JSON.stringify(storedViewsStates), this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY ? StorageScope.WORKSPACE : StorageScope.GLOBAL); } private saveVisibilityStates(viewDescriptors: IViewDescriptor[]): void { const storedViewsVisibilityStates = PersistentContributableViewsModel.loadViewsVisibilityState(this.hiddenViewsStorageId, this.storageService, this.contextService); for (const viewDescriptor of viewDescriptors) { if (viewDescriptor.canToggleVisibility) { const viewState = this.viewStates.get(viewDescriptor.id); storedViewsVisibilityStates.push({ id: viewDescriptor.id, isHidden: viewState ? !viewState.visible : void 0 }); } } this.storageService.store(this.hiddenViewsStorageId, JSON.stringify(storedViewsVisibilityStates), StorageScope.GLOBAL); } private static loadViewsStates(viewletStateStorageId: string, hiddenViewsStorageId: string, storageService: IStorageService, contextService: IWorkspaceContextService): Map<string, IViewState> { const viewStates = new Map<string, IViewState>(); const storedViewsStates = JSON.parse(storageService.get(viewletStateStorageId, contextService.getWorkbenchState() !== WorkbenchState.EMPTY ? StorageScope.WORKSPACE : StorageScope.GLOBAL, '{}')); const viewsVisibilityStates = PersistentContributableViewsModel.loadViewsVisibilityState(hiddenViewsStorageId, storageService, contextService); for (const { id, isHidden } of viewsVisibilityStates) { const viewState = storedViewsStates[id]; if (viewState) { viewStates.set(id, <IViewState>{ ...viewState, ...{ visible: !isHidden } }); } else { // New workspace viewStates.set(id, <IViewState>{ ...{ visible: !isHidden } }); } } for (const id of Object.keys(storedViewsStates)) { if (!viewStates.has(id)) { viewStates.set(id, <IViewState>{ ...storedViewsStates[id] }); } } return viewStates; } private static loadViewsVisibilityState(hiddenViewsStorageId: string, storageService: IStorageService, contextService: IWorkspaceContextService): { id: string, isHidden: boolean }[] { const storedVisibilityStates = <Array<string | { id: string, isHidden: boolean }>>JSON.parse(storageService.get(hiddenViewsStorageId, StorageScope.GLOBAL, '[]')); return <{ id: string, isHidden: boolean }[]>storedVisibilityStates.map(c => typeof c === 'string' /* migration */ ? { id: c, isHidden: true } : c); } dispose(): void { this.saveViewsStates(); super.dispose(); } } const SCM_VIEWLET_ID = 'workbench.view.scm'; export class ViewsService extends Disposable implements IViewsService { _serviceBrand: any; constructor( @IInstantiationService private instantiationService: IInstantiationService, @ILifecycleService private lifecycleService: ILifecycleService, @IViewletService private viewletService: IViewletService, @IStorageService private storageService: IStorageService, @IWorkspaceContextService private workspaceContextService: IWorkspaceContextService ) { super(); const viewContainersRegistry = Registry.as<IViewContainersRegistry>(ViewContainerExtensions.ViewContainersRegistry); viewContainersRegistry.all.forEach(viewContainer => this.onDidRegisterViewContainer(viewContainer)); this._register(viewContainersRegistry.onDidRegister(viewContainer => this.onDidRegisterViewContainer(viewContainer))); this._register(Registry.as<ViewletRegistry>(ViewletExtensions.Viewlets).onDidRegister(viewlet => this.viewletService.setViewletEnablement(viewlet.id, this.storageService.getBoolean(`viewservice.${viewlet.id}.enablement`, this.getStorageScope(), viewlet.id !== TEST_VIEW_CONTAINER_ID)))); } openView(id: string, focus: boolean): TPromise<IView> { const viewDescriptor = ViewsRegistry.getView(id); if (viewDescriptor) { const viewletDescriptor = this.viewletService.getViewlet(viewDescriptor.container.id); if (viewletDescriptor) { return this.viewletService.openViewlet(viewletDescriptor.id) .then((viewlet: IViewsViewlet) => { if (viewlet && viewlet.openView) { return viewlet.openView(id, focus); } return null; }); } } return TPromise.as(null); } private onDidRegisterViewContainer(viewContainer: ViewContainer): void { // TODO: @Joao Remove this after moving SCM Viewlet to ViewContainerViewlet - https://github.com/Microsoft/vscode/issues/49054 if (viewContainer.id !== SCM_VIEWLET_ID) { const viewDescriptorCollection = this._register(this.instantiationService.createInstance(ViewDescriptorCollection, viewContainer)); this._register(viewDescriptorCollection.onDidChange(() => this.updateViewletEnablement(viewContainer, viewDescriptorCollection))); this.lifecycleService.when(LifecyclePhase.Eventually).then(() => this.updateViewletEnablement(viewContainer, viewDescriptorCollection)); } } private updateViewletEnablement(viewContainer: ViewContainer, viewDescriptorCollection: ViewDescriptorCollection): void { const enabled = viewDescriptorCollection.viewDescriptors.length > 0; this.viewletService.setViewletEnablement(viewContainer.id, enabled); this.storageService.store(`viewservice.${viewContainer.id}.enablement`, enabled, this.getStorageScope()); } private getStorageScope(): StorageScope { return this.workspaceContextService.getWorkbenchState() === WorkbenchState.EMPTY ? StorageScope.GLOBAL : StorageScope.WORKSPACE; } }
src/vs/workbench/browser/parts/views/views.ts
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017560686683282256, 0.00017193943494930863, 0.00016602105461061, 0.00017187363118864596, 0.0000017950529809240834 ]
{ "id": 4, "code_window": [ "\t\t\t\t\t.then(rawVersion => {\n", "\t\t\t\t\t\tif (rawVersion) {\n", "\t\t\t\t\t\t\textension.properties.dependencies = getExtensions(rawVersion, PropertyType.Dependency);\n", "\t\t\t\t\t\t\textension.properties.engine = getEngine(rawVersion);\n", "\t\t\t\t\t\t\textension.assets.download = getVersionAsset(rawVersion, AssetType.VSIX);\n", "\t\t\t\t\t\t\textension.version = rawVersion.version;\n", "\t\t\t\t\t\t\treturn extension;\n", "\t\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\textension.properties.localizedLanguages = getLocalizedLanguages(rawVersion);\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "add", "edit_start_line_idx": 596 }
:root { --spacing-unit: 6px; --cell-padding: (4 * var(--spacing-unit)); } body { padding-left: calc(4 * var(--spacing-unit, 5px)); }
extensions/less/test/colorize-fixtures/test-cssvariables.less
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.0001730023795971647, 0.0001730023795971647, 0.0001730023795971647, 0.0001730023795971647, 0 ]
{ "id": 4, "code_window": [ "\t\t\t\t\t.then(rawVersion => {\n", "\t\t\t\t\t\tif (rawVersion) {\n", "\t\t\t\t\t\t\textension.properties.dependencies = getExtensions(rawVersion, PropertyType.Dependency);\n", "\t\t\t\t\t\t\textension.properties.engine = getEngine(rawVersion);\n", "\t\t\t\t\t\t\textension.assets.download = getVersionAsset(rawVersion, AssetType.VSIX);\n", "\t\t\t\t\t\t\textension.version = rawVersion.version;\n", "\t\t\t\t\t\t\treturn extension;\n", "\t\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\textension.properties.localizedLanguages = getLocalizedLanguages(rawVersion);\n" ], "file_path": "src/vs/platform/extensionManagement/node/extensionGalleryService.ts", "type": "add", "edit_start_line_idx": 596 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /* NOTE: THIS FILE WILL BE OVERWRITTEN DURING BUILD TIME, DO NOT EDIT */ div.monaco.main.css { }
src/vs/workbench/workbench.main.css
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017390924040228128, 0.00017390924040228128, 0.00017390924040228128, 0.00017390924040228128, 0 ]
{ "id": 5, "code_window": [ "\n", "'use strict';\n", "\n", "import { localize } from 'vs/nls';\n", "import { append, $, addClass, removeClass, toggleClass } from 'vs/base/browser/dom';\n", "import { IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle';\n", "import { Action } from 'vs/base/common/actions';\n", "import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';\n", "import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n", "import { IVirtualDelegate } from 'vs/base/browser/ui/list/list';\n", "import { IPagedRenderer } from 'vs/base/browser/ui/list/listPaging';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IDisposable, dispose } from 'vs/base/common/lifecycle';\n" ], "file_path": "src/vs/workbench/parts/extensions/electron-browser/extensionsList.ts", "type": "replace", "edit_start_line_idx": 9 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { localize } from 'vs/nls'; import { append, $, addClass, removeClass, toggleClass } from 'vs/base/browser/dom'; import { IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle'; import { Action } from 'vs/base/common/actions'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { IPagedRenderer } from 'vs/base/browser/ui/list/listPaging'; import { once } from 'vs/base/common/event'; import { domEvent } from 'vs/base/browser/event'; import { IExtension, IExtensionsWorkbenchService } from 'vs/workbench/parts/extensions/common/extensions'; import { InstallAction, UpdateAction, ManageExtensionAction, ReloadAction, extensionButtonProminentBackground, extensionButtonProminentForeground, MaliciousStatusLabelAction, DisabledStatusLabelAction } from 'vs/workbench/parts/extensions/electron-browser/extensionsActions'; import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { Label, RatingsWidget, InstallCountWidget } from 'vs/workbench/parts/extensions/browser/extensionsWidgets'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IExtensionTipsService, IExtensionManagementServerService } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { createCancelablePromise } from 'vs/base/common/async'; export interface ITemplateData { root: HTMLElement; element: HTMLElement; icon: HTMLImageElement; name: HTMLElement; installCount: HTMLElement; ratings: HTMLElement; author: HTMLElement; description: HTMLElement; extension: IExtension; disposables: IDisposable[]; extensionDisposables: IDisposable[]; } export class Delegate implements IVirtualDelegate<IExtension> { getHeight() { return 62; } getTemplateId() { return 'extension'; } } const actionOptions = { icon: true, label: true }; export class Renderer implements IPagedRenderer<IExtension, ITemplateData> { constructor( @IInstantiationService private instantiationService: IInstantiationService, @INotificationService private notificationService: INotificationService, @IExtensionsWorkbenchService private extensionsWorkbenchService: IExtensionsWorkbenchService, @IExtensionService private extensionService: IExtensionService, @IExtensionTipsService private extensionTipsService: IExtensionTipsService, @IThemeService private themeService: IThemeService, @IExtensionManagementServerService private extensionManagementServerService: IExtensionManagementServerService ) { } get templateId() { return 'extension'; } renderTemplate(root: HTMLElement): ITemplateData { const bookmark = append(root, $('span.bookmark')); append(bookmark, $('span.octicon.octicon-star')); const applyBookmarkStyle = (theme) => { const bgColor = theme.getColor(extensionButtonProminentBackground); const fgColor = theme.getColor(extensionButtonProminentForeground); bookmark.style.borderTopColor = bgColor ? bgColor.toString() : 'transparent'; bookmark.style.color = fgColor ? fgColor.toString() : 'white'; }; applyBookmarkStyle(this.themeService.getTheme()); const bookmarkStyler = this.themeService.onThemeChange(applyBookmarkStyle.bind(this)); const element = append(root, $('.extension')); const icon = append(element, $<HTMLImageElement>('img.icon')); const details = append(element, $('.details')); const headerContainer = append(details, $('.header-container')); const header = append(headerContainer, $('.header')); const name = append(header, $('span.name')); const version = append(header, $('span.version')); const installCount = append(header, $('span.install-count')); const ratings = append(header, $('span.ratings')); const description = append(details, $('.description.ellipsis')); const footer = append(details, $('.footer')); const author = append(footer, $('.author.ellipsis')); const actionbar = new ActionBar(footer, { animated: false, actionItemProvider: (action: Action) => { if (action.id === ManageExtensionAction.ID) { return (<ManageExtensionAction>action).actionItem; } return null; } }); actionbar.onDidRun(({ error }) => error && this.notificationService.error(error)); const versionWidget = this.instantiationService.createInstance(Label, version, (e: IExtension) => e.version); const installCountWidget = this.instantiationService.createInstance(InstallCountWidget, installCount, { small: true }); const ratingsWidget = this.instantiationService.createInstance(RatingsWidget, ratings, { small: true }); const maliciousStatusAction = this.instantiationService.createInstance(MaliciousStatusLabelAction, false); const disabledStatusAction = this.instantiationService.createInstance(DisabledStatusLabelAction); const installAction = this.instantiationService.createInstance(InstallAction); const updateAction = this.instantiationService.createInstance(UpdateAction); const reloadAction = this.instantiationService.createInstance(ReloadAction); const manageAction = this.instantiationService.createInstance(ManageExtensionAction); actionbar.push([updateAction, reloadAction, installAction, disabledStatusAction, maliciousStatusAction, manageAction], actionOptions); const disposables = [versionWidget, installCountWidget, ratingsWidget, maliciousStatusAction, disabledStatusAction, updateAction, installAction, reloadAction, manageAction, actionbar, bookmarkStyler]; return { root, element, icon, name, installCount, ratings, author, description, disposables, extensionDisposables: [], set extension(extension: IExtension) { versionWidget.extension = extension; installCountWidget.extension = extension; ratingsWidget.extension = extension; maliciousStatusAction.extension = extension; disabledStatusAction.extension = extension; installAction.extension = extension; updateAction.extension = extension; reloadAction.extension = extension; manageAction.extension = extension; } }; } renderPlaceholder(index: number, data: ITemplateData): void { addClass(data.element, 'loading'); data.root.removeAttribute('aria-label'); data.extensionDisposables = dispose(data.extensionDisposables); data.icon.src = ''; data.name.textContent = ''; data.author.textContent = ''; data.description.textContent = ''; data.installCount.style.display = 'none'; data.ratings.style.display = 'none'; data.extension = null; } renderElement(extension: IExtension, index: number, data: ITemplateData): void { removeClass(data.element, 'loading'); data.extensionDisposables = dispose(data.extensionDisposables); const installed = this.extensionsWorkbenchService.local.filter(e => e.id === extension.id)[0]; this.extensionService.getExtensions().then(runningExtensions => { if (installed && installed.local) { const installedExtensionServer = this.extensionManagementServerService.getExtensionManagementServer(installed.local.location); const isSameExtensionRunning = runningExtensions.some(e => areSameExtensions(e, extension) && installedExtensionServer.authority === this.extensionManagementServerService.getExtensionManagementServer(e.extensionLocation).authority); toggleClass(data.root, 'disabled', !isSameExtensionRunning); } else { removeClass(data.root, 'disabled'); } }); const onError = once(domEvent(data.icon, 'error')); onError(() => data.icon.src = extension.iconUrlFallback, null, data.extensionDisposables); data.icon.src = extension.iconUrl; if (!data.icon.complete) { data.icon.style.visibility = 'hidden'; data.icon.onload = () => data.icon.style.visibility = 'inherit'; } else { data.icon.style.visibility = 'inherit'; } this.updateRecommendationStatus(extension, data); data.extensionDisposables.push(this.extensionTipsService.onRecommendationChange(change => { if (change.extensionId.toLowerCase() === extension.id.toLowerCase()) { this.updateRecommendationStatus(extension, data); } })); data.name.textContent = extension.displayName; data.author.textContent = extension.publisherDisplayName; data.description.textContent = extension.description; data.installCount.style.display = ''; data.ratings.style.display = ''; data.extension = extension; const manifestPromise = createCancelablePromise(token => extension.getManifest(token).then(manifest => { if (manifest) { const name = manifest && manifest.contributes && manifest.contributes.localizations && manifest.contributes.localizations.length > 0 && manifest.contributes.localizations[0].localizedLanguageName; if (name) { data.description.textContent = name[0].toLocaleUpperCase() + name.slice(1); } } })); data.disposables.push(toDisposable(() => manifestPromise.cancel())); } disposeElement(): void { // noop } private updateRecommendationStatus(extension: IExtension, data: ITemplateData) { const extRecommendations = this.extensionTipsService.getAllRecommendationsWithReason(); let ariaLabel = extension.displayName + '. '; if (!extRecommendations[extension.id.toLowerCase()]) { removeClass(data.root, 'recommended'); data.root.title = ''; } else { addClass(data.root, 'recommended'); ariaLabel += extRecommendations[extension.id.toLowerCase()].reasonText + ' '; data.root.title = extRecommendations[extension.id.toLowerCase()].reasonText; } ariaLabel += localize('viewExtensionDetailsAria', "Press enter for extension details."); data.root.setAttribute('aria-label', ariaLabel); } disposeTemplate(data: ITemplateData): void { data.disposables = dispose(data.disposables); } }
src/vs/workbench/parts/extensions/electron-browser/extensionsList.ts
1
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.9941798448562622, 0.046574853360652924, 0.00016082283400464803, 0.00017364993982482702, 0.20683352649211884 ]
{ "id": 5, "code_window": [ "\n", "'use strict';\n", "\n", "import { localize } from 'vs/nls';\n", "import { append, $, addClass, removeClass, toggleClass } from 'vs/base/browser/dom';\n", "import { IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle';\n", "import { Action } from 'vs/base/common/actions';\n", "import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';\n", "import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n", "import { IVirtualDelegate } from 'vs/base/browser/ui/list/list';\n", "import { IPagedRenderer } from 'vs/base/browser/ui/list/listPaging';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IDisposable, dispose } from 'vs/base/common/lifecycle';\n" ], "file_path": "src/vs/workbench/parts/extensions/electron-browser/extensionsList.ts", "type": "replace", "edit_start_line_idx": 9 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { URI } from 'vs/base/common/uri'; import * as paths from 'vs/base/common/paths'; import * as resources from 'vs/base/common/resources'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { TernarySearchTree } from 'vs/base/common/map'; import { Event } from 'vs/base/common/event'; import { IWorkspaceIdentifier, IStoredWorkspaceFolder, isRawFileWorkspaceFolder, isRawUriWorkspaceFolder, ISingleFolderWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces'; import { coalesce, distinct } from 'vs/base/common/arrays'; import { isLinux } from 'vs/base/common/platform'; export const IWorkspaceContextService = createDecorator<IWorkspaceContextService>('contextService'); export const enum WorkbenchState { EMPTY = 1, FOLDER, WORKSPACE } export interface IWorkspaceFoldersChangeEvent { added: IWorkspaceFolder[]; removed: IWorkspaceFolder[]; changed: IWorkspaceFolder[]; } export interface IWorkspaceContextService { _serviceBrand: any; /** * An event which fires on workbench state changes. */ onDidChangeWorkbenchState: Event<WorkbenchState>; /** * An event which fires on workspace name changes. */ onDidChangeWorkspaceName: Event<void>; /** * An event which fires on workspace folders change. */ onDidChangeWorkspaceFolders: Event<IWorkspaceFoldersChangeEvent>; /** * Provides access to the workspace object the platform is running with. */ getWorkspace(): IWorkspace; /** * Return the state of the workbench. * * WorkbenchState.EMPTY - if the workbench was opened with empty window or file * WorkbenchState.FOLDER - if the workbench was opened with a folder * WorkbenchState.WORKSPACE - if the workbench was opened with a workspace */ getWorkbenchState(): WorkbenchState; /** * Returns the folder for the given resource from the workspace. * Can be null if there is no workspace or the resource is not inside the workspace. */ getWorkspaceFolder(resource: URI): IWorkspaceFolder; /** * Return `true` if the current workspace has the given identifier otherwise `false`. */ isCurrentWorkspace(workspaceIdentifier: ISingleFolderWorkspaceIdentifier | IWorkspaceIdentifier): boolean; /** * Returns if the provided resource is inside the workspace or not. */ isInsideWorkspace(resource: URI): boolean; } export namespace IWorkspace { export function isIWorkspace(thing: any): thing is IWorkspace { return thing && typeof thing === 'object' && typeof (thing as IWorkspace).id === 'string' && Array.isArray((thing as IWorkspace).folders); } } export interface IWorkspace { /** * the unique identifier of the workspace. */ readonly id: string; /** * Folders in the workspace. */ readonly folders: IWorkspaceFolder[]; /** * the location of the workspace configuration */ readonly configuration?: URI; } export interface IWorkspaceFolderData { /** * The associated URI for this workspace folder. */ readonly uri: URI; /** * The name of this workspace folder. Defaults to * the basename its [uri-path](#Uri.path) */ readonly name: string; /** * The ordinal number of this workspace folder. */ readonly index: number; } export namespace IWorkspaceFolder { export function isIWorkspaceFolder(thing: any): thing is IWorkspaceFolder { return thing && typeof thing === 'object' && URI.isUri((thing as IWorkspaceFolder).uri) && typeof (thing as IWorkspaceFolder).name === 'string' && typeof (thing as IWorkspaceFolder).toResource === 'function'; } } export interface IWorkspaceFolder extends IWorkspaceFolderData { /** * Given workspace folder relative path, returns the resource with the absolute path. */ toResource: (relativePath: string) => URI; } export class Workspace implements IWorkspace { private _foldersMap: TernarySearchTree<WorkspaceFolder> = TernarySearchTree.forPaths<WorkspaceFolder>(); private _folders: WorkspaceFolder[]; constructor( private _id: string, folders: WorkspaceFolder[] = [], private _configuration: URI = null, private _ctime?: number ) { this.folders = folders; } update(workspace: Workspace) { this._id = workspace.id; this._configuration = workspace.configuration; this._ctime = workspace.ctime; this.folders = workspace.folders; } get folders(): WorkspaceFolder[] { return this._folders; } set folders(folders: WorkspaceFolder[]) { this._folders = folders; this.updateFoldersMap(); } get id(): string { return this._id; } get ctime(): number { return this._ctime; } get configuration(): URI { return this._configuration; } set configuration(configuration: URI) { this._configuration = configuration; } getFolder(resource: URI): IWorkspaceFolder { if (!resource) { return null; } return this._foldersMap.findSubstr(resource.toString()); } private updateFoldersMap(): void { this._foldersMap = TernarySearchTree.forPaths<WorkspaceFolder>(); for (const folder of this.folders) { this._foldersMap.set(folder.uri.toString(), folder); } } toJSON(): IWorkspace { return { id: this.id, folders: this.folders, configuration: this.configuration }; } } export class WorkspaceFolder implements IWorkspaceFolder { readonly uri: URI; name: string; index: number; constructor(data: IWorkspaceFolderData, readonly raw?: IStoredWorkspaceFolder) { this.uri = data.uri; this.index = data.index; this.name = data.name; } toResource(relativePath: string): URI { return resources.joinPath(this.uri, relativePath); } toJSON(): IWorkspaceFolderData { return { uri: this.uri, name: this.name, index: this.index }; } } export function toWorkspaceFolders(configuredFolders: IStoredWorkspaceFolder[], relativeTo?: URI): WorkspaceFolder[] { let workspaceFolders = parseWorkspaceFolders(configuredFolders, relativeTo); return ensureUnique(coalesce(workspaceFolders)) .map(({ uri, raw, name }, index) => new WorkspaceFolder({ uri, name: name || resources.basenameOrAuthority(uri), index }, raw)); } function parseWorkspaceFolders(configuredFolders: IStoredWorkspaceFolder[], relativeTo: URI): WorkspaceFolder[] { return configuredFolders.map((configuredFolder, index) => { let uri: URI; if (isRawFileWorkspaceFolder(configuredFolder)) { uri = toUri(configuredFolder.path, relativeTo); } else if (isRawUriWorkspaceFolder(configuredFolder)) { try { uri = URI.parse(configuredFolder.uri); // this makes sure all workspace folder are absolute if (uri.path[0] !== '/') { uri = uri.with({ path: '/' + uri.path }); } } catch (e) { console.warn(e); // ignore } } if (!uri) { return void 0; } return new WorkspaceFolder({ uri, name: configuredFolder.name, index }, configuredFolder); }); } function toUri(path: string, relativeTo: URI): URI { if (path) { if (paths.isAbsolute(path)) { return URI.file(path); } if (relativeTo) { return resources.joinPath(relativeTo, path); } } return null; } function ensureUnique(folders: WorkspaceFolder[]): WorkspaceFolder[] { return distinct(folders, folder => isLinux ? folder.uri.toString() : folder.uri.toString().toLowerCase()); }
src/vs/platform/workspace/common/workspace.ts
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.0002549390774220228, 0.00017426635895390064, 0.0001629350008442998, 0.00017260013555642217, 0.000015969764717738144 ]
{ "id": 5, "code_window": [ "\n", "'use strict';\n", "\n", "import { localize } from 'vs/nls';\n", "import { append, $, addClass, removeClass, toggleClass } from 'vs/base/browser/dom';\n", "import { IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle';\n", "import { Action } from 'vs/base/common/actions';\n", "import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';\n", "import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n", "import { IVirtualDelegate } from 'vs/base/browser/ui/list/list';\n", "import { IPagedRenderer } from 'vs/base/browser/ui/list/listPaging';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IDisposable, dispose } from 'vs/base/common/lifecycle';\n" ], "file_path": "src/vs/workbench/parts/extensions/electron-browser/extensionsList.ts", "type": "replace", "edit_start_line_idx": 9 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><defs><style>.icon-canvas-transparent,.icon-vs-out{fill:#252526;}.icon-canvas-transparent{opacity:0;}.icon-vs-bg{fill:#c5c5c5;}.icon-vs-action-blue{fill:#75beff;}</style></defs><title>step-out</title><g id="canvas"><path class="icon-canvas-transparent" d="M16,16H0V0H16Z"/></g><g id="outline" style="display: none;"><path class="icon-vs-out" d="M10,10.78a3,3,0,1,1-4,0V6.225l-.97.97L2.556,4.72,7.275,0H8.725l4.72,4.72L10.97,7.194,10,6.225Z"/></g><g id="iconBg"><path class="icon-vs-bg" d="M8,11a2,2,0,1,1-2,2A2,2,0,0,1,8,11Z"/></g><g id="colorAction"><path class="icon-vs-action-blue" d="M3.97,4.72,8,.689l4.03,4.03L10.97,5.78,9,3.811V10H7V3.811L5.03,5.78Z"/></g></svg>
src/vs/workbench/parts/debug/browser/media/step-out-inverse.svg
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00016740082355681807, 0.00016740082355681807, 0.00016740082355681807, 0.00016740082355681807, 0 ]
{ "id": 5, "code_window": [ "\n", "'use strict';\n", "\n", "import { localize } from 'vs/nls';\n", "import { append, $, addClass, removeClass, toggleClass } from 'vs/base/browser/dom';\n", "import { IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle';\n", "import { Action } from 'vs/base/common/actions';\n", "import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';\n", "import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n", "import { IVirtualDelegate } from 'vs/base/browser/ui/list/list';\n", "import { IPagedRenderer } from 'vs/base/browser/ui/list/listPaging';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IDisposable, dispose } from 'vs/base/common/lifecycle';\n" ], "file_path": "src/vs/workbench/parts/extensions/electron-browser/extensionsList.ts", "type": "replace", "edit_start_line_idx": 9 }
[ { "c": "var", "t": "source.ts meta.var.expr.ts storage.type.ts", "r": { "dark_plus": "storage.type: #569CD6", "light_plus": "storage.type: #0000FF", "dark_vs": "storage.type: #569CD6", "light_vs": "storage.type: #0000FF", "hc_black": "storage.type: #569CD6" } }, { "c": " ", "t": "source.ts meta.var.expr.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "x", "t": "source.ts meta.var.expr.ts meta.var-single-variable.expr.ts meta.definition.variable.ts variable.other.readwrite.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": " ", "t": "source.ts meta.var.expr.ts meta.var-single-variable.expr.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "=", "t": "source.ts meta.var.expr.ts keyword.operator.assignment.ts", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.ts meta.var.expr.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "`", "t": "source.ts meta.var.expr.ts string.template.ts punctuation.definition.string.template.begin.ts", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "Hello ", "t": "source.ts meta.var.expr.ts string.template.ts", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "${", "t": "source.ts meta.var.expr.ts string.template.ts meta.template.expression.ts punctuation.definition.template-expression.begin.ts", "r": { "dark_plus": "punctuation.definition.template-expression.begin: #569CD6", "light_plus": "punctuation.definition.template-expression.begin: #0000FF", "dark_vs": "punctuation.definition.template-expression.begin: #569CD6", "light_vs": "punctuation.definition.template-expression.begin: #0000FF", "hc_black": "punctuation.definition.template-expression.begin: #569CD6" } }, { "c": "foo", "t": "source.ts meta.var.expr.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts variable.other.readwrite.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": "}", "t": "source.ts meta.var.expr.ts string.template.ts meta.template.expression.ts punctuation.definition.template-expression.end.ts", "r": { "dark_plus": "punctuation.definition.template-expression.end: #569CD6", "light_plus": "punctuation.definition.template-expression.end: #0000FF", "dark_vs": "punctuation.definition.template-expression.end: #569CD6", "light_vs": "punctuation.definition.template-expression.end: #0000FF", "hc_black": "punctuation.definition.template-expression.end: #569CD6" } }, { "c": "!", "t": "source.ts meta.var.expr.ts string.template.ts", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "`", "t": "source.ts meta.var.expr.ts string.template.ts punctuation.definition.string.template.end.ts", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": ";", "t": "source.ts punctuation.terminator.statement.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "console", "t": "source.ts meta.function-call.ts support.class.console.ts", "r": { "dark_plus": "support.class: #4EC9B0", "light_plus": "support.class: #267F99", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.class: #4EC9B0" } }, { "c": ".", "t": "source.ts meta.function-call.ts punctuation.accessor.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "log", "t": "source.ts meta.function-call.ts support.function.console.ts", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA" } }, { "c": "(", "t": "source.ts meta.brace.round.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "`", "t": "source.ts string.template.ts punctuation.definition.string.template.begin.ts", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "string text line 1", "t": "source.ts string.template.ts", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "string text line 2", "t": "source.ts string.template.ts", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "`", "t": "source.ts string.template.ts punctuation.definition.string.template.end.ts", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": ")", "t": "source.ts meta.brace.round.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ";", "t": "source.ts punctuation.terminator.statement.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "x", "t": "source.ts variable.other.readwrite.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": " ", "t": "source.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "=", "t": "source.ts keyword.operator.assignment.ts", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "tag", "t": "source.ts string.template.ts entity.name.function.tagged-template.ts", "r": { "dark_plus": "entity.name.function: #DCDCAA", "light_plus": "entity.name.function: #795E26", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "entity.name.function: #DCDCAA" } }, { "c": "`", "t": "source.ts string.template.ts punctuation.definition.string.template.begin.ts", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "Hello ", "t": "source.ts string.template.ts", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "${", "t": "source.ts string.template.ts meta.template.expression.ts punctuation.definition.template-expression.begin.ts", "r": { "dark_plus": "punctuation.definition.template-expression.begin: #569CD6", "light_plus": "punctuation.definition.template-expression.begin: #0000FF", "dark_vs": "punctuation.definition.template-expression.begin: #569CD6", "light_vs": "punctuation.definition.template-expression.begin: #0000FF", "hc_black": "punctuation.definition.template-expression.begin: #569CD6" } }, { "c": " ", "t": "source.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "a", "t": "source.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts variable.other.readwrite.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": " ", "t": "source.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "+", "t": "source.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts keyword.operator.arithmetic.ts", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "b", "t": "source.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts variable.other.readwrite.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": " ", "t": "source.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "}", "t": "source.ts string.template.ts meta.template.expression.ts punctuation.definition.template-expression.end.ts", "r": { "dark_plus": "punctuation.definition.template-expression.end: #569CD6", "light_plus": "punctuation.definition.template-expression.end: #0000FF", "dark_vs": "punctuation.definition.template-expression.end: #569CD6", "light_vs": "punctuation.definition.template-expression.end: #0000FF", "hc_black": "punctuation.definition.template-expression.end: #569CD6" } }, { "c": " world ", "t": "source.ts string.template.ts", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "${", "t": "source.ts string.template.ts meta.template.expression.ts punctuation.definition.template-expression.begin.ts", "r": { "dark_plus": "punctuation.definition.template-expression.begin: #569CD6", "light_plus": "punctuation.definition.template-expression.begin: #0000FF", "dark_vs": "punctuation.definition.template-expression.begin: #569CD6", "light_vs": "punctuation.definition.template-expression.begin: #0000FF", "hc_black": "punctuation.definition.template-expression.begin: #569CD6" } }, { "c": " ", "t": "source.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "a", "t": "source.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts variable.other.readwrite.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": " ", "t": "source.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "*", "t": "source.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts keyword.operator.arithmetic.ts", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "b", "t": "source.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts variable.other.readwrite.ts", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": " ", "t": "source.ts string.template.ts meta.template.expression.ts meta.embedded.line.ts", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "}", "t": "source.ts string.template.ts meta.template.expression.ts punctuation.definition.template-expression.end.ts", "r": { "dark_plus": "punctuation.definition.template-expression.end: #569CD6", "light_plus": "punctuation.definition.template-expression.end: #0000FF", "dark_vs": "punctuation.definition.template-expression.end: #569CD6", "light_vs": "punctuation.definition.template-expression.end: #0000FF", "hc_black": "punctuation.definition.template-expression.end: #569CD6" } }, { "c": "`", "t": "source.ts string.template.ts punctuation.definition.string.template.end.ts", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": ";", "t": "source.ts punctuation.terminator.statement.ts", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } } ]
extensions/typescript-basics/test/colorize-results/test-strings_ts.json
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017865808331407607, 0.00017375384049955755, 0.00016905977099668235, 0.00017392903100699186, 0.0000022940962480788585 ]
{ "id": 6, "code_window": [ "import { IExtensionTipsService, IExtensionManagementServerService } from 'vs/platform/extensionManagement/common/extensionManagement';\n", "import { IThemeService } from 'vs/platform/theme/common/themeService';\n", "import { INotificationService } from 'vs/platform/notification/common/notification';\n", "import { createCancelablePromise } from 'vs/base/common/async';\n", "\n", "export interface ITemplateData {\n", "\troot: HTMLElement;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/parts/extensions/electron-browser/extensionsList.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. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { localize } from 'vs/nls'; import { append, $, addClass, removeClass, toggleClass } from 'vs/base/browser/dom'; import { IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle'; import { Action } from 'vs/base/common/actions'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { IPagedRenderer } from 'vs/base/browser/ui/list/listPaging'; import { once } from 'vs/base/common/event'; import { domEvent } from 'vs/base/browser/event'; import { IExtension, IExtensionsWorkbenchService } from 'vs/workbench/parts/extensions/common/extensions'; import { InstallAction, UpdateAction, ManageExtensionAction, ReloadAction, extensionButtonProminentBackground, extensionButtonProminentForeground, MaliciousStatusLabelAction, DisabledStatusLabelAction } from 'vs/workbench/parts/extensions/electron-browser/extensionsActions'; import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { Label, RatingsWidget, InstallCountWidget } from 'vs/workbench/parts/extensions/browser/extensionsWidgets'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IExtensionTipsService, IExtensionManagementServerService } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { createCancelablePromise } from 'vs/base/common/async'; export interface ITemplateData { root: HTMLElement; element: HTMLElement; icon: HTMLImageElement; name: HTMLElement; installCount: HTMLElement; ratings: HTMLElement; author: HTMLElement; description: HTMLElement; extension: IExtension; disposables: IDisposable[]; extensionDisposables: IDisposable[]; } export class Delegate implements IVirtualDelegate<IExtension> { getHeight() { return 62; } getTemplateId() { return 'extension'; } } const actionOptions = { icon: true, label: true }; export class Renderer implements IPagedRenderer<IExtension, ITemplateData> { constructor( @IInstantiationService private instantiationService: IInstantiationService, @INotificationService private notificationService: INotificationService, @IExtensionsWorkbenchService private extensionsWorkbenchService: IExtensionsWorkbenchService, @IExtensionService private extensionService: IExtensionService, @IExtensionTipsService private extensionTipsService: IExtensionTipsService, @IThemeService private themeService: IThemeService, @IExtensionManagementServerService private extensionManagementServerService: IExtensionManagementServerService ) { } get templateId() { return 'extension'; } renderTemplate(root: HTMLElement): ITemplateData { const bookmark = append(root, $('span.bookmark')); append(bookmark, $('span.octicon.octicon-star')); const applyBookmarkStyle = (theme) => { const bgColor = theme.getColor(extensionButtonProminentBackground); const fgColor = theme.getColor(extensionButtonProminentForeground); bookmark.style.borderTopColor = bgColor ? bgColor.toString() : 'transparent'; bookmark.style.color = fgColor ? fgColor.toString() : 'white'; }; applyBookmarkStyle(this.themeService.getTheme()); const bookmarkStyler = this.themeService.onThemeChange(applyBookmarkStyle.bind(this)); const element = append(root, $('.extension')); const icon = append(element, $<HTMLImageElement>('img.icon')); const details = append(element, $('.details')); const headerContainer = append(details, $('.header-container')); const header = append(headerContainer, $('.header')); const name = append(header, $('span.name')); const version = append(header, $('span.version')); const installCount = append(header, $('span.install-count')); const ratings = append(header, $('span.ratings')); const description = append(details, $('.description.ellipsis')); const footer = append(details, $('.footer')); const author = append(footer, $('.author.ellipsis')); const actionbar = new ActionBar(footer, { animated: false, actionItemProvider: (action: Action) => { if (action.id === ManageExtensionAction.ID) { return (<ManageExtensionAction>action).actionItem; } return null; } }); actionbar.onDidRun(({ error }) => error && this.notificationService.error(error)); const versionWidget = this.instantiationService.createInstance(Label, version, (e: IExtension) => e.version); const installCountWidget = this.instantiationService.createInstance(InstallCountWidget, installCount, { small: true }); const ratingsWidget = this.instantiationService.createInstance(RatingsWidget, ratings, { small: true }); const maliciousStatusAction = this.instantiationService.createInstance(MaliciousStatusLabelAction, false); const disabledStatusAction = this.instantiationService.createInstance(DisabledStatusLabelAction); const installAction = this.instantiationService.createInstance(InstallAction); const updateAction = this.instantiationService.createInstance(UpdateAction); const reloadAction = this.instantiationService.createInstance(ReloadAction); const manageAction = this.instantiationService.createInstance(ManageExtensionAction); actionbar.push([updateAction, reloadAction, installAction, disabledStatusAction, maliciousStatusAction, manageAction], actionOptions); const disposables = [versionWidget, installCountWidget, ratingsWidget, maliciousStatusAction, disabledStatusAction, updateAction, installAction, reloadAction, manageAction, actionbar, bookmarkStyler]; return { root, element, icon, name, installCount, ratings, author, description, disposables, extensionDisposables: [], set extension(extension: IExtension) { versionWidget.extension = extension; installCountWidget.extension = extension; ratingsWidget.extension = extension; maliciousStatusAction.extension = extension; disabledStatusAction.extension = extension; installAction.extension = extension; updateAction.extension = extension; reloadAction.extension = extension; manageAction.extension = extension; } }; } renderPlaceholder(index: number, data: ITemplateData): void { addClass(data.element, 'loading'); data.root.removeAttribute('aria-label'); data.extensionDisposables = dispose(data.extensionDisposables); data.icon.src = ''; data.name.textContent = ''; data.author.textContent = ''; data.description.textContent = ''; data.installCount.style.display = 'none'; data.ratings.style.display = 'none'; data.extension = null; } renderElement(extension: IExtension, index: number, data: ITemplateData): void { removeClass(data.element, 'loading'); data.extensionDisposables = dispose(data.extensionDisposables); const installed = this.extensionsWorkbenchService.local.filter(e => e.id === extension.id)[0]; this.extensionService.getExtensions().then(runningExtensions => { if (installed && installed.local) { const installedExtensionServer = this.extensionManagementServerService.getExtensionManagementServer(installed.local.location); const isSameExtensionRunning = runningExtensions.some(e => areSameExtensions(e, extension) && installedExtensionServer.authority === this.extensionManagementServerService.getExtensionManagementServer(e.extensionLocation).authority); toggleClass(data.root, 'disabled', !isSameExtensionRunning); } else { removeClass(data.root, 'disabled'); } }); const onError = once(domEvent(data.icon, 'error')); onError(() => data.icon.src = extension.iconUrlFallback, null, data.extensionDisposables); data.icon.src = extension.iconUrl; if (!data.icon.complete) { data.icon.style.visibility = 'hidden'; data.icon.onload = () => data.icon.style.visibility = 'inherit'; } else { data.icon.style.visibility = 'inherit'; } this.updateRecommendationStatus(extension, data); data.extensionDisposables.push(this.extensionTipsService.onRecommendationChange(change => { if (change.extensionId.toLowerCase() === extension.id.toLowerCase()) { this.updateRecommendationStatus(extension, data); } })); data.name.textContent = extension.displayName; data.author.textContent = extension.publisherDisplayName; data.description.textContent = extension.description; data.installCount.style.display = ''; data.ratings.style.display = ''; data.extension = extension; const manifestPromise = createCancelablePromise(token => extension.getManifest(token).then(manifest => { if (manifest) { const name = manifest && manifest.contributes && manifest.contributes.localizations && manifest.contributes.localizations.length > 0 && manifest.contributes.localizations[0].localizedLanguageName; if (name) { data.description.textContent = name[0].toLocaleUpperCase() + name.slice(1); } } })); data.disposables.push(toDisposable(() => manifestPromise.cancel())); } disposeElement(): void { // noop } private updateRecommendationStatus(extension: IExtension, data: ITemplateData) { const extRecommendations = this.extensionTipsService.getAllRecommendationsWithReason(); let ariaLabel = extension.displayName + '. '; if (!extRecommendations[extension.id.toLowerCase()]) { removeClass(data.root, 'recommended'); data.root.title = ''; } else { addClass(data.root, 'recommended'); ariaLabel += extRecommendations[extension.id.toLowerCase()].reasonText + ' '; data.root.title = extRecommendations[extension.id.toLowerCase()].reasonText; } ariaLabel += localize('viewExtensionDetailsAria', "Press enter for extension details."); data.root.setAttribute('aria-label', ariaLabel); } disposeTemplate(data: ITemplateData): void { data.disposables = dispose(data.disposables); } }
src/vs/workbench/parts/extensions/electron-browser/extensionsList.ts
1
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.9991695880889893, 0.317982941865921, 0.0001647599128773436, 0.0002183391188737005, 0.4650760889053345 ]
{ "id": 6, "code_window": [ "import { IExtensionTipsService, IExtensionManagementServerService } from 'vs/platform/extensionManagement/common/extensionManagement';\n", "import { IThemeService } from 'vs/platform/theme/common/themeService';\n", "import { INotificationService } from 'vs/platform/notification/common/notification';\n", "import { createCancelablePromise } from 'vs/base/common/async';\n", "\n", "export interface ITemplateData {\n", "\troot: HTMLElement;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/parts/extensions/electron-browser/extensionsList.ts", "type": "replace", "edit_start_line_idx": 25 }
# Steps to publish a new version of monaco-editor-core ## Generate monaco.d.ts * The `monaco.d.ts` is now automatically generated when running `gulp watch` ## Bump version * increase version in `build/monaco/package.json` ## Generate npm contents for monaco-editor-core * Be sure to have all changes committed **and pushed to the remote** * (the generated files contain the HEAD sha and that should be available on the remote) * run gulp editor-distro ## Publish * `cd out-monaco-editor-core` * `npm publish`
build/monaco/README.md
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017398504132870585, 0.0001725263864500448, 0.00017176501569338143, 0.00017182905867230147, 0.0000010317663736714167 ]
{ "id": 6, "code_window": [ "import { IExtensionTipsService, IExtensionManagementServerService } from 'vs/platform/extensionManagement/common/extensionManagement';\n", "import { IThemeService } from 'vs/platform/theme/common/themeService';\n", "import { INotificationService } from 'vs/platform/notification/common/notification';\n", "import { createCancelablePromise } from 'vs/base/common/async';\n", "\n", "export interface ITemplateData {\n", "\troot: HTMLElement;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/parts/extensions/electron-browser/extensionsList.ts", "type": "replace", "edit_start_line_idx": 25 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#2d2d30}.icon-vs-out{fill:#2d2d30}.icon-vs-action-blue{fill:#75beff}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M9 14V8H7v6H1V2h14v12H9z" id="outline" style="display: none;"/><path class="icon-vs-action-blue" d="M10 9h4v4h-4V9zm-8 4h4V9H2v4zM2 3v4h12V3H2z" id="iconBg"/></svg>
src/vs/editor/contrib/documentSymbols/media/Structure_16x_vscode_inverse.svg
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017498726083431393, 0.00017498726083431393, 0.00017498726083431393, 0.00017498726083431393, 0 ]
{ "id": 6, "code_window": [ "import { IExtensionTipsService, IExtensionManagementServerService } from 'vs/platform/extensionManagement/common/extensionManagement';\n", "import { IThemeService } from 'vs/platform/theme/common/themeService';\n", "import { INotificationService } from 'vs/platform/notification/common/notification';\n", "import { createCancelablePromise } from 'vs/base/common/async';\n", "\n", "export interface ITemplateData {\n", "\troot: HTMLElement;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/parts/extensions/electron-browser/extensionsList.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. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import { ok } from 'vs/base/common/assert'; suite('Assert', () => { test('ok', function () { assert.throws(function () { ok(false); }); assert.throws(function () { ok(null); }); assert.throws(function () { ok(); }); assert.throws(function () { ok(null, 'Foo Bar'); }, function (e: Error) { return e.message.indexOf('Foo Bar') >= 0; }); ok(true); ok('foo'); ok({}); ok(5); }); });
src/vs/base/test/common/assert.test.ts
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017622044833842665, 0.000174131739186123, 0.00017316083540208638, 0.00017357285832986236, 0.0000012179078794360976 ]
{ "id": 7, "code_window": [ "\t\tdata.ratings.style.display = '';\n", "\t\tdata.extension = extension;\n", "\n", "\t\tconst manifestPromise = createCancelablePromise(token => extension.getManifest(token).then(manifest => {\n", "\t\t\tif (manifest) {\n", "\t\t\t\tconst name = manifest && manifest.contributes && manifest.contributes.localizations && manifest.contributes.localizations.length > 0 && manifest.contributes.localizations[0].localizedLanguageName;\n", "\t\t\t\tif (name) { data.description.textContent = name[0].toLocaleUpperCase() + name.slice(1); }\n", "\t\t\t}\n", "\t\t}));\n", "\t\tdata.disposables.push(toDisposable(() => manifestPromise.cancel()));\n", "\t}\n", "\n", "\tdisposeElement(): void {\n", "\t\t// noop\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (extension.gallery && extension.gallery.properties && extension.gallery.properties.localizedLanguages && extension.gallery.properties.localizedLanguages.length) {\n", "\t\t\tdata.description.textContent = extension.gallery.properties.localizedLanguages.map(name => name[0].toLocaleUpperCase() + name.slice(1)).join(', ');\n", "\t\t}\n" ], "file_path": "src/vs/workbench/parts/extensions/electron-browser/extensionsList.ts", "type": "replace", "edit_start_line_idx": 183 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { tmpdir } from 'os'; import * as path from 'path'; import { TPromise } from 'vs/base/common/winjs.base'; import { distinct } from 'vs/base/common/arrays'; import { getErrorMessage, isPromiseCanceledError, canceled } from 'vs/base/common/errors'; import { StatisticType, IGalleryExtension, IExtensionGalleryService, IGalleryExtensionAsset, IQueryOptions, SortBy, SortOrder, IExtensionManifest, IExtensionIdentifier, IReportedExtension, InstallOperation, ITranslation } from 'vs/platform/extensionManagement/common/extensionManagement'; import { getGalleryExtensionId, getGalleryExtensionTelemetryData, adoptToGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { assign, getOrDefault } from 'vs/base/common/objects'; import { IRequestService } from 'vs/platform/request/node/request'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IPager } from 'vs/base/common/paging'; import { IRequestOptions, IRequestContext, download, asJson, asText } from 'vs/base/node/request'; import pkg from 'vs/platform/node/package'; import product from 'vs/platform/node/product'; import { isEngineValid } from 'vs/platform/extensions/node/extensionValidator'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { readFile } from 'vs/base/node/pfs'; import { writeFileAndFlushSync } from 'vs/base/node/extfs'; import { generateUuid, isUUID } from 'vs/base/common/uuid'; import { values } from 'vs/base/common/map'; import { CancellationToken } from 'vs/base/common/cancellation'; interface IRawGalleryExtensionFile { assetType: string; source: string; } interface IRawGalleryExtensionProperty { key: string; value: string; } interface IRawGalleryExtensionVersion { version: string; lastUpdated: string; assetUri: string; fallbackAssetUri: string; files: IRawGalleryExtensionFile[]; properties?: IRawGalleryExtensionProperty[]; } interface IRawGalleryExtensionStatistics { statisticName: string; value: number; } interface IRawGalleryExtension { extensionId: string; extensionName: string; displayName: string; shortDescription: string; publisher: { displayName: string, publisherId: string, publisherName: string; }; versions: IRawGalleryExtensionVersion[]; statistics: IRawGalleryExtensionStatistics[]; flags: string; } interface IRawGalleryQueryResult { results: { extensions: IRawGalleryExtension[]; resultMetadata: { metadataType: string; metadataItems: { name: string; count: number; }[]; }[] }[]; } enum Flags { None = 0x0, IncludeVersions = 0x1, IncludeFiles = 0x2, IncludeCategoryAndTags = 0x4, IncludeSharedAccounts = 0x8, IncludeVersionProperties = 0x10, ExcludeNonValidated = 0x20, IncludeInstallationTargets = 0x40, IncludeAssetUri = 0x80, IncludeStatistics = 0x100, IncludeLatestVersionOnly = 0x200, Unpublished = 0x1000 } function flagsToString(...flags: Flags[]): string { return String(flags.reduce((r, f) => r | f, 0)); } enum FilterType { Tag = 1, ExtensionId = 4, Category = 5, ExtensionName = 7, Target = 8, Featured = 9, SearchText = 10, ExcludeWithFlags = 12 } const AssetType = { Icon: 'Microsoft.VisualStudio.Services.Icons.Default', Details: 'Microsoft.VisualStudio.Services.Content.Details', Changelog: 'Microsoft.VisualStudio.Services.Content.Changelog', Manifest: 'Microsoft.VisualStudio.Code.Manifest', VSIX: 'Microsoft.VisualStudio.Services.VSIXPackage', License: 'Microsoft.VisualStudio.Services.Content.License', Repository: 'Microsoft.VisualStudio.Services.Links.Source' }; const PropertyType = { Dependency: 'Microsoft.VisualStudio.Code.ExtensionDependencies', ExtensionPack: 'Microsoft.VisualStudio.Code.ExtensionPack', Engine: 'Microsoft.VisualStudio.Code.Engine' }; interface ICriterium { filterType: FilterType; value?: string; } const DefaultPageSize = 10; interface IQueryState { pageNumber: number; pageSize: number; sortBy: SortBy; sortOrder: SortOrder; flags: Flags; criteria: ICriterium[]; assetTypes: string[]; } const DefaultQueryState: IQueryState = { pageNumber: 1, pageSize: DefaultPageSize, sortBy: SortBy.NoneOrRelevance, sortOrder: SortOrder.Default, flags: Flags.None, criteria: [], assetTypes: [] }; class Query { constructor(private state = DefaultQueryState) { } get pageNumber(): number { return this.state.pageNumber; } get pageSize(): number { return this.state.pageSize; } get sortBy(): number { return this.state.sortBy; } get sortOrder(): number { return this.state.sortOrder; } get flags(): number { return this.state.flags; } withPage(pageNumber: number, pageSize: number = this.state.pageSize): Query { return new Query(assign({}, this.state, { pageNumber, pageSize })); } withFilter(filterType: FilterType, ...values: string[]): Query { const criteria = [ ...this.state.criteria, ...values.map(value => ({ filterType, value })) ]; return new Query(assign({}, this.state, { criteria })); } withSortBy(sortBy: SortBy): Query { return new Query(assign({}, this.state, { sortBy })); } withSortOrder(sortOrder: SortOrder): Query { return new Query(assign({}, this.state, { sortOrder })); } withFlags(...flags: Flags[]): Query { return new Query(assign({}, this.state, { flags: flags.reduce((r, f) => r | f, 0) })); } withAssetTypes(...assetTypes: string[]): Query { return new Query(assign({}, this.state, { assetTypes })); } get raw(): any { const { criteria, pageNumber, pageSize, sortBy, sortOrder, flags, assetTypes } = this.state; const filters = [{ criteria, pageNumber, pageSize, sortBy, sortOrder }]; return { filters, assetTypes, flags }; } get searchText(): string { const criterium = this.state.criteria.filter(criterium => criterium.filterType === FilterType.SearchText)[0]; return criterium ? criterium.value : ''; } } function getStatistic(statistics: IRawGalleryExtensionStatistics[], name: string): number { const result = (statistics || []).filter(s => s.statisticName === name)[0]; return result ? result.value : 0; } function getCoreTranslationAssets(version: IRawGalleryExtensionVersion): { [languageId: string]: IGalleryExtensionAsset } { const coreTranslationAssetPrefix = 'Microsoft.VisualStudio.Code.Translation.'; const result = version.files.filter(f => f.assetType.indexOf(coreTranslationAssetPrefix) === 0); return result.reduce((result, file) => { result[file.assetType.substring(coreTranslationAssetPrefix.length)] = getVersionAsset(version, file.assetType); return result; }, {}); } function getVersionAsset(version: IRawGalleryExtensionVersion, type: string): IGalleryExtensionAsset { const result = version.files.filter(f => f.assetType === type)[0]; if (type === AssetType.Repository) { if (version.properties) { const results = version.properties.filter(p => p.key === type); const gitRegExp = new RegExp('((git|ssh|http(s)?)|(git@[\w\.]+))(:(//)?)([\w\.@\:/\-~]+)(\.git)(/)?'); const uri = results.filter(r => gitRegExp.test(r.value))[0]; if (!uri) { return { uri: null, fallbackUri: null }; } return { uri: uri.value, fallbackUri: uri.value, }; } } if (!result) { if (type === AssetType.Icon) { const uri = require.toUrl('./media/defaultIcon.png'); return { uri, fallbackUri: uri }; } if (type === AssetType.Repository) { return { uri: null, fallbackUri: null }; } return null; } if (type === AssetType.VSIX) { return { uri: `${version.fallbackAssetUri}/${type}?redirect=true`, fallbackUri: `${version.fallbackAssetUri}/${type}` }; } return { uri: `${version.assetUri}/${type}`, fallbackUri: `${version.fallbackAssetUri}/${type}` }; } function getExtensions(version: IRawGalleryExtensionVersion, property: string): string[] { const values = version.properties ? version.properties.filter(p => p.key === property) : []; const value = values.length > 0 && values[0].value; return value ? value.split(',').map(v => adoptToGalleryExtensionId(v)) : []; } function getEngine(version: IRawGalleryExtensionVersion): string { const values = version.properties ? version.properties.filter(p => p.key === PropertyType.Engine) : []; return (values.length > 0 && values[0].value) || ''; } function getIsPreview(flags: string): boolean { return flags.indexOf('preview') !== -1; } function toExtension(galleryExtension: IRawGalleryExtension, version: IRawGalleryExtensionVersion, index: number, query: Query, querySource?: string): IGalleryExtension { const assets = { manifest: getVersionAsset(version, AssetType.Manifest), readme: getVersionAsset(version, AssetType.Details), changelog: getVersionAsset(version, AssetType.Changelog), download: getVersionAsset(version, AssetType.VSIX), icon: getVersionAsset(version, AssetType.Icon), license: getVersionAsset(version, AssetType.License), repository: getVersionAsset(version, AssetType.Repository), coreTranslations: getCoreTranslationAssets(version) }; return { identifier: { id: getGalleryExtensionId(galleryExtension.publisher.publisherName, galleryExtension.extensionName), uuid: galleryExtension.extensionId }, name: galleryExtension.extensionName, version: version.version, date: version.lastUpdated, displayName: galleryExtension.displayName, publisherId: galleryExtension.publisher.publisherId, publisher: galleryExtension.publisher.publisherName, publisherDisplayName: galleryExtension.publisher.displayName, description: galleryExtension.shortDescription || '', installCount: getStatistic(galleryExtension.statistics, 'install') + getStatistic(galleryExtension.statistics, 'updateCount'), rating: getStatistic(galleryExtension.statistics, 'averagerating'), ratingCount: getStatistic(galleryExtension.statistics, 'ratingcount'), assets, properties: { dependencies: getExtensions(version, PropertyType.Dependency), extensionPack: getExtensions(version, PropertyType.ExtensionPack), engine: getEngine(version) }, /* __GDPR__FRAGMENT__ "GalleryExtensionTelemetryData2" : { "index" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "searchText": { "classification": "CustomerContent", "purpose": "FeatureInsight" }, "querySource": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ telemetryData: { index: ((query.pageNumber - 1) * query.pageSize) + index, searchText: query.searchText, querySource }, preview: getIsPreview(galleryExtension.flags) }; } interface IRawExtensionsReport { malicious: string[]; slow: string[]; } export class ExtensionGalleryService implements IExtensionGalleryService { _serviceBrand: any; private extensionsGalleryUrl: string; private extensionsControlUrl: string; private readonly commonHeadersPromise: TPromise<{ [key: string]: string; }>; constructor( @IRequestService private requestService: IRequestService, @IEnvironmentService private environmentService: IEnvironmentService, @ITelemetryService private telemetryService: ITelemetryService ) { const config = product.extensionsGallery; this.extensionsGalleryUrl = config && config.serviceUrl; this.extensionsControlUrl = config && config.controlUrl; this.commonHeadersPromise = resolveMarketplaceHeaders(this.environmentService); } private api(path = ''): string { return `${this.extensionsGalleryUrl}${path}`; } isEnabled(): boolean { return !!this.extensionsGalleryUrl; } getExtension({ id, uuid }: IExtensionIdentifier, version?: string): TPromise<IGalleryExtension> { let query = new Query() .withFlags(Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, 1) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)); if (uuid) { query = query.withFilter(FilterType.ExtensionId, uuid); } else { query = query.withFilter(FilterType.ExtensionName, id); } return this.queryGallery(query, CancellationToken.None).then(({ galleryExtensions }) => { if (galleryExtensions.length) { const galleryExtension = galleryExtensions[0]; const versionAsset = version ? galleryExtension.versions.filter(v => v.version === version)[0] : galleryExtension.versions[0]; if (versionAsset) { return toExtension(galleryExtension, versionAsset, 0, query); } } return null; }); } query(options: IQueryOptions = {}): TPromise<IPager<IGalleryExtension>> { if (!this.isEnabled()) { return TPromise.wrapError<IPager<IGalleryExtension>>(new Error('No extension gallery service configured.')); } const type = options.names ? 'ids' : (options.text ? 'text' : 'all'); let text = options.text || ''; const pageSize = getOrDefault(options, o => o.pageSize, 50); /* __GDPR__ "galleryService:query" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "text": { "classification": "CustomerContent", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:query', { type, text }); let query = new Query() .withFlags(Flags.IncludeLatestVersionOnly, Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, pageSize) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)); if (text) { // Use category filter instead of "category:themes" text = text.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedCategory, category) => { query = query.withFilter(FilterType.Category, category || quotedCategory); return ''; }); // Use tag filter instead of "tag:debuggers" text = text.replace(/\btag:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedTag, tag) => { query = query.withFilter(FilterType.Tag, tag || quotedTag); return ''; }); text = text.trim(); if (text) { text = text.length < 200 ? text : text.substring(0, 200); query = query.withFilter(FilterType.SearchText, text); } query = query.withSortBy(SortBy.NoneOrRelevance); } else if (options.ids) { query = query.withFilter(FilterType.ExtensionId, ...options.ids); } else if (options.names) { query = query.withFilter(FilterType.ExtensionName, ...options.names); } else { query = query.withSortBy(SortBy.InstallCount); } if (typeof options.sortBy === 'number') { query = query.withSortBy(options.sortBy); } if (typeof options.sortOrder === 'number') { query = query.withSortOrder(options.sortOrder); } return this.queryGallery(query, CancellationToken.None).then(({ galleryExtensions, total }) => { const extensions = galleryExtensions.map((e, index) => toExtension(e, e.versions[0], index, query, options.source)); const pageSize = query.pageSize; const getPage = (pageIndex: number, ct: CancellationToken) => { if (ct.isCancellationRequested) { return TPromise.wrapError(canceled()); } const nextPageQuery = query.withPage(pageIndex + 1); return this.queryGallery(nextPageQuery, ct) .then(({ galleryExtensions }) => galleryExtensions.map((e, index) => toExtension(e, e.versions[0], index, nextPageQuery, options.source))); }; return { firstPage: extensions, total, pageSize, getPage } as IPager<IGalleryExtension>; }); } private queryGallery(query: Query, token: CancellationToken): TPromise<{ galleryExtensions: IRawGalleryExtension[], total: number; }> { return this.commonHeadersPromise.then(commonHeaders => { const data = JSON.stringify(query.raw); const headers = assign({}, commonHeaders, { 'Content-Type': 'application/json', 'Accept': 'application/json;api-version=3.0-preview.1', 'Accept-Encoding': 'gzip', 'Content-Length': data.length }); return this.requestService.request({ type: 'POST', url: this.api('/extensionquery'), data, headers }, token).then(context => { if (context.res.statusCode >= 400 && context.res.statusCode < 500) { return { galleryExtensions: [], total: 0 }; } return asJson<IRawGalleryQueryResult>(context).then(result => { const r = result.results[0]; const galleryExtensions = r.extensions; const resultCount = r.resultMetadata && r.resultMetadata.filter(m => m.metadataType === 'ResultCount')[0]; const total = resultCount && resultCount.metadataItems.filter(i => i.name === 'TotalCount')[0].count || 0; return { galleryExtensions, total }; }); }); }); } reportStatistic(publisher: string, name: string, version: string, type: StatisticType): TPromise<void> { if (!this.isEnabled()) { return TPromise.as(null); } return this.commonHeadersPromise.then(commonHeaders => { const headers = { ...commonHeaders, Accept: '*/*;api-version=4.0-preview.1' }; return this.requestService.request({ type: 'POST', url: this.api(`/publishers/${publisher}/extensions/${name}/${version}/stats?statType=${type}`), headers }, CancellationToken.None).then(null, () => null); }); } download(extension: IGalleryExtension, operation: InstallOperation): TPromise<string> { const zipPath = path.join(tmpdir(), generateUuid()); const data = getGalleryExtensionTelemetryData(extension); const startTime = new Date().getTime(); /* __GDPR__ "galleryService:downloadVSIX" : { "duration": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true }, "${include}": [ "${GalleryExtensionTelemetryData}" ] } */ const log = (duration: number) => this.telemetryService.publicLog('galleryService:downloadVSIX', assign(data, { duration })); const operationParam = operation === InstallOperation.Install ? 'install' : operation === InstallOperation.Update ? 'update' : ''; const downloadAsset = operationParam ? { uri: `${extension.assets.download.uri}&${operationParam}=true`, fallbackUri: `${extension.assets.download.fallbackUri}?${operationParam}=true` } : extension.assets.download; return this.getAsset(downloadAsset) .then(context => download(zipPath, context)) .then(() => log(new Date().getTime() - startTime)) .then(() => zipPath); } getReadme(extension: IGalleryExtension, token: CancellationToken): TPromise<string> { return this.getAsset(extension.assets.readme, {}, token) .then(asText); } getManifest(extension: IGalleryExtension, token: CancellationToken): TPromise<IExtensionManifest> { return this.getAsset(extension.assets.manifest, {}, token) .then(asText) .then(JSON.parse); } getCoreTranslation(extension: IGalleryExtension, languageId: string): TPromise<ITranslation> { const asset = extension.assets.coreTranslations[languageId.toUpperCase()]; if (asset) { return this.getAsset(asset) .then(asText) .then(JSON.parse); } return TPromise.as(null); } getChangelog(extension: IGalleryExtension, token: CancellationToken): TPromise<string> { return this.getAsset(extension.assets.changelog, {}, token) .then(asText); } loadAllDependencies(extensions: IExtensionIdentifier[], token: CancellationToken): TPromise<IGalleryExtension[]> { return this.getDependenciesReccursively(extensions.map(e => e.id), [], token); } loadCompatibleVersion(extension: IGalleryExtension): TPromise<IGalleryExtension> { if (extension.properties.engine && isEngineValid(extension.properties.engine)) { return TPromise.wrap(extension); } const query = new Query() .withFlags(Flags.IncludeVersions, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, 1) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)) .withAssetTypes(AssetType.Manifest, AssetType.VSIX) .withFilter(FilterType.ExtensionId, extension.identifier.uuid); return this.queryGallery(query, CancellationToken.None) .then(({ galleryExtensions }) => { const [rawExtension] = galleryExtensions; if (!rawExtension) { return null; } return this.getLastValidExtensionVersion(rawExtension, rawExtension.versions) .then(rawVersion => { if (rawVersion) { extension.properties.dependencies = getExtensions(rawVersion, PropertyType.Dependency); extension.properties.engine = getEngine(rawVersion); extension.assets.download = getVersionAsset(rawVersion, AssetType.VSIX); extension.version = rawVersion.version; return extension; } return null; }); }); } private loadDependencies(extensionNames: string[], token: CancellationToken): TPromise<IGalleryExtension[]> { if (!extensionNames || extensionNames.length === 0) { return TPromise.as([]); } let query = new Query() .withFlags(Flags.IncludeLatestVersionOnly, Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties) .withPage(1, extensionNames.length) .withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code') .withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished)) .withAssetTypes(AssetType.Icon, AssetType.License, AssetType.Details, AssetType.Manifest, AssetType.VSIX) .withFilter(FilterType.ExtensionName, ...extensionNames); return this.queryGallery(query, token).then(result => { const dependencies = []; const ids = []; for (let index = 0; index < result.galleryExtensions.length; index++) { const rawExtension = result.galleryExtensions[index]; if (ids.indexOf(rawExtension.extensionId) === -1) { dependencies.push(toExtension(rawExtension, rawExtension.versions[0], index, query, 'dependencies')); ids.push(rawExtension.extensionId); } } return dependencies; }); } private getDependenciesReccursively(toGet: string[], result: IGalleryExtension[], token: CancellationToken): TPromise<IGalleryExtension[]> { if (!toGet || !toGet.length) { return TPromise.wrap(result); } toGet = result.length ? toGet.filter(e => !ExtensionGalleryService.hasExtensionByName(result, e)) : toGet; if (!toGet.length) { return TPromise.wrap(result); } return this.loadDependencies(toGet, token) .then(loadedDependencies => { const dependenciesSet = new Set<string>(); for (const dep of loadedDependencies) { if (dep.properties.dependencies) { dep.properties.dependencies.forEach(d => dependenciesSet.add(d)); } } result = distinct(result.concat(loadedDependencies), d => d.identifier.uuid); const dependencies: string[] = []; dependenciesSet.forEach(d => !ExtensionGalleryService.hasExtensionByName(result, d) && dependencies.push(d)); return this.getDependenciesReccursively(dependencies, result, token); }); } private getAsset(asset: IGalleryExtensionAsset, options: IRequestOptions = {}, token: CancellationToken = CancellationToken.None): TPromise<IRequestContext> { return this.commonHeadersPromise.then(commonHeaders => { const baseOptions = { type: 'GET' }; const headers = assign({}, commonHeaders, options.headers || {}); options = assign({}, options, baseOptions, { headers }); const url = asset.uri; const fallbackUrl = asset.fallbackUri; const firstOptions = assign({}, options, { url }); return this.requestService.request(firstOptions, token) .then(context => { if (context.res.statusCode === 200) { return TPromise.as(context); } return asText(context) .then(message => TPromise.wrapError<IRequestContext>(new Error(`Expected 200, got back ${context.res.statusCode} instead.\n\n${message}`))); }) .then(null, err => { if (isPromiseCanceledError(err)) { return TPromise.wrapError<IRequestContext>(err); } const message = getErrorMessage(err); /* __GDPR__ "galleryService:requestError" : { "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "cdn": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:requestError', { url, cdn: true, message }); /* __GDPR__ "galleryService:cdnFallback" : { "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "message": { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:cdnFallback', { url, message }); const fallbackOptions = assign({}, options, { url: fallbackUrl }); return this.requestService.request(fallbackOptions, token).then(null, err => { if (isPromiseCanceledError(err)) { return TPromise.wrapError<IRequestContext>(err); } const message = getErrorMessage(err); /* __GDPR__ "galleryService:requestError" : { "url" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "cdn": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "message": { "classification": "CallstackOrException", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('galleryService:requestError', { url: fallbackUrl, cdn: false, message }); return TPromise.wrapError<IRequestContext>(err); }); }); }); } private getLastValidExtensionVersion(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> { const version = this.getLastValidExtensionVersionFromProperties(extension, versions); if (version) { return version; } return this.getLastValidExtensionVersionReccursively(extension, versions); } private getLastValidExtensionVersionFromProperties(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> { for (const version of versions) { const engine = getEngine(version); if (!engine) { return null; } if (isEngineValid(engine)) { return TPromise.wrap(version); } } return null; } private getLastValidExtensionVersionReccursively(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): TPromise<IRawGalleryExtensionVersion> { if (!versions.length) { return null; } const version = versions[0]; const asset = getVersionAsset(version, AssetType.Manifest); const headers = { 'Accept-Encoding': 'gzip' }; return this.getAsset(asset, { headers }) .then(context => asJson<IExtensionManifest>(context)) .then(manifest => { const engine = manifest.engines.vscode; if (!isEngineValid(engine)) { return this.getLastValidExtensionVersionReccursively(extension, versions.slice(1)); } version.properties = version.properties || []; version.properties.push({ key: PropertyType.Engine, value: manifest.engines.vscode }); return version; }); } private static hasExtensionByName(extensions: IGalleryExtension[], name: string): boolean { for (const extension of extensions) { if (`${extension.publisher}.${extension.name}` === name) { return true; } } return false; } getExtensionsReport(): TPromise<IReportedExtension[]> { if (!this.isEnabled()) { return TPromise.wrapError(new Error('No extension gallery service configured.')); } if (!this.extensionsControlUrl) { return TPromise.as([]); } return this.requestService.request({ type: 'GET', url: this.extensionsControlUrl }, CancellationToken.None).then(context => { if (context.res.statusCode !== 200) { return TPromise.wrapError(new Error('Could not get extensions report.')); } return asJson<IRawExtensionsReport>(context).then(result => { const map = new Map<string, IReportedExtension>(); for (const id of result.malicious) { const ext = map.get(id) || { id: { id }, malicious: true, slow: false }; ext.malicious = true; map.set(id, ext); } return TPromise.as(values(map)); }); }); } } export function resolveMarketplaceHeaders(environmentService: IEnvironmentService): TPromise<{ [key: string]: string; }> { const marketplaceMachineIdFile = path.join(environmentService.userDataPath, 'machineid'); return readFile(marketplaceMachineIdFile, 'utf8').then(contents => { if (isUUID(contents)) { return contents; } return TPromise.wrap(null); // invalid marketplace UUID }, error => { return TPromise.wrap(null); // error reading ID file }).then(uuid => { if (!uuid) { uuid = generateUuid(); try { writeFileAndFlushSync(marketplaceMachineIdFile, uuid); } catch (error) { //noop } } return { 'X-Market-Client-Id': `VSCode ${pkg.version}`, 'User-Agent': `VSCode ${pkg.version}`, 'X-Market-User-Id': uuid }; }); }
src/vs/platform/extensionManagement/node/extensionGalleryService.ts
1
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.0019042686326429248, 0.0002464225690346211, 0.0001590786559972912, 0.00017056005890481174, 0.00029166656895540655 ]
{ "id": 7, "code_window": [ "\t\tdata.ratings.style.display = '';\n", "\t\tdata.extension = extension;\n", "\n", "\t\tconst manifestPromise = createCancelablePromise(token => extension.getManifest(token).then(manifest => {\n", "\t\t\tif (manifest) {\n", "\t\t\t\tconst name = manifest && manifest.contributes && manifest.contributes.localizations && manifest.contributes.localizations.length > 0 && manifest.contributes.localizations[0].localizedLanguageName;\n", "\t\t\t\tif (name) { data.description.textContent = name[0].toLocaleUpperCase() + name.slice(1); }\n", "\t\t\t}\n", "\t\t}));\n", "\t\tdata.disposables.push(toDisposable(() => manifestPromise.cancel()));\n", "\t}\n", "\n", "\tdisposeElement(): void {\n", "\t\t// noop\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (extension.gallery && extension.gallery.properties && extension.gallery.properties.localizedLanguages && extension.gallery.properties.localizedLanguages.length) {\n", "\t\t\tdata.description.textContent = extension.gallery.properties.localizedLanguages.map(name => name[0].toLocaleUpperCase() + name.slice(1)).join(', ');\n", "\t\t}\n" ], "file_path": "src/vs/workbench/parts/extensions/electron-browser/extensionsList.ts", "type": "replace", "edit_start_line_idx": 183 }
This is the summary line. It can't be too long. After I can write a much more detailed description without quite the same restrictions on length. # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. # On branch master # Your branch is up-to-date with 'origin/master'. # # Changes to be committed: # deleted: README.md # modified: index.less # new file: spec/COMMIT_EDITMSG #
extensions/git/test/colorize-fixtures/COMMIT_EDITMSG
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017046870198100805, 0.00016987111303023994, 0.0001692735095275566, 0.00016987111303023994, 5.975962267257273e-7 ]
{ "id": 7, "code_window": [ "\t\tdata.ratings.style.display = '';\n", "\t\tdata.extension = extension;\n", "\n", "\t\tconst manifestPromise = createCancelablePromise(token => extension.getManifest(token).then(manifest => {\n", "\t\t\tif (manifest) {\n", "\t\t\t\tconst name = manifest && manifest.contributes && manifest.contributes.localizations && manifest.contributes.localizations.length > 0 && manifest.contributes.localizations[0].localizedLanguageName;\n", "\t\t\t\tif (name) { data.description.textContent = name[0].toLocaleUpperCase() + name.slice(1); }\n", "\t\t\t}\n", "\t\t}));\n", "\t\tdata.disposables.push(toDisposable(() => manifestPromise.cancel()));\n", "\t}\n", "\n", "\tdisposeElement(): void {\n", "\t\t// noop\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (extension.gallery && extension.gallery.properties && extension.gallery.properties.localizedLanguages && extension.gallery.properties.localizedLanguages.length) {\n", "\t\t\tdata.description.textContent = extension.gallery.properties.localizedLanguages.map(name => name[0].toLocaleUpperCase() + name.slice(1)).join(', ');\n", "\t\t}\n" ], "file_path": "src/vs/workbench/parts/extensions/electron-browser/extensionsList.ts", "type": "replace", "edit_start_line_idx": 183 }
{ "Region Start": { "prefix": "#region", "body": [ "#region $0" ], "description": "Folding Region Start" }, "Region End": { "prefix": "#endregion", "body": [ "#endregion" ], "description": "Folding Region End" } }
extensions/powershell/snippets/powershell.json
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00016918539768084884, 0.00016860399045981467, 0.0001680225832387805, 0.00016860399045981467, 5.814072210341692e-7 ]
{ "id": 7, "code_window": [ "\t\tdata.ratings.style.display = '';\n", "\t\tdata.extension = extension;\n", "\n", "\t\tconst manifestPromise = createCancelablePromise(token => extension.getManifest(token).then(manifest => {\n", "\t\t\tif (manifest) {\n", "\t\t\t\tconst name = manifest && manifest.contributes && manifest.contributes.localizations && manifest.contributes.localizations.length > 0 && manifest.contributes.localizations[0].localizedLanguageName;\n", "\t\t\t\tif (name) { data.description.textContent = name[0].toLocaleUpperCase() + name.slice(1); }\n", "\t\t\t}\n", "\t\t}));\n", "\t\tdata.disposables.push(toDisposable(() => manifestPromise.cancel()));\n", "\t}\n", "\n", "\tdisposeElement(): void {\n", "\t\t// noop\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (extension.gallery && extension.gallery.properties && extension.gallery.properties.localizedLanguages && extension.gallery.properties.localizedLanguages.length) {\n", "\t\t\tdata.description.textContent = extension.gallery.properties.localizedLanguages.map(name => name[0].toLocaleUpperCase() + name.slice(1)).join(', ');\n", "\t\t}\n" ], "file_path": "src/vs/workbench/parts/extensions/electron-browser/extensionsList.ts", "type": "replace", "edit_start_line_idx": 183 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { ExtensionContext, TextDocument, commands, ProviderResult, CancellationToken, workspace, tasks, Range, HoverProvider, Hover, Position, MarkdownString, Uri } from 'vscode'; import { createTask, startDebugging, findAllScriptRanges, extractDebugArgFromScript } from './tasks'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); let cachedDocument: Uri | undefined = undefined; let cachedScriptsMap: Map<string, [number, number, string]> | undefined = undefined; export function invalidateHoverScriptsCache(document?: TextDocument) { if (!document) { cachedDocument = undefined; return; } if (document.uri === cachedDocument) { cachedDocument = undefined; } } export class NpmScriptHoverProvider implements HoverProvider { private extensionContext: ExtensionContext; constructor(context: ExtensionContext) { this.extensionContext = context; context.subscriptions.push(commands.registerCommand('npm.runScriptFromHover', this.runScriptFromHover, this)); context.subscriptions.push(commands.registerCommand('npm.debugScriptFromHover', this.debugScriptFromHover, this)); } public provideHover(document: TextDocument, position: Position, _token: CancellationToken): ProviderResult<Hover> { let hover: Hover | undefined = undefined; if (!cachedDocument || cachedDocument.fsPath !== document.uri.fsPath) { cachedScriptsMap = findAllScriptRanges(document.getText()); cachedDocument = document.uri; } cachedScriptsMap!.forEach((value, key) => { let start = document.positionAt(value[0]); let end = document.positionAt(value[0] + value[1]); let range = new Range(start, end); if (range.contains(position)) { let contents: MarkdownString = new MarkdownString(); contents.isTrusted = true; contents.appendMarkdown(this.createRunScriptMarkdown(key, document.uri)); let debugArgs = extractDebugArgFromScript(value[2]); if (debugArgs) { contents.appendMarkdown(this.createDebugScriptMarkdown(key, document.uri, debugArgs[0], debugArgs[1])); } hover = new Hover(contents); } }); return hover; } private createRunScriptMarkdown(script: string, documentUri: Uri): string { let args = { documentUri: documentUri, script: script, }; return this.createMarkdownLink( localize('runScript', 'Run Script'), 'npm.runScriptFromHover', args, localize('runScript.tooltip', 'Run the script as a task') ); } private createDebugScriptMarkdown(script: string, documentUri: Uri, protocol: string, port: number): string { let args = { documentUri: documentUri, script: script, protocol: protocol, port: port }; return this.createMarkdownLink( localize('debugScript', 'Debug Script'), 'npm.debugScriptFromHover', args, localize('debugScript.tooltip', 'Runs the script under the debugger'), '|' ); } private createMarkdownLink(label: string, cmd: string, args: any, tooltip: string, separator?: string): string { let encodedArgs = encodeURIComponent(JSON.stringify(args)); let prefix = ''; if (separator) { prefix = ` ${separator} `; } return `${prefix}[${label}](command:${cmd}?${encodedArgs} "${tooltip}")`; } public runScriptFromHover(args: any) { let script = args.script; let documentUri = args.documentUri; let folder = workspace.getWorkspaceFolder(documentUri); if (folder) { let task = createTask(script, `run ${script}`, folder, documentUri); tasks.executeTask(task); } } public debugScriptFromHover(args: any) { let script = args.script; let documentUri = args.documentUri; let protocol = args.protocol; let port = args.port; let folder = workspace.getWorkspaceFolder(documentUri); if (folder) { startDebugging(script, protocol, port, folder); } } }
extensions/npm/src/scriptHover.ts
0
https://github.com/microsoft/vscode/commit/159762211cb777ba9b3aa7dc5e0630be71b5bd39
[ 0.00017442138050682843, 0.00017146681784652174, 0.00016916943422984332, 0.0001713410165393725, 0.0000014668163430542336 ]
{ "id": 0, "code_window": [ " }\n", "}\n", "\n", "export function esbuildPlugin(options: ESBuildOptions = {}): Plugin {\n", " const filter = createFilter(\n", " options.include || /\\.(tsx?|jsx)$/,\n", " options.exclude\n", " )\n", "\n", " return {\n", " name: 'vite:esbuild',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " options.include || /\\.(tsx?|jsx)($|\\?)/,\n" ], "file_path": "packages/vite/src/node/plugins/esbuild.ts", "type": "replace", "edit_start_line_idx": 99 }
import path from 'path' import chalk from 'chalk' import { Plugin } from '../plugin' import { Service, Message, Loader, TransformOptions, TransformResult } from 'esbuild' import { createDebugger, generateCodeFrame } from '../utils' import merge from 'merge-source-map' import { SourceMap } from 'rollup' import { ResolvedConfig } from '..' import { createFilter } from '@rollup/pluginutils' const debug = createDebugger('vite:esbuild') // lazy start the service let _servicePromise: Promise<Service> | undefined export interface ESBuildOptions extends TransformOptions { include?: string | RegExp | string[] | RegExp[] exclude?: string | RegExp | string[] | RegExp[] jsxInject?: string } export async function ensureService() { if (!_servicePromise) { _servicePromise = require('esbuild').startService() } return _servicePromise! } export async function stopService() { if (_servicePromise) { const service = await _servicePromise service.stop() _servicePromise = undefined } } export type EsbuildTransformResult = Omit<TransformResult, 'map'> & { map: SourceMap } export async function transformWithEsbuild( code: string, filename: string, options?: TransformOptions, inMap?: object ): Promise<EsbuildTransformResult> { const service = await ensureService() const resolvedOptions = { loader: path.extname(filename).slice(1) as Loader, sourcemap: true, // ensure source file name contains full query sourcefile: filename, ...options } as ESBuildOptions delete resolvedOptions.include delete resolvedOptions.exclude delete resolvedOptions.jsxInject try { const result = await service.transform(code, resolvedOptions) if (inMap) { const nextMap = JSON.parse(result.map) // merge-source-map will overwrite original sources if newMap also has // sourcesContent nextMap.sourcesContent = [] return { ...result, map: merge(inMap, nextMap) as SourceMap } } else { return { ...result, map: JSON.parse(result.map) } } } catch (e) { debug(`esbuild error with options used: `, resolvedOptions) // patch error information if (e.errors) { e.frame = '' e.errors.forEach((m: Message) => { e.frame += `\n` + prettifyMessage(m, code) }) e.loc = e.errors[0].location } throw e } } export function esbuildPlugin(options: ESBuildOptions = {}): Plugin { const filter = createFilter( options.include || /\.(tsx?|jsx)$/, options.exclude ) return { name: 'vite:esbuild', async transform(code, id) { if (filter(id)) { const result = await transformWithEsbuild(code, id, options) if (result.warnings.length) { result.warnings.forEach((m) => { this.warn(prettifyMessage(m, code)) }) } if (options.jsxInject) { result.code = options.jsxInject + ';' + result.code } return { code: result.code, map: result.map } } }, async closeBundle() { await stopService() } } } export const buildEsbuildPlugin = (config: ResolvedConfig): Plugin => { return { name: 'vite:esbuild-transpile', async renderChunk(code, chunk) { const target = config.build.target const minify = config.build.minify === 'esbuild' if (!target && !minify) { return null } return transformWithEsbuild(code, chunk.fileName, { target: target || undefined, minify }) }, async closeBundle() { await stopService() } } } function prettifyMessage(m: Message, code: string): string { let res = chalk.yellow(m.text) if (m.location) { const lines = code.split(/\r?\n/g) const line = Number(m.location.line) const column = Number(m.location.column) const offset = lines .slice(0, line - 1) .map((l) => l.length) .reduce((total, l) => total + l + 1, 0) + column res += `\n` + generateCodeFrame(code, offset, offset + 1) } return res + `\n` }
packages/vite/src/node/plugins/esbuild.ts
1
https://github.com/vitejs/vite/commit/42cd8b217de6afb53163eef69e96514c75de4443
[ 0.9959526062011719, 0.15291158854961395, 0.0001634997606743127, 0.0018338322406634688, 0.3334096670150757 ]
{ "id": 0, "code_window": [ " }\n", "}\n", "\n", "export function esbuildPlugin(options: ESBuildOptions = {}): Plugin {\n", " const filter = createFilter(\n", " options.include || /\\.(tsx?|jsx)$/,\n", " options.exclude\n", " )\n", "\n", " return {\n", " name: 'vite:esbuild',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " options.include || /\\.(tsx?|jsx)($|\\?)/,\n" ], "file_path": "packages/vite/src/node/plugins/esbuild.ts", "type": "replace", "edit_start_line_idx": 99 }
{ "name": "vite-monorepo", "private": true, "workspaces": [ "packages/*", "packages/playground/*" ], "scripts": { "lint": "eslint --ext .js,.ts packages/*/src/**", "test": "run-s test-serve test-build", "test-serve": "jest", "debug-serve": "cross-env VITE_DEBUG_SERVE=1 node --inspect-brk ./node_modules/.bin/jest", "test-build": "cross-env VITE_TEST_BUILD=1 jest", "debug-build": "cross-env VITE_TEST_BUILD=1 VITE_PRESERVE_BUILD_ARTIFACTS=1 node --inspect-brk ./node_modules/.bin/jest", "docs": "vitepress dev docs", "build-docs": "vitepress build docs", "build-vite": "cd packages/vite && yarn build", "build-plugin-vue": "cd packages/plugin-vue && yarn build", "ci-docs": "run-s build-vite build-plugin-vue build-docs" }, "devDependencies": { "@microsoft/api-extractor": "^7.12.1", "@types/fs-extra": "^9.0.5", "@types/jest": "^26.0.19", "@types/node": "^14.14.10", "@types/semver": "^7.3.4", "@typescript-eslint/parser": "^4.9.1", "chalk": "^4.1.0", "conventional-changelog-cli": "^2.1.1", "cross-env": "^7.0.3", "enquirer": "^2.3.6", "eslint": "^7.15.0", "eslint-plugin-node": "^11.1.0", "execa": "^5.0.0", "fs-extra": "^9.0.1", "jest": "^26.6.3", "lint-staged": "^10.5.3", "minimist": "^1.2.5", "npm-run-all": "^4.1.5", "playwright-chromium": "^1.7.0", "prettier": "^2.2.1", "rimraf": "^3.0.2", "semver": "^7.3.4", "sirv": "^1.0.10", "slash": "^3.0.0", "ts-jest": "^26.4.4", "typescript": "^4.1.2", "vitepress": "^0.10.5", "yorkie": "^2.0.0" }, "gitHooks": { "pre-commit": "lint-staged", "commit-msg": "node scripts/verifyCommit.js" }, "lint-staged": { "*.js": [ "prettier --write" ], "*.ts": [ "eslint", "prettier --parser=typescript --write" ] } }
package.json
0
https://github.com/vitejs/vite/commit/42cd8b217de6afb53163eef69e96514c75de4443
[ 0.00017420148651581258, 0.00016928506374824792, 0.00016599240188952535, 0.00016815368144307286, 0.000002781497187243076 ]
{ "id": 0, "code_window": [ " }\n", "}\n", "\n", "export function esbuildPlugin(options: ESBuildOptions = {}): Plugin {\n", " const filter = createFilter(\n", " options.include || /\\.(tsx?|jsx)$/,\n", " options.exclude\n", " )\n", "\n", " return {\n", " name: 'vite:esbuild',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " options.include || /\\.(tsx?|jsx)($|\\?)/,\n" ], "file_path": "packages/vite/src/node/plugins/esbuild.ts", "type": "replace", "edit_start_line_idx": 99 }
<h1>Alias</h1> <p class="fs"></p> <p class="fs-dir"></p> <p class="regex"></p> <p class="dep"></p> <script type="module"> import { msg as fsMsg } from 'fs' import { msg as fsDirMsg } from 'fs-dir/test' import { msg as regexMsg } from 'regex/test' import { msg as depMsg } from 'dep' function text(el, text) { document.querySelector(el).textContent = text } text('.fs', fsMsg) text('.fs-dir', fsDirMsg) text('.regex', regexMsg + ' via regex') text('.dep', depMsg) </script>
packages/playground/alias/index.html
0
https://github.com/vitejs/vite/commit/42cd8b217de6afb53163eef69e96514c75de4443
[ 0.00017640083387959749, 0.00017606020264793187, 0.00017547933384776115, 0.00017630044021643698, 4.1277610307588475e-7 ]
{ "id": 0, "code_window": [ " }\n", "}\n", "\n", "export function esbuildPlugin(options: ESBuildOptions = {}): Plugin {\n", " const filter = createFilter(\n", " options.include || /\\.(tsx?|jsx)$/,\n", " options.exclude\n", " )\n", "\n", " return {\n", " name: 'vite:esbuild',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " options.include || /\\.(tsx?|jsx)($|\\?)/,\n" ], "file_path": "packages/vite/src/node/plugins/esbuild.ts", "type": "replace", "edit_start_line_idx": 99 }
import { CompilerError } from '@vue/compiler-sfc' import { RollupError } from 'rollup' export function createRollupError( id: string, error: CompilerError | SyntaxError ): RollupError { ;(error as RollupError).id = id ;(error as RollupError).plugin = 'vue' if ('code' in error && error.loc) { ;(error as any).loc = { file: id, line: error.loc.start.line, column: error.loc.start.column } } return error as RollupError }
packages/plugin-vue/src/utils/error.ts
0
https://github.com/vitejs/vite/commit/42cd8b217de6afb53163eef69e96514c75de4443
[ 0.00017718436720315367, 0.00017409806605428457, 0.00017034115444403142, 0.0001747686619637534, 0.0000028336864943412365 ]
{ "id": 1, "code_window": [ " if (!url.startsWith('.') && !url.startsWith('/')) {\n", " url = VALID_ID_PREFIX + resolved.id\n", " }\n", "\n", " // for relative imports, inherit importer's version query\n", " if (isRelative) {\n", " const versionMatch = importer.match(DEP_VERSION_RE)\n", " if (versionMatch) {\n", " url = injectQuery(url, versionMatch[1])\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " // mark non-js/css imports with `?import`\n", " url = markExplicitImport(url)\n", "\n", " // for relative js/css imports, inherit importer's version query\n", " // do not do this for unknown type imports, otherwise the appended\n", " // query can break 3rd party plugin's extension checks.\n", " if (isRelative && !/[\\?&]import\\b/.test(url)) {\n" ], "file_path": "packages/vite/src/node/plugins/importsAnalysis.ts", "type": "replace", "edit_start_line_idx": 250 }
import fs from 'fs' import path from 'path' import { Plugin } from '../plugin' import { ResolvedConfig } from '../config' import chalk from 'chalk' import MagicString from 'magic-string' import { init, parse as parseImports, ImportSpecifier } from 'es-module-lexer' import { isCSSRequest, isDirectCSSRequest } from './css' import { cleanUrl, createDebugger, generateCodeFrame, injectQuery, isDataUrl, isExternalUrl, isJSRequest, normalizePath, prettifyUrl, timeFrom } from '../utils' import { debugHmr, handlePrunedModules, lexAcceptedHmrDeps } from '../server/hmr' import { FS_PREFIX, CLIENT_PUBLIC_PATH, DEP_VERSION_RE, VALID_ID_PREFIX } from '../constants' import { ViteDevServer } from '../' import { checkPublicFile } from './asset' import { parse as parseJS } from 'acorn' import { ImportDeclaration } from 'estree' import { makeLegalIdentifier } from '@rollup/pluginutils' const isDebug = !!process.env.DEBUG const debugRewrite = createDebugger('vite:rewrite') const skipRE = /\.(map|json)$/ const canSkip = (id: string) => skipRE.test(id) || isDirectCSSRequest(id) function markExplicitImport(url: string) { if (!isJSRequest(cleanUrl(url)) && !isCSSRequest(url)) { return injectQuery(url, 'import') } return url } /** * Server-only plugin that lexes, resolves, rewrites and analyzes url imports. * * - Imports are resolved to ensure they exist on disk * * - Lexes HMR accept calls and updates import relationships in the module graph * * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to * absolute file paths, e.g. * * ```js * import 'foo' * ``` * is rewritten to * ```js * import '/@fs//project/node_modules/foo/dist/foo.js' * ``` * * - CSS imports are appended with `.js` since both the js module and the actual * css (referenced via <link>) may go through the trasnform pipeline: * * ```js * import './style.css' * ``` * is rewritten to * ```js * import './style.css.js' * ``` */ export function importAnalysisPlugin(config: ResolvedConfig): Plugin { let server: ViteDevServer return { name: 'vite:imports', configureServer(_server) { server = _server }, async transform(source, importer) { const prettyImporter = prettifyUrl(normalizePath(importer), config.root) if (canSkip(importer)) { isDebug && debugRewrite(chalk.dim(`[skipped] ${prettyImporter}`)) return null } const rewriteStart = Date.now() let timeSpentResolving = 0 await init let imports: ImportSpecifier[] = [] try { imports = parseImports(source)[0] } catch (e) { this.error( `Failed to parse source for import rewrite.\n` + `The file either contains syntax error or it has not been properly transformed to JS.\n` + `If you are using JSX, make sure to named the file with the .jsx extension.`, e.idx ) } if (!imports.length) { isDebug && debugRewrite( `${timeFrom(rewriteStart)} ${chalk.dim( `[no imports] ${prettyImporter}` )}` ) return source } let hasHMR = false let isSelfAccepting = false let hasEnv = false let s: MagicString | undefined const str = () => s || (s = new MagicString(source)) // vite-only server context const { moduleGraph } = server // since we are already in the transform phase of the importer, it must // have been loaded so its entry is guaranteed in the module graph. const importerModule = moduleGraph.getModuleById(importer)! const importedUrls = new Set<string>() const acceptedUrls = new Set<{ url: string start: number end: number }>() const toAbsoluteUrl = (url: string) => path.posix.resolve(path.posix.dirname(importerModule.url), url) for (let i = 0; i < imports.length; i++) { const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex } = imports[i] const rawUrl = source.slice(start, end) let url = rawUrl if (isExternalUrl(url) || isDataUrl(url)) { continue } // check import.meta usage if (url === 'import.meta') { const prop = source.slice(end, end + 4) if (prop === '.hot') { hasHMR = true if (source.slice(end + 4, end + 11) === '.accept') { // further analyze accepted modules if ( lexAcceptedHmrDeps( source, source.indexOf('(', end + 11) + 1, acceptedUrls ) ) { isSelfAccepting = true } } } else if (prop === '.env') { hasEnv = true } continue } // For dynamic id, check if it's a literal that we can resolve let hasViteIgnore = false let isLiteralDynamicId = false if (dynamicIndex >= 0) { // check @vite-ignore which suppresses dynamic import warning hasViteIgnore = /\/\*\s*@vite-ignore\s*\*\//.test(url) // #998 remove comment url = url.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '') const literalIdMatch = url.match(/^\s*(?:'([^']+)'|"([^"]+)")\s*$/) if (literalIdMatch) { isLiteralDynamicId = true url = literalIdMatch[1] || literalIdMatch[2] } } // If resolvable, let's resolve it if (dynamicIndex === -1 || isLiteralDynamicId) { // skip client if (url === CLIENT_PUBLIC_PATH) { continue } // warn imports to non-asset /public files if ( url.startsWith('/') && !config.assetsInclude(cleanUrl(url)) && checkPublicFile(url, config.root) ) { throw new Error( `Cannot import non-asset file ${url} which is inside /public.` + `JS/CSS files inside /public are copied as-is on build and ` + `can only be referenced via <script src> or <link href> in html.` ) } const resolveStart = Date.now() const resolved = await this.resolve(url, importer) if (!resolved) { this.error( `Failed to resolve import "${rawUrl}". Does the file exist?`, start ) } timeSpentResolving += Date.now() - resolveStart const isRelative = url.startsWith('.') // normalize all imports into resolved URLs // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js` if (url !== resolved.id) { if (resolved.id.startsWith(config.root)) { // in root: infer short absolute path from root url = resolved.id.slice(config.root.length) } else if (fs.existsSync(cleanUrl(resolved.id))) { // exists but out of root: rewrite to absolute /@fs/ paths url = FS_PREFIX + normalizePath(resolved.id) } else { url = resolved.id } } // if the resolved id is not a valid browser import specifier, // prefix it to make it valid. We will strip this before feeding it // back into the transform pipeline if (!url.startsWith('.') && !url.startsWith('/')) { url = VALID_ID_PREFIX + resolved.id } // for relative imports, inherit importer's version query if (isRelative) { const versionMatch = importer.match(DEP_VERSION_RE) if (versionMatch) { url = injectQuery(url, versionMatch[1]) } } // mark non-js imports with `?import` url = markExplicitImport(url) // check if the dep has been hmr updated. If yes, we need to attach // its last updated timestamp to force the browser to fetch the most // up-to-date version of this module. try { const depModule = await moduleGraph.ensureEntryFromUrl(url) if (depModule.lastHMRTimestamp > 0) { url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`) } } catch (e) { // it's possible that the dep fails to resolve (non-existent import) // attach location to the missing import e.pos = start throw e } // rewrite if (url !== rawUrl) { // for optimized cjs deps, support named imports by rewriting named // imports to const assignments. if (isOptimizedCjs(resolved.id, server)) { if (isLiteralDynamicId) { // rewrite `import('package')` to expose module.exports // note plugin-commonjs' behavior is exposing all properties on // `module.exports` PLUS `module.exports` itself as `default`. str().overwrite( dynamicIndex, end + 1, `import('${url}').then(m => ({ ...m.default, default: m.default }))` ) } else { const exp = source.slice(expStart, expEnd) str().overwrite( expStart, expEnd, transformCjsImport(exp, url, rawUrl, i) ) } } else { str().overwrite(start, end, isLiteralDynamicId ? `'${url}'` : url) } } // record for HMR import chain analysis importedUrls.add(url) } else if (!hasViteIgnore && !isSupportedDynamicImport(url)) { this.warn( `\n` + chalk.cyan(importerModule.file) + `\n` + generateCodeFrame(source, start) + `\nThe above dynamic import cannot be analyzed by vite.\n` + `See ${chalk.blue( `https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations` )} ` + `for supported dynamic import formats. ` + `If this is intended to be left as-is, you can use the ` + `/* @vite-ignore */ comment inside the import() call to suppress this warning.\n` ) } } if (hasEnv) { // inject import.meta.env str().prepend(`import.meta.env = ${JSON.stringify(config.env)};`) } if (hasHMR) { debugHmr( `${ isSelfAccepting ? `[self-accepts]` : acceptedUrls.size ? `[accepts-deps]` : `[detected api usage]` } ${prettyImporter}` ) // inject hot context str().prepend( `import { createHotContext } from "${CLIENT_PUBLIC_PATH}";` + `import.meta.hot = createHotContext(${JSON.stringify( importerModule.url )});` ) } // normalize and rewrite accepted urls const normalizedAcceptedUrls = new Set<string>() for (const { url, start, end } of acceptedUrls) { const [normalized] = await moduleGraph.resolveUrl( toAbsoluteUrl(markExplicitImport(url)) ) normalizedAcceptedUrls.add(normalized) str().overwrite(start, end, JSON.stringify(normalized)) } // update the module graph for HMR analysis. // node CSS imports does its own graph update in the css plugin so we // only handle js graph updates here. if (!isCSSRequest(importer)) { const prunedImports = await moduleGraph.updateModuleInfo( importerModule, importedUrls, normalizedAcceptedUrls, isSelfAccepting ) if (hasHMR && prunedImports) { handlePrunedModules(prunedImports, server) } } isDebug && debugRewrite( `${timeFrom(rewriteStart, timeSpentResolving)} ${prettyImporter}` ) if (s) { return s.toString() } else { return source } } } } /** * https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations * This is probably less accurate but is much cheaper than a full AST parse. */ function isSupportedDynamicImport(url: string) { url = url.trim().slice(1, -1) // must be relative if (!url.startsWith('./') && !url.startsWith('../')) { return false } // must have extension if (!path.extname(url)) { return false } // must be more specific if importing from same dir if (url.startsWith('./${') && url.indexOf('/') === url.lastIndexOf('/')) { return false } return true } function isOptimizedCjs( id: string, { optimizeDepsMetadata, config: { optimizeCacheDir } }: ViteDevServer ): boolean { if (optimizeDepsMetadata && optimizeCacheDir) { const relative = path.relative(optimizeCacheDir, cleanUrl(id)) return relative in optimizeDepsMetadata.cjsEntries } return false } type ImportNameSpecifier = { importedName: string; localName: string } /** * Detect import statements to a known optimized CJS dependency and provide * ES named imports interop. We do this by rewriting named imports to a variable * assignment to the corresponding property on the `module.exports` of the cjs * module. Note this doesn't support dynamic re-assisgnments from within the cjs * module. * * Credits \@csr632 via #837 */ function transformCjsImport( importExp: string, url: string, rawUrl: string, importIndex: number ): string { const ast = (parseJS(importExp, { ecmaVersion: 2020, sourceType: 'module' }) as any).body[0] as ImportDeclaration const importNames: ImportNameSpecifier[] = [] ast.specifiers.forEach((obj) => { if (obj.type === 'ImportSpecifier' && obj.imported.type === 'Identifier') { const importedName = obj.imported.name const localName = obj.local.name importNames.push({ importedName, localName }) } else if (obj.type === 'ImportDefaultSpecifier') { importNames.push({ importedName: 'default', localName: obj.local.name }) } else if (obj.type === 'ImportNamespaceSpecifier') { importNames.push({ importedName: '*', localName: obj.local.name }) } }) // If there is multiple import for same id in one file, // importIndex will prevent the cjsModuleName to be duplicate const cjsModuleName = makeLegalIdentifier( `$viteCjsImport${importIndex}_${rawUrl}` ) const lines: string[] = [`import ${cjsModuleName} from "${url}";`] importNames.forEach(({ importedName, localName }) => { if (importedName === '*' || importedName === 'default') { lines.push(`const ${localName} = ${cjsModuleName};`) } else { lines.push(`const ${localName} = ${cjsModuleName}["${importedName}"];`) } }) return lines.join('\n') }
packages/vite/src/node/plugins/importsAnalysis.ts
1
https://github.com/vitejs/vite/commit/42cd8b217de6afb53163eef69e96514c75de4443
[ 0.9981604218482971, 0.049251995980739594, 0.00016256843809969723, 0.0003386822354514152, 0.2009536772966385 ]
{ "id": 1, "code_window": [ " if (!url.startsWith('.') && !url.startsWith('/')) {\n", " url = VALID_ID_PREFIX + resolved.id\n", " }\n", "\n", " // for relative imports, inherit importer's version query\n", " if (isRelative) {\n", " const versionMatch = importer.match(DEP_VERSION_RE)\n", " if (versionMatch) {\n", " url = injectQuery(url, versionMatch[1])\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " // mark non-js/css imports with `?import`\n", " url = markExplicitImport(url)\n", "\n", " // for relative js/css imports, inherit importer's version query\n", " // do not do this for unknown type imports, otherwise the appended\n", " // query can break 3rd party plugin's extension checks.\n", " if (isRelative && !/[\\?&]import\\b/.test(url)) {\n" ], "file_path": "packages/vite/src/node/plugins/importsAnalysis.ts", "type": "replace", "edit_start_line_idx": 250 }
export type HMRPayload = | ConnectedPayload | UpdatePayload | FullReloadPayload | CustomPayload | ErrorPayload | PrunePayload export interface ConnectedPayload { type: 'connected' } export interface UpdatePayload { type: 'update' updates: Update[] } export interface Update { type: 'js-update' | 'css-update' path: string acceptedPath: string timestamp: number } export interface PrunePayload { type: 'prune' paths: string[] } export interface FullReloadPayload { type: 'full-reload' path?: string } export interface CustomPayload { type: 'custom' event: string data?: any } export interface ErrorPayload { type: 'error' err: { [name: string]: any message: string stack: string id?: string frame?: string plugin?: string pluginCode?: string loc?: { file?: string line: number column: number } } }
packages/vite/types/hmrPayload.d.ts
0
https://github.com/vitejs/vite/commit/42cd8b217de6afb53163eef69e96514c75de4443
[ 0.00017361018399242312, 0.0001702567533357069, 0.0001670537021709606, 0.0001703997841104865, 0.0000023956401946634287 ]
{ "id": 1, "code_window": [ " if (!url.startsWith('.') && !url.startsWith('/')) {\n", " url = VALID_ID_PREFIX + resolved.id\n", " }\n", "\n", " // for relative imports, inherit importer's version query\n", " if (isRelative) {\n", " const versionMatch = importer.match(DEP_VERSION_RE)\n", " if (versionMatch) {\n", " url = injectQuery(url, versionMatch[1])\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " // mark non-js/css imports with `?import`\n", " url = markExplicitImport(url)\n", "\n", " // for relative js/css imports, inherit importer's version query\n", " // do not do this for unknown type imports, otherwise the appended\n", " // query can break 3rd party plugin's extension checks.\n", " if (isRelative && !/[\\?&]import\\b/.test(url)) {\n" ], "file_path": "packages/vite/src/node/plugins/importsAnalysis.ts", "type": "replace", "edit_start_line_idx": 250 }
declare module 'css-color-names' { const colors: Record<string, string> export default colors }
packages/playground/shims.d.ts
0
https://github.com/vitejs/vite/commit/42cd8b217de6afb53163eef69e96514c75de4443
[ 0.00017140999261755496, 0.00017140999261755496, 0.00017140999261755496, 0.00017140999261755496, 0 ]
{ "id": 1, "code_window": [ " if (!url.startsWith('.') && !url.startsWith('/')) {\n", " url = VALID_ID_PREFIX + resolved.id\n", " }\n", "\n", " // for relative imports, inherit importer's version query\n", " if (isRelative) {\n", " const versionMatch = importer.match(DEP_VERSION_RE)\n", " if (versionMatch) {\n", " url = injectQuery(url, versionMatch[1])\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " // mark non-js/css imports with `?import`\n", " url = markExplicitImport(url)\n", "\n", " // for relative js/css imports, inherit importer's version query\n", " // do not do this for unknown type imports, otherwise the appended\n", " // query can break 3rd party plugin's extension checks.\n", " if (isRelative && !/[\\?&]import\\b/.test(url)) {\n" ], "file_path": "packages/vite/src/node/plugins/importsAnalysis.ts", "type": "replace", "edit_start_line_idx": 250 }
interface ImportMeta { url: string readonly hot?: { readonly data: any accept(): void accept(cb: (mod: any) => void): void accept(dep: string, cb: (mod: any) => void): void accept(deps: readonly string[], cb: (mods: any[]) => void): void /** * @deprecated */ acceptDeps(): never dispose(cb: (data: any) => void): void decline(): void invalidate(): void on(event: string, cb: (...args: any[]) => void): void } readonly env: ImportMetaEnv } interface ImportMetaEnv { [key: string]: string | boolean | undefined BASE_URL: string MODE: string DEV: boolean PROD: boolean }
packages/vite/types/importMeta.d.ts
0
https://github.com/vitejs/vite/commit/42cd8b217de6afb53163eef69e96514c75de4443
[ 0.00029125396395102143, 0.0002001671091420576, 0.00016676769882906228, 0.00017132337961811572, 0.00005262189733912237 ]
{ "id": 2, "code_window": [ " }\n", " }\n", "\n", " // mark non-js imports with `?import`\n", " url = markExplicitImport(url)\n", "\n", " // check if the dep has been hmr updated. If yes, we need to attach\n", " // its last updated timestamp to force the browser to fetch the most\n", " // up-to-date version of this module.\n", " try {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/vite/src/node/plugins/importsAnalysis.ts", "type": "replace", "edit_start_line_idx": 258 }
import fs from 'fs' import path from 'path' import { Plugin } from '../plugin' import { ResolvedConfig } from '../config' import chalk from 'chalk' import MagicString from 'magic-string' import { init, parse as parseImports, ImportSpecifier } from 'es-module-lexer' import { isCSSRequest, isDirectCSSRequest } from './css' import { cleanUrl, createDebugger, generateCodeFrame, injectQuery, isDataUrl, isExternalUrl, isJSRequest, normalizePath, prettifyUrl, timeFrom } from '../utils' import { debugHmr, handlePrunedModules, lexAcceptedHmrDeps } from '../server/hmr' import { FS_PREFIX, CLIENT_PUBLIC_PATH, DEP_VERSION_RE, VALID_ID_PREFIX } from '../constants' import { ViteDevServer } from '../' import { checkPublicFile } from './asset' import { parse as parseJS } from 'acorn' import { ImportDeclaration } from 'estree' import { makeLegalIdentifier } from '@rollup/pluginutils' const isDebug = !!process.env.DEBUG const debugRewrite = createDebugger('vite:rewrite') const skipRE = /\.(map|json)$/ const canSkip = (id: string) => skipRE.test(id) || isDirectCSSRequest(id) function markExplicitImport(url: string) { if (!isJSRequest(cleanUrl(url)) && !isCSSRequest(url)) { return injectQuery(url, 'import') } return url } /** * Server-only plugin that lexes, resolves, rewrites and analyzes url imports. * * - Imports are resolved to ensure they exist on disk * * - Lexes HMR accept calls and updates import relationships in the module graph * * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to * absolute file paths, e.g. * * ```js * import 'foo' * ``` * is rewritten to * ```js * import '/@fs//project/node_modules/foo/dist/foo.js' * ``` * * - CSS imports are appended with `.js` since both the js module and the actual * css (referenced via <link>) may go through the trasnform pipeline: * * ```js * import './style.css' * ``` * is rewritten to * ```js * import './style.css.js' * ``` */ export function importAnalysisPlugin(config: ResolvedConfig): Plugin { let server: ViteDevServer return { name: 'vite:imports', configureServer(_server) { server = _server }, async transform(source, importer) { const prettyImporter = prettifyUrl(normalizePath(importer), config.root) if (canSkip(importer)) { isDebug && debugRewrite(chalk.dim(`[skipped] ${prettyImporter}`)) return null } const rewriteStart = Date.now() let timeSpentResolving = 0 await init let imports: ImportSpecifier[] = [] try { imports = parseImports(source)[0] } catch (e) { this.error( `Failed to parse source for import rewrite.\n` + `The file either contains syntax error or it has not been properly transformed to JS.\n` + `If you are using JSX, make sure to named the file with the .jsx extension.`, e.idx ) } if (!imports.length) { isDebug && debugRewrite( `${timeFrom(rewriteStart)} ${chalk.dim( `[no imports] ${prettyImporter}` )}` ) return source } let hasHMR = false let isSelfAccepting = false let hasEnv = false let s: MagicString | undefined const str = () => s || (s = new MagicString(source)) // vite-only server context const { moduleGraph } = server // since we are already in the transform phase of the importer, it must // have been loaded so its entry is guaranteed in the module graph. const importerModule = moduleGraph.getModuleById(importer)! const importedUrls = new Set<string>() const acceptedUrls = new Set<{ url: string start: number end: number }>() const toAbsoluteUrl = (url: string) => path.posix.resolve(path.posix.dirname(importerModule.url), url) for (let i = 0; i < imports.length; i++) { const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex } = imports[i] const rawUrl = source.slice(start, end) let url = rawUrl if (isExternalUrl(url) || isDataUrl(url)) { continue } // check import.meta usage if (url === 'import.meta') { const prop = source.slice(end, end + 4) if (prop === '.hot') { hasHMR = true if (source.slice(end + 4, end + 11) === '.accept') { // further analyze accepted modules if ( lexAcceptedHmrDeps( source, source.indexOf('(', end + 11) + 1, acceptedUrls ) ) { isSelfAccepting = true } } } else if (prop === '.env') { hasEnv = true } continue } // For dynamic id, check if it's a literal that we can resolve let hasViteIgnore = false let isLiteralDynamicId = false if (dynamicIndex >= 0) { // check @vite-ignore which suppresses dynamic import warning hasViteIgnore = /\/\*\s*@vite-ignore\s*\*\//.test(url) // #998 remove comment url = url.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '') const literalIdMatch = url.match(/^\s*(?:'([^']+)'|"([^"]+)")\s*$/) if (literalIdMatch) { isLiteralDynamicId = true url = literalIdMatch[1] || literalIdMatch[2] } } // If resolvable, let's resolve it if (dynamicIndex === -1 || isLiteralDynamicId) { // skip client if (url === CLIENT_PUBLIC_PATH) { continue } // warn imports to non-asset /public files if ( url.startsWith('/') && !config.assetsInclude(cleanUrl(url)) && checkPublicFile(url, config.root) ) { throw new Error( `Cannot import non-asset file ${url} which is inside /public.` + `JS/CSS files inside /public are copied as-is on build and ` + `can only be referenced via <script src> or <link href> in html.` ) } const resolveStart = Date.now() const resolved = await this.resolve(url, importer) if (!resolved) { this.error( `Failed to resolve import "${rawUrl}". Does the file exist?`, start ) } timeSpentResolving += Date.now() - resolveStart const isRelative = url.startsWith('.') // normalize all imports into resolved URLs // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js` if (url !== resolved.id) { if (resolved.id.startsWith(config.root)) { // in root: infer short absolute path from root url = resolved.id.slice(config.root.length) } else if (fs.existsSync(cleanUrl(resolved.id))) { // exists but out of root: rewrite to absolute /@fs/ paths url = FS_PREFIX + normalizePath(resolved.id) } else { url = resolved.id } } // if the resolved id is not a valid browser import specifier, // prefix it to make it valid. We will strip this before feeding it // back into the transform pipeline if (!url.startsWith('.') && !url.startsWith('/')) { url = VALID_ID_PREFIX + resolved.id } // for relative imports, inherit importer's version query if (isRelative) { const versionMatch = importer.match(DEP_VERSION_RE) if (versionMatch) { url = injectQuery(url, versionMatch[1]) } } // mark non-js imports with `?import` url = markExplicitImport(url) // check if the dep has been hmr updated. If yes, we need to attach // its last updated timestamp to force the browser to fetch the most // up-to-date version of this module. try { const depModule = await moduleGraph.ensureEntryFromUrl(url) if (depModule.lastHMRTimestamp > 0) { url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`) } } catch (e) { // it's possible that the dep fails to resolve (non-existent import) // attach location to the missing import e.pos = start throw e } // rewrite if (url !== rawUrl) { // for optimized cjs deps, support named imports by rewriting named // imports to const assignments. if (isOptimizedCjs(resolved.id, server)) { if (isLiteralDynamicId) { // rewrite `import('package')` to expose module.exports // note plugin-commonjs' behavior is exposing all properties on // `module.exports` PLUS `module.exports` itself as `default`. str().overwrite( dynamicIndex, end + 1, `import('${url}').then(m => ({ ...m.default, default: m.default }))` ) } else { const exp = source.slice(expStart, expEnd) str().overwrite( expStart, expEnd, transformCjsImport(exp, url, rawUrl, i) ) } } else { str().overwrite(start, end, isLiteralDynamicId ? `'${url}'` : url) } } // record for HMR import chain analysis importedUrls.add(url) } else if (!hasViteIgnore && !isSupportedDynamicImport(url)) { this.warn( `\n` + chalk.cyan(importerModule.file) + `\n` + generateCodeFrame(source, start) + `\nThe above dynamic import cannot be analyzed by vite.\n` + `See ${chalk.blue( `https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations` )} ` + `for supported dynamic import formats. ` + `If this is intended to be left as-is, you can use the ` + `/* @vite-ignore */ comment inside the import() call to suppress this warning.\n` ) } } if (hasEnv) { // inject import.meta.env str().prepend(`import.meta.env = ${JSON.stringify(config.env)};`) } if (hasHMR) { debugHmr( `${ isSelfAccepting ? `[self-accepts]` : acceptedUrls.size ? `[accepts-deps]` : `[detected api usage]` } ${prettyImporter}` ) // inject hot context str().prepend( `import { createHotContext } from "${CLIENT_PUBLIC_PATH}";` + `import.meta.hot = createHotContext(${JSON.stringify( importerModule.url )});` ) } // normalize and rewrite accepted urls const normalizedAcceptedUrls = new Set<string>() for (const { url, start, end } of acceptedUrls) { const [normalized] = await moduleGraph.resolveUrl( toAbsoluteUrl(markExplicitImport(url)) ) normalizedAcceptedUrls.add(normalized) str().overwrite(start, end, JSON.stringify(normalized)) } // update the module graph for HMR analysis. // node CSS imports does its own graph update in the css plugin so we // only handle js graph updates here. if (!isCSSRequest(importer)) { const prunedImports = await moduleGraph.updateModuleInfo( importerModule, importedUrls, normalizedAcceptedUrls, isSelfAccepting ) if (hasHMR && prunedImports) { handlePrunedModules(prunedImports, server) } } isDebug && debugRewrite( `${timeFrom(rewriteStart, timeSpentResolving)} ${prettyImporter}` ) if (s) { return s.toString() } else { return source } } } } /** * https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations * This is probably less accurate but is much cheaper than a full AST parse. */ function isSupportedDynamicImport(url: string) { url = url.trim().slice(1, -1) // must be relative if (!url.startsWith('./') && !url.startsWith('../')) { return false } // must have extension if (!path.extname(url)) { return false } // must be more specific if importing from same dir if (url.startsWith('./${') && url.indexOf('/') === url.lastIndexOf('/')) { return false } return true } function isOptimizedCjs( id: string, { optimizeDepsMetadata, config: { optimizeCacheDir } }: ViteDevServer ): boolean { if (optimizeDepsMetadata && optimizeCacheDir) { const relative = path.relative(optimizeCacheDir, cleanUrl(id)) return relative in optimizeDepsMetadata.cjsEntries } return false } type ImportNameSpecifier = { importedName: string; localName: string } /** * Detect import statements to a known optimized CJS dependency and provide * ES named imports interop. We do this by rewriting named imports to a variable * assignment to the corresponding property on the `module.exports` of the cjs * module. Note this doesn't support dynamic re-assisgnments from within the cjs * module. * * Credits \@csr632 via #837 */ function transformCjsImport( importExp: string, url: string, rawUrl: string, importIndex: number ): string { const ast = (parseJS(importExp, { ecmaVersion: 2020, sourceType: 'module' }) as any).body[0] as ImportDeclaration const importNames: ImportNameSpecifier[] = [] ast.specifiers.forEach((obj) => { if (obj.type === 'ImportSpecifier' && obj.imported.type === 'Identifier') { const importedName = obj.imported.name const localName = obj.local.name importNames.push({ importedName, localName }) } else if (obj.type === 'ImportDefaultSpecifier') { importNames.push({ importedName: 'default', localName: obj.local.name }) } else if (obj.type === 'ImportNamespaceSpecifier') { importNames.push({ importedName: '*', localName: obj.local.name }) } }) // If there is multiple import for same id in one file, // importIndex will prevent the cjsModuleName to be duplicate const cjsModuleName = makeLegalIdentifier( `$viteCjsImport${importIndex}_${rawUrl}` ) const lines: string[] = [`import ${cjsModuleName} from "${url}";`] importNames.forEach(({ importedName, localName }) => { if (importedName === '*' || importedName === 'default') { lines.push(`const ${localName} = ${cjsModuleName};`) } else { lines.push(`const ${localName} = ${cjsModuleName}["${importedName}"];`) } }) return lines.join('\n') }
packages/vite/src/node/plugins/importsAnalysis.ts
1
https://github.com/vitejs/vite/commit/42cd8b217de6afb53163eef69e96514c75de4443
[ 0.9969270825386047, 0.19262820482254028, 0.00016491881979163736, 0.0006585788214579225, 0.3765626847743988 ]
{ "id": 2, "code_window": [ " }\n", " }\n", "\n", " // mark non-js imports with `?import`\n", " url = markExplicitImport(url)\n", "\n", " // check if the dep has been hmr updated. If yes, we need to attach\n", " // its last updated timestamp to force the browser to fetch the most\n", " // up-to-date version of this module.\n", " try {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/vite/src/node/plugins/importsAnalysis.ts", "type": "replace", "edit_start_line_idx": 258 }
# 1.1.0 (2021-01-02) ### Features * **plugin-react-refresh:** types ([25d68c1](https://github.com/vitejs/vite/commit/25d68c17228be866152c719f7e2a4fe93cd88b8e))
packages/plugin-react-refresh/CHANGELOG.md
0
https://github.com/vitejs/vite/commit/42cd8b217de6afb53163eef69e96514c75de4443
[ 0.00016507819236721843, 0.00016507819236721843, 0.00016507819236721843, 0.00016507819236721843, 0 ]
{ "id": 2, "code_window": [ " }\n", " }\n", "\n", " // mark non-js imports with `?import`\n", " url = markExplicitImport(url)\n", "\n", " // check if the dep has been hmr updated. If yes, we need to attach\n", " // its last updated timestamp to force the browser to fetch the most\n", " // up-to-date version of this module.\n", " try {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/vite/src/node/plugins/importsAnalysis.ts", "type": "replace", "edit_start_line_idx": 258 }
<template> <h2>Template Static Asset Reference</h2> <p> Relative <img class="relative-import" src="./assets/asset.png" style="width: 30px;" /> </p> <p> Absolute <img class="absolute-import" src="/assets/asset.png" style="width: 30px;" /> </p> <p> Absolute import from public dir <img class="public-import" src="/icon.png" style="width: 30px;" /> </p> <p> SVG Fragment reference <img class="svg-frag" style="width:32px;height:32px;" src="./assets/fragment.svg#icon-heart-view" alt="" > </p> </template>
packages/playground/vue/Assets.vue
0
https://github.com/vitejs/vite/commit/42cd8b217de6afb53163eef69e96514c75de4443
[ 0.00017523806309327483, 0.00017327860405202955, 0.00017138074326794595, 0.0001732169621391222, 0.0000015753471416246612 ]
{ "id": 2, "code_window": [ " }\n", " }\n", "\n", " // mark non-js imports with `?import`\n", " url = markExplicitImport(url)\n", "\n", " // check if the dep has been hmr updated. If yes, we need to attach\n", " // its last updated timestamp to force the browser to fetch the most\n", " // up-to-date version of this module.\n", " try {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/vite/src/node/plugins/importsAnalysis.ts", "type": "replace", "edit_start_line_idx": 258 }
{ "name": "vite", "version": "2.0.0-beta.4", "license": "MIT", "author": "Evan You", "description": "Native-ESM powered web dev build tool", "bin": { "vite": "bin/vite.js" }, "main": "dist/node/index.js", "types": "dist/node/index.d.ts", "files": [ "bin", "dist", "env.d.ts" ], "engines": { "node": ">=12.0.0" }, "repository": { "type": "git", "url": "git+https://github.com/vitejs/vite.git" }, "bugs": { "url": "https://github.com/vitejs/vite/issues" }, "homepage": "https://github.com/vitejs/vite/tree/main/#readme", "scripts": { "dev": "run-p dev-client dev-node", "dev-client": "tsc -w --incremental --p src/client", "dev-node": "tsc -w --incremental --p src/node", "prebuild": "rimraf dist && yarn lint", "build": "run-s build-bundle build-types", "build-bundle": "rollup -c", "build-types": "run-s build-temp-types patch-types roll-types", "build-temp-types": "tsc --emitDeclarationOnly --outDir temp/node -p src/node", "patch-types": "node scripts/patchTypes", "roll-types": "api-extractor run && rimraf temp", "lint": "eslint --ext .ts src/**", "format": "prettier --write --parser typescript \"src/**/*.ts\"", "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s --commit-path .", "release": "node ../../scripts/release.js" }, "//": "READ .github/contributing.md to understand what to put under deps vs. devDeps!", "dependencies": { "esbuild": "^0.8.26", "postcss": "^8.2.1", "resolve": "^1.19.0", "rollup": "^2.35.1" }, "optionalDependencies": { "fsevents": "~2.1.2" }, "devDependencies": { "@rollup/plugin-alias": "^3.1.1", "@rollup/plugin-commonjs": "^17.0.0", "@rollup/plugin-dynamic-import-vars": "^1.1.1", "@rollup/plugin-json": "^4.1.0", "@rollup/plugin-node-resolve": "^11.0.1", "@rollup/plugin-typescript": "^8.0.0", "@rollup/pluginutils": "^4.1.0", "@types/clean-css": "^4.2.3", "@types/convert-source-map": "^1.5.1", "@types/debug": "^4.1.5", "@types/es-module-lexer": "^0.3.0", "@types/estree": "^0.0.45", "@types/etag": "^1.8.0", "@types/mime": "^2.0.3", "@types/node": "^14.14.10", "@types/resolve": "^1.17.1", "@types/ws": "^7.4.0", "@vue/compiler-dom": "^3.0.4", "acorn": "^8.0.4", "acorn-class-fields": "^0.3.7", "brotli-size": "^4.0.0", "cac": "^6.6.1", "chalk": "^4.1.0", "chokidar": "^3.4.3", "clean-css": "^4.2.3", "connect": "^3.7.0", "connect-history-api-fallback": "^1.6.0", "convert-source-map": "^1.7.0", "cors": "^2.8.5", "debug": "^4.3.1", "dotenv": "^8.2.0", "dotenv-expand": "^5.1.0", "es-module-lexer": "^0.3.26", "etag": "^1.8.1", "execa": "^5.0.0", "http-proxy": "^1.18.1", "isbuiltin": "^1.0.0", "launch-editor-middleware": "^2.2.1", "magic-string": "^0.25.7", "merge-source-map": "^1.1.0", "mime": "^2.4.7", "okie": "^1.0.1", "open": "^7.3.0", "open-in-editor": "^2.2.0", "postcss-import": "^13.0.0", "postcss-load-config": "^3.0.0", "postcss-modules": "^4.0.0", "rollup-plugin-dynamic-import-variables": "^1.1.0", "rollup-plugin-license": "^2.2.0", "selfsigned": "^1.10.8", "sirv": "^1.0.10", "slash": "^3.0.0", "source-map-support": "^0.5.19", "strip-ansi": "^6.0.0", "terser": "^5.5.1", "tslib": "^2.0.3", "types": "link:./types", "ws": "^7.4.1" } }
packages/vite/package.json
0
https://github.com/vitejs/vite/commit/42cd8b217de6afb53163eef69e96514c75de4443
[ 0.00017143906734418124, 0.00016795880219433457, 0.00016148266149684787, 0.00016852200496941805, 0.000002997210458488553 ]
{ "id": 0, "code_window": [ " vueJsxPublicPath,\n", " vueJsxFilePath\n", "} from '../esbuildService'\n", "import { readBody } from '../utils'\n", "\n", "export const esbuildPlugin: ServerPlugin = ({ app, config }) => {\n", " const jsxConfig = resolveJsxOptions(config.jsx)\n", "\n", " app.use(async (ctx, next) => {\n", " // intercept and return vue jsx helper import\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const esbuildPlugin: ServerPlugin = ({ app, config, resolver }) => {\n" ], "file_path": "src/node/server/serverPluginEsbuild.ts", "type": "replace", "edit_start_line_idx": 10 }
import { ServerPlugin } from '.' import { tjsxRE, transform, resolveJsxOptions, vueJsxPublicPath, vueJsxFilePath } from '../esbuildService' import { readBody } from '../utils' export const esbuildPlugin: ServerPlugin = ({ app, config }) => { const jsxConfig = resolveJsxOptions(config.jsx) app.use(async (ctx, next) => { // intercept and return vue jsx helper import if (ctx.path === vueJsxPublicPath) { await ctx.read(vueJsxFilePath) } await next() if (ctx.body && tjsxRE.test(ctx.path)) { ctx.type = 'js' const src = await readBody(ctx.body) const { code, map } = await transform( src!, ctx.url, jsxConfig, config.jsx ) ctx.body = code if (map) { ctx.map = JSON.parse(map) } } }) }
src/node/server/serverPluginEsbuild.ts
1
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.9984203577041626, 0.5561941862106323, 0.00016980033251456916, 0.6130933165550232, 0.4493602514266968 ]
{ "id": 0, "code_window": [ " vueJsxPublicPath,\n", " vueJsxFilePath\n", "} from '../esbuildService'\n", "import { readBody } from '../utils'\n", "\n", "export const esbuildPlugin: ServerPlugin = ({ app, config }) => {\n", " const jsxConfig = resolveJsxOptions(config.jsx)\n", "\n", " app.use(async (ctx, next) => {\n", " // intercept and return vue jsx helper import\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const esbuildPlugin: ServerPlugin = ({ app, config, resolver }) => {\n" ], "file_path": "src/node/server/serverPluginEsbuild.ts", "type": "replace", "edit_start_line_idx": 10 }
import { Plugin } from 'rollup' import { lookupFile } from '../utils' import { DepOptimizationOptions } from '.' import chalk from 'chalk' export const createBuiltInBailPlugin = ( allowList: DepOptimizationOptions['allowNodeBuiltins'] ): Plugin => { const isbuiltin = require('isbuiltin') return { name: 'vite:node-built-in-bail', resolveId(id, importer) { if (isbuiltin(id)) { let importingDep if (importer) { const pkg = JSON.parse(lookupFile(importer, ['package.json']) || `{}`) if (pkg.name) { importingDep = pkg.name } } if (importingDep && allowList && allowList.includes(importingDep)) { return null } const dep = importingDep ? `Dependency ${chalk.yellow(importingDep)}` : `A dependency` throw new Error( `${dep} is attempting to import Node built-in module ${chalk.yellow( id )}.\n` + `This will not work in a browser environment.\n` + `Imported by: ${chalk.gray(importer)}` ) } return null } } }
src/node/optimizer/pluginBuiltInBail.ts
0
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.0001765204651746899, 0.000173943059053272, 0.00016913360741455108, 0.00017505910363979638, 0.000002871174046958913 ]
{ "id": 0, "code_window": [ " vueJsxPublicPath,\n", " vueJsxFilePath\n", "} from '../esbuildService'\n", "import { readBody } from '../utils'\n", "\n", "export const esbuildPlugin: ServerPlugin = ({ app, config }) => {\n", " const jsxConfig = resolveJsxOptions(config.jsx)\n", "\n", " app.use(async (ctx, next) => {\n", " // intercept and return vue jsx helper import\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const esbuildPlugin: ServerPlugin = ({ app, config, resolver }) => {\n" ], "file_path": "src/node/server/serverPluginEsbuild.ts", "type": "replace", "edit_start_line_idx": 10 }
export async function asyncReplace( input: string, re: RegExp, replacer: (match: RegExpExecArray) => string | Promise<string> ) { let match: RegExpExecArray | null let remaining = input let rewritten = '' while ((match = re.exec(remaining))) { rewritten += remaining.slice(0, match.index) rewritten += await replacer(match) remaining = remaining.slice(match.index + match[0].length) } rewritten += remaining return rewritten } const injectReplaceRE = [/<head>/, /<!doctype html>/i] export function injectScriptToHtml(html: string, script: string) { // inject after head or doctype for (const re of injectReplaceRE) { if (re.test(html)) { return html.replace(re, `$&${script}`) } } // if no <head> tag or doctype is present, just prepend return script + html }
src/node/utils/transformUtils.ts
0
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.00017667874635662884, 0.00017423000826966017, 0.0001725796319078654, 0.00017343164654448628, 0.0000017661108131505898 ]
{ "id": 0, "code_window": [ " vueJsxPublicPath,\n", " vueJsxFilePath\n", "} from '../esbuildService'\n", "import { readBody } from '../utils'\n", "\n", "export const esbuildPlugin: ServerPlugin = ({ app, config }) => {\n", " const jsxConfig = resolveJsxOptions(config.jsx)\n", "\n", " app.use(async (ctx, next) => {\n", " // intercept and return vue jsx helper import\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export const esbuildPlugin: ServerPlugin = ({ app, config, resolver }) => {\n" ], "file_path": "src/node/server/serverPluginEsbuild.ts", "type": "replace", "edit_start_line_idx": 10 }
const yaml = require('js-yaml') export const i18nTransform = ({ code, query }) => { let resource if (/ya?ml/.test(query.lang)) { resource = yaml.safeLoad(code.trim()) } else { resource = JSON.parse(code.trim()) } return ` export default Comp => { Comp.i18n = ${JSON.stringify(resource || {})} }`.trim() }
playground/custom-blocks/i18nTransform.js
0
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.00017599241982679814, 0.00017596087127458304, 0.00017592932272236794, 0.00017596087127458304, 3.1548552215099335e-8 ]
{ "id": 1, "code_window": [ " const src = await readBody(ctx.body)\n", " const { code, map } = await transform(\n", " src!,\n", " ctx.url,\n", " jsxConfig,\n", " config.jsx\n", " )\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " resolver.requestToFile(ctx.url),\n" ], "file_path": "src/node/server/serverPluginEsbuild.ts", "type": "replace", "edit_start_line_idx": 26 }
import { ServerPlugin } from '.' import merge from 'merge-source-map' export interface SourceMap { version: number | string file: string sources: string[] sourcesContent: string[] names: string[] mappings: string } export function mergeSourceMap( oldMap: SourceMap | null | undefined, newMap: SourceMap ): SourceMap { if (!oldMap) { return newMap } // merge-source-map will overwrite original sources if newMap also has // sourcesContent newMap.sourcesContent = [] return merge(oldMap, newMap) as SourceMap } function genSourceMapString(map: SourceMap | string | undefined) { if (typeof map !== 'string') { map = JSON.stringify(map) } return `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from( map ).toString('base64')}` } export const sourceMapPlugin: ServerPlugin = ({ app }) => { app.use(async (ctx, next) => { await next() if (typeof ctx.body === 'string' && ctx.map) { ctx.body += genSourceMapString(ctx.map) } }) }
src/node/server/serverPluginSourceMap.ts
1
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.9935910701751709, 0.20003025233745575, 0.00016751547809690237, 0.0001733174140099436, 0.3967869281768799 ]
{ "id": 1, "code_window": [ " const src = await readBody(ctx.body)\n", " const { code, map } = await transform(\n", " src!,\n", " ctx.url,\n", " jsxConfig,\n", " config.jsx\n", " )\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " resolver.requestToFile(ctx.url),\n" ], "file_path": "src/node/server/serverPluginEsbuild.ts", "type": "replace", "edit_start_line_idx": 26 }
export function Test(props: { count: 0 }) { return <div>Rendered from Preact TSX: count is {props.count}</div> }
playground/jsx/testTsx.tsx
0
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.0001714313984848559, 0.0001714313984848559, 0.0001714313984848559, 0.0001714313984848559, 0 ]
{ "id": 1, "code_window": [ " const src = await readBody(ctx.body)\n", " const { code, map } = await transform(\n", " src!,\n", " ctx.url,\n", " jsxConfig,\n", " config.jsx\n", " )\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " resolver.requestToFile(ctx.url),\n" ], "file_path": "src/node/server/serverPluginEsbuild.ts", "type": "replace", "edit_start_line_idx": 26 }
import qs from 'querystring' import chalk from 'chalk' import path from 'path' import { Context, ServerPlugin } from '.' import { SFCBlock, SFCDescriptor, SFCTemplateBlock, SFCStyleBlock, SFCStyleCompileResults, CompilerOptions, SFCStyleCompileOptions } from '@vue/compiler-sfc' import { resolveCompiler, resolveVue } from '../utils/resolveVue' import hash_sum from 'hash-sum' import LRUCache from 'lru-cache' import { debugHmr, importerMap, ensureMapEntry } from './serverPluginHmr' import { resolveFrom, cachedRead, cleanUrl, watchFileIfOutOfRoot } from '../utils' import { transform } from '../esbuildService' import { InternalResolver } from '../resolver' import { seenUrls } from './serverPluginServeStatic' import { codegenCss } from './serverPluginCss' import { compileCss, rewriteCssUrls } from '../utils/cssUtils' import { parse } from '../utils/babelParse' import MagicString from 'magic-string' import { resolveImport } from './serverPluginModuleRewrite' import { SourceMap, mergeSourceMap } from './serverPluginSourceMap' const debug = require('debug')('vite:sfc') const getEtag = require('etag') export const srcImportMap = new Map() interface CacheEntry { descriptor?: SFCDescriptor template?: ResultWithMap script?: ResultWithMap styles: SFCStyleCompileResults[] customs: string[] } interface ResultWithMap { code: string map: SourceMap | null | undefined } export const vueCache = new LRUCache<string, CacheEntry>({ max: 65535 }) export const vuePlugin: ServerPlugin = ({ root, app, resolver, watcher, config }) => { const etagCacheCheck = (ctx: Context) => { ctx.etag = getEtag(ctx.body) // only add 304 tag check if not using service worker to cache user code if (!config.serviceWorker) { ctx.status = seenUrls.has(ctx.url) && ctx.etag === ctx.get('If-None-Match') ? 304 : 200 seenUrls.add(ctx.url) } } app.use(async (ctx, next) => { if (!ctx.path.endsWith('.vue') && !ctx.vue) { return next() } const query = ctx.query const publicPath = ctx.path let filePath = resolver.requestToFile(publicPath) // upstream plugins could've already read the file const descriptor = await parseSFC(root, filePath, ctx.body) if (!descriptor) { debug(`${ctx.url} - 404`) ctx.status = 404 return } if (!query.type) { // watch potentially out of root vue file since we do a custom read here watchFileIfOutOfRoot(watcher, root, filePath) if (descriptor.script && descriptor.script.src) { filePath = await resolveSrcImport( root, descriptor.script, ctx, resolver ) } ctx.type = 'js' const { code, map } = await compileSFCMain( descriptor, filePath, publicPath ) ctx.body = code ctx.map = map return etagCacheCheck(ctx) } if (query.type === 'template') { const templateBlock = descriptor.template! if (templateBlock.src) { filePath = await resolveSrcImport(root, templateBlock, ctx, resolver) } ctx.type = 'js' const { code, map } = compileSFCTemplate( root, templateBlock, filePath, publicPath, descriptor.styles.some((s) => s.scoped), config.vueCompilerOptions ) ctx.body = code ctx.map = map return etagCacheCheck(ctx) } if (query.type === 'style') { const index = Number(query.index) const styleBlock = descriptor.styles[index] if (styleBlock.src) { filePath = await resolveSrcImport(root, styleBlock, ctx, resolver) } const id = hash_sum(publicPath) const result = await compileSFCStyle( root, styleBlock, index, filePath, publicPath, config.cssPreprocessOptions ) ctx.type = 'js' ctx.body = codegenCss(`${id}-${index}`, result.code, result.modules) return etagCacheCheck(ctx) } if (query.type === 'custom') { const index = Number(query.index) const customBlock = descriptor.customBlocks[index] if (customBlock.src) { filePath = await resolveSrcImport(root, customBlock, ctx, resolver) } const result = resolveCustomBlock( customBlock, index, filePath, publicPath ) ctx.type = 'js' ctx.body = result return etagCacheCheck(ctx) } }) const handleVueReload = (watcher.handleVueReload = async ( filePath: string, timestamp: number = Date.now(), content?: string ) => { const publicPath = resolver.fileToRequest(filePath) const cacheEntry = vueCache.get(filePath) const { send } = watcher debugHmr(`busting Vue cache for ${filePath}`) vueCache.del(filePath) const descriptor = await parseSFC(root, filePath, content) if (!descriptor) { // read failed return } const prevDescriptor = cacheEntry && cacheEntry.descriptor if (!prevDescriptor) { // the file has never been accessed yet debugHmr(`no existing descriptor found for ${filePath}`) return } // check which part of the file changed let needRerender = false const sendReload = () => { send({ type: 'vue-reload', path: publicPath, changeSrcPath: publicPath, timestamp }) console.log( chalk.green(`[vite:hmr] `) + `${path.relative(root, filePath)} updated. (reload)` ) } if (!isEqualBlock(descriptor.script, prevDescriptor.script)) { return sendReload() } if (!isEqualBlock(descriptor.template, prevDescriptor.template)) { needRerender = true } let didUpdateStyle = false const styleId = hash_sum(publicPath) const prevStyles = prevDescriptor.styles || [] const nextStyles = descriptor.styles || [] // css modules update causes a reload because the $style object is changed // and it may be used in JS. It also needs to trigger a vue-style-update // event so the client busts the sw cache. if ( prevStyles.some((s) => s.module != null) || nextStyles.some((s) => s.module != null) ) { return sendReload() } // force reload if scoped status has changed if (prevStyles.some((s) => s.scoped) !== nextStyles.some((s) => s.scoped)) { return sendReload() } // only need to update styles if not reloading, since reload forces // style updates as well. nextStyles.forEach((_, i) => { if (!prevStyles[i] || !isEqualBlock(prevStyles[i], nextStyles[i])) { didUpdateStyle = true const path = `${publicPath}?type=style&index=${i}` send({ type: 'style-update', path, changeSrcPath: path, timestamp }) } }) // stale styles always need to be removed prevStyles.slice(nextStyles.length).forEach((_, i) => { didUpdateStyle = true send({ type: 'style-remove', path: publicPath, id: `${styleId}-${i + nextStyles.length}` }) }) const prevCustoms = prevDescriptor.customBlocks || [] const nextCustoms = descriptor.customBlocks || [] // custom blocks update causes a reload // because the custom block contents is changed and it may be used in JS. if ( nextCustoms.some( (_, i) => !prevCustoms[i] || !isEqualBlock(prevCustoms[i], nextCustoms[i]) ) ) { return sendReload() } if (needRerender) { send({ type: 'vue-rerender', path: publicPath, changeSrcPath: publicPath, timestamp }) } let updateType = [] if (needRerender) { updateType.push(`template`) } if (didUpdateStyle) { updateType.push(`style`) } if (updateType.length) { console.log( chalk.green(`[vite:hmr] `) + `${path.relative(root, filePath)} updated. (${updateType.join( ' & ' )})` ) } }) watcher.on('change', (file) => { if (file.endsWith('.vue')) { handleVueReload(file) } }) } function isEqualBlock(a: SFCBlock | null, b: SFCBlock | null) { if (!a && !b) return true if (!a || !b) return false // src imports will trigger their own updates if (a.src && b.src && a.src === b.src) return true if (a.content !== b.content) return false const keysA = Object.keys(a.attrs) const keysB = Object.keys(b.attrs) if (keysA.length !== keysB.length) { return false } return keysA.every((key) => a.attrs[key] === b.attrs[key]) } async function resolveSrcImport( root: string, block: SFCBlock, ctx: Context, resolver: InternalResolver ) { const importer = ctx.path const importee = cleanUrl(resolveImport(root, importer, block.src!, resolver)) const filePath = resolver.requestToFile(importee) block.content = (await ctx.read(filePath)).toString() // register HMR import relationship debugHmr(` ${importer} imports ${importee}`) ensureMapEntry(importerMap, importee).add(ctx.path) srcImportMap.set(filePath, ctx.url) return filePath } async function parseSFC( root: string, filePath: string, content?: string | Buffer ): Promise<SFCDescriptor | undefined> { let cached = vueCache.get(filePath) if (cached && cached.descriptor) { debug(`${filePath} parse cache hit`) return cached.descriptor } if (!content) { try { content = await cachedRead(null, filePath) } catch (e) { return } } if (typeof content !== 'string') { content = content.toString() } const start = Date.now() const { parse, generateCodeFrame } = resolveCompiler(root) const { descriptor, errors } = parse(content, { filename: filePath, sourceMap: true }) if (errors.length) { console.error(chalk.red(`\n[vite] SFC parse error: `)) errors.forEach((e) => { const locString = e.loc ? `:${e.loc.start.line}:${e.loc.start.column}` : `` console.error(chalk.underline(filePath + locString)) console.error(chalk.yellow(e.message)) if (e.loc) { console.error( generateCodeFrame( content as string, e.loc.start.offset, e.loc.end.offset ) + `\n` ) } }) } cached = cached || { styles: [], customs: [] } cached.descriptor = descriptor vueCache.set(filePath, cached) debug(`${filePath} parsed in ${Date.now() - start}ms.`) return descriptor } const defaultExportRE = /((?:^|\n|;)\s*)export default/ async function compileSFCMain( descriptor: SFCDescriptor, filePath: string, publicPath: string ): Promise<ResultWithMap> { let cached = vueCache.get(filePath) if (cached && cached.script) { return cached.script } const id = hash_sum(publicPath) let code = `` if (descriptor.script) { let content = descriptor.script.content if (descriptor.script.lang === 'ts') { const { code, map } = await transform(content, publicPath, { loader: 'ts' }) content = code descriptor.script.map = mergeSourceMap( descriptor.script.map as SourceMap, JSON.parse(map!) ) as SourceMap & { version: string } } // rewrite export default. // fast path: simple regex replacement to avoid full-blown babel parse. let replaced = content.replace(defaultExportRE, '$1const __script =') // if the script somehow still contains `default export`, it probably has // multi-line comments or template strings. fallback to a full parse. if (defaultExportRE.test(replaced)) { replaced = rewriteDefaultExport(content) } code += replaced } else { code += `const __script = {}` } let hasScoped = false let hasCSSModules = false if (descriptor.styles) { descriptor.styles.forEach((s, i) => { const styleRequest = publicPath + `?type=style&index=${i}` if (s.scoped) hasScoped = true if (s.module) { if (!hasCSSModules) { code += `\nconst __cssModules = __script.__cssModules = {}` hasCSSModules = true } const styleVar = `__style${i}` const moduleName = typeof s.module === 'string' ? s.module : '$style' code += `\nimport ${styleVar} from ${JSON.stringify( styleRequest + '&module' )}` code += `\n__cssModules[${JSON.stringify(moduleName)}] = ${styleVar}` } else { code += `\nimport ${JSON.stringify(styleRequest)}` } }) if (hasScoped) { code += `\n__script.__scopeId = "data-v-${id}"` } } if (descriptor.customBlocks) { descriptor.customBlocks.forEach((c, i) => { const attrsQuery = attrsToQuery(c.attrs, c.lang) const blockTypeQuery = `&blockType=${qs.escape(c.type)}` let customRequest = publicPath + `?type=custom&index=${i}${blockTypeQuery}${attrsQuery}` const customVar = `block${i}` code += `\nimport ${customVar} from ${JSON.stringify(customRequest)}\n` code += `if (typeof ${customVar} === 'function') ${customVar}(__script)\n` }) } if (descriptor.template) { const templateRequest = publicPath + `?type=template` code += `\nimport { render as __render } from ${JSON.stringify( templateRequest )}` code += `\n__script.render = __render` } code += `\n__script.__hmrId = ${JSON.stringify(publicPath)}` code += `\n__script.__file = ${JSON.stringify(filePath)}` code += `\nexport default __script` const result: ResultWithMap = { code, map: descriptor.script && (descriptor.script.map as SourceMap) } cached = cached || { styles: [], customs: [] } cached.script = result vueCache.set(filePath, cached) return result } function compileSFCTemplate( root: string, template: SFCTemplateBlock, filePath: string, publicPath: string, scoped: boolean, userOptions: CompilerOptions | undefined ): ResultWithMap { let cached = vueCache.get(filePath) if (cached && cached.template) { debug(`${publicPath} template cache hit`) return cached.template } const start = Date.now() const { compileTemplate, generateCodeFrame } = resolveCompiler(root) const { code, map, errors } = compileTemplate({ source: template.content, filename: filePath, inMap: template.map, transformAssetUrls: { base: path.posix.dirname(publicPath) }, compilerOptions: { ...userOptions, scopeId: scoped ? `data-v-${hash_sum(publicPath)}` : null, runtimeModuleName: resolveVue(root).isLocal ? // in local mode, vue would have been optimized so must be referenced // with .js postfix '/@modules/vue.js' : '/@modules/vue' }, preprocessLang: template.lang, preprocessCustomRequire: (id: string) => require(resolveFrom(root, id)) }) if (errors.length) { console.error(chalk.red(`\n[vite] SFC template compilation error: `)) errors.forEach((e) => { if (typeof e === 'string') { console.error(e) } else { const locString = e.loc ? `:${e.loc.start.line}:${e.loc.start.column}` : `` console.error(chalk.underline(filePath + locString)) console.error(chalk.yellow(e.message)) if (e.loc) { const original = template.map!.sourcesContent![0] console.error( generateCodeFrame(original, e.loc.start.offset, e.loc.end.offset) + `\n` ) } } }) } const result = { code, map: map as SourceMap } cached = cached || { styles: [], customs: [] } cached.template = result vueCache.set(filePath, cached) debug(`${publicPath} template compiled in ${Date.now() - start}ms.`) return result } async function compileSFCStyle( root: string, style: SFCStyleBlock, index: number, filePath: string, publicPath: string, preprocessOptions: SFCStyleCompileOptions['preprocessOptions'] ): Promise<SFCStyleCompileResults> { let cached = vueCache.get(filePath) const cachedEntry = cached && cached.styles && cached.styles[index] if (cachedEntry) { debug(`${publicPath} style cache hit`) return cachedEntry } const start = Date.now() const { generateCodeFrame } = resolveCompiler(root) const result = (await compileCss(root, publicPath, { source: style.content, filename: filePath + `?type=style&index=${index}`, id: ``, // will be computed in compileCss scoped: style.scoped != null, modules: style.module != null, preprocessLang: style.lang as SFCStyleCompileOptions['preprocessLang'], preprocessOptions })) as SFCStyleCompileResults if (result.errors.length) { console.error(chalk.red(`\n[vite] SFC style compilation error: `)) result.errors.forEach((e: any) => { if (typeof e === 'string') { console.error(e) } else { const lineOffset = style.loc.start.line - 1 if (e.line && e.column) { console.log( chalk.underline(`${filePath}:${e.line + lineOffset}:${e.column}`) ) } else { console.log(chalk.underline(filePath)) } const filePathRE = new RegExp( '.*' + path.basename(filePath).replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&') + '(:\\d+:\\d+:\\s*)?' ) const cleanMsg = e.message.replace(filePathRE, '') console.error(chalk.yellow(cleanMsg)) if (e.line && e.column && cleanMsg.split(/\n/g).length === 1) { const original = style.map!.sourcesContent![0] const offset = original .split(/\r?\n/g) .slice(0, e.line + lineOffset - 1) .map((l) => l.length) .reduce((total, l) => total + l + 1, 0) + e.column - 1 console.error(generateCodeFrame(original, offset, offset + 1)) + `\n` } } }) } result.code = await rewriteCssUrls(result.code, publicPath) cached = cached || { styles: [], customs: [] } cached.styles[index] = result vueCache.set(filePath, cached) debug(`${publicPath} style compiled in ${Date.now() - start}ms`) return result } function resolveCustomBlock( custom: SFCBlock, index: number, filePath: string, publicPath: string ): string { let cached = vueCache.get(filePath) const cachedEntry = cached && cached.customs && cached.customs[index] if (cachedEntry) { debug(`${publicPath} custom block cache hit`) return cachedEntry } const result = custom.content cached = cached || { styles: [], customs: [] } cached.customs[index] = result vueCache.set(filePath, cached) return result } // these are built-in query parameters so should be ignored // if the user happen to add them as attrs const ignoreList = ['id', 'index', 'src', 'type'] function attrsToQuery(attrs: SFCBlock['attrs'], langFallback?: string): string { let query = `` for (const name in attrs) { const value = attrs[name] if (!ignoreList.includes(name)) { query += `&${qs.escape(name)}=${value ? qs.escape(String(value)) : ``}` } } if (langFallback && !(`lang` in attrs)) { query += `&lang=${langFallback}` } return query } function rewriteDefaultExport(code: string): string { const s = new MagicString(code) const ast = parse(code) ast.forEach((node) => { if (node.type === 'ExportDefaultDeclaration') { s.overwrite(node.start!, node.declaration.start!, `const __script = `) } }) const ret = s.toString() return ret }
src/node/server/serverPluginVue.ts
0
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.9974408149719238, 0.09722483158111572, 0.0001638146786717698, 0.0001722661982057616, 0.2627716660499573 ]
{ "id": 1, "code_window": [ " const src = await readBody(ctx.body)\n", " const { code, map } = await transform(\n", " src!,\n", " ctx.url,\n", " jsxConfig,\n", " config.jsx\n", " )\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " resolver.requestToFile(ctx.url),\n" ], "file_path": "src/node/server/serverPluginEsbuild.ts", "type": "replace", "edit_start_line_idx": 26 }
import fs from 'fs-extra' import path from 'path' import slash from 'slash' import { cleanUrl, resolveFrom, queryRE, lookupFile, parseNodeModuleId } from './utils' import { moduleRE, moduleIdToFileMap, moduleFileToIdMap } from './server/serverPluginModuleResolve' import { resolveOptimizedCacheDir } from './optimizer' import { hmrClientPublicPath } from './server/serverPluginHmr' import chalk from 'chalk' const debug = require('debug')('vite:resolve') const isWin = require('os').platform() === 'win32' const pathSeparator = isWin ? '\\' : '/' export interface Resolver { requestToFile?(publicPath: string, root: string): string | undefined fileToRequest?(filePath: string, root: string): string | undefined alias?: ((id: string) => string | undefined) | Record<string, string> } export interface InternalResolver { requestToFile(publicPath: string): string fileToRequest(filePath: string): string normalizePublicPath(publicPath: string): string alias(id: string): string | undefined resolveRelativeRequest( publicPath: string, relativePublicPath: string ): { pathname: string; query: string } } export const supportedExts = ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'] export const mainFields = ['module', 'jsnext', 'jsnext:main', 'browser', 'main'] const defaultRequestToFile = (publicPath: string, root: string): string => { if (moduleRE.test(publicPath)) { const id = publicPath.replace(moduleRE, '') const cachedNodeModule = moduleIdToFileMap.get(id) if (cachedNodeModule) { return cachedNodeModule } // try to resolve from optimized modules const optimizedModule = resolveOptimizedModule(root, id) if (optimizedModule) { return optimizedModule } // try to resolve from normal node_modules const nodeModule = resolveNodeModuleFile(root, id) if (nodeModule) { moduleIdToFileMap.set(id, nodeModule) return nodeModule } } const publicDirPath = path.join(root, 'public', publicPath.slice(1)) if (fs.existsSync(publicDirPath)) { return publicDirPath } return path.join(root, publicPath.slice(1)) } const defaultFileToRequest = (filePath: string, root: string): string => { const moduleRequest = moduleFileToIdMap.get(filePath) if (moduleRequest) { return moduleRequest } return `/${slash(path.relative(root, filePath))}` } const isFile = (file: string): boolean => { try { return fs.statSync(file).isFile() } catch (e) { return false } } /** * this function resolve fuzzy file path. examples: * /path/file is a fuzzy file path for /path/file.tsx * /path/dir is a fuzzy file path for /path/dir/index.js * * returning undefined indicates the filePath is not fuzzy: * it is already an exact file path, or it can't match any file */ const resolveFilePathPostfix = (filePath: string): string | undefined => { const cleanPath = cleanUrl(filePath) if (!isFile(cleanPath)) { let postfix = '' for (const ext of supportedExts) { if (isFile(cleanPath + ext)) { postfix = ext break } if (isFile(path.join(cleanPath, '/index' + ext))) { postfix = '/index' + ext break } } const queryMatch = filePath.match(/\?.*$/) const query = queryMatch ? queryMatch[0] : '' const resolved = cleanPath + postfix + query if (resolved !== filePath) { debug(`(postfix) ${filePath} -> ${resolved}`) return postfix } } } const isDir = (p: string) => fs.existsSync(p) && fs.statSync(p).isDirectory() export function createResolver( root: string, resolvers: Resolver[] = [], userAlias: Record<string, string> = {} ): InternalResolver { resolvers = [...resolvers] const literalAlias: Record<string, string> = {} const literalDirAlias: Record<string, string> = {} const resolveAlias = (alias: Record<string, string>) => { for (const key in alias) { let target = alias[key] // aliasing a directory if (key.startsWith('/') && key.endsWith('/') && path.isAbsolute(target)) { // check first if this is aliasing to a path from root const fromRoot = path.join(root, target) if (isDir(fromRoot)) { target = fromRoot } else if (!isDir(target)) { continue } resolvers.push({ requestToFile(publicPath) { if (publicPath.startsWith(key)) { return path.join(target, publicPath.slice(key.length)) } }, fileToRequest(filePath) { if (filePath.startsWith(target + pathSeparator)) { return slash(key + path.relative(target, filePath)) } } }) literalDirAlias[key] = target } else { literalAlias[key] = target } } } resolvers.forEach((r) => { if (r.alias && typeof r.alias === 'object') { resolveAlias(r.alias) } }) resolveAlias(userAlias) const requestToFileCache = new Map<string, string>() const fileToRequestCache = new Map<string, string>() const resolver: InternalResolver = { requestToFile(publicPath) { if (requestToFileCache.has(publicPath)) { return requestToFileCache.get(publicPath)! } let resolved: string | undefined for (const r of resolvers) { const filepath = r.requestToFile && r.requestToFile(publicPath, root) if (filepath) { resolved = filepath break } } if (!resolved) { resolved = defaultRequestToFile(publicPath, root) } const postfix = resolveFilePathPostfix(resolved) if (postfix) { if (postfix[0] === '/') { resolved = path.join(resolved, postfix) } else { resolved += postfix } } requestToFileCache.set(publicPath, resolved) return resolved }, fileToRequest(filePath) { if (fileToRequestCache.has(filePath)) { return fileToRequestCache.get(filePath)! } for (const r of resolvers) { const request = r.fileToRequest && r.fileToRequest(filePath, root) if (request) return request } const res = defaultFileToRequest(filePath, root) fileToRequestCache.set(filePath, res) return res }, /** * Given a fuzzy public path, resolve missing extensions and /index.xxx */ normalizePublicPath(publicPath) { if (publicPath === hmrClientPublicPath) { return publicPath } // preserve query const queryMatch = publicPath.match(/\?.*$/) const query = queryMatch ? queryMatch[0] : '' const cleanPublicPath = cleanUrl(publicPath) const finalize = (result: string) => { result += query if ( resolver.requestToFile(result) !== resolver.requestToFile(publicPath) ) { throw new Error( `[vite] normalizePublicPath check fail. please report to vite.` ) } return result } if (!moduleRE.test(cleanPublicPath)) { return finalize( resolver.fileToRequest(resolver.requestToFile(cleanPublicPath)) ) } const filePath = resolver.requestToFile(cleanPublicPath) const cacheDir = resolveOptimizedCacheDir(root) if (cacheDir) { const relative = path.relative(cacheDir, filePath) if (!relative.startsWith('..')) { return finalize(path.posix.join('/@modules/', slash(relative))) } } // fileToRequest doesn't work with files in node_modules // because of edge cases like symlinks or yarn-aliased-install // or even aliased-symlinks // example id: "@babel/runtime/helpers/esm/slicedToArray" // see the test case: /playground/TestNormalizePublicPath.vue const id = publicPath.replace(moduleRE, '') const { scope, name, inPkgPath } = parseNodeModuleId(id) if (!inPkgPath) return publicPath let filePathPostFix = '' let findPkgFrom = filePath while (!filePathPostFix.startsWith(inPkgPath)) { // some package contains multi package.json... // for example: @babel/[email protected]/helpers/esm/package.json const pkgPath = lookupFile(findPkgFrom, ['package.json'], true) if (!pkgPath) { throw new Error( `[vite] can't find package.json for a node_module file: ` + `"${publicPath}". something is wrong.` ) } filePathPostFix = slash(path.relative(path.dirname(pkgPath), filePath)) findPkgFrom = path.join(path.dirname(pkgPath), '../') } return finalize( ['/@modules', scope, name, filePathPostFix].filter(Boolean).join('/') ) }, alias(id) { let aliased: string | undefined = literalAlias[id] if (aliased) { return aliased } for (const r of resolvers) { aliased = r.alias && typeof r.alias === 'function' ? r.alias(id) : undefined if (aliased) { return aliased } } }, resolveRelativeRequest(importer: string, importee: string) { const queryMatch = importee.match(queryRE) let resolved = importee if (importee.startsWith('.')) { resolved = path.posix.resolve(path.posix.dirname(importer), importee) for (const alias in literalDirAlias) { if (importer.startsWith(alias)) { if (!resolved.startsWith(alias)) { // resolved path is outside of alias directory, we need to use // its full path instead const importerFilePath = resolver.requestToFile(importer) const importeeFilePath = path.resolve( path.dirname(importerFilePath), importee ) resolved = resolver.fileToRequest(importeeFilePath) } break } } } return { pathname: cleanUrl(resolved) + // path resolve strips ending / which should be preserved (importee.endsWith('/') && !resolved.endsWith('/') ? '/' : ''), query: queryMatch ? queryMatch[0] : '' } } } return resolver } export const jsSrcRE = /\.(?:(?:j|t)sx?|vue)$|\.mjs$/ const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\// /** * Redirects a bare module request to a full path under /@modules/ * It resolves a bare node module id to its full entry path so that relative * imports from the entry can be correctly resolved. * e.g.: * - `import 'foo'` -> `import '/@modules/foo/dist/index.js'` * - `import 'foo/bar/baz'` -> `import '/@modules/foo/bar/baz.js'` */ export function resolveBareModuleRequest( root: string, id: string, importer: string, resolver: InternalResolver ): string { const optimized = resolveOptimizedModule(root, id) if (optimized) { // ensure optimized module requests always ends with `.js` - this is because // optimized deps may import one another and in the built bundle their // relative import paths ends with `.js`. If we don't append `.js` during // rewrites, it may result in duplicated copies of the same dep. return path.extname(id) === '.js' ? id : id + '.js' } let isEntry = false const basedir = path.dirname(resolver.requestToFile(importer)) const pkgInfo = resolveNodeModule(basedir, id, resolver) if (pkgInfo) { if (!pkgInfo.entry) { console.error( chalk.yellow( `[vite] dependency ${id} does not have default entry defined in ` + `package.json.` ) ) } else { isEntry = true id = pkgInfo.entry } } if (!isEntry) { const deepMatch = !isEntry && id.match(deepImportRE) if (deepMatch) { // deep import const depId = deepMatch[1] || deepMatch[2] // check if this is a deep import to an optimized dep. if (resolveOptimizedModule(root, depId)) { if (resolver.alias(depId) === id) { // this is a deep import but aliased from a bare module id. // redirect it the optimized copy. return resolveBareModuleRequest(root, depId, importer, resolver) } // warn against deep imports to optimized dep console.error( chalk.yellow( `\n[vite] Avoid deep import "${id}" (imported by ${importer})\n` + `because "${depId}" has been pre-optimized by vite into a single file.\n` + `Prefer importing directly from the module entry:\n` + chalk.cyan(`\n import { ... } from "${depId}" \n\n`) + `If the dependency requires deep import to function properly, \n` + `add the deep path to ${chalk.cyan( `optimizeDeps.include` )} in vite.config.js.\n` ) ) } // resolve ext for deepImport const filePath = resolveNodeModuleFile(root, id) if (filePath) { const deepPath = id.replace(deepImportRE, '') const normalizedFilePath = slash(filePath) const postfix = normalizedFilePath.slice( normalizedFilePath.lastIndexOf(deepPath) + deepPath.length ) id += postfix } } } // check and warn deep imports on optimized modules const ext = path.extname(id) if (!jsSrcRE.test(ext)) { // append import query for non-js deep imports return id + (queryRE.test(id) ? '&import' : '?import') } else { return id } } const viteOptimizedMap = new Map() export function resolveOptimizedModule( root: string, id: string ): string | undefined { const cacheKey = `${root}#${id}` const cached = viteOptimizedMap.get(cacheKey) if (cached) { return cached } const cacheDir = resolveOptimizedCacheDir(root) if (!cacheDir) return if (!path.extname(id)) id += '.js' const file = path.join(cacheDir, id) if (fs.existsSync(file) && fs.statSync(file).isFile()) { viteOptimizedMap.set(cacheKey, file) return file } } interface NodeModuleInfo { entry: string | undefined entryFilePath: string | undefined pkg: any } const nodeModulesInfoMap = new Map<string, NodeModuleInfo>() const nodeModulesFileMap = new Map() export function resolveNodeModule( root: string, id: string, resolver: InternalResolver ): NodeModuleInfo | undefined { const cacheKey = `${root}#${id}` const cached = nodeModulesInfoMap.get(cacheKey) if (cached) { return cached } let pkgPath try { // see if the id is a valid package name pkgPath = resolveFrom(root, `${id}/package.json`) } catch (e) { debug(`failed to resolve package.json for ${id}`) } if (pkgPath) { // if yes, this is a entry import. resolve entry file let pkg try { pkg = fs.readJSONSync(pkgPath) } catch (e) { return } let entryPoint: string | undefined // TODO properly support conditional exports // https://nodejs.org/api/esm.html#esm_conditional_exports // Note: this would require @rollup/plugin-node-resolve to support it too // or we will have to implement that logic in vite's own resolve plugin. if (!entryPoint) { for (const field of mainFields) { if (typeof pkg[field] === 'string') { entryPoint = pkg[field] break } } } // resolve object browser field in package.json // https://github.com/defunctzombie/package-browser-field-spec const browserField = pkg.browser if (entryPoint && browserField && typeof browserField === 'object') { entryPoint = mapWithBrowserField(entryPoint, browserField) } debug(`(node_module entry) ${id} -> ${entryPoint}`) // save resolved entry file path using the deep import path as key // e.g. foo/dist/foo.js // this is the path raw imports will be rewritten to, and is what will // be passed to resolveNodeModuleFile(). let entryFilePath: string | undefined // respect user manual alias const aliased = resolver.alias(id) if (aliased && aliased !== id) { entryFilePath = resolveNodeModuleFile(root, aliased) } if (!entryFilePath && entryPoint) { // #284 some packages specify entry without extension... entryFilePath = path.join(path.dirname(pkgPath), entryPoint!) const postfix = resolveFilePathPostfix(entryFilePath) if (postfix) { entryPoint += postfix entryFilePath += postfix } entryPoint = path.posix.join(id, entryPoint!) // save the resolved file path now so we don't need to do it again in // resolveNodeModuleFile() nodeModulesFileMap.set(entryPoint, entryFilePath) } const result: NodeModuleInfo = { entry: entryPoint!, entryFilePath, pkg } nodeModulesInfoMap.set(cacheKey, result) return result } } export function resolveNodeModuleFile( root: string, id: string ): string | undefined { const cacheKey = `${root}#${id}` const cached = nodeModulesFileMap.get(cacheKey) if (cached) { return cached } try { const resolved = resolveFrom(root, id) nodeModulesFileMap.set(cacheKey, resolved) return resolved } catch (e) { // error will be reported downstream } } const normalize = path.posix.normalize /** * given a relative path in pkg dir, * return a relative path in pkg dir, * mapped with the "map" object */ function mapWithBrowserField( relativePathInPkgDir: string, map: Record<string, string> ) { const normalized = normalize(relativePathInPkgDir) const foundEntry = Object.entries(map).find(([from]) => { return normalize(from) === normalized }) if (!foundEntry) { return normalized } const [, to] = foundEntry return normalize(to) }
src/node/resolver.ts
0
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.978274941444397, 0.017034944146871567, 0.0001641585404286161, 0.00017002804088406265, 0.1273193359375 ]
{ "id": 2, "code_window": [ "import { ServerPlugin } from '.'\n", "import merge from 'merge-source-map'\n", "\n" ], "labels": [ "keep", "add", "keep" ], "after_edit": [ "import { ExistingRawSourceMap } from 'rollup'\n", "import { RawSourceMap } from 'source-map'\n" ], "file_path": "src/node/server/serverPluginSourceMap.ts", "type": "add", "edit_start_line_idx": 2 }
import { ServerPlugin } from '.' import merge from 'merge-source-map' export interface SourceMap { version: number | string file: string sources: string[] sourcesContent: string[] names: string[] mappings: string } export function mergeSourceMap( oldMap: SourceMap | null | undefined, newMap: SourceMap ): SourceMap { if (!oldMap) { return newMap } // merge-source-map will overwrite original sources if newMap also has // sourcesContent newMap.sourcesContent = [] return merge(oldMap, newMap) as SourceMap } function genSourceMapString(map: SourceMap | string | undefined) { if (typeof map !== 'string') { map = JSON.stringify(map) } return `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from( map ).toString('base64')}` } export const sourceMapPlugin: ServerPlugin = ({ app }) => { app.use(async (ctx, next) => { await next() if (typeof ctx.body === 'string' && ctx.map) { ctx.body += genSourceMapString(ctx.map) } }) }
src/node/server/serverPluginSourceMap.ts
1
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.31448349356651306, 0.06577605754137039, 0.00018076108244713396, 0.005093033891171217, 0.1243971735239029 ]
{ "id": 2, "code_window": [ "import { ServerPlugin } from '.'\n", "import merge from 'merge-source-map'\n", "\n" ], "labels": [ "keep", "add", "keep" ], "after_edit": [ "import { ExistingRawSourceMap } from 'rollup'\n", "import { RawSourceMap } from 'source-map'\n" ], "file_path": "src/node/server/serverPluginSourceMap.ts", "type": "add", "edit_start_line_idx": 2 }
environment: nodejs_version: '12' install: - ps: Install-Product node $env:nodejs_version x64 - yarn --frozen-lockfile test_script: - git --version - node --version - yarn --version - yarn build - yarn test - yarn test-sw cache: - node_modules -> yarn.lock build: off
appveyor.yml
0
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.0001756306446623057, 0.00017179970745928586, 0.00016796875570435077, 0.00017179970745928586, 0.000003830944478977472 ]
{ "id": 2, "code_window": [ "import { ServerPlugin } from '.'\n", "import merge from 'merge-source-map'\n", "\n" ], "labels": [ "keep", "add", "keep" ], "after_edit": [ "import { ExistingRawSourceMap } from 'rollup'\n", "import { RawSourceMap } from 'source-map'\n" ], "file_path": "src/node/server/serverPluginSourceMap.ts", "type": "add", "edit_start_line_idx": 2 }
import { createApp } from 'vue' import App from './App.vue' import './hmr/testHmrManual' createApp(App).mount('#app')
playground/main.js
0
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.0001670729834586382, 0.0001670729834586382, 0.0001670729834586382, 0.0001670729834586382, 0 ]
{ "id": 2, "code_window": [ "import { ServerPlugin } from '.'\n", "import merge from 'merge-source-map'\n", "\n" ], "labels": [ "keep", "add", "keep" ], "after_edit": [ "import { ExistingRawSourceMap } from 'rollup'\n", "import { RawSourceMap } from 'source-map'\n" ], "file_path": "src/node/server/serverPluginSourceMap.ts", "type": "add", "edit_start_line_idx": 2 }
export let __text = 'qux loaded' let domEl export function render(_domEl) { domEl = _domEl domEl.innerHTML = __text } if (import.meta.hot) { import.meta.hot.accept((newModule) => { newModule.render(domEl) }) }
playground/hmr/testHmrPropagationFullDynamicImportSelfAccepting.js
0
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.00017198068962898105, 0.00017083653074223548, 0.0001696923718554899, 0.00017083653074223548, 0.000001144158886745572 ]
{ "id": 3, "code_window": [ "\n", "export interface SourceMap {\n", " version: number | string\n", " file: string\n", " sources: string[]\n", " sourcesContent: string[]\n", " names: string[]\n", " mappings: string\n", "}\n", "\n", "export function mergeSourceMap(\n", " oldMap: SourceMap | null | undefined,\n", " newMap: SourceMap\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type SourceMap = ExistingRawSourceMap | RawSourceMap\n" ], "file_path": "src/node/server/serverPluginSourceMap.ts", "type": "replace", "edit_start_line_idx": 3 }
import { ServerPlugin } from '.' import merge from 'merge-source-map' export interface SourceMap { version: number | string file: string sources: string[] sourcesContent: string[] names: string[] mappings: string } export function mergeSourceMap( oldMap: SourceMap | null | undefined, newMap: SourceMap ): SourceMap { if (!oldMap) { return newMap } // merge-source-map will overwrite original sources if newMap also has // sourcesContent newMap.sourcesContent = [] return merge(oldMap, newMap) as SourceMap } function genSourceMapString(map: SourceMap | string | undefined) { if (typeof map !== 'string') { map = JSON.stringify(map) } return `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from( map ).toString('base64')}` } export const sourceMapPlugin: ServerPlugin = ({ app }) => { app.use(async (ctx, next) => { await next() if (typeof ctx.body === 'string' && ctx.map) { ctx.body += genSourceMapString(ctx.map) } }) }
src/node/server/serverPluginSourceMap.ts
1
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.9983870983123779, 0.40180549025535583, 0.00017510527686681598, 0.01231019850820303, 0.4868200421333313 ]
{ "id": 3, "code_window": [ "\n", "export interface SourceMap {\n", " version: number | string\n", " file: string\n", " sources: string[]\n", " sourcesContent: string[]\n", " names: string[]\n", " mappings: string\n", "}\n", "\n", "export function mergeSourceMap(\n", " oldMap: SourceMap | null | undefined,\n", " newMap: SourceMap\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type SourceMap = ExistingRawSourceMap | RawSourceMap\n" ], "file_path": "src/node/server/serverPluginSourceMap.ts", "type": "replace", "edit_start_line_idx": 3 }
<template> <h2>Wasm</h2> <p> <button class="wasm-send" @click="run">Click to run wasm</button> <span class="wasm-response">{{ res }}</span> </p> </template> <script> import { ref } from 'vue' import init from './simple.wasm' export default { async setup() { const res = ref() const { exported_func } = await init({ imports: { imported_func: (arg) => { res.value = `Wasm result: ${arg}` } } }) return { res, run: exported_func } } } </script>
playground/wasm/TestWasm.vue
0
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.00017678525182418525, 0.0001731798256514594, 0.00017080141697078943, 0.00017256633145734668, 0.00000220435958908638 ]
{ "id": 3, "code_window": [ "\n", "export interface SourceMap {\n", " version: number | string\n", " file: string\n", " sources: string[]\n", " sourcesContent: string[]\n", " names: string[]\n", " mappings: string\n", "}\n", "\n", "export function mergeSourceMap(\n", " oldMap: SourceMap | null | undefined,\n", " newMap: SourceMap\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type SourceMap = ExistingRawSourceMap | RawSourceMap\n" ], "file_path": "src/node/server/serverPluginSourceMap.ts", "type": "replace", "edit_start_line_idx": 3 }
import { render } from 'preact' import { Test } from './testTsx.tsx' const Component = () => <div> Rendered from Preact JSX <Test count={1337} /> </div> export function renderPreact(el) { render(<Component/>, el) }
playground/jsx/testJsx.jsx
0
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.0001733113022055477, 0.00017330015543848276, 0.0001732889941195026, 0.00017330015543848276, 1.1154045687078451e-8 ]
{ "id": 3, "code_window": [ "\n", "export interface SourceMap {\n", " version: number | string\n", " file: string\n", " sources: string[]\n", " sourcesContent: string[]\n", " names: string[]\n", " mappings: string\n", "}\n", "\n", "export function mergeSourceMap(\n", " oldMap: SourceMap | null | undefined,\n", " newMap: SourceMap\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type SourceMap = ExistingRawSourceMap | RawSourceMap\n" ], "file_path": "src/node/server/serverPluginSourceMap.ts", "type": "replace", "edit_start_line_idx": 3 }
<template> <h2>Static Asset Handling</h2> <p> Fonts should be italic if font asset reference from CSS works. </p> <p class="asset-import"> Path for assets import from js: <code>{{ filepath }}</code> </p> <p> Relative asset reference in template: <img src="./nested/testAssets.png" style="width: 30px;" /> </p> <p> Absolute asset reference in template: <img src="/icon.png" style="width: 30px;" /> </p> <div class="css-bg"> <span style="background: #fff;">CSS background</span> </div> <div class="css-import-bg"> <span style="background: #fff;">CSS background with relative paths</span> </div> <div class="css-bg-data-uri"> <span style="background: #fff;">CSS background with Data URI</span> </div> </template> <script> import './testAssets.css' import filepath from './nested/testAssets.png' export default { data() { return { filepath } } } </script> <style> @font-face { font-family: 'Inter'; font-style: italic; font-weight: 400; font-display: swap; src: url('../fonts/Inter-Italic.woff2?#iefix') format('woff2'), url('/fonts/Inter-Italic.woff') format('woff'); } body { font-family: 'Inter'; } .css-bg { background: url(/icon.png); background-size: 10px; } .css-bg-data-uri { background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA0CAYAAADWr1sfAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTM4IDc5LjE1OTgyNCwgMjAxNi8wOS8xNC0wMTowOTowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NTAyNkI1RkE4N0VCMTFFQUFBQzJENzUzNDFGRjc1N0UiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NTAyNkI1Rjk4N0VCMTFFQUFBQzJENzUzNDFGRjc1N0UiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChNYWNpbnRvc2gpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6QTc3NzA2Q0Y4N0FCMTFFM0I3MERFRTAzNzcwNkMxMjMiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6QTc3NzA2RDA4N0FCMTFFM0I3MERFRTAzNzcwNkMxMjMiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6nwnGxAAAJtklEQVR42txZ6W9c1RU/970373nsJHgZ27FThahSV8BCqGQTlIQ2EiUBReqHVpT8Af0r+NA/ogpqqWiDKrZuKYQPLGEpAlEFiqOgICSUBOKQhDjxeGY885bb37n3TGKPZ+4bx0uWK53Ec+cu53fPfkbtfu13B4noF6AQVAEpah0ak3cUSBU8qh46RfWj50ltKJDXXyBKdMtibI+TXlLqm2C87y/+eO/vlVIVnWbUcShFyld8T19ypvLbZKpyALOjVPCqrUcT1mWXYtIzMUV7Rqn315tJJyk+J51OZwb7QA3QkQD/fAL6JWiIXKMOhkOPwp1DFE/OkJ6NAQxn+fhuPhaFOc8DE9loern+hD9SfJVCdaLdOy5gif9rpHfyHp3pCX5cs6X1PfnORkr+SA9FO4bsgkZm1ykngm8ZK06ll0EvgWY6SwDn1fGKcykVfriewh2D5oKskhhw5KmFzLO0MJdO1yfS87UD2Uxc0tXErM+qLYQ5XUspK8el9JvagXSmPmH2W4lfG3wHNMHciXnmIfj+OvCVga8sD+yMYHyZAZ8H/Qk06dySaiNljf/DB0vklWAB1RQqnS0WA18eQE0Dz0++rjyRluOJDHuzWkwZNAPgLPHfPIeHTK/EEzHWKt/zDdh2asBmUUnJg3TDB0rQIuYptby5x6RgPO/JxIes304p44V1DMAzKQUbe4xqa62h2vbFyWuxeUie1RKqvVmXG/sxOaYKPqliQKp3HmEOB43pWaxJaTPvUV6rdK3Z6FloGUt35yD54EGXEwvaU3nSPSIYF7D5T/mio1rzS7Jaa1we4YWDzb1GUpptqJ1OGUl7BJX+jS7HP/OKEPlgRH5/SP5AZMjrCTz+jtdQQckxauEZ/IZ4bKyhYEsv7h6GpmGuhnsznafORwQbtQKGY6F/gy64pMxPnF2JSQ33UM/ecWNX/PJG3RbYsn15qCiYTQdhr49j9m4jQd8zXlkFZv3d/B087SBM4OodC+5kJYIX5r09+8ZIDYYAn4gqOdFeEEwn2gFmMb0BesEpZeOxARAOJ4SXjLbDlljKcbaQ0ebwrRNLy409oH1Xz1H2xrRc3wfaYx1dm/sgQTyYMZ1wZ4nC+4es76gnC3lqP14QTFk7wDymQH8DnXKCZibKiQHY89gY+aUeGwcT66xaw40JMUnWn52t7NWVeKt5GNaUarw1naruxXn9Rrrz9jRjLsd5PtsfZY3aaBZo9tT5qnxKsExRizto59EOccRzJQomHAC0DzsOHxwy3lvXk8VxU1u1VJFPaSW5B177SRtfNaVnq08izNyjQl9UefFe4zNwdoTI4I8XTfznu3NUORYMiyKP10HvD4neZy7VzqBaHEOjnw5TsKnXfgaDRjKqxWuzzRKtTy/Wt2W1ZAukuyX9tr4Ns+vZpheAVfKoOCuDKrNzDB8Ysp9Znd2qnAnvh9r5I8+hDs86HRhfCIlyQqGgbuHDI0Sz9gHaZj0sQXhhpJhbktOVp5Kvak/x31Sg9rarRXVxXvjwKJxk0Z7N/sOjPEf1bCez7LS1Ji/0iduBAUAD6JDpRFsHqfDjDZRdTqyU26gn2ykkXUovzf2KCV66ZGxXL9YeVtsMMb9w1x0U/WTAADWqnGO4wvMhwdA14PmqfbLjClZdTkaqCFPrAor2byIvUsZrd5Syp4BaFYW8RUmDeG8+wwsVRY+Pk7c+MJpkChXfCfhkJ1XuBjCPV0Bvt0nhFwoPiQfbVjixgaKHho3qGSlbgIu9ti/VEdHifJkdVc2aRoizwnv7kT+nNuy5hxZeX3EtygM8DfoX6FPnCcxL1Yap6NGNCCFFk5x0ETra2i7v9TcWqbh3zIbASmzvcHP7qfA6vRzAJIH7JWeYktRPz2a2bHuoZKpEdjgWdBeoWboMTpwea4o3GiF1lXzZPWLh8Y3ca7oAPAd6E/RubjLCkgBz4fYhCu6cl2d73UmX13KSUcDecNugqX2Np9a5mvKu8Di3EoB5HAP9WboGnZMRFiiXb0MhhYjNOrbeVsc5DPPexEqXz+C9HufLHHPT3PyxIbwd6wZIt4DnxCG81lG1JT9miZiaGeVj8L0+m3I2UrdaezY/z65Auj9ab0vPNLOlp+fEGwtPb3cj3aUA5nEWdDA3GTGMpqT6AupFmLLpYWaL9Hag2XZZdVHqcR1cfGzchDhdyWwFpnKTjIPCG600YFad96S+rHeOzZ5tB7Et3jeItLNk8+Fa2j6jYnU2YSyhaNcwFe4dMHv5DD7L1WUTXt5zmtoyADe7Bwfn15cdHZix3cxIzB+ObC+q2Z1Q6pq0E6gynF0A715ErasbqQWbH9JOCC8zSwGwVMA8Phb3X3a2g5BnZ5cRT78Dj7trxMRR7liY+lhdu5ntVnFDFLm4N1a0nr2e5rVtysLDx0tl/noAc9X7TLNH5KxZuC1Tg6puH0SYKtoaumFrYWPbsS0xg+/2UbjVVkNXW67u8aHwkKwFYB6fgQ47nYXXBBSbEBPtGjUtnWy6YcEm/F1q5sLdkO5AQTonuap8Vu7+7HoYv17APF4Fve6KrabEkzhcuH+AAuTFGmmjkeScbdsU7hswxGtMkqJzM7PX5W5aa8BfSDdwyt30I9Nw44qn+MgYef1IKC42SLN9D4TU8+iYCWGmKSfdEceYkju/uBGAebwvDW53KcOeFxlYcBeqqd3DBiznyCHCUPCDdUTsweM0765M7np/OQwvF/A5aYOedDcKmo23zP5qsalovTfny9wL4xQyP18+KXedu5GAmx0G9pizrsrAJCOQsuovUPTIKIU/HzG/SPKczks97dnPODswXY5gBQDXxK72g3a0fURT5yoTY7nw5w6ksVcAzZq/C7mbcv+TO2rLZXYlJMzjtNjXBedN7IlBXuibtq3ph8W5vw1dkLNPrwSjKwWY89oXQf9xNgqaXruaWLulXK8cy5kvOvP3GwC4mWc/50wImj+xaLrmpFRugvPcUvPltQJMUr0cXcHzjpLrF82bAHBN1O+dFTjrHTmrdjMD5vER6B/LZLQmZ3y00sytBuC65LtvLeOMt+SM+q0AmMekNNbK17G3LHsnV4Ox1QLM4wNRy3gJe2LZ88FqMbWagL8CPe2sptpXQ0/L3lsOMGcW3Cv+O+hyF+svy9pjsveWA9z0tn8Afd7F2s9lbW01GVptwJxTHZfE3/Uj17SsOU7ddLRuYsDN8decDOyorFn1sVaAvyT7k8iZNt+dke++vJ0A8+CfMw+3mT8s39HtBviSgDs+b+64zF26HQHz+C/o+Xmfn5c5ul0BXyT7w/U5oTdlbs1GQGs/vgb9cd7fazr+L8AAD0zRYMSYHQAAAAAASUVORK5CYII=); background-size: 10px; } </style>
playground/test-assets/TestAssets.vue
0
https://github.com/vitejs/vite/commit/4c21121bfb9565253715366b133d8bf18f5ae42d
[ 0.000658719742204994, 0.0002461879630573094, 0.00017338964971713722, 0.00017612756346352398, 0.0001684922754066065 ]
{ "id": 0, "code_window": [ " <a href={this.pageUrl('users.html', this.props.language)}>\n", " User Showcase\n", " </a>\n", " <a\n", " href=\"http://stackoverflow.com/questions/tagged/\"\n", " target=\"_blank\">\n", " Stack Overflow\n", " </a>\n", " <a href=\"https://discordapp.com/\">Project Chat</a>\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "examples/basics/core/Footer.js", "type": "replace", "edit_start_line_idx": 54 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); const MarkdownBlock = require('./MarkdownBlock.js'); const translate = require('../server/translate.js').translate; const editThisDoc = translate( 'Edit this Doc|recruitment message asking to edit the doc source' ); const translateThisDoc = translate( 'Translate this Doc|recruitment message asking to translate the docs' ); // inner doc component for article itself class Doc extends React.Component { render() { let docSource = this.props.source; if (this.props.version && this.props.version !== 'next') { // If versioning is enabled and the current version is not next, we need to trim out "version-*" from the source if we want a valid edit link. docSource = docSource.match(new RegExp(/version-.*\/(.*\.md)/, 'i'))[1]; } const editUrl = this.props.metadata.custom_edit_url || (this.props.config.editUrl && this.props.config.editUrl + docSource); let editLink = editUrl && ( <a className="edit-page-link button" href={editUrl} target="_blank"> {editThisDoc} </a> ); // If internationalization is enabled, show Recruiting link instead of Edit Link. if ( this.props.language && this.props.language != 'en' && this.props.config.translationRecruitingLink ) { editLink = ( <a className="edit-page-link button" href={ this.props.config.translationRecruitingLink + '/' + this.props.language } target="_blank"> {translateThisDoc} </a> ); } return ( <div className="post"> <header className="postHeader"> {editLink} <h1>{this.props.title}</h1> </header> <article> <MarkdownBlock>{this.props.content}</MarkdownBlock> </article> </div> ); } } module.exports = Doc;
lib/core/Doc.js
1
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.0005597936105914414, 0.0002817209460772574, 0.00017107883468270302, 0.0002174518449464813, 0.00013996662164572626 ]
{ "id": 0, "code_window": [ " <a href={this.pageUrl('users.html', this.props.language)}>\n", " User Showcase\n", " </a>\n", " <a\n", " href=\"http://stackoverflow.com/questions/tagged/\"\n", " target=\"_blank\">\n", " Stack Overflow\n", " </a>\n", " <a href=\"https://discordapp.com/\">Project Chat</a>\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "examples/basics/core/Footer.js", "type": "replace", "edit_start_line_idx": 54 }
--- id: commands title: CLI Commands --- Docusaurus provides a set of scripts to help you generate, serve, and deploy your website. These scripts can be invoked with the `run` command when using Yarn or npm. Some common commands are: * [`yarn run start`](api-commands.md#docusaurus-start-port-number): build and serve the website from a local server * [`yarn run examples`](api-commands.md#docusaurus-examples): create example configuration files ## Running from the command line The scripts can be run using either Yarn or npm. If you've already gone through our Getting Started guide, you may already be familiar with the `start` command. It's the command that tells Docusaurus to run the `docusaurus-start` script which generates the site and starts up a server, and it's usually invoked like so: ``` yarn run start ``` The same script can be invoked using npm: ``` npm run start ``` To run a particular script, just replace the `start` command in the examples above with the command associated with your script. ## Using arguments Some commands support optional arguments. For example, to start a server on port 8080, you can specify the `--port` argument when running `start`: ``` yarn run start --port 8080 ``` If you run Docusaurus using npm, you can still use the command line arguments by inserting a `--` between `npm run <command>` and the command arguments: ``` npm run start -- --port 8080 ``` ## Configuration These scripts are set up under the `"scripts"` key in your `website/package.json` file as part of the installation process. If you need help setting them up again, please refer to the [Installation guide](getting-started-installation.md). Docusaurus provides some default mappings to allow you to run commands following Node conventions. Instead of typing `docusaurus-start` every time, you can type `yarn run start` or `npm start` to achieve the same. ## Commands <AUTOGENERATED_TABLE_OF_CONTENTS> ----- ## Reference ### `docusaurus-build` Alias: `build`. Generates the static website, applying translations if necessary. Useful for building the website prior to deployment. See also [`docusaurus-start`](api-commands.md#docusaurus-start-port-number). --- ### `docusaurus-examples [feature]` Alias: `examples` When no feature is specified, sets up a minimally configured example website in your project. This command is covered in depth in the [Site Preparation guide](getting-started-preparation.md). Specify a feature `translations` or `versions` to generate the extra example files for that feature. --- ### `docusaurus-publish` Alias: `publish-gh-pages` [Builds](api-commands.md#docusaurus-build), then deploys the static website to GitHub Pages. This command is meant to be run during the deployment step in Circle CI, and therefore expects a few environment variables to be defined: The following is generally set manually by the user in the CircleCI `config.yml` file. - `GIT_USER`: The git user to be associated with the deploy commit. - `USE_SSH`: Whether to use SSH instead of HTTPS for your connection to the GitHub repo. e.g., ```bash GIT_USER=docusaurus-bot USE_SSH=true yarn run publish-gh-pages ``` The following are set by the [CircleCI environment](https://circleci.com/docs/1.0/environment-variables/) during the build process. - `CIRCLE_BRANCH`: The git branch associated with the commit that triggered the CI run. - `CI_PULL_REQUEST`: Expected to be truthy if the current CI run was triggered by a commit in a pull request. The following should be set by you in `siteConfig.js` as `organizationName` and `projectName`, respectively. If they are not set in your site configuration, they fall back to the [CircleCI environment](https://circleci.com/docs/1.0/environment-variables/). - `CIRCLE_PROJECT_USERNAME`: The GitHub username or organization name that hosts the git repo, e.g. "facebook". - `CIRCLE_PROJECT_REPONAME`: The name of the git repo, e.g. "Docusaurus". You can learn more about configuring automatic deployments with CircleCI in the [Publishing guide](getting-started-publishing.md). --- ### `docusaurus-rename-version <currentVersion> <newVersion>` Alias: `rename-version` Renames an existing version of the docs to a new version name. See the [Versioning guide](guides-versioning.md#renaming-existing-versions) to learn more. --- ### `docusaurus-start [--port <number>]` Alias: `start`. This script will build the static website, apply translations if necessary, and then start a local server. The website will be served from port 3000 by default. --- ### `docusaurus-version <version>` Alias: `version` Generates a new version of the docs. This will result in a new copy of your site being generated and stored in its own versioned folder. Useful for capturing snapshots of API docs that map to specific versions of your software. Accepts any string as a version number. See the [Versioning guide](guides-versioning.md) to learn more. --- ### `docusaurus-write-translations` Alias: `write-translations` Writes the English for any strings that need to be translated into an `website/i18n/en.json` file. The script will go through every file in `website/pages/en` and through the `siteConfig.js` file and other config files to fetch English strings that will then be translated on Crowdin. See the [Translation guide](guides-translation.md) to learn more.
docs/api-commands.md
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017296147416345775, 0.0001676156825851649, 0.0001597570808371529, 0.0001693985832389444, 0.000004337528025644133 ]
{ "id": 0, "code_window": [ " <a href={this.pageUrl('users.html', this.props.language)}>\n", " User Showcase\n", " </a>\n", " <a\n", " href=\"http://stackoverflow.com/questions/tagged/\"\n", " target=\"_blank\">\n", " Stack Overflow\n", " </a>\n", " <a href=\"https://discordapp.com/\">Project Chat</a>\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "examples/basics/core/Footer.js", "type": "replace", "edit_start_line_idx": 54 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const fs = require('fs-extra'); const path = require('path'); const os = require('os'); const Feed = require('feed'); const chalk = require('chalk'); const glob = require('glob'); const CWD = process.cwd(); const sitemap = require('sitemap'); const siteConfig = require(CWD + '/siteConfig.js'); /****************************************************************************/ let readMetadata; let Metadata; let MetadataBlog; readMetadata = require('./readMetadata.js'); readMetadata.generateMetadataDocs(); Metadata = require('../core/metadata.js'); readMetadata.generateMetadataBlog(); MetadataBlog = require('../core/MetadataBlog.js'); /****************************************************************************/ module.exports = function(callback) { console.log('sitemap.js triggered...'); let urls = []; let files = glob.sync(CWD + '/pages/en/**/*.js'); // English-only is the default. let enabledLanguages = [ { enabled: true, name: 'English', tag: 'en', }, ]; // If we have a languages.js file, get all the enabled languages in there if (fs.existsSync(CWD + '/languages.js')) { let languages = require(CWD + '/languages.js'); enabledLanguages = languages.filter(lang => { return lang.enabled == true; }); } // create a url mapping to all the enabled languages files files.map(file => { let url = file.split('/pages/en')[1]; url = url.replace(/\.js$/, '.html'); let links = enabledLanguages.map(lang => { let langUrl = lang.tag + url; return {lang: lang.tag, url: langUrl}; }); urls.push({url, changefreq: 'weekly', priority: 0.5, links}); }); let htmlFiles = glob.sync(CWD + '/pages/**/*.html'); MetadataBlog.map(blog => { urls.push({ url: '/blog/' + blog.path, changefreq: 'weekly', priority: 0.3, }); }); Object.keys(Metadata) .filter(key => Metadata[key].language === 'en') .map(key => { let doc = Metadata[key]; let links = enabledLanguages.map(lang => { let langUrl = doc.permalink.replace('docs/en/', `docs/${lang.tag}/`); return {lang: lang.tag, url: langUrl}; }); urls.push({ url: doc.permalink, changefreq: 'hourly', priority: 1.0, links, }); }); const sm = sitemap.createSitemap({ hostname: siteConfig.url, cacheTime: 600 * 1000, // 600 sec - cache purge period urls: urls, }); sm.toXML((err, xml) => { if (err) { return 'An error has occurred.'; } callback(xml); }); };
lib/server/sitemap.js
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017667419160716236, 0.0001718362036626786, 0.00016431575932074338, 0.0001726303162286058, 0.0000037228815017442685 ]
{ "id": 0, "code_window": [ " <a href={this.pageUrl('users.html', this.props.language)}>\n", " User Showcase\n", " </a>\n", " <a\n", " href=\"http://stackoverflow.com/questions/tagged/\"\n", " target=\"_blank\">\n", " Stack Overflow\n", " </a>\n", " <a href=\"https://discordapp.com/\">Project Chat</a>\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "examples/basics/core/Footer.js", "type": "replace", "edit_start_line_idx": 54 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const CWD = process.cwd(); const fs = require('fs-extra'); const path = require('path'); const join = path.join; const languages_js = join(CWD, 'languages.js'); const versions_json = join(CWD, 'versions.json'); class Translation { constructor() { this.enabled = false; this.languages = [ { enabled: true, name: 'English', tag: 'en', }, ]; this._load(); } enabledLanguages() { return this.languages.filter(lang => lang.enabled); } _load() { if (fs.existsSync(languages_js)) { this.enabled = true; this.languages = require(languages_js); } } } class Versioning { constructor() { this.enabled = false; this.latestVersion = null; this.versions = []; this._load(); } _load() { if (fs.existsSync(versions_json)) { this.enabled = true; this.versions = JSON.parse(fs.readFileSync(versions_json, 'utf8')); this.latestVersion = this.versions[0]; } } } const env = { translation: new Translation(), versioning: new Versioning(), }; module.exports = env;
lib/server/env.js
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017560103151481599, 0.00017078829114325345, 0.00016590108862146735, 0.00017061700054910034, 0.0000030446074106293963 ]
{ "id": 1, "code_window": [ " Stack Overflow\n", " </a>\n", " <a href=\"https://discordapp.com/\">Project Chat</a>\n", " <a href=\"https://twitter.com/\" target=\"_blank\">\n", " Twitter\n", " </a>\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " href=\"https://twitter.com/\"\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "examples/basics/core/Footer.js", "type": "replace", "edit_start_line_idx": 58 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); class Footer extends React.Component { docUrl(doc, language) { const baseUrl = this.props.config.baseUrl; return baseUrl + 'docs/' + (language ? language + '/' : '') + doc; } pageUrl(doc, language) { const baseUrl = this.props.config.baseUrl; return baseUrl + (language ? language + '/' : '') + doc; } render() { const currentYear = new Date().getFullYear(); return ( <footer className="nav-footer" id="footer"> <section className="sitemap"> <a href={this.props.config.baseUrl} className="nav-home"> {this.props.config.footerIcon && ( <img src={this.props.config.baseUrl + this.props.config.footerIcon} alt={this.props.config.title} width="66" height="58" /> )} </a> <div> <h5>Docs</h5> <a href={this.docUrl('doc1.html', this.props.language)}> Getting Started (or other categories) </a> <a href={this.docUrl('doc2.html', this.props.language)}> Guides (or other categories) </a> <a href={this.docUrl('doc3.html', this.props.language)}> API Reference (or other categories) </a> </div> <div> <h5>Community</h5> <a href={this.pageUrl('users.html', this.props.language)}> User Showcase </a> <a href="http://stackoverflow.com/questions/tagged/" target="_blank"> Stack Overflow </a> <a href="https://discordapp.com/">Project Chat</a> <a href="https://twitter.com/" target="_blank"> Twitter </a> </div> <div> <h5>More</h5> <a href={this.props.config.baseUrl + 'blog'}>Blog</a> <a href="https://github.com/">GitHub</a> <a className="github-button" href={this.props.config.repoUrl} data-icon="octicon-star" data-count-href="/facebook/docusaurus/stargazers" data-show-count={true} data-count-aria-label="# stargazers on GitHub" aria-label="Star this project on GitHub"> Star </a> </div> </section> <a href="https://code.facebook.com/projects/" target="_blank" className="fbOpenSource"> <img src={this.props.config.baseUrl + 'img/oss_logo.png'} alt="Facebook Open Source" width="170" height="45" /> </a> <section className="copyright">{this.props.config.copyright}</section> </footer> ); } } module.exports = Footer;
examples/basics/core/Footer.js
1
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.32436051964759827, 0.03259789198637009, 0.00016362096357624978, 0.00017318774189334363, 0.0972542092204094 ]
{ "id": 1, "code_window": [ " Stack Overflow\n", " </a>\n", " <a href=\"https://discordapp.com/\">Project Chat</a>\n", " <a href=\"https://twitter.com/\" target=\"_blank\">\n", " Twitter\n", " </a>\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " href=\"https://twitter.com/\"\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "examples/basics/core/Footer.js", "type": "replace", "edit_start_line_idx": 58 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const Metadata = require('./metadata.js'); const React = require('react'); const Container = require('./Container.js'); const SideNav = require('./nav/SideNav.js'); const siteConfig = require(process.cwd() + '/siteConfig.js'); const readCategories = require('../server/readCategories.js'); class DocsSidebar extends React.Component { render() { let sidebar = this.props.metadata.sidebar; let docsCategories = readCategories(sidebar); const categoryName = docsCategories[this.props.metadata.language][0].name; if (!categoryName) { return null; } return ( <Container className="docsNavContainer" id="docsNav" wrapper={false}> <SideNav language={this.props.metadata.language} root={this.props.root} title={this.props.title} contents={docsCategories[this.props.metadata.language]} current={this.props.metadata} /> </Container> ); } } module.exports = DocsSidebar;
lib/core/DocsSidebar.js
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.0001739749131957069, 0.0001700635184533894, 0.00016526733816135675, 0.00017050592578016222, 0.0000037797865388711216 ]
{ "id": 1, "code_window": [ " Stack Overflow\n", " </a>\n", " <a href=\"https://discordapp.com/\">Project Chat</a>\n", " <a href=\"https://twitter.com/\" target=\"_blank\">\n", " Twitter\n", " </a>\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " href=\"https://twitter.com/\"\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "examples/basics/core/Footer.js", "type": "replace", "edit_start_line_idx": 58 }
.DS_Store .vscode *.code-workspace node_modules lib/core/metadata.js lib/core/MetadataBlog.js lib/pages/ website/build/ website/i18n/* website/node_modules website/package-lock.json website/translated_docs website/yarn.lock
.gitignore
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017348820983897895, 0.00017341924831271172, 0.00017335030133835971, 0.00017341924831271172, 6.895425030961633e-8 ]
{ "id": 1, "code_window": [ " Stack Overflow\n", " </a>\n", " <a href=\"https://discordapp.com/\">Project Chat</a>\n", " <a href=\"https://twitter.com/\" target=\"_blank\">\n", " Twitter\n", " </a>\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " href=\"https://twitter.com/\"\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "examples/basics/core/Footer.js", "type": "replace", "edit_start_line_idx": 58 }
<?xml version="1.0" encoding="UTF-8"?> <svg width="200px" height="200px" viewBox="0 0 200 200" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- Generator: Sketch 46.1 (44463) - http://www.bohemiancoding.com/sketch --> <title>docusaurus</title> <desc>Created with Sketch.</desc> <defs></defs> <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="docusaurus"> <rect id="Rectangle" fill="#FFFFFF" x="99" y="52" width="84" height="34"></rect> <g id="Group-2" transform="translate(3.000000, 17.000000)"> <path d="M20,146 C12.602,146 6.157,141.973 2.697,136 C0.992,138.944 0,142.353 0,146 C0,157.046 8.954,166 20,166 L40,166 L40,146 L20,146 Z" id="Fill-1" fill="#3ECC5F"></path> <path d="M109.9805,40.376 L180.0005,36 L180.0005,26 C180.0005,14.954 171.0455,6 160.0005,6 L70.0005,6 L67.5005,1.67 C66.3885,-0.255 63.6115,-0.255 62.5005,1.67 L60.0005,6 L57.5005,1.67 C56.3885,-0.255 53.6115,-0.255 52.5005,1.67 L50.0005,6 L47.5005,1.67 C46.3885,-0.255 43.6115,-0.255 42.5005,1.67 L40.0005,6 C39.9785,6 39.9575,6.003 39.9355,6.003 L35.7935,1.862 C34.2225,0.291 31.5405,1.009 30.9645,3.156 L29.5965,8.26 L24.4035,6.868 C22.2565,6.293 20.2925,8.257 20.8685,10.404 L22.2595,15.597 L17.1565,16.964 C15.0095,17.54 14.2905,20.223 15.8615,21.794 L20.0025,25.936 C20.0025,25.957 20.0005,25.978 20.0005,26 L15.6695,28.5 C13.7455,29.611 13.7455,32.389 15.6695,33.5 L20.0005,36 L15.6695,38.5 C13.7455,39.611 13.7455,42.389 15.6695,43.5 L20.0005,46 L15.6695,48.5 C13.7455,49.611 13.7455,52.389 15.6695,53.5 L20.0005,56 L15.6695,58.5 C13.7455,59.611 13.7455,62.389 15.6695,63.5 L20.0005,66 L15.6695,68.5 C13.7455,69.611 13.7455,72.389 15.6695,73.5 L20.0005,76 L15.6695,78.5 C13.7455,79.611 13.7455,82.389 15.6695,83.5 L20.0005,86 L15.6695,88.5 C13.7455,89.611 13.7455,92.389 15.6695,93.5 L20.0005,96 L15.6695,98.5 C13.7455,99.611 13.7455,102.389 15.6695,103.5 L20.0005,106 L15.6695,108.5 C13.7455,109.611 13.7455,112.389 15.6695,113.5 L20.0005,116 L15.6695,118.5 C13.7455,119.611 13.7455,122.389 15.6695,123.5 L20.0005,126 L15.6695,128.5 C13.7455,129.611 13.7455,132.389 15.6695,133.5 L20.0005,136 L15.6695,138.5 C13.7455,139.611 13.7455,142.389 15.6695,143.5 L20.0005,146 C20.0005,157.046 28.9545,166 40.0005,166 L160.0005,166 C171.0455,166 180.0005,157.046 180.0005,146 L180.0005,66 L109.9805,61.624 C104.3705,61.273 100.0005,56.621 100.0005,51 C100.0005,45.379 104.3705,40.727 109.9805,40.376" id="Fill-3" fill="#3ECC5F"></path> <polygon id="Fill-5" fill="#3ECC5F" points="140 166 170 166 170 126 140 126"></polygon> <path d="M190,141 C189.781,141 189.572,141.037 189.361,141.064 C189.323,140.914 189.287,140.763 189.245,140.613 C191.051,139.859 192.32,138.079 192.32,136 C192.32,133.238 190.082,131 187.32,131 C186.182,131 185.145,131.396 184.304,132.036 C184.193,131.923 184.082,131.811 183.969,131.7 C184.596,130.864 184.98,129.838 184.98,128.713 C184.98,125.951 182.742,123.713 179.98,123.713 C177.915,123.713 176.143,124.966 175.381,126.754 C175.233,126.712 175.084,126.677 174.936,126.639 C174.963,126.428 175,126.219 175,126 C175,123.238 172.762,121 170,121 C167.238,121 165,123.238 165,126 C165,126.219 165.037,126.428 165.064,126.639 C164.916,126.677 164.767,126.712 164.619,126.754 C163.857,124.966 162.085,123.713 160.02,123.713 C157.258,123.713 155.02,125.951 155.02,128.713 C155.02,129.838 155.404,130.864 156.031,131.7 C152.314,135.332 150,140.393 150,146 C150,157.046 158.954,166 170,166 C179.339,166 187.16,159.59 189.361,150.936 C189.572,150.963 189.781,151 190,151 C192.762,151 195,148.762 195,146 C195,143.238 192.762,141 190,141" id="Fill-7" fill="#44D860"></path> <polygon id="Fill-8" fill="#3ECC5F" points="150 106 180 106 180 86 150 86"></polygon> <path d="M190,98.5 C191.381,98.5 192.5,97.381 192.5,96 C192.5,94.619 191.381,93.5 190,93.5 C189.891,93.5 189.786,93.519 189.681,93.532 C189.661,93.457 189.644,93.382 189.623,93.307 C190.525,92.93 191.16,92.039 191.16,91 C191.16,89.619 190.041,88.5 188.66,88.5 C188.091,88.5 187.572,88.697 187.152,89.018 C187.097,88.961 187.041,88.905 186.984,88.85 C187.298,88.433 187.49,87.919 187.49,87.356 C187.49,85.976 186.371,84.856 184.99,84.856 C183.957,84.856 183.071,85.483 182.69,86.377 C181.833,86.138 180.934,86 180,86 C174.478,86 170,90.478 170,96 C170,101.522 174.478,106 180,106 C180.934,106 181.833,105.862 182.69,105.623 C183.071,106.517 183.957,107.144 184.99,107.144 C186.371,107.144 187.49,106.024 187.49,104.644 C187.49,104.081 187.298,103.567 186.984,103.15 C187.041,103.095 187.097,103.039 187.152,102.982 C187.572,103.303 188.091,103.5 188.66,103.5 C190.041,103.5 191.16,102.381 191.16,101 C191.16,99.961 190.525,99.07 189.623,98.693 C189.644,98.619 189.661,98.543 189.681,98.468 C189.786,98.481 189.891,98.5 190,98.5" id="Fill-9" fill="#44D860"></path> <path d="M60,38.5 C58.619,38.5 57.5,37.381 57.5,36 C57.5,31.864 54.136,28.5 50,28.5 C45.864,28.5 42.5,31.864 42.5,36 C42.5,37.381 41.381,38.5 40,38.5 C38.619,38.5 37.5,37.381 37.5,36 C37.5,29.107 43.107,23.5 50,23.5 C56.893,23.5 62.5,29.107 62.5,36 C62.5,37.381 61.381,38.5 60,38.5" id="Fill-10" fill="#000000"></path> <path d="M100,166 L160,166 C171.046,166 180,157.046 180,146 L180,76 L120,76 C108.954,76 100,84.954 100,96 L100,166 Z" id="Fill-11" fill="#FFFF50"></path> <path d="M165.0195,107 L114.9805,107 C114.4275,107 113.9805,106.553 113.9805,106 C113.9805,105.447 114.4275,105 114.9805,105 L165.0195,105 C165.5725,105 166.0195,105.447 166.0195,106 C166.0195,106.553 165.5725,107 165.0195,107" id="Fill-12" fill="#000000"></path> <path d="M165.0195,127 L114.9805,127 C114.4275,127 113.9805,126.553 113.9805,126 C113.9805,125.447 114.4275,125 114.9805,125 L165.0195,125 C165.5725,125 166.0195,125.447 166.0195,126 C166.0195,126.553 165.5725,127 165.0195,127" id="Fill-13" fill="#000000"></path> <path d="M165.0195,147 L114.9805,147 C114.4275,147 113.9805,146.553 113.9805,146 C113.9805,145.447 114.4275,145 114.9805,145 L165.0195,145 C165.5725,145 166.0195,145.447 166.0195,146 C166.0195,146.553 165.5725,147 165.0195,147" id="Fill-14" fill="#000000"></path> <path d="M165.0195,97.1855 L114.9805,97.1855 C114.4275,97.1855 113.9805,96.7375 113.9805,96.1855 C113.9805,95.6325 114.4275,95.1855 114.9805,95.1855 L165.0195,95.1855 C165.5725,95.1855 166.0195,95.6325 166.0195,96.1855 C166.0195,96.7375 165.5725,97.1855 165.0195,97.1855" id="Fill-15" fill="#000000"></path> <path d="M165.0195,117 L114.9805,117 C114.4275,117 113.9805,116.553 113.9805,116 C113.9805,115.447 114.4275,115 114.9805,115 L165.0195,115 C165.5725,115 166.0195,115.447 166.0195,116 C166.0195,116.553 165.5725,117 165.0195,117" id="Fill-16" fill="#000000"></path> <path d="M165.0195,137 L114.9805,137 C114.4275,137 113.9805,136.553 113.9805,136 C113.9805,135.447 114.4275,135 114.9805,135 L165.0195,135 C165.5725,135 166.0195,135.447 166.0195,136 C166.0195,136.553 165.5725,137 165.0195,137" id="Fill-17" fill="#000000"></path> <path d="M180,44.6113 C179.988,44.6113 179.978,44.6053 179.966,44.6063 C176.876,44.7113 175.414,47.8023 174.124,50.5293 C172.778,53.3783 171.737,55.2323 170.031,55.1763 C168.142,55.1083 167.062,52.9743 165.918,50.7153 C164.604,48.1223 163.104,45.1803 159.955,45.2903 C156.909,45.3943 155.442,48.0843 154.148,50.4573 C152.771,52.9853 151.834,54.5223 150.027,54.4513 C148.1,54.3813 147.076,52.6463 145.891,50.6383 C144.57,48.4023 143.043,45.8883 139.955,45.9743 C136.961,46.0773 135.49,48.3593 134.192,50.3743 C132.819,52.5043 131.857,53.8023 130.027,53.7253 C128.054,53.6543 127.035,52.2153 125.856,50.5483 C124.532,48.6753 123.04,46.5553 119.961,46.6583 C117.033,46.7583 115.562,48.6273 114.265,50.2763 C113.033,51.8403 112.071,53.0783 110.036,53.0003 C109.484,52.9783 109.021,53.4113 109.001,53.9643 C108.98,54.5153 109.412,54.9793 109.964,55.0003 C112.981,55.1013 114.509,53.1993 115.836,51.5133 C117.013,50.0173 118.029,48.7263 120.029,48.6583 C121.955,48.5763 122.858,49.7733 124.224,51.7033 C125.521,53.5373 126.993,55.6173 129.955,55.7243 C133.058,55.8283 134.551,53.5093 135.873,51.4573 C137.055,49.6233 138.075,48.0403 140.023,47.9733 C141.816,47.9063 142.792,49.3233 144.168,51.6543 C145.465,53.8513 146.934,56.3403 149.955,56.4503 C153.08,56.5583 154.589,53.8293 155.904,51.4153 C157.043,49.3273 158.118,47.3543 160.023,47.2893 C161.816,47.2473 162.751,48.8843 164.134,51.6193 C165.426,54.1723 166.891,57.0643 169.959,57.1753 C170.016,57.1773 170.072,57.1783 170.128,57.1783 C173.192,57.1783 174.646,54.1033 175.933,51.3843 C177.072,48.9743 178.15,46.7033 180,46.6113 L180,44.6113 Z" id="Fill-24" fill="#000000"></path> <polygon id="Fill-18" fill="#3ECC5F" points="80 166 120 166 120 126 80 126"></polygon> <path d="M140,141 C139.781,141 139.572,141.037 139.361,141.064 C139.323,140.914 139.287,140.763 139.245,140.613 C141.051,139.859 142.32,138.079 142.32,136 C142.32,133.238 140.082,131 137.32,131 C136.182,131 135.145,131.396 134.304,132.036 C134.193,131.923 134.082,131.811 133.969,131.7 C134.596,130.864 134.98,129.838 134.98,128.713 C134.98,125.951 132.742,123.713 129.98,123.713 C127.915,123.713 126.143,124.966 125.381,126.754 C125.233,126.712 125.084,126.677 124.936,126.639 C124.963,126.428 125,126.219 125,126 C125,123.238 122.762,121 120,121 C117.238,121 115,123.238 115,126 C115,126.219 115.037,126.428 115.064,126.639 C114.916,126.677 114.767,126.712 114.619,126.754 C113.857,124.966 112.085,123.713 110.02,123.713 C107.258,123.713 105.02,125.951 105.02,128.713 C105.02,129.838 105.404,130.864 106.031,131.7 C102.314,135.332 100,140.393 100,146 C100,157.046 108.954,166 120,166 C129.339,166 137.16,159.59 139.361,150.936 C139.572,150.963 139.781,151 140,151 C142.762,151 145,148.762 145,146 C145,143.238 142.762,141 140,141" id="Fill-19" fill="#44D860"></path> <polygon id="Fill-20" fill="#3ECC5F" points="80 106 120 106 120 86 80 86"></polygon> <path d="M130,98.5 C131.381,98.5 132.5,97.381 132.5,96 C132.5,94.619 131.381,93.5 130,93.5 C129.891,93.5 129.786,93.519 129.681,93.532 C129.661,93.457 129.644,93.382 129.623,93.307 C130.525,92.93 131.16,92.039 131.16,91 C131.16,89.619 130.041,88.5 128.66,88.5 C128.091,88.5 127.572,88.697 127.152,89.018 C127.097,88.961 127.041,88.905 126.984,88.85 C127.298,88.433 127.49,87.919 127.49,87.356 C127.49,85.976 126.371,84.856 124.99,84.856 C123.957,84.856 123.071,85.483 122.69,86.377 C121.833,86.138 120.934,86 120,86 C114.478,86 110,90.478 110,96 C110,101.522 114.478,106 120,106 C120.934,106 121.833,105.862 122.69,105.623 C123.071,106.517 123.957,107.144 124.99,107.144 C126.371,107.144 127.49,106.024 127.49,104.644 C127.49,104.081 127.298,103.567 126.984,103.15 C127.041,103.095 127.097,103.039 127.152,102.982 C127.572,103.303 128.091,103.5 128.66,103.5 C130.041,103.5 131.16,102.381 131.16,101 C131.16,99.961 130.525,99.07 129.623,98.693 C129.644,98.619 129.661,98.543 129.681,98.468 C129.786,98.481 129.891,98.5 130,98.5" id="Fill-21" fill="#44D860"></path> <path d="M140,24.75 C139.84,24.75 139.67,24.73 139.51,24.7 C139.35,24.67 139.189,24.62 139.04,24.56 C138.89,24.5 138.75,24.42 138.609,24.33 C138.479,24.24 138.35,24.13 138.229,24.02 C138.12,23.9 138.01,23.78 137.92,23.64 C137.83,23.5 137.75,23.36 137.689,23.21 C137.63,23.06 137.58,22.9 137.55,22.74 C137.52,22.58 137.5,22.41 137.5,22.25 C137.5,22.09 137.52,21.92 137.55,21.76 C137.58,21.6 137.63,21.45 137.689,21.29 C137.75,21.14 137.83,21 137.92,20.86 C138.01,20.73 138.12,20.6 138.229,20.48 C138.35,20.37 138.479,20.26 138.609,20.17 C138.75,20.08 138.89,20 139.04,19.94 C139.189,19.88 139.35,19.83 139.51,19.8 C139.83,19.73 140.16,19.73 140.49,19.8 C140.649,19.83 140.81,19.88 140.96,19.94 C141.109,20 141.25,20.08 141.39,20.17 C141.52,20.26 141.649,20.37 141.77,20.48 C141.88,20.6 141.99,20.73 142.08,20.86 C142.17,21 142.25,21.14 142.31,21.29 C142.37,21.45 142.42,21.6 142.45,21.76 C142.479,21.92 142.5,22.09 142.5,22.25 C142.5,22.91 142.229,23.56 141.77,24.02 C141.649,24.13 141.52,24.24 141.39,24.33 C141.25,24.42 141.109,24.5 140.96,24.56 C140.81,24.62 140.649,24.67 140.49,24.7 C140.33,24.73 140.16,24.75 140,24.75" id="Fill-22" fill="#000000"></path> <path d="M160,23.5 C159.34,23.5 158.7,23.23 158.229,22.77 C158.12,22.65 158.01,22.52 157.92,22.39 C157.83,22.25 157.75,22.11 157.689,21.96 C157.63,21.81 157.58,21.65 157.55,21.49 C157.52,21.33 157.5,21.16 157.5,21 C157.5,20.34 157.77,19.7 158.229,19.23 C158.35,19.12 158.479,19.01 158.609,18.92 C158.75,18.83 158.89,18.75 159.04,18.69 C159.189,18.63 159.35,18.58 159.51,18.55 C159.83,18.48 160.17,18.48 160.49,18.55 C160.649,18.58 160.81,18.63 160.96,18.69 C161.109,18.75 161.25,18.83 161.39,18.92 C161.52,19.01 161.649,19.12 161.77,19.23 C162.229,19.7 162.5,20.34 162.5,21 C162.5,21.16 162.479,21.33 162.45,21.49 C162.42,21.65 162.37,21.81 162.31,21.96 C162.24,22.11 162.17,22.25 162.08,22.39 C161.99,22.52 161.88,22.65 161.77,22.77 C161.649,22.88 161.52,22.99 161.39,23.08 C161.25,23.17 161.109,23.25 160.96,23.31 C160.81,23.37 160.649,23.42 160.49,23.45 C160.33,23.48 160.16,23.5 160,23.5" id="Fill-23" fill="#000000"></path> </g> </g> </g> </svg>
website/static/img/docusaurus.svg
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00018694682512432337, 0.00017239122826140374, 0.00016399816377088428, 0.0001693099329713732, 0.000008986477951111738 ]
{ "id": 2, "code_window": [ "\n", " <a\n", " href=\"https://code.facebook.com/projects/\"\n", " target=\"_blank\"\n", " className=\"fbOpenSource\">\n", " <img\n", " src={this.props.config.baseUrl + 'img/oss_logo.png'}\n", " alt=\"Facebook Open Source\"\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " rel=\"noreferrer noopener\"\n" ], "file_path": "examples/basics/core/Footer.js", "type": "add", "edit_start_line_idx": 82 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); class Footer extends React.Component { docUrl(doc, language) { const baseUrl = this.props.config.baseUrl; return baseUrl + 'docs/' + (language ? language + '/' : '') + doc; } pageUrl(doc, language) { const baseUrl = this.props.config.baseUrl; return baseUrl + (language ? language + '/' : '') + doc; } render() { const currentYear = new Date().getFullYear(); return ( <footer className="nav-footer" id="footer"> <section className="sitemap"> <a href={this.props.config.baseUrl} className="nav-home"> {this.props.config.footerIcon && ( <img src={this.props.config.baseUrl + this.props.config.footerIcon} alt={this.props.config.title} width="66" height="58" /> )} </a> <div> <h5>Docs</h5> <a href={this.docUrl('doc1.html', this.props.language)}> Getting Started (or other categories) </a> <a href={this.docUrl('doc2.html', this.props.language)}> Guides (or other categories) </a> <a href={this.docUrl('doc3.html', this.props.language)}> API Reference (or other categories) </a> </div> <div> <h5>Community</h5> <a href={this.pageUrl('users.html', this.props.language)}> User Showcase </a> <a href="http://stackoverflow.com/questions/tagged/" target="_blank"> Stack Overflow </a> <a href="https://discordapp.com/">Project Chat</a> <a href="https://twitter.com/" target="_blank"> Twitter </a> </div> <div> <h5>More</h5> <a href={this.props.config.baseUrl + 'blog'}>Blog</a> <a href="https://github.com/">GitHub</a> <a className="github-button" href={this.props.config.repoUrl} data-icon="octicon-star" data-count-href="/facebook/docusaurus/stargazers" data-show-count={true} data-count-aria-label="# stargazers on GitHub" aria-label="Star this project on GitHub"> Star </a> </div> </section> <a href="https://code.facebook.com/projects/" target="_blank" className="fbOpenSource"> <img src={this.props.config.baseUrl + 'img/oss_logo.png'} alt="Facebook Open Source" width="170" height="45" /> </a> <section className="copyright">{this.props.config.copyright}</section> </footer> ); } } module.exports = Footer;
examples/basics/core/Footer.js
1
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.9971064925193787, 0.1003982424736023, 0.0001690139906713739, 0.0005380950169637799, 0.29890382289886475 ]
{ "id": 2, "code_window": [ "\n", " <a\n", " href=\"https://code.facebook.com/projects/\"\n", " target=\"_blank\"\n", " className=\"fbOpenSource\">\n", " <img\n", " src={this.props.config.baseUrl + 'img/oss_logo.png'}\n", " alt=\"Facebook Open Source\"\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " rel=\"noreferrer noopener\"\n" ], "file_path": "examples/basics/core/Footer.js", "type": "add", "edit_start_line_idx": 82 }
{ "bracketSpacing": false, "jsxBracketSameLine": true, "parser": "flow", "printWidth": 80, "proseWrap": "never", "singleQuote": true, "trailingComma": "es5" }
.prettierrc
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017225822375621647, 0.00017225822375621647, 0.00017225822375621647, 0.00017225822375621647, 0 ]
{ "id": 2, "code_window": [ "\n", " <a\n", " href=\"https://code.facebook.com/projects/\"\n", " target=\"_blank\"\n", " className=\"fbOpenSource\">\n", " <img\n", " src={this.props.config.baseUrl + 'img/oss_logo.png'}\n", " alt=\"Facebook Open Source\"\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " rel=\"noreferrer noopener\"\n" ], "file_path": "examples/basics/core/Footer.js", "type": "add", "edit_start_line_idx": 82 }
--- id: navigation title: Navigation and Sidebars --- ## Referencing Site Documents If you want to reference another document in your `docs` folder (or the location you set via the [optional `customDocsPath`](https://docusaurus.io/docs/en/site-config.html#optional-fields) path site configuration option), then you just use the name of the document you want to reference. For example, if you are in `doc2.md` and you want to reference `doc1.md`: ``` I am referencing a [document](doc1.md). ``` > Docusaurus currently does not support documents in nested folders; only in a flatfile structure. We are looking into adding support for nested folders. ## How Documents are Linked New markdown files within `docs` will show up as pages on the website. Links to those documents are created first by using the `id` in the header of each document. If there is no `id` field, then the name of the file will serve as the link name. For example, creating an empty file such as `docs/getting-started.md` will enable the new page URL as `/docs/getting-started.html`. Suppose you add this to your document: ``` --- id: intro title: Getting Started --- My *new content* here.. ``` If you set the `id` field in the markdown header of the file, the doc will then be accessed from a URL of the form `/docs/intro.html`. > You need an `id` field to be able to add the document to the sidebar. ## Adding Documents to a Sidebar Many times, you will want to add a document to a sidebar that will be associated with one of the headers in the top navigation bar of the website. The most common sidebar, and the one that comes installed when Docusaurus is initialized, is the `docs` sidebar. > "docs" is just a name. It has no inherit meaning. You can change it as you wish. You configure the contents of the sidebar, and the order of its documents, in the `website/sidebars.json` file. > Until you add your document to `website/sidebars.json`, they will only be accessible via a direct URL. The doc will not show up in any sidebar. Within `sidebars.json`, add the `id` you used in the document header to existing sidebar/category. In the below case, `docs` is the name of the sidebar and `Getting Started` is a category within the sidebar. ``` { "docs": { "Getting Started": [ "getting-started" ``` Or you can create a new category within the sidebar: ``` { "docs": { ... "My New Sidebar Category": [ "getting-started" ], ... ``` ### Adding New Sidebars You can also put a document in a new sidebar. In the following example, we are creating an `examples-sidebar` sidebar within `sidebars.json` that has a category called `My Example Category` containing a document with an `id` of `my-examples`. ``` { "examples-sidebar": { "My Example Category": [ "my-examples" ], }, ... ``` It is important to note that until you [add a document from the `"examples-sidebar"` sidebar to the nav bar](#additions-to-the-site-navigation-bar), it will be hidden. ## Additions to the Site Navigation Bar To expose sidebars, you will add clickable labels to the site navigation bar at the top of the website. You can add documents, pages and external links. ### Adding Documents After creating a new sidebar for the site by [adding](#adding-new-sidebars) it to `sidebars.json`, you can expose the new sidebar from the top navigation bar by editing the `headerLinks` field of `siteConfig.js`. ``` headerLinks: [ ... { doc: 'my-examples', label: 'Examples' }, ... ], ``` A label called `Examples` will be added to the site navigation bar and when you click on it at the top of your site, the `examples-sidebar` will be shown and the default document will be `my-examples`. ### Adding Custom Pages To add custom pages to the site navigation bar, entries can be added to the `headerLinks` of `siteConfig.js`. For example, if we have a page within `website/pages/help.js`, we can link to it by adding the following: ``` headerLinks: [ ... { page: 'help', label: 'Help' }, ... ], ``` A label called `Help` will be added to the site navigation bar and when you click on it at the top of your site, the content from the `help.js` page will be shown. ### Adding External Links Custom links can be added to the site navigation bar with the following entry in `siteConfig.js`: ``` headerLinks: [ ... { href: 'https://github.com/facebook/Docusaurus', label: 'GitHub' }, ... ], ``` A label called `GitHub` will be added to the site navigation bar and when you click on it at the top of your site, the content of the external link will be shown. > To open external links in a new tab, provide an `external: true` flag within the header link config. ## Site Navigation Bar Positioning You have limited control where the search and languages dropdown elements are shown in the site navigation bar at the top of your website. ### Search If search is enabled on your site, your search bar will appear to the right of your links. If you want to put the search bar between links in the header, add a search entry in the `headerLinks` config array: ``` headerLinks: [ { doc: 'foo', label: 'Foo' }, { search: true }, { doc: 'bar', label: 'Bar' }, ], ``` ### Languages Dropdown If translations is enabled on your site, the language dropdown will appear to the right of your links (and to the left of the search bar, if search is enabled). If you want to put the language selection drop down between links in the header, add a languages entry in the `headerLinks` config array: ``` headerLinks: [ { doc: 'foo', label: 'Foo' }, { languages: true }, { doc: 'bar', label: 'Bar' }, ], ``` ## Active Links In Site Navigation Bar The links in the top navigation bar get `siteNavItemActive` and `siteNavGroupActive` class names to allow you to style the currently active link different from the others. `siteNavItemActive` is applied when there's an exact match between the navigation link and the currently displayed web page. > This does not include links of type `href` which are meant for external links only. If you manually set an `href` in your headerLinks to an internal page, document, or blog post, it will not get the `siteNavItemActive` class even if that page is being displayed. `siteNavGroupActive` will be added to these links: * `doc` links that belong to the same sidebar as the currently displayed document * The blog link when a blog post, or the blog listing page is being displayed These are two separate class names so you can have the active styles applied to either exact matches only or a bit more broadly for docs that belong together. If you don't want to make this distinction you can add both classes to the same css rule. ## Secondary On-Page Navigation We support secondary on-page navigation so you can more easily see the topics associated with a given document. To enable this feature, you need to add the `onPageNav` site configuration [option](api-site-config.md#optional-fields) to your `siteConfig.js`. ``` onPageNav: 'separate', ``` Currently, `separate` is the only option available for this field. This provides a separate navigation on the right side of the page.
docs/guides-navigation.md
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00020283817138988525, 0.0001685674797045067, 0.00016179583326447755, 0.0001666907628532499, 0.000008780254574958235 ]
{ "id": 2, "code_window": [ "\n", " <a\n", " href=\"https://code.facebook.com/projects/\"\n", " target=\"_blank\"\n", " className=\"fbOpenSource\">\n", " <img\n", " src={this.props.config.baseUrl + 'img/oss_logo.png'}\n", " alt=\"Facebook Open Source\"\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " rel=\"noreferrer noopener\"\n" ], "file_path": "examples/basics/core/Footer.js", "type": "add", "edit_start_line_idx": 82 }
<?xml version="1.0" encoding="UTF-8"?> <svg width="200px" height="200px" viewBox="0 0 200 200" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- Generator: Sketch 46.1 (44463) - http://www.bohemiancoding.com/sketch --> <title>docusaurus_keytar</title> <desc>Created with Sketch.</desc> <defs> <path d="M4.88271903,0.0904207227 L4.88271903,1.17009735 L4.88271903,1.17009735 C4.88271903,1.7223821 4.43500378,2.17009735 3.88271903,2.17009735 L1,2.17009735 C0.44771525,2.17009735 -9.92435301e-14,1.7223821 -9.93094496e-14,1.17009735 L-9.93094496e-14,0.0904207227 L4.88271903,0.0904207227 Z" id="path-1"></path> <path d="M4.88271903,0.0904207227 L4.88271903,1.17009735 C4.88271903,1.7223821 4.43500378,2.17009735 3.88271903,2.17009735 L1,2.17009735 C0.44771525,2.17009735 -9.92851634e-14,1.7223821 -9.95974136e-14,1.17009735 L-9.95974136e-14,0.0904207227 L4.88271903,0.0904207227 Z" id="path-3"></path> </defs> <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="docusaurus_keytar"> <rect id="Rectangle" fill="#FFFFFF" x="99" y="52" width="84" height="34"></rect> <g id="Group-2" transform="translate(3.000000, 17.000000)"> <path d="M20,146 C12.602,146 6.157,141.973 2.697,136 C0.992,138.944 0,142.353 0,146 C0,157.046 8.954,166 20,166 L40,166 L40,146 L20,146 Z" id="Fill-1" fill="#3ECC5F"></path> <path d="M109.9805,40.376 L180.0005,36 L180.0005,26 C180.0005,14.954 171.0455,6 160.0005,6 L70.0005,6 L67.5005,1.67 C66.3885,-0.255 63.6115,-0.255 62.5005,1.67 L60.0005,6 L57.5005,1.67 C56.3885,-0.255 53.6115,-0.255 52.5005,1.67 L50.0005,6 L47.5005,1.67 C46.3885,-0.255 43.6115,-0.255 42.5005,1.67 L40.0005,6 C39.9785,6 39.9575,6.003 39.9355,6.003 L35.7935,1.862 C34.2225,0.291 31.5405,1.009 30.9645,3.156 L29.5965,8.26 L24.4035,6.868 C22.2565,6.293 20.2925,8.257 20.8685,10.404 L22.2595,15.597 L17.1565,16.964 C15.0095,17.54 14.2905,20.223 15.8615,21.794 L20.0025,25.936 C20.0025,25.957 20.0005,25.978 20.0005,26 L15.6695,28.5 C13.7455,29.611 13.7455,32.389 15.6695,33.5 L20.0005,36 L15.6695,38.5 C13.7455,39.611 13.7455,42.389 15.6695,43.5 L20.0005,46 L15.6695,48.5 C13.7455,49.611 13.7455,52.389 15.6695,53.5 L20.0005,56 L15.6695,58.5 C13.7455,59.611 13.7455,62.389 15.6695,63.5 L20.0005,66 L15.6695,68.5 C13.7455,69.611 13.7455,72.389 15.6695,73.5 L20.0005,76 L15.6695,78.5 C13.7455,79.611 13.7455,82.389 15.6695,83.5 L20.0005,86 L15.6695,88.5 C13.7455,89.611 13.7455,92.389 15.6695,93.5 L20.0005,96 L15.6695,98.5 C13.7455,99.611 13.7455,102.389 15.6695,103.5 L20.0005,106 L15.6695,108.5 C13.7455,109.611 13.7455,112.389 15.6695,113.5 L20.0005,116 L15.6695,118.5 C13.7455,119.611 13.7455,122.389 15.6695,123.5 L20.0005,126 L15.6695,128.5 C13.7455,129.611 13.7455,132.389 15.6695,133.5 L20.0005,136 L15.6695,138.5 C13.7455,139.611 13.7455,142.389 15.6695,143.5 L20.0005,146 C20.0005,157.046 28.9545,166 40.0005,166 L160.0005,166 C171.0455,166 180.0005,157.046 180.0005,146 L180.0005,66 L109.9805,61.624 C104.3705,61.273 100.0005,56.621 100.0005,51 C100.0005,45.379 104.3705,40.727 109.9805,40.376" id="Fill-3" fill="#3ECC5F"></path> <polygon id="Fill-5" fill="#3ECC5F" points="140 166 170 166 170 126 140 126"></polygon> <path d="M190,141 C189.781,141 189.572,141.037 189.361,141.064 C189.323,140.914 189.287,140.763 189.245,140.613 C191.051,139.859 192.32,138.079 192.32,136 C192.32,133.238 190.082,131 187.32,131 C186.182,131 185.145,131.396 184.304,132.036 C184.193,131.923 184.082,131.811 183.969,131.7 C184.596,130.864 184.98,129.838 184.98,128.713 C184.98,125.951 182.742,123.713 179.98,123.713 C177.915,123.713 176.143,124.966 175.381,126.754 C175.233,126.712 175.084,126.677 174.936,126.639 C174.963,126.428 175,126.219 175,126 C175,123.238 172.762,121 170,121 C167.238,121 165,123.238 165,126 C165,126.219 165.037,126.428 165.064,126.639 C164.916,126.677 164.767,126.712 164.619,126.754 C163.857,124.966 162.085,123.713 160.02,123.713 C157.258,123.713 155.02,125.951 155.02,128.713 C155.02,129.838 155.404,130.864 156.031,131.7 C152.314,135.332 150,140.393 150,146 C150,157.046 158.954,166 170,166 C179.339,166 187.16,159.59 189.361,150.936 C189.572,150.963 189.781,151 190,151 C192.762,151 195,148.762 195,146 C195,143.238 192.762,141 190,141" id="Fill-7" fill="#44D860"></path> <polygon id="Fill-8" fill="#3ECC5F" points="150 106 180 106 180 86 150 86"></polygon> <path d="M190,98.5 C191.381,98.5 192.5,97.381 192.5,96 C192.5,94.619 191.381,93.5 190,93.5 C189.891,93.5 189.786,93.519 189.681,93.532 C189.661,93.457 189.644,93.382 189.623,93.307 C190.525,92.93 191.16,92.039 191.16,91 C191.16,89.619 190.041,88.5 188.66,88.5 C188.091,88.5 187.572,88.697 187.152,89.018 C187.097,88.961 187.041,88.905 186.984,88.85 C187.298,88.433 187.49,87.919 187.49,87.356 C187.49,85.976 186.371,84.856 184.99,84.856 C183.957,84.856 183.071,85.483 182.69,86.377 C181.833,86.138 180.934,86 180,86 C174.478,86 170,90.478 170,96 C170,101.522 174.478,106 180,106 C180.934,106 181.833,105.862 182.69,105.623 C183.071,106.517 183.957,107.144 184.99,107.144 C186.371,107.144 187.49,106.024 187.49,104.644 C187.49,104.081 187.298,103.567 186.984,103.15 C187.041,103.095 187.097,103.039 187.152,102.982 C187.572,103.303 188.091,103.5 188.66,103.5 C190.041,103.5 191.16,102.381 191.16,101 C191.16,99.961 190.525,99.07 189.623,98.693 C189.644,98.619 189.661,98.543 189.681,98.468 C189.786,98.481 189.891,98.5 190,98.5" id="Fill-9" fill="#44D860"></path> <path d="M60,38.5 C58.619,38.5 57.5,37.381 57.5,36 C57.5,31.864 54.136,28.5 50,28.5 C45.864,28.5 42.5,31.864 42.5,36 C42.5,37.381 41.381,38.5 40,38.5 C38.619,38.5 37.5,37.381 37.5,36 C37.5,29.107 43.107,23.5 50,23.5 C56.893,23.5 62.5,29.107 62.5,36 C62.5,37.381 61.381,38.5 60,38.5" id="Fill-10" fill="#000000"></path> <path d="M100,166 L160,166 C171.046,166 180,157.046 180,146 L180,76 L120,76 C108.954,76 100,84.954 100,96 L100,166 Z" id="Fill-11" fill="#FFFF50"></path> <path d="M165.0195,107 L114.9805,107 C114.4275,107 113.9805,106.553 113.9805,106 C113.9805,105.447 114.4275,105 114.9805,105 L165.0195,105 C165.5725,105 166.0195,105.447 166.0195,106 C166.0195,106.553 165.5725,107 165.0195,107" id="Fill-12" fill="#000000"></path> <path d="M165.0195,127 L114.9805,127 C114.4275,127 113.9805,126.553 113.9805,126 C113.9805,125.447 114.4275,125 114.9805,125 L165.0195,125 C165.5725,125 166.0195,125.447 166.0195,126 C166.0195,126.553 165.5725,127 165.0195,127" id="Fill-13" fill="#000000"></path> <path d="M165.0195,147 L114.9805,147 C114.4275,147 113.9805,146.553 113.9805,146 C113.9805,145.447 114.4275,145 114.9805,145 L165.0195,145 C165.5725,145 166.0195,145.447 166.0195,146 C166.0195,146.553 165.5725,147 165.0195,147" id="Fill-14" fill="#000000"></path> <path d="M165.0195,97.1855 L114.9805,97.1855 C114.4275,97.1855 113.9805,96.7375 113.9805,96.1855 C113.9805,95.6325 114.4275,95.1855 114.9805,95.1855 L165.0195,95.1855 C165.5725,95.1855 166.0195,95.6325 166.0195,96.1855 C166.0195,96.7375 165.5725,97.1855 165.0195,97.1855" id="Fill-15" fill="#000000"></path> <path d="M165.0195,117 L114.9805,117 C114.4275,117 113.9805,116.553 113.9805,116 C113.9805,115.447 114.4275,115 114.9805,115 L165.0195,115 C165.5725,115 166.0195,115.447 166.0195,116 C166.0195,116.553 165.5725,117 165.0195,117" id="Fill-16" fill="#000000"></path> <path d="M165.0195,137 L114.9805,137 C114.4275,137 113.9805,136.553 113.9805,136 C113.9805,135.447 114.4275,135 114.9805,135 L165.0195,135 C165.5725,135 166.0195,135.447 166.0195,136 C166.0195,136.553 165.5725,137 165.0195,137" id="Fill-17" fill="#000000"></path> <path d="M180,44.6113 C179.988,44.6113 179.978,44.6053 179.966,44.6063 C176.876,44.7113 175.414,47.8023 174.124,50.5293 C172.778,53.3783 171.737,55.2323 170.031,55.1763 C168.142,55.1083 167.062,52.9743 165.918,50.7153 C164.604,48.1223 163.104,45.1803 159.955,45.2903 C156.909,45.3943 155.442,48.0843 154.148,50.4573 C152.771,52.9853 151.834,54.5223 150.027,54.4513 C148.1,54.3813 147.076,52.6463 145.891,50.6383 C144.57,48.4023 143.043,45.8883 139.955,45.9743 C136.961,46.0773 135.49,48.3593 134.192,50.3743 C132.819,52.5043 131.857,53.8023 130.027,53.7253 C128.054,53.6543 127.035,52.2153 125.856,50.5483 C124.532,48.6753 123.04,46.5553 119.961,46.6583 C117.033,46.7583 115.562,48.6273 114.265,50.2763 C113.033,51.8403 112.071,53.0783 110.036,53.0003 C109.484,52.9783 109.021,53.4113 109.001,53.9643 C108.98,54.5153 109.412,54.9793 109.964,55.0003 C112.981,55.1013 114.509,53.1993 115.836,51.5133 C117.013,50.0173 118.029,48.7263 120.029,48.6583 C121.955,48.5763 122.858,49.7733 124.224,51.7033 C125.521,53.5373 126.993,55.6173 129.955,55.7243 C133.058,55.8283 134.551,53.5093 135.873,51.4573 C137.055,49.6233 138.075,48.0403 140.023,47.9733 C141.816,47.9063 142.792,49.3233 144.168,51.6543 C145.465,53.8513 146.934,56.3403 149.955,56.4503 C153.08,56.5583 154.589,53.8293 155.904,51.4153 C157.043,49.3273 158.118,47.3543 160.023,47.2893 C161.816,47.2473 162.751,48.8843 164.134,51.6193 C165.426,54.1723 166.891,57.0643 169.959,57.1753 C170.016,57.1773 170.072,57.1783 170.128,57.1783 C173.192,57.1783 174.646,54.1033 175.933,51.3843 C177.072,48.9743 178.15,46.7033 180,46.6113 L180,44.6113 Z" id="Fill-24" fill="#000000"></path> <polygon id="Fill-18" fill="#3ECC5F" points="80 166 120 166 120 126 80 126"></polygon> <g id="Group-3" transform="translate(145.451771, 89.000000) rotate(-15.000000) translate(-145.451771, -89.000000) translate(102.951771, 72.000000)"> <rect id="Rectangle-6" fill="#D8D8D8" x="0.0459167733" y="0.0141282379" width="84.5221834" height="33.3670127" rx="2"></rect> <g id="Group-6" transform="translate(1.000000, 20.750000)" fill="#4A4A4A"> <rect id="Rectangle-7" x="15.8182544" y="0.339290564" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="21.6051807" y="0.339290564" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="27.3921069" y="0.339290564" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="33.1790332" y="0.339290564" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="38.9659594" y="0.339290564" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="44.7528857" y="0.339290564" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="50.539812" y="0.339290564" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="56.3267382" y="0.339290564" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="62.1136645" y="0.339290564" width="4.88271903" height="4.88271903" rx="1"></rect> <path d="M1.44673156,0.339290564 L13.7332058,0.339290564 L13.7332058,0.339290564 C14.2854905,0.339290564 14.7332058,0.787005814 14.7332058,1.33929056 L14.7332058,4.22200959 L14.7332058,4.22200959 C14.7332058,4.77429434 14.2854905,5.22200959 13.7332058,5.22200959 L1.44673156,5.22200959 L1.44673156,5.22200959 C0.894446814,5.22200959 0.446731564,4.77429434 0.446731564,4.22200959 L0.446731564,1.33929056 L0.446731564,1.33929056 C0.446731564,0.787005814 0.894446814,0.339290564 1.44673156,0.339290564 Z" id="Rectangle-7"></path> <path d="M69.0814322,0.339290564 L81.3679064,0.339290564 L81.3679064,0.339290564 C81.9201911,0.339290564 82.3679064,0.787005814 82.3679064,1.33929056 L82.3679064,4.22200959 L82.3679064,4.22200959 C82.3679064,4.77429434 81.9201911,5.22200959 81.3679064,5.22200959 L69.0814322,5.22200959 L69.0814322,5.22200959 C68.5291474,5.22200959 68.0814322,4.77429434 68.0814322,4.22200959 L68.0814322,1.33929056 L68.0814322,1.33929056 C68.0814322,0.787005814 68.5291474,0.339290564 69.0814322,0.339290564 Z" id="Rectangle-7"></path> </g> <g id="Group-4" transform="translate(1.000000, 9.000000)" fill="#4A4A4A"> <path d="M1.44673156,0.403755164 L6.13786505,0.403755164 L6.13786505,0.403755164 C6.6901498,0.403755164 7.13786505,0.851470414 7.13786505,1.40375516 L7.13786505,4.28647419 L7.13786505,4.28647419 C7.13786505,4.83875894 6.6901498,5.28647419 6.13786505,5.28647419 L1.44673156,5.28647419 L1.44673156,5.28647419 C0.894446814,5.28647419 0.446731564,4.83875894 0.446731564,4.28647419 L0.446731564,1.40375516 L0.446731564,1.40375516 C0.446731564,0.851470414 0.894446814,0.403755164 1.44673156,0.403755164 Z" id="Rectangle-7"></path> <rect id="Rectangle-7" x="8.04207227" y="0.403755164" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="13.8289985" y="0.403755164" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="19.6159248" y="0.403755164" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="25.402851" y="0.403755164" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="31.1897773" y="0.403755164" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="36.9767035" y="0.403755164" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="42.7636298" y="0.403755164" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="48.5505561" y="0.403755164" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="54.3374823" y="0.403755164" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="60.1244086" y="0.403755164" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="65.9113348" y="0.403755164" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="71.6982611" y="0.403755164" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="77.4851873" y="0.403755164" width="4.88271903" height="4.88271903" rx="1"></rect> </g> <g id="Group" transform="translate(42.367906, 6.250000) rotate(-180.000000) translate(-42.367906, -6.250000) translate(1.367906, 3.750000)" fill="#4A4A4A"> <path d="M1,1.06204379e-16 L5.69113348,-6.40356908e-18 L5.69113348,2.22044605e-16 C6.24341823,6.11117331e-16 6.69113348,0.44771525 6.69113348,1 L6.69113348,3.88271903 L6.69113348,3.88271903 C6.69113348,4.43500378 6.24341823,4.88271903 5.69113348,4.88271903 L1,4.88271903 L1,4.88271903 C0.44771525,4.88271903 6.76353751e-17,4.43500378 0,3.88271903 L0,1 L0,1 C-6.76353751e-17,0.44771525 0.44771525,3.23498823e-16 1,2.22044605e-16 Z" id="Rectangle-7"></path> <rect id="Rectangle-7" x="7.59534071" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="13.382267" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="19.1691932" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="24.9561195" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="30.7430457" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="36.529972" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="42.3168982" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="48.1038245" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="53.8907507" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="59.677677" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="65.4646033" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="71.2515295" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="77.0384558" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="7.59534071" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="13.382267" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="19.1691932" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="24.9561195" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="30.7430457" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="36.529972" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="42.3168982" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="48.1038245" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="53.8907507" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="59.677677" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="65.4646033" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="71.2515295" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="77.0384558" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> </g> <g id="Group-5" transform="translate(1.000000, 15.000000)" fill="#4A4A4A"> <path d="M1.44673156,0.190681419 L8.12712095,0.190681419 L8.12712095,0.190681419 C8.6794057,0.190681419 9.12712095,0.638396669 9.12712095,1.19068142 L9.12712095,4.07340045 L9.12712095,4.07340045 C9.12712095,4.6256852 8.6794057,5.07340045 8.12712095,5.07340045 L1.44673156,5.07340045 L1.44673156,5.07340045 C0.894446814,5.07340045 0.446731564,4.6256852 0.446731564,4.07340045 L0.446731564,1.19068142 L0.446731564,1.19068142 C0.446731564,0.638396669 0.894446814,0.190681419 1.44673156,0.190681419 Z" id="Rectangle-7"></path> <g id="Group-2" transform="translate(10.212170, 0.190681)"> <rect id="Rectangle-7" x="0" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="5.78692625" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="11.5738525" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="17.3607788" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="23.147705" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="28.9346313" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="34.7215575" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="40.5084838" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="46.29541" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="52.0823363" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" x="57.8692625" y="0" width="4.88271903" height="4.88271903" rx="1"></rect> </g> <path d="M75.0491999,0.190681419 L81.3679064,0.190681419 L81.3679064,0.190681419 C81.9201911,0.190681419 82.3679064,0.638396669 82.3679064,1.19068142 L82.3679064,4.07340045 L82.3679064,4.07340045 C82.3679064,4.6256852 81.9201911,5.07340045 81.3679064,5.07340045 L75.0491999,5.07340045 L75.0491999,5.07340045 C74.4969151,5.07340045 74.0491999,4.6256852 74.0491999,4.07340045 L74.0491999,1.19068142 L74.0491999,1.19068142 C74.0491999,0.638396669 74.4969151,0.190681419 75.0491999,0.190681419 Z" id="Rectangle-7"></path> </g> <g id="Group-7" transform="translate(1.000000, 26.000000)"> <rect id="Rectangle-7" fill="#4A4A4A" x="0.446731564" y="1.12621682" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" fill="#4A4A4A" x="6.23365782" y="1.12621682" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" fill="#4A4A4A" x="12.0205841" y="1.12621682" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" fill="#4A4A4A" x="17.8075103" y="1.12621682" width="4.88271903" height="4.88271903" rx="1"></rect> <path d="M24.5944366,1.12621682 L52.4332751,1.12621682 L52.4332751,1.12621682 C52.9855598,1.12621682 53.4332751,1.57393207 53.4332751,2.12621682 L53.4332751,5.00893585 L53.4332751,5.00893585 C53.4332751,5.5612206 52.9855598,6.00893585 52.4332751,6.00893585 L24.5944366,6.00893585 L24.5944366,6.00893585 C24.0421518,6.00893585 23.5944366,5.5612206 23.5944366,5.00893585 L23.5944366,2.12621682 L23.5944366,2.12621682 C23.5944366,1.57393207 24.0421518,1.12621682 24.5944366,1.12621682 Z" id="Rectangle-7" fill="#4A4A4A"></path> <path d="M55.3374823,1.12621682 L58.9435671,1.12621682 L58.9435671,1.12621682 C59.4958519,1.12621682 59.9435671,1.57393207 59.9435671,2.12621682 L59.9435671,5.00893585 L59.9435671,5.00893585 C59.9435671,5.5612206 59.4958519,6.00893585 58.9435671,6.00893585 L55.3374823,6.00893585 L55.3374823,6.00893585 C54.7851976,6.00893585 54.3374823,5.5612206 54.3374823,5.00893585 L54.3374823,2.12621682 L54.3374823,2.12621682 C54.3374823,1.57393207 54.7851976,1.12621682 55.3374823,1.12621682 Z" id="Rectangle-7" fill="#4A4A4A"></path> <rect id="Rectangle-7" fill="#4A4A4A" x="60.8477743" y="1.12621682" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" fill="#4A4A4A" x="66.6347006" y="1.12621682" width="4.88271903" height="4.88271903" rx="1"></rect> <rect id="Rectangle-7" fill="#4A4A4A" x="77.4851873" y="1.12621682" width="4.88271903" height="4.88271903" rx="1"></rect> <g id="Rectangle-8" transform="translate(74.442663, 1.796314) rotate(-180.000000) translate(-74.442663, -1.796314) translate(71.942663, 0.296314)"> <mask id="mask-2" fill="white"> <use xlink:href="#path-1"></use> </mask> <use id="Combined-Shape" fill="#4A4A4A" xlink:href="#path-1"></use> </g> <g id="Rectangle-8" transform="translate(74.559944, 5.338839) rotate(-360.000000) translate(-74.559944, -5.338839) translate(72.059944, 3.838839)"> <mask id="mask-4" fill="white"> <use xlink:href="#path-3"></use> </mask> <use id="Combined-Shape" fill="#4A4A4A" xlink:href="#path-3"></use> </g> </g> <rect id="Rectangle-9" fill="#4A4A4A" x="1.80841445" y="1.08504867" width="81.3786505" height="2.17009735" rx="1.08504867"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="3.79767035" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="10.0421793" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="14.8456478" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="19.6491162" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="24.4525847" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="30.4569202" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="35.2603887" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="40.0638571" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="44.8673255" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="50.8716611" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="55.6751295" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="60.478598" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="66.4829335" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="71.286402" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> <rect id="Rectangle-10" fill="#D8D8D8" opacity="0.135643116" x="76.0898704" y="1.44673156" width="4.56329502" height="1.44673156" rx="0.723365782"></rect> </g> <path d="M140,141 C139.781,141 139.572,141.037 139.361,141.064 C139.323,140.914 139.287,140.763 139.245,140.613 C141.051,139.859 142.32,138.079 142.32,136 C142.32,133.238 140.082,131 137.32,131 C136.182,131 135.145,131.396 134.304,132.036 C134.193,131.923 134.082,131.811 133.969,131.7 C134.596,130.864 134.98,129.838 134.98,128.713 C134.98,125.951 132.742,123.713 129.98,123.713 C127.915,123.713 126.143,124.966 125.381,126.754 C125.233,126.712 125.084,126.677 124.936,126.639 C124.963,126.428 125,126.219 125,126 C125,123.238 122.762,121 120,121 C117.238,121 115,123.238 115,126 C115,126.219 115.037,126.428 115.064,126.639 C114.916,126.677 114.767,126.712 114.619,126.754 C113.857,124.966 112.085,123.713 110.02,123.713 C107.258,123.713 105.02,125.951 105.02,128.713 C105.02,129.838 105.404,130.864 106.031,131.7 C102.314,135.332 100,140.393 100,146 C100,157.046 108.954,166 120,166 C129.339,166 137.16,159.59 139.361,150.936 C139.572,150.963 139.781,151 140,151 C142.762,151 145,148.762 145,146 C145,143.238 142.762,141 140,141" id="Fill-19" fill="#44D860"></path> <polygon id="Fill-20" fill="#3ECC5F" points="80 106 120 106 120 86 80 86"></polygon> <path d="M130,98.5 C131.381,98.5 132.5,97.381 132.5,96 C132.5,94.619 131.381,93.5 130,93.5 C129.891,93.5 129.786,93.519 129.681,93.532 C129.661,93.457 129.644,93.382 129.623,93.307 C130.525,92.93 131.16,92.039 131.16,91 C131.16,89.619 130.041,88.5 128.66,88.5 C128.091,88.5 127.572,88.697 127.152,89.018 C127.097,88.961 127.041,88.905 126.984,88.85 C127.298,88.433 127.49,87.919 127.49,87.356 C127.49,85.976 126.371,84.856 124.99,84.856 C123.957,84.856 123.071,85.483 122.69,86.377 C121.833,86.138 120.934,86 120,86 C114.478,86 110,90.478 110,96 C110,101.522 114.478,106 120,106 C120.934,106 121.833,105.862 122.69,105.623 C123.071,106.517 123.957,107.144 124.99,107.144 C126.371,107.144 127.49,106.024 127.49,104.644 C127.49,104.081 127.298,103.567 126.984,103.15 C127.041,103.095 127.097,103.039 127.152,102.982 C127.572,103.303 128.091,103.5 128.66,103.5 C130.041,103.5 131.16,102.381 131.16,101 C131.16,99.961 130.525,99.07 129.623,98.693 C129.644,98.619 129.661,98.543 129.681,98.468 C129.786,98.481 129.891,98.5 130,98.5" id="Fill-21" fill="#44D860"></path> <path d="M140,24.75 C139.84,24.75 139.67,24.73 139.51,24.7 C139.35,24.67 139.189,24.62 139.04,24.56 C138.89,24.5 138.75,24.42 138.609,24.33 C138.479,24.24 138.35,24.13 138.229,24.02 C138.12,23.9 138.01,23.78 137.92,23.64 C137.83,23.5 137.75,23.36 137.689,23.21 C137.63,23.06 137.58,22.9 137.55,22.74 C137.52,22.58 137.5,22.41 137.5,22.25 C137.5,22.09 137.52,21.92 137.55,21.76 C137.58,21.6 137.63,21.45 137.689,21.29 C137.75,21.14 137.83,21 137.92,20.86 C138.01,20.73 138.12,20.6 138.229,20.48 C138.35,20.37 138.479,20.26 138.609,20.17 C138.75,20.08 138.89,20 139.04,19.94 C139.189,19.88 139.35,19.83 139.51,19.8 C139.83,19.73 140.16,19.73 140.49,19.8 C140.649,19.83 140.81,19.88 140.96,19.94 C141.109,20 141.25,20.08 141.39,20.17 C141.52,20.26 141.649,20.37 141.77,20.48 C141.88,20.6 141.99,20.73 142.08,20.86 C142.17,21 142.25,21.14 142.31,21.29 C142.37,21.45 142.42,21.6 142.45,21.76 C142.479,21.92 142.5,22.09 142.5,22.25 C142.5,22.91 142.229,23.56 141.77,24.02 C141.649,24.13 141.52,24.24 141.39,24.33 C141.25,24.42 141.109,24.5 140.96,24.56 C140.81,24.62 140.649,24.67 140.49,24.7 C140.33,24.73 140.16,24.75 140,24.75" id="Fill-22" fill="#000000"></path> <path d="M160,23.5 C159.34,23.5 158.7,23.23 158.229,22.77 C158.12,22.65 158.01,22.52 157.92,22.39 C157.83,22.25 157.75,22.11 157.689,21.96 C157.63,21.81 157.58,21.65 157.55,21.49 C157.52,21.33 157.5,21.16 157.5,21 C157.5,20.34 157.77,19.7 158.229,19.23 C158.35,19.12 158.479,19.01 158.609,18.92 C158.75,18.83 158.89,18.75 159.04,18.69 C159.189,18.63 159.35,18.58 159.51,18.55 C159.83,18.48 160.17,18.48 160.49,18.55 C160.649,18.58 160.81,18.63 160.96,18.69 C161.109,18.75 161.25,18.83 161.39,18.92 C161.52,19.01 161.649,19.12 161.77,19.23 C162.229,19.7 162.5,20.34 162.5,21 C162.5,21.16 162.479,21.33 162.45,21.49 C162.42,21.65 162.37,21.81 162.31,21.96 C162.24,22.11 162.17,22.25 162.08,22.39 C161.99,22.52 161.88,22.65 161.77,22.77 C161.649,22.88 161.52,22.99 161.39,23.08 C161.25,23.17 161.109,23.25 160.96,23.31 C160.81,23.37 160.649,23.42 160.49,23.45 C160.33,23.48 160.16,23.5 160,23.5" id="Fill-23" fill="#000000"></path> </g> </g> </g> </svg>
website/static/img/docusaurus_keytar.svg
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.0034165484830737114, 0.00042969893547706306, 0.00016215461073443294, 0.00016577908536419272, 0.0007855577860027552 ]
{ "id": 3, "code_window": [ " (post.author && post.authorTitle ? ' authorPhoto-big' : '');\n", " if (post.authorFBID) {\n", " return (\n", " <div className={className}>\n", " <a href={post.authorURL} target=\"_blank\">\n", " <img\n", " src={\n", " 'https://graph.facebook.com/' +\n", " post.authorFBID +\n", " '/picture/?height=200&width=200'\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a href={post.authorURL} target=\"_blank\" rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/BlogPost.js", "type": "replace", "edit_start_line_idx": 46 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); class Footer extends React.Component { docUrl(doc, language) { const baseUrl = this.props.config.baseUrl; return baseUrl + 'docs/' + (language ? language + '/' : '') + doc; } pageUrl(doc, language) { const baseUrl = this.props.config.baseUrl; return baseUrl + (language ? language + '/' : '') + doc; } render() { const currentYear = new Date().getFullYear(); return ( <footer className="nav-footer" id="footer"> <section className="sitemap"> <a href={this.props.config.baseUrl} className="nav-home"> {this.props.config.footerIcon && ( <img src={this.props.config.baseUrl + this.props.config.footerIcon} alt={this.props.config.title} width="66" height="58" /> )} </a> <div> <h5>Docs</h5> <a href={this.docUrl('doc1.html', this.props.language)}> Getting Started (or other categories) </a> <a href={this.docUrl('doc2.html', this.props.language)}> Guides (or other categories) </a> <a href={this.docUrl('doc3.html', this.props.language)}> API Reference (or other categories) </a> </div> <div> <h5>Community</h5> <a href={this.pageUrl('users.html', this.props.language)}> User Showcase </a> <a href="http://stackoverflow.com/questions/tagged/" target="_blank"> Stack Overflow </a> <a href="https://discordapp.com/">Project Chat</a> <a href="https://twitter.com/" target="_blank"> Twitter </a> </div> <div> <h5>More</h5> <a href={this.props.config.baseUrl + 'blog'}>Blog</a> <a href="https://github.com/">GitHub</a> <a className="github-button" href={this.props.config.repoUrl} data-icon="octicon-star" data-count-href="/facebook/docusaurus/stargazers" data-show-count={true} data-count-aria-label="# stargazers on GitHub" aria-label="Star this project on GitHub"> Star </a> </div> </section> <a href="https://code.facebook.com/projects/" target="_blank" className="fbOpenSource"> <img src={this.props.config.baseUrl + 'img/oss_logo.png'} alt="Facebook Open Source" width="170" height="45" /> </a> <section className="copyright">{this.props.config.copyright}</section> </footer> ); } } module.exports = Footer;
examples/basics/core/Footer.js
1
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.0012604539515450597, 0.0002763817610684782, 0.00016400379536207765, 0.00016709452029317617, 0.00032803183421492577 ]
{ "id": 3, "code_window": [ " (post.author && post.authorTitle ? ' authorPhoto-big' : '');\n", " if (post.authorFBID) {\n", " return (\n", " <div className={className}>\n", " <a href={post.authorURL} target=\"_blank\">\n", " <img\n", " src={\n", " 'https://graph.facebook.com/' +\n", " post.authorFBID +\n", " '/picture/?height=200&width=200'\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a href={post.authorURL} target=\"_blank\" rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/BlogPost.js", "type": "replace", "edit_start_line_idx": 46 }
--- id: versioning title: Versioning --- You can use the `version` script to cut a new documentation version based on the latest content in the `docs` folder. That specific set of documentation will then be preserved and accessible even as the documentation in the `docs` folder changes moving forward. ## How to Create New Versions Run the following script to generate a starter versions page listing all the site versions: ``` yarn examples versions ``` This creates the following file: ``` pages/en/versions.js ``` You can edit this file later on to customize how you display the versions. Add the following script to your `package.json` file if it doesn't already exist: ```json ... "scripts": { "version": "docusaurus-version" }, ... ``` Run the script with a command line argument of the version you wish to create. e.g., ```bash yarn run version 1.0.0 ``` This will preserve all documents currently in the `docs` folder and make them available as documentation for version `1.0.0`. If, for example, you ran the version script with 1.0.0 as the version number, version 1.0.0 is considered the latest release version for your project. The site will display the version number next to the title in the header. This version number links to a versions page that you created earlier. Documents in the `docs` folder will be considered part of version `next` and they are available, for example, at the url `docs/next/doc1.html`. Documents from the latest version use the url `docs/doc1.html`. Running the script again with `yarn run version 2.0.0` will create a version `2.0.0`, making version 2.0.0 the most recent set of documentation. Documents from version `1.0.0` will use the url `docs/1.0.0/doc1.html` while `2.0.0` will use `docs/doc1.html`. ## Versioning Patterns You can create version numbers in whatever format you wish, and a new version can be created with any version number as long as it does not match an existing version. Version ordering is determined by the order in which versions are created, independently of how they are numbered. ## Storing Files for Each Version Versioned documents are placed into `website/versioned_docs/version-${version}`, where `${version}` is the version number you supplied the `version` script. The markdown header for each versioned doc is altered by renaming the id frontmatter field to `original_id`, then using `"version-${version}-${original_id}"` as the value for the actual `id` field. Versioned sidebars are copied into `website/versioned_sidebars` and are named as `version-${version}-sidebars.json`. A `website/versions.json` file is created the first time you cut a version and is used by Docusaurus to detect what versions exist. Each time a new version is added, it gets added to the `versions.json` file. If you wish to change the documentation for a past version, you can access the files for that respective version. ## Fallback Functionality Only files in the `docs` folder and sidebar files that differ from those of the latest version will get copied each time a new version is specified. If there is no change across versions, Docusaurus will use the file from the latest version with that file. For example, a document with the original id `doc1` exists for the latest version, `1.0.0`, and has the same content as the document with the id `doc1` in the `docs` folder. When a new version `2.0.0` is created, the file for `doc1` will not be copied into `versioned_docs/version-2.0.0/`. There will still be a page for `docs/2.0.0/doc1.html`, but it will use the file from version `1.0.0`. ## Renaming Existing Versions To rename an existing version number to something else, first make sure the following script is in your `package.json` file: ```json ... "scripts": { "rename-version": "docusaurus-rename-version" }, ... ``` Run the script with command line arguments of first, the current version name, then second, the new version name. e.g., ```bash yarn run rename-version 1.0.0 1.0.1 ``` ## Versioning and Translations If you wish to use versioning and translations features, the `crowdin.yaml` file should be set up to upload and download versioned documents to and from Crowdin for translation. Translated, versioned files will go into the folder `translated_docs/${language}/version-${version}/`. For more information, check out the [translations guide](guides-translation.md).
docs/guides-versioning.md
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017478165682405233, 0.00016586919082328677, 0.00016310845967382193, 0.00016446426161564887, 0.0000035510656744008884 ]
{ "id": 3, "code_window": [ " (post.author && post.authorTitle ? ' authorPhoto-big' : '');\n", " if (post.authorFBID) {\n", " return (\n", " <div className={className}>\n", " <a href={post.authorURL} target=\"_blank\">\n", " <img\n", " src={\n", " 'https://graph.facebook.com/' +\n", " post.authorFBID +\n", " '/picture/?height=200&width=200'\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a href={post.authorURL} target=\"_blank\" rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/BlogPost.js", "type": "replace", "edit_start_line_idx": 46 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const BlogPost = require('./BlogPost.js'); const BlogSidebar = require('./BlogSidebar.js'); const Container = require('./Container.js'); const MetadataBlog = require('./MetadataBlog.js'); const React = require('react'); const Site = require('./Site.js'); // used to generate entire blog pages, i.e. collection of truncated blog posts class BlogPageLayout extends React.Component { getPageURL(page) { let url = this.props.config.baseUrl + 'blog/'; if (page > 0) { url += 'page' + (page + 1) + '/'; } return url; } render() { const perPage = this.props.metadata.perPage; const page = this.props.metadata.page; return ( <Site title="Blog" language="en" config={this.props.config} metadata={{blog: true, blogListing: true}}> <div className="docMainWrapper wrapper"> <BlogSidebar language={this.props.language} config={this.props.config} /> <Container className="mainContainer documentContainer postContainer blogContainer"> <div className="posts"> {MetadataBlog.slice(page * perPage, (page + 1) * perPage).map( post => { return ( <BlogPost post={post} content={post.content} truncate={true} key={post.path + post.title} config={this.props.config} /> ); } )} <div className="docs-prevnext"> {page > 0 && ( <a className="docs-prev" href={this.getPageURL(page - 1)}> ← Prev </a> )} {MetadataBlog.length > (page + 1) * perPage && ( <a className="docs-next" href={this.getPageURL(page + 1)}> Next → </a> )} </div> </div> </Container> </div> </Site> ); } } module.exports = BlogPageLayout;
lib/core/BlogPageLayout.js
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.006046046502888203, 0.0009006397449411452, 0.00016335640975739807, 0.0001650041958782822, 0.0019447819795459509 ]
{ "id": 3, "code_window": [ " (post.author && post.authorTitle ? ' authorPhoto-big' : '');\n", " if (post.authorFBID) {\n", " return (\n", " <div className={className}>\n", " <a href={post.authorURL} target=\"_blank\">\n", " <img\n", " src={\n", " 'https://graph.facebook.com/' +\n", " post.authorFBID +\n", " '/picture/?height=200&width=200'\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a href={post.authorURL} target=\"_blank\" rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/BlogPost.js", "type": "replace", "edit_start_line_idx": 46 }
If you are developing the Docusaurus core and you want a quick way to test your changes, you can use the Docusaurus website itself as your testing area. > For tips on testing other projects, see the [local testing of third-party projects doc](./local-third-party-project-testing.md). ## Testing It is straightforward to test your Docusaurus changes with Docusaurus. ``` cd /path/to/docusaurus-repo npm install cd website npm run start ``` > If you look in the `website/package.json` file, you will notice that running `start` with `npm run` actually executes the local `start-server.js` file. This is how you know you are running with local code. ## Debugging Locally ### VS Code Use the following code in VSCode to enable breakpoints. Please ensure you have a later version of node for non-legacy debugging. ``` { "version": "0.2.0", "configurations": [ { "name": "Docusaurus Start (Debug)", "type": "node", "request": "launch", "cwd": "${workspaceFolder}/website", "runtimeExecutable": "npm", "runtimeArgs": [ "run", "start-debug" ], "port": 9229 } ] } ``` ### Other Editors Feel free to contribute debug instructions for other IDEs ### Observing changes Now that the server is running, you can make changes to the core Docusaurus code and docs to see the effects on the Docusaurus site. Just refresh the local site, usually running at http://localhost:3000
admin/testing-changes-on-Docusaurus-itself.md
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017393328016623855, 0.00016883220814634115, 0.00016561438678763807, 0.00016821836470626295, 0.0000029702350730076432 ]
{ "id": 4, "code_window": [ " } else if (post.authorImage) {\n", " return (\n", " <div className={className}>\n", " <a href={post.authorURL} target=\"_blank\">\n", " <img src={post.authorImage} />\n", " </a>\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <a href={post.authorURL} target=\"_blank\" rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/BlogPost.js", "type": "replace", "edit_start_line_idx": 61 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); class Footer extends React.Component { docUrl(doc, language) { const baseUrl = this.props.config.baseUrl; return baseUrl + 'docs/' + (language ? language + '/' : '') + doc; } pageUrl(doc, language) { const baseUrl = this.props.config.baseUrl; return baseUrl + (language ? language + '/' : '') + doc; } render() { const currentYear = new Date().getFullYear(); return ( <footer className="nav-footer" id="footer"> <section className="sitemap"> <a href={this.props.config.baseUrl} className="nav-home"> {this.props.config.footerIcon && ( <img src={this.props.config.baseUrl + this.props.config.footerIcon} alt={this.props.config.title} width="66" height="58" /> )} </a> <div> <h5>Docs</h5> <a href={this.docUrl('doc1.html', this.props.language)}> Getting Started (or other categories) </a> <a href={this.docUrl('doc2.html', this.props.language)}> Guides (or other categories) </a> <a href={this.docUrl('doc3.html', this.props.language)}> API Reference (or other categories) </a> </div> <div> <h5>Community</h5> <a href={this.pageUrl('users.html', this.props.language)}> User Showcase </a> <a href="http://stackoverflow.com/questions/tagged/" target="_blank"> Stack Overflow </a> <a href="https://discordapp.com/">Project Chat</a> <a href="https://twitter.com/" target="_blank"> Twitter </a> </div> <div> <h5>More</h5> <a href={this.props.config.baseUrl + 'blog'}>Blog</a> <a href="https://github.com/">GitHub</a> <a className="github-button" href={this.props.config.repoUrl} data-icon="octicon-star" data-count-href="/facebook/docusaurus/stargazers" data-show-count={true} data-count-aria-label="# stargazers on GitHub" aria-label="Star this project on GitHub"> Star </a> </div> </section> <a href="https://code.facebook.com/projects/" target="_blank" className="fbOpenSource"> <img src={this.props.config.baseUrl + 'img/oss_logo.png'} alt="Facebook Open Source" width="170" height="45" /> </a> <section className="copyright">{this.props.config.copyright}</section> </footer> ); } } module.exports = Footer;
examples/basics/core/Footer.js
1
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.0001765246706781909, 0.00016801459423732013, 0.00016354903345927596, 0.00016826290811877698, 0.0000037910076571279205 ]
{ "id": 4, "code_window": [ " } else if (post.authorImage) {\n", " return (\n", " <div className={className}>\n", " <a href={post.authorURL} target=\"_blank\">\n", " <img src={post.authorImage} />\n", " </a>\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <a href={post.authorURL} target=\"_blank\" rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/BlogPost.js", "type": "replace", "edit_start_line_idx": 61 }
If you are developing the Docusaurus core and you want a quick way to test your changes, you can use the Docusaurus website itself as your testing area. > For tips on testing other projects, see the [local testing of third-party projects doc](./local-third-party-project-testing.md). ## Testing It is straightforward to test your Docusaurus changes with Docusaurus. ``` cd /path/to/docusaurus-repo npm install cd website npm run start ``` > If you look in the `website/package.json` file, you will notice that running `start` with `npm run` actually executes the local `start-server.js` file. This is how you know you are running with local code. ## Debugging Locally ### VS Code Use the following code in VSCode to enable breakpoints. Please ensure you have a later version of node for non-legacy debugging. ``` { "version": "0.2.0", "configurations": [ { "name": "Docusaurus Start (Debug)", "type": "node", "request": "launch", "cwd": "${workspaceFolder}/website", "runtimeExecutable": "npm", "runtimeArgs": [ "run", "start-debug" ], "port": 9229 } ] } ``` ### Other Editors Feel free to contribute debug instructions for other IDEs ### Observing changes Now that the server is running, you can make changes to the core Docusaurus code and docs to see the effects on the Docusaurus site. Just refresh the local site, usually running at http://localhost:3000
admin/testing-changes-on-Docusaurus-itself.md
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017579150153324008, 0.00017212313832715154, 0.00016771830269135535, 0.00017217802815139294, 0.000002755836476353579 ]
{ "id": 4, "code_window": [ " } else if (post.authorImage) {\n", " return (\n", " <div className={className}>\n", " <a href={post.authorURL} target=\"_blank\">\n", " <img src={post.authorImage} />\n", " </a>\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <a href={post.authorURL} target=\"_blank\" rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/BlogPost.js", "type": "replace", "edit_start_line_idx": 61 }
project_identifier_env: CROWDIN_DOCUSAURUS_PROJECT_ID api_key_env: CROWDIN_DOCUSAURUS_API_KEY base_path: "./" preserve_hierarchy: true files: - source: '/docs/*.md' translation: '/website/translated_docs/%locale%/%original_file_name%' languages_mapping: &anchor locale: 'af': 'af' 'ar': 'ar' 'bs-BA': 'bs-BA' 'ca': 'ca' 'cs': 'cs' 'da': 'da' 'de': 'de' 'el': 'el' 'es-ES': 'es-ES' 'fa': 'fa-IR' 'fi': 'fi' 'fr': 'fr' 'he': 'he' 'hu': 'hu' 'id': 'id-ID' 'it': 'it' 'ja': 'ja' 'ko': 'ko' 'mr': 'mr-IN' 'nl': 'nl' 'no': 'no-NO' 'pl': 'pl' 'pt-BR': 'pt-BR' 'pt-PT': 'pt-PT' 'ro': 'ro' 'ru': 'ru' 'sk': 'sk-SK' 'sr': 'sr' 'sv-SE': 'sv-SE' 'tr': 'tr' 'uk': 'uk' 'vi': 'vi' 'zh-CN': 'zh-CN' 'zh-TW': 'zh-TW' - source: '/website/i18n/en.json' translation: '/website/i18n/%locale%.json' languages_mapping: *anchor
crowdin.yaml
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017700569878797978, 0.00017353633302263916, 0.0001681693975115195, 0.0001741554879117757, 0.000002928726871687104 ]
{ "id": 4, "code_window": [ " } else if (post.authorImage) {\n", " return (\n", " <div className={className}>\n", " <a href={post.authorURL} target=\"_blank\">\n", " <img src={post.authorImage} />\n", " </a>\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <a href={post.authorURL} target=\"_blank\" rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/BlogPost.js", "type": "replace", "edit_start_line_idx": 61 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const languages = [ { enabled: true, name: 'English', tag: 'en', }, { enabled: false, name: '日本語', tag: 'ja', }, { enabled: false, name: 'العربية', tag: 'ar', }, { enabled: false, name: 'Bosanski', tag: 'bs-BA', }, { enabled: false, name: 'Català', tag: 'ca', }, { enabled: false, name: 'Čeština', tag: 'cs', }, { enabled: false, name: 'Dansk', tag: 'da', }, { enabled: false, name: 'Deutsch', tag: 'de', }, { enabled: false, name: 'Ελληνικά', tag: 'el', }, { enabled: false, name: 'Español', tag: 'es-ES', }, { enabled: false, name: 'فارسی', tag: 'fa-IR', }, { enabled: false, name: 'Suomi', tag: 'fi', }, { enabled: false, name: 'Français', tag: 'fr', }, { enabled: false, name: 'עִברִית', tag: 'he', }, { enabled: false, name: 'Magyar', tag: 'hu', }, { enabled: false, name: 'Bahasa Indonesia', tag: 'id-ID', }, { enabled: false, name: 'Italiano', tag: 'it', }, { enabled: false, name: 'Afrikaans', tag: 'af', }, { enabled: false, name: '한국어', tag: 'ko', }, { enabled: false, name: 'मराठी', tag: 'mr-IN', }, { enabled: false, name: 'Nederlands', tag: 'nl', }, { enabled: false, name: 'Norsk', tag: 'no-NO', }, { enabled: false, name: 'Polskie', tag: 'pl', }, { enabled: false, name: 'Português', tag: 'pt-PT', }, { enabled: false, name: 'Português (Brasil)', tag: 'pt-BR', }, { enabled: false, name: 'Română', tag: 'ro', }, { enabled: false, name: 'Русский', tag: 'ru', }, { enabled: false, name: 'Slovenský', tag: 'sk-SK', }, { enabled: false, name: 'Српски језик (Ћирилица)', tag: 'sr', }, { enabled: false, name: 'Svenska', tag: 'sv-SE', }, { enabled: false, name: 'Türkçe', tag: 'tr', }, { enabled: false, name: 'Українська', tag: 'uk', }, { enabled: false, name: 'Tiếng Việt', tag: 'vi', }, { enabled: false, name: '中文', tag: 'zh-CN', }, {enabled: false, name: '繁體中文', tag: 'zh-TW'}, ]; module.exports = languages;
examples/translations/languages.js
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.0001782724866643548, 0.00017533024947624654, 0.00017253535042982548, 0.00017583256703801453, 0.0000014838902870906168 ]
{ "id": 5, "code_window": [ " </p>\n", " <div className=\"authorBlock\">\n", " {post.author ? (\n", " <p className=\"post-authorName\">\n", " <a href={post.authorURL} target=\"_blank\">\n", " {post.author}\n", " </a>\n", " {post.authorTitle}\n", " </p>\n", " ) : null}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " href={post.authorURL}\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/BlogPost.js", "type": "replace", "edit_start_line_idx": 112 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const MarkdownBlock = require('./MarkdownBlock.js'); const React = require('react'); // inner blog component for the article itself, without sidebar/header/footer class BlogPost extends React.Component { renderContent() { let content = this.props.content; let hasSplit = false; if (content.split('<!--truncate-->').length > 1) { hasSplit = ( <div className="read-more"> <a className="button" href={this.props.config.baseUrl + 'blog/' + this.props.post.path}> Read More </a> </div> ); } if (this.props.truncate) { content = content.split('<!--truncate-->')[0]; return ( <article className="post-content"> <MarkdownBlock>{content}</MarkdownBlock> {hasSplit} </article> ); } return <MarkdownBlock>{content}</MarkdownBlock>; } renderAuthorPhoto() { const post = this.props.post; const className = 'authorPhoto' + (post.author && post.authorTitle ? ' authorPhoto-big' : ''); if (post.authorFBID) { return ( <div className={className}> <a href={post.authorURL} target="_blank"> <img src={ 'https://graph.facebook.com/' + post.authorFBID + '/picture/?height=200&width=200' } alt={post.author} /> </a> </div> ); } else if (post.authorImage) { return ( <div className={className}> <a href={post.authorURL} target="_blank"> <img src={post.authorImage} /> </a> </div> ); } else { return null; } } renderTitle() { const post = this.props.post; return ( <h1> <a href={this.props.config.baseUrl + 'blog/' + post.path}> {post.title} </a> </h1> ); } renderPostHeader() { const post = this.props.post; const match = post.path.match(/([0-9]+)\/([0-9]+)\/([0-9]+)/); // Because JavaScript sucks at date handling :( const year = match[1]; const month = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ][parseInt(match[2], 10) - 1]; const day = parseInt(match[3], 10); return ( <header className="postHeader"> {this.renderTitle()} <p className="post-meta"> {month} {day}, {year} </p> <div className="authorBlock"> {post.author ? ( <p className="post-authorName"> <a href={post.authorURL} target="_blank"> {post.author} </a> {post.authorTitle} </p> ) : null} {this.renderAuthorPhoto()} </div> </header> ); } render() { return ( <div className="post"> {this.renderPostHeader()} {this.renderContent()} </div> ); } } module.exports = BlogPost;
lib/core/BlogPost.js
1
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.5178015232086182, 0.04230383783578873, 0.00016666692681610584, 0.002085254527628422, 0.13219179213047028 ]
{ "id": 5, "code_window": [ " </p>\n", " <div className=\"authorBlock\">\n", " {post.author ? (\n", " <p className=\"post-authorName\">\n", " <a href={post.authorURL} target=\"_blank\">\n", " {post.author}\n", " </a>\n", " {post.authorTitle}\n", " </p>\n", " ) : null}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " href={post.authorURL}\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/BlogPost.js", "type": "replace", "edit_start_line_idx": 112 }
#!/usr/bin/env node /** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ require('babel-register')({ babelrc: false, only: [__dirname, process.cwd() + '/core'], plugins: [ require('./server/translate-plugin.js'), 'transform-class-properties', 'transform-object-rest-spread', ], presets: ['react', 'env'], }); // For verifying port usage const tcpPortUsed = require('tcp-port-used'); // initial check that required files are present const chalk = require('chalk'); const fs = require('fs'); const CWD = process.cwd(); if (!fs.existsSync(CWD + '/siteConfig.js')) { console.error( chalk.red('Error: No siteConfig.js file found in website folder!') ); process.exit(1); } const program = require('commander'); program.option('--port <number>', 'Specify port number').parse(process.argv); const port = parseInt(program.port, 10) || 3000; tcpPortUsed .check(port, 'localhost') .then(function(inUse) { if (inUse) { console.error(chalk.red('Port ' + port + ' is in use')); process.exit(1); } else { console.log('Starting Docusaurus server on port ' + port + '...'); // start local server on specified port const server = require('./server/server.js'); server(port); } }) .catch(function(ex) { setTimeout(function() { throw ex; }, 0); });
lib/start-server.js
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017433593166060746, 0.00017089657194446772, 0.00016543164383620024, 0.00017264304915443063, 0.0000035708353607333265 ]
{ "id": 5, "code_window": [ " </p>\n", " <div className=\"authorBlock\">\n", " {post.author ? (\n", " <p className=\"post-authorName\">\n", " <a href={post.authorURL} target=\"_blank\">\n", " {post.author}\n", " </a>\n", " {post.authorTitle}\n", " </p>\n", " ) : null}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " href={post.authorURL}\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/BlogPost.js", "type": "replace", "edit_start_line_idx": 112 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); const classNames = require('classnames'); class Container extends React.Component { render() { const containerClasses = classNames('container', this.props.className, { darkBackground: this.props.background === 'dark', highlightBackground: this.props.background === 'highlight', lightBackground: this.props.background === 'light', paddingAll: this.props.padding.indexOf('all') >= 0, paddingBottom: this.props.padding.indexOf('bottom') >= 0, paddingLeft: this.props.padding.indexOf('left') >= 0, paddingRight: this.props.padding.indexOf('right') >= 0, paddingTop: this.props.padding.indexOf('top') >= 0, }); let wrappedChildren; if (this.props.wrapper) { wrappedChildren = <div className="wrapper">{this.props.children}</div>; } else { wrappedChildren = this.props.children; } return ( <div className={containerClasses} id={this.props.id}> {wrappedChildren} </div> ); } } Container.defaultProps = { background: 'transparent', padding: [], wrapper: true, }; module.exports = Container;
lib/core/Container.js
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017373949231114239, 0.00016998992941807956, 0.00016600394155830145, 0.00016995923942886293, 0.0000026436919142724946 ]
{ "id": 5, "code_window": [ " </p>\n", " <div className=\"authorBlock\">\n", " {post.author ? (\n", " <p className=\"post-authorName\">\n", " <a href={post.authorURL} target=\"_blank\">\n", " {post.author}\n", " </a>\n", " {post.authorTitle}\n", " </p>\n", " ) : null}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " href={post.authorURL}\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/BlogPost.js", "type": "replace", "edit_start_line_idx": 112 }
google-site-verification: googlebbd50c8f1c6e7332.html
website/static/googlebbd50c8f1c6e7332.html
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00016859117022249848, 0.00016859117022249848, 0.00016859117022249848, 0.00016859117022249848, 0 ]
{ "id": 6, "code_window": [ "\n", " const editUrl =\n", " this.props.metadata.custom_edit_url ||\n", " (this.props.config.editUrl && this.props.config.editUrl + docSource);\n", " let editLink = editUrl && (\n", " <a className=\"edit-page-link button\" href={editUrl} target=\"_blank\">\n", " {editThisDoc}\n", " </a>\n", " );\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " className=\"edit-page-link button\"\n", " href={editUrl}\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/Doc.js", "type": "replace", "edit_start_line_idx": 33 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); class Footer extends React.Component { docUrl(doc, language) { const baseUrl = this.props.config.baseUrl; return baseUrl + 'docs/' + (language ? language + '/' : '') + doc; } pageUrl(doc, language) { const baseUrl = this.props.config.baseUrl; return baseUrl + (language ? language + '/' : '') + doc; } render() { const currentYear = new Date().getFullYear(); return ( <footer className="nav-footer" id="footer"> <section className="sitemap"> <a href={this.props.config.baseUrl} className="nav-home"> {this.props.config.footerIcon && ( <img src={this.props.config.baseUrl + this.props.config.footerIcon} alt={this.props.config.title} width="66" height="58" /> )} </a> <div> <h5>Docs</h5> <a href={this.docUrl('doc1.html', this.props.language)}> Getting Started (or other categories) </a> <a href={this.docUrl('doc2.html', this.props.language)}> Guides (or other categories) </a> <a href={this.docUrl('doc3.html', this.props.language)}> API Reference (or other categories) </a> </div> <div> <h5>Community</h5> <a href={this.pageUrl('users.html', this.props.language)}> User Showcase </a> <a href="http://stackoverflow.com/questions/tagged/" target="_blank"> Stack Overflow </a> <a href="https://discordapp.com/">Project Chat</a> <a href="https://twitter.com/" target="_blank"> Twitter </a> </div> <div> <h5>More</h5> <a href={this.props.config.baseUrl + 'blog'}>Blog</a> <a href="https://github.com/">GitHub</a> <a className="github-button" href={this.props.config.repoUrl} data-icon="octicon-star" data-count-href="/facebook/docusaurus/stargazers" data-show-count={true} data-count-aria-label="# stargazers on GitHub" aria-label="Star this project on GitHub"> Star </a> </div> </section> <a href="https://code.facebook.com/projects/" target="_blank" className="fbOpenSource"> <img src={this.props.config.baseUrl + 'img/oss_logo.png'} alt="Facebook Open Source" width="170" height="45" /> </a> <section className="copyright">{this.props.config.copyright}</section> </footer> ); } } module.exports = Footer;
examples/basics/core/Footer.js
1
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.0027828377205878496, 0.0007305634790100157, 0.00016635873180348426, 0.0005023314733989537, 0.0007489791023544967 ]
{ "id": 6, "code_window": [ "\n", " const editUrl =\n", " this.props.metadata.custom_edit_url ||\n", " (this.props.config.editUrl && this.props.config.editUrl + docSource);\n", " let editLink = editUrl && (\n", " <a className=\"edit-page-link button\" href={editUrl} target=\"_blank\">\n", " {editThisDoc}\n", " </a>\n", " );\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " className=\"edit-page-link button\"\n", " href={editUrl}\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/Doc.js", "type": "replace", "edit_start_line_idx": 33 }
--- id: site-config title: siteConfig.js --- A large part of site configuration is done by editing the `siteConfig.js` file. ## User Showcase The `users` array is used to store objects for each project/user that you want to show on your site. Currently this field is used by example the `pages/en/index.js` and `pages/en/users.js` files provided. Each user object should have `caption`, `image`, `infoLink`, and `pinned` fields. The `caption` is the text showed when someone hovers over the `image` of that user, and the `infoLink` is where clicking the image will bring someone. The `pinned` field determines whether or not it shows up on the `index` page. Currently this `users` array is used only by the `index.js` and `users.js` example files. If you do not wish to have a users page or show users on the `index` page, you may remove this section. ## siteConfig Fields The `siteConfig` object contains the bulk of the configuration settings for your website. ### Mandatory Fields `baseUrl` - baseUrl for your site. `colors` - Color configurations for the site. - `primaryColor` is the color used the header navigation bar and sidebars. - `secondaryColor` is the color seen in the second row of the header navigation bar when the site window is narrow (including on mobile). - Custom color configurations can also be added. For example, if user styles are added with colors specified as `$myColor`, then adding a `myColor` field to `colors` will allow you to easily configure this color. `copyright` - The copyright string at footer of site and within feed `favicon` - url for site favicon. `headerIcon` - url for icon used in header navigation bar. `headerLinks` - Links that will be used in the header navigation bar. The `label` field of each object will be the link text and will also be translated for each language. Example Usage: ```js headerLinks: [ // Links to document with id doc1 for current language/version { doc: "doc1", label: "Getting Started" }, // Link to page found at pages/en/help.js or if that does not exist, pages/help.js, for current language { page: "help", label: "Help" }, // Links to href destination { href: "https://github.com/", label: "GitHub" }, // Links to blog generated by Docusaurus (${baseUrl}blog) { blog: true, label: "Blog" }, // Determines search bar position among links { search: true }, // Determines language drop down position among links { languages: true } ], ``` `noIndex` - Boolean. If true, Docusaurus will politely ask crawlers and search engines to avoid indexing your site. This is done with a header tag and so only applies to docs and pages. Will not attempt to hide static resources. This is a best effort request. Malicious crawlers can and will still index your site. `projectName` - Project name. This must match your GitHub repo project name (case sensitive). `tagline` - Tagline for your website. `title` - Title for your website. `url` - url for your site. ### Optional Fields `algolia` - Information for Algolia search integration. If this field is excluded, the search bar will not appear in the header. You must specify two values for this field, and one (`appId`) is optional. - `apiKey` - the Algolia provided API key for your search. - `indexName` - the Algolia provided index name for your search (usually this is the project name) - `appId` - Algolia provides a default scraper for your docs. If you provide your own, you will probably get this id from them. `blogSidebarCount` - Control the number of blog posts that show up in the sidebar. See the [adding a blog docs](guides-blog.md#changing-how-many-blog-posts-show-on-sidebar) for more information. `cname` - The CNAME for your website. It will go into a `CNAME` file when your site it built. `customDocsPath` - By default, Docusaurus expects your documentation to be in a directory called `docs`. This directory is at the same level as the `website` directory (i.e., not inside the `website` directory). You can specify a custom path to your documentation with this field. **Note that all of your documentation `*.md` files must still reside in a flat hierarchy. You cannot have your documents in nested directories**. ```js customDocsPath: "docs/site" ``` ```js customDocsPath: "website-docs" ``` `disableHeaderTitle` - An option to disable showing the title in the header next to the header icon. Exclude this field to keep the header as normal, otherwise set to `true`. `disableTitleTagline` - An option to disable showing the tagline in the title of main pages. Exclude this field to keep page titles as `Title • Tagline`. Set to `true` to make page titles just `Title`. `editUrl` - url for editing docs, usage example: `editUrl + 'en/doc1.md'`. If this field is omitted, there will be no "Edit this Doc" button for each document. `facebookAppId` - If you want Facebook Like/Share buttons at the bottom of your blog posts, provide a [Facebook application id](https://www.facebook.com/help/audiencenetwork/804209223039296), and the buttons will show up on all blog posts. `facebookPixelId` - [Facebook Pixel](https://www.facebook.com/business/a/facebook-pixel) ID to track page views. `fonts` - Font-family css configuration for the site. If a font family is specified in `siteConfig.js` as `$myFont`, then adding a `myFont` key to an array in `fonts` will allow you to configure the font. Items appearing earlier in the array will take priority of later elements, so ordering of the fonts matter. In the below example, we have two sets of font configurations, `myFont` and `myOtherFont`. `Times New Roman` is the preferred font in `myFont`. `-apple-system` is the preferred in `myOtherFont`. ``` fonts: { myFont: [ "Times New Roman", "Serif" ], myOtherFont: [ "-apple-system", "system-ui" ] }, ``` The above fonts would be represented in your CSS file(s) as variables `$myFont` and `$myOtherFont`. ``` h1 { font-family: $myFont; } ``` `footerIcon` - url for a footer icon. Currently used in the `core/Footer.js` file provided as an example, but it can be removed from that file. `gaTrackingId` - Google Analytics tracking ID to track page views. `highlight` - [Syntax highlighting](api-doc-markdown.md) options: - `theme` is the name of the theme used by Highlight.js when highlighting code. You can find the [list of supported themes here](https://github.com/isagalaev/highlight.js/tree/master/src/styles). - `version` specifies a particular version of Highlight.js to be used. - `hljs` provides an escape valve by passing an instance of Highlight.js to the function specified here, allowing additional languages to be registered for syntax highlighting. - `defaultLang` defines a default language. It will be used if one is not specified at the top of the code block. You can find the [list of supported languages here](https://github.com/isagalaev/highlight.js/tree/master/src/languages). `markdownPlugins` - An array of plugins to be loaded by Remarkable, the markdown parser and renderer used by Docusaurus. The plugin will receive a reference to the Remarkable instance, allowing custom parsing and rendering rules to be defined. `ogImage` - url for an Open Graph image. This image will show up when your site is shared on Facebook, Twitter and any other websites/apps where the Open Graph protocol is supported. `onPageNav` - If you want a visible navigation option for representing topics on the current page. Currently, there is one accepted value for this option: - `separate` - The secondary navigation is a separate pane defaulting on the right side of a document. See http://docusaurus.io/docs/en/translation.html for an example. `organizationName` - GitHub username of the organization or user hosting this project. This is used by the publishing script to determine where your GitHub pages website will be hosted. `scripts` - Array of JavaScript sources to load. The script tag will be inserted in the HTML head. `separateCss` - Folders inside which any `css` files will not be processed and concatenated to Docusaurus' styles. This is to support static `html` pages that may be separate from Docusaurus with completely separate styles. `stylesheets` - Array of CSS sources to load. The link tag will be inserted in the HTML head. `translationRecruitingLink` - url for the `Help Translate` tab of language selection when languages besides English are enabled. This can be included you are using translations but does not have to be. `twitter` - set this to `true` if you want a Twitter social button to appear at the bottom of your blog posts. `useEnglishUrl` - If you do not have [translations](guides-translation.md) enabled (e.g., by having a `languages.js` file), but still want a link of the form `/docs/en/doc.html` (with the `en`), set this to `true`. `users` - The `users` array mentioned earlier. `wrapPagesHTML` - boolean flag to indicate whether `html` files in `/pages` should be wrapped with Docusaurus site styles, header and footer. This feature is experimental and relies on the files being `html` fragments instead of complete pages. It inserts the contents of your `html` file with no extra processing. Defaults to `false`. Users can also add their own custom fields if they wish to provide some data across different files. ## Example siteConfig.js with all fields ``` const users = [ { caption: "User1", image: "/test-site/img/docusaurus.svg", infoLink: "https://www.example.com", pinned: true } ]; const siteConfig = { title: "Docusaurus", tagline: "Generate websites!", url: "https://docusaurus.io", baseUrl: "/", // For github.io type URLS, you would combine the url and baseUrl like: // url: "https://reasonml.github.io", // url: "/reason-react/", organizationName: "facebook", projectName: "docusaurus", noIndex: false, headerLinks: [ { doc: "doc1", label: "Docs" }, { page: "help", label: "Help" }, { search: true }, { blog: true } ], // For no header links in the top nav bar -> headerLinks: [], headerIcon: "img/docusaurus.svg", favicon: "img/favicon.png", colors: { primaryColor: "#2E8555", secondaryColor: "#205C3B" }, editUrl: "https://github.com/facebook/docusaurus/edit/master/docs/", users, disableHeaderTitle: true, disableTitleTagline: true, separateCss: ["static/css/non-docusaurus", "static/assets/separate-css"], footerIcon: "img/docusaurus.svg", translationRecruitingLink: "https://crowdin.com/project/docusaurus", algolia: { apiKey: "0f9f28b9ab9efae89810921a351753b5", indexName: "github" }, gaTrackingId: "U-A2352", highlight: { theme: 'default' }, markdownPlugins: [ function foo(md) { md.renderer.rules.fence_custom.foo = function(tokens, idx, options, env, instance) { return '<div class="foo">bar</div>'; } } ], scripts: [ "https://docusaurus.io/slash.js" ], stylesheets: [ "https://docusaurus.io/style.css" ], facebookAppId: "1615782811974223", facebookPixelId: "352490515235776", twitter: "true" }; module.exports = siteConfig; ```
docs/api-site-config.md
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.0007027521496638656, 0.0001990971650229767, 0.0001635535736568272, 0.0001729822688503191, 0.00010818333976203576 ]
{ "id": 6, "code_window": [ "\n", " const editUrl =\n", " this.props.metadata.custom_edit_url ||\n", " (this.props.config.editUrl && this.props.config.editUrl + docSource);\n", " let editLink = editUrl && (\n", " <a className=\"edit-page-link button\" href={editUrl} target=\"_blank\">\n", " {editThisDoc}\n", " </a>\n", " );\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " className=\"edit-page-link button\"\n", " href={editUrl}\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/Doc.js", "type": "replace", "edit_start_line_idx": 33 }
# [Docusaurus](https://docusaurus.io) &middot; [![CircleCI](https://circleci.com/gh/facebook/Docusaurus.svg?style=svg)](https://circleci.com/gh/facebook/Docusaurus) [![npm version](https://badge.fury.io/js/docusaurus.svg)](https://badge.fury.io/js/docusaurus) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md#pull-requests) Docusaurus is a project for easily building, deploying, and maintaining open source project websites. * **Simple to Start** Docusaurus is built to be easy to [get up and running](https://docusaurus.io/docs/en/installation.html) in as little time possible. We've built Docusaurus to handle the website build process so you can focus on your project. * **Localizable** Docusaurus ships with [localization support](https://docusaurus.io/docs/en/translation.html) via CrowdIn. Empower and grow your international community by translating your documentation. * **Customizable** While Docusaurus ships with the key pages and sections you need to get started, including a home page, a docs section, a [blog](https://docusaurus.io/docs/en/blog.html), and additional support pages, it is also [customizable](https://docusaurus.io/docs/en/custom-pages.html) as well to ensure you have a site that is [uniquely yours](https://docusaurus.io/docs/en/api-pages.html). ## Installation Docusaurus is available as the [`docusaurus` package](https://www.npmjs.com/package/docusaurus-init) on [npm](https://www.npmjs.com). We have also released the [`docusaurus-init` package](https://www.npmjs.com/package/docusaurus-init) to make [getting started](https://docusaurus.io/docs/en/installation.html) with Docusaurus even easier. ## Contributing We've released Docusaurus because it helps us better scale and support the many OSS projects at Facebook. We hope that other organizations can benefit from the project. We are thankful for any contributions from the community. ### [Code of Conduct](https://code.facebook.com/codeofconduct) Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read [the full text](https://code.facebook.com/codeofconduct) so that you can understand what actions will and will not be tolerated. ### Contributing Guide Read our [contributing guide](https://github.com/facebook/Docusaurus/blob/master/CONTRIBUTING.md) to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to Docusaurus. ### Beginner Friendly Bugs To help you get your feet wet and get you familiar with our contribution process, we have a list of [beginner friendly bugs](https://github.com/facebook/Docusaurus/labels/good%20first%20issue) that contain bugs which are fairly easy to fix. This is a great place to get started. ## Contact We have a few channels for contact: - [Discord](https://discord.gg/docusaurus) with two text channels: - `#docusaurus-users` for those using Docusaurus. - `#docusaurus-dev` for those wanting to contribute to the Docusaurus core. - [@docusaurus](https://twitter.com/docusaurus) on Twitter - [GitHub Issues](https://github.com/facebook/docusaurus/issues) ## License Docusaurus is [MIT licensed](./LICENSE). The Docusaurus documentation (e.g., `.md` files in the `/docs` folder) is [Creative Commons licensed](./LICENSE-docs).
README.md
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017835716425906867, 0.00017206327174790204, 0.00016250474436674267, 0.00017240691522601992, 0.000005329309260559967 ]
{ "id": 6, "code_window": [ "\n", " const editUrl =\n", " this.props.metadata.custom_edit_url ||\n", " (this.props.config.editUrl && this.props.config.editUrl + docSource);\n", " let editLink = editUrl && (\n", " <a className=\"edit-page-link button\" href={editUrl} target=\"_blank\">\n", " {editThisDoc}\n", " </a>\n", " );\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " className=\"edit-page-link button\"\n", " href={editUrl}\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/Doc.js", "type": "replace", "edit_start_line_idx": 33 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const fs = require('fs-extra'); const path = require('path'); const os = require('os'); const Feed = require('feed'); const chalk = require('chalk'); const glob = require('glob'); const CWD = process.cwd(); const sitemap = require('sitemap'); const siteConfig = require(CWD + '/siteConfig.js'); /****************************************************************************/ let readMetadata; let Metadata; let MetadataBlog; readMetadata = require('./readMetadata.js'); readMetadata.generateMetadataDocs(); Metadata = require('../core/metadata.js'); readMetadata.generateMetadataBlog(); MetadataBlog = require('../core/MetadataBlog.js'); /****************************************************************************/ module.exports = function(callback) { console.log('sitemap.js triggered...'); let urls = []; let files = glob.sync(CWD + '/pages/en/**/*.js'); // English-only is the default. let enabledLanguages = [ { enabled: true, name: 'English', tag: 'en', }, ]; // If we have a languages.js file, get all the enabled languages in there if (fs.existsSync(CWD + '/languages.js')) { let languages = require(CWD + '/languages.js'); enabledLanguages = languages.filter(lang => { return lang.enabled == true; }); } // create a url mapping to all the enabled languages files files.map(file => { let url = file.split('/pages/en')[1]; url = url.replace(/\.js$/, '.html'); let links = enabledLanguages.map(lang => { let langUrl = lang.tag + url; return {lang: lang.tag, url: langUrl}; }); urls.push({url, changefreq: 'weekly', priority: 0.5, links}); }); let htmlFiles = glob.sync(CWD + '/pages/**/*.html'); MetadataBlog.map(blog => { urls.push({ url: '/blog/' + blog.path, changefreq: 'weekly', priority: 0.3, }); }); Object.keys(Metadata) .filter(key => Metadata[key].language === 'en') .map(key => { let doc = Metadata[key]; let links = enabledLanguages.map(lang => { let langUrl = doc.permalink.replace('docs/en/', `docs/${lang.tag}/`); return {lang: lang.tag, url: langUrl}; }); urls.push({ url: doc.permalink, changefreq: 'hourly', priority: 1.0, links, }); }); const sm = sitemap.createSitemap({ hostname: siteConfig.url, cacheTime: 600 * 1000, // 600 sec - cache purge period urls: urls, }); sm.toXML((err, xml) => { if (err) { return 'An error has occurred.'; } callback(xml); }); };
lib/server/sitemap.js
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017886723799165338, 0.00017405310063622892, 0.00016891909763216972, 0.0001749764196574688, 0.000003132357733193203 ]
{ "id": 7, "code_window": [ " href={\n", " this.props.config.translationRecruitingLink +\n", " '/' +\n", " this.props.language\n", " }\n", " target=\"_blank\">\n", " {translateThisDoc}\n", " </a>\n", " );\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/Doc.js", "type": "replace", "edit_start_line_idx": 52 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const MarkdownBlock = require('./MarkdownBlock.js'); const React = require('react'); // inner blog component for the article itself, without sidebar/header/footer class BlogPost extends React.Component { renderContent() { let content = this.props.content; let hasSplit = false; if (content.split('<!--truncate-->').length > 1) { hasSplit = ( <div className="read-more"> <a className="button" href={this.props.config.baseUrl + 'blog/' + this.props.post.path}> Read More </a> </div> ); } if (this.props.truncate) { content = content.split('<!--truncate-->')[0]; return ( <article className="post-content"> <MarkdownBlock>{content}</MarkdownBlock> {hasSplit} </article> ); } return <MarkdownBlock>{content}</MarkdownBlock>; } renderAuthorPhoto() { const post = this.props.post; const className = 'authorPhoto' + (post.author && post.authorTitle ? ' authorPhoto-big' : ''); if (post.authorFBID) { return ( <div className={className}> <a href={post.authorURL} target="_blank"> <img src={ 'https://graph.facebook.com/' + post.authorFBID + '/picture/?height=200&width=200' } alt={post.author} /> </a> </div> ); } else if (post.authorImage) { return ( <div className={className}> <a href={post.authorURL} target="_blank"> <img src={post.authorImage} /> </a> </div> ); } else { return null; } } renderTitle() { const post = this.props.post; return ( <h1> <a href={this.props.config.baseUrl + 'blog/' + post.path}> {post.title} </a> </h1> ); } renderPostHeader() { const post = this.props.post; const match = post.path.match(/([0-9]+)\/([0-9]+)\/([0-9]+)/); // Because JavaScript sucks at date handling :( const year = match[1]; const month = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ][parseInt(match[2], 10) - 1]; const day = parseInt(match[3], 10); return ( <header className="postHeader"> {this.renderTitle()} <p className="post-meta"> {month} {day}, {year} </p> <div className="authorBlock"> {post.author ? ( <p className="post-authorName"> <a href={post.authorURL} target="_blank"> {post.author} </a> {post.authorTitle} </p> ) : null} {this.renderAuthorPhoto()} </div> </header> ); } render() { return ( <div className="post"> {this.renderPostHeader()} {this.renderContent()} </div> ); } } module.exports = BlogPost;
lib/core/BlogPost.js
1
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.004898169543594122, 0.0008935580844990909, 0.0001652903447393328, 0.00017372905858792365, 0.0014135041274130344 ]
{ "id": 7, "code_window": [ " href={\n", " this.props.config.translationRecruitingLink +\n", " '/' +\n", " this.props.language\n", " }\n", " target=\"_blank\">\n", " {translateThisDoc}\n", " </a>\n", " );\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/Doc.js", "type": "replace", "edit_start_line_idx": 52 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); const Container = require('./Container.js'); const SideNav = require('./nav/SideNav.js'); const MetadataBlog = require('./MetadataBlog.js'); class BlogSidebar extends React.Component { render() { let blogSidebarCount = 5; let blogSidebarTitle = 'Recent Posts'; if (this.props.config.blogSidebarCount) { if (this.props.config.blogSidebarCount == 'ALL') { blogSidebarCount = MetadataBlog.length; blogSidebarTitle = 'All Blog Posts'; } else { blogSidebarCount = this.props.config.blogSidebarCount; } } const contents = [ { name: blogSidebarTitle, links: MetadataBlog.slice(0, blogSidebarCount), }, ]; const title = this.props.current && this.props.current.title; const current = { id: title || '', category: blogSidebarTitle, }; return ( <Container className="docsNavContainer" id="docsNav" wrapper={false}> <SideNav language={this.props.language} root={this.props.config.baseUrl + 'blog/'} title="Blog" contents={contents} current={current} /> </Container> ); } } module.exports = BlogSidebar;
lib/core/BlogSidebar.js
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.0008050718461163342, 0.0004461859352886677, 0.00017232967365998775, 0.0004262823495082557, 0.0002569997450336814 ]
{ "id": 7, "code_window": [ " href={\n", " this.props.config.translationRecruitingLink +\n", " '/' +\n", " this.props.language\n", " }\n", " target=\"_blank\">\n", " {translateThisDoc}\n", " </a>\n", " );\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/Doc.js", "type": "replace", "edit_start_line_idx": 52 }
#!/usr/bin/env node /** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* generate the i18n/en.json file */ const CWD = process.cwd(); const fs = require('fs-extra'); const mkdirp = require('mkdirp'); const glob = require('glob'); const readMetadata = require('./server/readMetadata.js'); const path = require('path'); const siteConfig = require(CWD + '/siteConfig.js'); const babylon = require('babylon'); const traverse = require('babel-traverse').default; const sidebars = require(CWD + '/sidebars.json'); let currentTranslations = { 'localized-strings': {}, 'pages-strings': {}, }; if (fs.existsSync(path)) { currentTranslations = JSON.parse( fs.readFileSync(CWD + '/i18n/en.json', 'utf8') ); } function writeFileAndCreateFolder(file, content) { mkdirp.sync(file.replace(new RegExp('/[^/]*$'), '')); fs.writeFileSync(file, content); } function execute() { let translations = { 'localized-strings': { next: 'Next', previous: 'Previous', tagline: siteConfig.tagline, }, 'pages-strings': {}, }; // look through markdown headers of docs for titles and categories to translate let files = glob.sync(CWD + '/../' + readMetadata.getDocsPath() + '/**'); files.forEach(file => { const extension = path.extname(file); if (extension === '.md' || extension === '.markdown') { let res; try { res = readMetadata.processMetadata(file); } catch (e) { console.error(e); process.exit(1); } if (!res) { return; } const metadata = res.metadata; translations['localized-strings'][metadata.localized_id] = metadata.title; if (metadata.sidebar_label) { translations['localized-strings'][metadata.sidebar_label] = metadata.sidebar_label; } } }); // look through header links for text to translate siteConfig.headerLinks.forEach(link => { if (link.label) { translations['localized-strings'][link.label] = link.label; } }); // find sidebar category titles to translate Object.keys(sidebars).forEach(sb => { const categories = sidebars[sb]; Object.keys(categories).forEach(category => { translations['localized-strings'][category] = category; }); }); files = glob.sync(CWD + '/versioned_sidebars/*'); files.forEach(file => { if (!file.endsWith('-sidebars.json')) { if (file.endsWith('-sidebar.json')) { console.warn( `Skipping ${file}. Make sure your sidebar filenames follow this format: 'version-VERSION-sidebars.json'.` ); } return; } let sidebarContent; try { sidebarContent = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { console.error(`Could not parse ${file} into json. ${e}`); process.exit(1); } Object.keys(sidebarContent).forEach(sb => { const categories = sidebarContent[sb]; Object.keys(categories).forEach(category => { translations['localized-strings'][category] = category; }); }); }); // go through pages to look for text inside translate tags files = glob.sync(CWD + '/pages/en/**'); files.forEach(file => { const extension = path.extname(file); if (extension === '.js') { const ast = babylon.parse(fs.readFileSync(file, 'utf8'), { plugins: ['jsx'], }); traverse(ast, { enter(path) { if ( path.node.type === 'JSXElement' && path.node.openingElement.name.name === 'translate' ) { const text = path.node.children[0].value .trim() .replace(/\s+/g, ' '); let description = 'no description given'; const attributes = path.node.openingElement.attributes; for (let i = 0; i < attributes.length; i++) { if (attributes[i].name.name === 'desc') { description = attributes[i].value.value; } } translations['pages-strings'][text + '|' + description] = text; } }, }); } }); // Manually add 'Help Translate' to en.json translations['pages-strings'][ 'Help Translate|recruit community translators for your project' ] = 'Help Translate'; translations['pages-strings'][ 'Edit this Doc|recruitment message asking to edit the doc source' ] = 'Edit'; translations['pages-strings'][ 'Translate this Doc|recruitment message asking to translate the docs' ] = 'Translate'; translations['pages-strings'] = Object.assign( translations['pages-strings'], currentTranslations['pages-strings'] ); translations['localized-strings'] = Object.assign( translations['localized-strings'], currentTranslations['localized-strings'] ); writeFileAndCreateFolder( CWD + '/i18n/en.json', JSON.stringify( Object.assign( { _comment: 'This file is auto-generated by write-translations.js', }, translations ), null, 2 ) + '\n' ); } execute(); module.exports = execute;
lib/write-translations.js
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017434556502848864, 0.00016749669157434255, 0.0001614126085769385, 0.0001667103060754016, 0.000004279028416931396 ]
{ "id": 7, "code_window": [ " href={\n", " this.props.config.translationRecruitingLink +\n", " '/' +\n", " this.props.language\n", " }\n", " target=\"_blank\">\n", " {translateThisDoc}\n", " </a>\n", " );\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/Doc.js", "type": "replace", "edit_start_line_idx": 52 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); const BlogPost = require('./BlogPost.js'); const BlogSidebar = require('./BlogSidebar.js'); const Container = require('./Container.js'); const Site = require('./Site.js'); // used for entire blog posts, i.e., each written blog article with sidebar with site header/footer class BlogPostLayout extends React.Component { renderSocialButtons() { const post = this.props.metadata; const fbLike = this.props.config.facebookAppId ? ( <div className="fb-like" data-layout="standard" data-share="true" data-width="225" data-show-faces="false" /> ) : null; const twitterShare = this.props.config.twitter ? ( <a href="https://twitter.com/share" className="twitter-share-button" data-text={post.title} data-url={ this.props.config.url + this.props.config.baseUrl + 'blog/' + post.path } data-related={this.props.config.twitter} data-via={post.authorTwitter} data-show-count="false"> Tweet </a> ) : null; if (!fbLike && !twitterShare) { return; } return ( <div> <aside className="entry-share"> <div className="social-buttons"> {fbLike} {twitterShare} </div> </aside> </div> ); } getDescription() { var descLines = this.props.children.trim().split('\n'); for (var i = 0; i < descLines.length; i++) { // Don't want blank lines or descriptions that are raw image rendering strings if (descLines[i] && !descLines[i].startsWith('![')) { return descLines[i]; } } return null; } render() { return ( <Site className="sideNavVisible" url={'blog/' + this.props.metadata.path} title={this.props.metadata.title} language={'en'} description={this.getDescription()} config={this.props.config} metadata={{blog: true}}> <div className="docMainWrapper wrapper"> <BlogSidebar language={'en'} current={this.props.metadata} config={this.props.config} /> <Container className="mainContainer documentContainer postContainer blogContainer"> <div className="lonePost"> <BlogPost post={this.props.metadata} content={this.props.children} language={'en'} config={this.props.config} /> {this.renderSocialButtons()} </div> <div className="blog-recent"> <a className="button" href={this.props.config.baseUrl + 'blog'}> Recent Posts </a> </div> </Container> </div> </Site> ); } } module.exports = BlogPostLayout;
lib/core/BlogPostLayout.js
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.0018770216265693307, 0.0006800659466534853, 0.00016482621140312403, 0.00048293068539351225, 0.000570056086871773 ]
{ "id": 8, "code_window": [ " }\n", " // add Crowdin project recruiting link\n", " if (siteConfig.translationRecruitingLink) {\n", " enabledLanguages.push(\n", " <li key=\"recruiting\">\n", " <a href={siteConfig.translationRecruitingLink} target=\"_blank\">\n", " {helpTranslateString}\n", " </a>\n", " </li>\n", " );\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " href={siteConfig.translationRecruitingLink}\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/nav/HeaderNav.js", "type": "replace", "edit_start_line_idx": 48 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const MarkdownBlock = require('./MarkdownBlock.js'); const React = require('react'); // inner blog component for the article itself, without sidebar/header/footer class BlogPost extends React.Component { renderContent() { let content = this.props.content; let hasSplit = false; if (content.split('<!--truncate-->').length > 1) { hasSplit = ( <div className="read-more"> <a className="button" href={this.props.config.baseUrl + 'blog/' + this.props.post.path}> Read More </a> </div> ); } if (this.props.truncate) { content = content.split('<!--truncate-->')[0]; return ( <article className="post-content"> <MarkdownBlock>{content}</MarkdownBlock> {hasSplit} </article> ); } return <MarkdownBlock>{content}</MarkdownBlock>; } renderAuthorPhoto() { const post = this.props.post; const className = 'authorPhoto' + (post.author && post.authorTitle ? ' authorPhoto-big' : ''); if (post.authorFBID) { return ( <div className={className}> <a href={post.authorURL} target="_blank"> <img src={ 'https://graph.facebook.com/' + post.authorFBID + '/picture/?height=200&width=200' } alt={post.author} /> </a> </div> ); } else if (post.authorImage) { return ( <div className={className}> <a href={post.authorURL} target="_blank"> <img src={post.authorImage} /> </a> </div> ); } else { return null; } } renderTitle() { const post = this.props.post; return ( <h1> <a href={this.props.config.baseUrl + 'blog/' + post.path}> {post.title} </a> </h1> ); } renderPostHeader() { const post = this.props.post; const match = post.path.match(/([0-9]+)\/([0-9]+)\/([0-9]+)/); // Because JavaScript sucks at date handling :( const year = match[1]; const month = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ][parseInt(match[2], 10) - 1]; const day = parseInt(match[3], 10); return ( <header className="postHeader"> {this.renderTitle()} <p className="post-meta"> {month} {day}, {year} </p> <div className="authorBlock"> {post.author ? ( <p className="post-authorName"> <a href={post.authorURL} target="_blank"> {post.author} </a> {post.authorTitle} </p> ) : null} {this.renderAuthorPhoto()} </div> </header> ); } render() { return ( <div className="post"> {this.renderPostHeader()} {this.renderContent()} </div> ); } } module.exports = BlogPost;
lib/core/BlogPost.js
1
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017607500194571912, 0.0001708074560156092, 0.00016409342060796916, 0.0001708938361844048, 0.0000036522751543088816 ]
{ "id": 8, "code_window": [ " }\n", " // add Crowdin project recruiting link\n", " if (siteConfig.translationRecruitingLink) {\n", " enabledLanguages.push(\n", " <li key=\"recruiting\">\n", " <a href={siteConfig.translationRecruitingLink} target=\"_blank\">\n", " {helpTranslateString}\n", " </a>\n", " </li>\n", " );\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " href={siteConfig.translationRecruitingLink}\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/nav/HeaderNav.js", "type": "replace", "edit_start_line_idx": 48 }
<svg xmlns="http://www.w3.org/2000/svg" width="600" height="600" viewBox="0 0 600 600"><g fill="#F26B00"><path d="M142.536 198.858c0 26.36-21.368 47.72-47.72 47.72-26.36 0-47.722-21.36-47.722-47.72s21.36-47.72 47.72-47.72c26.355 0 47.722 21.36 47.722 47.72"/><path d="M505.18 414.225H238.124c-35.25 0-63.926-28.674-63.926-63.923s28.678-63.926 63.926-63.926h120.78c20.816 0 37.753-16.938 37.753-37.756s-16.938-37.756-37.753-37.756H94.81c-7.227 0-13.086-5.86-13.086-13.085 0-7.227 5.86-13.086 13.085-13.086h264.093c35.25 0 63.923 28.678 63.923 63.926s-28.674 63.923-63.923 63.923h-120.78c-20.82 0-37.756 16.938-37.756 37.76 0 20.816 16.938 37.753 37.756 37.753H505.18c7.227 0 13.086 5.86 13.086 13.085 0 7.226-5.858 13.085-13.085 13.085z"/><path d="M457.464 401.142c0-26.36 21.36-47.72 47.72-47.72s47.72 21.36 47.72 47.72-21.36 47.72-47.72 47.72-47.72-21.36-47.72-47.72"/></g></svg>
website/static/img/relay.svg
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.0010920047061517835, 0.0010920047061517835, 0.0010920047061517835, 0.0010920047061517835, 0 ]
{ "id": 8, "code_window": [ " }\n", " // add Crowdin project recruiting link\n", " if (siteConfig.translationRecruitingLink) {\n", " enabledLanguages.push(\n", " <li key=\"recruiting\">\n", " <a href={siteConfig.translationRecruitingLink} target=\"_blank\">\n", " {helpTranslateString}\n", " </a>\n", " </li>\n", " );\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " href={siteConfig.translationRecruitingLink}\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/nav/HeaderNav.js", "type": "replace", "edit_start_line_idx": 48 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* replaces translate tags with calls to translate function */ module.exports = function translatePlugin(babel) { const {types: t} = babel; return { visitor: { JSXElement(path) { if (path.node.openingElement.name.name !== 'translate') { return; } /* assume translate element only has one child which is the text */ const text = path.node.children[0].value.trim().replace(/\s+/g, ' '); let description = 'no description given'; const attributes = path.node.openingElement.attributes; for (let i = 0; i < attributes.length; i++) { if (attributes[i].name.name === 'desc') { description = attributes[i].value.value; } } /* use an expression container if inside a jsxelement */ if (path.findParent(path => true).node.type === 'JSXElement') { path.replaceWith( t.jSXExpressionContainer( t.callExpression(t.identifier('translate'), [ t.stringLiteral(text + '|' + description), ]) ) ); } else { path.replaceWith( t.callExpression(t.identifier('translate'), [ t.stringLiteral(text + '|' + description), ]) ); } }, }, }; };
lib/server/translate-plugin.js
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017272499098908156, 0.00016830414824653417, 0.00016414147103205323, 0.0001693049562163651, 0.0000033955091112147784 ]
{ "id": 8, "code_window": [ " }\n", " // add Crowdin project recruiting link\n", " if (siteConfig.translationRecruitingLink) {\n", " enabledLanguages.push(\n", " <li key=\"recruiting\">\n", " <a href={siteConfig.translationRecruitingLink} target=\"_blank\">\n", " {helpTranslateString}\n", " </a>\n", " </li>\n", " );\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <a\n", " href={siteConfig.translationRecruitingLink}\n", " target=\"_blank\"\n", " rel=\"noreferrer noopener\">\n" ], "file_path": "lib/core/nav/HeaderNav.js", "type": "replace", "edit_start_line_idx": 48 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const CWD = process.cwd(); const fs = require('fs-extra'); const path = require('path'); const join = path.join; const languages_js = join(CWD, 'languages.js'); const versions_json = join(CWD, 'versions.json'); class Translation { constructor() { this.enabled = false; this.languages = [ { enabled: true, name: 'English', tag: 'en', }, ]; this._load(); } enabledLanguages() { return this.languages.filter(lang => lang.enabled); } _load() { if (fs.existsSync(languages_js)) { this.enabled = true; this.languages = require(languages_js); } } } class Versioning { constructor() { this.enabled = false; this.latestVersion = null; this.versions = []; this._load(); } _load() { if (fs.existsSync(versions_json)) { this.enabled = true; this.versions = JSON.parse(fs.readFileSync(versions_json, 'utf8')); this.latestVersion = this.versions[0]; } } } const env = { translation: new Translation(), versioning: new Versioning(), }; module.exports = env;
lib/server/env.js
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.0022028847597539425, 0.000619791797362268, 0.0001653185609029606, 0.00017124155419878662, 0.0007520192302763462 ]
{ "id": 9, "code_window": [ "\n", " <a\n", " href=\"https://code.facebook.com/projects/\"\n", " target=\"_blank\"\n", " className=\"fbOpenSource\"\n", " >\n", " <img\n", " src={`${this.props.config.baseUrl}img/oss_logo.png`}\n", " alt=\"Facebook Open Source\"\n", " width=\"170\"\n", " height=\"45\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " rel=\"noreferrer noopener\"\n", " className=\"fbOpenSource\">\n" ], "file_path": "website/core/Footer.js", "type": "replace", "edit_start_line_idx": 94 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); class Footer extends React.Component { docUrl(doc, language) { const baseUrl = this.props.config.baseUrl; return baseUrl + 'docs/' + (language ? language + '/' : '') + doc; } pageUrl(doc, language) { const baseUrl = this.props.config.baseUrl; return baseUrl + (language ? language + '/' : '') + doc; } render() { const currentYear = new Date().getFullYear(); return ( <footer className="nav-footer" id="footer"> <section className="sitemap"> <a href={this.props.config.baseUrl} className="nav-home"> {this.props.config.footerIcon && ( <img src={this.props.config.baseUrl + this.props.config.footerIcon} alt={this.props.config.title} width="66" height="58" /> )} </a> <div> <h5>Docs</h5> <a href={this.docUrl('doc1.html', this.props.language)}> Getting Started (or other categories) </a> <a href={this.docUrl('doc2.html', this.props.language)}> Guides (or other categories) </a> <a href={this.docUrl('doc3.html', this.props.language)}> API Reference (or other categories) </a> </div> <div> <h5>Community</h5> <a href={this.pageUrl('users.html', this.props.language)}> User Showcase </a> <a href="http://stackoverflow.com/questions/tagged/" target="_blank"> Stack Overflow </a> <a href="https://discordapp.com/">Project Chat</a> <a href="https://twitter.com/" target="_blank"> Twitter </a> </div> <div> <h5>More</h5> <a href={this.props.config.baseUrl + 'blog'}>Blog</a> <a href="https://github.com/">GitHub</a> <a className="github-button" href={this.props.config.repoUrl} data-icon="octicon-star" data-count-href="/facebook/docusaurus/stargazers" data-show-count={true} data-count-aria-label="# stargazers on GitHub" aria-label="Star this project on GitHub"> Star </a> </div> </section> <a href="https://code.facebook.com/projects/" target="_blank" className="fbOpenSource"> <img src={this.props.config.baseUrl + 'img/oss_logo.png'} alt="Facebook Open Source" width="170" height="45" /> </a> <section className="copyright">{this.props.config.copyright}</section> </footer> ); } } module.exports = Footer;
examples/basics/core/Footer.js
1
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.9944530129432678, 0.09991076588630676, 0.00017216609558090568, 0.000364086648914963, 0.29818108677864075 ]
{ "id": 9, "code_window": [ "\n", " <a\n", " href=\"https://code.facebook.com/projects/\"\n", " target=\"_blank\"\n", " className=\"fbOpenSource\"\n", " >\n", " <img\n", " src={`${this.props.config.baseUrl}img/oss_logo.png`}\n", " alt=\"Facebook Open Source\"\n", " width=\"170\"\n", " height=\"45\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " rel=\"noreferrer noopener\"\n", " className=\"fbOpenSource\">\n" ], "file_path": "website/core/Footer.js", "type": "replace", "edit_start_line_idx": 94 }
project_identifier_env: CROWDIN_DOCUSAURUS_PROJECT_ID api_key_env: CROWDIN_DOCUSAURUS_API_KEY base_path: "./" preserve_hierarchy: true files: - source: '/docs/*.md' translation: '/website/translated_docs/%locale%/%original_file_name%' languages_mapping: &anchor locale: 'af': 'af' 'ar': 'ar' 'bs-BA': 'bs-BA' 'ca': 'ca' 'cs': 'cs' 'da': 'da' 'de': 'de' 'el': 'el' 'es-ES': 'es-ES' 'fa': 'fa-IR' 'fi': 'fi' 'fr': 'fr' 'he': 'he' 'hu': 'hu' 'id': 'id-ID' 'it': 'it' 'ja': 'ja' 'ko': 'ko' 'mr': 'mr-IN' 'nl': 'nl' 'no': 'no-NO' 'pl': 'pl' 'pt-BR': 'pt-BR' 'pt-PT': 'pt-PT' 'ro': 'ro' 'ru': 'ru' 'sk': 'sk-SK' 'sr': 'sr' 'sv-SE': 'sv-SE' 'tr': 'tr' 'uk': 'uk' 'vi': 'vi' 'zh-CN': 'zh-CN' 'zh-TW': 'zh-TW' - source: '/website/i18n/en.json' translation: '/website/i18n/%locale%.json' languages_mapping: *anchor
examples/translations/crowdin.yaml
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.00017549573385622352, 0.00017370124987792224, 0.00016821862664073706, 0.00017495306383352727, 0.000002752934960881248 ]
{ "id": 9, "code_window": [ "\n", " <a\n", " href=\"https://code.facebook.com/projects/\"\n", " target=\"_blank\"\n", " className=\"fbOpenSource\"\n", " >\n", " <img\n", " src={`${this.props.config.baseUrl}img/oss_logo.png`}\n", " alt=\"Facebook Open Source\"\n", " width=\"170\"\n", " height=\"45\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " rel=\"noreferrer noopener\"\n", " className=\"fbOpenSource\">\n" ], "file_path": "website/core/Footer.js", "type": "replace", "edit_start_line_idx": 94 }
<?xml version="1.0" encoding="UTF-8"?> <svg width="32px" height="32px" viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- Generator: Sketch 47.1 (45422) - http://www.bohemiancoding.com/sketch --> <title>Artboard 3</title> <desc>Created with Sketch.</desc> <defs> <linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="linearGradient-1"> <stop stop-color="#6F4824" offset="0%"></stop> <stop stop-color="#8F5D2F" offset="100%"></stop> </linearGradient> <linearGradient x1="2.73388929%" y1="39.0211096%" x2="100%" y2="39.0211105%" id="linearGradient-2"> <stop stop-color="#BF9155" offset="0%"></stop> <stop stop-color="#8B582B" offset="100%"></stop> </linearGradient> <path d="M24,21.1715729 L22.1715729,23 L24,24.8284271 L24,29 C24,29.5522847 23.5522847,30 23,30 L9.5,30 L8,30 L8,28.5 L8,17.5 L8,16 L9.5,16 L23,16 C23.5522847,16 24,16.4477153 24,17 L24,21.1715729 Z M10,18 L10,28 L22,28 L22,18 L10,18 Z M12,22 L22,22 L22,24 L12,24 L12,22 Z" id="path-3"></path> <filter x="-9.4%" y="-10.7%" width="118.8%" height="121.4%" filterUnits="objectBoundingBox" id="filter-4"> <feMorphology radius="0.5" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology> <feOffset dx="0" dy="0" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset> <feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.137879303 0" type="matrix" in="shadowOffsetOuter1"></feColorMatrix> </filter> </defs> <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="Artboard-3"> <ellipse id="Oval" fill="url(#linearGradient-1)" cx="16" cy="7" rx="16" ry="6"></ellipse> <path d="M0.910430441,21 L0,21 L0,25 C0,28.3137085 7.163444,31 16,31 C24.836556,31 32,28.3137085 32,25 L32,21 L31.0895696,21 C31.6791775,21.6255579 32,22.2987292 32,23 C32,26.3137085 24.836556,29 16,29 C7.163444,29 0,26.3137085 0,23 C0,22.2987292 0.320822513,21.6255579 0.910430441,21 Z" id="Combined-Shape" fill="#000000" opacity="0.0661798007"></path> <rect id="Rectangle-15" fill="#644222" x="22" y="21" width="2" height="2"></rect> <path d="M32,8 L32,25 C32,28.3137085 24.836556,31 16,31 C7.163444,31 0,28.3137085 0,25 L0,9 L-6.66133815e-15,9 C0,12.3137085 7.163444,15 16,15 C24.836556,15 32,12.3137085 32,9 L32,8 Z" id="Combined-Shape" fill="url(#linearGradient-2)"></path> <ellipse id="Oval" fill="#794E27" cx="16" cy="7.5" rx="16" ry="6.5"></ellipse> <g id="Combined-Shape"> <use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-3"></use> <use fill="#FFFFFF" fill-rule="evenodd" xlink:href="#path-3"></use> </g> <ellipse id="Oval-5" fill-opacity="0.23680933" fill="#000000" cx="5.5" cy="22" rx="1" ry="1"></ellipse> <ellipse id="Oval-5" fill-opacity="0.23680933" fill="#000000" cx="3.5" cy="21" rx="1" ry="1"></ellipse> <ellipse id="Oval-5" fill-opacity="0.23680933" fill="#000000" cx="1.5" cy="20" rx="1" ry="1"></ellipse> </g> </g> </svg>
website/static/img/bucklescript.svg
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.0001751922827679664, 0.00017331319395452738, 0.00017042936815414578, 0.00017381555517204106, 0.000001879357796497061 ]
{ "id": 9, "code_window": [ "\n", " <a\n", " href=\"https://code.facebook.com/projects/\"\n", " target=\"_blank\"\n", " className=\"fbOpenSource\"\n", " >\n", " <img\n", " src={`${this.props.config.baseUrl}img/oss_logo.png`}\n", " alt=\"Facebook Open Source\"\n", " width=\"170\"\n", " height=\"45\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " rel=\"noreferrer noopener\"\n", " className=\"fbOpenSource\">\n" ], "file_path": "website/core/Footer.js", "type": "replace", "edit_start_line_idx": 94 }
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); const CompLibrary = require('../../core/CompLibrary.js'); const MarkdownBlock = CompLibrary.MarkdownBlock; /* Used to read markdown */ const Container = CompLibrary.Container; const GridBlock = CompLibrary.GridBlock; const siteConfig = require(process.cwd() + '/siteConfig.js'); function imgUrl(img) { return siteConfig.baseUrl + 'img/' + img; } function docUrl(doc, language) { return siteConfig.baseUrl + 'docs/' + (language ? language + '/' : '') + doc; } function pageUrl(page, language) { return siteConfig.baseUrl + (language ? language + '/' : '') + page; } class Button extends React.Component { render() { return ( <div className="pluginWrapper buttonWrapper"> <a className="button" href={this.props.href} target={this.props.target}> {this.props.children} </a> </div> ); } } Button.defaultProps = { target: '_self', }; const SplashContainer = props => ( <div className="homeContainer"> <div className="homeSplashFade"> <div className="wrapper homeWrapper">{props.children}</div> </div> </div> ); const Logo = props => ( <div className="projectLogo"> <img src={props.img_src} /> </div> ); const ProjectTitle = props => ( <h2 className="projectTitle"> {siteConfig.title} <small>{siteConfig.tagline}</small> </h2> ); const PromoSection = props => ( <div className="section promoSection"> <div className="promoRow"> <div className="pluginRowBlock">{props.children}</div> </div> </div> ); class HomeSplash extends React.Component { render() { let language = this.props.language || ''; return ( <SplashContainer> <Logo img_src={imgUrl('docusaurus.svg')} /> <div className="inner"> <ProjectTitle /> <PromoSection> <Button href="#try">Try It Out</Button> <Button href={docUrl('doc1.html', language)}>Example Link</Button> <Button href={docUrl('doc2.html', language)}>Example Link 2</Button> </PromoSection> </div> </SplashContainer> ); } } const Block = props => ( <Container padding={['bottom', 'top']} id={props.id} background={props.background}> <GridBlock align="center" contents={props.children} layout={props.layout} /> </Container> ); const Features = props => ( <Block layout="fourColumn"> {[ { content: 'This is the content of my feature', image: imgUrl('docusaurus.svg'), imageAlign: 'top', title: 'Feature One', }, { content: 'The content of my second feature', image: imgUrl('docusaurus.svg'), imageAlign: 'top', title: 'Feature Two', }, ]} </Block> ); const FeatureCallout = props => ( <div className="productShowcaseSection paddingBottom" style={{textAlign: 'center'}}> <h2>Feature Callout</h2> <MarkdownBlock>These are features of this project</MarkdownBlock> </div> ); const LearnHow = props => ( <Block background="light"> {[ { content: 'Talk about learning how to use this', image: imgUrl('docusaurus.svg'), imageAlign: 'right', title: 'Learn How', }, ]} </Block> ); const TryOut = props => ( <Block id="try"> {[ { content: 'Talk about trying this out', image: imgUrl('docusaurus.svg'), imageAlign: 'left', title: 'Try it Out', }, ]} </Block> ); const Description = props => ( <Block background="dark"> {[ { content: 'This is another description of how this project is useful', image: imgUrl('docusaurus.svg'), imageAlign: 'right', title: 'Description', }, ]} </Block> ); const Showcase = props => { if ((siteConfig.users || []).length === 0) { return null; } const showcase = siteConfig.users .filter(user => { return user.pinned; }) .map((user, i) => { return ( <a href={user.infoLink} key={i}> <img src={user.image} alt={user.caption} title={user.caption} /> </a> ); }); return ( <div className="productShowcaseSection paddingBottom"> <h2>{"Who's Using This?"}</h2> <p>This project is used by all these people</p> <div className="logos">{showcase}</div> <div className="more-users"> <a className="button" href={pageUrl('users.html', props.language)}> More {siteConfig.title} Users </a> </div> </div> ); }; class Index extends React.Component { render() { let language = this.props.language || ''; return ( <div> <HomeSplash language={language} /> <div className="mainContainer"> <Features /> <FeatureCallout /> <LearnHow /> <TryOut /> <Description /> <Showcase language={language} /> </div> </div> ); } } module.exports = Index;
examples/basics/pages/en/index.js
0
https://github.com/facebook/docusaurus/commit/e19b9ac56e227c40209cec774b5b74a539819153
[ 0.0011881018290296197, 0.00026984934811480343, 0.00016435649013146758, 0.00017436643247492611, 0.00024305992701556534 ]
{ "id": 0, "code_window": [ " }\n", "\n", " onEntryFinished(entry: har.Entry) {\n", " const event: trace.ResourceSnapshotTraceEvent = { type: 'resource-snapshot', snapshot: entry };\n", " this._appendTraceOperation(async () => {\n", " visitSha1s(event, this._state!.networkSha1s);\n", " await fs.promises.appendFile(this._state!.networkFile, JSON.stringify(event) + '\\n');\n", " });\n", " }\n", "\n", " onContentBlob(sha1: string, buffer: Buffer) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const visited = visitTraceEvent(event, this._state!.networkSha1s);\n", " await fs.promises.appendFile(this._state!.networkFile, JSON.stringify(visited) + '\\n');\n" ], "file_path": "packages/playwright-core/src/server/trace/recorder/tracing.ts", "type": "replace", "edit_start_line_idx": 369 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { EventEmitter } from 'events'; import fs from 'fs'; import os from 'os'; import path from 'path'; import type { NameValue } from '../../../common/types'; import type { TracingTracingStopChunkParams } from '@protocol/channels'; import { commandsWithTracingSnapshots } from '../../../protocol/debug'; import { ManualPromise } from '../../../utils/manualPromise'; import type { RegisteredListener } from '../../../utils/eventsHelper'; import { eventsHelper } from '../../../utils/eventsHelper'; import { assert, calculateSha1, createGuid, monotonicTime } from '../../../utils'; import { mkdirIfNeeded, removeFolders } from '../../../utils/fileUtils'; import { Artifact } from '../../artifact'; import { BrowserContext } from '../../browserContext'; import { ElementHandle } from '../../dom'; import type { APIRequestContext } from '../../fetch'; import type { CallMetadata, InstrumentationListener } from '../../instrumentation'; import { SdkObject } from '../../instrumentation'; import { Page } from '../../page'; import type * as har from '@trace/har'; import type { HarTracerDelegate } from '../../har/harTracer'; import { HarTracer } from '../../har/harTracer'; import type { FrameSnapshot } from '@trace/snapshot'; import type * as trace from '@trace/trace'; import type { VERSION } from '@trace/trace'; import type { SnapshotterBlob, SnapshotterDelegate } from './snapshotter'; import { Snapshotter } from './snapshotter'; import { yazl } from '../../../zipBundle'; const version: VERSION = 3; export type TracerOptions = { name?: string; snapshots?: boolean; screenshots?: boolean; sources?: boolean; }; type RecordingState = { options: TracerOptions, traceName: string, networkFile: string, traceFile: string, tracesDir: string, resourcesDir: string, filesCount: number, networkSha1s: Set<string>, traceSha1s: Set<string>, sources: Set<string>, recording: boolean; }; const kScreencastOptions = { width: 800, height: 600, quality: 90 }; export class Tracing extends SdkObject implements InstrumentationListener, SnapshotterDelegate, HarTracerDelegate { private _writeChain = Promise.resolve(); private _snapshotter?: Snapshotter; private _harTracer: HarTracer; private _screencastListeners: RegisteredListener[] = []; private _pendingCalls = new Map<string, { sdkObject: SdkObject, metadata: CallMetadata, beforeSnapshot: Promise<void>, actionSnapshot?: Promise<void>, afterSnapshot?: Promise<void> }>(); private _context: BrowserContext | APIRequestContext; private _state: RecordingState | undefined; private _isStopping = false; private _precreatedTracesDir: string | undefined; private _tracesTmpDir: string | undefined; private _allResources = new Set<string>(); private _contextCreatedEvent: trace.ContextCreatedTraceEvent; constructor(context: BrowserContext | APIRequestContext, tracesDir: string | undefined) { super(context, 'tracing'); this._context = context; this._precreatedTracesDir = tracesDir; this._harTracer = new HarTracer(context, null, this, { content: 'attach', includeTraceInfo: true, recordRequestOverrides: false, waitForContentOnStop: false, skipScripts: true, }); this._contextCreatedEvent = { version, type: 'context-options', browserName: '', options: {}, platform: process.platform, wallTime: 0, }; if (context instanceof BrowserContext) { this._snapshotter = new Snapshotter(context, this); assert(tracesDir, 'tracesDir must be specified for BrowserContext'); this._contextCreatedEvent.browserName = context._browser.options.name; this._contextCreatedEvent.options = context._options; } } async start(options: TracerOptions) { if (this._isStopping) throw new Error('Cannot start tracing while stopping'); if (this._state) { const o = this._state.options; if (o.name !== options.name || !o.screenshots !== !options.screenshots || !o.snapshots !== !options.snapshots) throw new Error('Tracing has been already started with different options'); return; } // TODO: passing the same name for two contexts makes them write into a single file // and conflict. const traceName = options.name || createGuid(); // Init the state synchrounously. this._state = { options, traceName, traceFile: '', networkFile: '', tracesDir: '', resourcesDir: '', filesCount: 0, traceSha1s: new Set(), networkSha1s: new Set(), sources: new Set(), recording: false }; const state = this._state; state.tracesDir = await this._createTracesDirIfNeeded(); state.resourcesDir = path.join(state.tracesDir, 'resources'); state.traceFile = path.join(state.tracesDir, traceName + '.trace'); state.networkFile = path.join(state.tracesDir, traceName + '.network'); this._writeChain = fs.promises.mkdir(state.resourcesDir, { recursive: true }).then(() => fs.promises.writeFile(state.networkFile, '')); if (options.snapshots) this._harTracer.start(); } async startChunk(options: { title?: string } = {}) { if (this._state && this._state.recording) await this.stopChunk({ mode: 'doNotSave' }); if (!this._state) throw new Error('Must start tracing before starting a new chunk'); if (this._isStopping) throw new Error('Cannot start a trace chunk while stopping'); const state = this._state; const suffix = state.filesCount ? `-${state.filesCount}` : ``; state.filesCount++; state.traceFile = path.join(state.tracesDir, `${state.traceName}${suffix}.trace`); state.recording = true; this._appendTraceOperation(async () => { await mkdirIfNeeded(state.traceFile); await fs.promises.appendFile(state.traceFile, JSON.stringify({ ...this._contextCreatedEvent, title: options.title, wallTime: Date.now() }) + '\n'); }); this._context.instrumentation.addListener(this, this._context); if (state.options.screenshots) this._startScreencast(); if (state.options.snapshots) await this._snapshotter?.start(); } private _startScreencast() { if (!(this._context instanceof BrowserContext)) return; for (const page of this._context.pages()) this._startScreencastInPage(page); this._screencastListeners.push( eventsHelper.addEventListener(this._context, BrowserContext.Events.Page, this._startScreencastInPage.bind(this)), ); } private _stopScreencast() { eventsHelper.removeEventListeners(this._screencastListeners); if (!(this._context instanceof BrowserContext)) return; for (const page of this._context.pages()) page.setScreencastOptions(null); } async stop() { if (!this._state) return; if (this._isStopping) throw new Error(`Tracing is already stopping`); if (this._state.recording) throw new Error(`Must stop trace file before stopping tracing`); this._harTracer.stop(); await this._writeChain; this._state = undefined; } async deleteTmpTracesDir() { if (this._tracesTmpDir) await removeFolders([this._tracesTmpDir]); } private async _createTracesDirIfNeeded() { if (this._precreatedTracesDir) return this._precreatedTracesDir; this._tracesTmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'playwright-tracing-')); return this._tracesTmpDir; } async dispose() { this._snapshotter?.dispose(); this._harTracer.stop(); await this._writeChain; } async stopChunk(params: TracingTracingStopChunkParams): Promise<{ artifact: Artifact | null, sourceEntries: NameValue[] | undefined }> { if (this._isStopping) throw new Error(`Tracing is already stopping`); this._isStopping = true; if (!this._state || !this._state.recording) { this._isStopping = false; if (params.mode !== 'doNotSave') throw new Error(`Must start tracing before stopping`); return { artifact: null, sourceEntries: [] }; } const state = this._state!; this._context.instrumentation.removeListener(this); if (this._state?.options.screenshots) this._stopScreencast(); for (const { sdkObject, metadata, beforeSnapshot, actionSnapshot, afterSnapshot } of this._pendingCalls.values()) { await Promise.all([beforeSnapshot, actionSnapshot, afterSnapshot]); let callMetadata = metadata; if (!afterSnapshot) { // Note: we should not modify metadata here to avoid side-effects in any other place. callMetadata = { ...metadata, error: { error: { name: 'Error', message: 'Action was interrupted' } }, }; } await this.onAfterCall(sdkObject, callMetadata); } if (state.options.snapshots) await this._snapshotter?.stop(); // Chain the export operation against write operations, // so that neither trace files nor sha1s change during the export. return await this._appendTraceOperation(async () => { if (params.mode === 'doNotSave') return { artifact: null, sourceEntries: undefined }; // Har files a live, make a snapshot before returning the resulting entries. const networkFile = path.join(state.networkFile, '..', createGuid()); await fs.promises.copyFile(state.networkFile, networkFile); const entries: NameValue[] = []; entries.push({ name: 'trace.trace', value: state.traceFile }); entries.push({ name: 'trace.network', value: networkFile }); for (const sha1 of new Set([...state.traceSha1s, ...state.networkSha1s])) entries.push({ name: path.join('resources', sha1), value: path.join(state.resourcesDir, sha1) }); let sourceEntries: NameValue[] | undefined; if (state.sources.size) { sourceEntries = []; for (const value of state.sources) { const entry = { name: 'resources/src@' + calculateSha1(value) + '.txt', value }; if (params.mode === 'compressTraceAndSources') { if (fs.existsSync(entry.value)) entries.push(entry); } else { sourceEntries.push(entry); } } } const artifact = await this._exportZip(entries, state).catch(() => null); return { artifact, sourceEntries }; }).finally(() => { // Only reset trace sha1s, network resources are preserved between chunks. state.traceSha1s = new Set(); state.sources = new Set(); this._isStopping = false; state.recording = false; }) || { artifact: null, sourceEntries: undefined }; } private async _exportZip(entries: NameValue[], state: RecordingState): Promise<Artifact | null> { const zipFile = new yazl.ZipFile(); const result = new ManualPromise<Artifact | null>(); (zipFile as any as EventEmitter).on('error', error => result.reject(error)); for (const entry of entries) zipFile.addFile(entry.value, entry.name); zipFile.end(); const zipFileName = state.traceFile + '.zip'; zipFile.outputStream.pipe(fs.createWriteStream(zipFileName)).on('close', () => { const artifact = new Artifact(this._context, zipFileName); artifact.reportFinished(); result.resolve(artifact); }); return result; } async _captureSnapshot(name: 'before' | 'after' | 'action' | 'event', sdkObject: SdkObject, metadata: CallMetadata, element?: ElementHandle) { if (!this._snapshotter) return; if (!sdkObject.attribution.page) return; if (!this._snapshotter.started()) return; if (!shouldCaptureSnapshot(metadata)) return; const snapshotName = `${name}@${metadata.id}`; metadata.snapshots.push({ title: name, snapshotName }); // We have |element| for input actions (page.click and handle.click) // and |sdkObject| element for accessors like handle.textContent. if (!element && sdkObject instanceof ElementHandle) element = sdkObject; await this._snapshotter.captureSnapshot(sdkObject.attribution.page, snapshotName, element).catch(() => {}); } async onBeforeCall(sdkObject: SdkObject, metadata: CallMetadata) { sdkObject.attribution.page?.temporarlyDisableTracingScreencastThrottling(); // Set afterSnapshot name for all the actions that operate selectors. // Elements resolved from selectors will be marked on the snapshot. metadata.afterSnapshot = `after@${metadata.id}`; const beforeSnapshot = this._captureSnapshot('before', sdkObject, metadata); this._pendingCalls.set(metadata.id, { sdkObject, metadata, beforeSnapshot }); if (this._state?.options.sources) { for (const frame of metadata.stack || []) this._state.sources.add(frame.file); } await beforeSnapshot; } async onBeforeInputAction(sdkObject: SdkObject, metadata: CallMetadata, element: ElementHandle) { sdkObject.attribution.page?.temporarlyDisableTracingScreencastThrottling(); const actionSnapshot = this._captureSnapshot('action', sdkObject, metadata, element); this._pendingCalls.get(metadata.id)!.actionSnapshot = actionSnapshot; await actionSnapshot; } async onAfterCall(sdkObject: SdkObject, metadata: CallMetadata) { sdkObject.attribution.page?.temporarlyDisableTracingScreencastThrottling(); const pendingCall = this._pendingCalls.get(metadata.id); if (!pendingCall || pendingCall.afterSnapshot) return; if (!sdkObject.attribution.context) { this._pendingCalls.delete(metadata.id); return; } pendingCall.afterSnapshot = this._captureSnapshot('after', sdkObject, metadata); await pendingCall.afterSnapshot; const event: trace.ActionTraceEvent = { type: 'action', metadata }; this._appendTraceEvent(event); this._pendingCalls.delete(metadata.id); } onEvent(sdkObject: SdkObject, metadata: CallMetadata) { if (!sdkObject.attribution.context) return; const event: trace.ActionTraceEvent = { type: 'event', metadata }; this._appendTraceEvent(event); } onEntryStarted(entry: har.Entry) { } onEntryFinished(entry: har.Entry) { const event: trace.ResourceSnapshotTraceEvent = { type: 'resource-snapshot', snapshot: entry }; this._appendTraceOperation(async () => { visitSha1s(event, this._state!.networkSha1s); await fs.promises.appendFile(this._state!.networkFile, JSON.stringify(event) + '\n'); }); } onContentBlob(sha1: string, buffer: Buffer) { this._appendResource(sha1, buffer); } onSnapshotterBlob(blob: SnapshotterBlob): void { this._appendResource(blob.sha1, blob.buffer); } onFrameSnapshot(snapshot: FrameSnapshot): void { this._appendTraceEvent({ type: 'frame-snapshot', snapshot }); } private _startScreencastInPage(page: Page) { page.setScreencastOptions(kScreencastOptions); const prefix = page.guid; this._screencastListeners.push( eventsHelper.addEventListener(page, Page.Events.ScreencastFrame, params => { const suffix = params.timestamp || Date.now(); const sha1 = `${prefix}-${suffix}.jpeg`; const event: trace.ScreencastFrameTraceEvent = { type: 'screencast-frame', pageId: page.guid, sha1, width: params.width, height: params.height, timestamp: monotonicTime() }; // Make sure to write the screencast frame before adding a reference to it. this._appendResource(sha1, params.buffer); this._appendTraceEvent(event); }), ); } private _appendTraceEvent(event: trace.TraceEvent) { this._appendTraceOperation(async () => { visitSha1s(event, this._state!.traceSha1s); await fs.promises.appendFile(this._state!.traceFile, JSON.stringify(event) + '\n'); }); } private _appendResource(sha1: string, buffer: Buffer) { if (this._allResources.has(sha1)) return; this._allResources.add(sha1); const resourcePath = path.join(this._state!.resourcesDir, sha1); this._appendTraceOperation(async () => { try { // Perhaps we've already written this resource? await fs.promises.access(resourcePath); } catch (e) { // If not, let's write! Note that async access is safe because we // never remove resources until the very end. await fs.promises.writeFile(resourcePath, buffer).catch(() => {}); } }); } private async _appendTraceOperation<T>(cb: () => Promise<T>): Promise<T | undefined> { // This method serializes all writes to the trace. let error: Error | undefined; let result: T | undefined; this._writeChain = this._writeChain.then(async () => { // This check is here because closing the browser removes the tracesDir and tracing // dies trying to archive. if (this._context instanceof BrowserContext && !this._context._browser.isConnected()) return; try { result = await cb(); } catch (e) { error = e; } }); await this._writeChain; if (error) throw error; return result; } } function visitSha1s(object: any, sha1s: Set<string>) { if (Array.isArray(object)) { object.forEach(o => visitSha1s(o, sha1s)); return; } if (typeof object === 'object') { for (const key in object) { if (key === 'sha1' || key === '_sha1' || key.endsWith('Sha1')) { const sha1 = object[key]; if (sha1) sha1s.add(sha1); } visitSha1s(object[key], sha1s); } return; } } export function shouldCaptureSnapshot(metadata: CallMetadata): boolean { return commandsWithTracingSnapshots.has(metadata.type + '.' + metadata.method); }
packages/playwright-core/src/server/trace/recorder/tracing.ts
1
https://github.com/microsoft/playwright/commit/6d363888f27b1238986398fd1d6e1f149e039e12
[ 0.9967437982559204, 0.023157374933362007, 0.00016422115731984377, 0.00028415455017238855, 0.14236968755722046 ]
{ "id": 0, "code_window": [ " }\n", "\n", " onEntryFinished(entry: har.Entry) {\n", " const event: trace.ResourceSnapshotTraceEvent = { type: 'resource-snapshot', snapshot: entry };\n", " this._appendTraceOperation(async () => {\n", " visitSha1s(event, this._state!.networkSha1s);\n", " await fs.promises.appendFile(this._state!.networkFile, JSON.stringify(event) + '\\n');\n", " });\n", " }\n", "\n", " onContentBlob(sha1: string, buffer: Buffer) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const visited = visitTraceEvent(event, this._state!.networkSha1s);\n", " await fs.promises.appendFile(this._state!.networkFile, JSON.stringify(visited) + '\\n');\n" ], "file_path": "packages/playwright-core/src/server/trace/recorder/tracing.ts", "type": "replace", "edit_start_line_idx": 369 }
/** * Copyright 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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type { TestInfoImpl } from './testInfo'; import type { Suite } from './test'; let currentTestInfoValue: TestInfoImpl | null = null; export function setCurrentTestInfo(testInfo: TestInfoImpl | null) { currentTestInfoValue = testInfo; } export function currentTestInfo(): TestInfoImpl | null { return currentTestInfoValue; } let currentFileSuite: Suite | undefined; export function setCurrentlyLoadingFileSuite(suite: Suite | undefined) { currentFileSuite = suite; } export function currentlyLoadingFileSuite() { return currentFileSuite; }
packages/playwright-test/src/globals.ts
0
https://github.com/microsoft/playwright/commit/6d363888f27b1238986398fd1d6e1f149e039e12
[ 0.00017828319687396288, 0.00017225560441147536, 0.00016177531506400555, 0.00017448193102609366, 0.000006246627890504897 ]