-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathdereference-document.ts
More file actions
526 lines (451 loc) · 15.8 KB
/
dereference-document.ts
File metadata and controls
526 lines (451 loc) · 15.8 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
import Dereferencer from "@json-schema-tools/dereferencer";
import getMetaSchemaForVersion from "./get-meta-schema-for-version";
import {
OpenrpcDocument as OpenRPC,
ReferenceObject,
ExamplePairingObject,
JSONSchema,
SchemaComponents,
ContentDescriptorComponents,
ContentDescriptorObject,
OpenrpcDocument,
MethodObject,
MethodOrReference,
} from "./types";
import referenceResolver from "@json-schema-tools/reference-resolver";
import safeStringify from "fast-safe-stringify";
export type ReferenceResolver = typeof referenceResolver;
/**
* Provides an error interface for OpenRPC Document dereferencing problems
*
* @category Errors
*
*/
export class OpenRPCDocumentDereferencingError implements Error {
public name = "OpenRPCDocumentDereferencingError";
public message: string;
/**
* @param e The error that originated from jsonSchemaRefParser
*/
constructor(e: string) {
this.message = `The json schema provided cannot be dereferenced. Received Error: \n ${e}`;
}
}
const derefItem = async (item: ReferenceObject, doc: OpenRPC, resolver: ReferenceResolver) => {
const { $ref } = item;
if ($ref === undefined) {
return item;
}
try {
// returns resolved value of the reference
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (await resolver.resolve($ref, doc)) as any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (err: any) {
throw new OpenRPCDocumentDereferencingError(
[
`unable to eval pointer against OpenRPC Document.`,
`error type: ${err.name}`,
`instance: ${err.instance}`,
`token: ${err.token}`,
`pointer: ${$ref}`,
`reference object: ${safeStringify(item)}`,
].join("\n")
);
}
};
const derefItems = async (items: ReferenceObject[], doc: OpenRPC, resolver: ReferenceResolver) => {
const dereffed = [];
for (const i of items) {
dereffed.push(await derefItem(i, doc, resolver));
}
return dereffed;
};
const matchDerefItems = async (
items: ReferenceObject[] | ReferenceObject,
doc: OpenRPC,
resolver: ReferenceResolver
) => {
if (Array.isArray(items)) {
return derefItems(items, doc, resolver);
}
return derefItem(items, doc, resolver);
};
const handleSchemaWithSchemaComponents = async (
s: JSONSchema,
schemaComponents: SchemaComponents | undefined
) => {
if (s === true || s === false) {
return Promise.resolve(s);
}
if (schemaComponents !== undefined) {
s.components = { schemas: schemaComponents };
}
const dereffer = new Dereferencer(s);
try {
const dereffed = await dereffer.resolve();
if (dereffed !== true && dereffed !== false) {
delete dereffed.components;
delete s.components;
}
return dereffed;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
throw new OpenRPCDocumentDereferencingError(
[
"Unable to parse reference inside of JSONSchema",
s.title ? `Schema Title: ${s.title}` : "",
`error message: ${e.message}`,
`schema in question: ${safeStringify(s)}`,
].join("\n")
);
}
};
const handleSchemaComponents = async (doc: OpenrpcDocument): Promise<OpenrpcDocument> => {
if (doc.components === undefined) {
return Promise.resolve(doc);
}
if (doc.components.schemas === undefined) {
return Promise.resolve(doc);
}
const schemas = doc.components.schemas as SchemaComponents;
const schemaKeys = Object.keys(schemas);
for (const k of schemaKeys) {
schemas[k] = await handleSchemaWithSchemaComponents(schemas[k], schemas);
}
return doc;
};
const handleSchemasInsideContentDescriptorComponents = async (
doc: OpenrpcDocument
): Promise<OpenrpcDocument> => {
if (doc.components === undefined) {
return Promise.resolve(doc);
}
if (doc.components.contentDescriptors === undefined) {
return Promise.resolve(doc);
}
const cds = doc.components.contentDescriptors as ContentDescriptorComponents;
const cdsKeys = Object.keys(cds);
let componentSchemas: SchemaComponents = {};
if (doc.components.schemas) {
componentSchemas = doc.components.schemas as SchemaComponents;
}
for (const cdK of cdsKeys) {
cds[cdK].schema = await handleSchemaWithSchemaComponents(cds[cdK].schema, componentSchemas);
}
return doc;
};
type DefinitionsMap = { [key: string]: string[] };
// remap the definitions map to remove the definitions. prefix and replace it with the parent object type
const remap = (definitionsMap: DefinitionsMap): DefinitionsMap => {
const remappedDefinitions: DefinitionsMap = {};
const graph = new Map<string, Set<string>>();
const resolved = new Set<string>();
// Build dependency graph
for (const [key, paths] of Object.entries(definitionsMap)) {
graph.set(key, new Set());
for (const path of paths) {
const parts = path.split(".");
if (parts.length === 1) {
graph.get(key)?.add(path);
} else if (path.startsWith("definitions.")) {
parts.shift(); // Remove 'definitions'
const parentType = parts[0];
if (parentType && parentType !== key) {
graph.get(key)?.add(parentType);
}
}
}
}
// Helper to resolve a definition and its dependencies
const resolveDef = (key: string) => {
if (resolved.has(key)) return;
// Resolve dependencies first
graph.get(key)?.forEach((dep) => resolveDef(dep));
if (!definitionsMap[key]) {
return key;
}
const accumulatedPaths: string[] = [];
definitionsMap[key].forEach((path) => {
if (!path.startsWith("definitions.")) {
accumulatedPaths.push(path);
return;
}
const parts = path.split(".");
parts.shift(); // Remove 'definitions'
const parentType = parts.shift();
const remainingPath = parts.join(".");
if (!parentType || !remappedDefinitions[parentType]) {
accumulatedPaths.push(remainingPath);
return;
}
remappedDefinitions[parentType].forEach((basePath: string) => {
const newPath = basePath ? `${basePath}.${remainingPath}` : remainingPath;
accumulatedPaths.push(newPath);
});
});
remappedDefinitions[key] = accumulatedPaths;
resolved.add(key);
};
// Resolve all definitions
Object.keys(definitionsMap).forEach(resolveDef);
return remappedDefinitions;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function createDefinitionsMap(schema: any, path = ""): DefinitionsMap {
const definitionsMap: DefinitionsMap = {};
const simplifyPath = (path: string): string => {
// Remove .items, .patternProperties, and anything after them
return path.split(/\.(items|patternProperties)/)[0];
};
const addToMap = (definitionName: string, currentPath: string) => {
if (definitionName && definitionName !== "referenceObject") {
if (!definitionsMap[definitionName]) {
definitionsMap[definitionName] = [];
}
const simplifiedPath = simplifyPath(currentPath);
if (simplifiedPath && !definitionsMap[definitionName].includes(simplifiedPath)) {
definitionsMap[definitionName].push(simplifiedPath);
}
}
};
// Handle object properties recursively
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const traverseObject = (obj: any, currentPath: string) => {
if (!obj || typeof obj !== "object") return;
// Handle direct $ref
if ("$ref" in obj) {
const definitionName = obj["$ref"].split("/").pop();
addToMap(definitionName, currentPath);
}
// Handle arrays with items
if ("items" in obj) {
// Direct $ref in items
if (obj.items.$ref) {
const definitionName = obj.items.$ref.split("/").pop();
addToMap(definitionName, `${currentPath}.items`);
}
// oneOf in items
if (obj.items.oneOf) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
obj.items.oneOf.forEach((item: any) => {
if (item.$ref) {
const definitionName = item.$ref.split("/").pop();
addToMap(definitionName, `${currentPath}.items`);
}
});
}
}
// Handle properties
if ("properties" in obj) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Object.entries(obj.properties).forEach(([key, value]: [string, any]) => {
const newPath = currentPath ? `${currentPath}.${key}` : key;
traverseObject(value, newPath);
});
}
// Handle oneOf at current level
if ("oneOf" in obj) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
obj.oneOf.forEach((item: any) => {
if (item.$ref) {
const definitionName = item.$ref.split("/").pop();
addToMap(definitionName, currentPath);
}
traverseObject(item, currentPath);
});
}
// Recursively traverse all other properties
Object.entries(obj).forEach(([key, value]) => {
if (
value &&
typeof value === "object" &&
key !== "properties" &&
key !== "items" &&
key !== "oneOf"
) {
const newPath = currentPath ? `${currentPath}.${key}` : key;
traverseObject(value, newPath);
}
});
};
traverseObject(schema, path);
return remap(definitionsMap);
}
function resolveDefinition(definitionsMap: DefinitionsMap, definitionKey: string): string[] {
return definitionsMap[definitionKey] || [];
}
interface DocResult {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
items: any[]; // Single array of all matching objects
}
// Traverses an object based on a dot-separated path and returns all matching objects at that path
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getDoc = (docName: string, derefDoc: any): DocResult => {
const docNames = docName.split(".");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const traverseObject = (obj: any, pathParts: string[]): any[] => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const results: any[] = [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const traverse = (current: any, depth: number) => {
if (!current) return;
// If we've reached our target depth, collect this object
if (depth === pathParts.length) {
results.push(current);
return;
}
const part = pathParts[depth];
const next = current[part];
// Handle both arrays and objects
if (Array.isArray(next)) {
next.forEach((item) => traverse(item, depth + 1));
} else if (next && typeof next === "object") {
traverse(next, depth + 1);
}
};
traverse(obj, 0);
return results;
};
return { items: traverseObject(derefDoc, docNames) };
};
/* eslint-disable @typescript-eslint/no-explicit-any */
const handleExtension = async (
extensionOrRef: any,
doc: OpenrpcDocument,
resolver: ReferenceResolver
): Promise<any> => {
if (extensionOrRef.$ref !== undefined) {
extensionOrRef = await derefItem({ $ref: extensionOrRef.$ref }, doc, resolver);
}
let componentSchemas: SchemaComponents = {};
if (doc.components && doc.components.schemas) {
componentSchemas = doc.components.schemas as SchemaComponents;
}
if (extensionOrRef.schema !== undefined) {
extensionOrRef.schema = await handleSchemaWithSchemaComponents(
extensionOrRef.schema,
componentSchemas
);
}
return extensionOrRef;
};
/* eslint-enable @typescript-eslint/no-explicit-any */
const handleMethod = async (
methodOrRef: MethodOrReference,
doc: OpenrpcDocument,
resolver: ReferenceResolver
): Promise<MethodObject> => {
let method = methodOrRef as MethodObject;
if (methodOrRef.$ref !== undefined) {
method = await derefItem({ $ref: methodOrRef.$ref }, doc, resolver);
}
if (method.tags !== undefined) {
method.tags = await derefItems(method.tags as ReferenceObject[], doc, resolver);
}
if (method.errors !== undefined) {
method.errors = await derefItems(method.errors as ReferenceObject[], doc, resolver);
}
if (method.links !== undefined) {
method.links = await derefItems(method.links as ReferenceObject[], doc, resolver);
}
if (method.examples !== undefined) {
method.examples = await derefItems(method.examples as ReferenceObject[], doc, resolver);
for (const exPairing of method.examples as ExamplePairingObject[]) {
exPairing.params = await derefItems(exPairing.params as ReferenceObject[], doc, resolver);
if (exPairing.result !== undefined) {
exPairing.result = await derefItem(exPairing.result as ReferenceObject, doc, resolver);
}
}
}
method.params = await derefItems(method.params as ReferenceObject[], doc, resolver);
if (method.result !== undefined) {
method.result = await derefItem(method.result as ReferenceObject, doc, resolver);
}
let componentSchemas: SchemaComponents = {};
if (doc.components && doc.components.schemas) {
componentSchemas = doc.components.schemas as SchemaComponents;
}
const params = method.params as ContentDescriptorObject[];
for (const p of params) {
p.schema = await handleSchemaWithSchemaComponents(p.schema, componentSchemas);
}
if (method.result !== undefined) {
const result = method.result as ContentDescriptorObject;
result.schema = await handleSchemaWithSchemaComponents(result.schema, componentSchemas);
}
return method;
};
/**
* replaces $ref's within a document and its schemas. The replaced value will be a javascript object reference to the
* real schema / open-rpc component
*
* @param schema The OpenRPC document
*
* @returns The same OpenRPC Document that was passed in, but with all $ref's dereferenced.
*
* @throws [[OpenRPCDocumentDereferencingError]]
*
* @example
* ```typescript
*
* import { OpenRPC } from "@open-rpc/meta-schema"
* import { dereferenceDocument } from "@open-rpc/schema-utils-js";
*
* try {
* const dereffedDocument = await dereferenceDocument({ ... }) as OpenRPC;
* } catch (e) {
* // handle validation errors
* }
* ```
*
*/
export default async function dereferenceDocument(
openrpcDocument: OpenRPC,
resolver: ReferenceResolver = referenceResolver
): Promise<OpenRPC> {
let derefDoc = { ...openrpcDocument };
derefDoc = await handleSchemaComponents(derefDoc);
derefDoc = await handleSchemasInsideContentDescriptorComponents(derefDoc);
const metaSchema = getMetaSchemaForVersion(openrpcDocument.openrpc);
const definitionsMap = createDefinitionsMap(metaSchema);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const extensions = [] as any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const extensionDerefs = [] as any;
if (derefDoc["x-extensions"]) {
for (const extension of derefDoc["x-extensions"]) {
const derefedExtension = await handleExtension(extension, derefDoc, resolver);
extensions.push(derefedExtension);
for (const def of derefedExtension.restricted) {
extensionDerefs.push({
extensionName: derefedExtension.name,
docNames: resolveDefinition(definitionsMap, def),
});
}
}
derefDoc["x-extensions"] = extensions;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const methods = [] as any;
for (const method of derefDoc.methods) {
methods.push(await handleMethod(method, derefDoc, resolver));
}
for (const extension of extensionDerefs) {
for (const docName of extension.docNames) {
const { items } = getDoc(docName, derefDoc);
// Process all matching items that have the extension
for (const item of items) {
if (item && item[extension.extensionName]) {
item[extension.extensionName] = await matchDerefItems(
item[extension.extensionName],
derefDoc,
resolver
);
}
}
}
}
derefDoc.methods = methods;
return derefDoc;
}