Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 | 1x 1x 1x 1x 1x 1x 1x 100x 100x 100x 200x 102x 102x 1x 102x 102x 100x 1x 100x 100x 111x 111x 104x 100x 1x 98x 1x 1x 1133x 1133x 1133x 1133x 1104x 1x 239x 36x 239x 119x 119x 115x 115x 119x 1x 8x 8x 8x 1x 1x 2246x 1141x 1141x 1x 1x 116x 116x 116x 1x 9x 9x 8x 1x 1x 27x 8x 19x 19x 15x 4x 4x 4x 3x 3x 3x 1x 1x 1x 364x 364x 364x 364x 364x 364x 364x 364x 364x 1x 4x 16x 16x 1x 1365x 1x 4x 4x 4x 4x 23x 4x 8x 8x 46x 46x 8x 4x 8x 8x 8x 4x 1x 339x 339x 339x 1000x 1000x 339x 331x 662x 2x 2x 2x 1x 1133x 1133x 1133x 1x 228x 1x 100x 100x 100x 1x 100x 100x 100x 100x 98x 100x 1x 76x 76x 76x 76x 76x 221x 221x 76x 2x 1x 8x 8x 8x 8x 1x 36x 1x 1x 35x 34x 34x 34x 34x 34x 34x 1x 1x 1x 1x 1x 116x 116x 116x 116x 3x 3x 3x 116x 116x 300x 16x 284x 284x 277x 284x 568x 568x 284x 116x 300x 300x 300x 300x 746x 743x 116x 124x 6x 124x 124x 124x 124x 124x 1x 1x 124x 124x 116x 240x 240x 240x 240x 19530x 15624x 15624x 151x 11718x 7812x 7812x 491x 1384x 1384x 1384x 1384x 11718x 7812x 7812x 435x 435x 435x 240x 2077x 2077x 302x 302x 302x 302x 124x 124x 178x 176x 176x 1953x 1953x 1953x 240x 2210x 2210x 133x 2077x 2077x 240x 116x 1x 130x 114x 96x 12x 12x 12x 12x 12x 11x 11x 119x 2x 117x 117x 117x 100x 101x 101x 101x 101x 117x 117x 117x 1x 97x 93x 4x 4x 8x 4x 1x 1253x 1253x 2x 2x 2x 1x 1x | /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as Json from 'jsonc-parser'; import { JSONSchema, JSONSchemaMap, JSONSchemaRef } from '../jsonSchema'; import { URI } from 'vscode-uri'; import * as Strings from '../utils/strings'; import * as Parser from '../parser/jsonParser'; import { SchemaRequestService, WorkspaceContextService, PromiseConstructor, Thenable } from '../jsonLanguageTypes'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); export interface IJSONSchemaService { /** * Registers a schema file in the current workspace to be applicable to files that match the pattern */ registerExternalSchema(uri: string, filePatterns?: string[], unresolvedSchema?: JSONSchema): ISchemaHandle; /** * Clears all cached schema files */ clearExternalSchemas(): void; /** * Registers contributed schemas */ setSchemaContributions(schemaContributions: ISchemaContributions): void; /** * Looks up the appropriate schema for the given URI */ getSchemaForResource(resource: string, document?: Parser.JSONDocument): Thenable<ResolvedSchema | undefined>; /** * Returns all registered schema ids */ getRegisteredSchemaIds(filter?: (scheme: string) => boolean): string[]; } export interface SchemaAssociation { pattern: string[]; uris: string[]; } export interface ISchemaContributions { schemas?: { [id: string]: JSONSchema }; schemaAssociations?: SchemaAssociation[]; } export interface ISchemaHandle { /** * The schema id */ url: string; /** * The schema from the file, with potential $ref references */ getUnresolvedSchema(): Thenable<UnresolvedSchema>; /** * The schema from the file, with references resolved */ getResolvedSchema(): Thenable<ResolvedSchema>; } class FilePatternAssociation { private readonly uris: string[]; private readonly patternRegExps: RegExp[]; private readonly isInclude: boolean[]; constructor(pattern: string[], uris: string[]) { this.patternRegExps = []; this.isInclude = []; try { for (let p of pattern) { const include = p[0] !== '!'; if (!include) { p = p.substring(1); } this.patternRegExps.push(new RegExp(Strings.convertSimple2RegExpPattern(p) + '$')); this.isInclude.push(include); } this.uris = uris; } catch (e) { // invalid pattern this.patternRegExps.length = 0; this.isInclude.length = 0; this.uris = []; } } public matchesPattern(fileName: string): boolean { let match = false; for (let i = 0; i < this.patternRegExps.length; i++) { const regExp = this.patternRegExps[i]; if (regExp.test(fileName)) { match = this.isInclude[i]; } } return match; } public getURIs() { return this.uris; } } type SchemaDependencies = { [uri: string]: true }; class SchemaHandle implements ISchemaHandle { public url: string; public dependencies: SchemaDependencies; private resolvedSchema: Thenable<ResolvedSchema> | undefined; private unresolvedSchema: Thenable<UnresolvedSchema> | undefined; private service: JSONSchemaService; constructor(service: JSONSchemaService, url: string, unresolvedSchemaContent?: JSONSchema) { this.service = service; this.url = url; this.dependencies = {}; if (unresolvedSchemaContent) { this.unresolvedSchema = this.service.promise.resolve(new UnresolvedSchema(unresolvedSchemaContent)); } } public getUnresolvedSchema(): Thenable<UnresolvedSchema> { if (!this.unresolvedSchema) { this.unresolvedSchema = this.service.loadSchema(this.url); } return this.unresolvedSchema; } public getResolvedSchema(): Thenable<ResolvedSchema> { if (!this.resolvedSchema) { this.resolvedSchema = this.getUnresolvedSchema().then(unresolved => { return this.service.resolveSchemaContent(unresolved, this.url, this.dependencies); }); } return this.resolvedSchema; } public clearSchema() { this.resolvedSchema = undefined; this.unresolvedSchema = undefined; this.dependencies = {}; } } export class UnresolvedSchema { public schema: JSONSchema; public errors: string[]; constructor(schema: JSONSchema, errors: string[] = []) { this.schema = schema; this.errors = errors; } } export class ResolvedSchema { public schema: JSONSchema; public errors: string[]; constructor(schema: JSONSchema, Ierrors: string[] = []) { this.schema = schema; this.errors = errors; } public getSection(path: string[]): JSONSchema | undefined { const schemaRef = this.getSectionRecursive(path, this.schema); if (schemaRef) { return Parser.asSchema(schemaRef); } return undefined; } private getSectionRecursive(path: string[], schema: JSONSchemaRef): JSONSchemaRef | undefined { if (!schema || typeof schema === 'boolean' || path.length === 0) { return schema; } const next = path.shift()!; if (schema.properties && typeof schema.properties[next]) { return this.getSectionRecursive(path, schema.properties[next]); } else Iif (schema.patternProperties) { for (const pattern of Object.keys(schema.patternProperties)) { const regex = new RegExp(pattern); if (regex.test(next)) { return this.getSectionRecursive(path, schema.patternProperties[pattern]); } } } else Iif (typeof schema.additionalProperties === 'object') { return this.getSectionRecursive(path, schema.additionalProperties); } else if (next.match('[0-9]+')) { Iif (Array.isArray(schema.items)) { const index = parseInt(next, 10); if (!isNaN(index) && schema.items[index]) { return this.getSectionRecursive(path, schema.items[index]); } } else Eif (schema.items) { return this.getSectionRecursive(path, schema.items); } } return undefined; } } export class JSONSchemaService implements IJSONSchemaService { private contributionSchemas: { [id: string]: SchemaHandle }; private contributionAssociations: FilePatternAssociation[]; private schemasById: { [id: string]: SchemaHandle }; private filePatternAssociations: FilePatternAssociation[]; private registeredSchemasIds: { [id: string]: boolean }; private contextService: WorkspaceContextService | undefined; private callOnDispose: Function[]; private requestService: SchemaRequestService | undefined; private promiseConstructor: PromiseConstructor; private cachedSchemaForResource: { resource: string; resolvedSchema: Thenable<ResolvedSchema | undefined> } | undefined; constructor(requestService?: SchemaRequestService, contextService?: WorkspaceContextService, promiseConstructor?: PromiseConstructor) { this.contextService = contextService; this.requestService = requestService; this.promiseConstructor = promiseConstructor || Promise; this.callOnDispose = []; this.contributionSchemas = {}; this.contributionAssociations = []; this.schemasById = {}; this.filePatternAssociations = []; this.registeredSchemasIds = {}; } public getRegisteredSchemaIds(filter?: (scheme: string) => boolean): string[] { return Object.keys(this.registeredSchemasIds).filter(id => { const scheme = URI.parse(id).scheme; return scheme !== 'schemaservice' && (!filter || filter(scheme)); }); } public get promise() { return this.promiseConstructor; } public dispose(): void { while (this.callOnDispose.length > 0) { this.callOnDispose.pop()!(); } } public onResourceChange(uri: string): boolean { let hasChanges = false; uri = normalizeId(uri); const toWalk = [uri]; const all: (SchemaHandle | undefined)[] = Object.keys(this.schemasById).map(key => this.schemasById[key]); while (toWalk.length) { const curr = toWalk.pop()!; for (let i = 0; i < all.length; i++) { const handle = all[i]; if (handle && (handle.url === curr || handle.dependencies[curr])) { if (handle.url !== curr) { toWalk.push(handle.url); } handle.clearSchema(); all[i] = undefined; hasChanges = true; } } } return hasChanges; } public setSchemaContributions(schemaContributions: ISchemaContributions): void { Eif (schemaContributions.schemas) { const schemas = schemaContributions.schemas; for (const id in schemas) { const normalizedId = normalizeId(id); this.contributionSchemas[normalizedId] = this.addSchemaHandle(normalizedId, schemas[id]); } } if (Array.isArray(schemaContributions.schemaAssociations)) { const schemaAssociations = schemaContributions.schemaAssociations; for (let schemaAssociation of schemaAssociations) { const uris = schemaAssociation.uris.map(normalizeId); const association = this.addFilePatternAssociation(schemaAssociation.pattern, uris); this.contributionAssociations.push(association); } } } private addSchemaHandle(id: string, unresolvedSchemaContent?: JSONSchema): SchemaHandle { const schemaHandle = new SchemaHandle(this, id, unresolvedSchemaContent); this.schemasById[id] = schemaHandle; return schemaHandle; } private getOrAddSchemaHandle(id: string, unresolvedSchemaContent?: JSONSchema): SchemaHandle { return this.schemasById[id] || this.addSchemaHandle(id, unresolvedSchemaContent); } private addFilePatternAssociation(pattern: string[], uris: string[]): FilePatternAssociation { const fpa = new FilePatternAssociation(pattern, uris); this.filePatternAssociations.push(fpa); return fpa; } public registerExternalSchema(uri: string, filePatterns?: string[], unresolvedSchemaContent?: JSONSchema): ISchemaHandle { const id = normalizeId(uri); this.registeredSchemasIds[id] = true; this.cachedSchemaForResource = undefined; if (filePatterns) { this.addFilePatternAssociation(filePatterns, [uri]); } return unresolvedSchemaContent ? this.addSchemaHandle(id, unresolvedSchemaContent) : this.getOrAddSchemaHandle(id); } public clearExternalSchemas(): void { this.schemasById = {}; this.filePatternAssociations = []; this.registeredSchemasIds = {}; this.cachedSchemaForResource = undefined; for (const id in this.contributionSchemas) { this.schemasById[id] = this.contributionSchemas[id]; this.registeredSchemasIds[id] = true; } for (const contributionAssociation of this.contributionAssociations) { this.filePatternAssociations.push(contributionAssociation); } } public getResolvedSchema(schemaId: string): Thenable<ResolvedSchema | undefined> { const id = normalizeId(schemaId); const schemaHandle = this.schemasById[id]; Eif (schemaHandle) { return schemaHandle.getResolvedSchema(); } return this.promise.resolve(undefined); } public loadSchema(url: string): Thenable<UnresolvedSchema> { if (!this.requestService) { const errorMessage = localize('json.schema.norequestservice', 'Unable to load schema from \'{0}\'. No schema request service available', toDisplayString(url)); return this.promise.resolve(new UnresolvedSchema(<JSONSchema>{}, [errorMessage])); } return this.requestService(url).then( content => { Iif (!content) { const errorMessage = localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': No content.', toDisplayString(url)); return new UnresolvedSchema(<JSONSchema>{}, [errorMessage]); } let schemaContent: JSONSchema = {}; const jsonErrors: Json.ParseError[] = []; schemaContent = Json.parse(content, jsonErrors); const errors = jsonErrors.length ? [localize('json.schema.invalidFormat', 'Unable to parse content from \'{0}\': Parse error at offset {1}.', toDisplayString(url), jsonErrors[0].offset)] : []; return new UnresolvedSchema(schemaContent, errors); }, (error: any) => { let errorMessage = error.toString() as string; const errorSplit = error.toString().split('Error: '); Iif (errorSplit.length > 1) { // more concise error message, URL and context are attached by caller anyways errorMessage = errorSplit[1]; } Iif (Strings.endsWith(errorMessage, '.')) { errorMessage = errorMessage.substr(0, errorMessage.length - 1); } return new UnresolvedSchema(<JSONSchema>{}, [localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': {1}.', toDisplayString(url), errorMessage)]); } ); } public resolveSchemaContent(schemaToResolve: UnresolvedSchema, schemaURL: string, dependencies: SchemaDependencies): Thenable<ResolvedSchema> { const resolveErrors: string[] = schemaToResolve.errors.slice(0); const schema = schemaToResolve.schema; if (schema.$schema) { const id = normalizeId(schema.$schema); Iif (id === 'http://json-schema.org/draft-03/schema') { return this.promise.resolve(new ResolvedSchema({}, [localize('json.schema.draft03.notsupported', "Draft-03 schemas are not supported.")])); } else Iif (id === 'https://json-schema.org/draft/2019-09/schema') { schemaToResolve.errors.push(localize('json.schema.draft201909.notsupported', "Draft 2019-09 schemas are not yet fully supported.")); } } const contextService = this.contextService; const findSection = (schema: JSONSchema, path: string | undefined): any => { if (!path) { return schema; } let current: any = schema; if (path[0] === '/') { path = path.substr(1); } path.split('/').some((part) => { current = current[part]; return !current; }); return current; }; const merge = (target: JSONSchema, sourceRoot: JSONSchema, sourceURI: string, refSegment: string | undefined): void => { const path = refSegment ? decodeURIComponent(refSegment) : undefined; const section = findSection(sourceRoot, path); Eif (section) { for (const key in section) { if (section.hasOwnProperty(key) && !target.hasOwnProperty(key)) { (<any>target)[key] = section[key]; } } } else { resolveErrors.push(localize('json.schema.invalidref', '$ref \'{0}\' in \'{1}\' can not be resolved.', path, sourceURI)); } }; const resolveExternalLink = (node: JSONSchema, uri: string, refSegment: string | undefined, parentSchemaURL: string, parentSchemaDependencies: SchemaDependencies): Thenable<any> => { if (contextService && !/^\w+:\/\/.*/.test(uri)) { uri = contextService.resolveRelativePath(uri, parentSchemaURL); } uri = normalizeId(uri); const referencedHandle = this.getOrAddSchemaHandle(uri); return referencedHandle.getUnresolvedSchema().then(unresolvedSchema => { parentSchemaDependencies[uri] = true; if (unresolvedSchema.errors.length) { const loc = refSegment ? uri + '#' + refSegment : uri; resolveErrors.push(localize('json.schema.problemloadingref', 'Problems loading reference \'{0}\': {1}', loc, unresolvedSchema.errors[0])); } merge(node, unresolvedSchema.schema, uri, refSegment); return resolveRefs(node, unresolvedSchema.schema, uri, referencedHandle.dependencies); }); }; const resolveRefs = (node: JSONSchema, parentSchema: JSONSchema, parentSchemaURL: string, parentSchemaDependencies: SchemaDependencies): Thenable<any> => { Iif (!node || typeof node !== 'object') { return Promise.resolve(null); } const toWalk: JSONSchema[] = [node]; const seen: JSONSchema[] = []; const openPromises: Thenable<any>[] = []; const collectEntries = (...entries: (JSONSchemaRef | undefined)[]) => { for (const entry of entries) { if (typeof entry === 'object') { toWalk.push(entry); } } }; const collectMapEntries = (...maps: (JSONSchemaMap | undefined)[]) => { for (const map of maps) { if (typeof map === 'object') { for (const k in map) { const key = k as keyof JSONSchemaMap; const entry = map[key]; Eif (typeof entry === 'object') { toWalk.push(entry); } } } } }; const collectArrayEntries = (...arrays: (JSONSchemaRef[] | undefined)[]) => { for (const array of arrays) { if (Array.isArray(array)) { for (const entry of array) { Eif (typeof entry === 'object') { toWalk.push(entry); } } } } }; const handleRef = (next: JSONSchema) => { const seenRefs = []; while (next.$ref) { const ref = next.$ref; const segments = ref.split('#', 2); delete next.$ref; if (segments[0].length > 0) { openPromises.push(resolveExternalLink(next, segments[0], segments[1], parentSchemaURL, parentSchemaDependencies)); return; } else { if (seenRefs.indexOf(ref) === -1) { merge(next, parentSchema, parentSchemaURL, segments[1]); // can set next.$ref again, use seenRefs to avoid circle seenRefs.push(ref); } } } collectEntries(<JSONSchema>next.items, <JSONSchema>next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else); collectMapEntries(next.definitions, next.properties, next.patternProperties, <JSONSchemaMap>next.dependencies); collectArrayEntries(next.anyOf, next.allOf, next.oneOf, <JSONSchema[]>next.items); }; while (toWalk.length) { const next = toWalk.pop()!; if (seen.indexOf(next) >= 0) { continue; } seen.push(next); handleRef(next); } return this.promise.all(openPromises); }; return resolveRefs(schema, schema, schemaURL, dependencies).then(_ => new ResolvedSchema(schema, resolveErrors)); } public getSchemaForResource(resource: string, document?: Parser.JSONDocument): Thenable<ResolvedSchema | undefined> { // first use $schema if present if (document && document.root && document.root.type === 'object') { const schemaProperties = document.root.properties.filter(p => (p.keyNode.value === '$schema') && p.valueNode && p.valueNode.type === 'string'); if (schemaProperties.length > 0) { const valueNode = schemaProperties[0].valueNode; Eif (valueNode && valueNode.type === 'string') { let schemeId = <string>Parser.getNodeValue(valueNode); Iif (schemeId && Strings.startsWith(schemeId, '.') && this.contextService) { schemeId = this.contextService.resolveRelativePath(schemeId, resource); } if (schemeId) { const id = normalizeId(schemeId); return this.getOrAddSchemaHandle(id).getResolvedSchema(); } } } } if (this.cachedSchemaForResource && this.cachedSchemaForResource.resource === resource) { return this.cachedSchemaForResource.resolvedSchema; } const seen: { [schemaId: string]: boolean } = Object.create(null); const schemas: string[] = []; for (const entry of this.filePatternAssociations) { if (entry.matchesPattern(resource)) { for (const schemaId of entry.getURIs()) { Eif (!seen[schemaId]) { schemas.push(schemaId); seen[schemaId] = true; } } } } const resolvedSchema = schemas.length > 0 ? this.createCombinedSchema(resource, schemas).getResolvedSchema() : this.promise.resolve(undefined); this.cachedSchemaForResource = { resource, resolvedSchema }; return resolvedSchema; } private createCombinedSchema(resource: string, schemaIds: string[]): ISchemaHandle { if (schemaIds.length === 1) { return this.getOrAddSchemaHandle(schemaIds[0]); } else { const combinedSchemaId = 'schemaservice://combinedSchema/' + encodeURIComponent(resource); const combinedSchema: JSONSchema = { allOf: schemaIds.map(schemaId => ({ $ref: schemaId })) }; return this.addSchemaHandle(combinedSchemaId, combinedSchema); } } } function normalizeId(id: string): string { // remove trailing '#', normalize drive capitalization try { return URI.parse(id).toString(); } catch (e) { return id; } } function toDisplayString(url: string) { try { const uri = URI.parse(url); if (uri.scheme === 'file') { return uri.fsPath; } } catch (e) { // ignore } return url; } |