1 | import { isUndefined } from 'ramda-adjunct';
|
---|
2 | import { filter } from '@swagger-api/apidom-core';
|
---|
3 | import { isSchemaElement } from '@swagger-api/apidom-ns-openapi-3-1';
|
---|
4 | import { uriToPointer, evaluate as jsonPointerEvaluate } from '@swagger-api/apidom-json-pointer';
|
---|
5 | import * as url from "../../../../util/url.mjs";
|
---|
6 | import EvaluationJsonSchemaUriError from "../../../../errors/EvaluationJsonSchemaUriError.mjs";
|
---|
7 | import { isAnchor, uriToAnchor, evaluate as $anchorEvaluate } from "./$anchor.mjs";
|
---|
8 | import { resolveSchema$idField } from "../../../../resolve/strategies/openapi-3-1/util.mjs";
|
---|
9 | /**
|
---|
10 | * Evaluates JSON Schema $ref containing unknown URI against ApiDOM fragment.
|
---|
11 | */
|
---|
12 | export const evaluate = (uri, element) => {
|
---|
13 | const {
|
---|
14 | cache
|
---|
15 | } = evaluate;
|
---|
16 | const uriStrippedHash = url.stripHash(uri);
|
---|
17 | const isSchemaElementWith$id = e => isSchemaElement(e) && typeof e.$id !== 'undefined';
|
---|
18 |
|
---|
19 | // warm the cache
|
---|
20 | if (!cache.has(element)) {
|
---|
21 | const schemaObjectElements = filter(isSchemaElementWith$id, element);
|
---|
22 | cache.set(element, Array.from(schemaObjectElements));
|
---|
23 | }
|
---|
24 |
|
---|
25 | // search for the matching schema
|
---|
26 | const result = cache.get(element).find(e => {
|
---|
27 | const $idBaseURI = resolveSchema$idField(uriStrippedHash, e);
|
---|
28 | return $idBaseURI === uriStrippedHash;
|
---|
29 | });
|
---|
30 | if (isUndefined(result)) {
|
---|
31 | throw new EvaluationJsonSchemaUriError(`Evaluation failed on URI: "${uri}"`);
|
---|
32 | }
|
---|
33 | let fragmentEvaluate;
|
---|
34 | let selector;
|
---|
35 | if (isAnchor(uriToAnchor(uri))) {
|
---|
36 | // we're dealing with JSON Schema $anchor here
|
---|
37 | fragmentEvaluate = $anchorEvaluate;
|
---|
38 | selector = uriToAnchor(uri);
|
---|
39 | } else {
|
---|
40 | // we're assuming here that we're dealing with JSON Pointer here
|
---|
41 | fragmentEvaluate = jsonPointerEvaluate;
|
---|
42 | selector = uriToPointer(uri);
|
---|
43 | }
|
---|
44 |
|
---|
45 | // @ts-ignore
|
---|
46 | return fragmentEvaluate(selector, result);
|
---|
47 | };
|
---|
48 | evaluate.cache = new WeakMap();
|
---|
49 | export { EvaluationJsonSchemaUriError };
|
---|
50 | export { default as JsonSchemaUriError } from "../../../../errors/JsonSchemaUriError.mjs"; |
---|