@speclynx/apidom-reference 4.13.0 → 4.14.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.
@@ -0,0 +1,811 @@
1
+ "use strict";
2
+
3
+ var _interopRequireWildcard = require("@babel/runtime-corejs3/helpers/interopRequireWildcard").default;
4
+ var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default;
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.default = void 0;
9
+ var _ramda = require("ramda");
10
+ var _apidomDatamodel = require("@speclynx/apidom-datamodel");
11
+ var _apidomCore = require("@speclynx/apidom-core");
12
+ var _apidomError = require("@speclynx/apidom-error");
13
+ var _apidomTraverse = require("@speclynx/apidom-traverse");
14
+ var _apidomJsonPointer = require("@speclynx/apidom-json-pointer");
15
+ var _apidomNsOpenapi = require("@speclynx/apidom-ns-openapi-3-1");
16
+ var _BundleError = _interopRequireDefault(require("../../../errors/BundleError.cjs"));
17
+ var _UnresolvableReferenceError = _interopRequireDefault(require("../../../errors/UnresolvableReferenceError.cjs"));
18
+ var _MaximumBundleDepthError = _interopRequireDefault(require("../../../errors/MaximumBundleDepthError.cjs"));
19
+ var _MaximumResolveDepthError = _interopRequireDefault(require("../../../errors/MaximumResolveDepthError.cjs"));
20
+ var _EvaluationJsonSchemaUriError = _interopRequireDefault(require("../../../errors/EvaluationJsonSchemaUriError.cjs"));
21
+ var url = _interopRequireWildcard(require("../../../util/url.cjs"));
22
+ var _index = _interopRequireDefault(require("../../../parse/index.cjs"));
23
+ var _Reference = _interopRequireDefault(require("../../../Reference.cjs"));
24
+ var _File = _interopRequireDefault(require("../../../File.cjs"));
25
+ var _$anchor = require("../../../dereference/strategies/openapi-3-1/selectors/$anchor.cjs");
26
+ var _uri = require("../../../dereference/strategies/openapi-3-1/selectors/uri.cjs");
27
+ var _util = require("../../../dereference/strategies/openapi-3-1/util.cjs");
28
+ var _util2 = require("../../util.cjs");
29
+ /**
30
+ * Maps the `referenced-element` meta value (set during refraction) to the
31
+ * Components Object field where the referenced element should be hoisted.
32
+ * Field names are sourced from the Components Object fixed fields so they
33
+ * cannot drift from the namespace definition.
34
+ */
35
+ const cf = (0, _apidomCore.fixedFields)(_apidomNsOpenapi.ComponentsElement, {
36
+ indexed: true
37
+ });
38
+ const componentFieldByReferencedElement = {
39
+ schema: cf.schemas.name,
40
+ response: cf.responses.name,
41
+ parameter: cf.parameters.name,
42
+ example: cf.examples.name,
43
+ requestBody: cf.requestBodies.name,
44
+ header: cf.headers.name,
45
+ securityScheme: cf.securitySchemes.name,
46
+ link: cf.links.name,
47
+ callback: cf.callbacks.name,
48
+ pathItem: cf.pathItems.name
49
+ };
50
+
51
+ /**
52
+ * Maps a Components Object field to the named-content element the namespace
53
+ * uses for it, so a bundle-created field matches a parsed/refracted one
54
+ * (e.g. carries the `components-schemas` class) rather than being a generic
55
+ * object.
56
+ */
57
+ const componentFieldElementByField = {
58
+ [cf.schemas.name]: _apidomNsOpenapi.ComponentsSchemasElement,
59
+ [cf.responses.name]: _apidomNsOpenapi.ComponentsResponsesElement,
60
+ [cf.parameters.name]: _apidomNsOpenapi.ComponentsParametersElement,
61
+ [cf.examples.name]: _apidomNsOpenapi.ComponentsExamplesElement,
62
+ [cf.requestBodies.name]: _apidomNsOpenapi.ComponentsRequestBodiesElement,
63
+ [cf.headers.name]: _apidomNsOpenapi.ComponentsHeadersElement,
64
+ [cf.securitySchemes.name]: _apidomNsOpenapi.ComponentsSecuritySchemesElement,
65
+ [cf.links.name]: _apidomNsOpenapi.ComponentsLinksElement,
66
+ [cf.callbacks.name]: _apidomNsOpenapi.ComponentsCallbacksElement,
67
+ [cf.pathItems.name]: _apidomNsOpenapi.ComponentsPathItemsElement
68
+ };
69
+
70
+ /**
71
+ * @public
72
+ */
73
+
74
+ /**
75
+ * @public
76
+ */
77
+ class OpenAPI3_1BundleVisitor {
78
+ reference;
79
+ options;
80
+
81
+ /**
82
+ * The base URI (without hash) of the entry document. A reference is
83
+ * considered internal when it resolves to this URI and external otherwise.
84
+ * Derived from the shared refSet's root reference.
85
+ */
86
+ get entryURI() {
87
+ return url.stripHash(this.reference.refSet?.rootRef?.uri ?? '');
88
+ }
89
+
90
+ /**
91
+ * The entry parse result. Derived from the shared refSet's root reference.
92
+ */
93
+ get entryParseResult() {
94
+ return this.reference.refSet.rootRef.value;
95
+ }
96
+
97
+ /**
98
+ * The entry document element. Hoisted external fragments are placed into its
99
+ * `components` object. The `canBundle` guard guarantees it is an
100
+ * OpenApi3_1Element.
101
+ */
102
+ get entryResult() {
103
+ return this.entryParseResult.result;
104
+ }
105
+
106
+ /**
107
+ * Shared across the entry document and every external document visitor.
108
+ * Guarantees each external fragment is hoisted exactly once and gives us a
109
+ * stable internal pointer to rewrite every referencing element to.
110
+ */
111
+ assignments;
112
+
113
+ /**
114
+ * Component names already reserved per Components Object field. Reserved
115
+ * before recursion so collision suffixing (`Pet`, `Pet-2`, ...) accounts for
116
+ * components that are still being bundled.
117
+ */
118
+ reservedNames;
119
+
120
+ /**
121
+ * Caches refracted fragments keyed by source element and target element type.
122
+ * The type is part of the key because the same source can be refracted into
123
+ * different semantic elements depending on the referencing context (e.g. a
124
+ * generic object referenced once as a Parameter and once as a Response).
125
+ */
126
+ refractCache;
127
+ constructor({
128
+ reference,
129
+ options,
130
+ assignments = new Map(),
131
+ reservedNames = new Map(),
132
+ refractCache = new WeakMap()
133
+ }) {
134
+ this.reference = reference;
135
+ this.options = options;
136
+ this.assignments = assignments;
137
+ this.reservedNames = reservedNames;
138
+ this.refractCache = refractCache;
139
+ }
140
+ getRefracted(source, type) {
141
+ return this.refractCache.get(source)?.get(type);
142
+ }
143
+ setRefracted(source, type, refracted) {
144
+ let byType = this.refractCache.get(source);
145
+ if (byType === undefined) {
146
+ byType = new Map();
147
+ this.refractCache.set(source, byType);
148
+ }
149
+ byType.set(type, refracted);
150
+ }
151
+ toBaseURI(uri) {
152
+ return url.resolve(this.reference.uri, url.sanitize(url.stripHash(uri)));
153
+ }
154
+ async toReference(uri) {
155
+ // detect maximum depth of resolution
156
+ if (this.reference.depth >= this.options.resolve.maxDepth) {
157
+ throw new _MaximumResolveDepthError.default(`Maximum resolution depth of ${this.options.resolve.maxDepth} has been exceeded by file "${this.reference.uri}"`, {
158
+ maxDepth: this.options.resolve.maxDepth,
159
+ uri: this.reference.uri
160
+ });
161
+ }
162
+ const baseURI = this.toBaseURI(uri);
163
+ const {
164
+ refSet
165
+ } = this.reference;
166
+
167
+ // we've already processed this Reference in past
168
+ if (refSet.has(baseURI)) {
169
+ return refSet.find((0, _ramda.propEq)(baseURI, 'uri'));
170
+ }
171
+ const parseResult = await (0, _index.default)(url.unsanitize(baseURI), {
172
+ ...this.options,
173
+ parse: {
174
+ ...this.options.parse,
175
+ mediaType: 'text/plain'
176
+ }
177
+ });
178
+ const reference = new _Reference.default({
179
+ uri: baseURI,
180
+ value: parseResult,
181
+ depth: this.reference.depth + 1
182
+ });
183
+ refSet.add(reference);
184
+ return reference;
185
+ }
186
+
187
+ /**
188
+ * Normalizes a self-reference (e.g. `./root.json#/components/schemas/Pet`)
189
+ * to a bare fragment (`#/components/schemas/Pet`) so the bundled document stays
190
+ * transferable. Bare fragments are returned unchanged.
191
+ */
192
+ normalizeSelfReference(ref) {
193
+ return ref.startsWith('#') ? ref : url.getHash(ref);
194
+ }
195
+
196
+ /**
197
+ * Handles an error according to the `bundle.continueOnError` option.
198
+ *
199
+ * For new errors: wraps in UnresolvableReferenceError with structured
200
+ * context. For errors already wrapped by a nested visitor: prepends the
201
+ * current hop to the trace.
202
+ *
203
+ * Inner/intermediate visitors always throw to let the trace accumulate. Only
204
+ * the entry document visitor respects continueOnError (callback/swallow/throw).
205
+ */
206
+ handleError(message, error, referencingElement, refFieldName, refFieldValue, visitorPath) {
207
+ // a collision reported as `error` is a deliberate hard stop with no
208
+ // resolution-failure analog, so pass it through unchanged. A maxDepth
209
+ // breach (MaximumBundleDepthError, which also extends BundleError) is a
210
+ // resolution failure and flows through below — wrapped and subject to
211
+ // continueOnError, like dereferencing.
212
+ if (error instanceof _BundleError.default && !(error instanceof _MaximumBundleDepthError.default)) {
213
+ throw error;
214
+ }
215
+ const {
216
+ continueOnError
217
+ } = this.options.bundle;
218
+ const isEntryDocument = url.stripHash(this.reference.refSet?.rootRef?.uri ?? '') === this.reference.uri;
219
+ const uri = this.reference.uri;
220
+ const type = referencingElement.element;
221
+ const codeFrame = (0, _apidomCore.toYAML)(referencingElement);
222
+ const location = visitorPath.formatPath();
223
+ const hop = {
224
+ uri,
225
+ type,
226
+ refFieldName,
227
+ refFieldValue,
228
+ location,
229
+ codeFrame
230
+ };
231
+ let unresolvedError;
232
+ if (error instanceof _UnresolvableReferenceError.default) {
233
+ // @ts-ignore
234
+ error.trace = [hop, ...error.trace];
235
+ unresolvedError = error;
236
+ } else {
237
+ unresolvedError = new _UnresolvableReferenceError.default(message, {
238
+ cause: error,
239
+ type,
240
+ uri,
241
+ location,
242
+ codeFrame,
243
+ refFieldName,
244
+ refFieldValue,
245
+ trace: []
246
+ });
247
+ }
248
+ if (!isEntryDocument || continueOnError === false) throw unresolvedError;
249
+ if (typeof continueOnError === 'function') continueOnError(unresolvedError);
250
+ }
251
+
252
+ /**
253
+ * Lazily creates the Components Object (and the requested field within it)
254
+ * on the entry document, returning the field where a fragment is hoisted.
255
+ */
256
+ ensureComponentsField(field) {
257
+ const entryResult = this.entryResult;
258
+ let components = entryResult.components;
259
+ if (!(0, _apidomDatamodel.isObjectElement)(components)) {
260
+ components = new _apidomNsOpenapi.ComponentsElement();
261
+ entryResult.components = components;
262
+ }
263
+ let fieldElement = components.get(field);
264
+ if (!(0, _apidomDatamodel.isObjectElement)(fieldElement)) {
265
+ const FieldElement = componentFieldElementByField[field] ?? _apidomDatamodel.ObjectElement;
266
+ fieldElement = new FieldElement();
267
+ components.set(field, fieldElement);
268
+ }
269
+ return fieldElement;
270
+ }
271
+
272
+ /**
273
+ * Derives a component name from the referenced JSON Pointer's last token,
274
+ * falling back to the referenced file's basename.
275
+ */
276
+ basenameOf(jsonPointer, baseURI) {
277
+ const tokens = (0, _apidomJsonPointer.parse)(jsonPointer).tree;
278
+ const lastToken = tokens.length > 0 ? tokens[tokens.length - 1] : '';
279
+ return lastToken || url.getBasename(baseURI) || 'Schema';
280
+ }
281
+
282
+ /**
283
+ * Computes the base component name (before collision suffixing) according to
284
+ * the configured naming strategy.
285
+ */
286
+ baseName(element, field, jsonPointer, baseURI) {
287
+ // strategy specific options take precedence over the top-level bundle options
288
+ const componentNamesStrategy = this.options.bundle.strategyOpts['openapi-3-1']?.componentNamesStrategy ?? this.options.bundle.componentNamesStrategy;
289
+ if (typeof componentNamesStrategy === 'function') {
290
+ const resolved = componentNamesStrategy({
291
+ element,
292
+ field,
293
+ jsonPointer,
294
+ baseURI
295
+ });
296
+ if (typeof resolved === 'string' && resolved !== '') {
297
+ return resolved;
298
+ }
299
+ return this.basenameOf(jsonPointer, baseURI);
300
+ }
301
+ if (componentNamesStrategy === 'title') {
302
+ const title = (0, _apidomDatamodel.isObjectElement)(element) ? (0, _apidomCore.toValue)(element.get('title')) : undefined;
303
+ if (typeof title === 'string' && title.trim() !== '') {
304
+ const name = (0, _util2.sanitizeComponentName)((0, _util2.toPascalCase)(title));
305
+ if (name !== '') return name;
306
+ }
307
+ // fall back to basename when no usable title is present
308
+ }
309
+ return this.basenameOf(jsonPointer, baseURI);
310
+ }
311
+
312
+ /**
313
+ * Computes a collision-free component name within the target field. A name is
314
+ * taken if it's already placed in components or reserved by a component that
315
+ * is still being bundled (reserved before recursion).
316
+ */
317
+ uniqueName(candidate, field) {
318
+ const fieldElement = this.ensureComponentsField(field);
319
+ const reserved = this.reservedNames.get(field) ?? new Set();
320
+ return (0, _util2.uniqueName)(candidate, name => fieldElement.hasKey(name) || reserved.has(name));
321
+ }
322
+
323
+ /**
324
+ * Reports a collision-forced rename according to the configured severity.
325
+ * A rename means two distinct targets resolved to the same name; each keeps
326
+ * its own component (and origin), so report the rename per severity.
327
+ */
328
+ reportNameCollision(preferredName, componentName, field) {
329
+ // strategy specific options take precedence over the top-level bundle options
330
+ const onComponentNameCollision = this.options.bundle.strategyOpts['openapi-3-1']?.onComponentNameCollision ?? this.options.bundle.onComponentNameCollision;
331
+ if (componentName === preferredName || onComponentNameCollision === 'off') {
332
+ return;
333
+ }
334
+ const message = `Component "${preferredName}" in components/${field} is referenced with the same name but different content. Renamed to "${componentName}".`;
335
+ if (onComponentNameCollision === 'error') {
336
+ throw new _BundleError.default(message);
337
+ }
338
+ const annotation = new _apidomDatamodel.AnnotationElement(message);
339
+ annotation.classes.push('warning');
340
+ annotation.code = 'bundle-component-name-collision';
341
+ // append (never prepend) so the result element stays ahead of annotations
342
+ this.entryParseResult.content.push(annotation);
343
+ }
344
+ async ReferenceElement(path) {
345
+ const referencingElement = path.node;
346
+ const $ref = (0, _apidomCore.toValue)(referencingElement.$ref);
347
+ const retrievalURI = this.toBaseURI($ref);
348
+ const isInternalReference = this.entryURI === retrievalURI;
349
+ const isExternalReference = !isInternalReference;
350
+ if (isInternalReference) {
351
+ // normalize self-references to a bare fragment so the bundled
352
+ // document stays transferable; bare fragments are left untouched
353
+ referencingElement.set('$ref', this.normalizeSelfReference($ref));
354
+ path.skip();
355
+ return;
356
+ }
357
+
358
+ // honor the resolve.external switch
359
+ if (!this.options.resolve.external && isExternalReference) {
360
+ path.skip();
361
+ return;
362
+ }
363
+ const $refBaseURI = url.resolve(retrievalURI, $ref);
364
+ const jsonPointer = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference($refBaseURI);
365
+
366
+ // the target bucket depends on the referencing context, so it's part of the
367
+ // identity: the same external target referenced as e.g. both a parameter and
368
+ // a response must be hoisted into both components fields. The refractor sets
369
+ // `referenced-element` for every Reference Object position; the `schemas`
370
+ // fallback is a defensive default for the (unexpected) untagged case.
371
+ const referencedElementType = referencingElement.meta.get('referenced-element');
372
+ const field = componentFieldByReferencedElement[referencedElementType] ?? componentFieldByReferencedElement.schema;
373
+ const canonicalKey = `${field}\t${retrievalURI}#${jsonPointer}`;
374
+
375
+ // already hoisted (or being hoisted) — just rewrite the pointer.
376
+ //
377
+ // this is also how circular references terminate: the assignment is
378
+ // reserved BEFORE recursing into the fragment (see below), so a reference
379
+ // that cycles back (directly or indirectly) finds its pointer already
380
+ // reserved here and is rewritten without recursing. Cycles are deliberately
381
+ // preserved as internal `$ref`s pointing at each other — that is valid,
382
+ // serializable output; resolving the cycle (if desired) is dereferencing's
383
+ // job, not bundling's.
384
+ if (this.assignments.has(canonicalKey)) {
385
+ referencingElement.set('$ref', this.assignments.get(canonicalKey));
386
+ path.skip();
387
+ return;
388
+ }
389
+ try {
390
+ // detect maximum depth of bundling
391
+ if (this.reference.depth >= this.options.bundle.maxDepth) {
392
+ throw new _MaximumBundleDepthError.default(`Maximum bundle depth of "${this.options.bundle.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
393
+ maxDepth: this.options.bundle.maxDepth,
394
+ uri: this.reference.uri
395
+ });
396
+ }
397
+ const reference = await this.toReference($ref);
398
+
399
+ // possibly non-semantic fragment
400
+ let referencedElement = (0, _apidomJsonPointer.evaluate)(reference.value.result, jsonPointer);
401
+
402
+ // apply semantics to the fragment so nested references become Reference Objects
403
+ if (referencedElement.element !== referencedElementType && !(0, _apidomNsOpenapi.isReferenceElement)(referencedElement)) {
404
+ const cached = this.getRefracted(referencedElement, referencedElementType);
405
+ if (cached !== undefined) {
406
+ referencedElement = cached;
407
+ } else if ((0, _apidomNsOpenapi.isReferenceLikeElement)(referencedElement)) {
408
+ const sourceElement = referencedElement;
409
+ referencedElement = (0, _apidomNsOpenapi.refractReference)(referencedElement);
410
+ referencedElement.meta.set('referenced-element', referencedElementType);
411
+ this.setRefracted(sourceElement, referencedElementType, referencedElement);
412
+ } else {
413
+ const sourceElement = referencedElement;
414
+ referencedElement = (0, _apidomNsOpenapi.refract)(referencedElement, {
415
+ element: referencedElementType
416
+ });
417
+ this.setRefracted(sourceElement, referencedElementType, referencedElement);
418
+ }
419
+ }
420
+ const preferredName = this.baseName(referencedElement, field, jsonPointer, retrievalURI);
421
+ const componentName = this.uniqueName(preferredName, field);
422
+ const internalPointer = `#/components/${field}/${(0, _apidomJsonPointer.escape)(componentName)}`;
423
+ this.reportNameCollision(preferredName, componentName, field);
424
+
425
+ // reserve the assignment and component name before recursing so cyclic
426
+ // references terminate
427
+ this.assignments.set(canonicalKey, internalPointer);
428
+ if (!this.reservedNames.has(field)) this.reservedNames.set(field, new Set());
429
+ this.reservedNames.get(field).add(componentName);
430
+
431
+ // own a copy of the fragment and bundle its own external references
432
+ const hoistedElement = (0, _apidomDatamodel.cloneDeep)(referencedElement);
433
+ const visitor = new OpenAPI3_1BundleVisitor({
434
+ reference,
435
+ options: this.options,
436
+ assignments: this.assignments,
437
+ reservedNames: this.reservedNames,
438
+ refractCache: this.refractCache
439
+ });
440
+ const bundledElement = await (0, _apidomTraverse.traverseAsync)(hoistedElement, visitor, {
441
+ mutable: true
442
+ });
443
+
444
+ // annotate the hoisted fragment with info about its origin
445
+ if ((0, _apidomDatamodel.isElement)(bundledElement)) {
446
+ bundledElement.meta.set('ref-origin', reference.uri);
447
+ }
448
+
449
+ // place the bundled fragment into the entry document's components
450
+ this.ensureComponentsField(field).set(componentName, bundledElement);
451
+
452
+ // rewrite the referencing element to point at the hoisted fragment
453
+ referencingElement.set('$ref', internalPointer);
454
+ path.skip();
455
+ } catch (error) {
456
+ this.handleError(`Error while bundling Reference Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
457
+ path.skip();
458
+ }
459
+ }
460
+
461
+ /**
462
+ * Unlike OpenAPI 3.0 (which has no `components.pathItems` field and therefore
463
+ * inlines external Path Items in place), OpenAPI 3.1 hoists an external Path
464
+ * Item Object into `components.pathItems` and rewrites the referencing `$ref`
465
+ * to an internal pointer — mirroring how Reference Objects are bundled.
466
+ * Sibling fields next to the `$ref` (e.g. `summary`, `description`) are kept
467
+ * on the referencing element.
468
+ */
469
+ async PathItemElement(path) {
470
+ const pathItemElement = path.node;
471
+
472
+ // ignore Path Item Objects without a $ref field
473
+ if (!(0, _apidomDatamodel.isStringElement)(pathItemElement.$ref)) {
474
+ return;
475
+ }
476
+ const $ref = (0, _apidomCore.toValue)(pathItemElement.$ref);
477
+ const retrievalURI = this.toBaseURI($ref);
478
+ const isInternalReference = this.entryURI === retrievalURI;
479
+ const isExternalReference = !isInternalReference;
480
+ if (isInternalReference) {
481
+ // normalize self-references to a bare fragment so the bundled
482
+ // document stays transferable; bare fragments are left untouched
483
+ pathItemElement.set('$ref', this.normalizeSelfReference($ref));
484
+ path.skip();
485
+ return;
486
+ }
487
+
488
+ // honor the resolve.external switch
489
+ if (!this.options.resolve.external && isExternalReference) {
490
+ path.skip();
491
+ return;
492
+ }
493
+ const $refBaseURI = url.resolve(retrievalURI, $ref);
494
+ const jsonPointer = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference($refBaseURI);
495
+ const field = cf.pathItems.name;
496
+ const canonicalKey = `${field}\t${retrievalURI}#${jsonPointer}`;
497
+
498
+ // already hoisted (or being hoisted) — just rewrite the pointer. The
499
+ // assignment is reserved BEFORE recursing, so a circular Path Item chain
500
+ // terminates here with an internal pointer instead of recursing forever.
501
+ if (this.assignments.has(canonicalKey)) {
502
+ pathItemElement.set('$ref', this.assignments.get(canonicalKey));
503
+ path.skip();
504
+ return;
505
+ }
506
+ try {
507
+ // detect maximum depth of bundling
508
+ if (this.reference.depth >= this.options.bundle.maxDepth) {
509
+ throw new _MaximumBundleDepthError.default(`Maximum bundle depth of "${this.options.bundle.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
510
+ maxDepth: this.options.bundle.maxDepth,
511
+ uri: this.reference.uri
512
+ });
513
+ }
514
+ const reference = await this.toReference($ref);
515
+ let referencedElement = (0, _apidomJsonPointer.evaluate)(reference.value.result, jsonPointer);
516
+
517
+ // apply Path Item semantics to the referenced fragment
518
+ if (!(0, _apidomNsOpenapi.isPathItemElement)(referencedElement)) {
519
+ const cached = this.getRefracted(referencedElement, 'pathItem');
520
+ if (cached !== undefined) {
521
+ referencedElement = cached;
522
+ } else {
523
+ const sourceElement = referencedElement;
524
+ referencedElement = (0, _apidomNsOpenapi.refractPathItem)(referencedElement);
525
+ this.setRefracted(sourceElement, 'pathItem', referencedElement);
526
+ }
527
+ }
528
+ const preferredName = this.baseName(referencedElement, field, jsonPointer, retrievalURI);
529
+ const componentName = this.uniqueName(preferredName, field);
530
+ const internalPointer = `#/components/${field}/${(0, _apidomJsonPointer.escape)(componentName)}`;
531
+ this.reportNameCollision(preferredName, componentName, field);
532
+
533
+ // reserve the assignment and component name before recursing so cyclic
534
+ // references terminate
535
+ this.assignments.set(canonicalKey, internalPointer);
536
+ if (!this.reservedNames.has(field)) this.reservedNames.set(field, new Set());
537
+ this.reservedNames.get(field).add(componentName);
538
+
539
+ // own a copy of the fragment and bundle its own external references
540
+ const hoistedElement = (0, _apidomDatamodel.cloneDeep)(referencedElement);
541
+ const visitor = new OpenAPI3_1BundleVisitor({
542
+ reference,
543
+ options: this.options,
544
+ assignments: this.assignments,
545
+ reservedNames: this.reservedNames,
546
+ refractCache: this.refractCache
547
+ });
548
+ const bundledElement = await (0, _apidomTraverse.traverseAsync)(hoistedElement, visitor, {
549
+ mutable: true
550
+ });
551
+
552
+ // a `$ref` surviving on the hoisted Path Item means it pointed at another
553
+ // Path Item (a chain or cycle); it has already been rewritten to an
554
+ // internal `#/components/pathItems/...` pointer by the child traversal
555
+ bundledElement.meta.set('ref-origin', reference.uri);
556
+
557
+ // place the bundled Path Item into the entry document's components
558
+ this.ensureComponentsField(field).set(componentName, bundledElement);
559
+
560
+ // rewrite the referencing Path Item to point at the hoisted one, keeping
561
+ // any sibling fields (e.g. summary, description) next to the $ref
562
+ pathItemElement.set('$ref', internalPointer);
563
+ path.skip();
564
+ } catch (error) {
565
+ this.handleError(`Error while bundling Path Item Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, pathItemElement, '$ref', $ref, path);
566
+ path.skip();
567
+ }
568
+ }
569
+
570
+ /**
571
+ * Schema Objects in OpenAPI 3.1 are a JSON Schema 2020-12 dialect, so they are
572
+ * bundled per the JSON Schema Compound Document rules: the external schema
573
+ * RESOURCE is embedded verbatim into `components.schemas` (carrying its `$id`),
574
+ * and the referencing `$ref` is left UNCHANGED — it keeps resolving against the
575
+ * embedded resource's `$id`. This mirrors the canonical hyperjump
576
+ * `json-schema-bundle` behavior (the whole resource is embedded once, keyed by
577
+ * its `$id`; references are not rewritten).
578
+ */
579
+ async SchemaElement(path) {
580
+ const referencingElement = path.node;
581
+
582
+ // skip current referencing schema as $ref keyword was not defined
583
+ if (!(0, _apidomDatamodel.isStringElement)(referencingElement.$ref)) {
584
+ return;
585
+ }
586
+ const $ref = (0, _apidomCore.toValue)(referencingElement.$ref);
587
+ try {
588
+ // compute baseURI using rules around $id and $ref keywords. The current
589
+ // document's URI is the retrieval URI — derive it directly (not via
590
+ // toReference) so an internal $ref needs no resolution and never trips the
591
+ // resolve.maxDepth guard, matching how ReferenceElement returns early.
592
+ const retrievalURI = this.reference.uri;
593
+ const $refBaseURI = (0, _util.resolveSchema$refField)(retrievalURI, referencingElement);
594
+ const $refBaseURIStrippedHash = url.stripHash($refBaseURI);
595
+ const file = new _File.default({
596
+ uri: $refBaseURIStrippedHash
597
+ });
598
+ const isUnknownURI = (0, _ramda.none)(r => r.canRead(file), this.options.resolve.resolvers);
599
+ const isURL = !isUnknownURI;
600
+ const isInternalReference = url.stripHash(this.reference.uri) === $refBaseURIStrippedHash;
601
+ const isExternalReference = !isInternalReference;
602
+
603
+ // internal Schema Object $refs resolve against the in-document $id graph;
604
+ // leaving them untouched keeps that resolution valid. Unlike Reference
605
+ // Objects, a JSON Schema $ref is NOT normalized to a bare fragment.
606
+ if (isInternalReference) {
607
+ return;
608
+ }
609
+
610
+ // honor the resolve.external switch
611
+ if (!this.options.resolve.external && isExternalReference) {
612
+ return;
613
+ }
614
+
615
+ // detect maximum depth of bundling before fetching the external resource,
616
+ // matching ReferenceElement/PathItemElement (which check before toReference)
617
+ if (this.reference.depth >= this.options.bundle.maxDepth) {
618
+ throw new _MaximumBundleDepthError.default(`Maximum bundle depth of "${this.options.bundle.maxDepth}" has been exceeded in file "${this.reference.uri}"`, {
619
+ maxDepth: this.options.bundle.maxDepth,
620
+ uri: this.reference.uri
621
+ });
622
+ }
623
+
624
+ // locate the external schema resource the $ref targets, reusing the
625
+ // dereference strategy's classification. First try to resolve the target
626
+ // as a canonical URI / URL against the current document's $id graph; if
627
+ // that fails, fall back to fetching the external document and resolving
628
+ // the fragment there as a $anchor or JSON Pointer.
629
+ let schemaReference = this.reference;
630
+ try {
631
+ const referenceAsSchema = (0, _util.maybeRefractToSchemaElement)(schemaReference.value.result);
632
+ (0, _uri.evaluate)($refBaseURI, referenceAsSchema);
633
+ } catch (error) {
634
+ if (isURL && error instanceof _EvaluationJsonSchemaUriError.default) {
635
+ if ((0, _$anchor.isAnchor)((0, _$anchor.uriToAnchor)($refBaseURI))) {
636
+ schemaReference = await this.toReference(url.unsanitize($refBaseURI));
637
+ const selector = (0, _$anchor.uriToAnchor)($refBaseURI);
638
+ const referenceAsSchema = (0, _util.maybeRefractToSchemaElement)(schemaReference.value.result);
639
+ (0, _$anchor.evaluate)(selector, referenceAsSchema);
640
+ } else {
641
+ schemaReference = await this.toReference(url.unsanitize($refBaseURI));
642
+ const selector = _apidomJsonPointer.URIFragmentIdentifier.fromURIReference($refBaseURI);
643
+ const referenceAsSchema = (0, _util.maybeRefractToSchemaElement)(schemaReference.value.result);
644
+ (0, _apidomJsonPointer.evaluate)(referenceAsSchema, selector);
645
+ }
646
+ } else {
647
+ throw error;
648
+ }
649
+ }
650
+
651
+ // a $ref that resolves (by $id/$anchor/pointer) within the current document
652
+ // is internal even when its URI form (e.g. a URN or absolute $id) is not a
653
+ // bare fragment. Leave it untouched — it resolves against the in-document
654
+ // $id graph, and embedding the current document into itself would be wrong.
655
+ if (url.stripHash(schemaReference.uri) === url.stripHash(this.reference.uri)) {
656
+ return;
657
+ }
658
+
659
+ // the resource to embed is the WHOLE external document (its root schema),
660
+ // identified by its $id. A $ref into a fragment of the document embeds the
661
+ // entire document resource once; the fragment keeps resolving against the
662
+ // embedded $id.
663
+ const resourceRoot = (0, _util.maybeRefractToSchemaElement)(schemaReference.value.result);
664
+ const resourceBaseURI = (0, _util.resolveSchema$idField)(url.stripHash(schemaReference.uri), resourceRoot) ?? url.stripHash(schemaReference.uri);
665
+ const field = cf.schemas.name;
666
+ const canonicalKey = `${field}\t${resourceBaseURI}`;
667
+
668
+ // resource already embedded (or being embedded) — leave the referencing
669
+ // $ref untouched and stop. This also terminates circular external schema
670
+ // references, since the assignment is reserved BEFORE recursion.
671
+ if (this.assignments.has(canonicalKey)) {
672
+ path.skip();
673
+ return;
674
+ }
675
+
676
+ // own a copy of the resource and ensure it carries a $id so the unchanged
677
+ // $ref still resolves against it once embedded
678
+ const embeddedElement = (0, _apidomDatamodel.cloneDeep)(resourceRoot);
679
+ if (!(0, _apidomDatamodel.isStringElement)(embeddedElement.$id)) {
680
+ embeddedElement.set('$id', resourceBaseURI);
681
+ }
682
+
683
+ // the embedded thing is the WHOLE resource (keyed by its $id), so its name
684
+ // is derived from the resource URI, not the $ref fragment — passing a root
685
+ // pointer makes baseName fall back to the resource basename
686
+ const preferredName = this.baseName(embeddedElement, field, '', resourceBaseURI);
687
+ const componentName = this.uniqueName(preferredName, field);
688
+ this.reportNameCollision(preferredName, componentName, field);
689
+
690
+ // reserve the assignment and component name before recursing so circular
691
+ // external schema references terminate
692
+ this.assignments.set(canonicalKey, `#/components/${field}/${(0, _apidomJsonPointer.escape)(componentName)}`);
693
+ if (!this.reservedNames.has(field)) this.reservedNames.set(field, new Set());
694
+ this.reservedNames.get(field).add(componentName);
695
+
696
+ // bundle external references contained within the embedded resource;
697
+ // nested external resources land flat in the same components.schemas
698
+ const visitor = new OpenAPI3_1BundleVisitor({
699
+ reference: schemaReference,
700
+ options: this.options,
701
+ assignments: this.assignments,
702
+ reservedNames: this.reservedNames,
703
+ refractCache: this.refractCache
704
+ });
705
+ const bundledElement = await (0, _apidomTraverse.traverseAsync)(embeddedElement, visitor, {
706
+ mutable: true
707
+ });
708
+
709
+ // annotate the embedded resource with info about its origin
710
+ bundledElement.meta.set('ref-origin', schemaReference.uri);
711
+
712
+ // place the embedded resource into the entry document's components
713
+ this.ensureComponentsField(field).set(componentName, bundledElement);
714
+
715
+ // the referencing $ref is left UNCHANGED — it resolves against the
716
+ // embedded resource's $id
717
+ path.skip();
718
+ } catch (error) {
719
+ this.handleError(`Error while bundling Schema Object. Cannot resolve $ref "${$ref}": ${error.message}`, error, referencingElement, '$ref', $ref, path);
720
+ path.skip();
721
+ }
722
+ }
723
+
724
+ /**
725
+ * Example Object `externalValue` points at arbitrary external content that
726
+ * has no place in the Components Object. The referenced value is inlined into
727
+ * the Example's `value` field.
728
+ */
729
+ async ExampleElement(path) {
730
+ const exampleElement = path.node;
731
+
732
+ // ignore Example Objects without an externalValue field
733
+ if (!(0, _apidomDatamodel.isStringElement)(exampleElement.externalValue)) {
734
+ return;
735
+ }
736
+
737
+ // value and externalValue fields are mutually exclusive
738
+ if (exampleElement.hasKey('value') && (0, _apidomDatamodel.isStringElement)(exampleElement.externalValue)) {
739
+ throw new _apidomError.ApiDOMStructuredError('ExampleElement value and externalValue fields are mutually exclusive', {
740
+ value: (0, _apidomCore.toValue)(exampleElement.value),
741
+ externalValue: (0, _apidomCore.toValue)(exampleElement.externalValue)
742
+ });
743
+ }
744
+ const externalValue = (0, _apidomCore.toValue)(exampleElement.externalValue);
745
+ const retrievalURI = this.toBaseURI(externalValue);
746
+ const isInternalReference = this.entryURI === retrievalURI;
747
+ const isExternalReference = !isInternalReference;
748
+
749
+ // honor the resolve.external switch
750
+ if (!this.options.resolve.external && isExternalReference) {
751
+ return;
752
+ }
753
+ try {
754
+ const reference = await this.toReference(externalValue);
755
+ const valueElement = (0, _apidomDatamodel.cloneShallow)(reference.value.result);
756
+ valueElement.meta.set('ref-origin', reference.uri);
757
+ const exampleElementCopy = (0, _apidomDatamodel.cloneShallow)(exampleElement);
758
+ exampleElementCopy.value = valueElement;
759
+ exampleElementCopy.remove('externalValue');
760
+ path.replaceWith(exampleElementCopy);
761
+ } catch (error) {
762
+ this.handleError(`Error while bundling Example Object. Cannot resolve externalValue "${externalValue}": ${error.message}`, error, exampleElement, 'externalValue', externalValue, path);
763
+ }
764
+ }
765
+
766
+ /**
767
+ * Link Object `operationRef` points at an Operation Object, which has no
768
+ * Components Object field in OpenAPI 3.1 and therefore cannot be hoisted or
769
+ * inlined. To keep the link resolvable from the bundled document, an external
770
+ * `operationRef` is rewritten to its absolute URI. Internal `operationRef`
771
+ * values and `operationId` links are left untouched.
772
+ */
773
+ async LinkElement(path) {
774
+ const linkElement = path.node;
775
+
776
+ // operationRef and operationId fields are mutually exclusive
777
+ if ((0, _apidomDatamodel.isStringElement)(linkElement.operationRef) && (0, _apidomDatamodel.isStringElement)(linkElement.operationId)) {
778
+ throw new _apidomError.ApiDOMStructuredError('LinkElement operationRef and operationId fields are mutually exclusive', {
779
+ operationRef: (0, _apidomCore.toValue)(linkElement.operationRef),
780
+ operationId: (0, _apidomCore.toValue)(linkElement.operationId)
781
+ });
782
+ }
783
+
784
+ // only external operationRef links need adjusting
785
+ if (!(0, _apidomDatamodel.isStringElement)(linkElement.operationRef)) {
786
+ return;
787
+ }
788
+ const operationRef = (0, _apidomCore.toValue)(linkElement.operationRef);
789
+ const retrievalURI = this.toBaseURI(operationRef);
790
+ const isInternalReference = this.entryURI === retrievalURI;
791
+ if (isInternalReference) {
792
+ // normalize a self-reference operationRef to a bare fragment so the bundled
793
+ // document stays transferable; bare fragments are left untouched
794
+ linkElement.set('operationRef', this.normalizeSelfReference(operationRef));
795
+ return;
796
+ }
797
+
798
+ // honor the resolve.external switch
799
+ if (!this.options.resolve.external) {
800
+ return;
801
+ }
802
+
803
+ // rewrite to an absolute URI so the link keeps resolving once the document
804
+ // is treated as self-contained
805
+ const absoluteURI = url.resolve(this.reference.uri, operationRef);
806
+ if (absoluteURI !== operationRef) {
807
+ linkElement.set('operationRef', absoluteURI);
808
+ }
809
+ }
810
+ }
811
+ var _default = exports.default = OpenAPI3_1BundleVisitor;