@speclynx/apidom-reference 3.0.0 → 3.1.0

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