@speclynx/apidom-reference 4.0.2 → 4.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/apidom-reference.browser.js +15 -15
  3. package/dist/apidom-reference.browser.min.js +1 -1
  4. package/package.json +25 -25
  5. package/src/File.cjs +50 -0
  6. package/src/File.mjs +44 -0
  7. package/src/Reference.cjs +31 -0
  8. package/src/Reference.mjs +27 -0
  9. package/src/ReferenceSet.cjs +60 -0
  10. package/src/ReferenceSet.mjs +57 -0
  11. package/src/bundle/index.cjs +61 -0
  12. package/src/bundle/index.mjs +55 -0
  13. package/src/bundle/strategies/BundleStrategy.cjs +20 -0
  14. package/src/bundle/strategies/BundleStrategy.mjs +16 -0
  15. package/src/bundle/strategies/openapi-3-1/index.cjs +35 -0
  16. package/src/bundle/strategies/openapi-3-1/index.mjs +29 -0
  17. package/src/configuration/empty.cjs +9 -0
  18. package/src/configuration/empty.mjs +1 -0
  19. package/src/configuration/saturated.cjs +88 -0
  20. package/src/configuration/saturated.mjs +80 -0
  21. package/src/dereference/index.cjs +90 -0
  22. package/src/dereference/index.mjs +83 -0
  23. package/src/dereference/strategies/DereferenceStrategy.cjs +20 -0
  24. package/src/dereference/strategies/DereferenceStrategy.mjs +16 -0
  25. package/src/dereference/strategies/apidom/index.cjs +89 -0
  26. package/src/dereference/strategies/apidom/index.mjs +83 -0
  27. package/src/dereference/strategies/apidom/selectors/element-id.cjs +47 -0
  28. package/src/dereference/strategies/apidom/selectors/element-id.mjs +41 -0
  29. package/src/dereference/strategies/apidom/visitor.cjs +266 -0
  30. package/src/dereference/strategies/apidom/visitor.mjs +259 -0
  31. package/src/dereference/strategies/arazzo-1/index.cjs +109 -0
  32. package/src/dereference/strategies/arazzo-1/index.mjs +100 -0
  33. package/src/dereference/strategies/arazzo-1/selectors/$anchor.cjs +12 -0
  34. package/src/dereference/strategies/arazzo-1/selectors/$anchor.mjs +1 -0
  35. package/src/dereference/strategies/arazzo-1/selectors/uri.cjs +8 -0
  36. package/src/dereference/strategies/arazzo-1/selectors/uri.mjs +1 -0
  37. package/src/dereference/strategies/arazzo-1/source-descriptions.cjs +248 -0
  38. package/src/dereference/strategies/arazzo-1/source-descriptions.mjs +243 -0
  39. package/src/dereference/strategies/arazzo-1/util.cjs +37 -0
  40. package/src/dereference/strategies/arazzo-1/util.mjs +29 -0
  41. package/src/dereference/strategies/arazzo-1/visitor.cjs +507 -0
  42. package/src/dereference/strategies/arazzo-1/visitor.mjs +500 -0
  43. package/src/dereference/strategies/asyncapi-2/index.cjs +94 -0
  44. package/src/dereference/strategies/asyncapi-2/index.mjs +88 -0
  45. package/src/dereference/strategies/asyncapi-2/visitor.cjs +501 -0
  46. package/src/dereference/strategies/asyncapi-2/visitor.mjs +494 -0
  47. package/src/dereference/strategies/openapi-2/index.cjs +96 -0
  48. package/src/dereference/strategies/openapi-2/index.mjs +90 -0
  49. package/src/dereference/strategies/openapi-2/visitor.cjs +629 -0
  50. package/src/dereference/strategies/openapi-2/visitor.mjs +622 -0
  51. package/src/dereference/strategies/openapi-3-0/index.cjs +96 -0
  52. package/src/dereference/strategies/openapi-3-0/index.mjs +90 -0
  53. package/src/dereference/strategies/openapi-3-0/visitor.cjs +622 -0
  54. package/src/dereference/strategies/openapi-3-0/visitor.mjs +615 -0
  55. package/src/dereference/strategies/openapi-3-1/index.cjs +99 -0
  56. package/src/dereference/strategies/openapi-3-1/index.mjs +90 -0
  57. package/src/dereference/strategies/openapi-3-1/selectors/$anchor.cjs +65 -0
  58. package/src/dereference/strategies/openapi-3-1/selectors/$anchor.mjs +54 -0
  59. package/src/dereference/strategies/openapi-3-1/selectors/uri.cjs +50 -0
  60. package/src/dereference/strategies/openapi-3-1/selectors/uri.mjs +42 -0
  61. package/src/dereference/strategies/openapi-3-1/util.cjs +68 -0
  62. package/src/dereference/strategies/openapi-3-1/util.mjs +59 -0
  63. package/src/dereference/strategies/openapi-3-1/visitor.cjs +874 -0
  64. package/src/dereference/strategies/openapi-3-1/visitor.mjs +867 -0
  65. package/src/dereference/util.cjs +31 -0
  66. package/src/dereference/util.mjs +27 -0
  67. package/src/errors/BundleError.cjs +10 -0
  68. package/src/errors/BundleError.mjs +7 -0
  69. package/src/errors/DereferenceError.cjs +10 -0
  70. package/src/errors/DereferenceError.mjs +7 -0
  71. package/src/errors/EvaluationElementIdError.cjs +10 -0
  72. package/src/errors/EvaluationElementIdError.mjs +7 -0
  73. package/src/errors/EvaluationJsonSchema$anchorError.cjs +11 -0
  74. package/src/errors/EvaluationJsonSchema$anchorError.mjs +6 -0
  75. package/src/errors/EvaluationJsonSchemaUriError.cjs +11 -0
  76. package/src/errors/EvaluationJsonSchemaUriError.mjs +6 -0
  77. package/src/errors/InvalidJsonSchema$anchorError.cjs +15 -0
  78. package/src/errors/InvalidJsonSchema$anchorError.mjs +10 -0
  79. package/src/errors/JsonSchema$anchorError.cjs +10 -0
  80. package/src/errors/JsonSchema$anchorError.mjs +7 -0
  81. package/src/errors/JsonSchemaUriError.cjs +10 -0
  82. package/src/errors/JsonSchemaUriError.mjs +7 -0
  83. package/src/errors/MaximumBundleDepthError.cjs +11 -0
  84. package/src/errors/MaximumBundleDepthError.mjs +6 -0
  85. package/src/errors/MaximumDereferenceDepthError.cjs +11 -0
  86. package/src/errors/MaximumDereferenceDepthError.mjs +6 -0
  87. package/src/errors/MaximumResolveDepthError.cjs +11 -0
  88. package/src/errors/MaximumResolveDepthError.mjs +6 -0
  89. package/src/errors/ParseError.cjs +10 -0
  90. package/src/errors/ParseError.mjs +7 -0
  91. package/src/errors/ParserError.cjs +11 -0
  92. package/src/errors/ParserError.mjs +6 -0
  93. package/src/errors/PluginError.cjs +18 -0
  94. package/src/errors/PluginError.mjs +15 -0
  95. package/src/errors/ResolveError.cjs +10 -0
  96. package/src/errors/ResolveError.mjs +7 -0
  97. package/src/errors/ResolverError.cjs +11 -0
  98. package/src/errors/ResolverError.mjs +6 -0
  99. package/src/errors/UnmatchedBundleStrategyError.cjs +11 -0
  100. package/src/errors/UnmatchedBundleStrategyError.mjs +6 -0
  101. package/src/errors/UnmatchedDereferenceStrategyError.cjs +11 -0
  102. package/src/errors/UnmatchedDereferenceStrategyError.mjs +6 -0
  103. package/src/errors/UnmatchedParserError.cjs +11 -0
  104. package/src/errors/UnmatchedParserError.mjs +6 -0
  105. package/src/errors/UnmatchedResolveStrategyError.cjs +11 -0
  106. package/src/errors/UnmatchedResolveStrategyError.mjs +6 -0
  107. package/src/errors/UnmatchedResolverError.cjs +11 -0
  108. package/src/errors/UnmatchedResolverError.mjs +6 -0
  109. package/src/errors/UnresolvableReferenceError.cjs +11 -0
  110. package/src/errors/UnresolvableReferenceError.mjs +6 -0
  111. package/src/index.cjs +146 -0
  112. package/src/index.mjs +103 -0
  113. package/src/options/index.cjs +194 -0
  114. package/src/options/index.mjs +191 -0
  115. package/src/options/util.cjs +24 -0
  116. package/src/options/util.mjs +19 -0
  117. package/src/parse/index.cjs +69 -0
  118. package/src/parse/index.mjs +63 -0
  119. package/src/parse/parsers/Parser.cjs +62 -0
  120. package/src/parse/parsers/Parser.mjs +58 -0
  121. package/src/parse/parsers/apidom-json/index.cjs +70 -0
  122. package/src/parse/parsers/apidom-json/index.mjs +64 -0
  123. package/src/parse/parsers/arazzo-json-1/index.cjs +62 -0
  124. package/src/parse/parsers/arazzo-json-1/index.mjs +56 -0
  125. package/src/parse/parsers/arazzo-json-1/source-descriptions.cjs +221 -0
  126. package/src/parse/parsers/arazzo-json-1/source-descriptions.mjs +214 -0
  127. package/src/parse/parsers/arazzo-yaml-1/index.cjs +62 -0
  128. package/src/parse/parsers/arazzo-yaml-1/index.mjs +56 -0
  129. package/src/parse/parsers/arazzo-yaml-1/source-descriptions.cjs +12 -0
  130. package/src/parse/parsers/arazzo-yaml-1/source-descriptions.mjs +7 -0
  131. package/src/parse/parsers/asyncapi-json-2/index.cjs +54 -0
  132. package/src/parse/parsers/asyncapi-json-2/index.mjs +48 -0
  133. package/src/parse/parsers/asyncapi-yaml-2/index.cjs +54 -0
  134. package/src/parse/parsers/asyncapi-yaml-2/index.mjs +48 -0
  135. package/src/parse/parsers/binary/index-browser.cjs +56 -0
  136. package/src/parse/parsers/binary/index-browser.mjs +50 -0
  137. package/src/parse/parsers/binary/index-node.cjs +51 -0
  138. package/src/parse/parsers/binary/index-node.mjs +45 -0
  139. package/src/parse/parsers/json/index.cjs +53 -0
  140. package/src/parse/parsers/json/index.mjs +47 -0
  141. package/src/parse/parsers/openapi-json-2/index.cjs +54 -0
  142. package/src/parse/parsers/openapi-json-2/index.mjs +48 -0
  143. package/src/parse/parsers/openapi-json-3-0/index.cjs +54 -0
  144. package/src/parse/parsers/openapi-json-3-0/index.mjs +48 -0
  145. package/src/parse/parsers/openapi-json-3-1/index.cjs +54 -0
  146. package/src/parse/parsers/openapi-json-3-1/index.mjs +48 -0
  147. package/src/parse/parsers/openapi-yaml-2/index.cjs +54 -0
  148. package/src/parse/parsers/openapi-yaml-2/index.mjs +48 -0
  149. package/src/parse/parsers/openapi-yaml-3-0/index.cjs +54 -0
  150. package/src/parse/parsers/openapi-yaml-3-0/index.mjs +48 -0
  151. package/src/parse/parsers/openapi-yaml-3-1/index.cjs +54 -0
  152. package/src/parse/parsers/openapi-yaml-3-1/index.mjs +48 -0
  153. package/src/parse/parsers/yaml-1-2/index.cjs +56 -0
  154. package/src/parse/parsers/yaml-1-2/index.mjs +50 -0
  155. package/src/resolve/index.cjs +67 -0
  156. package/src/resolve/index.mjs +60 -0
  157. package/src/resolve/resolvers/HTTPResolver.cjs +45 -0
  158. package/src/resolve/resolvers/HTTPResolver.mjs +37 -0
  159. package/src/resolve/resolvers/Resolver.cjs +20 -0
  160. package/src/resolve/resolvers/Resolver.mjs +16 -0
  161. package/src/resolve/resolvers/file/index-browser.cjs +24 -0
  162. package/src/resolve/resolvers/file/index-browser.mjs +19 -0
  163. package/src/resolve/resolvers/file/index-node.cjs +49 -0
  164. package/src/resolve/resolvers/file/index-node.mjs +42 -0
  165. package/src/resolve/resolvers/http-axios/cache/MemoryCache.cjs +41 -0
  166. package/src/resolve/resolvers/http-axios/cache/MemoryCache.mjs +37 -0
  167. package/src/resolve/resolvers/http-axios/index.cjs +113 -0
  168. package/src/resolve/resolvers/http-axios/index.mjs +105 -0
  169. package/src/resolve/strategies/ResolveStrategy.cjs +20 -0
  170. package/src/resolve/strategies/ResolveStrategy.mjs +16 -0
  171. package/src/resolve/strategies/apidom/index.cjs +49 -0
  172. package/src/resolve/strategies/apidom/index.mjs +43 -0
  173. package/src/resolve/strategies/asyncapi-2/index.cjs +49 -0
  174. package/src/resolve/strategies/asyncapi-2/index.mjs +43 -0
  175. package/src/resolve/strategies/openapi-2/index.cjs +49 -0
  176. package/src/resolve/strategies/openapi-2/index.mjs +43 -0
  177. package/src/resolve/strategies/openapi-3-0/index.cjs +49 -0
  178. package/src/resolve/strategies/openapi-3-0/index.mjs +43 -0
  179. package/src/resolve/strategies/openapi-3-1/index.cjs +49 -0
  180. package/src/resolve/strategies/openapi-3-1/index.mjs +43 -0
  181. package/src/resolve/util.cjs +37 -0
  182. package/src/resolve/util.mjs +30 -0
  183. package/src/util/plugins.cjs +39 -0
  184. package/src/util/plugins.mjs +34 -0
  185. package/src/util/url.cjs +288 -0
  186. package/src/util/url.mjs +274 -0
@@ -0,0 +1,615 @@
1
+ import { propEq } from 'ramda';
2
+ import { isUndefined } from 'ramda-adjunct';
3
+ import { isStringElement, isElement, RefElement, cloneShallow, cloneDeep } from '@speclynx/apidom-datamodel';
4
+ import { toValue, toYAML } from '@speclynx/apidom-core';
5
+ import { ApiDOMStructuredError } from '@speclynx/apidom-error';
6
+ import { traverse, traverseAsync, find } from '@speclynx/apidom-traverse';
7
+ import { evaluate, URIFragmentIdentifier } from '@speclynx/apidom-json-pointer';
8
+ import { isReferenceElement, isOperationElement, isPathItemElement, isReferenceLikeElement, refract, refractReference, refractPathItem, refractOperation } from '@speclynx/apidom-ns-openapi-3-0';
9
+ import UnresolvableReferenceError from "../../../errors/UnresolvableReferenceError.mjs";
10
+ import MaximumDereferenceDepthError from "../../../errors/MaximumDereferenceDepthError.mjs";
11
+ import MaximumResolveDepthError from "../../../errors/MaximumResolveDepthError.mjs";
12
+ import * as url from "../../../util/url.mjs";
13
+ import parse from "../../../parse/index.mjs";
14
+ import Reference from "../../../Reference.mjs";
15
+ import { AncestorLineage } from "../../util.mjs";
16
+ /**
17
+ * @public
18
+ */
19
+ /**
20
+ * @public
21
+ */
22
+ class OpenAPI3_0DereferenceVisitor {
23
+ indirections;
24
+ reference;
25
+ options;
26
+ refractCache;
27
+
28
+ /**
29
+ * Tracks element ancestors across dive-deep traversal boundaries.
30
+ * Used for cycle detection: if a referenced element is found in
31
+ * the ancestor lineage, a circular reference is detected.
32
+ */
33
+ ancestors;
34
+ constructor({
35
+ reference,
36
+ options,
37
+ indirections = [],
38
+ ancestors = new AncestorLineage(),
39
+ refractCache = new WeakMap()
40
+ }) {
41
+ this.indirections = indirections;
42
+ this.reference = reference;
43
+ this.options = options;
44
+ this.ancestors = new AncestorLineage(...ancestors);
45
+ this.refractCache = refractCache;
46
+ }
47
+ toAncestorLineage(path) {
48
+ const ancestorNodes = path.getAncestorNodes();
49
+ const directAncestors = new Set(ancestorNodes.filter(isElement));
50
+ const ancestorsLineage = new AncestorLineage(...this.ancestors, directAncestors);
51
+ return [ancestorsLineage, directAncestors];
52
+ }
53
+ toBaseURI(uri) {
54
+ return url.resolve(this.reference.uri, url.sanitize(url.stripHash(uri)));
55
+ }
56
+ async toReference(uri) {
57
+ // detect maximum depth of resolution
58
+ if (this.reference.depth >= this.options.resolve.maxDepth) {
59
+ throw new MaximumResolveDepthError(`Maximum resolution depth of ${this.options.resolve.maxDepth} has been exceeded by file "${this.reference.uri}"`, {
60
+ maxDepth: this.options.resolve.maxDepth,
61
+ uri: this.reference.uri
62
+ });
63
+ }
64
+ const baseURI = this.toBaseURI(uri);
65
+ const {
66
+ refSet
67
+ } = this.reference;
68
+
69
+ // we've already processed this Reference in past
70
+ if (refSet.has(baseURI)) {
71
+ return refSet.find(propEq(baseURI, 'uri'));
72
+ }
73
+ const parseResult = await parse(url.unsanitize(baseURI), {
74
+ ...this.options,
75
+ parse: {
76
+ ...this.options.parse,
77
+ mediaType: 'text/plain'
78
+ }
79
+ });
80
+
81
+ // register new mutable reference with a refSet
82
+ //
83
+ // NOTE(known limitation): the mutable reference is mutated in place during traversal
84
+ // (via `{ mutable: true }`). When an external document evaluates a JSON pointer back
85
+ // into this document, it may receive an already-resolved element instead of the original
86
+ // $ref. That resolved element was produced using the entry document's resolution context
87
+ // (ancestors, indirections), which may differ from the external document's context.
88
+ // This can affect cycle detection in rare cross-document circular reference patterns.
89
+ //
90
+ // Remediation: evaluate JSON pointers against the immutable (original) parse tree
91
+ // instead of the mutable working copy. The `immutable://` reference below preserves
92
+ // the original tree and could be used for pointer evaluation, ensuring every resolution
93
+ // context always sees raw, unresolved elements and processes them with its own
94
+ // ancestors/indirections. The trade-off is that elements referenced by multiple
95
+ // documents would be resolved once per context instead of being reused.
96
+ const mutableReference = new Reference({
97
+ uri: baseURI,
98
+ value: this.options.dereference.immutable ? cloneDeep(parseResult) : parseResult,
99
+ depth: this.reference.depth + 1
100
+ });
101
+ refSet.add(mutableReference);
102
+ if (this.options.dereference.immutable) {
103
+ // register new immutable reference with a refSet
104
+ const immutableReference = new Reference({
105
+ uri: `immutable://${baseURI}`,
106
+ value: parseResult,
107
+ depth: this.reference.depth + 1
108
+ });
109
+ refSet.add(immutableReference);
110
+ }
111
+ return mutableReference;
112
+ }
113
+
114
+ /**
115
+ * Handles an error according to the continueOnError option.
116
+ *
117
+ * For new errors: wraps in UnresolvableReferenceError with structured context
118
+ * (type, uri, location, codeFrame, refFieldName, refFieldValue, trace).
119
+ * For errors already wrapped by a nested visitor: prepends the current hop to the trace.
120
+ *
121
+ * Inner/intermediate visitors always throw to let the trace accumulate.
122
+ * Only the entry document visitor respects continueOnError (callback/swallow/throw).
123
+ */
124
+ handleError(message, error, referencingElement, refFieldName, refFieldValue, visitorPath) {
125
+ const {
126
+ continueOnError
127
+ } = this.options.dereference;
128
+ const isEntryDocument = url.stripHash(this.reference.refSet?.rootRef?.uri ?? '') === this.reference.uri;
129
+ const uri = this.reference.uri;
130
+ const type = referencingElement.element;
131
+ const codeFrame = toYAML(referencingElement);
132
+
133
+ // find element location by identity in the document tree.
134
+ // guarded: this.reference.value may not be a ParseResultElement or may lack a result.
135
+ // falls back to visitorPath which may produce an incomplete path when
136
+ // dereferenceApiDOM is called with a fragment (cloneShallow creates a new root identity).
137
+ let location;
138
+ const root = this.reference.value.result;
139
+ if (isElement(root)) {
140
+ traverse(root, {
141
+ enter: p => {
142
+ if (p.node === referencingElement || this.refractCache.get(p.node) === referencingElement) {
143
+ location = p.formatPath();
144
+ p.stop();
145
+ }
146
+ }
147
+ });
148
+ }
149
+ location ??= visitorPath.formatPath();
150
+ const hop = {
151
+ uri,
152
+ type,
153
+ refFieldName,
154
+ refFieldValue,
155
+ location,
156
+ codeFrame
157
+ };
158
+
159
+ // enrich existing error from nested visitor or create new one
160
+ let unresolvedError;
161
+ if (error instanceof UnresolvableReferenceError) {
162
+ // prefix relative locations for entries belonging to the referenced document
163
+ const refBaseURI = this.toBaseURI(refFieldValue);
164
+ const fragment = URIFragmentIdentifier.fromURIReference(refFieldValue);
165
+ if (fragment) {
166
+ if (refBaseURI === error.uri && error.location) {
167
+ error.location = fragment + error.location;
168
+ }
169
+ for (const h of error.trace) {
170
+ if (h.uri === refBaseURI && h.location) h.location = fragment + h.location;
171
+ }
172
+ }
173
+ // @ts-ignore
174
+ error.trace = [hop, ...error.trace];
175
+ unresolvedError = error;
176
+ } else {
177
+ unresolvedError = new UnresolvableReferenceError(message, {
178
+ cause: error,
179
+ type,
180
+ uri,
181
+ location,
182
+ codeFrame,
183
+ refFieldName,
184
+ refFieldValue,
185
+ trace: []
186
+ });
187
+ }
188
+ if (!isEntryDocument || continueOnError === false) throw unresolvedError;
189
+ if (typeof continueOnError === 'function') continueOnError(unresolvedError);
190
+ }
191
+ async ReferenceElement(path) {
192
+ const referencingElement = path.node;
193
+
194
+ // skip current referencing element as it's already been access
195
+ if (this.indirections.includes(referencingElement)) {
196
+ path.skip();
197
+ return;
198
+ }
199
+ const retrievalURI = this.toBaseURI(toValue(referencingElement.$ref));
200
+ const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
201
+ const isExternalReference = !isInternalReference;
202
+
203
+ // ignore resolving internal Reference Objects
204
+ if (!this.options.resolve.internal && isInternalReference) {
205
+ // skip traversing this reference element and all it's child elements
206
+ path.skip();
207
+ return;
208
+ }
209
+ // ignore resolving external Reference Objects
210
+ if (!this.options.resolve.external && isExternalReference) {
211
+ // skip traversing this reference element and all it's child elements
212
+ path.skip();
213
+ return;
214
+ }
215
+ const $refBaseURI = url.resolve(retrievalURI, toValue(referencingElement.$ref));
216
+ const indirectionsSize = this.indirections.length;
217
+ try {
218
+ const reference = await this.toReference(toValue(referencingElement.$ref));
219
+ this.indirections.push(referencingElement);
220
+ const jsonPointer = URIFragmentIdentifier.fromURIReference($refBaseURI);
221
+
222
+ // possibly non-semantic fragment
223
+ let referencedElement = evaluate(reference.value.result, jsonPointer);
224
+
225
+ // applying semantics to a fragment
226
+ const referencedElementType = referencingElement.meta.get('referenced-element');
227
+ if (referencedElement.element !== referencedElementType && !isReferenceElement(referencedElement)) {
228
+ if (this.refractCache.has(referencedElement)) {
229
+ referencedElement = this.refractCache.get(referencedElement);
230
+ } else if (isReferenceLikeElement(referencedElement)) {
231
+ // handling generic indirect references
232
+ const sourceElement = referencedElement;
233
+ referencedElement = refractReference(referencedElement);
234
+ referencedElement.meta.set('referenced-element', referencedElementType);
235
+ this.refractCache.set(sourceElement, referencedElement);
236
+ } else {
237
+ // handling direct references
238
+ const sourceElement = referencedElement;
239
+ referencedElement = refract(referencedElement, {
240
+ element: referencedElementType
241
+ });
242
+ this.refractCache.set(sourceElement, referencedElement);
243
+ }
244
+ }
245
+
246
+ // detect direct or indirect reference
247
+ if (referencingElement === referencedElement) {
248
+ throw new ApiDOMStructuredError('Recursive Reference Object detected', {
249
+ $ref: toValue(referencingElement.$ref)
250
+ });
251
+ }
252
+
253
+ // detect maximum depth of dereferencing
254
+ if (this.indirections.length > this.options.dereference.maxDepth) {
255
+ throw new MaximumDereferenceDepthError(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
256
+ maxDepth: this.options.dereference.maxDepth,
257
+ uri: this.reference.uri
258
+ });
259
+ }
260
+
261
+ // detect second deep dive into the same fragment and avoid it
262
+ const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
263
+ if (ancestorsLineage.includes(referencedElement)) {
264
+ reference.refSet.circular = true;
265
+ if (this.options.dereference.circular === 'error') {
266
+ throw new ApiDOMStructuredError('Circular reference detected', {
267
+ $ref: toValue(referencingElement.$ref)
268
+ });
269
+ } else if (this.options.dereference.circular === 'replace') {
270
+ const refElement = new RefElement($refBaseURI, {
271
+ type: referencingElement.element,
272
+ uri: reference.uri,
273
+ $ref: toValue(referencingElement.$ref)
274
+ });
275
+ const replacer = this.options.dereference.strategyOpts['openapi-3-0']?.circularReplacer ?? this.options.dereference.circularReplacer;
276
+ const replacement = replacer(refElement);
277
+ path.replaceWith(replacement);
278
+ return;
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Dive deep into the fragment.
284
+ *
285
+ * Cases to consider:
286
+ * 1. We're crossing document boundary
287
+ * 2. Fragment is from non-entry document
288
+ * 3. Fragment is a Reference Object. We need to follow it to get the eventual value
289
+ * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
290
+ */
291
+ const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
292
+ const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
293
+ if ((isExternalReference || isNonEntryDocument || isReferenceElement(referencedElement) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
294
+ // append referencing reference to ancestors lineage
295
+ directAncestors.add(referencingElement);
296
+ const visitor = new OpenAPI3_0DereferenceVisitor({
297
+ reference,
298
+ indirections: [...this.indirections],
299
+ options: this.options,
300
+ refractCache: this.refractCache,
301
+ ancestors: ancestorsLineage
302
+ });
303
+ referencedElement = await traverseAsync(referencedElement, visitor, {
304
+ mutable: true
305
+ });
306
+
307
+ // remove referencing reference from ancestors lineage
308
+ directAncestors.delete(referencingElement);
309
+ }
310
+
311
+ /**
312
+ * Creating a new version of referenced element to avoid modifying the original one.
313
+ */
314
+ const mergedElement = cloneShallow(referencedElement);
315
+ // annotate referenced element with info about original referencing element
316
+ mergedElement.meta.set('ref-fields', {
317
+ $ref: toValue(referencingElement.$ref)
318
+ });
319
+ // annotate fragment with info about origin
320
+ mergedElement.meta.set('ref-origin', reference.uri);
321
+ mergedElement.meta.set('ref-type', referencingElement.element);
322
+
323
+ /**
324
+ * Transclude referencing element with merged referenced element.
325
+ */
326
+ path.replaceWith(mergedElement);
327
+ } catch (error) {
328
+ const $ref = toValue(referencingElement.$ref);
329
+ this.handleError(`Error while dereferencing Reference Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
330
+ } finally {
331
+ if (this.indirections.length > indirectionsSize) this.indirections.pop();
332
+ }
333
+ }
334
+ async PathItemElement(path) {
335
+ const referencingElement = path.node;
336
+
337
+ // ignore PathItemElement without $ref field
338
+ if (!isStringElement(referencingElement.$ref)) {
339
+ return;
340
+ }
341
+
342
+ // skip current referencing element as it's already been access
343
+ if (this.indirections.includes(referencingElement)) {
344
+ path.skip();
345
+ return;
346
+ }
347
+ const retrievalURI = this.toBaseURI(toValue(referencingElement.$ref));
348
+ const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
349
+ const isExternalReference = !isInternalReference;
350
+
351
+ // ignore resolving internal Path Item Objects
352
+ if (!this.options.resolve.internal && isInternalReference) {
353
+ // skip traversing this Path Item element but traverse all it's child elements
354
+ return;
355
+ }
356
+ // ignore resolving external Path Item Objects
357
+ if (!this.options.resolve.external && isExternalReference) {
358
+ // skip traversing this Path Item element but traverse all it's child elements
359
+ return;
360
+ }
361
+ const $refBaseURI = url.resolve(retrievalURI, toValue(referencingElement.$ref));
362
+ const indirectionsSize = this.indirections.length;
363
+ try {
364
+ const reference = await this.toReference(toValue(referencingElement.$ref));
365
+ this.indirections.push(referencingElement);
366
+ const jsonPointer = URIFragmentIdentifier.fromURIReference($refBaseURI);
367
+
368
+ // possibly non-semantic referenced element
369
+ let referencedElement = evaluate(reference.value.result, jsonPointer);
370
+
371
+ // applying semantics to a referenced element
372
+ if (!isPathItemElement(referencedElement)) {
373
+ if (this.refractCache.has(referencedElement)) {
374
+ referencedElement = this.refractCache.get(referencedElement);
375
+ } else {
376
+ const sourceElement = referencedElement;
377
+ referencedElement = refractPathItem(referencedElement);
378
+ this.refractCache.set(sourceElement, referencedElement);
379
+ }
380
+ }
381
+
382
+ // detect direct or indirect reference
383
+ if (referencingElement === referencedElement) {
384
+ throw new ApiDOMStructuredError('Recursive Path Item Object reference detected', {
385
+ $ref: toValue(referencingElement.$ref)
386
+ });
387
+ }
388
+
389
+ // detect maximum depth of dereferencing
390
+ if (this.indirections.length > this.options.dereference.maxDepth) {
391
+ throw new MaximumDereferenceDepthError(`Maximum dereference depth of "${this.options.dereference.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
392
+ maxDepth: this.options.dereference.maxDepth,
393
+ uri: this.reference.uri
394
+ });
395
+ }
396
+
397
+ // detect cross-boundary cycle
398
+ const [ancestorsLineage, directAncestors] = this.toAncestorLineage(path);
399
+ if (ancestorsLineage.includes(referencedElement)) {
400
+ reference.refSet.circular = true;
401
+ if (this.options.dereference.circular === 'error') {
402
+ throw new ApiDOMStructuredError('Circular reference detected', {
403
+ $ref: toValue(referencingElement.$ref)
404
+ });
405
+ } else if (this.options.dereference.circular === 'replace') {
406
+ const refElement = new RefElement($refBaseURI, {
407
+ type: referencingElement.element,
408
+ uri: reference.uri,
409
+ $ref: toValue(referencingElement.$ref)
410
+ });
411
+ const replacer = this.options.dereference.strategyOpts['openapi-3-0']?.circularReplacer ?? this.options.dereference.circularReplacer;
412
+ const replacement = replacer(refElement);
413
+ path.replaceWith(replacement);
414
+ return;
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Dive deep into the fragment.
420
+ *
421
+ * Cases to consider:
422
+ * 1. We're crossing document boundary
423
+ * 2. Fragment is from non-entry document
424
+ * 3. Fragment is a Path Item Object with $ref field. We need to follow it to get the eventual value
425
+ * 4. We are dereferencing the fragment lazily/eagerly depending on circular mode
426
+ */
427
+ const isNonEntryDocument = url.stripHash(reference.refSet.rootRef.uri) !== reference.uri;
428
+ const shouldDetectCircular = ['error', 'replace'].includes(this.options.dereference.circular);
429
+ if ((isExternalReference || isNonEntryDocument || isPathItemElement(referencedElement) && isStringElement(referencedElement.$ref) || shouldDetectCircular) && !ancestorsLineage.includesCycle(referencedElement)) {
430
+ // append referencing reference to ancestors lineage
431
+ directAncestors.add(referencingElement);
432
+ const visitor = new OpenAPI3_0DereferenceVisitor({
433
+ reference,
434
+ indirections: [...this.indirections],
435
+ options: this.options,
436
+ refractCache: this.refractCache,
437
+ ancestors: ancestorsLineage
438
+ });
439
+ referencedElement = await traverseAsync(referencedElement, visitor, {
440
+ mutable: true
441
+ });
442
+
443
+ // remove referencing reference from ancestors lineage
444
+ directAncestors.delete(referencingElement);
445
+ }
446
+
447
+ /**
448
+ * Creating a new version of Path Item by merging fields from referenced Path Item with referencing one.
449
+ */
450
+ if (isPathItemElement(referencedElement)) {
451
+ const mergedElement = cloneShallow(referencedElement);
452
+ // existing keywords from referencing PathItemElement overrides ones from referenced element
453
+ referencingElement.forEach((value, keyElement, item) => {
454
+ mergedElement.remove(toValue(keyElement));
455
+ mergedElement.content.push(item);
456
+ });
457
+ mergedElement.remove('$ref');
458
+
459
+ // annotate referenced element with info about original referencing element
460
+ mergedElement.meta.set('ref-fields', {
461
+ $ref: toValue(referencingElement.$ref)
462
+ });
463
+ // annotate referenced element with info about origin and type
464
+ mergedElement.meta.set('ref-origin', reference.uri);
465
+ mergedElement.meta.set('ref-type', referencingElement.element);
466
+ referencedElement = mergedElement;
467
+ }
468
+
469
+ /**
470
+ * Transclude referencing element with merged referenced element.
471
+ */
472
+ path.replaceWith(referencedElement);
473
+ } catch (error) {
474
+ const $ref = toValue(referencingElement.$ref);
475
+ this.handleError(`Error while dereferencing Path Item Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
476
+ } finally {
477
+ if (this.indirections.length > indirectionsSize) this.indirections.pop();
478
+ }
479
+ }
480
+ async LinkElement(path) {
481
+ const linkElement = path.node;
482
+
483
+ // ignore LinkElement without operationRef or operationId field
484
+ if (!isStringElement(linkElement.operationRef) && !isStringElement(linkElement.operationId)) {
485
+ return;
486
+ }
487
+
488
+ // operationRef and operationId fields are mutually exclusive
489
+ if (isStringElement(linkElement.operationRef) && isStringElement(linkElement.operationId)) {
490
+ throw new ApiDOMStructuredError('LinkElement operationRef and operationId fields are mutually exclusive', {
491
+ operationRef: toValue(linkElement.operationRef),
492
+ operationId: toValue(linkElement.operationId)
493
+ });
494
+ }
495
+ try {
496
+ let operationElement;
497
+ if (isStringElement(linkElement.operationRef)) {
498
+ // possibly non-semantic referenced element
499
+ const jsonPointer = URIFragmentIdentifier.fromURIReference(toValue(linkElement.operationRef));
500
+ const retrievalURI = this.toBaseURI(toValue(linkElement.operationRef));
501
+ const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
502
+ const isExternalReference = !isInternalReference;
503
+
504
+ // ignore resolving internal Operation Object reference
505
+ if (!this.options.resolve.internal && isInternalReference) {
506
+ // skip traversing this Link element but traverse all it's child elements
507
+ return;
508
+ }
509
+ // ignore resolving external Operation Object reference
510
+ if (!this.options.resolve.external && isExternalReference) {
511
+ // skip traversing this Link element but traverse all it's child elements
512
+ return;
513
+ }
514
+ const reference = await this.toReference(toValue(linkElement.operationRef));
515
+ operationElement = evaluate(reference.value.result, jsonPointer);
516
+ // applying semantics to a referenced element
517
+ if (!isOperationElement(operationElement)) {
518
+ if (this.refractCache.has(operationElement)) {
519
+ operationElement = this.refractCache.get(operationElement);
520
+ } else {
521
+ const sourceElement = operationElement;
522
+ operationElement = refractOperation(operationElement);
523
+ this.refractCache.set(sourceElement, operationElement);
524
+ }
525
+ }
526
+ // create shallow clone to be able to annotate with metadata
527
+ operationElement = cloneShallow(operationElement);
528
+ // annotate operation element with info about origin
529
+ operationElement.meta.set('ref-origin', reference.uri);
530
+ operationElement.meta.set('ref-type', linkElement.element);
531
+ const linkElementCopy = cloneShallow(linkElement);
532
+ linkElementCopy.operationRef?.meta.set('operation', operationElement);
533
+
534
+ /**
535
+ * Transclude Link Object containing Operation Object in its meta.
536
+ */
537
+ path.replaceWith(linkElementCopy);
538
+ return;
539
+ }
540
+ if (isStringElement(linkElement.operationId)) {
541
+ const operationId = toValue(linkElement.operationId);
542
+ const reference = await this.toReference(url.unsanitize(this.reference.uri));
543
+ const operationPath = find(reference.value.result, path => isOperationElement(path.node) && isElement(path.node.operationId) && path.node.operationId.equals(operationId));
544
+ operationElement = operationPath?.node;
545
+ // OperationElement not found by its operationId
546
+ if (isUndefined(operationElement)) {
547
+ throw new ApiDOMStructuredError(`OperationElement(operationId=${operationId}) not found`, {
548
+ operationId
549
+ });
550
+ }
551
+ const linkElementCopy = cloneShallow(linkElement);
552
+ linkElementCopy.operationId?.meta.set('operation', operationElement);
553
+
554
+ /**
555
+ * Transclude Link Object containing Operation Object in its meta.
556
+ */
557
+ path.replaceWith(linkElementCopy);
558
+ }
559
+ } catch (error) {
560
+ const refFieldName = isStringElement(linkElement.operationRef) ? 'operationRef' : 'operationId';
561
+ const refFieldValue = isStringElement(linkElement.operationRef) ? toValue(linkElement.operationRef) : toValue(linkElement.operationId);
562
+ this.handleError(`Error while dereferencing Link Object. Cannot resolve ${refFieldName} "${refFieldValue}": ${error.message}`, error, linkElement, refFieldName, refFieldValue, path);
563
+ }
564
+ }
565
+ async ExampleElement(path) {
566
+ const exampleElement = path.node;
567
+
568
+ // ignore ExampleElement without externalValue field
569
+ if (!isStringElement(exampleElement.externalValue)) {
570
+ return;
571
+ }
572
+
573
+ // value and externalValue fields are mutually exclusive
574
+ if (exampleElement.hasKey('value') && isStringElement(exampleElement.externalValue)) {
575
+ throw new ApiDOMStructuredError('ExampleElement value and externalValue fields are mutually exclusive', {
576
+ value: toValue(exampleElement.value),
577
+ externalValue: toValue(exampleElement.externalValue)
578
+ });
579
+ }
580
+ const retrievalURI = this.toBaseURI(toValue(exampleElement.externalValue));
581
+ const isInternalReference = url.stripHash(this.reference.uri) === retrievalURI;
582
+ const isExternalReference = !isInternalReference;
583
+
584
+ // ignore resolving external Example Objects
585
+ if (!this.options.resolve.internal && isInternalReference) {
586
+ // skip traversing this Example element but traverse all it's child elements
587
+ return;
588
+ }
589
+ // ignore resolving external Example Objects
590
+ if (!this.options.resolve.external && isExternalReference) {
591
+ // skip traversing this Example element but traverse all it's child elements
592
+ return;
593
+ }
594
+ try {
595
+ const reference = await this.toReference(toValue(exampleElement.externalValue));
596
+
597
+ // shallow clone of the referenced element
598
+ const valueElement = cloneShallow(reference.value.result);
599
+ // annotate operation element with info about origin
600
+ valueElement.meta.set('ref-origin', reference.uri);
601
+ valueElement.meta.set('ref-type', exampleElement.element);
602
+ const exampleElementCopy = cloneShallow(exampleElement);
603
+ exampleElementCopy.value = valueElement;
604
+
605
+ /**
606
+ * Transclude Example Object containing external value.
607
+ */
608
+ path.replaceWith(exampleElementCopy);
609
+ } catch (error) {
610
+ const externalValue = toValue(exampleElement.externalValue);
611
+ this.handleError(`Error while dereferencing Example Object. Cannot resolve externalValue "${externalValue}": ${error.message}`, error, exampleElement, 'externalValue', externalValue, path);
612
+ }
613
+ }
614
+ }
615
+ export default OpenAPI3_0DereferenceVisitor;