Run prettier

pull/2748/head
Alex Dima 5 years ago
parent 06e3393f83
commit 0b344d31d0
No known key found for this signature in database
GPG Key ID: 6E58D7B045760DA0

@ -6,4 +6,4 @@
"**/release": true, "**/release": true,
"**/out": true "**/out": true
} }
} }

@ -1,21 +1,21 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) Microsoft Corporation Copyright (c) Microsoft Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.

@ -1,37 +1,39 @@
# Monaco JSON # Monaco JSON
JSON language plugin for the Monaco Editor. It provides the following features when editing JSON files: JSON language plugin for the Monaco Editor. It provides the following features when editing JSON files:
* Code completion, based on JSON schemas or by looking at similar objects in the same file
* Hovers, based on JSON schemas - Code completion, based on JSON schemas or by looking at similar objects in the same file
* Validation: Syntax errors and schema validation - Hovers, based on JSON schemas
* Formatting - Validation: Syntax errors and schema validation
* Document Symbols - Formatting
* Syntax highlighting - Document Symbols
* Color decorators for all properties matching a schema containing `format: "color-hex"'` (non-standard schema extension) - Syntax highlighting
- Color decorators for all properties matching a schema containing `format: "color-hex"'` (non-standard schema extension)
Schemas can be provided by configuration. See [here](https://github.com/Microsoft/monaco-json/blob/master/monaco.d.ts)
for the API that the JSON plugin offers to configure the JSON language support. Schemas can be provided by configuration. See [here](https://github.com/Microsoft/monaco-json/blob/master/monaco.d.ts)
for the API that the JSON plugin offers to configure the JSON language support.
Internally the JSON plugin uses the [vscode-json-languageservice](https://github.com/Microsoft/vscode-json-languageservice)
node module, providing the implementation of the features listed above. The same module is also used Internally the JSON plugin uses the [vscode-json-languageservice](https://github.com/Microsoft/vscode-json-languageservice)
in [Visual Studio Code](https://github.com/Microsoft/vscode) to power the JSON editing experience. node module, providing the implementation of the features listed above. The same module is also used
in [Visual Studio Code](https://github.com/Microsoft/vscode) to power the JSON editing experience.
## Issues
## Issues
Please file issues concerning `monaco-json` in the [`monaco-editor` repository](https://github.com/Microsoft/monaco-editor/issues).
Please file issues concerning `monaco-json` in the [`monaco-editor` repository](https://github.com/Microsoft/monaco-editor/issues).
## Installing
## Installing
This npm module is bundled and distributed in the [monaco-editor](https://www.npmjs.com/package/monaco-editor) npm module.
This npm module is bundled and distributed in the [monaco-editor](https://www.npmjs.com/package/monaco-editor) npm module.
## Development
## Development
* `git clone https://github.com/Microsoft/monaco-json`
* `npm install .` - `git clone https://github.com/Microsoft/monaco-json`
* compile with `npm run compile` - `npm install .`
* watch with `npm run watch` - compile with `npm run compile`
* `npm run prepublishOnly` - watch with `npm run watch`
* open `$/monaco-json/test/index.html` in your favorite browser. - `npm run prepublishOnly`
- open `$/monaco-json/test/index.html` in your favorite browser.
## License
[MIT](https://github.com/Microsoft/monaco-json/blob/master/LICENSE.md) ## License
[MIT](https://github.com/Microsoft/monaco-json/blob/master/LICENSE.md)

2
monaco.d.ts vendored

@ -4,7 +4,6 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
declare namespace monaco.languages.json { declare namespace monaco.languages.json {
export interface DiagnosticsOptions { export interface DiagnosticsOptions {
/** /**
* If set, the validator will be enabled and perform syntax validation as well as schema based validation. * If set, the validator will be enabled and perform syntax validation as well as schema based validation.
@ -87,5 +86,4 @@ declare namespace monaco.languages.json {
setModeConfiguration(modeConfiguration: ModeConfiguration): void; setModeConfiguration(modeConfiguration: ModeConfiguration): void;
} }
export const jsonDefaults: LanguageServiceDefaults; export const jsonDefaults: LanguageServiceDefaults;
} }

@ -1,7 +1,7 @@
const requirejs = require('requirejs'); const requirejs = require('requirejs');
const path = require('path'); const path = require('path');
const fs = require('fs'); const fs = require('fs');
const Terser = require("terser"); const Terser = require('terser');
const helpers = require('monaco-plugin-helpers'); const helpers = require('monaco-plugin-helpers');
const REPO_ROOT = path.resolve(__dirname, '..'); const REPO_ROOT = path.resolve(__dirname, '..');
@ -25,52 +25,80 @@ bundleOne('jsonMode');
bundleOne('jsonWorker'); bundleOne('jsonWorker');
function bundleOne(moduleId) { function bundleOne(moduleId) {
requirejs.optimize({ requirejs.optimize(
baseUrl: 'out/amd/', {
name: 'vs/language/json/' + moduleId, baseUrl: 'out/amd/',
out: 'release/dev/' + moduleId + '.js', name: 'vs/language/json/' + moduleId,
paths: { out: 'release/dev/' + moduleId + '.js',
'vs/language/json': REPO_ROOT + '/out/amd', paths: {
'vs/language/json/fillers/monaco-editor-core': REPO_ROOT + '/out/amd/fillers/monaco-editor-core-amd', 'vs/language/json': REPO_ROOT + '/out/amd',
'vs/language/json/fillers/monaco-editor-core':
REPO_ROOT + '/out/amd/fillers/monaco-editor-core-amd'
},
optimize: 'none',
packages: [
{
name: 'vscode-json-languageservice',
location: path.join(
REPO_ROOT,
'node_modules/vscode-json-languageservice/lib/umd'
),
main: 'jsonLanguageService'
},
{
name: 'vscode-languageserver-types',
location: path.join(
REPO_ROOT,
'node_modules/vscode-languageserver-types/lib/umd'
),
main: 'main'
},
{
name: 'vscode-languageserver-textdocument',
location: path.join(
REPO_ROOT,
'node_modules/vscode-languageserver-textdocument/lib/umd'
),
main: 'main'
},
{
name: 'jsonc-parser',
location: path.join(REPO_ROOT, 'node_modules/jsonc-parser/lib/umd'),
main: 'main'
},
{
name: 'vscode-uri',
location: path.join(REPO_ROOT, 'node_modules/vscode-uri/lib/umd'),
main: 'index'
},
{
name: 'vscode-nls',
location: path.join(REPO_ROOT, '/out/amd/fillers'),
main: 'vscode-nls'
}
]
}, },
optimize: 'none', async function (buildResponse) {
packages: [{ const devFilePath = path.join(
name: 'vscode-json-languageservice', REPO_ROOT,
location: path.join(REPO_ROOT, 'node_modules/vscode-json-languageservice/lib/umd'), 'release/dev/' + moduleId + '.js'
main: 'jsonLanguageService' );
}, { const minFilePath = path.join(
name: 'vscode-languageserver-types', REPO_ROOT,
location: path.join(REPO_ROOT, 'node_modules/vscode-languageserver-types/lib/umd'), 'release/min/' + moduleId + '.js'
main: 'main' );
}, { const fileContents = fs.readFileSync(devFilePath).toString();
name: 'vscode-languageserver-textdocument', console.log(`Minifying ${devFilePath}...`);
location: path.join(REPO_ROOT, 'node_modules/vscode-languageserver-textdocument/lib/umd'), const result = await Terser.minify(fileContents, {
main: 'main' output: {
}, { comments: 'some'
name: 'jsonc-parser', }
location: path.join(REPO_ROOT, 'node_modules/jsonc-parser/lib/umd'), });
main: 'main' console.log(`Done minifying ${devFilePath}.`);
}, { try {
name: 'vscode-uri', fs.mkdirSync(path.join(REPO_ROOT, 'release/min'));
location: path.join(REPO_ROOT, 'node_modules/vscode-uri/lib/umd'), } catch (err) {}
main: 'index' fs.writeFileSync(minFilePath, BUNDLED_FILE_HEADER + result.code);
}, { }
name: 'vscode-nls', );
location: path.join(REPO_ROOT, '/out/amd/fillers'),
main: 'vscode-nls'
}]
}, async function (buildResponse) {
const devFilePath = path.join(REPO_ROOT, 'release/dev/' + moduleId + '.js');
const minFilePath = path.join(REPO_ROOT, 'release/min/' + moduleId + '.js');
const fileContents = fs.readFileSync(devFilePath).toString();
console.log(`Minifying ${devFilePath}...`);
const result = await Terser.minify(fileContents, {
output: {
comments: 'some'
}
});
console.log(`Done minifying ${devFilePath}.`);
try { fs.mkdirSync(path.join(REPO_ROOT, 'release/min')) } catch (err) { }
fs.writeFileSync(minFilePath, BUNDLED_FILE_HEADER + result.code);
})
} }

@ -10,7 +10,10 @@ const REPO_ROOT = path.join(__dirname, '../');
const SRC_PATH = path.join(REPO_ROOT, 'out/amd/monaco.contribution.d.ts'); const SRC_PATH = path.join(REPO_ROOT, 'out/amd/monaco.contribution.d.ts');
const DST_PATH = path.join(REPO_ROOT, 'monaco.d.ts'); const DST_PATH = path.join(REPO_ROOT, 'monaco.d.ts');
const lines = fs.readFileSync(SRC_PATH).toString().split(/\r\n|\r|\n/); const lines = fs
.readFileSync(SRC_PATH)
.toString()
.split(/\r\n|\r|\n/);
let result = [ let result = [
`/*---------------------------------------------------------------------------------------------`, `/*---------------------------------------------------------------------------------------------`,
` * Copyright (c) Microsoft Corporation. All rights reserved.`, ` * Copyright (c) Microsoft Corporation. All rights reserved.`,

@ -12,19 +12,13 @@ helpers.packageESM({
repoRoot: REPO_ROOT, repoRoot: REPO_ROOT,
esmSource: 'out/esm', esmSource: 'out/esm',
esmDestination: 'release/esm', esmDestination: 'release/esm',
entryPoints: [ entryPoints: ['monaco.contribution.js', 'jsonMode.js', 'json.worker.js'],
'monaco.contribution.js',
'jsonMode.js',
'json.worker.js'
],
resolveAlias: { resolveAlias: {
'vscode-nls': path.join(REPO_ROOT, "out/esm/fillers/vscode-nls.js") 'vscode-nls': path.join(REPO_ROOT, 'out/esm/fillers/vscode-nls.js')
}, },
resolveSkip: [ resolveSkip: ['monaco-editor-core'],
'monaco-editor-core'
],
destinationFolderSimplification: { destinationFolderSimplification: {
'node_modules': '_deps', node_modules: '_deps',
'jsonc-parser/lib/esm': 'jsonc-parser', 'jsonc-parser/lib/esm': 'jsonc-parser',
'vscode-languageserver-types/lib/esm': 'vscode-languageserver-types', 'vscode-languageserver-types/lib/esm': 'vscode-languageserver-types',
'vscode-uri/lib/esm': 'vscode-uri', 'vscode-uri/lib/esm': 'vscode-uri',

@ -7,6 +7,6 @@
declare var define; declare var define;
define([], function() { define([], function () {
return (<any>self).monaco; return (<any>self).monaco;
}); });

@ -20,7 +20,7 @@ export interface LoadFunc {
} }
function format(message: string, args: any[]): string { function format(message: string, args: any[]): string {
let result:string; let result: string;
if (args.length === 0) { if (args.length === 0) {
result = message; result = message;
@ -33,14 +33,18 @@ function format(message: string, args: any[]): string {
return result; return result;
} }
function localize(key: string | LocalizeInfo, message: string, ...args: any[]): string { function localize(
key: string | LocalizeInfo,
message: string,
...args: any[]
): string {
return format(message, args); return format(message, args);
} }
export function loadMessageBundle(file?: string): LocalizeFunc { export function loadMessageBundle(file?: string): LocalizeFunc {
return localize; return localize;
} }
export function config(opt?: Options | string): LoadFunc { export function config(opt?: Options | string): LoadFunc {
return loadMessageBundle; return loadMessageBundle;
} }

@ -9,6 +9,6 @@ import { JSONWorker } from './jsonWorker';
self.onmessage = () => { self.onmessage = () => {
// ignore the first message // ignore the first message
worker.initialize((ctx, createData) => { worker.initialize((ctx, createData) => {
return new JSONWorker(ctx, createData) return new JSONWorker(ctx, createData);
}); });
}; };

@ -1,109 +1,157 @@
/*--------------------------------------------------------------------------------------------- /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved. * Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import { WorkerManager } from './workerManager'; import { WorkerManager } from './workerManager';
import type { JSONWorker } from './jsonWorker'; import type { JSONWorker } from './jsonWorker';
import { LanguageServiceDefaults } from './monaco.contribution'; import { LanguageServiceDefaults } from './monaco.contribution';
import * as languageFeatures from './languageFeatures'; import * as languageFeatures from './languageFeatures';
import { createTokenizationSupport } from './tokenization'; import { createTokenizationSupport } from './tokenization';
import { Uri, IDisposable, languages } from './fillers/monaco-editor-core' import { Uri, IDisposable, languages } from './fillers/monaco-editor-core';
export function setupMode(defaults: LanguageServiceDefaults): IDisposable { export function setupMode(defaults: LanguageServiceDefaults): IDisposable {
const disposables: IDisposable[] = [];
const disposables: IDisposable[] = []; const providers: IDisposable[] = [];
const providers: IDisposable[] = [];
const client = new WorkerManager(defaults);
const client = new WorkerManager(defaults); disposables.push(client);
disposables.push(client);
const worker: languageFeatures.WorkerAccessor = (
const worker: languageFeatures.WorkerAccessor = (...uris: Uri[]): Promise<JSONWorker> => { ...uris: Uri[]
return client.getLanguageServiceWorker(...uris); ): Promise<JSONWorker> => {
}; return client.getLanguageServiceWorker(...uris);
};
function registerProviders(): void { function registerProviders(): void {
const { languageId, modeConfiguration } = defaults; const { languageId, modeConfiguration } = defaults;
disposeAll(providers); disposeAll(providers);
if (modeConfiguration.documentFormattingEdits) { if (modeConfiguration.documentFormattingEdits) {
providers.push(languages.registerDocumentFormattingEditProvider(languageId, new languageFeatures.DocumentFormattingEditProvider(worker))); providers.push(
} languages.registerDocumentFormattingEditProvider(
if (modeConfiguration.documentRangeFormattingEdits) { languageId,
providers.push(languages.registerDocumentRangeFormattingEditProvider(languageId, new languageFeatures.DocumentRangeFormattingEditProvider(worker))); new languageFeatures.DocumentFormattingEditProvider(worker)
} )
if (modeConfiguration.completionItems) { );
providers.push(languages.registerCompletionItemProvider(languageId, new languageFeatures.CompletionAdapter(worker))); }
} if (modeConfiguration.documentRangeFormattingEdits) {
if (modeConfiguration.hovers) { providers.push(
providers.push(languages.registerHoverProvider(languageId, new languageFeatures.HoverAdapter(worker))); languages.registerDocumentRangeFormattingEditProvider(
} languageId,
if (modeConfiguration.documentSymbols) { new languageFeatures.DocumentRangeFormattingEditProvider(worker)
providers.push(languages.registerDocumentSymbolProvider(languageId, new languageFeatures.DocumentSymbolAdapter(worker))); )
} );
if (modeConfiguration.tokens) { }
providers.push(languages.setTokensProvider(languageId, createTokenizationSupport(true))); if (modeConfiguration.completionItems) {
} providers.push(
if (modeConfiguration.colors) { languages.registerCompletionItemProvider(
providers.push(languages.registerColorProvider(languageId, new languageFeatures.DocumentColorAdapter(worker))); languageId,
} new languageFeatures.CompletionAdapter(worker)
if (modeConfiguration.foldingRanges) { )
providers.push(languages.registerFoldingRangeProvider(languageId, new languageFeatures.FoldingRangeAdapter(worker))); );
} }
if (modeConfiguration.diagnostics) { if (modeConfiguration.hovers) {
providers.push(new languageFeatures.DiagnosticsAdapter(languageId, worker, defaults)); providers.push(
} languages.registerHoverProvider(
if (modeConfiguration.selectionRanges) { languageId,
providers.push(languages.registerSelectionRangeProvider(languageId, new languageFeatures.SelectionRangeAdapter(worker))); new languageFeatures.HoverAdapter(worker)
} )
} );
}
registerProviders(); if (modeConfiguration.documentSymbols) {
providers.push(
disposables.push(languages.setLanguageConfiguration(defaults.languageId, richEditConfiguration)); languages.registerDocumentSymbolProvider(
languageId,
let modeConfiguration = defaults.modeConfiguration; new languageFeatures.DocumentSymbolAdapter(worker)
defaults.onDidChange((newDefaults) => { )
if (newDefaults.modeConfiguration !== modeConfiguration) { );
modeConfiguration = newDefaults.modeConfiguration; }
registerProviders(); if (modeConfiguration.tokens) {
} providers.push(
}); languages.setTokensProvider(languageId, createTokenizationSupport(true))
);
disposables.push(asDisposable(providers)); }
if (modeConfiguration.colors) {
return asDisposable(disposables); providers.push(
} languages.registerColorProvider(
languageId,
function asDisposable(disposables: IDisposable[]): IDisposable { new languageFeatures.DocumentColorAdapter(worker)
return { dispose: () => disposeAll(disposables) }; )
} );
}
function disposeAll(disposables: IDisposable[]) { if (modeConfiguration.foldingRanges) {
while (disposables.length) { providers.push(
disposables.pop().dispose(); languages.registerFoldingRangeProvider(
} languageId,
} new languageFeatures.FoldingRangeAdapter(worker)
)
const richEditConfiguration: languages.LanguageConfiguration = { );
wordPattern: /(-?\d*\.\d\w*)|([^\[\{\]\}\:\"\,\s]+)/g, }
if (modeConfiguration.diagnostics) {
comments: { providers.push(
lineComment: '//', new languageFeatures.DiagnosticsAdapter(languageId, worker, defaults)
blockComment: ['/*', '*/'] );
}, }
if (modeConfiguration.selectionRanges) {
brackets: [ providers.push(
['{', '}'], languages.registerSelectionRangeProvider(
['[', ']'] languageId,
], new languageFeatures.SelectionRangeAdapter(worker)
)
autoClosingPairs: [ );
{ open: '{', close: '}', notIn: ['string'] }, }
{ open: '[', close: ']', notIn: ['string'] }, }
{ open: '"', close: '"', notIn: ['string'] }
] registerProviders();
};
disposables.push(
languages.setLanguageConfiguration(
defaults.languageId,
richEditConfiguration
)
);
let modeConfiguration = defaults.modeConfiguration;
defaults.onDidChange((newDefaults) => {
if (newDefaults.modeConfiguration !== modeConfiguration) {
modeConfiguration = newDefaults.modeConfiguration;
registerProviders();
}
});
disposables.push(asDisposable(providers));
return asDisposable(disposables);
}
function asDisposable(disposables: IDisposable[]): IDisposable {
return { dispose: () => disposeAll(disposables) };
}
function disposeAll(disposables: IDisposable[]) {
while (disposables.length) {
disposables.pop().dispose();
}
}
const richEditConfiguration: languages.LanguageConfiguration = {
wordPattern: /(-?\d*\.\d\w*)|([^\[\{\]\}\:\"\,\s]+)/g,
comments: {
lineComment: '//',
blockComment: ['/*', '*/']
},
brackets: [
['{', '}'],
['[', ']']
],
autoClosingPairs: [
{ open: '{', close: '}', notIn: ['string'] },
{ open: '[', close: ']', notIn: ['string'] },
{ open: '"', close: '"', notIn: ['string'] }
]
};

@ -1,108 +1,159 @@
/*--------------------------------------------------------------------------------------------- /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved. * Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import * as jsonService from 'vscode-json-languageservice'; import * as jsonService from 'vscode-json-languageservice';
import type { worker } from './fillers/monaco-editor-core' import type { worker } from './fillers/monaco-editor-core';
let defaultSchemaRequestService; let defaultSchemaRequestService;
if (typeof fetch !== 'undefined') { if (typeof fetch !== 'undefined') {
defaultSchemaRequestService = function (url) { return fetch(url).then(response => response.text()) }; defaultSchemaRequestService = function (url) {
} return fetch(url).then((response) => response.text());
};
export class JSONWorker { }
private _ctx: worker.IWorkerContext; export class JSONWorker {
private _languageService: jsonService.LanguageService; private _ctx: worker.IWorkerContext;
private _languageSettings: jsonService.LanguageSettings; private _languageService: jsonService.LanguageService;
private _languageId: string; private _languageSettings: jsonService.LanguageSettings;
private _languageId: string;
constructor(ctx: worker.IWorkerContext, createData: ICreateData) {
this._ctx = ctx; constructor(ctx: worker.IWorkerContext, createData: ICreateData) {
this._languageSettings = createData.languageSettings; this._ctx = ctx;
this._languageId = createData.languageId; this._languageSettings = createData.languageSettings;
this._languageService = jsonService.getLanguageService({ this._languageId = createData.languageId;
schemaRequestService: createData.enableSchemaRequest && defaultSchemaRequestService this._languageService = jsonService.getLanguageService({
}); schemaRequestService:
this._languageService.configure(this._languageSettings); createData.enableSchemaRequest && defaultSchemaRequestService
} });
this._languageService.configure(this._languageSettings);
async doValidation(uri: string): Promise<jsonService.Diagnostic[]> { }
let document = this._getTextDocument(uri);
if (document) { async doValidation(uri: string): Promise<jsonService.Diagnostic[]> {
let jsonDocument = this._languageService.parseJSONDocument(document); let document = this._getTextDocument(uri);
return this._languageService.doValidation(document, jsonDocument); if (document) {
} let jsonDocument = this._languageService.parseJSONDocument(document);
return Promise.resolve([]); return this._languageService.doValidation(document, jsonDocument);
} }
async doComplete(uri: string, position: jsonService.Position): Promise<jsonService.CompletionList> { return Promise.resolve([]);
let document = this._getTextDocument(uri); }
let jsonDocument = this._languageService.parseJSONDocument(document); async doComplete(
return this._languageService.doComplete(document, position, jsonDocument); uri: string,
} position: jsonService.Position
async doResolve(item: jsonService.CompletionItem): Promise<jsonService.CompletionItem> { ): Promise<jsonService.CompletionList> {
return this._languageService.doResolve(item); let document = this._getTextDocument(uri);
} let jsonDocument = this._languageService.parseJSONDocument(document);
async doHover(uri: string, position: jsonService.Position): Promise<jsonService.Hover> { return this._languageService.doComplete(document, position, jsonDocument);
let document = this._getTextDocument(uri); }
let jsonDocument = this._languageService.parseJSONDocument(document); async doResolve(
return this._languageService.doHover(document, position, jsonDocument); item: jsonService.CompletionItem
} ): Promise<jsonService.CompletionItem> {
async format(uri: string, range: jsonService.Range, options: jsonService.FormattingOptions): Promise<jsonService.TextEdit[]> { return this._languageService.doResolve(item);
let document = this._getTextDocument(uri); }
let textEdits = this._languageService.format(document, range, options); async doHover(
return Promise.resolve(textEdits); uri: string,
} position: jsonService.Position
async resetSchema(uri: string): Promise<boolean> { ): Promise<jsonService.Hover> {
return Promise.resolve(this._languageService.resetSchema(uri)); let document = this._getTextDocument(uri);
} let jsonDocument = this._languageService.parseJSONDocument(document);
async findDocumentSymbols(uri: string): Promise<jsonService.SymbolInformation[]> { return this._languageService.doHover(document, position, jsonDocument);
let document = this._getTextDocument(uri); }
let jsonDocument = this._languageService.parseJSONDocument(document); async format(
let symbols = this._languageService.findDocumentSymbols(document, jsonDocument); uri: string,
return Promise.resolve(symbols); range: jsonService.Range,
} options: jsonService.FormattingOptions
async findDocumentColors(uri: string): Promise<jsonService.ColorInformation[]> { ): Promise<jsonService.TextEdit[]> {
let document = this._getTextDocument(uri); let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document); let textEdits = this._languageService.format(document, range, options);
let colorSymbols = this._languageService.findDocumentColors(document, jsonDocument); return Promise.resolve(textEdits);
return Promise.resolve(colorSymbols); }
} async resetSchema(uri: string): Promise<boolean> {
async getColorPresentations(uri: string, color: jsonService.Color, range: jsonService.Range): Promise<jsonService.ColorPresentation[]> { return Promise.resolve(this._languageService.resetSchema(uri));
let document = this._getTextDocument(uri); }
let jsonDocument = this._languageService.parseJSONDocument(document); async findDocumentSymbols(
let colorPresentations = this._languageService.getColorPresentations(document, jsonDocument, color, range); uri: string
return Promise.resolve(colorPresentations); ): Promise<jsonService.SymbolInformation[]> {
} let document = this._getTextDocument(uri);
async getFoldingRanges(uri: string, context?: { rangeLimit?: number; }): Promise<jsonService.FoldingRange[]> { let jsonDocument = this._languageService.parseJSONDocument(document);
let document = this._getTextDocument(uri); let symbols = this._languageService.findDocumentSymbols(
let ranges = this._languageService.getFoldingRanges(document, context); document,
return Promise.resolve(ranges); jsonDocument
} );
async getSelectionRanges(uri: string, positions: jsonService.Position[]): Promise<jsonService.SelectionRange[]> { return Promise.resolve(symbols);
let document = this._getTextDocument(uri); }
let jsonDocument = this._languageService.parseJSONDocument(document); async findDocumentColors(
let ranges = this._languageService.getSelectionRanges(document, positions, jsonDocument); uri: string
return Promise.resolve(ranges); ): Promise<jsonService.ColorInformation[]> {
} let document = this._getTextDocument(uri);
private _getTextDocument(uri: string): jsonService.TextDocument { let jsonDocument = this._languageService.parseJSONDocument(document);
let models = this._ctx.getMirrorModels(); let colorSymbols = this._languageService.findDocumentColors(
for (let model of models) { document,
if (model.uri.toString() === uri) { jsonDocument
return jsonService.TextDocument.create(uri, this._languageId, model.version, model.getValue()); );
} return Promise.resolve(colorSymbols);
} }
return null; async getColorPresentations(
} uri: string,
} color: jsonService.Color,
range: jsonService.Range
export interface ICreateData { ): Promise<jsonService.ColorPresentation[]> {
languageId: string; let document = this._getTextDocument(uri);
languageSettings: jsonService.LanguageSettings; let jsonDocument = this._languageService.parseJSONDocument(document);
enableSchemaRequest: boolean; let colorPresentations = this._languageService.getColorPresentations(
} document,
jsonDocument,
export function create(ctx: worker.IWorkerContext, createData: ICreateData): JSONWorker { color,
return new JSONWorker(ctx, createData); range
} );
return Promise.resolve(colorPresentations);
}
async getFoldingRanges(
uri: string,
context?: { rangeLimit?: number }
): Promise<jsonService.FoldingRange[]> {
let document = this._getTextDocument(uri);
let ranges = this._languageService.getFoldingRanges(document, context);
return Promise.resolve(ranges);
}
async getSelectionRanges(
uri: string,
positions: jsonService.Position[]
): Promise<jsonService.SelectionRange[]> {
let document = this._getTextDocument(uri);
let jsonDocument = this._languageService.parseJSONDocument(document);
let ranges = this._languageService.getSelectionRanges(
document,
positions,
jsonDocument
);
return Promise.resolve(ranges);
}
private _getTextDocument(uri: string): jsonService.TextDocument {
let models = this._ctx.getMirrorModels();
for (let model of models) {
if (model.uri.toString() === uri) {
return jsonService.TextDocument.create(
uri,
this._languageId,
model.version,
model.getValue()
);
}
}
return null;
}
}
export interface ICreateData {
languageId: string;
languageSettings: jsonService.LanguageSettings;
enableSchemaRequest: boolean;
}
export function create(
ctx: worker.IWorkerContext,
createData: ICreateData
): JSONWorker {
return new JSONWorker(ctx, createData);
}

File diff suppressed because it is too large Load Diff

@ -1,185 +1,199 @@
/*--------------------------------------------------------------------------------------------- /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved. * Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import * as mode from './jsonMode'; import * as mode from './jsonMode';
import { Emitter, IEvent, languages } from './fillers/monaco-editor-core' import { Emitter, IEvent, languages } from './fillers/monaco-editor-core';
// --- JSON configuration and defaults --------- // --- JSON configuration and defaults ---------
export interface DiagnosticsOptions { export interface DiagnosticsOptions {
/** /**
* If set, the validator will be enabled and perform syntax validation as well as schema based validation. * If set, the validator will be enabled and perform syntax validation as well as schema based validation.
*/ */
readonly validate?: boolean; readonly validate?: boolean;
/** /**
* If set, comments are tolerated. If set to false, syntax errors will be emitted for comments. * If set, comments are tolerated. If set to false, syntax errors will be emitted for comments.
*/ */
readonly allowComments?: boolean; readonly allowComments?: boolean;
/** /**
* A list of known schemas and/or associations of schemas to file names. * A list of known schemas and/or associations of schemas to file names.
*/ */
readonly schemas?: { readonly schemas?: {
/** /**
* The URI of the schema, which is also the identifier of the schema. * The URI of the schema, which is also the identifier of the schema.
*/ */
readonly uri: string; readonly uri: string;
/** /**
* A list of file names that are associated to the schema. The '*' wildcard can be used. For example '*.schema.json', 'package.json' * A list of file names that are associated to the schema. The '*' wildcard can be used. For example '*.schema.json', 'package.json'
*/ */
readonly fileMatch?: string[]; readonly fileMatch?: string[];
/** /**
* The schema for the given URI. * The schema for the given URI.
*/ */
readonly schema?: any; readonly schema?: any;
}[]; }[];
/** /**
* If set, the schema service would load schema content on-demand with 'fetch' if available * If set, the schema service would load schema content on-demand with 'fetch' if available
*/ */
readonly enableSchemaRequest?: boolean; readonly enableSchemaRequest?: boolean;
} }
export interface ModeConfiguration { export interface ModeConfiguration {
/** /**
* Defines whether the built-in documentFormattingEdit provider is enabled. * Defines whether the built-in documentFormattingEdit provider is enabled.
*/ */
readonly documentFormattingEdits?: boolean; readonly documentFormattingEdits?: boolean;
/** /**
* Defines whether the built-in documentRangeFormattingEdit provider is enabled. * Defines whether the built-in documentRangeFormattingEdit provider is enabled.
*/ */
readonly documentRangeFormattingEdits?: boolean; readonly documentRangeFormattingEdits?: boolean;
/** /**
* Defines whether the built-in completionItemProvider is enabled. * Defines whether the built-in completionItemProvider is enabled.
*/ */
readonly completionItems?: boolean; readonly completionItems?: boolean;
/** /**
* Defines whether the built-in hoverProvider is enabled. * Defines whether the built-in hoverProvider is enabled.
*/ */
readonly hovers?: boolean; readonly hovers?: boolean;
/** /**
* Defines whether the built-in documentSymbolProvider is enabled. * Defines whether the built-in documentSymbolProvider is enabled.
*/ */
readonly documentSymbols?: boolean; readonly documentSymbols?: boolean;
/** /**
* Defines whether the built-in tokens provider is enabled. * Defines whether the built-in tokens provider is enabled.
*/ */
readonly tokens?: boolean; readonly tokens?: boolean;
/** /**
* Defines whether the built-in color provider is enabled. * Defines whether the built-in color provider is enabled.
*/ */
readonly colors?: boolean; readonly colors?: boolean;
/** /**
* Defines whether the built-in foldingRange provider is enabled. * Defines whether the built-in foldingRange provider is enabled.
*/ */
readonly foldingRanges?: boolean; readonly foldingRanges?: boolean;
/** /**
* Defines whether the built-in diagnostic provider is enabled. * Defines whether the built-in diagnostic provider is enabled.
*/ */
readonly diagnostics?: boolean; readonly diagnostics?: boolean;
/** /**
* Defines whether the built-in selection range provider is enabled. * Defines whether the built-in selection range provider is enabled.
*/ */
readonly selectionRanges?: boolean; readonly selectionRanges?: boolean;
}
}
export interface LanguageServiceDefaults {
export interface LanguageServiceDefaults { readonly languageId: string;
readonly languageId: string; readonly onDidChange: IEvent<LanguageServiceDefaults>;
readonly onDidChange: IEvent<LanguageServiceDefaults>; readonly diagnosticsOptions: DiagnosticsOptions;
readonly diagnosticsOptions: DiagnosticsOptions; readonly modeConfiguration: ModeConfiguration;
readonly modeConfiguration: ModeConfiguration; setDiagnosticsOptions(options: DiagnosticsOptions): void;
setDiagnosticsOptions(options: DiagnosticsOptions): void; setModeConfiguration(modeConfiguration: ModeConfiguration): void;
setModeConfiguration(modeConfiguration: ModeConfiguration): void; }
}
class LanguageServiceDefaultsImpl implements LanguageServiceDefaults {
class LanguageServiceDefaultsImpl implements LanguageServiceDefaults { private _onDidChange = new Emitter<LanguageServiceDefaults>();
private _diagnosticsOptions: DiagnosticsOptions;
private _onDidChange = new Emitter<LanguageServiceDefaults>(); private _modeConfiguration: ModeConfiguration;
private _diagnosticsOptions: DiagnosticsOptions; private _languageId: string;
private _modeConfiguration: ModeConfiguration;
private _languageId: string; constructor(
languageId: string,
constructor(languageId: string, diagnosticsOptions: DiagnosticsOptions, modeConfiguration: ModeConfiguration) { diagnosticsOptions: DiagnosticsOptions,
this._languageId = languageId; modeConfiguration: ModeConfiguration
this.setDiagnosticsOptions(diagnosticsOptions); ) {
this.setModeConfiguration(modeConfiguration); this._languageId = languageId;
} this.setDiagnosticsOptions(diagnosticsOptions);
this.setModeConfiguration(modeConfiguration);
get onDidChange(): IEvent<LanguageServiceDefaults> { }
return this._onDidChange.event;
} get onDidChange(): IEvent<LanguageServiceDefaults> {
return this._onDidChange.event;
get languageId(): string { }
return this._languageId;
} get languageId(): string {
return this._languageId;
get modeConfiguration(): ModeConfiguration { }
return this._modeConfiguration;
} get modeConfiguration(): ModeConfiguration {
return this._modeConfiguration;
get diagnosticsOptions(): DiagnosticsOptions { }
return this._diagnosticsOptions;
} get diagnosticsOptions(): DiagnosticsOptions {
return this._diagnosticsOptions;
setDiagnosticsOptions(options: DiagnosticsOptions): void { }
this._diagnosticsOptions = options || Object.create(null);
this._onDidChange.fire(this); setDiagnosticsOptions(options: DiagnosticsOptions): void {
} this._diagnosticsOptions = options || Object.create(null);
this._onDidChange.fire(this);
setModeConfiguration(modeConfiguration: ModeConfiguration): void { }
this._modeConfiguration = modeConfiguration || Object.create(null);
this._onDidChange.fire(this); setModeConfiguration(modeConfiguration: ModeConfiguration): void {
}; this._modeConfiguration = modeConfiguration || Object.create(null);
} this._onDidChange.fire(this);
}
const diagnosticDefault: Required<DiagnosticsOptions> = { }
validate: true,
allowComments: true, const diagnosticDefault: Required<DiagnosticsOptions> = {
schemas: [], validate: true,
enableSchemaRequest: false allowComments: true,
}; schemas: [],
enableSchemaRequest: false
const modeConfigurationDefault: Required<ModeConfiguration> = { };
documentFormattingEdits: true,
documentRangeFormattingEdits: true, const modeConfigurationDefault: Required<ModeConfiguration> = {
completionItems: true, documentFormattingEdits: true,
hovers: true, documentRangeFormattingEdits: true,
documentSymbols: true, completionItems: true,
tokens: true, hovers: true,
colors: true, documentSymbols: true,
foldingRanges: true, tokens: true,
diagnostics: true, colors: true,
selectionRanges: true foldingRanges: true,
} diagnostics: true,
selectionRanges: true
export const jsonDefaults: LanguageServiceDefaults = new LanguageServiceDefaultsImpl('json', diagnosticDefault, modeConfigurationDefault); };
// export to the global based API export const jsonDefaults: LanguageServiceDefaults = new LanguageServiceDefaultsImpl(
(<any>languages).json = { jsonDefaults }; 'json',
diagnosticDefault,
// --- Registration to monaco editor --- modeConfigurationDefault
);
function getMode(): Promise<typeof mode> {
return import('./jsonMode'); // export to the global based API
} (<any>languages).json = { jsonDefaults };
languages.register({ // --- Registration to monaco editor ---
id: 'json',
extensions: ['.json', '.bowerrc', '.jshintrc', '.jscsrc', '.eslintrc', '.babelrc', '.har'], function getMode(): Promise<typeof mode> {
aliases: ['JSON', 'json'], return import('./jsonMode');
mimetypes: ['application/json'], }
});
languages.register({
languages.onLanguage('json', () => { id: 'json',
getMode().then(mode => mode.setupMode(jsonDefaults)); extensions: [
}); '.json',
'.bowerrc',
'.jshintrc',
'.jscsrc',
'.eslintrc',
'.babelrc',
'.har'
],
aliases: ['JSON', 'json'],
mimetypes: ['application/json']
});
languages.onLanguage('json', () => {
getMode().then((mode) => mode.setupMode(jsonDefaults));
});

@ -4,13 +4,22 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import * as json from 'jsonc-parser'; import * as json from 'jsonc-parser';
import { languages } from './fillers/monaco-editor-core' import { languages } from './fillers/monaco-editor-core';
export function createTokenizationSupport(supportComments: boolean): languages.TokensProvider { export function createTokenizationSupport(
return { supportComments: boolean
getInitialState: () => new JSONState(null, null, false), ): languages.TokensProvider {
tokenize: (line, state, offsetDelta?, stopAtOffset?) => tokenize(supportComments, line, <JSONState>state, offsetDelta, stopAtOffset) return {
}; getInitialState: () => new JSONState(null, null, false),
tokenize: (line, state, offsetDelta?, stopAtOffset?) =>
tokenize(
supportComments,
line,
<JSONState>state,
offsetDelta,
stopAtOffset
)
};
} }
export const TOKEN_DELIM_OBJECT = 'delimiter.bracket.json'; export const TOKEN_DELIM_OBJECT = 'delimiter.bracket.json';
@ -26,155 +35,170 @@ export const TOKEN_COMMENT_BLOCK = 'comment.block.json';
export const TOKEN_COMMENT_LINE = 'comment.line.json'; export const TOKEN_COMMENT_LINE = 'comment.line.json';
class JSONState implements languages.IState { class JSONState implements languages.IState {
private _state: languages.IState;
private _state: languages.IState;
public scanError: json.ScanError;
public scanError: json.ScanError; public lastWasColon: boolean;
public lastWasColon: boolean;
constructor(
constructor(state: languages.IState, scanError: json.ScanError, lastWasColon: boolean) { state: languages.IState,
this._state = state; scanError: json.ScanError,
this.scanError = scanError; lastWasColon: boolean
this.lastWasColon = lastWasColon; ) {
} this._state = state;
this.scanError = scanError;
public clone(): JSONState { this.lastWasColon = lastWasColon;
return new JSONState(this._state, this.scanError, this.lastWasColon); }
}
public clone(): JSONState {
public equals(other: languages.IState): boolean { return new JSONState(this._state, this.scanError, this.lastWasColon);
if (other === this) { }
return true;
} public equals(other: languages.IState): boolean {
if (!other || !(other instanceof JSONState)) { if (other === this) {
return false; return true;
} }
return this.scanError === (<JSONState>other).scanError && if (!other || !(other instanceof JSONState)) {
this.lastWasColon === (<JSONState>other).lastWasColon; return false;
} }
return (
public getStateData(): languages.IState { this.scanError === (<JSONState>other).scanError &&
return this._state; this.lastWasColon === (<JSONState>other).lastWasColon
} );
}
public setStateData(state: languages.IState): void {
this._state = state; public getStateData(): languages.IState {
} return this._state;
}
public setStateData(state: languages.IState): void {
this._state = state;
}
} }
function tokenize(comments: boolean, line: string, state: JSONState, offsetDelta: number = 0, stopAtOffset?: number): languages.ILineTokens { function tokenize(
comments: boolean,
// handle multiline strings and block comments line: string,
var numberOfInsertedCharacters = 0, state: JSONState,
adjustOffset = false; offsetDelta: number = 0,
stopAtOffset?: number
switch (state.scanError) { ): languages.ILineTokens {
case json.ScanError.UnexpectedEndOfString: // handle multiline strings and block comments
line = '"' + line; var numberOfInsertedCharacters = 0,
numberOfInsertedCharacters = 1; adjustOffset = false;
break;
case json.ScanError.UnexpectedEndOfComment: switch (state.scanError) {
line = '/*' + line; case json.ScanError.UnexpectedEndOfString:
numberOfInsertedCharacters = 2; line = '"' + line;
break; numberOfInsertedCharacters = 1;
} break;
case json.ScanError.UnexpectedEndOfComment:
var scanner = json.createScanner(line), line = '/*' + line;
kind: json.SyntaxKind, numberOfInsertedCharacters = 2;
ret: languages.ILineTokens, break;
lastWasColon = state.lastWasColon; }
ret = { var scanner = json.createScanner(line),
tokens: <languages.IToken[]>[], kind: json.SyntaxKind,
endState: state.clone() ret: languages.ILineTokens,
}; lastWasColon = state.lastWasColon;
while (true) { ret = {
tokens: <languages.IToken[]>[],
var offset = offsetDelta + scanner.getPosition(), endState: state.clone()
type = ''; };
kind = scanner.scan(); while (true) {
if (kind === json.SyntaxKind.EOF) { var offset = offsetDelta + scanner.getPosition(),
break; type = '';
}
kind = scanner.scan();
// Check that the scanner has advanced if (kind === json.SyntaxKind.EOF) {
if (offset === offsetDelta + scanner.getPosition()) { break;
throw new Error('Scanner did not advance, next 3 characters are: ' + line.substr(scanner.getPosition(), 3)); }
}
// Check that the scanner has advanced
// In case we inserted /* or " character, we need to if (offset === offsetDelta + scanner.getPosition()) {
// adjust the offset of all tokens (except the first) throw new Error(
if (adjustOffset) { 'Scanner did not advance, next 3 characters are: ' +
offset -= numberOfInsertedCharacters; line.substr(scanner.getPosition(), 3)
} );
adjustOffset = numberOfInsertedCharacters > 0; }
// In case we inserted /* or " character, we need to
// brackets and type // adjust the offset of all tokens (except the first)
switch (kind) { if (adjustOffset) {
case json.SyntaxKind.OpenBraceToken: offset -= numberOfInsertedCharacters;
type = TOKEN_DELIM_OBJECT; }
lastWasColon = false; adjustOffset = numberOfInsertedCharacters > 0;
break;
case json.SyntaxKind.CloseBraceToken: // brackets and type
type = TOKEN_DELIM_OBJECT; switch (kind) {
lastWasColon = false; case json.SyntaxKind.OpenBraceToken:
break; type = TOKEN_DELIM_OBJECT;
case json.SyntaxKind.OpenBracketToken: lastWasColon = false;
type = TOKEN_DELIM_ARRAY; break;
lastWasColon = false; case json.SyntaxKind.CloseBraceToken:
break; type = TOKEN_DELIM_OBJECT;
case json.SyntaxKind.CloseBracketToken: lastWasColon = false;
type = TOKEN_DELIM_ARRAY; break;
lastWasColon = false; case json.SyntaxKind.OpenBracketToken:
break; type = TOKEN_DELIM_ARRAY;
case json.SyntaxKind.ColonToken: lastWasColon = false;
type = TOKEN_DELIM_COLON; break;
lastWasColon = true; case json.SyntaxKind.CloseBracketToken:
break; type = TOKEN_DELIM_ARRAY;
case json.SyntaxKind.CommaToken: lastWasColon = false;
type = TOKEN_DELIM_COMMA; break;
lastWasColon = false; case json.SyntaxKind.ColonToken:
break; type = TOKEN_DELIM_COLON;
case json.SyntaxKind.TrueKeyword: lastWasColon = true;
case json.SyntaxKind.FalseKeyword: break;
type = TOKEN_VALUE_BOOLEAN; case json.SyntaxKind.CommaToken:
lastWasColon = false; type = TOKEN_DELIM_COMMA;
break; lastWasColon = false;
case json.SyntaxKind.NullKeyword: break;
type = TOKEN_VALUE_NULL; case json.SyntaxKind.TrueKeyword:
lastWasColon = false; case json.SyntaxKind.FalseKeyword:
break; type = TOKEN_VALUE_BOOLEAN;
case json.SyntaxKind.StringLiteral: lastWasColon = false;
type = lastWasColon ? TOKEN_VALUE_STRING : TOKEN_PROPERTY_NAME; break;
lastWasColon = false; case json.SyntaxKind.NullKeyword:
break; type = TOKEN_VALUE_NULL;
case json.SyntaxKind.NumericLiteral: lastWasColon = false;
type = TOKEN_VALUE_NUMBER; break;
lastWasColon = false; case json.SyntaxKind.StringLiteral:
break; type = lastWasColon ? TOKEN_VALUE_STRING : TOKEN_PROPERTY_NAME;
} lastWasColon = false;
break;
// comments, iff enabled case json.SyntaxKind.NumericLiteral:
if (comments) { type = TOKEN_VALUE_NUMBER;
switch (kind) { lastWasColon = false;
case json.SyntaxKind.LineCommentTrivia: break;
type = TOKEN_COMMENT_LINE; }
break;
case json.SyntaxKind.BlockCommentTrivia: // comments, iff enabled
type = TOKEN_COMMENT_BLOCK; if (comments) {
break; switch (kind) {
} case json.SyntaxKind.LineCommentTrivia:
} type = TOKEN_COMMENT_LINE;
break;
ret.endState = new JSONState(state.getStateData(), scanner.getTokenError(), lastWasColon); case json.SyntaxKind.BlockCommentTrivia:
ret.tokens.push({ type = TOKEN_COMMENT_BLOCK;
startIndex: offset, break;
scopes: type }
}); }
}
ret.endState = new JSONState(
return ret; state.getStateData(),
scanner.getTokenError(),
lastWasColon
);
ret.tokens.push({
startIndex: offset,
scopes: type
});
}
return ret;
} }

@ -1,16 +1,16 @@
{ {
"compilerOptions": { "compilerOptions": {
"declaration": true, "declaration": true,
"module": "esnext", "module": "esnext",
"moduleResolution": "node", "moduleResolution": "node",
"outDir": "../out/esm", "outDir": "../out/esm",
"target": "es5", "target": "es5",
"lib": [ "lib": [
"dom", "dom",
"es5", "es5",
"es2015.collection", "es2015.collection",
"es2015.promise", "es2015.promise",
"es2015.iterable" "es2015.iterable"
] ]
} }
} }

@ -1,16 +1,16 @@
{ {
"compilerOptions": { "compilerOptions": {
"module": "amd", "module": "amd",
"moduleResolution": "node", "moduleResolution": "node",
"outDir": "../out/amd", "outDir": "../out/amd",
"declaration": true, "declaration": true,
"target": "es5", "target": "es5",
"lib": [ "lib": [
"dom", "dom",
"es5", "es5",
"es2015.collection", "es2015.collection",
"es2015.promise", "es2015.promise",
"es2015.iterable" "es2015.iterable"
] ]
} }
} }

@ -1,87 +1,91 @@
/*--------------------------------------------------------------------------------------------- /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved. * Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import { LanguageServiceDefaults } from './monaco.contribution'; import { LanguageServiceDefaults } from './monaco.contribution';
import type { JSONWorker } from './jsonWorker'; import type { JSONWorker } from './jsonWorker';
import { IDisposable, Uri, editor } from './fillers/monaco-editor-core' import { IDisposable, Uri, editor } from './fillers/monaco-editor-core';
const STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min const STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min
export class WorkerManager { export class WorkerManager {
private _defaults: LanguageServiceDefaults;
private _defaults: LanguageServiceDefaults; private _idleCheckInterval: number;
private _idleCheckInterval: number; private _lastUsedTime: number;
private _lastUsedTime: number; private _configChangeListener: IDisposable;
private _configChangeListener: IDisposable;
private _worker: editor.MonacoWebWorker<JSONWorker>;
private _worker: editor.MonacoWebWorker<JSONWorker>; private _client: Promise<JSONWorker>;
private _client: Promise<JSONWorker>;
constructor(defaults: LanguageServiceDefaults) {
constructor(defaults: LanguageServiceDefaults) { this._defaults = defaults;
this._defaults = defaults; this._worker = null;
this._worker = null; this._idleCheckInterval = setInterval(() => this._checkIfIdle(), 30 * 1000);
this._idleCheckInterval = setInterval(() => this._checkIfIdle(), 30 * 1000); this._lastUsedTime = 0;
this._lastUsedTime = 0; this._configChangeListener = this._defaults.onDidChange(() =>
this._configChangeListener = this._defaults.onDidChange(() => this._stopWorker()); this._stopWorker()
} );
}
private _stopWorker(): void {
if (this._worker) { private _stopWorker(): void {
this._worker.dispose(); if (this._worker) {
this._worker = null; this._worker.dispose();
} this._worker = null;
this._client = null; }
} this._client = null;
}
dispose(): void {
clearInterval(this._idleCheckInterval); dispose(): void {
this._configChangeListener.dispose(); clearInterval(this._idleCheckInterval);
this._stopWorker(); this._configChangeListener.dispose();
} this._stopWorker();
}
private _checkIfIdle(): void {
if (!this._worker) { private _checkIfIdle(): void {
return; if (!this._worker) {
} return;
let timePassedSinceLastUsed = Date.now() - this._lastUsedTime; }
if (timePassedSinceLastUsed > STOP_WHEN_IDLE_FOR) { let timePassedSinceLastUsed = Date.now() - this._lastUsedTime;
this._stopWorker(); if (timePassedSinceLastUsed > STOP_WHEN_IDLE_FOR) {
} this._stopWorker();
} }
}
private _getClient(): Promise<JSONWorker> {
this._lastUsedTime = Date.now(); private _getClient(): Promise<JSONWorker> {
this._lastUsedTime = Date.now();
if (!this._client) {
this._worker = editor.createWebWorker<JSONWorker>({ if (!this._client) {
this._worker = editor.createWebWorker<JSONWorker>({
// module that exports the create() method and returns a `JSONWorker` instance // module that exports the create() method and returns a `JSONWorker` instance
moduleId: 'vs/language/json/jsonWorker', moduleId: 'vs/language/json/jsonWorker',
label: this._defaults.languageId, label: this._defaults.languageId,
// passed in to the create() method // passed in to the create() method
createData: { createData: {
languageSettings: this._defaults.diagnosticsOptions, languageSettings: this._defaults.diagnosticsOptions,
languageId: this._defaults.languageId, languageId: this._defaults.languageId,
enableSchemaRequest: this._defaults.diagnosticsOptions.enableSchemaRequest enableSchemaRequest: this._defaults.diagnosticsOptions
} .enableSchemaRequest
}); }
});
this._client = <Promise<JSONWorker>><any>this._worker.getProxy();
} this._client = <Promise<JSONWorker>>(<any>this._worker.getProxy());
}
return this._client;
} return this._client;
}
getLanguageServiceWorker(...resources: Uri[]): Promise<JSONWorker> {
let _client: JSONWorker; getLanguageServiceWorker(...resources: Uri[]): Promise<JSONWorker> {
return this._getClient().then((client) => { let _client: JSONWorker;
_client = client return this._getClient()
}).then(_ => { .then((client) => {
return this._worker.withSyncedResources(resources) _client = client;
}).then(_ => _client); })
} .then((_) => {
} return this._worker.withSyncedResources(resources);
})
.then((_) => _client);
}
}

@ -1,118 +1,126 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link rel="stylesheet" data-name="vs/editor/editor.main" href="../node_modules/monaco-editor-core/dev/vs/editor/editor.main.css"> <link
</head> rel="stylesheet"
<body> data-name="vs/editor/editor.main"
href="../node_modules/monaco-editor-core/dev/vs/editor/editor.main.css"
<h2>Monaco Editor JSON test page</h2> />
<div id="container" style="width:800px;height:600px;border:1px solid grey"></div> </head>
<body>
<script> <h2>Monaco Editor JSON test page</h2>
// Loading basic-languages to get the json language definition <div
var paths = { id="container"
'vs/basic-languages': '../node_modules/monaco-languages/release/dev', style="width: 800px; height: 600px; border: 1px solid grey"
'vs/language/json': '../release/dev', ></div>
'vs': '../node_modules/monaco-editor-core/dev/vs'
}; <script>
if (document.location.protocol === 'http:') { // Loading basic-languages to get the json language definition
// Add support for running local http server var paths = {
let testIndex = document.location.pathname.indexOf('/test/'); 'vs/basic-languages': '../node_modules/monaco-languages/release/dev',
if (testIndex !== -1) { 'vs/language/json': '../release/dev',
let prefix = document.location.pathname.substr(0, testIndex); vs: '../node_modules/monaco-editor-core/dev/vs'
paths['vs/language/json'] = prefix + '/release/dev'; };
} if (document.location.protocol === 'http:') {
} // Add support for running local http server
var require = { let testIndex = document.location.pathname.indexOf('/test/');
paths: paths if (testIndex !== -1) {
}; let prefix = document.location.pathname.substr(0, testIndex);
</script> paths['vs/language/json'] = prefix + '/release/dev';
<script src="../node_modules/monaco-editor-core/dev/vs/loader.js"></script> }
<script src="../node_modules/monaco-editor-core/dev/vs/editor/editor.main.nls.js"></script> }
<script src="../node_modules/monaco-editor-core/dev/vs/editor/editor.main.js"></script> var require = {
paths: paths
<script> };
require([ </script>
'vs/basic-languages/monaco.contribution', <script src="../node_modules/monaco-editor-core/dev/vs/loader.js"></script>
'vs/language/json/monaco.contribution' <script src="../node_modules/monaco-editor-core/dev/vs/editor/editor.main.nls.js"></script>
], function() { <script src="../node_modules/monaco-editor-core/dev/vs/editor/editor.main.js"></script>
var editor = monaco.editor.create(document.getElementById('container'), {
value: [ <script>
'{', require([
' "type": "team",', 'vs/basic-languages/monaco.contribution',
' "test": {', 'vs/language/json/monaco.contribution'
' "testPage": "tools/testing/run-tests.htm",', ], function () {
' "enabled": true', var editor = monaco.editor.create(
' },', document.getElementById('container'),
' "search": {', {
' "excludeFolders": [', value: [
' ".git",', '{',
' "node_modules",', ' "type": "team",',
' "tools/bin",', ' "test": {',
' "tools/counts",', ' "testPage": "tools/testing/run-tests.htm",',
' "tools/policheck",', ' "enabled": true',
' "tools/tfs_build_extensions",', ' },',
' "tools/testing/jscoverage",', ' "search": {',
' "tools/testing/qunit",', ' "excludeFolders": [',
' "tools/testing/chutzpah",', ' ".git",',
' "server.net"', ' "node_modules",',
' ]', ' "tools/bin",',
' },', ' "tools/counts",',
' "languages": {', ' "tools/policheck",',
' "vs.languages.typescript": {', ' "tools/tfs_build_extensions",',
' "validationSettings": [{', ' "tools/testing/jscoverage",',
' "scope":"/",', ' "tools/testing/qunit",',
' "noImplicitAny":true,', ' "tools/testing/chutzpah",',
' "noLib":false,', ' "server.net"',
' "extraLibs":[],', ' ]',
' "semanticValidation":true,', ' },',
' "syntaxValidation":true,', ' "languages": {',
' "codeGenTarget":"ES5",', ' "vs.languages.typescript": {',
' "moduleGenTarget":"",', ' "validationSettings": [{',
' "lint": {', ' "scope":"/",',
' "emptyBlocksWithoutComment": "warning",', ' "noImplicitAny":true,',
' "curlyBracketsMustNotBeOmitted": "warning",', ' "noLib":false,',
' "comparisonOperatorsNotStrict": "warning",', ' "extraLibs":[],',
' "missingSemicolon": "warning",', ' "semanticValidation":true,',
' "unknownTypeOfResults": "warning",', ' "syntaxValidation":true,',
' "semicolonsInsteadOfBlocks": "warning",', ' "codeGenTarget":"ES5",',
' "functionsInsideLoops": "warning",', ' "moduleGenTarget":"",',
' "functionsWithoutReturnType": "warning",', ' "lint": {',
' "tripleSlashReferenceAlike": "warning",', ' "emptyBlocksWithoutComment": "warning",',
' "unusedImports": "warning",', ' "curlyBracketsMustNotBeOmitted": "warning",',
' "unusedVariables": "warning",', ' "comparisonOperatorsNotStrict": "warning",',
' "unusedFunctions": "warning",', ' "missingSemicolon": "warning",',
' "unusedMembers": "warning"', ' "unknownTypeOfResults": "warning",',
' }', ' "semicolonsInsteadOfBlocks": "warning",',
' },', ' "functionsInsideLoops": "warning",',
' {', ' "functionsWithoutReturnType": "warning",',
' "scope":"/client",', ' "tripleSlashReferenceAlike": "warning",',
' "baseUrl":"/client",', ' "unusedImports": "warning",',
' "moduleGenTarget":"amd"', ' "unusedVariables": "warning",',
' },', ' "unusedFunctions": "warning",',
' {', ' "unusedMembers": "warning"',
' "scope":"/server",', ' }',
' "moduleGenTarget":"commonjs"', ' },',
' },', ' {',
' {', ' "scope":"/client",',
' "scope":"/build",', ' "baseUrl":"/client",',
' "moduleGenTarget":"commonjs"', ' "moduleGenTarget":"amd"',
' },', ' },',
' {', ' {',
' "scope":"/node_modules/nake",', ' "scope":"/server",',
' "moduleGenTarget":"commonjs"', ' "moduleGenTarget":"commonjs"',
' }],', ' },',
' "allowMultipleWorkers": true', ' {',
' }', ' "scope":"/build",',
' }', ' "moduleGenTarget":"commonjs"',
'}', ' },',
].join('\n'), ' {',
language: 'json' ' "scope":"/node_modules/nake",',
}); ' "moduleGenTarget":"commonjs"',
}); ' }],',
</script> ' "allowMultipleWorkers": true',
' }',
</body> ' }',
</html> '}'
].join('\n'),
language: 'json'
}
);
});
</script>
</body>
</html>

Loading…
Cancel
Save