/
documentInventory.ts
218 lines (181 loc) · 7.68 KB
/
documentInventory.ts
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
import { extractSourceFromRef, isLocalRef } from '@stoplight/json';
import { extname, resolve } from '@stoplight/path';
import { Dictionary, IParserResult, JsonPath } from '@stoplight/types';
import { isObjectLike } from 'lodash';
import { Document, IDocument } from './document';
import { Resolver, ResolveResult } from '@stoplight/spectral-ref-resolver';
import { formatParserDiagnostics, formatResolverErrors } from './errorMessages';
import * as Parsers from '@stoplight/spectral-parsers';
import { IRuleResult } from './types';
import { getClosestJsonPath, isAbsoluteRef, traverseObjUntilRef } from '@stoplight/spectral-runtime';
import { Format } from './ruleset/format';
export type DocumentInventoryItem = {
document: IDocument;
path: JsonPath;
missingPropertyPath: JsonPath;
};
export interface IDocumentInventory {
readonly graph: ResolveResult['graph'] | null;
readonly referencedDocuments: Dictionary<IDocument>;
findAssociatedItemForPath(path: JsonPath, resolved: boolean): DocumentInventoryItem | null;
}
export class DocumentInventory implements IDocumentInventory {
private static readonly _cachedRemoteDocuments = new WeakMap<Resolver['uriCache'], Dictionary<IDocument>>();
public graph: ResolveResult['graph'] | null;
public resolved: unknown;
public errors: IRuleResult[] | null;
public diagnostics: IRuleResult[] = [];
public readonly referencedDocuments: Dictionary<IDocument>;
public get source(): string | null {
return this.document.source;
}
public get unresolved(): unknown {
return this.document.data;
}
public get formats(): Set<Format> | null {
return this.document.formats ?? null;
}
constructor(public readonly document: IDocument, protected resolver: Resolver) {
this.graph = null;
this.errors = null;
const cacheKey = resolver.uriCache;
const cachedDocuments = DocumentInventory._cachedRemoteDocuments.get(cacheKey);
if (cachedDocuments !== void 0) {
this.referencedDocuments = cachedDocuments;
} else {
this.referencedDocuments = {};
DocumentInventory._cachedRemoteDocuments.set(cacheKey, this.referencedDocuments);
}
}
public async resolve(): Promise<void> {
if (!isObjectLike(this.document.data)) {
this.graph = null;
this.resolved = this.document.data;
this.errors = null;
return;
}
const resolveResult = await this.resolver.resolve(this.document.data, {
...(this.document.source !== null ? { baseUri: this.document.source } : null),
parseResolveResult: this.parseResolveResult,
});
this.graph = resolveResult.graph;
this.resolved = resolveResult.result;
this.errors = formatResolverErrors(this.document, resolveResult.errors);
}
public findAssociatedItemForPath(path: JsonPath, resolved: boolean): DocumentInventoryItem | null {
if (!resolved) {
const newPath: JsonPath = getClosestJsonPath(this.unresolved, path);
const item: DocumentInventoryItem = {
document: this.document,
path: newPath,
missingPropertyPath: path,
};
return item;
}
try {
const newPath: JsonPath = getClosestJsonPath(this.resolved, path);
const $ref = traverseObjUntilRef(this.unresolved, newPath);
if ($ref === null) {
const item: DocumentInventoryItem = {
document: this.document,
path: getClosestJsonPath(this.unresolved, path),
missingPropertyPath: path,
};
return item;
}
const missingPropertyPath =
newPath.length === 0 ? [] : path.slice(path.lastIndexOf(newPath[newPath.length - 1]) + 1);
let { source } = this;
if (source === null || this.graph === null) {
return null;
}
let refMap = this.graph.getNodeData(source).refMap;
let resolvedDoc = this.document;
// Add '#' on the beginning of "path" to simplify the logic below.
const adjustedPath: JsonPath = [...'#', ...path];
// Walk through the segments of 'path' one at a time, looking for
// json path locations containing a $ref.
let refMapKey = '';
for (const segment of adjustedPath) {
if (refMapKey.length) {
refMapKey = refMapKey.concat('/');
}
refMapKey = refMapKey.concat(segment.toString().replace(/\//g, '~1'));
// If our current refMapKey value is in fact a key in refMap,
// then we'll "reverse-resolve" it by replacing refMapKey with
// the actual value of that key within refMap.
// It's possible that we have a "ref to a ref", so we'll do this
// "reverse-resolve" step in a while loop.
while (refMapKey in refMap) {
const newRef = refMap[refMapKey];
if (isLocalRef(newRef)) {
refMapKey = newRef;
} else {
const extractedSource = extractSourceFromRef(newRef);
if (extractedSource === null) {
const item: DocumentInventoryItem = {
document: resolvedDoc,
path: getClosestJsonPath(resolvedDoc.data, path),
missingPropertyPath: path,
};
return item;
}
// Update 'source' to reflect the filename within the external ref.
source = isAbsoluteRef(extractedSource) ? extractedSource : resolve(source, '..', extractedSource);
// Update "resolvedDoc" to reflect the new "source" value and make sure we found an actual document.
const newResolvedDoc = source === this.document.source ? this.document : this.referencedDocuments[source];
if (newResolvedDoc === null || newResolvedDoc === undefined) {
const item: DocumentInventoryItem = {
document: resolvedDoc,
path: getClosestJsonPath(resolvedDoc.data, path),
missingPropertyPath: path,
};
return item;
}
resolvedDoc = newResolvedDoc;
// Update "refMap" to reflect the new "source" value.
refMap = this.graph.getNodeData(source).refMap;
refMapKey = newRef.indexOf('#') >= 0 ? newRef.slice(newRef.indexOf('#')) : '#';
}
}
}
const closestPath = getClosestJsonPath(resolvedDoc.data, this.convertRefMapKeyToPath(refMapKey));
const item: DocumentInventoryItem = {
document: resolvedDoc,
path: closestPath,
missingPropertyPath: [...closestPath, ...missingPropertyPath],
};
return item;
} catch (e) {
// console.warn(`Caught exception! e=${e}`);
return null;
}
}
protected convertRefMapKeyToPath(refPath: string): JsonPath {
const jsonPath: JsonPath = [];
if (refPath.startsWith('#/')) {
refPath = refPath.slice(2);
}
const pathSegments: string[] = refPath.split('/');
for (const pathSegment of pathSegments) {
jsonPath.push(pathSegment.replace('~1', '/'));
}
return jsonPath;
}
protected parseResolveResult: Resolver['parseResolveResult'] = resolveOpts => {
const source = resolveOpts.targetAuthority.href().replace(/\/$/, '');
const ext = extname(source);
const content = String(resolveOpts.result);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const parser: Parsers.IParser<IParserResult<unknown, any, any, any>> =
ext === '.json' ? Parsers.Json : Parsers.Yaml;
const document = new Document(content, parser, source);
resolveOpts.result = document.data;
if (document.diagnostics.length > 0) {
this.diagnostics.push(...formatParserDiagnostics(document.diagnostics, document.source));
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.referencedDocuments[source] = document;
return Promise.resolve(resolveOpts);
};
}