How to use the vscode-json-languageservice.getLanguageService function in vscode-json-languageservice

To help you get started, we’ve selected a few vscode-json-languageservice examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Levertion / mcfunction-langserver / src / data / noncached.ts View on Github external
export async function loadNonCached(): Promise {
    const schemas: { [key: string]: string } = {
        [textComponentSchema]: JSON.stringify(
            // FIXME: parcel breaks require.resolve so we need to use plain require to get the correct path
            // tslint:disable-next-line:no-require-imports
            require("minecraft-json-schemas/java/shared/text_component")
        )
    };
    const schemaRequestService: SchemaRequestService = url =>
        schemas.hasOwnProperty(url)
            ? SynchronousPromise.resolve(schemas[url])
            : SynchronousPromise.reject(
                  `Schema at url ${url} not supported`
              );

    const jsonService = getLanguageService({
        promiseConstructor: SynchronousPromise,
        schemaRequestService
    });
    jsonService.configure({
        allowComments: false,
        schemas: [
            {
                fileMatch: ["text-component.json"],
                uri: textComponentSchema
            }
        ],
        validate: true
    });

    return {
        jsonService,
github redhat-developer / yaml-language-server / out / server / src / server.js View on Github external
schemaURL: uri
            }
        });
    }
    let headers = { 'Accept-Encoding': 'gzip, deflate' };
    return request_light_1.xhr({ url: uri, followRedirects: 5, headers }).then(response => {
        return response.responseText;
    }, (error) => {
        return Promise.reject(error.responseText || request_light_1.getErrorStatusDescription(error.status) || error.toString());
    });
};
let yamlConfigurationSettings = void 0;
let schemaAssociations = void 0;
let schemasConfigurationSettings = [];
let languageService = yamlLanguageService_1.getLanguageService(schemaRequestService, workspaceContext);
let jsonLanguageService = vscode_json_languageservice_1.getLanguageService(schemaRequestService);
connection.onDidChangeConfiguration((change) => {
    let settings = change.settings;
    yamlConfigurationSettings = settings.yaml.schemas;
    schemasConfigurationSettings = [];
    // yamlConfigurationSettings is a mapping of Kedge/Kubernetes/Schema to Glob pattern
    /*
     * {
     * 		"Kedge": ["/*"],
     * 		"http://schemaLocation": "/*"
     * }
     */
    for (let url in yamlConfigurationSettings) {
        let globPattern = yamlConfigurationSettings[url];
        let schemaObj = {
            "fileMatch": Array.isArray(globPattern) ? globPattern : [globPattern],
            "url": url
github Azure / azure-resource-manager-schemas / tools / tests.ts View on Github external
it(`running schema validation on '${templateTestFile}'`, async function() {
      this.timeout(30000);

      const service = getLanguageService({
        schemaRequestService: loadRawSchema,
        workspaceContext: { 
          resolveRelativePath: (relativePath, resource) => url.resolve(resource, relativePath)
        },
      });

      const content = await readFile(templateTestFile, { encoding: 'utf8' });
      const textDocument = TextDocument.create(templateTestFile, 'json', 0, content);
      const jsonDocument = service.parseJSONDocument(textDocument);
    
      const result = await service.doValidation(textDocument, jsonDocument);
      expect(result).to.deep.equal([]);
    });
  }
github Azure / azure-resource-manager-schemas / tools / runSchemaValidation.js View on Github external
return Promise.reject('Resource not found.');
};

let workspaceContext = {
	resolveRelativePath: (relativePath, resource) => {
		return url.resolve(resource, relativePath);
	}
};

let parameters = {
	schemaRequestService: requestServiceMock,
	workspaceContext: workspaceContext
};

let service = SchemaService.getLanguageService(parameters);
let templateFolder = './templateFiles';

let validateTemplateWithSchema = function (file) {
	let filePath = path.join(__dirname, templateFolder, file);
	let content = fs.readFileSync(filePath, 'utf8');

	let textDocument = Types.TextDocument.create(filePath, 'json', 0, content);
	let jsonDocument = service.parseJSONDocument(textDocument);

	return service.doValidation(textDocument, jsonDocument);
};

describe('validate template files with schema - ', () => {
	let files = fs.readdirSync(templateFolder);

	forEach(files).it("running schema validation on '%s'", function (file, done) {
github microsoft / monaco-json / src / jsonWorker.ts View on Github external
constructor(ctx: IWorkerContext, createData: ICreateData) {
		this._ctx = ctx;
		this._languageSettings = createData.languageSettings;
		this._languageId = createData.languageId;
		this._languageService = jsonService.getLanguageService({ promiseConstructor: PromiseAdapter });
		this._languageService.configure(this._languageSettings);
	}
github TypeFox / monaco-languageclient / examples / browser / src / client.ts View on Github external
}

function resolveSchema(url: string): Promise {
    const promise = new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.onload = () => resolve(xhr.responseText);
        xhr.onerror = () => reject(xhr.statusText);
        xhr.open("GET", url, true);
        xhr.send();
    });
    return promise;
}

const m2p = new MonacoToProtocolConverter();
const p2m = new ProtocolToMonacoConverter();
const jsonService = getLanguageService({
    schemaRequestService: resolveSchema
});
const pendingValidationRequests = new Map();

monaco.languages.registerCompletionItemProvider(LANGUAGE_ID, {
    provideCompletionItems(model, position, context, token): monaco.Thenable {
        const document = createDocument(model);
        const wordUntil = model.getWordUntilPosition(position);
        const defaultRange = new monaco.Range(position.lineNumber, wordUntil.startColumn, position.lineNumber, wordUntil.endColumn);
        const jsonDocument = jsonService.parseJSONDocument(document);
        return jsonService.doComplete(document, m2p.asPosition(position.lineNumber, position.column), jsonDocument).then((list) => {
            return p2m.asCompletionResult(list, defaultRange);
        });
    },

    resolveCompletionItem(model, position, item, token): monaco.languages.CompletionItem | monaco.Thenable {
github azeemba / eslint-plugin-json / src / index.js View on Github external
const _ = require('lodash/fp');
const jsonService = require('vscode-json-languageservice');

const jsonServiceHandle = jsonService.getLanguageService({});

const ErrorCodes = {
    Undefined: 0,
    EnumValueMismatch: 1,
    UnexpectedEndOfComment: 0x101,
    UnexpectedEndOfString: 0x102,
    UnexpectedEndOfNumber: 0x103,
    InvalidUnicode: 0x104,
    InvalidEscapeCharacter: 0x105,
    InvalidCharacter: 0x106,
    PropertyExpected: 0x201,
    CommaExpected: 0x202,
    ColonExpected: 0x203,
    ValueExpected: 0x204,
    CommaOrCloseBacketExpected: 0x205,
    CommaOrCloseBraceExpected: 0x206,
github microsoft / vscode-cosmosdb / src / mongo / services / languageService.ts View on Github external
this.db = account.db(connectionParams.databaseName);
					this.schemaService.registerSchemas(this.db)
						.then(schemas => {
							this.configureSchemas(schemas);
						});
				});
		});

		connection.onRequest('disconnect', () => {
			this.db = null;
			for (const schema of this.schemas) {
				this.jsonLanguageService.resetSchema(schema.uri);
			}
		});

		this.jsonLanguageService = getLanguageService({
			schemaRequestService: uri => this.schemaService.resolveSchema(uri),
			contributions: []
		});

		this.mongoDocumentsManager = new MongoScriptDocumentManager(this.schemaService, this.jsonLanguageService);
	}