From cb67b587267e2db9b8512eeb5b821220010b93ba Mon Sep 17 00:00:00 2001 From: quobix Date: Sun, 29 Nov 2026 15:05:15 -0500 Subject: [PATCH 1/4] refactor(bundler): share the composed bundling pipeline --- bundler/bundler.go | 121 +++++---------------------------------------- 1 file changed, 13 insertions(+), 108 deletions(-) diff --git a/bundler/bundler.go b/bundler/bundler.go index ffca4070..85e55328 100644 --- a/bundler/bundler.go +++ b/bundler/bundler.go @@ -478,8 +478,19 @@ func BundleDocumentComposedWithOrigins(model *v3.Document, compositionConfig *Bu return composeWithOrigins(model, compositionConfig) } -// composeWithOrigins performs composed bundling and returns origin tracking information +func compose(model *v3.Document, compositionConfig *BundleCompositionConfig) ([]byte, error) { + result, err := composeDocument(model, compositionConfig, nil) + if result == nil { + return nil, err + } + return result.Bytes, err +} + func composeWithOrigins(model *v3.Document, compositionConfig *BundleCompositionConfig) (*BundleResult, error) { + return composeDocument(model, compositionConfig, make(ComponentOriginMap)) +} + +func composeDocument(model *v3.Document, compositionConfig *BundleCompositionConfig, origins ComponentOriginMap) (*BundleResult, error) { if compositionConfig == nil { compositionConfig = &BundleCompositionConfig{ Delimiter: "__", @@ -520,7 +531,7 @@ func composeWithOrigins(model *v3.Document, compositionConfig *BundleComposition refMap: orderedmap.New[string, *processRef](), compositionConfig: compositionConfig, discriminatorMappings: discriminatorMappings, - origins: make(ComponentOriginMap), + origins: origins, } // Enqueue mapping targets after cf exists; root-local #/ refs stay in place. @@ -590,112 +601,6 @@ func composeWithOrigins(model *v3.Document, compositionConfig *BundleComposition return result, errors.Join(errs...) } -func compose(model *v3.Document, compositionConfig *BundleCompositionConfig) ([]byte, error) { - if compositionConfig == nil { - compositionConfig = &BundleCompositionConfig{ - Delimiter: "__", - } - } else { - if compositionConfig.Delimiter == "" { - compositionConfig.Delimiter = "__" - } - if strings.Contains(compositionConfig.Delimiter, "#") || - strings.Contains(compositionConfig.Delimiter, "/") { - return nil, errors.New("composition delimiter cannot contain '#' or '/' characters") - } - if strings.Contains(compositionConfig.Delimiter, " ") { - return nil, errors.New("composition delimiter cannot contain spaces") - } - } - - if model == nil || model.Rolodex == nil { - return nil, errors.New("model or rolodex is nil") - } - - rolodex := model.Rolodex - indexes := rolodex.GetIndexes() - rootIndex := rolodex.GetRootIndex() - if err := validateDiscriminatorMappings(rolodex); err != nil { - return nil, err - } - - // Collect discriminator mappings before ref processing so mapping-only targets can be composed. - discriminatorMappings := collectDiscriminatorMappingNodesWithContext(rolodex) - - cf := &handleIndexConfig{ - idx: rootIndex, - rootIdx: rootIndex, - model: model, - indexes: indexes, - seen: sync.Map{}, - refMap: orderedmap.New[string, *processRef](), - compositionConfig: compositionConfig, - discriminatorMappings: discriminatorMappings, - origins: make(ComponentOriginMap), - } - - // Enqueue mapping targets after cf exists; root-local #/ refs stay in place. - enqueueDiscriminatorMappingTargets(discriminatorMappings, cf, rootIndex) - // Refresh indexes in case mapping resolution loaded new ones. - cf.indexes = rolodex.GetIndexes() - if err := validateDiscriminatorMappings(rolodex); err != nil { - return nil, err - } - - if err := handleIndex(cf); err != nil { - return nil, err - } - if err := handleDiscriminatorMappingIndexes(cf, rootIndex, rolodex); err != nil { - return nil, err - } - rewriteExtensionRefsForComposedBundle(rolodex) - - processedNodes := orderedmap.New[string, *processRef]() - var errs []error - for _, ref := range cf.refMap.FromOldest() { - err := processReference(model, ref, cf) - errs = append(errs, err) - processedNodes.Set(ref.mapKey, ref) - if ref.ref != nil && ref.mapKey != ref.ref.FullDefinition { - processedNodes.Set(ref.ref.FullDefinition, ref) - } - } - - slices.SortFunc(indexes, func(i, j *index.SpecIndex) int { - if i.GetSpecAbsolutePath() < j.GetSpecAbsolutePath() { - return 1 - } - return 0 - }) - - // Remap indexed refs. - remapIndex(rootIndex, processedNodes) - - for _, idx := range indexes { - remapIndex(idx, processedNodes) - } - - // Update discriminator mapping values after component names are final. - updateDiscriminatorMappingsComposed(discriminatorMappings, processedNodes, rolodex) - - // Inline anything that could not be recomposed. - inlinedPaths := inlineRequiredRefs(cf.inlineRequired, rolodex) - - // Rewrite any remaining unindexed refs after mapping resolution loads new indexes. - allLoadedIndexes := rolodex.GetIndexes() - rewriteAllRefs(rootIndex, processedNodes, rolodex) - for _, idx := range allLoadedIndexes { - rewriteAllRefs(idx, processedNodes, rolodex) - } - - rewriteInlinedAbsoluteRefs(rolodex, allLoadedIndexes, inlinedPaths) - - b, err := renderBundledModel(model, rootIndex) - errs = append(errs, err) - - return b, errors.Join(errs...) -} - // rewriteInlinedAbsoluteRefs updates absolute $ref values that were resolved by // the inline fallback after the index's normal rewrite pass has already run. func rewriteInlinedAbsoluteRefs(rolodex *index.Rolodex, indexes []*index.SpecIndex, inlinedPaths map[string]*yaml.Node) { From 556520fe9ab863e01f25f23858927eddf0b78885 Mon Sep 17 00:00:00 2001 From: quobix Date: Sun, 29 Nov 2026 15:22:30 -0500 Subject: [PATCH 2/4] fix(bundler): follow only reachable external fragments --- bundler/bundler.go | 187 ++++++-------- bundler/bundler_composer.go | 154 ++---------- bundler/bundler_composer_test.go | 28 +-- bundler/bundler_issue873_test.go | 77 +++--- bundler/composed_fragments.go | 381 +++++++++++++++++++++++++++++ bundler/composed_fragments_test.go | 309 +++++++++++++++++++++++ bundler/composer_functions.go | 10 +- bundler/composer_functions_test.go | 22 +- 8 files changed, 850 insertions(+), 318 deletions(-) create mode 100644 bundler/composed_fragments.go create mode 100644 bundler/composed_fragments_test.go diff --git a/bundler/bundler.go b/bundler/bundler.go index 85e55328..cc48c318 100644 --- a/bundler/bundler.go +++ b/bundler/bundler.go @@ -12,7 +12,6 @@ import ( "path/filepath" "slices" "strings" - "sync" "github.com/pb33f/go-yaml" @@ -39,34 +38,9 @@ func renderBundledModel(model *v3.Document, rootIndex *index.SpecIndex) ([]byte, return model.Render() } -func validateDiscriminatorMappings(rolodex *index.Rolodex) error { - if rolodex == nil { - return nil - } - - if err := validateDiscriminatorMappingsFromIndex(rolodex.GetRootIndex()); err != nil { - return err - } - for _, idx := range rolodex.GetIndexes() { - if err := validateDiscriminatorMappingsFromIndex(idx); err != nil { - return err - } - } - return nil -} +type discriminatorVisitor func(*yaml.Node) error -func validateDiscriminatorMappingsFromIndex(idx *index.SpecIndex) error { - if idx == nil { - return nil - } - return validateDiscriminatorMappingsFromNode(idx.GetRootNode()) -} - -func validateDiscriminatorMappingsFromNode(n *yaml.Node) error { - return validateDiscriminatorMappingsFromRootNode(n, make(map[*yaml.Node]struct{})) -} - -func validateDiscriminatorMappingsFromRootNode(n *yaml.Node, seen map[*yaml.Node]struct{}) error { +func (visit discriminatorVisitor) root(n *yaml.Node, seen map[*yaml.Node]struct{}) error { n = discriminatorValidationNode(n) if n == nil { return nil @@ -75,13 +49,13 @@ func validateDiscriminatorMappingsFromRootNode(n *yaml.Node, seen map[*yaml.Node switch n.Kind { case yaml.MappingNode: if !isOpenAPIDocumentRoot(n) && isDiscriminatorValidationSchemaCandidate(n) { - return validateDiscriminatorMappingsFromSchemaNode(n, seen) + return visit.schema(n, seen) } - if err := validateDiscriminatorMappingsFromOpenAPIObject(n, seen, make(map[*yaml.Node]struct{}), nil); err != nil { + if err := visit.object(n, seen, make(map[*yaml.Node]struct{}), nil); err != nil { return err } if isDiscriminatorValidationSchemaCandidate(n) { - return validateDiscriminatorMappingsFromSchemaNode(n, seen) + return visit.schema(n, seen) } } return nil @@ -92,8 +66,9 @@ func isOpenAPIDocumentRoot(n *yaml.Node) bool { if n == nil || n.Kind != yaml.MappingNode { return false } - for i := 0; i < len(n.Content); i += 2 { - keyNode := utils.NodeAlias(n.Content[i]) + content := utils.ResolveMergeNodes(n).Content + for i := 0; i < len(content); i += 2 { + keyNode := utils.NodeAlias(content[i]) if keyNode == nil { continue } @@ -112,7 +87,7 @@ func discriminatorValidationNode(n *yaml.Node) *yaml.Node { return n } -func validateDiscriminatorMappingsFromOpenAPIObject(n *yaml.Node, schemaSeen, objectSeen map[*yaml.Node]struct{}, path []string) error { +func (visit discriminatorVisitor) object(n *yaml.Node, schemaSeen, objectSeen map[*yaml.Node]struct{}, path []string) error { n = discriminatorValidationNode(n) if n == nil { return nil @@ -125,14 +100,15 @@ func validateDiscriminatorMappingsFromOpenAPIObject(n *yaml.Node, schemaSeen, ob switch n.Kind { case yaml.SequenceNode: for _, c := range n.Content { - if err := validateDiscriminatorMappingsFromOpenAPIObject(c, schemaSeen, objectSeen, path); err != nil { + if err := visit.object(c, schemaSeen, objectSeen, path); err != nil { return err } } case yaml.MappingNode: - for i := 0; i < len(n.Content); i += 2 { - keyNode := utils.NodeAlias(n.Content[i]) - valueNode := utils.NodeAlias(n.Content[i+1]) + content := utils.ResolveMergeNodes(n).Content + for i := 0; i < len(content); i += 2 { + keyNode := utils.NodeAlias(content[i]) + valueNode := utils.NodeAlias(content[i+1]) if keyNode == nil || valueNode == nil { continue } @@ -143,24 +119,24 @@ func validateDiscriminatorMappingsFromOpenAPIObject(n *yaml.Node, schemaSeen, ob switch { case key == lowbase.SchemaLabel: - if err := validateDiscriminatorMappingsFromSchemaNode(valueNode, schemaSeen); err != nil { + if err := visit.schema(valueNode, schemaSeen); err != nil { return err } continue case key == "schemas" && (len(path) == 0 || path[len(path)-1] == "components"): - if err := validateDiscriminatorMappingsFromSchemaMap(valueNode, schemaSeen); err != nil { + if err := visit.schemaMap(valueNode, schemaSeen); err != nil { return err } continue case key == "definitions" && len(path) == 0: - if err := validateDiscriminatorMappingsFromSchemaMap(valueNode, schemaSeen); err != nil { + if err := visit.schemaMap(valueNode, schemaSeen); err != nil { return err } continue } if valueNode.Kind == yaml.MappingNode || valueNode.Kind == yaml.SequenceNode { - if err := validateDiscriminatorMappingsFromOpenAPIObject(valueNode, schemaSeen, objectSeen, append(path, key)); err != nil { + if err := visit.object(valueNode, schemaSeen, objectSeen, append(path, key)); err != nil { return err } } @@ -175,7 +151,7 @@ func shouldSkipDiscriminatorValidationOpenAPIValue(key string) bool { strings.HasPrefix(key, "x-") } -func validateDiscriminatorMappingsFromSchemaNode(n *yaml.Node, seen map[*yaml.Node]struct{}) error { +func (visit discriminatorVisitor) schema(n *yaml.Node, seen map[*yaml.Node]struct{}) error { n = discriminatorValidationNode(n) if n == nil || n.Kind != yaml.MappingNode { return nil @@ -185,28 +161,29 @@ func validateDiscriminatorMappingsFromSchemaNode(n *yaml.Node, seen map[*yaml.No } seen[n] = struct{}{} - for i := 0; i < len(n.Content); i += 2 { - keyNode := utils.NodeAlias(n.Content[i]) - valueNode := utils.NodeAlias(n.Content[i+1]) + content := utils.ResolveMergeNodes(n).Content + for i := 0; i < len(content); i += 2 { + keyNode := utils.NodeAlias(content[i]) + valueNode := utils.NodeAlias(content[i+1]) if keyNode == nil || valueNode == nil { continue } key := keyNode.Value switch { case key == lowbase.DiscriminatorLabel: - if err := lowbase.ValidateDiscriminatorMappingValueNodes(valueNode); err != nil { + if err := visit(valueNode); err != nil { return err } case isDirectSchemaChildKey(key): - if err := validateDiscriminatorMappingsFromSchemaNode(valueNode, seen); err != nil { + if err := visit.schema(valueNode, seen); err != nil { return err } case isSchemaMapChildKey(key): - if err := validateDiscriminatorMappingsFromSchemaMap(valueNode, seen); err != nil { + if err := visit.schemaMap(valueNode, seen); err != nil { return err } case isSchemaArrayChildKey(key): - if err := validateDiscriminatorMappingsFromSchemaArray(valueNode, seen); err != nil { + if err := visit.schemaArray(valueNode, seen); err != nil { return err } } @@ -214,26 +191,27 @@ func validateDiscriminatorMappingsFromSchemaNode(n *yaml.Node, seen map[*yaml.No return nil } -func validateDiscriminatorMappingsFromSchemaMap(n *yaml.Node, seen map[*yaml.Node]struct{}) error { +func (visit discriminatorVisitor) schemaMap(n *yaml.Node, seen map[*yaml.Node]struct{}) error { n = discriminatorValidationNode(n) if n == nil || n.Kind != yaml.MappingNode { return nil } - for i := 1; i < len(n.Content); i += 2 { - if err := validateDiscriminatorMappingsFromSchemaNode(n.Content[i], seen); err != nil { + content := utils.ResolveMergeNodes(n).Content + for i := 1; i < len(content); i += 2 { + if err := visit.schema(content[i], seen); err != nil { return err } } return nil } -func validateDiscriminatorMappingsFromSchemaArray(n *yaml.Node, seen map[*yaml.Node]struct{}) error { +func (visit discriminatorVisitor) schemaArray(n *yaml.Node, seen map[*yaml.Node]struct{}) error { n = discriminatorValidationNode(n) if n == nil || n.Kind != yaml.SequenceNode { return nil } for _, c := range n.Content { - if err := validateDiscriminatorMappingsFromSchemaNode(c, seen); err != nil { + if err := visit.schema(c, seen); err != nil { return err } } @@ -245,8 +223,9 @@ func isDiscriminatorValidationSchemaCandidate(n *yaml.Node) bool { if n == nil || n.Kind != yaml.MappingNode { return false } - for i := 0; i < len(n.Content); i += 2 { - keyNode := utils.NodeAlias(n.Content[i]) + content := utils.ResolveMergeNodes(n).Content + for i := 0; i < len(content); i += 2 { + keyNode := utils.NodeAlias(content[i]) if keyNode == nil { continue } @@ -355,7 +334,7 @@ func BundleBytes(bytes []byte, configuration *datamodel.DocumentConfiguration) ( // BundleBytesComposed will take a byte slice of an OpenAPI specification and return a composed bundled version of it. // this is the same as BundleBytes, but it will compose the bundling instead of inline it. // -// Composed means that every external file will have references lifted out and added to the `components` section of the document. +// Composition lifts external targets reachable from the root into its `components` section. // Names will be preserved where possible, conflicts will dealt with by using a delimiter and appending a number. func BundleBytesComposed(bytes []byte, configuration *datamodel.DocumentConfiguration, compositionConfig *BundleCompositionConfig) ([]byte, error) { doc, err := libopenapi.NewDocumentWithConfiguration(bytes, configuration) @@ -459,7 +438,7 @@ type BundleInlineConfig struct { } // BundleDocumentComposed will take a v3.Document and return a composed bundled version of it. Composed means -// that every external file will have references lifted out and added to the `components` section of the document. +// that external targets reachable from the root are lifted into its `components` section. // Names will be preserved where possible, conflicts will be appended with a number. If the type of the reference cannot // be determined, it will be added to the `components` section as a `Schema` type, a warning will be logged. // The document model will be mutated permanently. @@ -513,39 +492,15 @@ func composeDocument(model *v3.Document, compositionConfig *BundleCompositionCon } rolodex := model.Rolodex - indexes := rolodex.GetIndexes() rootIndex := rolodex.GetRootIndex() - if err := validateDiscriminatorMappings(rolodex); err != nil { - return nil, err - } - - // Collect discriminator mappings before ref processing so mapping-only targets can be composed. - discriminatorMappings := collectDiscriminatorMappingNodesWithContext(rolodex) - - cf := &handleIndexConfig{ - idx: rootIndex, - rootIdx: rootIndex, - model: model, - indexes: indexes, - seen: sync.Map{}, - refMap: orderedmap.New[string, *processRef](), - compositionConfig: compositionConfig, - discriminatorMappings: discriminatorMappings, - origins: origins, - } - - // Enqueue mapping targets after cf exists; root-local #/ refs stay in place. - enqueueDiscriminatorMappingTargets(discriminatorMappings, cf, rootIndex) - // Refresh indexes in case mapping resolution loaded new ones. - cf.indexes = rolodex.GetIndexes() - if err := validateDiscriminatorMappings(rolodex); err != nil { - return nil, err - } - - if err := handleIndex(cf); err != nil { - return nil, err - } - if err := handleDiscriminatorMappingIndexes(cf, rootIndex, rolodex); err != nil { + cf := &compositionContext{ + rootIdx: rootIndex, + refMap: orderedmap.New[string, *processRef](), + compositionConfig: compositionConfig, + origins: origins, + } + reachable := make(map[*index.Reference]*processRef) + if err := collectComposedReferences(cf, rolodex, reachable); err != nil { return nil, err } rewriteExtensionRefsForComposedBundle(rolodex) @@ -561,6 +516,8 @@ func composeDocument(model *v3.Document, compositionConfig *BundleCompositionCon } } + // Mapping-only targets can load more indexes during discovery. + indexes := slices.Clone(rolodex.GetIndexes()) slices.SortFunc(indexes, func(i, j *index.SpecIndex) int { if i.GetSpecAbsolutePath() < j.GetSpecAbsolutePath() { return 1 @@ -569,14 +526,14 @@ func composeDocument(model *v3.Document, compositionConfig *BundleCompositionCon }) // Remap indexed refs. - remapIndex(rootIndex, processedNodes) + remapIndex(rootIndex, processedNodes, reachable) for _, idx := range indexes { - remapIndex(idx, processedNodes) + remapIndex(idx, processedNodes, reachable) } // Update discriminator mapping values after component names are final. - updateDiscriminatorMappingsComposed(discriminatorMappings, processedNodes, rolodex) + updateDiscriminatorMappingsComposed(cf.discriminatorMappings, processedNodes, rolodex) // Inline anything that could not be recomposed. inlinedPaths := inlineRequiredRefs(cf.inlineRequired, rolodex) @@ -985,6 +942,12 @@ func collectDiscriminatorMappingNodesWithContext(rolodex *index.Rolodex) []*disc // collectDiscriminatorMappingNodesFromIndexWithContext recursively walks a YAML node tree // to find discriminator mapping nodes, preserving the source index context. func collectDiscriminatorMappingNodesFromIndexWithContext(idx *index.SpecIndex, n *yaml.Node, mappings *[]*discriminatorMappingWithContext) { + walkDiscriminatorMappingNodes(n, func(value *yaml.Node) { + *mappings = append(*mappings, &discriminatorMappingWithContext{node: value, sourceIdx: idx}) + }) +} + +func walkDiscriminatorMappingNodes(n *yaml.Node, yield func(*yaml.Node)) { if n.Kind == yaml.DocumentNode && len(n.Content) > 0 { n = n.Content[0] } @@ -992,7 +955,7 @@ func collectDiscriminatorMappingNodesFromIndexWithContext(idx *index.SpecIndex, switch n.Kind { case yaml.SequenceNode: for _, c := range n.Content { - collectDiscriminatorMappingNodesFromIndexWithContext(idx, c, mappings) + walkDiscriminatorMappingNodes(c, yield) } return case yaml.MappingNode: @@ -1008,23 +971,27 @@ func collectDiscriminatorMappingNodesFromIndexWithContext(idx *index.SpecIndex, case "discriminator": discriminator = v } - collectDiscriminatorMappingNodesFromIndexWithContext(idx, v, mappings) + walkDiscriminatorMappingNodes(v, yield) } - if discriminator != nil && discriminator.Kind == yaml.MappingNode { - for i := 0; i < len(discriminator.Content); i += 2 { - if discriminator.Content[i].Value == "mapping" { - mappingNode := discriminator.Content[i+1] - if mappingNode.Kind != yaml.MappingNode { - continue - } - for j := 0; j < len(mappingNode.Content); j += 2 { - *mappings = append(*mappings, &discriminatorMappingWithContext{ - node: mappingNode.Content[j+1], - sourceIdx: idx, - }) - } - } + visitDiscriminatorMappingValues(discriminator, yield) +} + +func visitDiscriminatorMappingValues(discriminator *yaml.Node, yield func(*yaml.Node)) { + discriminator = utils.ResolveMergeNodes(discriminator) + if discriminator == nil || discriminator.Kind != yaml.MappingNode { + return + } + for i := 0; i+1 < len(discriminator.Content); i += 2 { + if discriminator.Content[i].Value != "mapping" { + continue + } + mapping := utils.ResolveMergeNodes(discriminator.Content[i+1]) + if mapping == nil || mapping.Kind != yaml.MappingNode { + continue + } + for j := 1; j < len(mapping.Content); j += 2 { + yield(utils.NodeAlias(mapping.Content[j])) } } } diff --git a/bundler/bundler_composer.go b/bundler/bundler_composer.go index cb5f7ef4..b1440cdf 100644 --- a/bundler/bundler_composer.go +++ b/bundler/bundler_composer.go @@ -5,11 +5,9 @@ package bundler import ( "context" - "fmt" "net/url" "path/filepath" "strings" - "sync" "github.com/pb33f/go-yaml" v3 "github.com/pb33f/libopenapi/datamodel/high/v3" @@ -39,104 +37,19 @@ type discriminatorMappingWithContext struct { node *yaml.Node // The YAML node containing the mapping value sourceIdx *index.SpecIndex // The index where the mapping was found canonicalKey string // ref.FullDefinition captured before bundling mutates refs + target *processRef targetIdx *index.SpecIndex // The index where the resolved ref actually lives (may differ from sourceIdx) } -type handleIndexConfig struct { - idx *index.SpecIndex +type compositionContext struct { rootIdx *index.SpecIndex - model *v3.Document - indexes []*index.SpecIndex refMap *orderedmap.Map[string, *processRef] - seen sync.Map inlineRequired []*processRef compositionConfig *BundleCompositionConfig discriminatorMappings []*discriminatorMappingWithContext // mapping nodes with source context origins ComponentOriginMap // component origins for navigation } -// handleIndex will recursively explore the indexes and their references, building a map of references -// to be processed later. It will also check for circular references and avoid infinite loops. -// everything is stored in the handleIndexConfig, which is passed around to avoid passing too many parameters. -func handleIndex(c *handleIndexConfig) error { - mappedReferences := c.idx.GetMappedReferences() - sequencedReferences := c.idx.GetRawReferencesSequenced() - var indexesToExplore []*index.SpecIndex - - for _, sequenced := range sequencedReferences { - if sequenced.IsExtensionRef { - continue - } - mappedReference := mappedReferences[sequenced.FullDefinition] - if mappedReference == nil { - mappedReference, _ = c.idx.SearchIndexForReference(sequenced.FullDefinition) - } - - // Check for invalid sibling properties if strict validation is enabled - if c.compositionConfig.StrictValidation && - c.idx.GetConfig().SpecInfo.VersionNumeric == 3.0 && - sequenced.HasSiblingProperties { - siblingKeys := make([]string, 0, len(sequenced.SiblingProperties)) - for key := range sequenced.SiblingProperties { - siblingKeys = append(siblingKeys, key) - } - return fmt.Errorf("invalid OpenAPI 3.0 specification: $ref cannot have sibling properties. Found $ref '%s' with siblings %v at line %d, column %d", - sequenced.FullDefinition, siblingKeys, sequenced.Node.Line, sequenced.Node.Column) - } - - // if we're in the root document, don't bundle anything. - refExp := strings.Split(sequenced.FullDefinition, "#/") - var foundIndex *index.SpecIndex - - // make sure to use the correct index. - // https://github.com/pb33f/libopenapi/issues/397 - for _, i := range c.indexes { - if i.GetSpecAbsolutePath() == refExp[0] { - foundIndex = i - if mappedReference != nil && !mappedReference.Circular { - - lookup := sequenced.FullDefinition - mr := i.FindComponent(context.Background(), lookup) - if mr != nil { - // Use the component from the matching index. - mappedReference = mr - break - } - } - } - } - refMapKey := processRefMapKey(mappedReference, sequenced) - if foundIndex != nil && mappedReference != nil { - // Avoid recomposing components that resolve back to the root document. - if c.rootIdx != nil && foundIndex.GetSpecAbsolutePath() == c.rootIdx.GetSpecAbsolutePath() { - continue - } - // Store the reference to be composed in the root. - if kk := c.refMap.GetOrZero(refMapKey); kk == nil { - c.refMap.Set(refMapKey, &processRef{ - idx: foundIndex, - ref: mappedReference, - seqRef: sequenced, - mapKey: refMapKey, - name: mappedReference.Name, - }) - } - if _, ok := c.seen.Load(foundIndex.GetSpecAbsolutePath()); !ok { - c.seen.Store(foundIndex.GetSpecAbsolutePath(), mappedReference) // TODO: replace with map. - indexesToExplore = append(indexesToExplore, foundIndex) - } - } - } - - for _, idx := range indexesToExplore { - c.idx = idx - if err := handleIndex(c); err != nil { - return err - } - } - return nil -} - // openAPIRootKeys contains known OpenAPI root-level keys that should NOT be // recomposed as components. OpenAPI root keys are always lowercase per spec. // Package-level to avoid allocation on each call. @@ -177,7 +90,7 @@ func rootSupportsMediaTypeComponents(rootIdx *index.SpecIndex) bool { // processReference will extract a reference from the current index, and transform it into a first class // top-level component in the root OpenAPI document. -func processReference(model *v3.Document, pr *processRef, cf *handleIndexConfig) error { +func processReference(model *v3.Document, pr *processRef, cf *compositionContext) error { idx := pr.idx var components *v3.Components var err error @@ -222,8 +135,8 @@ func processReference(model *v3.Document, pr *processRef, cf *handleIndexConfig) } } - unknown := func(procRef *processRef, config *handleIndexConfig) { - if l := config.idx.GetLogger(); l != nil { + unknown := func(procRef *processRef, config *compositionContext) { + if l := config.rootIdx.GetLogger(); l != nil { l.Warn("[bundler] unable to compose reference, not sure where it goes.", "$ref", procRef.ref.FullDefinition) } // no idea what do with this, so we will inline it. @@ -354,9 +267,10 @@ func isOpenAPIComponentNameChar(r rune) bool { // This handles cases where a schema is ONLY referenced via discriminator mapping. func enqueueDiscriminatorMappingTargets( mappings []*discriminatorMappingWithContext, - cf *handleIndexConfig, + cf *compositionContext, rootIdx *index.SpecIndex, -) { +) []*processRef { + var targets []*processRef for _, mapping := range mappings { refValue := mapping.node.Value @@ -389,6 +303,21 @@ func enqueueDiscriminatorMappingTargets( continue } + // Lookup may return the relative spelling from the source document. Qualify + // it with the resolved file before deduplicating across mapping sources. + if foundIdx != nil { + _, fragment, hasFragment := strings.Cut(ref.FullDefinition, "#/") + full := foundIdx.GetSpecAbsolutePath() + if hasFragment { + full += "#/" + fragment + } + if full != "" && full != ref.FullDefinition { + resolved := *ref + resolved.FullDefinition = full + ref = &resolved + } + } + // Cache the canonical key and target index before bundling mutates refs. mapping.canonicalKey = ref.FullDefinition mapping.targetIdx = foundIdx @@ -397,7 +326,7 @@ func enqueueDiscriminatorMappingTargets( // Skip targets already queued for composition. if existing := cf.refMap.GetOrZero(mapKey); existing != nil { - existing.fromDiscriminator = true + mapping.target = existing continue } @@ -415,8 +344,11 @@ func enqueueDiscriminatorMappingTargets( name: name, fromDiscriminator: true, } + mapping.target = pr cf.refMap.Set(mapKey, pr) + targets = append(targets, pr) } + return targets } // resolveDiscriminatorMappingTarget attempts to resolve a mapping value as a whole-file reference. @@ -484,38 +416,6 @@ func resolveDiscriminatorMappingTarget( return ref, idx } -// handleDiscriminatorMappingIndexes ensures indexes discovered only via discriminator mappings -// are explored so their internal refs are composed. -func handleDiscriminatorMappingIndexes( - cf *handleIndexConfig, - rootIdx *index.SpecIndex, - rolodex *index.Rolodex, -) error { - for _, mapping := range cf.discriminatorMappings { - if mapping.targetIdx == nil { - continue - } - if mapping.targetIdx == rootIdx { - continue - } - if _, ok := cf.seen.Load(mapping.targetIdx.GetSpecAbsolutePath()); ok { - continue - } - - // Refresh indexes in case new ones were loaded during mapping resolution. - if rolodex != nil { - cf.indexes = rolodex.GetIndexes() - } - - cf.idx = mapping.targetIdx - if err := handleIndex(cf); err != nil { - return err - } - } - cf.idx = rootIdx - return nil -} - func deriveNameFromFullDefinition(fullDef string) string { if idx := strings.Index(fullDef, "#"); idx != -1 { fullDef = fullDef[:idx] diff --git a/bundler/bundler_composer_test.go b/bundler/bundler_composer_test.go index b14edb63..7daa459b 100644 --- a/bundler/bundler_composer_test.go +++ b/bundler/bundler_composer_test.go @@ -58,7 +58,7 @@ func TestBundlerComposed(t *testing.T) { // err = os.WriteFile("test/specs/bundled.yaml", bytes, 0644) v3Doc.Model.Components = nil - err = processReference(&v3Doc.Model, &processRef{}, &handleIndexConfig{compositionConfig: &BundleCompositionConfig{}}) + err = processReference(&v3Doc.Model, &processRef{}, &compositionContext{compositionConfig: &BundleCompositionConfig{}}) assert.Error(t, err) } @@ -67,8 +67,7 @@ func TestProcessReference_ContextualSingleSegmentRejectsUnsafeNode(t *testing.T) Components: &v3.Components{}, } idx := newVersionedIndex(3.1) - cf := &handleIndexConfig{ - idx: idx, + cf := &compositionContext{ rootIdx: idx, inlineRequired: nil, compositionConfig: &BundleCompositionConfig{Delimiter: "__"}, @@ -95,8 +94,7 @@ func TestProcessReference_JSONSchemaDefsReturnsComposeError(t *testing.T) { }, } idx := newVersionedIndex(3.2) - cf := &handleIndexConfig{ - idx: idx, + cf := &compositionContext{ rootIdx: idx, compositionConfig: &BundleCompositionConfig{Delimiter: "__"}, } @@ -118,8 +116,7 @@ func TestProcessReference_JSONSchemaDefsFallsBackWhenSchemasMissing(t *testing.T Components: &v3.Components{}, } idx := newVersionedIndex(3.2) - cf := &handleIndexConfig{ - idx: idx, + cf := &compositionContext{ rootIdx: idx, compositionConfig: &BundleCompositionConfig{Delimiter: "__"}, } @@ -310,13 +307,13 @@ components: ref.FullDefinition = ref.FullDefinition + "#/components/schemas/Cat" } - cf := &handleIndexConfig{ + cf := &compositionContext{ refMap: orderedmap.New[string, *processRef](), } enqueueDiscriminatorMappingTargets(mappings, cf, rolodex.GetRootIndex()) - pr := cf.refMap.GetOrZero(ref.FullDefinition) + pr := cf.refMap.GetOrZero(filepath.Join(tmpDir, "schemas", "Cat.yaml") + "#/components/schemas/Cat") require.NotNil(t, pr) assert.Equal(t, "Cat", pr.name) } @@ -391,19 +388,6 @@ paths: {}`), &rootNode)) assert.NotEqual(t, yaml.DocumentNode, ref.Node.Kind) } -func TestHandleDiscriminatorMappingIndexes_SkipsRootTarget(t *testing.T) { - rootIdx := &index.SpecIndex{} - cf := &handleIndexConfig{ - idx: rootIdx, - rootIdx: rootIdx, - discriminatorMappings: []*discriminatorMappingWithContext{{targetIdx: rootIdx}}, - } - - err := handleDiscriminatorMappingIndexes(cf, rootIdx, nil) - require.NoError(t, err) - assert.Equal(t, rootIdx, cf.idx) -} - // TestBundleBytesComposed_DiscriminatorMapping tests that composed bundling correctly // updates discriminator mappings when external schemas are moved to components. func TestBundleBytesComposed_DiscriminatorMapping(t *testing.T) { diff --git a/bundler/bundler_issue873_test.go b/bundler/bundler_issue873_test.go index 67f18f05..9b8dda54 100644 --- a/bundler/bundler_issue873_test.go +++ b/bundler/bundler_issue873_test.go @@ -10,6 +10,7 @@ import ( "github.com/pb33f/libopenapi/datamodel" highbase "github.com/pb33f/libopenapi/datamodel/high/base" v3 "github.com/pb33f/libopenapi/datamodel/high/v3" + lowbase "github.com/pb33f/libopenapi/datamodel/low/base" "github.com/pb33f/libopenapi/index" "github.com/pb33f/testify/assert" "github.com/pb33f/testify/require" @@ -283,16 +284,12 @@ func TestRenderBundledModelUsesSourceIndentationAndFallback(t *testing.T) { } func TestValidateDiscriminatorMappingsHelperPaths(t *testing.T) { - assert.NoError(t, validateDiscriminatorMappings(nil)) - assert.NoError(t, validateDiscriminatorMappingsFromIndex(nil)) - assert.NoError(t, validateDiscriminatorMappingsFromNode(nil)) + visit := discriminatorVisitor(lowbase.ValidateDiscriminatorMappingValueNodes) + validate := func(n *yaml.Node) error { + return visit.root(n, make(map[*yaml.Node]struct{})) + } + assert.NoError(t, validate(nil)) - root := parseYAMLNode(t, []byte(`openapi: 3.1.0 -info: - title: root - version: 1.0.0 -paths: {} -`)) invalid := parseYAMLNode(t, []byte(`components: schemas: Pet: @@ -321,19 +318,13 @@ x-any: enabled: false `)) - assert.ErrorContains(t, validateDiscriminatorMappingsFromNode(invalid), "discriminator.mapping.required") - assert.NoError(t, validateDiscriminatorMappingsFromNode(extensionPayload)) - assert.NoError(t, validateDiscriminatorMappingsFromNode(examplePayload)) - - cfg := index.CreateOpenAPIIndexConfig() - rolodex := index.NewRolodex(cfg) - rolodex.SetRootIndex(index.NewSpecIndexWithConfig(root, cfg)) - rolodex.AddIndex(index.NewSpecIndexWithConfig(invalid, cfg)) - - assert.ErrorContains(t, validateDiscriminatorMappings(rolodex), "discriminator.mapping.required") + assert.ErrorContains(t, validate(invalid), "discriminator.mapping.required") + assert.NoError(t, validate(extensionPayload)) + assert.NoError(t, validate(examplePayload)) } func TestValidateDiscriminatorMappingsCoverageBranches(t *testing.T) { + visit := discriminatorVisitor(lowbase.ValidateDiscriminatorMappingValueNodes) validSchema := parseYAMLNode(t, []byte(`type: object discriminator: propertyName: type @@ -341,7 +332,7 @@ discriminator: dog: '#/components/schemas/Dog' `)).Content[0] - assert.NoError(t, validateDiscriminatorMappingsFromOpenAPIObject(nil, nil, nil, nil)) + assert.NoError(t, visit.object(nil, nil, nil, nil)) assert.False(t, isOpenAPIDocumentRoot(&yaml.Node{Kind: yaml.ScalarNode})) assert.False(t, isOpenAPIDocumentRoot(&yaml.Node{ Kind: yaml.MappingNode, @@ -373,15 +364,15 @@ discriminator: type: object `)).Content[0] assert.ErrorContains(t, - validateDiscriminatorMappingsFromRootNode(openAPIRootWithSchemaCandidate, seenOpenAPI), + visit.root(openAPIRootWithSchemaCandidate, seenOpenAPI), "discriminator.mapping.bad", ) seenObject := make(map[*yaml.Node]struct{}) - assert.NoError(t, validateDiscriminatorMappingsFromOpenAPIObject(openAPIRootWithSchemaCandidate, nil, seenObject, nil)) - assert.NoError(t, validateDiscriminatorMappingsFromOpenAPIObject(openAPIRootWithSchemaCandidate, nil, seenObject, nil)) + assert.NoError(t, visit.object(openAPIRootWithSchemaCandidate, nil, seenObject, nil)) + assert.NoError(t, visit.object(openAPIRootWithSchemaCandidate, nil, seenObject, nil)) - assert.NoError(t, validateDiscriminatorMappingsFromOpenAPIObject(&yaml.Node{ + assert.NoError(t, visit.object(&yaml.Node{ Kind: yaml.MappingNode, Content: []*yaml.Node{ nil, @@ -399,7 +390,7 @@ discriminator: type: object `)).Content[0] assert.ErrorContains(t, - validateDiscriminatorMappingsFromOpenAPIObject(invalidSchemaObject, make(map[*yaml.Node]struct{}), make(map[*yaml.Node]struct{}), nil), + visit.object(invalidSchemaObject, make(map[*yaml.Node]struct{}), make(map[*yaml.Node]struct{}), nil), "discriminator.mapping.bad", ) @@ -413,7 +404,7 @@ discriminator: type: object `)).Content[0] assert.ErrorContains(t, - validateDiscriminatorMappingsFromOpenAPIObject(invalidComponentsSchemas, make(map[*yaml.Node]struct{}), make(map[*yaml.Node]struct{}), nil), + visit.object(invalidComponentsSchemas, make(map[*yaml.Node]struct{}), make(map[*yaml.Node]struct{}), nil), "discriminator.mapping.bad", ) @@ -426,7 +417,7 @@ discriminator: type: object `)).Content[0] assert.ErrorContains(t, - validateDiscriminatorMappingsFromOpenAPIObject(invalidDefinitions, make(map[*yaml.Node]struct{}), make(map[*yaml.Node]struct{}), nil), + visit.object(invalidDefinitions, make(map[*yaml.Node]struct{}), make(map[*yaml.Node]struct{}), nil), "discriminator.mapping.bad", ) validDefinitions := parseYAMLNode(t, []byte(`definitions: @@ -437,7 +428,7 @@ discriminator: dog: '#/definitions/Dog' `)).Content[0] assert.NoError(t, - validateDiscriminatorMappingsFromOpenAPIObject(validDefinitions, make(map[*yaml.Node]struct{}), make(map[*yaml.Node]struct{}), nil), + visit.object(validDefinitions, make(map[*yaml.Node]struct{}), make(map[*yaml.Node]struct{}), nil), ) invalidNestedObject := parseYAMLNode(t, []byte(`nested: @@ -449,28 +440,28 @@ discriminator: type: object `)).Content[0] assert.ErrorContains(t, - validateDiscriminatorMappingsFromOpenAPIObject(invalidNestedObject, make(map[*yaml.Node]struct{}), make(map[*yaml.Node]struct{}), nil), + visit.object(invalidNestedObject, make(map[*yaml.Node]struct{}), make(map[*yaml.Node]struct{}), nil), "discriminator.mapping.bad", ) - assert.NoError(t, validateDiscriminatorMappingsFromOpenAPIObject(&yaml.Node{ + assert.NoError(t, visit.object(&yaml.Node{ Kind: yaml.SequenceNode, Content: []*yaml.Node{ parseYAMLNode(t, []byte("x-any:\n discriminator:\n mapping:\n bad:\n type: object\n")).Content[0], }, }, make(map[*yaml.Node]struct{}), make(map[*yaml.Node]struct{}), nil)) - assert.ErrorContains(t, validateDiscriminatorMappingsFromOpenAPIObject(&yaml.Node{ + assert.ErrorContains(t, visit.object(&yaml.Node{ Kind: yaml.SequenceNode, Content: []*yaml.Node{invalidSchemaObject}, }, make(map[*yaml.Node]struct{}), make(map[*yaml.Node]struct{}), nil), "discriminator.mapping.bad") - assert.NoError(t, validateDiscriminatorMappingsFromSchemaNode(nil, make(map[*yaml.Node]struct{}))) - assert.NoError(t, validateDiscriminatorMappingsFromSchemaNode(&yaml.Node{Kind: yaml.ScalarNode}, make(map[*yaml.Node]struct{}))) + assert.NoError(t, visit.schema(nil, make(map[*yaml.Node]struct{}))) + assert.NoError(t, visit.schema(&yaml.Node{Kind: yaml.ScalarNode}, make(map[*yaml.Node]struct{}))) seenSchema := make(map[*yaml.Node]struct{}) - assert.NoError(t, validateDiscriminatorMappingsFromSchemaNode(validSchema, seenSchema)) - assert.NoError(t, validateDiscriminatorMappingsFromSchemaNode(validSchema, seenSchema)) + assert.NoError(t, visit.schema(validSchema, seenSchema)) + assert.NoError(t, visit.schema(validSchema, seenSchema)) - assert.NoError(t, validateDiscriminatorMappingsFromSchemaNode(&yaml.Node{ + assert.NoError(t, visit.schema(&yaml.Node{ Kind: yaml.MappingNode, Content: []*yaml.Node{ nil, @@ -480,7 +471,7 @@ discriminator: }, }, make(map[*yaml.Node]struct{}))) - assert.ErrorContains(t, validateDiscriminatorMappingsFromSchemaNode(parseYAMLNode(t, []byte(`items: + assert.ErrorContains(t, visit.schema(parseYAMLNode(t, []byte(`items: discriminator: propertyName: type mapping: @@ -488,7 +479,7 @@ discriminator: type: object `)).Content[0], make(map[*yaml.Node]struct{})), "discriminator.mapping.bad") - assert.ErrorContains(t, validateDiscriminatorMappingsFromSchemaNode(parseYAMLNode(t, []byte(`properties: + assert.ErrorContains(t, visit.schema(parseYAMLNode(t, []byte(`properties: pet: discriminator: propertyName: type @@ -497,7 +488,7 @@ discriminator: type: object `)).Content[0], make(map[*yaml.Node]struct{})), "discriminator.mapping.bad") - assert.ErrorContains(t, validateDiscriminatorMappingsFromSchemaNode(parseYAMLNode(t, []byte(`oneOf: + assert.ErrorContains(t, visit.schema(parseYAMLNode(t, []byte(`oneOf: - discriminator: propertyName: type mapping: @@ -505,10 +496,10 @@ discriminator: type: object `)).Content[0], make(map[*yaml.Node]struct{})), "discriminator.mapping.bad") - assert.NoError(t, validateDiscriminatorMappingsFromSchemaMap(nil, make(map[*yaml.Node]struct{}))) - assert.NoError(t, validateDiscriminatorMappingsFromSchemaMap(&yaml.Node{Kind: yaml.ScalarNode}, make(map[*yaml.Node]struct{}))) - assert.NoError(t, validateDiscriminatorMappingsFromSchemaArray(nil, make(map[*yaml.Node]struct{}))) - assert.NoError(t, validateDiscriminatorMappingsFromSchemaArray(&yaml.Node{Kind: yaml.ScalarNode}, make(map[*yaml.Node]struct{}))) + assert.NoError(t, visit.schemaMap(nil, make(map[*yaml.Node]struct{}))) + assert.NoError(t, visit.schemaMap(&yaml.Node{Kind: yaml.ScalarNode}, make(map[*yaml.Node]struct{}))) + assert.NoError(t, visit.schemaArray(nil, make(map[*yaml.Node]struct{}))) + assert.NoError(t, visit.schemaArray(&yaml.Node{Kind: yaml.ScalarNode}, make(map[*yaml.Node]struct{}))) } func TestComposeWithOriginsReturnsDiscriminatorValidationError(t *testing.T) { diff --git a/bundler/composed_fragments.go b/bundler/composed_fragments.go new file mode 100644 index 00000000..adf4772a --- /dev/null +++ b/bundler/composed_fragments.go @@ -0,0 +1,381 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package bundler + +import ( + "context" + "fmt" + "net/url" + "strconv" + "strings" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/libopenapi/datamodel/low/base" + v3 "github.com/pb33f/libopenapi/datamodel/low/v3" + "github.com/pb33f/libopenapi/index" + "github.com/pb33f/libopenapi/orderedmap" + "github.com/pb33f/libopenapi/utils" +) + +type compositionFragment struct { + idx *index.SpecIndex + node *yaml.Node + definition string + bucket string +} + +// The index records each use of a YAML alias separately. A shared $ref value +// can therefore have more than one OpenAPI role. +type aliasScope struct { + children map[string]*aliasScope + refs map[*yaml.Node]*index.Reference +} + +func (s *aliasScope) add(ref *index.Reference) { + for _, part := range ref.SourcePath { + if s.children == nil { + s.children = make(map[string]*aliasScope) + } + if s.children[part] == nil { + s.children[part] = new(aliasScope) + } + s = s.children[part] + } + if s.refs == nil { + s.refs = make(map[*yaml.Node]*index.Reference) + } + s.refs[ref.KeyNode] = ref +} + +type fragmentVisit struct { + node *yaml.Node + scope *aliasScope +} + +type fragmentIndex struct { + refs map[*yaml.Node]*index.Reference + aliases *aliasScope + visited map[fragmentVisit]bool + schemas, objects map[*yaml.Node]struct{} +} + +// Discover dependencies from the root and from each selected external node. +// Keep discovery separate from naming so reachable collisions retain their original order. +func collectComposedReferences(c *compositionContext, rolodex *index.Rolodex, reachable map[*index.Reference]*processRef) error { + files := make(map[*index.SpecIndex]*fragmentIndex) + indexes := make(map[string]*index.SpecIndex) + for _, idx := range rolodex.GetIndexes() { + indexes[idx.GetSpecAbsolutePath()] = idx + } + pending := []compositionFragment{{idx: c.rootIdx, node: c.rootIdx.GetRootNode()}} + type targetKey struct { + idx *index.SpecIndex + definition, bucket string + } + seen := make(map[targetKey]bool) + enqueue := func(pr *processRef, bucket string) { + key := targetKey{pr.idx, pr.ref.FullDefinition, bucket} + if !seen[key] { + seen[key] = true + pending = append(pending, compositionFragment{pr.idx, pr.ref.Node, key.definition, bucket}) + } + } + for len(pending) > 0 { + fragment := pending[len(pending)-1] + pending = pending[:len(pending)-1] + idx, node := fragment.idx, discriminatorValidationNode(fragment.node) + file := files[idx] + if file == nil { + file = &fragmentIndex{schemas: make(map[*yaml.Node]struct{}), objects: make(map[*yaml.Node]struct{})} + files[idx] = file + } + mappings, err := file.collectMappings(fragment) + if err != nil { + return err + } + c.discriminatorMappings = append(c.discriminatorMappings, mappings...) + for _, pr := range enqueueDiscriminatorMappingTargets(mappings, c, c.rootIdx) { + if pr.idx != nil && pr.idx != c.rootIdx { + indexes[pr.idx.GetSpecAbsolutePath()] = pr.idx + enqueue(pr, v3.SchemasLabel) + } + } + refs := file.references(idx, node, fragment.definition) + for _, ref := range refs { + if ref.IsExtensionRef { + continue + } + if c.compositionConfig.StrictValidation && ref.HasSiblingProperties && idx.GetConfig().SpecInfo.VersionNumeric == 3.0 { + keys := make([]string, 0, len(ref.SiblingProperties)) + for key := range ref.SiblingProperties { + keys = append(keys, key) + } + return fmt.Errorf("invalid OpenAPI 3.0 specification: $ref cannot have sibling properties. Found $ref '%s' with siblings %v at line %d, column %d", + ref.FullDefinition, keys, ref.Node.Line, ref.Node.Column) + } + pr := resolveComposedReference(idx, ref, c.rootIdx, indexes) + reachable[ref] = pr + if pr != nil { + bucket, _ := inferComponentTypeFromSourcePath(ref.SourcePath) + enqueue(pr, bucket) + } + } + } + + c.orderDiscriminatorTargets(rolodex) + c.orderReachableReferences(reachable) + return nil +} + +// Assign names in the index's reference order, visiting each file once. +// Mapping targets already occupy their original priority in refMap. +func (c *compositionContext) orderReachableReferences(reachable map[*index.Reference]*processRef) { + seenFiles := make(map[*index.SpecIndex]bool) + var order func(*index.SpecIndex) + order = func(idx *index.SpecIndex) { + var children []*index.SpecIndex + for _, ref := range idx.GetRawReferencesSequenced() { + if pr := reachable[ref]; pr != nil { + if c.refMap.GetOrZero(pr.mapKey) == nil { + c.refMap.Set(pr.mapKey, pr) + } + if !seenFiles[pr.idx] { + seenFiles[pr.idx] = true + children = append(children, pr.idx) + } + } + } + for _, child := range children { + order(child) + } + } + seenFiles[c.rootIdx] = true + order(c.rootIdx) + for _, pr := range c.refMap.FromOldest() { + if !pr.fromDiscriminator { + break + } + if idx := pr.idx; idx != nil && !seenFiles[idx] { + seenFiles[idx] = true + order(idx) + } + } +} + +func (f *fragmentIndex) collectMappings(fragment compositionFragment) ([]*discriminatorMappingWithContext, error) { + var mappings []*discriminatorMappingWithContext + visit := discriminatorVisitor(func(d *yaml.Node) error { + if err := base.ValidateDiscriminatorMappingValueNodes(d); err != nil { + return err + } + visitDiscriminatorMappingValues(d, func(value *yaml.Node) { + mappings = append(mappings, &discriminatorMappingWithContext{node: value, sourceIdx: fragment.idx}) + }) + return nil + }) + var err error + switch fragment.bucket { + case v3.SchemasLabel: + err = visit.schema(fragment.node, f.schemas) + case v3.ExamplesLabel: + // Example values are literal payloads. + case "": + err = visit.root(fragment.node, f.schemas) + default: + err = visit.object(fragment.node, f.schemas, f.objects, nil) + } + return mappings, err +} + +// Keep discriminator targets ahead of ordinary references and in the order their +// mappings occur in each source document, even when fragments are reached out of order. +func (c *compositionContext) orderDiscriminatorTargets(rolodex *index.Rolodex) { + if c.refMap.Len() < 2 { + return + } + selected := make(map[*index.SpecIndex]map[*yaml.Node]*processRef) + for _, m := range c.discriminatorMappings { + if m.target == nil { + continue + } + if selected[m.sourceIdx] == nil { + selected[m.sourceIdx] = make(map[*yaml.Node]*processRef) + } + selected[m.sourceIdx][m.node] = m.target + } + targets := orderedmap.New[string, *processRef]() + order := func(idx *index.SpecIndex) { + items := selected[idx] + switch len(items) { + case 0: + case 1: + for _, pr := range items { + targets.Set(pr.mapKey, pr) + } + default: + walkDiscriminatorMappingNodes(idx.GetRootNode(), func(value *yaml.Node) { + if pr := items[value]; pr != nil { + targets.Set(pr.mapKey, pr) + } + }) + } + } + order(c.rootIdx) + for _, idx := range rolodex.GetIndexes() { + order(idx) + } + // An alias or a mapping-only index can introduce a target outside the authored walk. + for key, pr := range c.refMap.FromOldest() { + targets.Set(key, pr) + } + c.refMap = targets +} + +func (f *fragmentIndex) references(idx *index.SpecIndex, node *yaml.Node, definition string) []*index.Reference { + raw := idx.GetRawReferencesSequenced() + if len(raw) == 0 || node == discriminatorValidationNode(idx.GetRootNode()) { + return raw + } + if f.refs == nil { + f.refs = make(map[*yaml.Node]*index.Reference, len(raw)) + f.visited = make(map[fragmentVisit]bool) + for _, ref := range raw { + if _, shared := f.refs[ref.KeyNode]; shared { + f.refs[ref.KeyNode] = nil + if f.aliases == nil { + f.aliases = new(aliasScope) + } + } else { + f.refs[ref.KeyNode] = ref + } + } + if f.aliases != nil { + for _, ref := range raw { + if f.refs[ref.KeyNode] == nil { + f.aliases.add(ref) + } + } + } + } + scope := f.aliases + if scope != nil { + for _, part := range fragmentSourcePath(idx.GetRootNode(), definition) { + scope = scope.children[part] + if scope == nil { + break + } + } + } + var refs []*index.Reference + var walk func(*yaml.Node, *aliasScope) + walk = func(n *yaml.Node, scope *aliasScope) { + n = utils.NodeAlias(n) + if n == nil || len(n.Content) == 0 { + return + } + key := fragmentVisit{n, scope} + if f.visited[key] { + return + } + f.visited[key] = true + if n.Kind == yaml.SequenceNode { + for _, item := range n.Content { + walk(item, scope) + } + return + } + content := utils.ResolveMergeNodes(n).Content + for i := 0; i+1 < len(content); i += 2 { + name, value := content[i].Value, content[i+1] + if name == "$ref" { + ref := f.refs[value] + if ref == nil && scope != nil { + ref = scope.refs[value] + } + if ref != nil { + refs = append(refs, ref) + } + } + var child *aliasScope + if scope != nil { + child = scope.children[strings.ReplaceAll(name, "/", "~1")] + } + walk(value, child) + } + } + walk(node, scope) + return refs +} + +// SourcePath escapes slashes and omits sequence offsets. Keep numeric mapping keys. +func fragmentSourcePath(root *yaml.Node, definition string) []string { + _, pointer, _ := strings.Cut(definition, "#/") + pointer, _ = url.PathUnescape(pointer) + parts := strings.Split(pointer, "/") + // Most selectors contain only mapping keys. They need no second tree lookup. + numeric := false + for i, part := range parts { + parts[i] = strings.ReplaceAll(part, "~0", "~") + if _, err := strconv.Atoi(part); err == nil { + numeric = true + } + } + if !numeric { + return parts + } + var path []string + node := discriminatorValidationNode(root) + for part := range strings.SplitSeq(pointer, "/") { + node = utils.ResolveMergeNodes(node) + if node == nil { + return nil + } + if node.Kind == yaml.SequenceNode { + i, err := strconv.Atoi(part) + if err != nil || i < 0 || i >= len(node.Content) { + return nil + } + node = node.Content[i] + continue + } + key := decodeSingleSegmentPointer(part) + path = append(path, strings.ReplaceAll(key, "/", "~1")) + content := node.Content + node = nil + for i := 0; i+1 < len(content); i += 2 { + if content[i].Value == key { + node = content[i+1] + break + } + } + } + return path +} + +func resolveComposedReference(source *index.SpecIndex, ref *index.Reference, root *index.SpecIndex, indexes map[string]*index.SpecIndex) *processRef { + path, _, _ := strings.Cut(ref.FullDefinition, "#/") + if path == root.GetSpecAbsolutePath() { + return nil + } + target := source.GetMappedReferences()[ref.FullDefinition] + if target == nil { + target, _ = source.SearchIndexForReference(ref.FullDefinition) + } + owner := indexes[path] + if owner == nil && target != nil && target.Index != nil && target.Index.GetSpecAbsolutePath() == path { + // A discriminator mapping can load another file during discovery. + owner = target.Index + indexes[path] = owner + } + if owner == nil || target == nil { + return nil + } + if !target.Circular { + // Use the authored target in its owning index, including intermediate aliases (#397). + if authored := owner.FindComponent(context.Background(), ref.FullDefinition); authored != nil { + target = authored + } + } + return &processRef{idx: owner, ref: target, seqRef: ref, mapKey: processRefMapKey(target, ref), name: target.Name} +} diff --git a/bundler/composed_fragments_test.go b/bundler/composed_fragments_test.go new file mode 100644 index 00000000..18547efe --- /dev/null +++ b/bundler/composed_fragments_test.go @@ -0,0 +1,309 @@ +// Copyright 2026 Princess B33f Heavy Industries / Dave Shanley +// SPDX-License-Identifier: MIT + +package bundler + +import ( + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/pb33f/go-yaml" + "github.com/pb33f/libopenapi" + "github.com/pb33f/libopenapi/datamodel" + v3 "github.com/pb33f/libopenapi/datamodel/high/v3" + "github.com/pb33f/libopenapi/index" + "github.com/pb33f/testify/require" +) + +// Each API mutates its input, so build a fresh model for each call. +func checkComposedAPIs(t *testing.T, root string, cfg *datamodel.DocumentConfiguration, check func(*testing.T, *v3.Document, ComponentOriginMap)) { + t.Helper() + for _, api := range []string{"BundleDocumentComposed", "BundleDocumentComposedWithOrigins"} { + t.Run(api, func(t *testing.T) { + doc, err := libopenapi.NewDocumentWithConfiguration([]byte(root), cfg) + require.NoError(t, err) + model, err := doc.BuildV3Model() + require.NoError(t, err) + if api == "BundleDocumentComposedWithOrigins" { + result, err := BundleDocumentComposedWithOrigins(&model.Model, nil) + require.NoError(t, err) + require.NotNil(t, result.Origins) + check(t, parseBundledV3Document(t, result.Bytes), result.Origins) + } else { + out, err := BundleDocumentComposed(&model.Model, nil) + require.NoError(t, err) + check(t, parseBundledV3Document(t, out), nil) + } + }) + } +} + +func TestComposedReachableFragments(t *testing.T) { + const root = `openapi: 3.0.3 +info: {title: Documents, version: '1'} +paths: + /pets/options: {$ref: './pets/paths.yaml#/paths/~1pets~1options'} + /docs/{id}: {$ref: './docs/paths.yaml#/paths/~1docs~1{id}'} +` + cfg := externalRegressionConfig(t, map[string]string{ + "api/openapi.yaml": root, + "api/pets/paths.yaml": `paths: + /pets/options: + get: {responses: {'200': {description: ok}}} + /pets: + get: + responses: + '200': + description: ok + content: + application/json: + schema: {$ref: '../../other/openapi.yaml#/components/schemas/Id'} +`, + "api/docs/paths.yaml": `paths: + /docs/{id}: + parameters: [{$ref: '../common/parameters.yaml#/components/parameters/id'}] + get: {responses: {'200': {description: ok}}} +`, + "api/common/parameters.yaml": `components: + parameters: + id: {name: id, in: path, required: true, schema: {$ref: './schemas.yaml#/components/schemas/Id'}} +`, + "api/common/schemas.yaml": "components: {schemas: {Id: {type: string, format: uuid}}}", + "other/openapi.yaml": "components: {schemas: {Id: {type: integer}}}", + }) + cfg.SpecFilePath = filepath.Join(cfg.BasePath, "api", "openapi.yaml") + + checkComposedAPIs(t, root, cfg, func(t *testing.T, doc *v3.Document, origins ComponentOriginMap) { + schemas := doc.Components.Schemas + require.Equal(t, []string{"Id"}, slices.Collect(schemas.KeysFromOldest())) + id := schemas.GetOrZero("Id").Schema() + require.Equal(t, []string{"string"}, id.Type) + require.Equal(t, "uuid", id.Format) + param := doc.Paths.PathItems.GetOrZero("/docs/{id}").Parameters[0] + require.Equal(t, "#/components/parameters/id", param.GoLow().GetReference()) + require.Equal(t, "#/components/schemas/Id", param.Schema.GetReference()) + if origins != nil { + require.Len(t, origins, 2) + origin := origins["#/components/schemas/Id"] + require.NotNil(t, origin) + require.Equal(t, filepath.Join(cfg.BasePath, "api", "common", "schemas.yaml"), origin.OriginalFile) + require.False(t, origin.WasRenamed) + } + }) +} + +func TestComposedReachableDiscriminatorMappings(t *testing.T) { + const root = `openapi: 3.1.0 +info: {title: Animals, version: '1'} +paths: {} +components: + schemas: + Pet: + oneOf: + - {$ref: './animals.yaml#/components/schemas/Feline'} + - {$ref: './animals.yaml#/components/schemas/Canine'} +` + cfg := externalRegressionConfig(t, map[string]string{ + "animals.yaml": `x-feline: &feline + discriminator: {propertyName: kind, mapping: {cat: './breeds.yaml#/components/schemas/Cat', other: 'urn:example:other'}} +components: + schemas: + Feline: + <<: *feline + type: object + Canine: + type: object + discriminator: {propertyName: kind, mapping: {dog: './breeds.yaml#/components/schemas/Dog'}} + Unused: + type: object + discriminator: {propertyName: kind, mapping: {wolf: './breeds.yaml#/components/schemas/Wolf'}} + InvalidUnused: + discriminator: {propertyName: kind, mapping: {bad: [invalid]}} +`, + "breeds.yaml": `components: + schemas: + Cat: + type: object + discriminator: {propertyName: breed, mapping: {tabby: '#/components/schemas/Tabby'}} + Tabby: + type: object + properties: {id: {$ref: './id.yaml'}} + Dog: {type: object} + Wolf: {type: object} +`, + "id.yaml": "type: integer", + }) + cfg.SpecFilePath = filepath.Join(cfg.BasePath, "root.yaml") + + checkComposedAPIs(t, root, cfg, func(t *testing.T, doc *v3.Document, origins ComponentOriginMap) { + schemas := doc.Components.Schemas + require.ElementsMatch(t, []string{"Pet", "Feline", "Canine", "Cat", "Dog", "Tabby", "id"}, slices.Collect(schemas.KeysFromOldest())) + for _, m := range []struct{ schema, tag, target string }{ + {"Feline", "cat", "Cat"}, {"Canine", "dog", "Dog"}, {"Cat", "tabby", "Tabby"}, + } { + mapping := schemas.GetOrZero(m.schema).Schema().Discriminator.Mapping + require.Equal(t, "#/components/schemas/"+m.target, mapping.GetOrZero(m.tag)) + } + require.Equal(t, "#/components/schemas/id", schemas.GetOrZero("Tabby").Schema().Properties.GetOrZero("id").GetReference()) + require.Equal(t, "urn:example:other", schemas.GetOrZero("Feline").Schema().Discriminator.Mapping.GetOrZero("other")) + if origins != nil { + require.Len(t, origins, schemas.Len()-1) // Pet is declared in the root. + require.Contains(t, origins, "#/components/schemas/Tabby") + require.NotContains(t, origins, "#/components/schemas/Wolf") + } + }) +} + +func TestComposedAliasInUnusedFragment(t *testing.T) { + const root = `openapi: 3.1.0 +info: {title: Responses, version: '1'} +paths: + /used: {$ref: './paths.yaml#/entries/0'} + /health: {$ref: './paths.yaml#/health'} + /ready: {$ref: './paths.yaml#/ready'} +components: + schemas: + Wrapper: {type: object, properties: {thing: {$ref: './parts.yaml#/Thing'}}} +` + cfg := externalRegressionConfig(t, map[string]string{ + "paths.yaml": `entries: + - get: + responses: + '200': &shared {$ref: './parts.yaml#/Thing'} + - get: + responses: + '200': {description: ok, content: {application/json: {schema: *shared}}} +health: {get: &probe {responses: {'200': {description: healthy}}}} +ready: {get: *probe} +`, + "parts.yaml": "Thing: {description: answer}", + }) + checkComposedAPIs(t, root, cfg, func(t *testing.T, doc *v3.Document, origins ComponentOriginMap) { + wrapper := doc.Components.Schemas.GetOrZero("Wrapper").Schema() + require.Equal(t, "#/components/schemas/Thing", wrapper.Properties.GetOrZero("thing").GetReference()) + require.Equal(t, "answer", doc.Components.Responses.GetOrZero("Thing").Description) + response := doc.Paths.PathItems.GetOrZero("/used").Get.Responses.Codes.GetOrZero("200") + require.Equal(t, "#/components/responses/Thing", response.GoLow().GetReference()) + for _, path := range []string{"/health", "/ready"} { + require.Equal(t, "healthy", doc.Paths.PathItems.GetOrZero(path).Get.Responses.Codes.GetOrZero("200").Description) + } + }) +} + +func TestComposedDiscriminatorCollisionOrder(t *testing.T) { + const root = `openapi: 3.1.0 +info: {title: Animals, version: '1'} +paths: {} +components: + schemas: + Pet: + oneOf: + - {$ref: './animals.yaml#/components/schemas/Canine'} + - {$ref: './animals.yaml#/components/schemas/Feline'} +` + cfg := externalRegressionConfig(t, map[string]string{ + "animals.yaml": `components: + schemas: + Feline: {type: object, discriminator: {propertyName: kind, mapping: {cat: './cats.yaml#/components/schemas/Id'}}} + Canine: {type: object, discriminator: {propertyName: kind, mapping: {dog: './dogs.yaml#/components/schemas/Id'}}} +`, + "cats.yaml": "components: {schemas: {Id: {type: string, format: uuid, allOf: [{$ref: './cats-id.yaml#/components/schemas/Limit'}]}}}", + "dogs.yaml": "components: {schemas: {Id: {type: integer, allOf: [{$ref: './dogs-id.yaml#/components/schemas/Limit'}]}}}", + "cats-id.yaml": "components: {schemas: {Limit: {type: string, maxLength: 36}}}", + "dogs-id.yaml": "components: {schemas: {Limit: {type: integer, maximum: 42}}}", + }) + checkComposedAPIs(t, root, cfg, func(t *testing.T, doc *v3.Document, origins ComponentOriginMap) { + s := doc.Components.Schemas + require.Equal(t, "#/components/schemas/Id", s.GetOrZero("Feline").Schema().Discriminator.Mapping.GetOrZero("cat")) + require.Equal(t, "#/components/schemas/Id__dogs", s.GetOrZero("Canine").Schema().Discriminator.Mapping.GetOrZero("dog")) + require.Equal(t, "uuid", s.GetOrZero("Id").Schema().Format) + require.Equal(t, []string{"integer"}, s.GetOrZero("Id__dogs").Schema().Type) + require.Equal(t, "#/components/schemas/Limit", s.GetOrZero("Id").Schema().AllOf[0].GetReference()) + require.Equal(t, "#/components/schemas/Limit__dogs-id", s.GetOrZero("Id__dogs").Schema().AllOf[0].GetReference()) + require.Equal(t, []string{"string"}, s.GetOrZero("Limit").Schema().Type) + require.Equal(t, []string{"integer"}, s.GetOrZero("Limit__dogs-id").Schema().Type) + }) +} + +func TestComposedDiscriminatorRelativeToEachSource(t *testing.T) { + const root = `openapi: 3.1.0 +info: {title: Animals, version: '1'} +paths: {} +components: + schemas: + Pet: {oneOf: [{$ref: './cats/pet.yaml#/Cat'}, {$ref: './dogs/pet.yaml#/Dog'}]} +` + const mapped = "{type: object, discriminator: {propertyName: kind, mapping: {id: './types.yaml#/components/schemas/Id'}}}" + cfg := externalRegressionConfig(t, map[string]string{ + "cats/pet.yaml": "Cat: " + mapped, "cats/types.yaml": "components: {schemas: {Id: {type: string}}}", + "dogs/pet.yaml": "Dog: " + mapped, "dogs/types.yaml": "components: {schemas: {Id: {type: integer}}}", + }) + checkComposedAPIs(t, root, cfg, func(t *testing.T, doc *v3.Document, origins ComponentOriginMap) { + schemas := doc.Components.Schemas + for _, item := range []struct{ schema, kind, dir string }{{"Cat", "string", "cats"}, {"Dog", "integer", "dogs"}} { + target := schemas.GetOrZero(item.schema).Schema().Discriminator.Mapping.GetOrZero("id") + name, ok := strings.CutPrefix(target, "#/components/schemas/") + require.True(t, ok) + require.Equal(t, []string{item.kind}, schemas.GetOrZero(name).Schema().Type) + if origins != nil { + require.Equal(t, filepath.Join(cfg.BasePath, item.dir, "types.yaml"), origins[target].OriginalFile) + } + } + }) +} + +func TestComposedFragmentSourcePath(t *testing.T) { + var root yaml.Node + require.NoError(t, yaml.Unmarshal([]byte(`Lists: {"200": [{"/a~b": {type: object}}]}`), &root)) + for _, tc := range []struct { + pointer string + want []string + }{ + {"#/Lists/200/0/~1a~0b", []string{"Lists", "200", "~1a~b"}}, + {"#/lists/200/0", nil}, // JSON Pointer keys are case-sensitive. + {"#/Lists/200/1", nil}, + {"#/Lists/200/unknown", nil}, + } { + require.Equal(t, tc.want, fragmentSourcePath(&root, tc.pointer), tc.pointer) + } +} + +func TestComposedMissingFragment(t *testing.T) { + root, rolodex := buildResolveRefContext(t) + external := rolodex.GetIndexes()[0] + path := external.GetSpecAbsolutePath() + missing := &index.Reference{FullDefinition: path + "#/missing"} + require.Nil(t, resolveComposedReference(root, missing, root, map[string]*index.SpecIndex{path: external})) +} + +func TestComposedDiscriminatorInRequestBody(t *testing.T) { + const root = `openapi: 3.1.0 +info: {title: Animals, version: '1'} +paths: + /pets: + post: + requestBody: {$ref: './requests.yaml#/components/requestBodies/Pet'} + responses: {'200': {description: ok}} +` + cfg := externalRegressionConfig(t, map[string]string{ + "requests.yaml": `components: + requestBodies: + Pet: + required: true + content: + application/json: + schema: + type: object + discriminator: {propertyName: kind, mapping: {cat: './cat.yaml'}} +`, + "cat.yaml": "type: object", + }) + checkComposedAPIs(t, root, cfg, func(t *testing.T, doc *v3.Document, origins ComponentOriginMap) { + body := doc.Components.RequestBodies.GetOrZero("Pet") + mapping := body.Content.GetOrZero("application/json").Schema.Schema().Discriminator.Mapping + require.Equal(t, "#/components/schemas/cat", mapping.GetOrZero("cat")) + require.NotNil(t, doc.Components.Schemas.GetOrZero("cat")) + }) +} diff --git a/bundler/composer_functions.go b/bundler/composer_functions.go index 65ebbede..8db3ab68 100644 --- a/bundler/composer_functions.go +++ b/bundler/composer_functions.go @@ -274,7 +274,7 @@ func composeReferenceAs( components *v3.Components, pr *processRef, idx *index.SpecIndex, - cf *handleIndexConfig, + cf *compositionContext, ) (bool, error) { delimiter := compositionDelimiter(cf) @@ -352,7 +352,7 @@ func fileImportLocationForType( componentType string, components *v3.Components, pr *processRef, - cf *handleIndexConfig, + cf *compositionContext, ) (bool, []string) { delimiter := compositionDelimiter(cf) @@ -488,11 +488,11 @@ func checkForCollision[T any](schemaName, delimiter string, pr *processRef, comp return schemaName } -func remapIndex(idx *index.SpecIndex, processedNodes *orderedmap.Map[string, *processRef]) { +func remapIndex(idx *index.SpecIndex, processedNodes *orderedmap.Map[string, *processRef], reachable map[*index.Reference]*processRef) { seq := idx.GetRawReferencesSequenced() for _, sequenced := range seq { - if sequenced.IsExtensionRef { + if _, selected := reachable[sequenced]; !selected { continue } rewireRef(idx, sequenced, sequenced.FullDefinition, processedNodes) @@ -827,7 +827,7 @@ func walkAndRewriteRefs( } } -func compositionDelimiter(cf *handleIndexConfig) string { +func compositionDelimiter(cf *compositionContext) string { if cf == nil || cf.compositionConfig == nil || cf.compositionConfig.Delimiter == "" { return defaultCompositionDelimiter } diff --git a/bundler/composer_functions_test.go b/bundler/composer_functions_test.go index 8e1e5e74..e2e37908 100644 --- a/bundler/composer_functions_test.go +++ b/bundler/composer_functions_test.go @@ -39,7 +39,7 @@ func TestComposeReferenceAs_MediaType(t *testing.T) { MediaTypes: orderedmap.New[string, *highv3.MediaType](), } idx := newVersionedIndex(3.2) - cf := &handleIndexConfig{ + cf := &compositionContext{ rootIdx: idx, compositionConfig: &BundleCompositionConfig{ Delimiter: "__", @@ -59,7 +59,7 @@ func TestComposeReferenceAs_UnsupportedMediaTypeComponentInlines(t *testing.T) { MediaTypes: orderedmap.New[string, *highv3.MediaType](), } idx := newVersionedIndex(3.1) - cf := &handleIndexConfig{ + cf := &compositionContext{ rootIdx: idx, compositionConfig: &BundleCompositionConfig{ Delimiter: "__", @@ -76,7 +76,7 @@ func TestComposeReferenceAs_UnsupportedMediaTypeComponentInlines(t *testing.T) { func TestComposeReferenceAs_MissingComponentMap(t *testing.T) { idx := newVersionedIndex(3.2) - cf := &handleIndexConfig{ + cf := &compositionContext{ rootIdx: idx, compositionConfig: &BundleCompositionConfig{ Delimiter: "__", @@ -110,7 +110,7 @@ func TestFileImportLocationForType_MediaType(t *testing.T) { components := &highv3.Components{ MediaTypes: orderedmap.New[string, *highv3.MediaType](), } - cf := &handleIndexConfig{ + cf := &compositionContext{ rootIdx: newVersionedIndex(3.2), compositionConfig: &BundleCompositionConfig{ Delimiter: "__", @@ -127,7 +127,7 @@ func TestFileImportLocationForType_MediaType(t *testing.T) { } func TestFileImportLocationForType_MissingComponentMap(t *testing.T) { - cf := &handleIndexConfig{ + cf := &compositionContext{ rootIdx: newVersionedIndex(3.2), compositionConfig: &BundleCompositionConfig{ Delimiter: "__", @@ -187,7 +187,7 @@ func TestFileImportLocationForType_UnsupportedComponentVersionsInline(t *testing for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - cf := &handleIndexConfig{ + cf := &compositionContext{ rootIdx: newVersionedIndex(tt.version), compositionConfig: &BundleCompositionConfig{ Delimiter: "__", @@ -685,9 +685,9 @@ func TestJSONSchemaDefsComponentName(t *testing.T) { assert.Equal(t, "company profile", decodeJSONSchemaDefsSegment("company%20profile")) assert.Equal(t, "company/profile", decodeJSONSchemaDefsSegment("company%7E1profile")) assert.Equal(t, defaultCompositionDelimiter, compositionDelimiter(nil)) - assert.Equal(t, defaultCompositionDelimiter, compositionDelimiter(&handleIndexConfig{})) - assert.Equal(t, defaultCompositionDelimiter, compositionDelimiter(&handleIndexConfig{compositionConfig: &BundleCompositionConfig{}})) - assert.Equal(t, "@@", compositionDelimiter(&handleIndexConfig{compositionConfig: &BundleCompositionConfig{Delimiter: "@@"}})) + assert.Equal(t, defaultCompositionDelimiter, compositionDelimiter(&compositionContext{})) + assert.Equal(t, defaultCompositionDelimiter, compositionDelimiter(&compositionContext{compositionConfig: &BundleCompositionConfig{}})) + assert.Equal(t, "@@", compositionDelimiter(&compositionContext{compositionConfig: &BundleCompositionConfig{Delimiter: "@@"}})) } func TestRenameRefWithSourceUsesComposedLocation(t *testing.T) { @@ -721,7 +721,7 @@ func TestRemapIndexSkipsMappedExtensionRefs(t *testing.T) { }, }) - remapIndex(idx, orderedmap.New[string, *processRef]()) + remapIndex(idx, orderedmap.New[string, *processRef](), nil) assert.Equal(t, "./sample.md", refNode.Content[1].Value) } @@ -736,7 +736,7 @@ func TestResolveRefToComposed_RootFallbackFromExternalSource(t *testing.T) { indexes := rolodex.GetIndexes() require.NotEmpty(t, indexes) - got := resolveRefToComposed("#/components/schemas/RootThing", indexes[0], orderedmap.New[string, *processRef](), rolodex) + got := resolveRefToComposed("../root.yaml#/components/schemas/RootThing", indexes[0], orderedmap.New[string, *processRef](), rolodex) assert.Equal(t, "#/components/schemas/RootThing", got) } From 7b031298bad10a3134fde221ee256acfe8183faf Mon Sep 17 00:00:00 2001 From: quobix Date: Sun, 29 Nov 2026 15:29:37 -0500 Subject: [PATCH 3/4] fix(bundler): preserve discriminator mapping context and aliases --- bundler/bundler.go | 46 +++++++- bundler/bundler_composer.go | 2 +- bundler/composed_fragments.go | 63 ++++++++--- bundler/composed_fragments_test.go | 171 ++++++++++++++++++++++++++++- bundler/source_context.go | 29 +++-- 5 files changed, 269 insertions(+), 42 deletions(-) diff --git a/bundler/bundler.go b/bundler/bundler.go index cc48c318..f76d290d 100644 --- a/bundler/bundler.go +++ b/bundler/bundler.go @@ -20,6 +20,7 @@ import ( highbase "github.com/pb33f/libopenapi/datamodel/high/base" v3 "github.com/pb33f/libopenapi/datamodel/high/v3" lowbase "github.com/pb33f/libopenapi/datamodel/low/base" + lowv3 "github.com/pb33f/libopenapi/datamodel/low/v3" "github.com/pb33f/libopenapi/index" "github.com/pb33f/libopenapi/orderedmap" "github.com/pb33f/libopenapi/utils" @@ -134,6 +135,17 @@ func (visit discriminatorVisitor) object(n *yaml.Node, schemaSeen, objectSeen ma } continue } + // The keys of these maps are user-defined names, including "schema", + // "examples" and names starting with "x-". Visit their values directly. + if valueNode.Kind == yaml.MappingNode && isDiscriminatorObjectMap(key, path) { + entries := utils.ResolveMergeNodes(valueNode).Content + for j := 1; j < len(entries); j += 2 { + if err := visit.object(entries[j], schemaSeen, objectSeen, append(path, key, entries[j-1].Value)); err != nil { + return err + } + } + continue + } if valueNode.Kind == yaml.MappingNode || valueNode.Kind == yaml.SequenceNode { if err := visit.object(valueNode, schemaSeen, objectSeen, append(path, key)); err != nil { @@ -145,6 +157,17 @@ func (visit discriminatorVisitor) object(n *yaml.Node, schemaSeen, objectSeen ma return nil } +func isDiscriminatorObjectMap(key string, path []string) bool { + if len(path) == 1 && path[0] == lowv3.ComponentsLabel { + return true + } + switch key { + case lowv3.ContentLabel, lowv3.HeadersLabel, lowv3.LinksLabel, lowv3.CallbacksLabel, lowv3.WebhooksLabel: + return true + } + return false +} + func shouldSkipDiscriminatorValidationOpenAPIValue(key string) bool { return key == lowbase.ExampleLabel || key == lowbase.ExamplesLabel || @@ -974,11 +997,13 @@ func walkDiscriminatorMappingNodes(n *yaml.Node, yield func(*yaml.Node)) { walkDiscriminatorMappingNodes(v, yield) } - visitDiscriminatorMappingValues(discriminator, yield) + visitDiscriminatorMappingValues(discriminator, false, yield) } -func visitDiscriminatorMappingValues(discriminator *yaml.Node, yield func(*yaml.Node)) { - discriminator = utils.ResolveMergeNodes(discriminator) +func visitDiscriminatorMappingValues(discriminator *yaml.Node, resolveAliases bool, yield func(*yaml.Node)) { + if resolveAliases { + discriminator = utils.ResolveMergeNodes(discriminator) + } if discriminator == nil || discriminator.Kind != yaml.MappingNode { return } @@ -986,12 +1011,15 @@ func visitDiscriminatorMappingValues(discriminator *yaml.Node, yield func(*yaml. if discriminator.Content[i].Value != "mapping" { continue } - mapping := utils.ResolveMergeNodes(discriminator.Content[i+1]) + mapping := discriminator.Content[i+1] + if resolveAliases { + mapping = utils.ResolveMergeNodes(mapping) + } if mapping == nil || mapping.Kind != yaml.MappingNode { continue } for j := 1; j < len(mapping.Content); j += 2 { - yield(utils.NodeAlias(mapping.Content[j])) + yield(mapping.Content[j]) } } } @@ -999,7 +1027,7 @@ func visitDiscriminatorMappingValues(discriminator *yaml.Node, yield func(*yaml. // updateDiscriminatorMappingsComposed updates discriminator mapping references to point to composed component locations. func updateDiscriminatorMappingsComposed(mappings []*discriminatorMappingWithContext, processedNodes *orderedmap.Map[string, *processRef], rolodex *index.Rolodex) { for _, mapping := range mappings { - originalValue := mapping.node.Value + originalValue := utils.NodeAlias(mapping.node).Value if originalValue == "" { continue } @@ -1042,6 +1070,12 @@ func updateDiscriminatorMappingsComposed(mappings []*discriminatorMappingWithCon // Use targetIdx (where the ref actually lives), NOT sourceIdx newRef := renameRef(targetIdx, canonicalKey, processedNodes) if newRef != originalValue { + // Replace this use of an alias. Other uses retain the anchored string. + if mapping.node.Kind == yaml.AliasNode { + mapping.node.Kind = yaml.ScalarNode + mapping.node.Tag = "!!str" + mapping.node.Alias = nil + } mapping.node.Value = newRef } } diff --git a/bundler/bundler_composer.go b/bundler/bundler_composer.go index b1440cdf..2cf82481 100644 --- a/bundler/bundler_composer.go +++ b/bundler/bundler_composer.go @@ -272,7 +272,7 @@ func enqueueDiscriminatorMappingTargets( ) []*processRef { var targets []*processRef for _, mapping := range mappings { - refValue := mapping.node.Value + refValue := utils.NodeAlias(mapping.node).Value // Skip empty values if refValue == "" { diff --git a/bundler/composed_fragments.go b/bundler/composed_fragments.go index adf4772a..52266601 100644 --- a/bundler/composed_fragments.go +++ b/bundler/composed_fragments.go @@ -74,13 +74,29 @@ func collectComposedReferences(c *compositionContext, rolodex *index.Rolodex, re definition, bucket string } seen := make(map[targetKey]bool) - enqueue := func(pr *processRef, bucket string) { - key := targetKey{pr.idx, pr.ref.FullDefinition, bucket} - if !seen[key] { - seen[key] = true - pending = append(pending, compositionFragment{pr.idx, pr.ref.Node, key.definition, bucket}) + enqueue := func(idx *index.SpecIndex, definition, bucket string, node *yaml.Node) { + key := targetKey{idx, definition, bucket} + if seen[key] { + return } + seen[key] = true + if idx == c.rootIdx { + // Most root-local references target schemas already visited in the root. + // Follow pointers into other locations without lifting the root node. + if mapped := idx.GetMappedReferences()[definition]; mapped != nil && bucket == v3.SchemasLabel { + if _, visited := files[idx].schemas[discriminatorValidationNode(mapped.Node)]; visited { + return + } + } + ref := idx.FindComponentInRoot(context.Background(), definition) + if ref == nil { + return + } + node = ref.Node + } + pending = append(pending, compositionFragment{idx, node, definition, bucket}) } + rootPath := c.rootIdx.GetSpecAbsolutePath() for len(pending) > 0 { fragment := pending[len(pending)-1] pending = pending[:len(pending)-1] @@ -98,7 +114,18 @@ func collectComposedReferences(c *compositionContext, rolodex *index.Rolodex, re for _, pr := range enqueueDiscriminatorMappingTargets(mappings, c, c.rootIdx) { if pr.idx != nil && pr.idx != c.rootIdx { indexes[pr.idx.GetSpecAbsolutePath()] = pr.idx - enqueue(pr, v3.SchemasLabel) + enqueue(pr.idx, pr.ref.FullDefinition, v3.SchemasLabel, pr.ref.Node) + } + } + if idx == c.rootIdx { + for _, mapping := range mappings { + if value := utils.NodeAlias(mapping.node).Value; strings.HasPrefix(value, "#/") { + enqueue(idx, rootPath+value, v3.SchemasLabel, nil) + } + } + if fragment.definition != "" { + // The full root already supplied its ordinary indexed references. + continue } } refs := file.references(idx, node, fragment.definition) @@ -114,11 +141,17 @@ func collectComposedReferences(c *compositionContext, rolodex *index.Rolodex, re return fmt.Errorf("invalid OpenAPI 3.0 specification: $ref cannot have sibling properties. Found $ref '%s' with siblings %v at line %d, column %d", ref.FullDefinition, keys, ref.Node.Line, ref.Node.Column) } - pr := resolveComposedReference(idx, ref, c.rootIdx, indexes) - reachable[ref] = pr - if pr != nil { - bucket, _ := inferComponentTypeFromSourcePath(ref.SourcePath) - enqueue(pr, bucket) + bucket, _ := inferComponentTypeFromSourcePath(ref.SourcePath) + path, _, _ := strings.Cut(ref.FullDefinition, "#/") + if path == rootPath { + reachable[ref] = nil + enqueue(c.rootIdx, ref.FullDefinition, bucket, nil) + } else { + pr := resolveComposedReference(idx, ref, path, indexes) + reachable[ref] = pr + if pr != nil { + enqueue(pr.idx, pr.ref.FullDefinition, bucket, pr.ref.Node) + } } } } @@ -169,7 +202,7 @@ func (f *fragmentIndex) collectMappings(fragment compositionFragment) ([]*discri if err := base.ValidateDiscriminatorMappingValueNodes(d); err != nil { return err } - visitDiscriminatorMappingValues(d, func(value *yaml.Node) { + visitDiscriminatorMappingValues(d, true, func(value *yaml.Node) { mappings = append(mappings, &discriminatorMappingWithContext{node: value, sourceIdx: fragment.idx}) }) return nil @@ -353,11 +386,7 @@ func fragmentSourcePath(root *yaml.Node, definition string) []string { return path } -func resolveComposedReference(source *index.SpecIndex, ref *index.Reference, root *index.SpecIndex, indexes map[string]*index.SpecIndex) *processRef { - path, _, _ := strings.Cut(ref.FullDefinition, "#/") - if path == root.GetSpecAbsolutePath() { - return nil - } +func resolveComposedReference(source *index.SpecIndex, ref *index.Reference, path string, indexes map[string]*index.SpecIndex) *processRef { target := source.GetMappedReferences()[ref.FullDefinition] if target == nil { target, _ = source.SearchIndexForReference(ref.FullDefinition) diff --git a/bundler/composed_fragments_test.go b/bundler/composed_fragments_test.go index 18547efe..38bbeb00 100644 --- a/bundler/composed_fragments_test.go +++ b/bundler/composed_fragments_test.go @@ -101,6 +101,7 @@ paths: {} components: schemas: Pet: + example: {discriminator: {mapping: {wolf: './breeds.yaml#/components/schemas/Wolf'}}} oneOf: - {$ref: './animals.yaml#/components/schemas/Feline'} - {$ref: './animals.yaml#/components/schemas/Canine'} @@ -148,6 +149,11 @@ components: } require.Equal(t, "#/components/schemas/id", schemas.GetOrZero("Tabby").Schema().Properties.GetOrZero("id").GetReference()) require.Equal(t, "urn:example:other", schemas.GetOrZero("Feline").Schema().Discriminator.Mapping.GetOrZero("other")) + var example struct { + Discriminator struct{ Mapping map[string]string } + } + require.NoError(t, schemas.GetOrZero("Pet").Schema().Example.Decode(&example)) + require.Equal(t, "./breeds.yaml#/components/schemas/Wolf", example.Discriminator.Mapping["wolf"]) if origins != nil { require.Len(t, origins, schemas.Len()-1) // Pet is declared in the root. require.Contains(t, origins, "#/components/schemas/Tabby") @@ -275,7 +281,7 @@ func TestComposedMissingFragment(t *testing.T) { external := rolodex.GetIndexes()[0] path := external.GetSpecAbsolutePath() missing := &index.Reference{FullDefinition: path + "#/missing"} - require.Nil(t, resolveComposedReference(root, missing, root, map[string]*index.SpecIndex{path: external})) + require.Nil(t, resolveComposedReference(root, missing, path, map[string]*index.SpecIndex{path: external})) } func TestComposedDiscriminatorInRequestBody(t *testing.T) { @@ -284,8 +290,11 @@ info: {title: Animals, version: '1'} paths: /pets: post: - requestBody: {$ref: './requests.yaml#/components/requestBodies/Pet'} + requestBody: {$ref: '#/components/requestBodies/Request'} responses: {'200': {description: ok}} +components: + requestBodies: + Request: {$ref: './requests.yaml#/components/requestBodies/Pet'} ` cfg := externalRegressionConfig(t, map[string]string{ "requests.yaml": `components: @@ -307,3 +316,161 @@ paths: require.NotNil(t, doc.Components.Schemas.GetOrZero("cat")) }) } + +func TestComposedDiscriminatorInNamedComponents(t *testing.T) { + const root = `openapi: 3.1.0 +info: {title: Animals, version: '1'} +paths: {} +components: + schemas: + example: {$ref: './animals.yaml#/Animal'} + responses: + RESPONSE_NAME: + description: ok + content: + application/json: + schema: {type: object, discriminator: {propertyName: kind, mapping: {dog: './dog.yaml'}}} +` + cfg := externalRegressionConfig(t, map[string]string{ + "animals.yaml": "Animal: {type: object, discriminator: {propertyName: kind, mapping: {cat: './cat.yaml'}}}", + "cat.yaml": "type: string", "dog.yaml": "type: integer", + }) + for _, name := range []string{"example", "examples", "schema", "x-pet"} { + t.Run(name, func(t *testing.T) { + checkComposedAPIs(t, strings.ReplaceAll(root, "RESPONSE_NAME", name), cfg, func(t *testing.T, doc *v3.Document, _ ComponentOriginMap) { + s := doc.Components.Schemas + require.Equal(t, []string{"string"}, s.GetOrZero("cat").Schema().Type) + require.Equal(t, []string{"integer"}, s.GetOrZero("dog").Schema().Type) + require.Equal(t, "#/components/schemas/cat", s.GetOrZero("example").Schema().Discriminator.Mapping.GetOrZero("cat")) + response := doc.Components.Responses.GetOrZero(name) + require.Equal(t, "#/components/schemas/dog", response.Content.GetOrZero("application/json").Schema.Schema().Discriminator.Mapping.GetOrZero("dog")) + }) + }) + } +} + +func TestComposedMappingThroughRootPointer(t *testing.T) { + const root = `openapi: 3.1.0 +info: {title: Animals, version: '1'} +paths: {} +components: + schemas: + Species: {$ref: '#/x-species'} +x-species: + type: object + discriminator: {propertyName: kind, mapping: {feline: '#/x-feline', unknown: '#/missing'}} +x-feline: + type: object + discriminator: {propertyName: breed, mapping: {cat: './cat.yaml'}} +x-unused: + discriminator: {propertyName: kind, mapping: {dog: './dog.yaml'}} +` + cfg := externalRegressionConfig(t, map[string]string{"cat.yaml": "type: string", "dog.yaml": "type: integer"}) + checkComposedAPIs(t, root, cfg, func(t *testing.T, doc *v3.Document, origins ComponentOriginMap) { + s := doc.Components.Schemas + require.ElementsMatch(t, []string{"Species", "cat"}, slices.Collect(s.KeysFromOldest())) + require.Equal(t, "#/x-species", s.GetOrZero("Species").GetReference()) + require.Equal(t, "#/missing", s.GetOrZero("Species").Schema().Discriminator.Mapping.GetOrZero("unknown")) + var feline struct { + Discriminator struct{ Mapping map[string]string } + } + require.NoError(t, doc.Extensions.GetOrZero("x-feline").Decode(&feline)) + require.Equal(t, "#/components/schemas/cat", feline.Discriminator.Mapping["cat"]) + if origins != nil { + require.Len(t, origins, 1) + } + }) +} + +func TestComposedInvalidMappingInNamedResponse(t *testing.T) { + document := parseYAMLNode(t, []byte(`components: + responses: + examples: + description: ok + content: + application/json: + schema: {discriminator: {propertyName: kind, mapping: {cat: [invalid]}}} +`)) + _, err := (&fragmentIndex{schemas: make(map[*yaml.Node]struct{})}).collectMappings(compositionFragment{node: document}) + require.ErrorContains(t, err, "discriminator.mapping.cat") +} + +func TestComposedDiscriminatorScalarAlias(t *testing.T) { + const root = `openapi: 3.1.0 +info: {title: Animals, version: '1'} +paths: {} +x-original-url: &file './cat.yaml' +components: + schemas: + Pet: + description: *file + type: object + discriminator: {propertyName: kind, mapping: {cat: *file}} +` + cfg := externalRegressionConfig(t, map[string]string{"cat.yaml": "type: string"}) + checkComposedAPIs(t, root, cfg, func(t *testing.T, doc *v3.Document, _ ComponentOriginMap) { + pet := doc.Components.Schemas.GetOrZero("Pet").Schema() + require.Equal(t, "./cat.yaml", doc.Extensions.GetOrZero("x-original-url").Value) + require.Equal(t, "./cat.yaml", pet.Description) + require.Equal(t, "#/components/schemas/cat", pet.Discriminator.Mapping.GetOrZero("cat")) + }) +} + +func TestInlineLiteralMappingAlias(t *testing.T) { + const root = `openapi: 3.1.0 +info: {title: Examples, version: '1'} +paths: {} +x-doc-example: + values: &values {cat: './types.yaml#/components/schemas/Cat'} + discriminator: {propertyName: sample, mapping: *values} +` + cfg := externalRegressionConfig(t, map[string]string{"types.yaml": "components: {schemas: {Cat: {type: string}}}"}) + out, err := BundleBytesWithConfig([]byte(root), cfg, &BundleInlineConfig{ResolveDiscriminatorExternalRefs: true}) + require.NoError(t, err) + doc := parseBundledV3Document(t, out) + require.Nil(t, doc.Components) + var literal struct { + Discriminator struct{ Mapping map[string]string } + } + require.NoError(t, doc.Extensions.GetOrZero("x-doc-example").Decode(&literal)) + require.Equal(t, "./types.yaml#/components/schemas/Cat", literal.Discriminator.Mapping["cat"]) +} + +func TestComposedBytesStrictValidationIgnoresUnusedFragment(t *testing.T) { + const root = `openapi: 3.0.3 +info: {title: Animals, version: '1'} +paths: {} +components: + schemas: + Animal: {$ref: './models.yaml#/components/schemas/Pet'} +` + cfg := externalRegressionConfig(t, map[string]string{ + "models.yaml": `openapi: 3.0.3 +info: {title: Models, version: '1'} +paths: {} +components: + schemas: + Pet: {type: object, discriminator: {propertyName: kind, mapping: {cat: './cat.yaml'}}} + Unused: {$ref: './dog.yaml', description: invalid sibling in OpenAPI 3.0} +`, + "cat.yaml": "type: string", "dog.yaml": "type: integer", + }) + composition := &BundleCompositionConfig{StrictValidation: true} + check := func(t *testing.T, out []byte) { + t.Helper() + schemas := parseBundledV3Document(t, out).Components.Schemas + require.ElementsMatch(t, []string{"Animal", "Pet", "cat"}, slices.Collect(schemas.KeysFromOldest())) + require.Equal(t, "#/components/schemas/cat", schemas.GetOrZero("Pet").Schema().Discriminator.Mapping.GetOrZero("cat")) + } + t.Run("BundleBytesComposed", func(t *testing.T) { + out, err := BundleBytesComposed([]byte(root), cfg, composition) + require.NoError(t, err) + check(t, out) + }) + t.Run("BundleBytesComposedWithOrigins", func(t *testing.T) { + result, err := BundleBytesComposedWithOrigins([]byte(root), cfg, composition) + require.NoError(t, err) + check(t, result.Bytes) + require.Len(t, result.Origins, 2) + }) +} diff --git a/bundler/source_context.go b/bundler/source_context.go index 929e815c..a90f8037 100644 --- a/bundler/source_context.go +++ b/bundler/source_context.go @@ -18,6 +18,16 @@ func inferComponentTypeFromSourcePath(sourcePath []string) (string, bool) { if len(sourcePath) == 0 { return "", false } + // At a component definition the final segment is a name, even when it + // matches an OpenAPI keyword such as "example" or "schema". + if len(sourcePath) == 3 && sourcePath[0] == v3.ComponentsLabel { + switch bucket := sourcePath[1]; bucket { + case v3.SchemasLabel, v3.ResponsesLabel, v3.ParametersLabel, v3.ExamplesLabel, + v3.RequestBodiesLabel, v3.HeadersLabel, v3.SecuritySchemesLabel, v3.LinksLabel, + v3.CallbacksLabel, v3.PathItemsLabel, v3.MediaTypesLabel: + return bucket, true + } + } for i := len(sourcePath) - 1; i >= 0; i-- { segment := sourcePath[i] @@ -35,28 +45,15 @@ func inferComponentTypeFromSourcePath(sourcePath []string) (string, bool) { } switch previous { - case v3.ResponsesLabel: - return v3.ResponsesLabel, true - case v3.ParametersLabel: - return v3.ParametersLabel, true - case v3.HeadersLabel: - return v3.HeadersLabel, true - case v3.ExamplesLabel: - return v3.ExamplesLabel, true - case v3.LinksLabel: - return v3.LinksLabel, true + case v3.ResponsesLabel, v3.ParametersLabel, v3.HeadersLabel, v3.ExamplesLabel, + v3.LinksLabel, v3.PathItemsLabel, v3.MediaTypesLabel, v3.SecuritySchemesLabel: + return previous, true case v3.CallbacksLabel: if i == len(sourcePath)-1 { return v3.CallbacksLabel, true } - case v3.PathItemsLabel: - return v3.PathItemsLabel, true - case v3.MediaTypesLabel: - return v3.MediaTypesLabel, true case v3.ContentLabel: return v3.MediaTypesLabel, true - case v3.SecuritySchemesLabel: - return v3.SecuritySchemesLabel, true } if segment == v3.RequestBodyLabel { From c84257dec11b7393984424d40d27d293fcdbcb3b Mon Sep 17 00:00:00 2001 From: quobix Date: Sun, 29 Nov 2026 15:33:33 -0500 Subject: [PATCH 4/4] fix(bundler): isolate aliased discriminator mappings before rewrite --- bundler/bundler.go | 26 +++++++++++++++++++---- bundler/composed_fragments_test.go | 34 ++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/bundler/bundler.go b/bundler/bundler.go index f76d290d..1c6c8327 100644 --- a/bundler/bundler.go +++ b/bundler/bundler.go @@ -184,7 +184,8 @@ func (visit discriminatorVisitor) schema(n *yaml.Node, seen map[*yaml.Node]struc } seen[n] = struct{}{} - content := utils.ResolveMergeNodes(n).Content + effective := utils.ResolveMergeNodes(n) + content := effective.Content for i := 0; i < len(content); i += 2 { keyNode := utils.NodeAlias(content[i]) valueNode := utils.NodeAlias(content[i+1]) @@ -194,7 +195,14 @@ func (visit discriminatorVisitor) schema(n *yaml.Node, seen map[*yaml.Node]struc key := keyNode.Value switch { case key == lowbase.DiscriminatorLabel: - if err := visit(valueNode); err != nil { + d := content[i+1] + if effective != n && !slices.Contains(n.Content, content[i]) { + // Override the inherited field on this schema before the visitor + // rewrites it. The merge source can also be a literal example. + d = utils.CloneYAMLNodeWithFlags(d, utils.YAMLNodeCloneStripAnchors) + n.Content = append(n.Content, content[i], d) + } + if err := visit(d); err != nil { return err } case isDirectSchemaChildKey(key): @@ -1002,7 +1010,7 @@ func walkDiscriminatorMappingNodes(n *yaml.Node, yield func(*yaml.Node)) { func visitDiscriminatorMappingValues(discriminator *yaml.Node, resolveAliases bool, yield func(*yaml.Node)) { if resolveAliases { - discriminator = utils.ResolveMergeNodes(discriminator) + discriminator = ownDiscriminatorMappingNode(discriminator) } if discriminator == nil || discriminator.Kind != yaml.MappingNode { return @@ -1013,7 +1021,7 @@ func visitDiscriminatorMappingValues(discriminator *yaml.Node, resolveAliases bo } mapping := discriminator.Content[i+1] if resolveAliases { - mapping = utils.ResolveMergeNodes(mapping) + mapping = ownDiscriminatorMappingNode(mapping) } if mapping == nil || mapping.Kind != yaml.MappingNode { continue @@ -1024,6 +1032,16 @@ func visitDiscriminatorMappingValues(discriminator *yaml.Node, resolveAliases bo } } +// Materialize an aliased or merged object at this use before rewriting its +// mapping values. Other uses of the same anchor keep their authored values. +func ownDiscriminatorMappingNode(n *yaml.Node) *yaml.Node { + resolved := utils.ResolveMergeNodes(n) + if resolved != nil && resolved != n { + *n = *utils.CloneYAMLNodeWithFlags(resolved, utils.YAMLNodeCloneStripAnchors) + } + return n +} + // updateDiscriminatorMappingsComposed updates discriminator mapping references to point to composed component locations. func updateDiscriminatorMappingsComposed(mappings []*discriminatorMappingWithContext, processedNodes *orderedmap.Map[string, *processRef], rolodex *index.Rolodex) { for _, mapping := range mappings { diff --git a/bundler/composed_fragments_test.go b/bundler/composed_fragments_test.go index 38bbeb00..30b50596 100644 --- a/bundler/composed_fragments_test.go +++ b/bundler/composed_fragments_test.go @@ -416,6 +416,40 @@ components: }) } +func TestComposedDiscriminatorMappingAliasKeepsLiteral(t *testing.T) { + const root = `openapi: 3.1.0 +info: {title: Animals, version: '1'} +paths: {} +components: + schemas: + Literal: + type: object + example: {lookup: &value LITERAL} + Pet: SCHEMA +` + const table = "{cat: './cat.yaml'}" + const discriminator = "{propertyName: kind, mapping: " + table + "}" + cfg := externalRegressionConfig(t, map[string]string{"cat.yaml": "type: string"}) + for _, tc := range []struct{ name, literal, schema string }{ + {"mapping alias", table, "{type: object, discriminator: {propertyName: kind, mapping: *value}}"}, + {"mapping merge", table, "{type: object, discriminator: {propertyName: kind, mapping: {<<: *value}}}"}, + {"discriminator alias", discriminator, "{type: object, discriminator: *value}"}, + {"discriminator merge", discriminator, "{type: object, discriminator: {<<: *value}}"}, + {"schema merge", "{type: object, discriminator: " + discriminator + "}", "{<<: *value}"}, + } { + t.Run(tc.name, func(t *testing.T) { + spec := strings.NewReplacer("LITERAL", tc.literal, "SCHEMA", tc.schema).Replace(root) + checkComposedAPIs(t, spec, cfg, func(t *testing.T, doc *v3.Document, _ ComponentOriginMap) { + s := doc.Components.Schemas + example, err := yaml.Marshal(s.GetOrZero("Literal").Schema().Example) + require.NoError(t, err) + require.Contains(t, string(example), "./cat.yaml") + require.Equal(t, "#/components/schemas/cat", s.GetOrZero("Pet").Schema().Discriminator.Mapping.GetOrZero("cat")) + }) + }) + } +} + func TestInlineLiteralMappingAlias(t *testing.T) { const root = `openapi: 3.1.0 info: {title: Examples, version: '1'}