-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathjsonSchemaService.ts
More file actions
766 lines (675 loc) · 25.4 KB
/
jsonSchemaService.ts
File metadata and controls
766 lines (675 loc) · 25.4 KB
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
/*---------------------------------------------------------------------------------------------
* 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.js';
import { URI } from 'vscode-uri';
import * as Strings from '../utils/strings.js';
import { asSchema, getSchemaDraftFromId, JSONDocument, normalizeId } from '../parser/jsonParser.js';
import { SchemaRequestService, WorkspaceContextService, PromiseConstructor, MatchingSchema, TextDocument, SchemaConfiguration, SchemaDraft, ErrorCode } from '../jsonLanguageTypes.js';
import * as l10n from '@vscode/l10n';
import { createRegex } from '../utils/glob.js';
import { isObject, isString } from '../utils/objects.js';
import { DiagnosticRelatedInformation, Range } from 'vscode-languageserver-types';
export interface IJSONSchemaService {
/**
* Registers a schema file in the current workspace to be applicable to files that match the pattern
*/
registerExternalSchema(config: SchemaConfiguration): 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?: JSONDocument): PromiseLike<ResolvedSchema | undefined>;
/**
* Returns all registered schema ids
*/
getRegisteredSchemaIds(filter?: (scheme: string) => boolean): string[];
}
export interface SchemaAssociation {
pattern: string[];
uris: string[];
folderUri?: string;
}
export interface ISchemaContributions {
schemas?: { [id: string]: JSONSchema };
schemaAssociations?: SchemaAssociation[];
}
export interface ISchemaHandle {
/**
* The schema id
*/
uri: string;
/**
* The schema from the file, with potential $ref references
*/
getUnresolvedSchema(): PromiseLike<UnresolvedSchema>;
/**
* The schema from the file, with references resolved
*/
getResolvedSchema(): PromiseLike<ResolvedSchema>;
}
const BANG = '!';
const PATH_SEP = '/';
interface IGlobWrapper {
regexp: RegExp;
include: boolean;
}
class FilePatternAssociation {
private readonly globWrappers: IGlobWrapper[];
constructor(pattern: string[], private readonly folderUri: string | undefined, private readonly uris: string[]) {
this.globWrappers = [];
try {
for (let patternString of pattern) {
const include = patternString[0] !== BANG;
if (!include) {
patternString = patternString.substring(1);
}
if (patternString.length > 0) {
if (patternString[0] === PATH_SEP) {
patternString = patternString.substring(1);
}
this.globWrappers.push({
regexp: createRegex('**/' + patternString, { extended: true, globstar: true }),
include: include,
});
}
};
if (folderUri) {
folderUri = normalizeResourceForMatching(folderUri);
if (!folderUri.endsWith('/')) {
folderUri = folderUri + '/';
}
this.folderUri = folderUri;
}
} catch (e) {
this.globWrappers.length = 0;
this.uris = [];
}
}
public matchesPattern(fileName: string): boolean {
if (this.folderUri && !fileName.startsWith(this.folderUri)) {
return false;
}
let match = false;
for (const { regexp, include } of this.globWrappers) {
if (regexp.test(fileName)) {
match = include;
}
}
return match;
}
public getURIs() {
return this.uris;
}
}
type SchemaDependencies = Set<string>;
class SchemaHandle implements ISchemaHandle {
public readonly uri: string;
public readonly dependencies: SchemaDependencies;
public anchors: Map<string, JSONSchema> | undefined;
private resolvedSchema: PromiseLike<ResolvedSchema> | undefined;
private unresolvedSchema: PromiseLike<UnresolvedSchema> | undefined;
private readonly service: JSONSchemaService;
constructor(service: JSONSchemaService, uri: string, unresolvedSchemaContent?: JSONSchema) {
this.service = service;
this.uri = uri;
this.dependencies = new Set();
this.anchors = undefined;
if (unresolvedSchemaContent) {
this.unresolvedSchema = this.service.promise.resolve(new UnresolvedSchema(unresolvedSchemaContent));
}
}
public getUnresolvedSchema(): PromiseLike<UnresolvedSchema> {
if (!this.unresolvedSchema) {
this.unresolvedSchema = this.service.loadSchema(this.uri);
}
return this.unresolvedSchema;
}
public getResolvedSchema(): PromiseLike<ResolvedSchema> {
if (!this.resolvedSchema) {
this.resolvedSchema = this.getUnresolvedSchema().then(unresolved => {
return this.service.resolveSchemaContent(unresolved, this);
});
}
return this.resolvedSchema;
}
public clearSchema(): boolean {
const hasChanges = !!this.unresolvedSchema;
this.resolvedSchema = undefined;
this.unresolvedSchema = undefined;
this.dependencies.clear();
this.anchors = undefined;
return hasChanges;
}
}
export class UnresolvedSchema {
public readonly schema: JSONSchema;
public readonly errors: SchemaDiagnostic[];
constructor(schema: JSONSchema, errors: SchemaDiagnostic[] = []) {
this.schema = schema;
this.errors = errors;
}
}
export type SchemaDiagnostic = { readonly message: string; readonly code: ErrorCode; relatedInformation?: DiagnosticRelatedInformation[] }
function toDiagnostic(message: string, code: ErrorCode, relatedURL?: string): SchemaDiagnostic {
const relatedInformation: DiagnosticRelatedInformation[] | undefined = relatedURL ? [{
location: { uri: relatedURL, range: Range.create(0, 0, 0, 0) },
message
}] : undefined;
return { message, code, relatedInformation };
}
export class ResolvedSchema {
public readonly schema: JSONSchema;
public readonly errors: SchemaDiagnostic[];
public readonly warnings: SchemaDiagnostic[];
public readonly schemaDraft: SchemaDraft | undefined;
constructor(schema: JSONSchema, errors: SchemaDiagnostic[] = [], warnings: SchemaDiagnostic[] = [], schemaDraft: SchemaDraft | undefined) {
this.schema = schema;
this.errors = errors;
this.warnings = warnings;
this.schemaDraft = schemaDraft;
}
public getSection(path: string[]): JSONSchema | undefined {
const schemaRef = this.getSectionRecursive(path, this.schema);
if (schemaRef) {
return 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 if (schema.patternProperties) {
for (const pattern of Object.keys(schema.patternProperties)) {
const regex = Strings.extendedRegExp(pattern);
if (regex?.test(next)) {
return this.getSectionRecursive(path, schema.patternProperties[pattern]);
}
}
} else if (typeof schema.additionalProperties === 'object') {
return this.getSectionRecursive(path, schema.additionalProperties);
} else if (next.match('[0-9]+')) {
if (Array.isArray(schema.items)) {
const index = parseInt(next, 10);
if (!isNaN(index) && schema.items[index]) {
return this.getSectionRecursive(path, schema.items[index]);
}
} else if (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: PromiseLike<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 {
// always clear this local cache when a resource changes
this.cachedSchemaForResource = undefined;
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.uri === curr || handle.dependencies.has(curr))) {
if (handle.uri !== curr) {
toWalk.push(handle.uri);
}
if (handle.clearSchema()) {
hasChanges = true;
}
all[i] = undefined;
}
}
}
return hasChanges;
}
public setSchemaContributions(schemaContributions: ISchemaContributions): void {
if (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, schemaAssociation.folderUri, 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[], folderUri: string | undefined, uris: string[]): FilePatternAssociation {
const fpa = new FilePatternAssociation(pattern, folderUri, uris);
this.filePatternAssociations.push(fpa);
return fpa;
}
public registerExternalSchema(config: SchemaConfiguration): ISchemaHandle {
const id = normalizeId(config.uri);
this.registeredSchemasIds[id] = true;
this.cachedSchemaForResource = undefined;
if (config.fileMatch && config.fileMatch.length) {
this.addFilePatternAssociation(config.fileMatch, config.folderUri, [id]);
}
return config.schema ? this.addSchemaHandle(id, config.schema) : 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): PromiseLike<ResolvedSchema | undefined> {
const id = normalizeId(schemaId);
const schemaHandle = this.schemasById[id];
if (schemaHandle) {
return schemaHandle.getResolvedSchema();
}
return this.promise.resolve(undefined);
}
public loadSchema(url: string): PromiseLike<UnresolvedSchema> {
if (!this.requestService) {
const errorMessage = l10n.t('Unable to load schema from \'{0}\'. No schema request service available', toDisplayString(url));
return this.promise.resolve(new UnresolvedSchema(<JSONSchema>{}, [toDiagnostic(errorMessage, ErrorCode.SchemaResolveError, url)]));
}
return this.requestService(url).then(
content => {
if (!content) {
const errorMessage = l10n.t('Unable to load schema from \'{0}\': No content.', toDisplayString(url));
return new UnresolvedSchema(<JSONSchema>{}, [toDiagnostic(errorMessage, ErrorCode.SchemaResolveError, url)]);
}
const errors = [];
if (content.charCodeAt(0) === 65279) {
errors.push(toDiagnostic(l10n.t('Problem reading content from \'{0}\': UTF-8 with BOM detected, only UTF 8 is allowed.', toDisplayString(url)), ErrorCode.SchemaResolveError, url));
content = content.trimStart();
}
let schemaContent: JSONSchema = {};
const jsonErrors: Json.ParseError[] = [];
schemaContent = Json.parse(content, jsonErrors);
if (jsonErrors.length) {
errors.push(toDiagnostic(l10n.t('Unable to parse content from \'{0}\': Parse error at offset {1}.', toDisplayString(url), jsonErrors[0].offset), ErrorCode.SchemaResolveError, url));
}
return new UnresolvedSchema(schemaContent, errors);
},
(error: any) => {
let { message, code } = error;
if (typeof message !== 'string') {
let errorMessage = error.toString() as string;
const errorSplit = error.toString().split('Error: ');
if (errorSplit.length > 1) {
// more concise error message, URL and context are attached by caller anyways
errorMessage = errorSplit[1];
}
if (Strings.endsWith(errorMessage, '.')) {
errorMessage = errorMessage.substr(0, errorMessage.length - 1);
}
message = errorMessage;
}
let errorCode = ErrorCode.SchemaResolveError;
if (typeof code === 'number' && code < 0x10000) {
errorCode += code;
}
const errorMessage = l10n.t('Unable to load schema from \'{0}\': {1}.', toDisplayString(url), message);
return new UnresolvedSchema(<JSONSchema>{}, [toDiagnostic(errorMessage, errorCode, url)]);
}
);
}
public resolveSchemaContent(schemaToResolve: UnresolvedSchema, handle: SchemaHandle): PromiseLike<ResolvedSchema> {
const resolveErrors: SchemaDiagnostic[] = schemaToResolve.errors.slice(0);
const schema = schemaToResolve.schema;
const schemaDraft = schema.$schema ? getSchemaDraftFromId(schema.$schema) : undefined;
if (schemaDraft === SchemaDraft.v3) {
return this.promise.resolve(new ResolvedSchema({}, [toDiagnostic(l10n.t("Draft-03 schemas are not supported."), ErrorCode.SchemaUnsupportedFeature)], [], schemaDraft));
}
let usesUnsupportedFeatures = new Set();
const contextService = this.contextService;
const findSectionByJSONPointer = (schema: JSONSchema, path: string): any => {
path = decodeURIComponent(path);
let current: any = schema;
if (path[0] === '/') {
path = path.substring(1);
}
path.split('/').some((part) => {
part = part.replace(/~1/g, '/').replace(/~0/g, '~');
current = current[part];
return !current;
});
return current;
};
const findSchemaById = (schema: JSONSchema, handle: SchemaHandle, id: string) => {
if (!handle.anchors) {
handle.anchors = collectAnchors(schema);
}
return handle.anchors.get(id);
};
const merge = (target: JSONSchema, section: any): void => {
for (const key in section) {
if (section.hasOwnProperty(key) && key !== 'id' && key !== '$id') {
(<any>target)[key] = section[key];
}
}
};
const mergeRef = (target: JSONSchema, sourceRoot: JSONSchema, sourceHandle: SchemaHandle, refSegment: string | undefined): void => {
let section;
if (refSegment === undefined || refSegment.length === 0) {
section = sourceRoot;
} else if (refSegment.charAt(0) === '/') {
// A $ref to a JSON Pointer (i.e #/definitions/foo)
section = findSectionByJSONPointer(sourceRoot, refSegment);
} else {
// A $ref to a sub-schema with an $id (i.e #hello)
section = findSchemaById(sourceRoot, sourceHandle, refSegment);
}
if (section) {
merge(target, section);
} else {
const message = l10n.t('$ref \'{0}\' in \'{1}\' can not be resolved.', refSegment || '', sourceHandle.uri)
resolveErrors.push(toDiagnostic(message, ErrorCode.SchemaResolveError));
}
};
const resolveExternalLink = (node: JSONSchema, uri: string, refSegment: string | undefined, parentHandle: SchemaHandle): PromiseLike<any> => {
if (contextService && !/^[A-Za-z][A-Za-z0-9+\-.+]*:\/.*/.test(uri)) {
uri = contextService.resolveRelativePath(uri, parentHandle.uri);
}
uri = normalizeId(uri);
const referencedHandle = this.getOrAddSchemaHandle(uri);
return referencedHandle.getUnresolvedSchema().then(unresolvedSchema => {
parentHandle.dependencies.add(uri);
if (unresolvedSchema.errors.length) {
const error = unresolvedSchema.errors[0];
const loc = refSegment ? uri + '#' + refSegment : uri;
const errorMessage = refSegment? l10n.t('Problems loading reference \'{0}\': {1}', refSegment, error.message) : error.message;
resolveErrors.push(toDiagnostic(errorMessage, error.code, uri));
}
mergeRef(node, unresolvedSchema.schema, referencedHandle, refSegment);
return resolveRefs(node, unresolvedSchema.schema, referencedHandle);
});
};
const resolveRefs = (node: JSONSchema, parentSchema: JSONSchema, parentHandle: SchemaHandle): PromiseLike<any> => {
const openPromises: PromiseLike<any>[] = [];
this.traverseNodes(node, next => {
const seenRefs = new Set<string>();
while (next.$ref) {
const ref = next.$ref;
const segments = ref.split('#', 2);
delete next.$ref;
if (segments[0].length > 0) {
// This is a reference to an external schema
openPromises.push(resolveExternalLink(next, segments[0], segments[1], parentHandle));
return;
} else {
// This is a reference inside the current schema
if (!seenRefs.has(ref)) {
const id = segments[1];
mergeRef(next, parentSchema, parentHandle, id);
seenRefs.add(ref);
}
}
}
if (next.$recursiveRef) {
usesUnsupportedFeatures.add('$recursiveRef');
}
if (next.$dynamicRef) {
usesUnsupportedFeatures.add('$dynamicRef');
}
});
return this.promise.all(openPromises);
};
const collectAnchors = (root: JSONSchema): Map<string, JSONSchema> => {
const result = new Map<string, JSONSchema>();
this.traverseNodes(root, next => {
const id = next.$id || next.id;
const anchor = isString(id) && id.charAt(0) === '#' ? id.substring(1) : next.$anchor;
if (anchor) {
if (result.has(anchor)) {
resolveErrors.push(toDiagnostic(l10n.t('Duplicate anchor declaration: \'{0}\'', anchor), ErrorCode.SchemaResolveError));
} else {
result.set(anchor, next);
}
}
if (next.$recursiveAnchor) {
usesUnsupportedFeatures.add('$recursiveAnchor');
}
if (next.$dynamicAnchor) {
usesUnsupportedFeatures.add('$dynamicAnchor');
}
});
return result;
};
return resolveRefs(schema, schema, handle).then(_ => {
let resolveWarnings: SchemaDiagnostic[] = [];
if (usesUnsupportedFeatures.size) {
resolveWarnings.push(toDiagnostic(l10n.t('The schema uses meta-schema features ({0}) that are not yet supported by the validator.', Array.from(usesUnsupportedFeatures.keys()).join(', ')), ErrorCode.SchemaUnsupportedFeature));
}
return new ResolvedSchema(schema, resolveErrors, resolveWarnings, schemaDraft);
});
}
private traverseNodes(root: JSONSchema, handle: (node: JSONSchema) => void) {
if (!root || typeof root !== 'object') {
return Promise.resolve(null);
}
const seen = new Set<JSONSchema>();
const collectEntries = (...entries: (JSONSchemaRef | undefined)[]) => {
for (const entry of entries) {
if (isObject(entry)) {
toWalk.push(entry);
}
}
};
const collectMapEntries = (...maps: (JSONSchemaMap | undefined)[]) => {
for (const map of maps) {
if (isObject(map)) {
for (const k in map) {
const key = k as keyof JSONSchemaMap;
const entry = map[key];
if (isObject(entry)) {
toWalk.push(entry);
}
}
}
}
};
const collectArrayEntries = (...arrays: (JSONSchemaRef[] | undefined)[]) => {
for (const array of arrays) {
if (Array.isArray(array)) {
for (const entry of array) {
if (isObject(entry)) {
toWalk.push(entry);
}
}
}
}
};
const collectEntryOrArrayEntries = (items: (JSONSchemaRef[] | JSONSchemaRef | undefined)) => {
if (Array.isArray(items)) {
for (const entry of items) {
if (isObject(entry)) {
toWalk.push(entry);
}
}
} else if (isObject(items)) {
toWalk.push(items);
}
};
const toWalk: JSONSchema[] = [root];
let next = toWalk.pop();
while (next) {
if (!seen.has(next)) {
seen.add(next);
handle(next);
collectEntries(next.additionalItems, next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else, next.unevaluatedItems, next.unevaluatedProperties);
collectMapEntries(next.definitions, next.$defs, next.properties, next.patternProperties, <JSONSchemaMap>next.dependencies, next.dependentSchemas);
collectArrayEntries(next.anyOf, next.allOf, next.oneOf, next.prefixItems);
collectEntryOrArrayEntries(next.items);
}
next = toWalk.pop();
}
};
private getSchemaFromProperty(resource: string, document: JSONDocument): string | undefined {
if (document.root?.type === 'object') {
for (const p of document.root.properties) {
if (p.keyNode.value === '$schema' && p.valueNode?.type === 'string') {
let schemaId = p.valueNode.value;
if (this.contextService && !/^\w[\w\d+.-]*:/.test(schemaId)) { // has scheme
schemaId = this.contextService.resolveRelativePath(schemaId, resource);
}
return schemaId;
}
}
}
return undefined;
}
private getAssociatedSchemas(resource: string): string[] {
const seen: { [schemaId: string]: boolean } = Object.create(null);
const schemas: string[] = [];
const normalizedResource = normalizeResourceForMatching(resource);
for (const entry of this.filePatternAssociations) {
if (entry.matchesPattern(normalizedResource)) {
for (const schemaId of entry.getURIs()) {
if (!seen[schemaId]) {
schemas.push(schemaId);
seen[schemaId] = true;
}
}
}
}
return schemas;
}
public getSchemaURIsForResource(resource: string, document?: JSONDocument): string[] {
let schemeId = document && this.getSchemaFromProperty(resource, document);
if (schemeId) {
return [schemeId];
}
return this.getAssociatedSchemas(resource);
}
public getSchemaForResource(resource: string, document?: JSONDocument): PromiseLike<ResolvedSchema | undefined> {
if (document) {
// first use $schema if present
let schemeId = this.getSchemaFromProperty(resource, document);
if (schemeId) {
const id = normalizeId(schemeId);
return this.getOrAddSchemaHandle(id).getResolvedSchema();
}
}
if (this.cachedSchemaForResource && this.cachedSchemaForResource.resource === resource) {
return this.cachedSchemaForResource.resolvedSchema;
}
const schemas = this.getAssociatedSchemas(resource);
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);
}
}
public getMatchingSchemas(document: TextDocument, jsonDocument: JSONDocument, schema?: JSONSchema): PromiseLike<MatchingSchema[]> {
if (schema) {
const id = schema.id || ('schemaservice://untitled/matchingSchemas/' + idCounter++);
const handle = this.addSchemaHandle(id, schema);
return handle.getResolvedSchema().then(resolvedSchema => {
return jsonDocument.getMatchingSchemas(resolvedSchema.schema).filter(s => !s.inverted);
});
}
return this.getSchemaForResource(document.uri, jsonDocument).then(schema => {
if (schema) {
return jsonDocument.getMatchingSchemas(schema.schema).filter(s => !s.inverted);
}
return [];
});
}
}
let idCounter = 0;
function normalizeResourceForMatching(resource: string): string {
// remove queries and fragments, normalize drive capitalization
try {
return URI.parse(resource).with({ fragment: null, query: null }).toString(true);
} catch (e) {
return resource;
}
}
function toDisplayString(url: string) {
try {
const uri = URI.parse(url);
if (uri.scheme === 'file') {
return uri.fsPath;
}
} catch (e) {
// ignore
}
return url;
}