diff --git a/.goreleaser.yml b/.goreleaser.yml index 2911b58f..10f8b994 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -1,9 +1,9 @@ # Visit https://goreleaser.com for documentation on how to customize this # behavior. -before: - hooks: - # this is just an example and not a requirement for provider building/publishing - - go mod tidy +# before: +# hooks: +# # this is just an example and not a requirement for provider building/publishing +# - go mod tidy builds: - env: # goreleaser does not work with CGO, it could also complicate diff --git a/go.mod b/go.mod index 7416c5d2..13f80d05 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,6 @@ require ( github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue v1.8.0 github.com/aws/aws-sdk-go-v2/service/dynamodb v1.15.0 github.com/aws/smithy-go v1.11.1 - github.com/getkin/kin-openapi v0.92.0 github.com/go-openapi/spec v0.20.4 github.com/go-openapi/strfmt v0.21.2 github.com/go-openapi/validate v0.21.0 diff --git a/go.sum b/go.sum index 0742d05a..af601f44 100644 --- a/go.sum +++ b/go.sum @@ -78,9 +78,6 @@ github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7 github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= -github.com/getkin/kin-openapi v0.92.0 h1:lR1imqtGufk9Iv5dQoGwWbBP2SMcwI2ndIydSqwUyBI= -github.com/getkin/kin-openapi v0.92.0/go.mod h1:LWZfzOd7PRy8GJ1dJ6mCU6tNdSfOwRac1BUPam4aw6Q= -github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gliderlabs/ssh v0.2.2/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= github.com/go-git/gcfg v1.5.0 h1:Q5ViNfGF8zFgyJWPqYwA7qGFoMTEiBmdlkcfRmpIMa4= @@ -176,7 +173,6 @@ github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8 github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= diff --git a/vendor/github.com/getkin/kin-openapi/LICENSE b/vendor/github.com/getkin/kin-openapi/LICENSE deleted file mode 100644 index 992b9831..00000000 --- a/vendor/github.com/getkin/kin-openapi/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017-2018 the project authors. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/getkin/kin-openapi/jsoninfo/doc.go b/vendor/github.com/getkin/kin-openapi/jsoninfo/doc.go deleted file mode 100644 index e59ec2c3..00000000 --- a/vendor/github.com/getkin/kin-openapi/jsoninfo/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package jsoninfo provides information and functions for marshalling/unmarshalling JSON. -package jsoninfo diff --git a/vendor/github.com/getkin/kin-openapi/jsoninfo/field_info.go b/vendor/github.com/getkin/kin-openapi/jsoninfo/field_info.go deleted file mode 100644 index 2382b731..00000000 --- a/vendor/github.com/getkin/kin-openapi/jsoninfo/field_info.go +++ /dev/null @@ -1,121 +0,0 @@ -package jsoninfo - -import ( - "reflect" - "strings" - "unicode" - "unicode/utf8" -) - -// FieldInfo contains information about JSON serialization of a field. -type FieldInfo struct { - MultipleFields bool // Whether multiple Go fields share this JSON name - HasJSONTag bool - TypeIsMarshaller bool - TypeIsUnmarshaller bool - JSONOmitEmpty bool - JSONString bool - Index []int - Type reflect.Type - JSONName string -} - -func AppendFields(fields []FieldInfo, parentIndex []int, t reflect.Type) []FieldInfo { - if t.Kind() == reflect.Ptr { - t = t.Elem() - } - // For each field - numField := t.NumField() -iteration: - for i := 0; i < numField; i++ { - f := t.Field(i) - index := make([]int, 0, len(parentIndex)+1) - index = append(index, parentIndex...) - index = append(index, i) - - // See whether this is an embedded field - if f.Anonymous { - if f.Tag.Get("json") == "-" { - continue - } - fields = AppendFields(fields, index, f.Type) - continue iteration - } - - // Ignore certain types - switch f.Type.Kind() { - case reflect.Func, reflect.Chan: - continue iteration - } - - // Is it a private (lowercase) field? - firstRune, _ := utf8.DecodeRuneInString(f.Name) - if unicode.IsLower(firstRune) { - continue iteration - } - - // Declare a field - field := FieldInfo{ - Index: index, - Type: f.Type, - JSONName: f.Name, - } - - // Read "json" tag - jsonTag := f.Tag.Get("json") - - // Read our custom "multijson" tag that - // allows multiple fields with the same name. - if v := f.Tag.Get("multijson"); v != "" { - field.MultipleFields = true - jsonTag = v - } - - // Handle "-" - if jsonTag == "-" { - continue - } - - // Parse the tag - if jsonTag != "" { - field.HasJSONTag = true - for i, part := range strings.Split(jsonTag, ",") { - if i == 0 { - if part != "" { - field.JSONName = part - } - } else { - switch part { - case "omitempty": - field.JSONOmitEmpty = true - case "string": - field.JSONString = true - } - } - } - } - - _, field.TypeIsMarshaller = field.Type.MethodByName("MarshalJSON") - _, field.TypeIsUnmarshaller = field.Type.MethodByName("UnmarshalJSON") - - // Field is done - fields = append(fields, field) - } - - return fields -} - -type sortableFieldInfos []FieldInfo - -func (list sortableFieldInfos) Len() int { - return len(list) -} - -func (list sortableFieldInfos) Less(i, j int) bool { - return list[i].JSONName < list[j].JSONName -} - -func (list sortableFieldInfos) Swap(i, j int) { - a, b := list[i], list[j] - list[i], list[j] = b, a -} diff --git a/vendor/github.com/getkin/kin-openapi/jsoninfo/marshal.go b/vendor/github.com/getkin/kin-openapi/jsoninfo/marshal.go deleted file mode 100644 index 2a98d68f..00000000 --- a/vendor/github.com/getkin/kin-openapi/jsoninfo/marshal.go +++ /dev/null @@ -1,162 +0,0 @@ -package jsoninfo - -import ( - "encoding/json" - "fmt" - "reflect" -) - -// MarshalStrictStruct function: -// * Marshals struct fields, ignoring MarshalJSON() and fields without 'json' tag. -// * Correctly handles StrictStruct semantics. -func MarshalStrictStruct(value StrictStruct) ([]byte, error) { - encoder := NewObjectEncoder() - if err := value.EncodeWith(encoder, value); err != nil { - return nil, err - } - return encoder.Bytes() -} - -type ObjectEncoder struct { - result map[string]json.RawMessage -} - -func NewObjectEncoder() *ObjectEncoder { - return &ObjectEncoder{ - result: make(map[string]json.RawMessage, 8), - } -} - -// Bytes returns the result of encoding. -func (encoder *ObjectEncoder) Bytes() ([]byte, error) { - return json.Marshal(encoder.result) -} - -// EncodeExtension adds a key/value to the current JSON object. -func (encoder *ObjectEncoder) EncodeExtension(key string, value interface{}) error { - data, err := json.Marshal(value) - if err != nil { - return err - } - encoder.result[key] = data - return nil -} - -// EncodeExtensionMap adds all properties to the result. -func (encoder *ObjectEncoder) EncodeExtensionMap(value map[string]json.RawMessage) error { - if value != nil { - result := encoder.result - for k, v := range value { - result[k] = v - } - } - return nil -} - -func (encoder *ObjectEncoder) EncodeStructFieldsAndExtensions(value interface{}) error { - reflection := reflect.ValueOf(value) - - // Follow "encoding/json" semantics - if reflection.Kind() != reflect.Ptr { - // Panic because this is a clear programming error - panic(fmt.Errorf("value %s is not a pointer", reflection.Type().String())) - } - if reflection.IsNil() { - // Panic because this is a clear programming error - panic(fmt.Errorf("value %s is nil", reflection.Type().String())) - } - - // Take the element - reflection = reflection.Elem() - - // Obtain typeInfo - typeInfo := GetTypeInfo(reflection.Type()) - - // Declare result - result := encoder.result - - // Supported fields -iteration: - for _, field := range typeInfo.Fields { - // Fields without JSON tag are ignored - if !field.HasJSONTag { - continue - } - - // Marshal - fieldValue := reflection.FieldByIndex(field.Index) - if v, ok := fieldValue.Interface().(json.Marshaler); ok { - if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() { - if field.JSONOmitEmpty { - continue iteration - } - result[field.JSONName] = []byte("null") - continue - } - fieldData, err := v.MarshalJSON() - if err != nil { - return err - } - result[field.JSONName] = fieldData - continue - } - switch fieldValue.Kind() { - case reflect.Ptr, reflect.Interface: - if fieldValue.IsNil() { - if field.JSONOmitEmpty { - continue iteration - } - result[field.JSONName] = []byte("null") - continue - } - case reflect.Struct: - case reflect.Map: - if field.JSONOmitEmpty && (fieldValue.IsNil() || fieldValue.Len() == 0) { - continue iteration - } - case reflect.Slice: - if field.JSONOmitEmpty && fieldValue.Len() == 0 { - continue iteration - } - case reflect.Bool: - x := fieldValue.Bool() - if field.JSONOmitEmpty && !x { - continue iteration - } - s := "false" - if x { - s = "true" - } - result[field.JSONName] = []byte(s) - continue iteration - case reflect.Int64, reflect.Int, reflect.Int32: - if field.JSONOmitEmpty && fieldValue.Int() == 0 { - continue iteration - } - case reflect.Uint64, reflect.Uint, reflect.Uint32: - if field.JSONOmitEmpty && fieldValue.Uint() == 0 { - continue iteration - } - case reflect.Float64: - if field.JSONOmitEmpty && fieldValue.Float() == 0.0 { - continue iteration - } - case reflect.String: - if field.JSONOmitEmpty && len(fieldValue.String()) == 0 { - continue iteration - } - default: - panic(fmt.Errorf("field %q has unsupported type %s", field.JSONName, field.Type.String())) - } - - // No special treament is needed - // Use plain old "encoding/json".Marshal - fieldData, err := json.Marshal(fieldValue.Addr().Interface()) - if err != nil { - return err - } - result[field.JSONName] = fieldData - } - - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/jsoninfo/marshal_ref.go b/vendor/github.com/getkin/kin-openapi/jsoninfo/marshal_ref.go deleted file mode 100644 index 29575e9e..00000000 --- a/vendor/github.com/getkin/kin-openapi/jsoninfo/marshal_ref.go +++ /dev/null @@ -1,30 +0,0 @@ -package jsoninfo - -import ( - "encoding/json" -) - -func MarshalRef(value string, otherwise interface{}) ([]byte, error) { - if value != "" { - return json.Marshal(&refProps{ - Ref: value, - }) - } - return json.Marshal(otherwise) -} - -func UnmarshalRef(data []byte, destRef *string, destOtherwise interface{}) error { - refProps := &refProps{} - if err := json.Unmarshal(data, refProps); err == nil { - ref := refProps.Ref - if ref != "" { - *destRef = ref - return nil - } - } - return json.Unmarshal(data, destOtherwise) -} - -type refProps struct { - Ref string `json:"$ref,omitempty" yaml:"$ref,omitempty"` -} diff --git a/vendor/github.com/getkin/kin-openapi/jsoninfo/strict_struct.go b/vendor/github.com/getkin/kin-openapi/jsoninfo/strict_struct.go deleted file mode 100644 index 6b4d8397..00000000 --- a/vendor/github.com/getkin/kin-openapi/jsoninfo/strict_struct.go +++ /dev/null @@ -1,6 +0,0 @@ -package jsoninfo - -type StrictStruct interface { - EncodeWith(encoder *ObjectEncoder, value interface{}) error - DecodeWith(decoder *ObjectDecoder, value interface{}) error -} diff --git a/vendor/github.com/getkin/kin-openapi/jsoninfo/type_info.go b/vendor/github.com/getkin/kin-openapi/jsoninfo/type_info.go deleted file mode 100644 index 3dbb8d5d..00000000 --- a/vendor/github.com/getkin/kin-openapi/jsoninfo/type_info.go +++ /dev/null @@ -1,68 +0,0 @@ -package jsoninfo - -import ( - "reflect" - "sort" - "sync" -) - -var ( - typeInfos = map[reflect.Type]*TypeInfo{} - typeInfosMutex sync.RWMutex -) - -// TypeInfo contains information about JSON serialization of a type -type TypeInfo struct { - Type reflect.Type - Fields []FieldInfo -} - -func GetTypeInfoForValue(value interface{}) *TypeInfo { - return GetTypeInfo(reflect.TypeOf(value)) -} - -// GetTypeInfo returns TypeInfo for the given type. -func GetTypeInfo(t reflect.Type) *TypeInfo { - for t.Kind() == reflect.Ptr { - t = t.Elem() - } - typeInfosMutex.RLock() - typeInfo, exists := typeInfos[t] - typeInfosMutex.RUnlock() - if exists { - return typeInfo - } - if t.Kind() != reflect.Struct { - typeInfo = &TypeInfo{ - Type: t, - } - } else { - // Allocate - typeInfo = &TypeInfo{ - Type: t, - Fields: make([]FieldInfo, 0, 16), - } - - // Add fields - typeInfo.Fields = AppendFields(nil, nil, t) - - // Sort fields - sort.Sort(sortableFieldInfos(typeInfo.Fields)) - } - - // Publish - typeInfosMutex.Lock() - typeInfos[t] = typeInfo - typeInfosMutex.Unlock() - return typeInfo -} - -// FieldNames returns all field names -func (typeInfo *TypeInfo) FieldNames() []string { - fields := typeInfo.Fields - names := make([]string, 0, len(fields)) - for _, field := range fields { - names = append(names, field.JSONName) - } - return names -} diff --git a/vendor/github.com/getkin/kin-openapi/jsoninfo/unmarshal.go b/vendor/github.com/getkin/kin-openapi/jsoninfo/unmarshal.go deleted file mode 100644 index ce3c337a..00000000 --- a/vendor/github.com/getkin/kin-openapi/jsoninfo/unmarshal.go +++ /dev/null @@ -1,121 +0,0 @@ -package jsoninfo - -import ( - "encoding/json" - "fmt" - "reflect" -) - -// UnmarshalStrictStruct function: -// * Unmarshals struct fields, ignoring UnmarshalJSON(...) and fields without 'json' tag. -// * Correctly handles StrictStruct -func UnmarshalStrictStruct(data []byte, value StrictStruct) error { - decoder, err := NewObjectDecoder(data) - if err != nil { - return err - } - return value.DecodeWith(decoder, value) -} - -type ObjectDecoder struct { - Data []byte - remainingFields map[string]json.RawMessage -} - -func NewObjectDecoder(data []byte) (*ObjectDecoder, error) { - var remainingFields map[string]json.RawMessage - if err := json.Unmarshal(data, &remainingFields); err != nil { - return nil, fmt.Errorf("failed to unmarshal extension properties: %v (%s)", err, data) - } - return &ObjectDecoder{ - Data: data, - remainingFields: remainingFields, - }, nil -} - -// DecodeExtensionMap returns all properties that were not decoded previously. -func (decoder *ObjectDecoder) DecodeExtensionMap() map[string]json.RawMessage { - return decoder.remainingFields -} - -func (decoder *ObjectDecoder) DecodeStructFieldsAndExtensions(value interface{}) error { - reflection := reflect.ValueOf(value) - if reflection.Kind() != reflect.Ptr { - panic(fmt.Errorf("value %T is not a pointer", value)) - } - if reflection.IsNil() { - panic(fmt.Errorf("value %T is nil", value)) - } - reflection = reflection.Elem() - for (reflection.Kind() == reflect.Interface || reflection.Kind() == reflect.Ptr) && !reflection.IsNil() { - reflection = reflection.Elem() - } - reflectionType := reflection.Type() - if reflectionType.Kind() != reflect.Struct { - panic(fmt.Errorf("value %T is not a struct", value)) - } - typeInfo := GetTypeInfo(reflectionType) - - // Supported fields - fields := typeInfo.Fields - remainingFields := decoder.remainingFields - for fieldIndex, field := range fields { - // Fields without JSON tag are ignored - if !field.HasJSONTag { - continue - } - - // Get data - fieldData, exists := remainingFields[field.JSONName] - if !exists { - continue - } - - // Unmarshal - if field.TypeIsUnmarshaller { - fieldType := field.Type - isPtr := false - if fieldType.Kind() == reflect.Ptr { - fieldType = fieldType.Elem() - isPtr = true - } - fieldValue := reflect.New(fieldType) - if err := fieldValue.Interface().(json.Unmarshaler).UnmarshalJSON(fieldData); err != nil { - if field.MultipleFields { - i := fieldIndex + 1 - if i < len(fields) && fields[i].JSONName == field.JSONName { - continue - } - } - return fmt.Errorf("failed to unmarshal property %q (%s): %v", - field.JSONName, fieldValue.Type().String(), err) - } - if !isPtr { - fieldValue = fieldValue.Elem() - } - reflection.FieldByIndex(field.Index).Set(fieldValue) - - // Remove the field from remaining fields - delete(remainingFields, field.JSONName) - } else { - fieldPtr := reflection.FieldByIndex(field.Index) - if fieldPtr.Kind() != reflect.Ptr || fieldPtr.IsNil() { - fieldPtr = fieldPtr.Addr() - } - if err := json.Unmarshal(fieldData, fieldPtr.Interface()); err != nil { - if field.MultipleFields { - i := fieldIndex + 1 - if i < len(fields) && fields[i].JSONName == field.JSONName { - continue - } - } - return fmt.Errorf("failed to unmarshal property %q (%s): %v", - field.JSONName, fieldPtr.Type().String(), err) - } - - // Remove the field from remaining fields - delete(remainingFields, field.JSONName) - } - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/jsoninfo/unsupported_properties_error.go b/vendor/github.com/getkin/kin-openapi/jsoninfo/unsupported_properties_error.go deleted file mode 100644 index f69aafdc..00000000 --- a/vendor/github.com/getkin/kin-openapi/jsoninfo/unsupported_properties_error.go +++ /dev/null @@ -1,42 +0,0 @@ -package jsoninfo - -import ( - "encoding/json" - "fmt" - "sort" -) - -// UnsupportedPropertiesError is a helper for extensions that want to refuse -// unsupported JSON object properties. -// -// It produces a helpful error message. -type UnsupportedPropertiesError struct { - Value interface{} - UnsupportedProperties map[string]json.RawMessage -} - -func NewUnsupportedPropertiesError(v interface{}, m map[string]json.RawMessage) error { - return &UnsupportedPropertiesError{ - Value: v, - UnsupportedProperties: m, - } -} - -func (err *UnsupportedPropertiesError) Error() string { - m := err.UnsupportedProperties - typeInfo := GetTypeInfoForValue(err.Value) - if m == nil || typeInfo == nil { - return fmt.Sprintf("invalid %T", *err) - } - keys := make([]string, 0, len(m)) - for k := range m { - keys = append(keys, k) - } - sort.Strings(keys) - supported := typeInfo.FieldNames() - if len(supported) == 0 { - return fmt.Sprintf("type \"%T\" doesn't take any properties. Unsupported properties: %+v", - err.Value, keys) - } - return fmt.Sprintf("unsupported properties: %+v (supported properties are: %+v)", keys, supported) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/callback.go b/vendor/github.com/getkin/kin-openapi/openapi3/callback.go deleted file mode 100644 index 5f883c1c..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/callback.go +++ /dev/null @@ -1,37 +0,0 @@ -package openapi3 - -import ( - "context" - "fmt" - - "github.com/go-openapi/jsonpointer" -) - -type Callbacks map[string]*CallbackRef - -var _ jsonpointer.JSONPointable = (*Callbacks)(nil) - -func (c Callbacks) JSONLookup(token string) (interface{}, error) { - ref, ok := c[token] - if ref == nil || !ok { - return nil, fmt.Errorf("object has no field %q", token) - } - - if ref.Ref != "" { - return &Ref{Ref: ref.Ref}, nil - } - return ref.Value, nil -} - -// Callback is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#callbackObject -type Callback map[string]*PathItem - -func (value Callback) Validate(ctx context.Context) error { - for _, v := range value { - if err := v.Validate(ctx); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/components.go b/vendor/github.com/getkin/kin-openapi/openapi3/components.go deleted file mode 100644 index 42af634d..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/components.go +++ /dev/null @@ -1,109 +0,0 @@ -package openapi3 - -import ( - "context" - "fmt" - "regexp" - - "github.com/getkin/kin-openapi/jsoninfo" -) - -// Components is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#componentsObject -type Components struct { - ExtensionProps - - Schemas Schemas `json:"schemas,omitempty" yaml:"schemas,omitempty"` - Parameters ParametersMap `json:"parameters,omitempty" yaml:"parameters,omitempty"` - Headers Headers `json:"headers,omitempty" yaml:"headers,omitempty"` - RequestBodies RequestBodies `json:"requestBodies,omitempty" yaml:"requestBodies,omitempty"` - Responses Responses `json:"responses,omitempty" yaml:"responses,omitempty"` - SecuritySchemes SecuritySchemes `json:"securitySchemes,omitempty" yaml:"securitySchemes,omitempty"` - Examples Examples `json:"examples,omitempty" yaml:"examples,omitempty"` - Links Links `json:"links,omitempty" yaml:"links,omitempty"` - Callbacks Callbacks `json:"callbacks,omitempty" yaml:"callbacks,omitempty"` -} - -func NewComponents() Components { - return Components{} -} - -func (components *Components) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(components) -} - -func (components *Components) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, components) -} - -func (components *Components) Validate(ctx context.Context) (err error) { - for k, v := range components.Schemas { - if err = ValidateIdentifier(k); err != nil { - return - } - if err = v.Validate(ctx); err != nil { - return - } - } - - for k, v := range components.Parameters { - if err = ValidateIdentifier(k); err != nil { - return - } - if err = v.Validate(ctx); err != nil { - return - } - } - - for k, v := range components.RequestBodies { - if err = ValidateIdentifier(k); err != nil { - return - } - if err = v.Validate(ctx); err != nil { - return - } - } - - for k, v := range components.Responses { - if err = ValidateIdentifier(k); err != nil { - return - } - if err = v.Validate(ctx); err != nil { - return - } - } - - for k, v := range components.Headers { - if err = ValidateIdentifier(k); err != nil { - return - } - if err = v.Validate(ctx); err != nil { - return - } - } - - for k, v := range components.SecuritySchemes { - if err = ValidateIdentifier(k); err != nil { - return - } - if err = v.Validate(ctx); err != nil { - return - } - } - - return -} - -const identifierPattern = `^[a-zA-Z0-9._-]+$` - -// IdentifierRegExp verifies whether Component object key matches 'identifierPattern' pattern, according to OapiAPI v3.x.0. -// Hovever, to be able supporting legacy OpenAPI v2.x, there is a need to customize above pattern in orde not to fail -// converted v2-v3 validation -var IdentifierRegExp = regexp.MustCompile(identifierPattern) - -func ValidateIdentifier(value string) error { - if IdentifierRegExp.MatchString(value) { - return nil - } - return fmt.Errorf("identifier %q is not supported by OpenAPIv3 standard (regexp: %q)", value, identifierPattern) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/content.go b/vendor/github.com/getkin/kin-openapi/openapi3/content.go deleted file mode 100644 index 5edb7d3f..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/content.go +++ /dev/null @@ -1,115 +0,0 @@ -package openapi3 - -import ( - "context" - "strings" -) - -// Content is specified by OpenAPI/Swagger 3.0 standard. -type Content map[string]*MediaType - -func NewContent() Content { - return make(map[string]*MediaType, 4) -} - -func NewContentWithSchema(schema *Schema, consumes []string) Content { - if len(consumes) == 0 { - return Content{ - "*/*": NewMediaType().WithSchema(schema), - } - } - content := make(map[string]*MediaType, len(consumes)) - for _, mediaType := range consumes { - content[mediaType] = NewMediaType().WithSchema(schema) - } - return content -} - -func NewContentWithSchemaRef(schema *SchemaRef, consumes []string) Content { - if len(consumes) == 0 { - return Content{ - "*/*": NewMediaType().WithSchemaRef(schema), - } - } - content := make(map[string]*MediaType, len(consumes)) - for _, mediaType := range consumes { - content[mediaType] = NewMediaType().WithSchemaRef(schema) - } - return content -} - -func NewContentWithJSONSchema(schema *Schema) Content { - return Content{ - "application/json": NewMediaType().WithSchema(schema), - } -} -func NewContentWithJSONSchemaRef(schema *SchemaRef) Content { - return Content{ - "application/json": NewMediaType().WithSchemaRef(schema), - } -} - -func NewContentWithFormDataSchema(schema *Schema) Content { - return Content{ - "multipart/form-data": NewMediaType().WithSchema(schema), - } -} - -func NewContentWithFormDataSchemaRef(schema *SchemaRef) Content { - return Content{ - "multipart/form-data": NewMediaType().WithSchemaRef(schema), - } -} - -func (content Content) Get(mime string) *MediaType { - // If the mime is empty then short-circuit to the wildcard. - // We do this here so that we catch only the specific case of - // and empty mime rather than a present, but invalid, mime type. - if mime == "" { - return content["*/*"] - } - // Start by making the most specific match possible - // by using the mime type in full. - if v := content[mime]; v != nil { - return v - } - // If an exact match is not found then we strip all - // metadata from the mime type and only use the x/y - // portion. - i := strings.IndexByte(mime, ';') - if i < 0 { - // If there is no metadata then preserve the full mime type - // string for later wildcard searches. - i = len(mime) - } - mime = mime[:i] - if v := content[mime]; v != nil { - return v - } - // If the x/y pattern has no specific match then we - // try the x/* pattern. - i = strings.IndexByte(mime, '/') - if i < 0 { - // In the case that the given mime type is not valid because it is - // missing the subtype we return nil so that this does not accidentally - // resolve with the wildcard. - return nil - } - mime = mime[:i] + "/*" - if v := content[mime]; v != nil { - return v - } - // Finally, the most generic match of */* is returned - // as a catch-all. - return content["*/*"] -} - -func (value Content) Validate(ctx context.Context) error { - for _, v := range value { - // Validate MediaType - if err := v.Validate(ctx); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/discriminator.go b/vendor/github.com/getkin/kin-openapi/openapi3/discriminator.go deleted file mode 100644 index 5e181a29..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/discriminator.go +++ /dev/null @@ -1,28 +0,0 @@ -package openapi3 - -import ( - "context" - - "github.com/getkin/kin-openapi/jsoninfo" -) - -// Discriminator is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#discriminatorObject -type Discriminator struct { - ExtensionProps - - PropertyName string `json:"propertyName" yaml:"propertyName"` - Mapping map[string]string `json:"mapping,omitempty" yaml:"mapping,omitempty"` -} - -func (value *Discriminator) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(value) -} - -func (value *Discriminator) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, value) -} - -func (value *Discriminator) Validate(ctx context.Context) error { - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/doc.go b/vendor/github.com/getkin/kin-openapi/openapi3/doc.go deleted file mode 100644 index fc2735cb..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package openapi3 parses and writes OpenAPI 3 specification documents. -// -// See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md -package openapi3 diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/encoding.go b/vendor/github.com/getkin/kin-openapi/openapi3/encoding.go deleted file mode 100644 index b0dab7be..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/encoding.go +++ /dev/null @@ -1,94 +0,0 @@ -package openapi3 - -import ( - "context" - "fmt" - - "github.com/getkin/kin-openapi/jsoninfo" -) - -// Encoding is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#encodingObject -type Encoding struct { - ExtensionProps - - ContentType string `json:"contentType,omitempty" yaml:"contentType,omitempty"` - Headers Headers `json:"headers,omitempty" yaml:"headers,omitempty"` - Style string `json:"style,omitempty" yaml:"style,omitempty"` - Explode *bool `json:"explode,omitempty" yaml:"explode,omitempty"` - AllowReserved bool `json:"allowReserved,omitempty" yaml:"allowReserved,omitempty"` -} - -func NewEncoding() *Encoding { - return &Encoding{} -} - -func (encoding *Encoding) WithHeader(name string, header *Header) *Encoding { - return encoding.WithHeaderRef(name, &HeaderRef{ - Value: header, - }) -} - -func (encoding *Encoding) WithHeaderRef(name string, ref *HeaderRef) *Encoding { - headers := encoding.Headers - if headers == nil { - headers = make(map[string]*HeaderRef) - encoding.Headers = headers - } - headers[name] = ref - return encoding -} - -func (encoding *Encoding) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(encoding) -} - -func (encoding *Encoding) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, encoding) -} - -// SerializationMethod returns a serialization method of request body. -// When serialization method is not defined the method returns the default serialization method. -func (encoding *Encoding) SerializationMethod() *SerializationMethod { - sm := &SerializationMethod{Style: SerializationForm, Explode: true} - if encoding != nil { - if encoding.Style != "" { - sm.Style = encoding.Style - } - if encoding.Explode != nil { - sm.Explode = *encoding.Explode - } - } - return sm -} - -func (value *Encoding) Validate(ctx context.Context) error { - if value == nil { - return nil - } - for k, v := range value.Headers { - if err := ValidateIdentifier(k); err != nil { - return nil - } - if err := v.Validate(ctx); err != nil { - return nil - } - } - - // Validate a media types's serialization method. - sm := value.SerializationMethod() - switch { - case sm.Style == SerializationForm && sm.Explode, - sm.Style == SerializationForm && !sm.Explode, - sm.Style == SerializationSpaceDelimited && sm.Explode, - sm.Style == SerializationSpaceDelimited && !sm.Explode, - sm.Style == SerializationPipeDelimited && sm.Explode, - sm.Style == SerializationPipeDelimited && !sm.Explode, - sm.Style == SerializationDeepObject && sm.Explode: - // it is a valid - default: - return fmt.Errorf("serialization method with style=%q and explode=%v is not supported by media type", sm.Style, sm.Explode) - } - - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/errors.go b/vendor/github.com/getkin/kin-openapi/openapi3/errors.go deleted file mode 100644 index ce52cd48..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/errors.go +++ /dev/null @@ -1,43 +0,0 @@ -package openapi3 - -import ( - "bytes" - "errors" -) - -// MultiError is a collection of errors, intended for when -// multiple issues need to be reported upstream -type MultiError []error - -func (me MultiError) Error() string { - buff := &bytes.Buffer{} - for _, e := range me { - buff.WriteString(e.Error()) - buff.WriteString(" | ") - } - return buff.String() -} - -//Is allows you to determine if a generic error is in fact a MultiError using `errors.Is()` -//It will also return true if any of the contained errors match target -func (me MultiError) Is(target error) bool { - if _, ok := target.(MultiError); ok { - return true - } - for _, e := range me { - if errors.Is(e, target) { - return true - } - } - return false -} - -//As allows you to use `errors.As()` to set target to the first error within the multi error that matches the target type -func (me MultiError) As(target interface{}) bool { - for _, e := range me { - if errors.As(e, target) { - return true - } - } - return false -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/example.go b/vendor/github.com/getkin/kin-openapi/openapi3/example.go deleted file mode 100644 index 19cceb4d..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/example.go +++ /dev/null @@ -1,54 +0,0 @@ -package openapi3 - -import ( - "context" - "fmt" - - "github.com/getkin/kin-openapi/jsoninfo" - "github.com/go-openapi/jsonpointer" -) - -type Examples map[string]*ExampleRef - -var _ jsonpointer.JSONPointable = (*Examples)(nil) - -func (e Examples) JSONLookup(token string) (interface{}, error) { - ref, ok := e[token] - if ref == nil || !ok { - return nil, fmt.Errorf("object has no field %q", token) - } - - if ref.Ref != "" { - return &Ref{Ref: ref.Ref}, nil - } - return ref.Value, nil -} - -// Example is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#exampleObject -type Example struct { - ExtensionProps - - Summary string `json:"summary,omitempty" yaml:"summary,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Value interface{} `json:"value,omitempty" yaml:"value,omitempty"` - ExternalValue string `json:"externalValue,omitempty" yaml:"externalValue,omitempty"` -} - -func NewExample(value interface{}) *Example { - return &Example{ - Value: value, - } -} - -func (example *Example) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(example) -} - -func (example *Example) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, example) -} - -func (value *Example) Validate(ctx context.Context) error { - return nil // TODO -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/extension.go b/vendor/github.com/getkin/kin-openapi/openapi3/extension.go deleted file mode 100644 index f6b7ef9b..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/extension.go +++ /dev/null @@ -1,38 +0,0 @@ -package openapi3 - -import ( - "github.com/getkin/kin-openapi/jsoninfo" -) - -// ExtensionProps provides support for OpenAPI extensions. -// It reads/writes all properties that begin with "x-". -type ExtensionProps struct { - Extensions map[string]interface{} `json:"-" yaml:"-"` -} - -// Assert that the type implements the interface -var _ jsoninfo.StrictStruct = &ExtensionProps{} - -// EncodeWith will be invoked by package "jsoninfo" -func (props *ExtensionProps) EncodeWith(encoder *jsoninfo.ObjectEncoder, value interface{}) error { - for k, v := range props.Extensions { - if err := encoder.EncodeExtension(k, v); err != nil { - return err - } - } - return encoder.EncodeStructFieldsAndExtensions(value) -} - -// DecodeWith will be invoked by package "jsoninfo" -func (props *ExtensionProps) DecodeWith(decoder *jsoninfo.ObjectDecoder, value interface{}) error { - if err := decoder.DecodeStructFieldsAndExtensions(value); err != nil { - return err - } - source := decoder.DecodeExtensionMap() - result := make(map[string]interface{}, len(source)) - for k, v := range source { - result[k] = v - } - props.Extensions = result - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/external_docs.go b/vendor/github.com/getkin/kin-openapi/openapi3/external_docs.go deleted file mode 100644 index bb9dd5a8..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/external_docs.go +++ /dev/null @@ -1,37 +0,0 @@ -package openapi3 - -import ( - "context" - "errors" - "fmt" - "net/url" - - "github.com/getkin/kin-openapi/jsoninfo" -) - -// ExternalDocs is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#external-documentation-object -type ExternalDocs struct { - ExtensionProps - - Description string `json:"description,omitempty" yaml:"description,omitempty"` - URL string `json:"url,omitempty" yaml:"url,omitempty"` -} - -func (e *ExternalDocs) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(e) -} - -func (e *ExternalDocs) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, e) -} - -func (e *ExternalDocs) Validate(ctx context.Context) error { - if e.URL == "" { - return errors.New("url is required") - } - if _, err := url.Parse(e.URL); err != nil { - return fmt.Errorf("url is incorrect: %w", err) - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/header.go b/vendor/github.com/getkin/kin-openapi/openapi3/header.go deleted file mode 100644 index 9adb5ac3..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/header.go +++ /dev/null @@ -1,128 +0,0 @@ -package openapi3 - -import ( - "context" - "errors" - "fmt" - - "github.com/getkin/kin-openapi/jsoninfo" - "github.com/go-openapi/jsonpointer" -) - -type Headers map[string]*HeaderRef - -var _ jsonpointer.JSONPointable = (*Headers)(nil) - -func (h Headers) JSONLookup(token string) (interface{}, error) { - ref, ok := h[token] - if ref == nil || !ok { - return nil, fmt.Errorf("object has no field %q", token) - } - - if ref.Ref != "" { - return &Ref{Ref: ref.Ref}, nil - } - return ref.Value, nil -} - -// Header is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#headerObject -type Header struct { - Parameter -} - -var _ jsonpointer.JSONPointable = (*Header)(nil) - -func (value *Header) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, value) -} - -// SerializationMethod returns a header's serialization method. -func (value *Header) SerializationMethod() (*SerializationMethod, error) { - style := value.Style - if style == "" { - style = SerializationSimple - } - explode := false - if value.Explode != nil { - explode = *value.Explode - } - return &SerializationMethod{Style: style, Explode: explode}, nil -} - -func (value *Header) Validate(ctx context.Context) error { - if value.Name != "" { - return errors.New("header 'name' MUST NOT be specified, it is given in the corresponding headers map") - } - if value.In != "" { - return errors.New("header 'in' MUST NOT be specified, it is implicitly in header") - } - - // Validate a parameter's serialization method. - sm, err := value.SerializationMethod() - if err != nil { - return err - } - if smSupported := false || - sm.Style == SerializationSimple && !sm.Explode || - sm.Style == SerializationSimple && sm.Explode; !smSupported { - e := fmt.Errorf("serialization method with style=%q and explode=%v is not supported by a header parameter", sm.Style, sm.Explode) - return fmt.Errorf("header schema is invalid: %v", e) - } - - if (value.Schema == nil) == (value.Content == nil) { - e := fmt.Errorf("parameter must contain exactly one of content and schema: %v", value) - return fmt.Errorf("header schema is invalid: %v", e) - } - if schema := value.Schema; schema != nil { - if err := schema.Validate(ctx); err != nil { - return fmt.Errorf("header schema is invalid: %v", err) - } - } - - if content := value.Content; content != nil { - if err := content.Validate(ctx); err != nil { - return fmt.Errorf("header content is invalid: %v", err) - } - } - return nil -} - -func (value Header) JSONLookup(token string) (interface{}, error) { - switch token { - case "schema": - if value.Schema != nil { - if value.Schema.Ref != "" { - return &Ref{Ref: value.Schema.Ref}, nil - } - return value.Schema.Value, nil - } - case "name": - return value.Name, nil - case "in": - return value.In, nil - case "description": - return value.Description, nil - case "style": - return value.Style, nil - case "explode": - return value.Explode, nil - case "allowEmptyValue": - return value.AllowEmptyValue, nil - case "allowReserved": - return value.AllowReserved, nil - case "deprecated": - return value.Deprecated, nil - case "required": - return value.Required, nil - case "example": - return value.Example, nil - case "examples": - return value.Examples, nil - case "content": - return value.Content, nil - } - - v, _, err := jsonpointer.GetForToken(value.ExtensionProps, token) - return v, err -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/info.go b/vendor/github.com/getkin/kin-openapi/openapi3/info.go deleted file mode 100644 index 6b41589b..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/info.go +++ /dev/null @@ -1,99 +0,0 @@ -package openapi3 - -import ( - "context" - "errors" - - "github.com/getkin/kin-openapi/jsoninfo" -) - -// Info is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#infoObject -type Info struct { - ExtensionProps - - Title string `json:"title" yaml:"title"` // Required - Description string `json:"description,omitempty" yaml:"description,omitempty"` - TermsOfService string `json:"termsOfService,omitempty" yaml:"termsOfService,omitempty"` - Contact *Contact `json:"contact,omitempty" yaml:"contact,omitempty"` - License *License `json:"license,omitempty" yaml:"license,omitempty"` - Version string `json:"version" yaml:"version"` // Required -} - -func (value *Info) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(value) -} - -func (value *Info) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, value) -} - -func (value *Info) Validate(ctx context.Context) error { - if contact := value.Contact; contact != nil { - if err := contact.Validate(ctx); err != nil { - return err - } - } - - if license := value.License; license != nil { - if err := license.Validate(ctx); err != nil { - return err - } - } - - if value.Version == "" { - return errors.New("value of version must be a non-empty string") - } - - if value.Title == "" { - return errors.New("value of title must be a non-empty string") - } - - return nil -} - -// Contact is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#contactObject -type Contact struct { - ExtensionProps - - Name string `json:"name,omitempty" yaml:"name,omitempty"` - URL string `json:"url,omitempty" yaml:"url,omitempty"` - Email string `json:"email,omitempty" yaml:"email,omitempty"` -} - -func (value *Contact) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(value) -} - -func (value *Contact) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, value) -} - -func (value *Contact) Validate(ctx context.Context) error { - return nil -} - -// License is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#licenseObject -type License struct { - ExtensionProps - - Name string `json:"name" yaml:"name"` // Required - URL string `json:"url,omitempty" yaml:"url,omitempty"` -} - -func (value *License) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(value) -} - -func (value *License) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, value) -} - -func (value *License) Validate(ctx context.Context) error { - if value.Name == "" { - return errors.New("value of license name must be a non-empty string") - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/internalize_refs.go b/vendor/github.com/getkin/kin-openapi/openapi3/internalize_refs.go deleted file mode 100644 index 3a993bfb..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/internalize_refs.go +++ /dev/null @@ -1,369 +0,0 @@ -package openapi3 - -import ( - "context" - "path/filepath" - "strings" -) - -type RefNameResolver func(string) string - -// DefaultRefResolver is a default implementation of refNameResolver for the -// InternalizeRefs function. -// -// If a reference points to an element inside a document, it returns the last -// element in the reference using filepath.Base. Otherwise if the reference points -// to a file, it returns the file name trimmed of all extensions. -func DefaultRefNameResolver(ref string) string { - if ref == "" { - return "" - } - split := strings.SplitN(ref, "#", 2) - if len(split) == 2 { - return filepath.Base(split[1]) - } - ref = split[0] - for ext := filepath.Ext(ref); len(ext) > 0; ext = filepath.Ext(ref) { - ref = strings.TrimSuffix(ref, ext) - } - return filepath.Base(ref) -} - -func schemaNames(s Schemas) []string { - out := make([]string, 0, len(s)) - for i := range s { - out = append(out, i) - } - return out -} - -func parametersMapNames(s ParametersMap) []string { - out := make([]string, 0, len(s)) - for i := range s { - out = append(out, i) - } - return out -} - -func isExternalRef(ref string) bool { - return ref != "" && !strings.HasPrefix(ref, "#/components/") -} - -func (doc *T) addSchemaToSpec(s *SchemaRef, refNameResolver RefNameResolver) { - if s == nil || !isExternalRef(s.Ref) { - return - } - - name := refNameResolver(s.Ref) - if _, ok := doc.Components.Schemas[name]; ok { - s.Ref = "#/components/schemas/" + name - return - } - - if doc.Components.Schemas == nil { - doc.Components.Schemas = make(Schemas) - } - doc.Components.Schemas[name] = s.Value.NewRef() - s.Ref = "#/components/schemas/" + name -} - -func (doc *T) addParameterToSpec(p *ParameterRef, refNameResolver RefNameResolver) { - if p == nil || !isExternalRef(p.Ref) { - return - } - name := refNameResolver(p.Ref) - if _, ok := doc.Components.Parameters[name]; ok { - p.Ref = "#/components/parameters/" + name - return - } - - if doc.Components.Parameters == nil { - doc.Components.Parameters = make(ParametersMap) - } - doc.Components.Parameters[name] = &ParameterRef{Value: p.Value} - p.Ref = "#/components/parameters/" + name -} - -func (doc *T) addHeaderToSpec(h *HeaderRef, refNameResolver RefNameResolver) { - if h == nil || !isExternalRef(h.Ref) { - return - } - name := refNameResolver(h.Ref) - if _, ok := doc.Components.Headers[name]; ok { - h.Ref = "#/components/headers/" + name - return - } - if doc.Components.Headers == nil { - doc.Components.Headers = make(Headers) - } - doc.Components.Headers[name] = &HeaderRef{Value: h.Value} - h.Ref = "#/components/headers/" + name -} - -func (doc *T) addRequestBodyToSpec(r *RequestBodyRef, refNameResolver RefNameResolver) { - if r == nil || !isExternalRef(r.Ref) { - return - } - name := refNameResolver(r.Ref) - if _, ok := doc.Components.RequestBodies[name]; ok { - r.Ref = "#/components/requestBodies/" + name - return - } - if doc.Components.RequestBodies == nil { - doc.Components.RequestBodies = make(RequestBodies) - } - doc.Components.RequestBodies[name] = &RequestBodyRef{Value: r.Value} - r.Ref = "#/components/requestBodies/" + name -} - -func (doc *T) addResponseToSpec(r *ResponseRef, refNameResolver RefNameResolver) { - if r == nil || !isExternalRef(r.Ref) { - return - } - name := refNameResolver(r.Ref) - if _, ok := doc.Components.Responses[name]; ok { - r.Ref = "#/components/responses/" + name - return - } - if doc.Components.Responses == nil { - doc.Components.Responses = make(Responses) - } - doc.Components.Responses[name] = &ResponseRef{Value: r.Value} - r.Ref = "#/components/responses/" + name - -} - -func (doc *T) addSecuritySchemeToSpec(ss *SecuritySchemeRef, refNameResolver RefNameResolver) { - if ss == nil || !isExternalRef(ss.Ref) { - return - } - name := refNameResolver(ss.Ref) - if _, ok := doc.Components.SecuritySchemes[name]; ok { - ss.Ref = "#/components/securitySchemes/" + name - return - } - if doc.Components.SecuritySchemes == nil { - doc.Components.SecuritySchemes = make(SecuritySchemes) - } - doc.Components.SecuritySchemes[name] = &SecuritySchemeRef{Value: ss.Value} - ss.Ref = "#/components/securitySchemes/" + name - -} - -func (doc *T) addExampleToSpec(e *ExampleRef, refNameResolver RefNameResolver) { - if e == nil || !isExternalRef(e.Ref) { - return - } - name := refNameResolver(e.Ref) - if _, ok := doc.Components.Examples[name]; ok { - e.Ref = "#/components/examples/" + name - return - } - if doc.Components.Examples == nil { - doc.Components.Examples = make(Examples) - } - doc.Components.Examples[name] = &ExampleRef{Value: e.Value} - e.Ref = "#/components/examples/" + name - -} - -func (doc *T) addLinkToSpec(l *LinkRef, refNameResolver RefNameResolver) { - if l == nil || !isExternalRef(l.Ref) { - return - } - name := refNameResolver(l.Ref) - if _, ok := doc.Components.Links[name]; ok { - l.Ref = "#/components/links/" + name - return - } - if doc.Components.Links == nil { - doc.Components.Links = make(Links) - } - doc.Components.Links[name] = &LinkRef{Value: l.Value} - l.Ref = "#/components/links/" + name - -} - -func (doc *T) addCallbackToSpec(c *CallbackRef, refNameResolver RefNameResolver) { - if c == nil || !isExternalRef(c.Ref) { - return - } - name := refNameResolver(c.Ref) - if _, ok := doc.Components.Callbacks[name]; ok { - c.Ref = "#/components/callbacks/" + name - } - if doc.Components.Callbacks == nil { - doc.Components.Callbacks = make(Callbacks) - } - doc.Components.Callbacks[name] = &CallbackRef{Value: c.Value} - c.Ref = "#/components/callbacks/" + name -} - -func (doc *T) derefSchema(s *Schema, refNameResolver RefNameResolver) { - if s == nil { - return - } - - for _, list := range []SchemaRefs{s.AllOf, s.AnyOf, s.OneOf} { - for _, s2 := range list { - doc.addSchemaToSpec(s2, refNameResolver) - if s2 != nil { - doc.derefSchema(s2.Value, refNameResolver) - } - } - } - for _, s2 := range s.Properties { - doc.addSchemaToSpec(s2, refNameResolver) - if s2 != nil { - doc.derefSchema(s2.Value, refNameResolver) - } - } - for _, ref := range []*SchemaRef{s.Not, s.AdditionalProperties, s.Items} { - doc.addSchemaToSpec(ref, refNameResolver) - if ref != nil { - doc.derefSchema(ref.Value, refNameResolver) - } - } -} - -func (doc *T) derefHeaders(hs Headers, refNameResolver RefNameResolver) { - for _, h := range hs { - doc.addHeaderToSpec(h, refNameResolver) - doc.derefParameter(h.Value.Parameter, refNameResolver) - } -} - -func (doc *T) derefExamples(es Examples, refNameResolver RefNameResolver) { - for _, e := range es { - doc.addExampleToSpec(e, refNameResolver) - } -} - -func (doc *T) derefContent(c Content, refNameResolver RefNameResolver) { - for _, mediatype := range c { - doc.addSchemaToSpec(mediatype.Schema, refNameResolver) - if mediatype.Schema != nil { - doc.derefSchema(mediatype.Schema.Value, refNameResolver) - } - doc.derefExamples(mediatype.Examples, refNameResolver) - for _, e := range mediatype.Encoding { - doc.derefHeaders(e.Headers, refNameResolver) - } - } -} - -func (doc *T) derefLinks(ls Links, refNameResolver RefNameResolver) { - for _, l := range ls { - doc.addLinkToSpec(l, refNameResolver) - } -} - -func (doc *T) derefResponses(es Responses, refNameResolver RefNameResolver) { - for _, e := range es { - doc.addResponseToSpec(e, refNameResolver) - if e.Value != nil { - doc.derefHeaders(e.Value.Headers, refNameResolver) - doc.derefContent(e.Value.Content, refNameResolver) - doc.derefLinks(e.Value.Links, refNameResolver) - } - } -} - -func (doc *T) derefParameter(p Parameter, refNameResolver RefNameResolver) { - doc.addSchemaToSpec(p.Schema, refNameResolver) - doc.derefContent(p.Content, refNameResolver) - if p.Schema != nil { - doc.derefSchema(p.Schema.Value, refNameResolver) - } -} - -func (doc *T) derefRequestBody(r RequestBody, refNameResolver RefNameResolver) { - doc.derefContent(r.Content, refNameResolver) -} - -func (doc *T) derefPaths(paths map[string]*PathItem, refNameResolver RefNameResolver) { - for _, ops := range paths { - // inline full operations - ops.Ref = "" - - for _, op := range ops.Operations() { - doc.addRequestBodyToSpec(op.RequestBody, refNameResolver) - if op.RequestBody != nil && op.RequestBody.Value != nil { - doc.derefRequestBody(*op.RequestBody.Value, refNameResolver) - } - for _, cb := range op.Callbacks { - doc.addCallbackToSpec(cb, refNameResolver) - if cb.Value != nil { - doc.derefPaths(*cb.Value, refNameResolver) - } - } - doc.derefResponses(op.Responses, refNameResolver) - for _, param := range op.Parameters { - doc.addParameterToSpec(param, refNameResolver) - if param.Value != nil { - doc.derefParameter(*param.Value, refNameResolver) - } - } - } - } -} - -// InternalizeRefs removes all references to external files from the spec and moves them -// to the components section. -// -// refNameResolver takes in references to returns a name to store the reference under locally. -// It MUST return a unique name for each reference type. -// A default implementation is provided that will suffice for most use cases. See the function -// documention for more details. -// -// Example: -// -// doc.InternalizeRefs(context.Background(), nil) -func (doc *T) InternalizeRefs(ctx context.Context, refNameResolver func(ref string) string) { - if refNameResolver == nil { - refNameResolver = DefaultRefNameResolver - } - - // Handle components section - names := schemaNames(doc.Components.Schemas) - for _, name := range names { - schema := doc.Components.Schemas[name] - doc.addSchemaToSpec(schema, refNameResolver) - if schema != nil { - schema.Ref = "" // always dereference the top level - doc.derefSchema(schema.Value, refNameResolver) - } - } - names = parametersMapNames(doc.Components.Parameters) - for _, name := range names { - p := doc.Components.Parameters[name] - doc.addParameterToSpec(p, refNameResolver) - if p != nil && p.Value != nil { - p.Ref = "" // always dereference the top level - doc.derefParameter(*p.Value, refNameResolver) - } - } - doc.derefHeaders(doc.Components.Headers, refNameResolver) - for _, req := range doc.Components.RequestBodies { - doc.addRequestBodyToSpec(req, refNameResolver) - if req != nil && req.Value != nil { - req.Ref = "" // always dereference the top level - doc.derefRequestBody(*req.Value, refNameResolver) - } - } - doc.derefResponses(doc.Components.Responses, refNameResolver) - for _, ss := range doc.Components.SecuritySchemes { - doc.addSecuritySchemeToSpec(ss, refNameResolver) - } - doc.derefExamples(doc.Components.Examples, refNameResolver) - doc.derefLinks(doc.Components.Links, refNameResolver) - for _, cb := range doc.Components.Callbacks { - doc.addCallbackToSpec(cb, refNameResolver) - if cb != nil && cb.Value != nil { - cb.Ref = "" // always dereference the top level - doc.derefPaths(*cb.Value, refNameResolver) - } - } - - doc.derefPaths(doc.Paths, refNameResolver) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/link.go b/vendor/github.com/getkin/kin-openapi/openapi3/link.go deleted file mode 100644 index 19a725a8..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/link.go +++ /dev/null @@ -1,57 +0,0 @@ -package openapi3 - -import ( - "context" - "errors" - "fmt" - - "github.com/getkin/kin-openapi/jsoninfo" - "github.com/go-openapi/jsonpointer" -) - -type Links map[string]*LinkRef - -func (l Links) JSONLookup(token string) (interface{}, error) { - ref, ok := l[token] - if ok == false { - return nil, fmt.Errorf("object has no field %q", token) - } - - if ref != nil && ref.Ref != "" { - return &Ref{Ref: ref.Ref}, nil - } - return ref.Value, nil -} - -var _ jsonpointer.JSONPointable = (*Links)(nil) - -// Link is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#linkObject -type Link struct { - ExtensionProps - - OperationRef string `json:"operationRef,omitempty" yaml:"operationRef,omitempty"` - OperationID string `json:"operationId,omitempty" yaml:"operationId,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Parameters map[string]interface{} `json:"parameters,omitempty" yaml:"parameters,omitempty"` - Server *Server `json:"server,omitempty" yaml:"server,omitempty"` - RequestBody interface{} `json:"requestBody,omitempty" yaml:"requestBody,omitempty"` -} - -func (value *Link) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(value) -} - -func (value *Link) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, value) -} - -func (value *Link) Validate(ctx context.Context) error { - if value.OperationID == "" && value.OperationRef == "" { - return errors.New("missing operationId or operationRef on link") - } - if value.OperationID != "" && value.OperationRef != "" { - return fmt.Errorf("operationId %q and operationRef %q are mutually exclusive", value.OperationID, value.OperationRef) - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/loader.go b/vendor/github.com/getkin/kin-openapi/openapi3/loader.go deleted file mode 100644 index 8af733c3..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/loader.go +++ /dev/null @@ -1,1030 +0,0 @@ -package openapi3 - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/url" - "path" - "path/filepath" - "reflect" - "strconv" - "strings" - - "github.com/ghodss/yaml" -) - -func foundUnresolvedRef(ref string) error { - return fmt.Errorf("found unresolved ref: %q", ref) -} - -func failedToResolveRefFragmentPart(value, what string) error { - return fmt.Errorf("failed to resolve %q in fragment in URI: %q", what, value) -} - -// Loader helps deserialize an OpenAPIv3 document -type Loader struct { - // IsExternalRefsAllowed enables visiting other files - IsExternalRefsAllowed bool - - // ReadFromURIFunc allows overriding the any file/URL reading func - ReadFromURIFunc ReadFromURIFunc - - Context context.Context - - rootDir string - - visitedPathItemRefs map[string]struct{} - - visitedDocuments map[string]*T - - visitedExample map[*Example]struct{} - visitedHeader map[*Header]struct{} - visitedLink map[*Link]struct{} - visitedParameter map[*Parameter]struct{} - visitedRequestBody map[*RequestBody]struct{} - visitedResponse map[*Response]struct{} - visitedSchema map[*Schema]struct{} - visitedSecurityScheme map[*SecurityScheme]struct{} -} - -// NewLoader returns an empty Loader -func NewLoader() *Loader { - return &Loader{} -} - -func (loader *Loader) resetVisitedPathItemRefs() { - loader.visitedPathItemRefs = make(map[string]struct{}) -} - -// LoadFromURI loads a spec from a remote URL -func (loader *Loader) LoadFromURI(location *url.URL) (*T, error) { - loader.resetVisitedPathItemRefs() - return loader.loadFromURIInternal(location) -} - -// LoadFromFile loads a spec from a local file path -func (loader *Loader) LoadFromFile(location string) (*T, error) { - loader.rootDir = path.Dir(location) - return loader.LoadFromURI(&url.URL{Path: filepath.ToSlash(location)}) -} - -func (loader *Loader) loadFromURIInternal(location *url.URL) (*T, error) { - data, err := loader.readURL(location) - if err != nil { - return nil, err - } - return loader.loadFromDataWithPathInternal(data, location) -} - -func (loader *Loader) allowsExternalRefs(ref string) (err error) { - if !loader.IsExternalRefsAllowed { - err = fmt.Errorf("encountered disallowed external reference: %q", ref) - } - return -} - -// loadSingleElementFromURI reads the data from ref and unmarshals to the passed element. -func (loader *Loader) loadSingleElementFromURI(ref string, rootPath *url.URL, element interface{}) (*url.URL, error) { - if err := loader.allowsExternalRefs(ref); err != nil { - return nil, err - } - - parsedURL, err := url.Parse(ref) - if err != nil { - return nil, err - } - if fragment := parsedURL.Fragment; fragment != "" { - return nil, fmt.Errorf("unexpected ref fragment %q", fragment) - } - - resolvedPath, err := resolvePath(rootPath, parsedURL) - if err != nil { - return nil, fmt.Errorf("could not resolve path: %v", err) - } - - data, err := loader.readURL(resolvedPath) - if err != nil { - return nil, err - } - if err := yaml.Unmarshal(data, element); err != nil { - return nil, err - } - - return resolvedPath, nil -} - -func (loader *Loader) readURL(location *url.URL) ([]byte, error) { - if f := loader.ReadFromURIFunc; f != nil { - return f(loader, location) - } - return DefaultReadFromURI(loader, location) -} - -// LoadFromData loads a spec from a byte array -func (loader *Loader) LoadFromData(data []byte) (*T, error) { - loader.resetVisitedPathItemRefs() - doc := &T{} - if err := yaml.Unmarshal(data, doc); err != nil { - return nil, err - } - if err := loader.ResolveRefsIn(doc, nil); err != nil { - return nil, err - } - return doc, nil -} - -// LoadFromDataWithPath takes the OpenAPI document data in bytes and a path where the resolver can find referred -// elements and returns a *T with all resolved data or an error if unable to load data or resolve refs. -func (loader *Loader) LoadFromDataWithPath(data []byte, location *url.URL) (*T, error) { - loader.resetVisitedPathItemRefs() - return loader.loadFromDataWithPathInternal(data, location) -} - -func (loader *Loader) loadFromDataWithPathInternal(data []byte, location *url.URL) (*T, error) { - if loader.visitedDocuments == nil { - loader.visitedDocuments = make(map[string]*T) - } - uri := location.String() - if doc, ok := loader.visitedDocuments[uri]; ok { - return doc, nil - } - - doc := &T{} - loader.visitedDocuments[uri] = doc - - if err := yaml.Unmarshal(data, doc); err != nil { - return nil, err - } - if err := loader.ResolveRefsIn(doc, location); err != nil { - return nil, err - } - - return doc, nil -} - -// ResolveRefsIn expands references if for instance spec was just unmarshalled -func (loader *Loader) ResolveRefsIn(doc *T, location *url.URL) (err error) { - if loader.visitedPathItemRefs == nil { - loader.resetVisitedPathItemRefs() - } - - // Visit all components - components := doc.Components - for _, component := range components.Headers { - if err = loader.resolveHeaderRef(doc, component, location); err != nil { - return - } - } - for _, component := range components.Parameters { - if err = loader.resolveParameterRef(doc, component, location); err != nil { - return - } - } - for _, component := range components.RequestBodies { - if err = loader.resolveRequestBodyRef(doc, component, location); err != nil { - return - } - } - for _, component := range components.Responses { - if err = loader.resolveResponseRef(doc, component, location); err != nil { - return - } - } - for _, component := range components.Schemas { - if err = loader.resolveSchemaRef(doc, component, location); err != nil { - return - } - } - for _, component := range components.SecuritySchemes { - if err = loader.resolveSecuritySchemeRef(doc, component, location); err != nil { - return - } - } - for _, component := range components.Examples { - if err = loader.resolveExampleRef(doc, component, location); err != nil { - return - } - } - for _, component := range components.Callbacks { - if err = loader.resolveCallbackRef(doc, component, location); err != nil { - return - } - } - - // Visit all operations - for entrypoint, pathItem := range doc.Paths { - if pathItem == nil { - continue - } - if err = loader.resolvePathItemRef(doc, entrypoint, pathItem, location); err != nil { - return - } - } - - return -} - -func join(basePath *url.URL, relativePath *url.URL) (*url.URL, error) { - if basePath == nil { - return relativePath, nil - } - newPath, err := url.Parse(basePath.String()) - if err != nil { - return nil, fmt.Errorf("cannot copy path: %q", basePath.String()) - } - newPath.Path = path.Join(path.Dir(newPath.Path), relativePath.Path) - return newPath, nil -} - -func resolvePath(basePath *url.URL, componentPath *url.URL) (*url.URL, error) { - if componentPath.Scheme == "" && componentPath.Host == "" { - // support absolute paths - if componentPath.Path[0] == '/' { - return componentPath, nil - } - return join(basePath, componentPath) - } - return componentPath, nil -} - -func isSingleRefElement(ref string) bool { - return !strings.Contains(ref, "#") -} - -func (loader *Loader) resolveComponent( - doc *T, - ref string, - path *url.URL, - resolved interface{}, -) ( - componentPath *url.URL, - err error, -) { - if doc, ref, componentPath, err = loader.resolveRef(doc, ref, path); err != nil { - return nil, err - } - - parsedURL, err := url.Parse(ref) - if err != nil { - return nil, fmt.Errorf("cannot parse reference: %q: %v", ref, parsedURL) - } - fragment := parsedURL.Fragment - if !strings.HasPrefix(fragment, "/") { - return nil, fmt.Errorf("expected fragment prefix '#/' in URI %q", ref) - } - - drill := func(cursor interface{}) (interface{}, error) { - for _, pathPart := range strings.Split(fragment[1:], "/") { - pathPart = unescapeRefString(pathPart) - - if cursor, err = drillIntoField(cursor, pathPart); err != nil { - e := failedToResolveRefFragmentPart(ref, pathPart) - return nil, fmt.Errorf("%s: %s", e.Error(), err.Error()) - } - if cursor == nil { - return nil, failedToResolveRefFragmentPart(ref, pathPart) - } - } - return cursor, nil - } - var cursor interface{} - if cursor, err = drill(doc); err != nil { - if path == nil { - return nil, err - } - var err2 error - data, err2 := loader.readURL(path) - if err2 != nil { - return nil, err - } - if err2 = yaml.Unmarshal(data, &cursor); err2 != nil { - return nil, err - } - if cursor, err2 = drill(cursor); err2 != nil || cursor == nil { - return nil, err - } - err = nil - } - - switch { - case reflect.TypeOf(cursor) == reflect.TypeOf(resolved): - reflect.ValueOf(resolved).Elem().Set(reflect.ValueOf(cursor).Elem()) - return componentPath, nil - - case reflect.TypeOf(cursor) == reflect.TypeOf(map[string]interface{}{}): - codec := func(got, expect interface{}) error { - enc, err := json.Marshal(got) - if err != nil { - return err - } - if err = json.Unmarshal(enc, expect); err != nil { - return err - } - return nil - } - if err := codec(cursor, resolved); err != nil { - return nil, fmt.Errorf("bad data in %q", ref) - } - return componentPath, nil - - default: - return nil, fmt.Errorf("bad data in %q", ref) - } -} - -func drillIntoField(cursor interface{}, fieldName string) (interface{}, error) { - // Special case due to multijson - if s, ok := cursor.(*SchemaRef); ok && fieldName == "additionalProperties" { - if ap := s.Value.AdditionalPropertiesAllowed; ap != nil { - return *ap, nil - } - return s.Value.AdditionalProperties, nil - } - - switch val := reflect.Indirect(reflect.ValueOf(cursor)); val.Kind() { - case reflect.Map: - elementValue := val.MapIndex(reflect.ValueOf(fieldName)) - if !elementValue.IsValid() { - return nil, fmt.Errorf("map key %q not found", fieldName) - } - return elementValue.Interface(), nil - - case reflect.Slice: - i, err := strconv.ParseUint(fieldName, 10, 32) - if err != nil { - return nil, err - } - index := int(i) - if 0 > index || index >= val.Len() { - return nil, errors.New("slice index out of bounds") - } - return val.Index(index).Interface(), nil - - case reflect.Struct: - hasFields := false - for i := 0; i < val.NumField(); i++ { - hasFields = true - field := val.Type().Field(i) - tagValue := field.Tag.Get("yaml") - yamlKey := strings.Split(tagValue, ",")[0] - if yamlKey == "-" { - tagValue := field.Tag.Get("multijson") - yamlKey = strings.Split(tagValue, ",")[0] - } - if yamlKey == fieldName { - return val.Field(i).Interface(), nil - } - } - // if cursor is a "ref wrapper" struct (e.g. RequestBodyRef), - if _, ok := val.Type().FieldByName("Value"); ok { - // try digging into its Value field - return drillIntoField(val.FieldByName("Value").Interface(), fieldName) - } - if hasFields { - if ff := val.Type().Field(0); ff.PkgPath == "" && ff.Name == "ExtensionProps" { - extensions := val.Field(0).Interface().(ExtensionProps).Extensions - if enc, ok := extensions[fieldName]; ok { - var dec interface{} - if err := json.Unmarshal(enc.(json.RawMessage), &dec); err != nil { - return nil, err - } - return dec, nil - } - } - } - return nil, fmt.Errorf("struct field %q not found", fieldName) - - default: - return nil, errors.New("not a map, slice nor struct") - } -} - -func (loader *Loader) documentPathForRecursiveRef(current *url.URL, resolvedRef string) *url.URL { - if loader.rootDir == "" { - return current - } - return &url.URL{Path: path.Join(loader.rootDir, resolvedRef)} - -} - -func (loader *Loader) resolveRef(doc *T, ref string, path *url.URL) (*T, string, *url.URL, error) { - if ref != "" && ref[0] == '#' { - return doc, ref, path, nil - } - - if err := loader.allowsExternalRefs(ref); err != nil { - return nil, "", nil, err - } - - parsedURL, err := url.Parse(ref) - if err != nil { - return nil, "", nil, fmt.Errorf("cannot parse reference: %q: %v", ref, parsedURL) - } - fragment := parsedURL.Fragment - parsedURL.Fragment = "" - - var resolvedPath *url.URL - if resolvedPath, err = resolvePath(path, parsedURL); err != nil { - return nil, "", nil, fmt.Errorf("error resolving path: %v", err) - } - - if doc, err = loader.loadFromURIInternal(resolvedPath); err != nil { - return nil, "", nil, fmt.Errorf("error resolving reference %q: %v", ref, err) - } - - return doc, "#" + fragment, resolvedPath, nil -} - -func (loader *Loader) resolveHeaderRef(doc *T, component *HeaderRef, documentPath *url.URL) (err error) { - if component != nil && component.Value != nil { - if loader.visitedHeader == nil { - loader.visitedHeader = make(map[*Header]struct{}) - } - if _, ok := loader.visitedHeader[component.Value]; ok { - return nil - } - loader.visitedHeader[component.Value] = struct{}{} - } - - if component == nil { - return errors.New("invalid header: value MUST be an object") - } - if ref := component.Ref; ref != "" { - if isSingleRefElement(ref) { - var header Header - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &header); err != nil { - return err - } - component.Value = &header - } else { - var resolved HeaderRef - componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveHeaderRef(doc, &resolved, componentPath); err != nil { - return err - } - component.Value = resolved.Value - documentPath = loader.documentPathForRecursiveRef(documentPath, resolved.Ref) - } - } - value := component.Value - if value == nil { - return nil - } - - if schema := value.Schema; schema != nil { - if err := loader.resolveSchemaRef(doc, schema, documentPath); err != nil { - return err - } - } - return nil -} - -func (loader *Loader) resolveParameterRef(doc *T, component *ParameterRef, documentPath *url.URL) (err error) { - if component != nil && component.Value != nil { - if loader.visitedParameter == nil { - loader.visitedParameter = make(map[*Parameter]struct{}) - } - if _, ok := loader.visitedParameter[component.Value]; ok { - return nil - } - loader.visitedParameter[component.Value] = struct{}{} - } - - if component == nil { - return errors.New("invalid parameter: value MUST be an object") - } - ref := component.Ref - if ref != "" { - if isSingleRefElement(ref) { - var param Parameter - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, ¶m); err != nil { - return err - } - component.Value = ¶m - } else { - var resolved ParameterRef - componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveParameterRef(doc, &resolved, componentPath); err != nil { - return err - } - component.Value = resolved.Value - documentPath = loader.documentPathForRecursiveRef(documentPath, resolved.Ref) - } - } - value := component.Value - if value == nil { - return nil - } - - if value.Content != nil && value.Schema != nil { - return errors.New("cannot contain both schema and content in a parameter") - } - for _, contentType := range value.Content { - if schema := contentType.Schema; schema != nil { - if err := loader.resolveSchemaRef(doc, schema, documentPath); err != nil { - return err - } - } - } - if schema := value.Schema; schema != nil { - if err := loader.resolveSchemaRef(doc, schema, documentPath); err != nil { - return err - } - } - return nil -} - -func (loader *Loader) resolveRequestBodyRef(doc *T, component *RequestBodyRef, documentPath *url.URL) (err error) { - if component != nil && component.Value != nil { - if loader.visitedRequestBody == nil { - loader.visitedRequestBody = make(map[*RequestBody]struct{}) - } - if _, ok := loader.visitedRequestBody[component.Value]; ok { - return nil - } - loader.visitedRequestBody[component.Value] = struct{}{} - } - - if component == nil { - return errors.New("invalid requestBody: value MUST be an object") - } - if ref := component.Ref; ref != "" { - if isSingleRefElement(ref) { - var requestBody RequestBody - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &requestBody); err != nil { - return err - } - component.Value = &requestBody - } else { - var resolved RequestBodyRef - componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err = loader.resolveRequestBodyRef(doc, &resolved, componentPath); err != nil { - return err - } - component.Value = resolved.Value - documentPath = loader.documentPathForRecursiveRef(documentPath, resolved.Ref) - } - } - value := component.Value - if value == nil { - return nil - } - - for _, contentType := range value.Content { - for name, example := range contentType.Examples { - if err := loader.resolveExampleRef(doc, example, documentPath); err != nil { - return err - } - contentType.Examples[name] = example - } - if schema := contentType.Schema; schema != nil { - if err := loader.resolveSchemaRef(doc, schema, documentPath); err != nil { - return err - } - } - } - return nil -} - -func (loader *Loader) resolveResponseRef(doc *T, component *ResponseRef, documentPath *url.URL) (err error) { - if component != nil && component.Value != nil { - if loader.visitedResponse == nil { - loader.visitedResponse = make(map[*Response]struct{}) - } - if _, ok := loader.visitedResponse[component.Value]; ok { - return nil - } - loader.visitedResponse[component.Value] = struct{}{} - } - - if component == nil { - return errors.New("invalid response: value MUST be an object") - } - ref := component.Ref - if ref != "" { - if isSingleRefElement(ref) { - var resp Response - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &resp); err != nil { - return err - } - component.Value = &resp - } else { - var resolved ResponseRef - componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveResponseRef(doc, &resolved, componentPath); err != nil { - return err - } - component.Value = resolved.Value - documentPath = loader.documentPathForRecursiveRef(documentPath, resolved.Ref) - } - } - value := component.Value - if value == nil { - return nil - } - - for _, header := range value.Headers { - if err := loader.resolveHeaderRef(doc, header, documentPath); err != nil { - return err - } - } - for _, contentType := range value.Content { - if contentType == nil { - continue - } - for name, example := range contentType.Examples { - if err := loader.resolveExampleRef(doc, example, documentPath); err != nil { - return err - } - contentType.Examples[name] = example - } - if schema := contentType.Schema; schema != nil { - if err := loader.resolveSchemaRef(doc, schema, documentPath); err != nil { - return err - } - contentType.Schema = schema - } - } - for _, link := range value.Links { - if err := loader.resolveLinkRef(doc, link, documentPath); err != nil { - return err - } - } - return nil -} - -func (loader *Loader) resolveSchemaRef(doc *T, component *SchemaRef, documentPath *url.URL) (err error) { - if component != nil && component.Value != nil { - if loader.visitedSchema == nil { - loader.visitedSchema = make(map[*Schema]struct{}) - } - if _, ok := loader.visitedSchema[component.Value]; ok { - return nil - } - loader.visitedSchema[component.Value] = struct{}{} - } - - if component == nil { - return errors.New("invalid schema: value MUST be an object") - } - ref := component.Ref - if ref != "" { - if isSingleRefElement(ref) { - var schema Schema - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &schema); err != nil { - return err - } - component.Value = &schema - } else { - var resolved SchemaRef - componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveSchemaRef(doc, &resolved, componentPath); err != nil { - return err - } - component.Value = resolved.Value - documentPath = loader.documentPathForRecursiveRef(documentPath, resolved.Ref) - } - } - value := component.Value - if value == nil { - return nil - } - - // ResolveRefs referred schemas - if v := value.Items; v != nil { - if err := loader.resolveSchemaRef(doc, v, documentPath); err != nil { - return err - } - } - for _, v := range value.Properties { - if err := loader.resolveSchemaRef(doc, v, documentPath); err != nil { - return err - } - } - if v := value.AdditionalProperties; v != nil { - if err := loader.resolveSchemaRef(doc, v, documentPath); err != nil { - return err - } - } - if v := value.Not; v != nil { - if err := loader.resolveSchemaRef(doc, v, documentPath); err != nil { - return err - } - } - for _, v := range value.AllOf { - if err := loader.resolveSchemaRef(doc, v, documentPath); err != nil { - return err - } - } - for _, v := range value.AnyOf { - if err := loader.resolveSchemaRef(doc, v, documentPath); err != nil { - return err - } - } - for _, v := range value.OneOf { - if err := loader.resolveSchemaRef(doc, v, documentPath); err != nil { - return err - } - } - return nil -} - -func (loader *Loader) resolveSecuritySchemeRef(doc *T, component *SecuritySchemeRef, documentPath *url.URL) (err error) { - if component != nil && component.Value != nil { - if loader.visitedSecurityScheme == nil { - loader.visitedSecurityScheme = make(map[*SecurityScheme]struct{}) - } - if _, ok := loader.visitedSecurityScheme[component.Value]; ok { - return nil - } - loader.visitedSecurityScheme[component.Value] = struct{}{} - } - - if component == nil { - return errors.New("invalid securityScheme: value MUST be an object") - } - if ref := component.Ref; ref != "" { - if isSingleRefElement(ref) { - var scheme SecurityScheme - if _, err = loader.loadSingleElementFromURI(ref, documentPath, &scheme); err != nil { - return err - } - component.Value = &scheme - } else { - var resolved SecuritySchemeRef - componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveSecuritySchemeRef(doc, &resolved, componentPath); err != nil { - return err - } - component.Value = resolved.Value - _ = loader.documentPathForRecursiveRef(documentPath, resolved.Ref) - } - } - return nil -} - -func (loader *Loader) resolveExampleRef(doc *T, component *ExampleRef, documentPath *url.URL) (err error) { - if component != nil && component.Value != nil { - if loader.visitedExample == nil { - loader.visitedExample = make(map[*Example]struct{}) - } - if _, ok := loader.visitedExample[component.Value]; ok { - return nil - } - loader.visitedExample[component.Value] = struct{}{} - } - - if component == nil { - return errors.New("invalid example: value MUST be an object") - } - if ref := component.Ref; ref != "" { - if isSingleRefElement(ref) { - var example Example - if _, err = loader.loadSingleElementFromURI(ref, documentPath, &example); err != nil { - return err - } - component.Value = &example - } else { - var resolved ExampleRef - componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveExampleRef(doc, &resolved, componentPath); err != nil { - return err - } - component.Value = resolved.Value - _ = loader.documentPathForRecursiveRef(documentPath, resolved.Ref) - } - } - return nil -} - -func (loader *Loader) resolveCallbackRef(doc *T, component *CallbackRef, documentPath *url.URL) (err error) { - - if component == nil { - return errors.New("invalid callback: value MUST be an object") - } - if ref := component.Ref; ref != "" { - if isSingleRefElement(ref) { - var resolved Callback - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &resolved); err != nil { - return err - } - component.Value = &resolved - } else { - var resolved CallbackRef - componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveCallbackRef(doc, &resolved, componentPath); err != nil { - return err - } - component.Value = resolved.Value - documentPath = loader.documentPathForRecursiveRef(documentPath, resolved.Ref) - } - } - value := component.Value - if value == nil { - return nil - } - - for entrypoint, pathItem := range *value { - entrypoint, pathItem := entrypoint, pathItem - err = func() (err error) { - key := "-" - if documentPath != nil { - key = documentPath.EscapedPath() - } - key += entrypoint - if _, ok := loader.visitedPathItemRefs[key]; ok { - return nil - } - loader.visitedPathItemRefs[key] = struct{}{} - - if pathItem == nil { - return errors.New("invalid path item: value MUST be an object") - } - ref := pathItem.Ref - if ref != "" { - if isSingleRefElement(ref) { - var p PathItem - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &p); err != nil { - return err - } - *pathItem = p - } else { - if doc, ref, documentPath, err = loader.resolveRef(doc, ref, documentPath); err != nil { - return - } - - rest := strings.TrimPrefix(ref, "#/components/callbacks/") - if rest == ref { - return fmt.Errorf(`expected prefix "#/components/callbacks/" in URI %q`, ref) - } - id := unescapeRefString(rest) - - definitions := doc.Components.Callbacks - if definitions == nil { - return failedToResolveRefFragmentPart(ref, "callbacks") - } - resolved := definitions[id] - if resolved == nil { - return failedToResolveRefFragmentPart(ref, id) - } - - for _, p := range *resolved.Value { - *pathItem = *p - break - } - } - } - return loader.resolvePathItemRefContinued(doc, pathItem, documentPath) - }() - if err != nil { - return err - } - } - return nil -} - -func (loader *Loader) resolveLinkRef(doc *T, component *LinkRef, documentPath *url.URL) (err error) { - if component != nil && component.Value != nil { - if loader.visitedLink == nil { - loader.visitedLink = make(map[*Link]struct{}) - } - if _, ok := loader.visitedLink[component.Value]; ok { - return nil - } - loader.visitedLink[component.Value] = struct{}{} - } - - if component == nil { - return errors.New("invalid link: value MUST be an object") - } - if ref := component.Ref; ref != "" { - if isSingleRefElement(ref) { - var link Link - if _, err = loader.loadSingleElementFromURI(ref, documentPath, &link); err != nil { - return err - } - component.Value = &link - } else { - var resolved LinkRef - componentPath, err := loader.resolveComponent(doc, ref, documentPath, &resolved) - if err != nil { - return err - } - if err := loader.resolveLinkRef(doc, &resolved, componentPath); err != nil { - return err - } - component.Value = resolved.Value - _ = loader.documentPathForRecursiveRef(documentPath, resolved.Ref) - } - } - return nil -} - -func (loader *Loader) resolvePathItemRef(doc *T, entrypoint string, pathItem *PathItem, documentPath *url.URL) (err error) { - key := "_" - if documentPath != nil { - key = documentPath.EscapedPath() - } - key += entrypoint - if _, ok := loader.visitedPathItemRefs[key]; ok { - return nil - } - loader.visitedPathItemRefs[key] = struct{}{} - - if pathItem == nil { - return errors.New("invalid path item: value MUST be an object") - } - ref := pathItem.Ref - if ref != "" { - if isSingleRefElement(ref) { - var p PathItem - if documentPath, err = loader.loadSingleElementFromURI(ref, documentPath, &p); err != nil { - return err - } - *pathItem = p - } else { - if doc, ref, documentPath, err = loader.resolveRef(doc, ref, documentPath); err != nil { - return - } - - rest := strings.TrimPrefix(ref, "#/paths/") - if rest == ref { - return fmt.Errorf(`expected prefix "#/paths/" in URI %q`, ref) - } - id := unescapeRefString(rest) - - definitions := doc.Paths - if definitions == nil { - return failedToResolveRefFragmentPart(ref, "paths") - } - resolved := definitions[id] - if resolved == nil { - return failedToResolveRefFragmentPart(ref, id) - } - - *pathItem = *resolved - } - } - return loader.resolvePathItemRefContinued(doc, pathItem, documentPath) -} - -func (loader *Loader) resolvePathItemRefContinued(doc *T, pathItem *PathItem, documentPath *url.URL) (err error) { - for _, parameter := range pathItem.Parameters { - if err = loader.resolveParameterRef(doc, parameter, documentPath); err != nil { - return - } - } - for _, operation := range pathItem.Operations() { - for _, parameter := range operation.Parameters { - if err = loader.resolveParameterRef(doc, parameter, documentPath); err != nil { - return - } - } - if requestBody := operation.RequestBody; requestBody != nil { - if err = loader.resolveRequestBodyRef(doc, requestBody, documentPath); err != nil { - return - } - } - for _, response := range operation.Responses { - if err = loader.resolveResponseRef(doc, response, documentPath); err != nil { - return - } - } - for _, callback := range operation.Callbacks { - if err = loader.resolveCallbackRef(doc, callback, documentPath); err != nil { - return - } - } - } - return -} - -func unescapeRefString(ref string) string { - return strings.Replace(strings.Replace(ref, "~1", "/", -1), "~0", "~", -1) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/loader_uri_reader.go b/vendor/github.com/getkin/kin-openapi/openapi3/loader_uri_reader.go deleted file mode 100644 index 8357a980..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/loader_uri_reader.go +++ /dev/null @@ -1,104 +0,0 @@ -package openapi3 - -import ( - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "path/filepath" -) - -// ReadFromURIFunc defines a function which reads the contents of a resource -// located at a URI. -type ReadFromURIFunc func(loader *Loader, url *url.URL) ([]byte, error) - -// ErrURINotSupported indicates the ReadFromURIFunc does not know how to handle a -// given URI. -var ErrURINotSupported = errors.New("unsupported URI") - -// ReadFromURIs returns a ReadFromURIFunc which tries to read a URI using the -// given reader functions, in the same order. If a reader function does not -// support the URI and returns ErrURINotSupported, the next function is checked -// until a match is found, or the URI is not supported by any. -func ReadFromURIs(readers ...ReadFromURIFunc) ReadFromURIFunc { - return func(loader *Loader, url *url.URL) ([]byte, error) { - for i := range readers { - buf, err := readers[i](loader, url) - if err == ErrURINotSupported { - continue - } else if err != nil { - return nil, err - } - return buf, nil - } - return nil, ErrURINotSupported - } -} - -// DefaultReadFromURI returns a caching ReadFromURIFunc which can read remote -// HTTP URIs and local file URIs. -var DefaultReadFromURI = URIMapCache(ReadFromURIs(ReadFromHTTP(http.DefaultClient), ReadFromFile)) - -// ReadFromHTTP returns a ReadFromURIFunc which uses the given http.Client to -// read the contents from a remote HTTP URI. This client may be customized to -// implement timeouts, RFC 7234 caching, etc. -func ReadFromHTTP(cl *http.Client) ReadFromURIFunc { - return func(loader *Loader, location *url.URL) ([]byte, error) { - if location.Scheme == "" || location.Host == "" { - return nil, ErrURINotSupported - } - req, err := http.NewRequest("GET", location.String(), nil) - if err != nil { - return nil, err - } - resp, err := cl.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - if resp.StatusCode > 399 { - return nil, fmt.Errorf("error loading %q: request returned status code %d", location.String(), resp.StatusCode) - } - return ioutil.ReadAll(resp.Body) - } -} - -// ReadFromFile is a ReadFromURIFunc which reads local file URIs. -func ReadFromFile(loader *Loader, location *url.URL) ([]byte, error) { - if location.Host != "" { - return nil, ErrURINotSupported - } - if location.Scheme != "" && location.Scheme != "file" { - return nil, ErrURINotSupported - } - return ioutil.ReadFile(location.Path) -} - -// URIMapCache returns a ReadFromURIFunc that caches the contents read from URI -// locations in a simple map. This cache implementation is suitable for -// short-lived processes such as command-line tools which process OpenAPI -// documents. -func URIMapCache(reader ReadFromURIFunc) ReadFromURIFunc { - cache := map[string][]byte{} - return func(loader *Loader, location *url.URL) (buf []byte, err error) { - if location.Scheme == "" || location.Scheme == "file" { - if !filepath.IsAbs(location.Path) { - // Do not cache relative file paths; this can cause trouble if - // the current working directory changes when processing - // multiple top-level documents. - return reader(loader, location) - } - } - uri := location.String() - var ok bool - if buf, ok = cache[uri]; ok { - return - } - if buf, err = reader(loader, location); err != nil { - return - } - cache[uri] = buf - return - } -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/media_type.go b/vendor/github.com/getkin/kin-openapi/openapi3/media_type.go deleted file mode 100644 index 5c001ca6..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/media_type.go +++ /dev/null @@ -1,101 +0,0 @@ -package openapi3 - -import ( - "context" - - "github.com/getkin/kin-openapi/jsoninfo" - "github.com/go-openapi/jsonpointer" -) - -// MediaType is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#mediaTypeObject -type MediaType struct { - ExtensionProps - - Schema *SchemaRef `json:"schema,omitempty" yaml:"schema,omitempty"` - Example interface{} `json:"example,omitempty" yaml:"example,omitempty"` - Examples Examples `json:"examples,omitempty" yaml:"examples,omitempty"` - Encoding map[string]*Encoding `json:"encoding,omitempty" yaml:"encoding,omitempty"` -} - -var _ jsonpointer.JSONPointable = (*MediaType)(nil) - -func NewMediaType() *MediaType { - return &MediaType{} -} - -func (mediaType *MediaType) WithSchema(schema *Schema) *MediaType { - if schema == nil { - mediaType.Schema = nil - } else { - mediaType.Schema = &SchemaRef{Value: schema} - } - return mediaType -} - -func (mediaType *MediaType) WithSchemaRef(schema *SchemaRef) *MediaType { - mediaType.Schema = schema - return mediaType -} - -func (mediaType *MediaType) WithExample(name string, value interface{}) *MediaType { - example := mediaType.Examples - if example == nil { - example = make(map[string]*ExampleRef) - mediaType.Examples = example - } - example[name] = &ExampleRef{ - Value: NewExample(value), - } - return mediaType -} - -func (mediaType *MediaType) WithEncoding(name string, enc *Encoding) *MediaType { - encoding := mediaType.Encoding - if encoding == nil { - encoding = make(map[string]*Encoding) - mediaType.Encoding = encoding - } - encoding[name] = enc - return mediaType -} - -func (mediaType *MediaType) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(mediaType) -} - -func (mediaType *MediaType) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, mediaType) -} - -func (value *MediaType) Validate(ctx context.Context) error { - if value == nil { - return nil - } - if schema := value.Schema; schema != nil { - if err := schema.Validate(ctx); err != nil { - return err - } - } - return nil -} - -func (mediaType MediaType) JSONLookup(token string) (interface{}, error) { - switch token { - case "schema": - if mediaType.Schema != nil { - if mediaType.Schema.Ref != "" { - return &Ref{Ref: mediaType.Schema.Ref}, nil - } - return mediaType.Schema.Value, nil - } - case "example": - return mediaType.Example, nil - case "examples": - return mediaType.Examples, nil - case "encoding": - return mediaType.Encoding, nil - } - v, _, err := jsonpointer.GetForToken(mediaType.ExtensionProps, token) - return v, err -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/openapi3.go b/vendor/github.com/getkin/kin-openapi/openapi3/openapi3.go deleted file mode 100644 index d376812b..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/openapi3.go +++ /dev/null @@ -1,125 +0,0 @@ -package openapi3 - -import ( - "context" - "errors" - "fmt" - - "github.com/getkin/kin-openapi/jsoninfo" -) - -// T is the root of an OpenAPI v3 document -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#oasObject -type T struct { - ExtensionProps - - OpenAPI string `json:"openapi" yaml:"openapi"` // Required - Components Components `json:"components,omitempty" yaml:"components,omitempty"` - Info *Info `json:"info" yaml:"info"` // Required - Paths Paths `json:"paths" yaml:"paths"` // Required - Security SecurityRequirements `json:"security,omitempty" yaml:"security,omitempty"` - Servers Servers `json:"servers,omitempty" yaml:"servers,omitempty"` - Tags Tags `json:"tags,omitempty" yaml:"tags,omitempty"` - ExternalDocs *ExternalDocs `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"` -} - -func (doc *T) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(doc) -} - -func (doc *T) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, doc) -} - -func (doc *T) AddOperation(path string, method string, operation *Operation) { - paths := doc.Paths - if paths == nil { - paths = make(Paths) - doc.Paths = paths - } - pathItem := paths[path] - if pathItem == nil { - pathItem = &PathItem{} - paths[path] = pathItem - } - pathItem.SetOperation(method, operation) -} - -func (doc *T) AddServer(server *Server) { - doc.Servers = append(doc.Servers, server) -} - -func (value *T) Validate(ctx context.Context) error { - if value.OpenAPI == "" { - return errors.New("value of openapi must be a non-empty string") - } - - // NOTE: only mention info/components/paths/... key in this func's errors. - - { - wrap := func(e error) error { return fmt.Errorf("invalid components: %v", e) } - if err := value.Components.Validate(ctx); err != nil { - return wrap(err) - } - } - - { - wrap := func(e error) error { return fmt.Errorf("invalid info: %v", e) } - if v := value.Info; v != nil { - if err := v.Validate(ctx); err != nil { - return wrap(err) - } - } else { - return wrap(errors.New("must be an object")) - } - } - - { - wrap := func(e error) error { return fmt.Errorf("invalid paths: %v", e) } - if v := value.Paths; v != nil { - if err := v.Validate(ctx); err != nil { - return wrap(err) - } - } else { - return wrap(errors.New("must be an object")) - } - } - - { - wrap := func(e error) error { return fmt.Errorf("invalid security: %v", e) } - if v := value.Security; v != nil { - if err := v.Validate(ctx); err != nil { - return wrap(err) - } - } - } - - { - wrap := func(e error) error { return fmt.Errorf("invalid servers: %v", e) } - if v := value.Servers; v != nil { - if err := v.Validate(ctx); err != nil { - return wrap(err) - } - } - } - - { - wrap := func(e error) error { return fmt.Errorf("invalid tags: %w", e) } - if v := value.Tags; v != nil { - if err := v.Validate(ctx); err != nil { - return wrap(err) - } - } - } - - { - wrap := func(e error) error { return fmt.Errorf("invalid external docs: %w", e) } - if v := value.ExternalDocs; v != nil { - if err := v.Validate(ctx); err != nil { - return wrap(err) - } - } - } - - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/operation.go b/vendor/github.com/getkin/kin-openapi/openapi3/operation.go deleted file mode 100644 index 29e70c77..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/operation.go +++ /dev/null @@ -1,149 +0,0 @@ -package openapi3 - -import ( - "context" - "errors" - "fmt" - "strconv" - - "github.com/getkin/kin-openapi/jsoninfo" - "github.com/go-openapi/jsonpointer" -) - -// Operation represents "operation" specified by" OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object -type Operation struct { - ExtensionProps - - // Optional tags for documentation. - Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"` - - // Optional short summary. - Summary string `json:"summary,omitempty" yaml:"summary,omitempty"` - - // Optional description. Should use CommonMark syntax. - Description string `json:"description,omitempty" yaml:"description,omitempty"` - - // Optional operation ID. - OperationID string `json:"operationId,omitempty" yaml:"operationId,omitempty"` - - // Optional parameters. - Parameters Parameters `json:"parameters,omitempty" yaml:"parameters,omitempty"` - - // Optional body parameter. - RequestBody *RequestBodyRef `json:"requestBody,omitempty" yaml:"requestBody,omitempty"` - - // Responses. - Responses Responses `json:"responses" yaml:"responses"` // Required - - // Optional callbacks - Callbacks Callbacks `json:"callbacks,omitempty" yaml:"callbacks,omitempty"` - - Deprecated bool `json:"deprecated,omitempty" yaml:"deprecated,omitempty"` - - // Optional security requirements that overrides top-level security. - Security *SecurityRequirements `json:"security,omitempty" yaml:"security,omitempty"` - - // Optional servers that overrides top-level servers. - Servers *Servers `json:"servers,omitempty" yaml:"servers,omitempty"` - - ExternalDocs *ExternalDocs `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"` -} - -var _ jsonpointer.JSONPointable = (*Operation)(nil) - -func NewOperation() *Operation { - return &Operation{} -} - -func (operation *Operation) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(operation) -} - -func (operation *Operation) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, operation) -} - -func (operation Operation) JSONLookup(token string) (interface{}, error) { - switch token { - case "requestBody": - if operation.RequestBody != nil { - if operation.RequestBody.Ref != "" { - return &Ref{Ref: operation.RequestBody.Ref}, nil - } - return operation.RequestBody.Value, nil - } - case "tags": - return operation.Tags, nil - case "summary": - return operation.Summary, nil - case "description": - return operation.Description, nil - case "operationID": - return operation.OperationID, nil - case "parameters": - return operation.Parameters, nil - case "responses": - return operation.Responses, nil - case "callbacks": - return operation.Callbacks, nil - case "deprecated": - return operation.Deprecated, nil - case "security": - return operation.Security, nil - case "servers": - return operation.Servers, nil - case "externalDocs": - return operation.ExternalDocs, nil - } - - v, _, err := jsonpointer.GetForToken(operation.ExtensionProps, token) - return v, err -} - -func (operation *Operation) AddParameter(p *Parameter) { - operation.Parameters = append(operation.Parameters, &ParameterRef{ - Value: p, - }) -} - -func (operation *Operation) AddResponse(status int, response *Response) { - responses := operation.Responses - if responses == nil { - responses = NewResponses() - operation.Responses = responses - } - code := "default" - if status != 0 { - code = strconv.FormatInt(int64(status), 10) - } - responses[code] = &ResponseRef{ - Value: response, - } -} - -func (value *Operation) Validate(ctx context.Context) error { - if v := value.Parameters; v != nil { - if err := v.Validate(ctx); err != nil { - return err - } - } - if v := value.RequestBody; v != nil { - if err := v.Validate(ctx); err != nil { - return err - } - } - if v := value.Responses; v != nil { - if err := v.Validate(ctx); err != nil { - return err - } - } else { - return errors.New("value of responses must be an object") - } - if v := value.ExternalDocs; v != nil { - if err := v.Validate(ctx); err != nil { - return fmt.Errorf("invalid external docs: %w", err) - } - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/parameter.go b/vendor/github.com/getkin/kin-openapi/openapi3/parameter.go deleted file mode 100644 index e283a98f..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/parameter.go +++ /dev/null @@ -1,310 +0,0 @@ -package openapi3 - -import ( - "context" - "errors" - "fmt" - "strconv" - - "github.com/getkin/kin-openapi/jsoninfo" - "github.com/go-openapi/jsonpointer" -) - -type ParametersMap map[string]*ParameterRef - -var _ jsonpointer.JSONPointable = (*ParametersMap)(nil) - -func (p ParametersMap) JSONLookup(token string) (interface{}, error) { - ref, ok := p[token] - if ref == nil || ok == false { - return nil, fmt.Errorf("object has no field %q", token) - } - - if ref.Ref != "" { - return &Ref{Ref: ref.Ref}, nil - } - return ref.Value, nil -} - -// Parameters is specified by OpenAPI/Swagger 3.0 standard. -type Parameters []*ParameterRef - -var _ jsonpointer.JSONPointable = (*Parameters)(nil) - -func (p Parameters) JSONLookup(token string) (interface{}, error) { - index, err := strconv.Atoi(token) - if err != nil { - return nil, err - } - - if index < 0 || index >= len(p) { - return nil, fmt.Errorf("index %d out of bounds of array of length %d", index, len(p)) - } - - ref := p[index] - - if ref != nil && ref.Ref != "" { - return &Ref{Ref: ref.Ref}, nil - } - return ref.Value, nil -} - -func NewParameters() Parameters { - return make(Parameters, 0, 4) -} - -func (parameters Parameters) GetByInAndName(in string, name string) *Parameter { - for _, item := range parameters { - if v := item.Value; v != nil { - if v.Name == name && v.In == in { - return v - } - } - } - return nil -} - -func (value Parameters) Validate(ctx context.Context) error { - dupes := make(map[string]struct{}) - for _, item := range value { - if v := item.Value; v != nil { - key := v.In + ":" + v.Name - if _, ok := dupes[key]; ok { - return fmt.Errorf("more than one %q parameter has name %q", v.In, v.Name) - } - dupes[key] = struct{}{} - } - - if err := item.Validate(ctx); err != nil { - return err - } - } - return nil -} - -// Parameter is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameterObject -type Parameter struct { - ExtensionProps - - Name string `json:"name,omitempty" yaml:"name,omitempty"` - In string `json:"in,omitempty" yaml:"in,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Style string `json:"style,omitempty" yaml:"style,omitempty"` - Explode *bool `json:"explode,omitempty" yaml:"explode,omitempty"` - AllowEmptyValue bool `json:"allowEmptyValue,omitempty" yaml:"allowEmptyValue,omitempty"` - AllowReserved bool `json:"allowReserved,omitempty" yaml:"allowReserved,omitempty"` - Deprecated bool `json:"deprecated,omitempty" yaml:"deprecated,omitempty"` - Required bool `json:"required,omitempty" yaml:"required,omitempty"` - Schema *SchemaRef `json:"schema,omitempty" yaml:"schema,omitempty"` - Example interface{} `json:"example,omitempty" yaml:"example,omitempty"` - Examples Examples `json:"examples,omitempty" yaml:"examples,omitempty"` - Content Content `json:"content,omitempty" yaml:"content,omitempty"` -} - -var _ jsonpointer.JSONPointable = (*Parameter)(nil) - -const ( - ParameterInPath = "path" - ParameterInQuery = "query" - ParameterInHeader = "header" - ParameterInCookie = "cookie" -) - -func NewPathParameter(name string) *Parameter { - return &Parameter{ - Name: name, - In: ParameterInPath, - Required: true, - } -} - -func NewQueryParameter(name string) *Parameter { - return &Parameter{ - Name: name, - In: ParameterInQuery, - } -} - -func NewHeaderParameter(name string) *Parameter { - return &Parameter{ - Name: name, - In: ParameterInHeader, - } -} - -func NewCookieParameter(name string) *Parameter { - return &Parameter{ - Name: name, - In: ParameterInCookie, - } -} - -func (parameter *Parameter) WithDescription(value string) *Parameter { - parameter.Description = value - return parameter -} - -func (parameter *Parameter) WithRequired(value bool) *Parameter { - parameter.Required = value - return parameter -} - -func (parameter *Parameter) WithSchema(value *Schema) *Parameter { - if value == nil { - parameter.Schema = nil - } else { - parameter.Schema = &SchemaRef{ - Value: value, - } - } - return parameter -} - -func (parameter *Parameter) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(parameter) -} - -func (parameter *Parameter) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, parameter) -} - -func (value Parameter) JSONLookup(token string) (interface{}, error) { - switch token { - case "schema": - if value.Schema != nil { - if value.Schema.Ref != "" { - return &Ref{Ref: value.Schema.Ref}, nil - } - return value.Schema.Value, nil - } - case "name": - return value.Name, nil - case "in": - return value.In, nil - case "description": - return value.Description, nil - case "style": - return value.Style, nil - case "explode": - return value.Explode, nil - case "allowEmptyValue": - return value.AllowEmptyValue, nil - case "allowReserved": - return value.AllowReserved, nil - case "deprecated": - return value.Deprecated, nil - case "required": - return value.Required, nil - case "example": - return value.Example, nil - case "examples": - return value.Examples, nil - case "content": - return value.Content, nil - } - - v, _, err := jsonpointer.GetForToken(value.ExtensionProps, token) - return v, err -} - -// SerializationMethod returns a parameter's serialization method. -// When a parameter's serialization method is not defined the method returns -// the default serialization method corresponding to a parameter's location. -func (parameter *Parameter) SerializationMethod() (*SerializationMethod, error) { - switch parameter.In { - case ParameterInPath, ParameterInHeader: - style := parameter.Style - if style == "" { - style = SerializationSimple - } - explode := false - if parameter.Explode != nil { - explode = *parameter.Explode - } - return &SerializationMethod{Style: style, Explode: explode}, nil - case ParameterInQuery, ParameterInCookie: - style := parameter.Style - if style == "" { - style = SerializationForm - } - explode := true - if parameter.Explode != nil { - explode = *parameter.Explode - } - return &SerializationMethod{Style: style, Explode: explode}, nil - default: - return nil, fmt.Errorf("unexpected parameter's 'in': %q", parameter.In) - } -} - -func (value *Parameter) Validate(ctx context.Context) error { - if value.Name == "" { - return errors.New("parameter name can't be blank") - } - in := value.In - switch in { - case - ParameterInPath, - ParameterInQuery, - ParameterInHeader, - ParameterInCookie: - default: - return fmt.Errorf("parameter can't have 'in' value %q", value.In) - } - - if in == ParameterInPath && !value.Required { - return fmt.Errorf("path parameter %q must be required", value.Name) - } - - // Validate a parameter's serialization method. - sm, err := value.SerializationMethod() - if err != nil { - return err - } - var smSupported bool - switch { - case value.In == ParameterInPath && sm.Style == SerializationSimple && !sm.Explode, - value.In == ParameterInPath && sm.Style == SerializationSimple && sm.Explode, - value.In == ParameterInPath && sm.Style == SerializationLabel && !sm.Explode, - value.In == ParameterInPath && sm.Style == SerializationLabel && sm.Explode, - value.In == ParameterInPath && sm.Style == SerializationMatrix && !sm.Explode, - value.In == ParameterInPath && sm.Style == SerializationMatrix && sm.Explode, - - value.In == ParameterInQuery && sm.Style == SerializationForm && sm.Explode, - value.In == ParameterInQuery && sm.Style == SerializationForm && !sm.Explode, - value.In == ParameterInQuery && sm.Style == SerializationSpaceDelimited && sm.Explode, - value.In == ParameterInQuery && sm.Style == SerializationSpaceDelimited && !sm.Explode, - value.In == ParameterInQuery && sm.Style == SerializationPipeDelimited && sm.Explode, - value.In == ParameterInQuery && sm.Style == SerializationPipeDelimited && !sm.Explode, - value.In == ParameterInQuery && sm.Style == SerializationDeepObject && sm.Explode, - - value.In == ParameterInHeader && sm.Style == SerializationSimple && !sm.Explode, - value.In == ParameterInHeader && sm.Style == SerializationSimple && sm.Explode, - - value.In == ParameterInCookie && sm.Style == SerializationForm && !sm.Explode, - value.In == ParameterInCookie && sm.Style == SerializationForm && sm.Explode: - smSupported = true - } - if !smSupported { - e := fmt.Errorf("serialization method with style=%q and explode=%v is not supported by a %s parameter", sm.Style, sm.Explode, in) - return fmt.Errorf("parameter %q schema is invalid: %v", value.Name, e) - } - - if (value.Schema == nil) == (value.Content == nil) { - e := errors.New("parameter must contain exactly one of content and schema") - return fmt.Errorf("parameter %q schema is invalid: %v", value.Name, e) - } - if schema := value.Schema; schema != nil { - if err := schema.Validate(ctx); err != nil { - return fmt.Errorf("parameter %q schema is invalid: %v", value.Name, err) - } - } - - if content := value.Content; content != nil { - if err := content.Validate(ctx); err != nil { - return fmt.Errorf("parameter %q content is invalid: %v", value.Name, err) - } - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/path_item.go b/vendor/github.com/getkin/kin-openapi/openapi3/path_item.go deleted file mode 100644 index 4473d639..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/path_item.go +++ /dev/null @@ -1,129 +0,0 @@ -package openapi3 - -import ( - "context" - "fmt" - "net/http" - - "github.com/getkin/kin-openapi/jsoninfo" -) - -// PathItem is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#pathItemObject -type PathItem struct { - ExtensionProps - - Ref string `json:"$ref,omitempty" yaml:"$ref,omitempty"` - Summary string `json:"summary,omitempty" yaml:"summary,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Connect *Operation `json:"connect,omitempty" yaml:"connect,omitempty"` - Delete *Operation `json:"delete,omitempty" yaml:"delete,omitempty"` - Get *Operation `json:"get,omitempty" yaml:"get,omitempty"` - Head *Operation `json:"head,omitempty" yaml:"head,omitempty"` - Options *Operation `json:"options,omitempty" yaml:"options,omitempty"` - Patch *Operation `json:"patch,omitempty" yaml:"patch,omitempty"` - Post *Operation `json:"post,omitempty" yaml:"post,omitempty"` - Put *Operation `json:"put,omitempty" yaml:"put,omitempty"` - Trace *Operation `json:"trace,omitempty" yaml:"trace,omitempty"` - Servers Servers `json:"servers,omitempty" yaml:"servers,omitempty"` - Parameters Parameters `json:"parameters,omitempty" yaml:"parameters,omitempty"` -} - -func (pathItem *PathItem) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(pathItem) -} - -func (pathItem *PathItem) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, pathItem) -} - -func (pathItem *PathItem) Operations() map[string]*Operation { - operations := make(map[string]*Operation, 4) - if v := pathItem.Connect; v != nil { - operations[http.MethodConnect] = v - } - if v := pathItem.Delete; v != nil { - operations[http.MethodDelete] = v - } - if v := pathItem.Get; v != nil { - operations[http.MethodGet] = v - } - if v := pathItem.Head; v != nil { - operations[http.MethodHead] = v - } - if v := pathItem.Options; v != nil { - operations[http.MethodOptions] = v - } - if v := pathItem.Patch; v != nil { - operations[http.MethodPatch] = v - } - if v := pathItem.Post; v != nil { - operations[http.MethodPost] = v - } - if v := pathItem.Put; v != nil { - operations[http.MethodPut] = v - } - if v := pathItem.Trace; v != nil { - operations[http.MethodTrace] = v - } - return operations -} - -func (pathItem *PathItem) GetOperation(method string) *Operation { - switch method { - case http.MethodConnect: - return pathItem.Connect - case http.MethodDelete: - return pathItem.Delete - case http.MethodGet: - return pathItem.Get - case http.MethodHead: - return pathItem.Head - case http.MethodOptions: - return pathItem.Options - case http.MethodPatch: - return pathItem.Patch - case http.MethodPost: - return pathItem.Post - case http.MethodPut: - return pathItem.Put - case http.MethodTrace: - return pathItem.Trace - default: - panic(fmt.Errorf("unsupported HTTP method %q", method)) - } -} - -func (pathItem *PathItem) SetOperation(method string, operation *Operation) { - switch method { - case http.MethodConnect: - pathItem.Connect = operation - case http.MethodDelete: - pathItem.Delete = operation - case http.MethodGet: - pathItem.Get = operation - case http.MethodHead: - pathItem.Head = operation - case http.MethodOptions: - pathItem.Options = operation - case http.MethodPatch: - pathItem.Patch = operation - case http.MethodPost: - pathItem.Post = operation - case http.MethodPut: - pathItem.Put = operation - case http.MethodTrace: - pathItem.Trace = operation - default: - panic(fmt.Errorf("unsupported HTTP method %q", method)) - } -} - -func (value *PathItem) Validate(ctx context.Context) error { - for _, operation := range value.Operations() { - if err := operation.Validate(ctx); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/paths.go b/vendor/github.com/getkin/kin-openapi/openapi3/paths.go deleted file mode 100644 index 24ab5f30..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/paths.go +++ /dev/null @@ -1,194 +0,0 @@ -package openapi3 - -import ( - "context" - "fmt" - "strings" -) - -// Paths is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#paths-object -type Paths map[string]*PathItem - -func (value Paths) Validate(ctx context.Context) error { - normalizedPaths := make(map[string]string) - for path, pathItem := range value { - if path == "" || path[0] != '/' { - return fmt.Errorf("path %q does not start with a forward slash (/)", path) - } - - if pathItem == nil { - value[path] = &PathItem{} - pathItem = value[path] - } - - normalizedPath, _, varsInPath := normalizeTemplatedPath(path) - if oldPath, ok := normalizedPaths[normalizedPath]; ok { - return fmt.Errorf("conflicting paths %q and %q", path, oldPath) - } - normalizedPaths[path] = path - - var commonParams []string - for _, parameterRef := range pathItem.Parameters { - if parameterRef != nil { - if parameter := parameterRef.Value; parameter != nil && parameter.In == ParameterInPath { - commonParams = append(commonParams, parameter.Name) - } - } - } - for method, operation := range pathItem.Operations() { - var setParams []string - for _, parameterRef := range operation.Parameters { - if parameterRef != nil { - if parameter := parameterRef.Value; parameter != nil && parameter.In == ParameterInPath { - setParams = append(setParams, parameter.Name) - } - } - } - if expected := len(setParams) + len(commonParams); expected != len(varsInPath) { - expected -= len(varsInPath) - if expected < 0 { - expected *= -1 - } - missing := make(map[string]struct{}, expected) - definedParams := append(setParams, commonParams...) - for _, name := range definedParams { - if _, ok := varsInPath[name]; !ok { - missing[name] = struct{}{} - } - } - for name := range varsInPath { - got := false - for _, othername := range definedParams { - if othername == name { - got = true - break - } - } - if !got { - missing[name] = struct{}{} - } - } - if len(missing) != 0 { - missings := make([]string, 0, len(missing)) - for name := range missing { - missings = append(missings, name) - } - return fmt.Errorf("operation %s %s must define exactly all path parameters (missing: %v)", method, path, missings) - } - } - } - - if err := pathItem.Validate(ctx); err != nil { - return err - } - } - - if err := value.validateUniqueOperationIDs(); err != nil { - return err - } - - return nil -} - -// Find returns a path that matches the key. -// -// The method ignores differences in template variable names (except possible "*" suffix). -// -// For example: -// -// paths := openapi3.Paths { -// "/person/{personName}": &openapi3.PathItem{}, -// } -// pathItem := path.Find("/person/{name}") -// -// would return the correct path item. -func (paths Paths) Find(key string) *PathItem { - // Try directly access the map - pathItem := paths[key] - if pathItem != nil { - return pathItem - } - - normalizedPath, expected, _ := normalizeTemplatedPath(key) - for path, pathItem := range paths { - pathNormalized, got, _ := normalizeTemplatedPath(path) - if got == expected && pathNormalized == normalizedPath { - return pathItem - } - } - return nil -} - -func (value Paths) validateUniqueOperationIDs() error { - operationIDs := make(map[string]string) - for urlPath, pathItem := range value { - if pathItem == nil { - continue - } - for httpMethod, operation := range pathItem.Operations() { - if operation == nil || operation.OperationID == "" { - continue - } - endpoint := httpMethod + " " + urlPath - if endpointDup, ok := operationIDs[operation.OperationID]; ok { - if endpoint > endpointDup { // For make error message a bit more deterministic. May be useful for tests. - endpoint, endpointDup = endpointDup, endpoint - } - return fmt.Errorf("operations %q and %q have the same operation id %q", - endpoint, endpointDup, operation.OperationID) - } - operationIDs[operation.OperationID] = endpoint - } - } - return nil -} - -func normalizeTemplatedPath(path string) (string, uint, map[string]struct{}) { - if strings.IndexByte(path, '{') < 0 { - return path, 0, nil - } - - var buffTpl strings.Builder - buffTpl.Grow(len(path)) - - var ( - cc rune - count uint - isVariable bool - vars = make(map[string]struct{}) - buffVar strings.Builder - ) - for i, c := range path { - if isVariable { - if c == '}' { - // End path variable - isVariable = false - - vars[buffVar.String()] = struct{}{} - buffVar = strings.Builder{} - - // First append possible '*' before this character - // The character '}' will be appended - if i > 0 && cc == '*' { - buffTpl.WriteRune(cc) - } - } else { - buffVar.WriteRune(c) - continue - } - - } else if c == '{' { - // Begin path variable - isVariable = true - - // The character '{' will be appended - count++ - } - - // Append the character - buffTpl.WriteRune(c) - cc = c - } - return buffTpl.String(), count, vars -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/refs.go b/vendor/github.com/getkin/kin-openapi/openapi3/refs.go deleted file mode 100644 index 333cd174..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/refs.go +++ /dev/null @@ -1,307 +0,0 @@ -package openapi3 - -import ( - "context" - - "github.com/getkin/kin-openapi/jsoninfo" - "github.com/go-openapi/jsonpointer" -) - -// Ref is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#referenceObject -type Ref struct { - Ref string `json:"$ref" yaml:"$ref"` -} - -// CallbackRef represents either a Callback or a $ref to a Callback. -// When serializing and both fields are set, Ref is preferred over Value. -type CallbackRef struct { - Ref string - Value *Callback -} - -var _ jsonpointer.JSONPointable = (*CallbackRef)(nil) - -func (value *CallbackRef) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalRef(value.Ref, value.Value) -} - -func (value *CallbackRef) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalRef(data, &value.Ref, &value.Value) -} - -func (value *CallbackRef) Validate(ctx context.Context) error { - if v := value.Value; v != nil { - return v.Validate(ctx) - } - return foundUnresolvedRef(value.Ref) -} - -func (value CallbackRef) JSONLookup(token string) (interface{}, error) { - if token == "$ref" { - return value.Ref, nil - } - - ptr, _, err := jsonpointer.GetForToken(value.Value, token) - return ptr, err -} - -// ExampleRef represents either a Example or a $ref to a Example. -// When serializing and both fields are set, Ref is preferred over Value. -type ExampleRef struct { - Ref string - Value *Example -} - -var _ jsonpointer.JSONPointable = (*ExampleRef)(nil) - -func (value *ExampleRef) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalRef(value.Ref, value.Value) -} - -func (value *ExampleRef) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalRef(data, &value.Ref, &value.Value) -} - -func (value *ExampleRef) Validate(ctx context.Context) error { - if v := value.Value; v != nil { - return v.Validate(ctx) - } - return foundUnresolvedRef(value.Ref) -} - -func (value ExampleRef) JSONLookup(token string) (interface{}, error) { - if token == "$ref" { - return value.Ref, nil - } - - ptr, _, err := jsonpointer.GetForToken(value.Value, token) - return ptr, err -} - -// HeaderRef represents either a Header or a $ref to a Header. -// When serializing and both fields are set, Ref is preferred over Value. -type HeaderRef struct { - Ref string - Value *Header -} - -var _ jsonpointer.JSONPointable = (*HeaderRef)(nil) - -func (value *HeaderRef) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalRef(value.Ref, value.Value) -} - -func (value *HeaderRef) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalRef(data, &value.Ref, &value.Value) -} - -func (value *HeaderRef) Validate(ctx context.Context) error { - if v := value.Value; v != nil { - return v.Validate(ctx) - } - return foundUnresolvedRef(value.Ref) -} - -func (value HeaderRef) JSONLookup(token string) (interface{}, error) { - if token == "$ref" { - return value.Ref, nil - } - - ptr, _, err := jsonpointer.GetForToken(value.Value, token) - return ptr, err -} - -// LinkRef represents either a Link or a $ref to a Link. -// When serializing and both fields are set, Ref is preferred over Value. -type LinkRef struct { - Ref string - Value *Link -} - -func (value *LinkRef) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalRef(value.Ref, value.Value) -} - -func (value *LinkRef) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalRef(data, &value.Ref, &value.Value) -} - -func (value *LinkRef) Validate(ctx context.Context) error { - if v := value.Value; v != nil { - return v.Validate(ctx) - } - return foundUnresolvedRef(value.Ref) -} - -// ParameterRef represents either a Parameter or a $ref to a Parameter. -// When serializing and both fields are set, Ref is preferred over Value. -type ParameterRef struct { - Ref string - Value *Parameter -} - -var _ jsonpointer.JSONPointable = (*ParameterRef)(nil) - -func (value *ParameterRef) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalRef(value.Ref, value.Value) -} - -func (value *ParameterRef) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalRef(data, &value.Ref, &value.Value) -} - -func (value *ParameterRef) Validate(ctx context.Context) error { - if v := value.Value; v != nil { - return v.Validate(ctx) - } - return foundUnresolvedRef(value.Ref) -} - -func (value ParameterRef) JSONLookup(token string) (interface{}, error) { - if token == "$ref" { - return value.Ref, nil - } - - ptr, _, err := jsonpointer.GetForToken(value.Value, token) - return ptr, err -} - -// ResponseRef represents either a Response or a $ref to a Response. -// When serializing and both fields are set, Ref is preferred over Value. -type ResponseRef struct { - Ref string - Value *Response -} - -var _ jsonpointer.JSONPointable = (*ResponseRef)(nil) - -func (value *ResponseRef) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalRef(value.Ref, value.Value) -} - -func (value *ResponseRef) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalRef(data, &value.Ref, &value.Value) -} - -func (value *ResponseRef) Validate(ctx context.Context) error { - if v := value.Value; v != nil { - return v.Validate(ctx) - } - return foundUnresolvedRef(value.Ref) -} - -func (value ResponseRef) JSONLookup(token string) (interface{}, error) { - if token == "$ref" { - return value.Ref, nil - } - - ptr, _, err := jsonpointer.GetForToken(value.Value, token) - return ptr, err -} - -// RequestBodyRef represents either a RequestBody or a $ref to a RequestBody. -// When serializing and both fields are set, Ref is preferred over Value. -type RequestBodyRef struct { - Ref string - Value *RequestBody -} - -var _ jsonpointer.JSONPointable = (*RequestBodyRef)(nil) - -func (value *RequestBodyRef) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalRef(value.Ref, value.Value) -} - -func (value *RequestBodyRef) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalRef(data, &value.Ref, &value.Value) -} - -func (value *RequestBodyRef) Validate(ctx context.Context) error { - if v := value.Value; v != nil { - return v.Validate(ctx) - } - return foundUnresolvedRef(value.Ref) -} - -func (value RequestBodyRef) JSONLookup(token string) (interface{}, error) { - if token == "$ref" { - return value.Ref, nil - } - - ptr, _, err := jsonpointer.GetForToken(value.Value, token) - return ptr, err -} - -// SchemaRef represents either a Schema or a $ref to a Schema. -// When serializing and both fields are set, Ref is preferred over Value. -type SchemaRef struct { - Ref string - Value *Schema -} - -var _ jsonpointer.JSONPointable = (*SchemaRef)(nil) - -func NewSchemaRef(ref string, value *Schema) *SchemaRef { - return &SchemaRef{ - Ref: ref, - Value: value, - } -} - -func (value *SchemaRef) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalRef(value.Ref, value.Value) -} - -func (value *SchemaRef) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalRef(data, &value.Ref, &value.Value) -} - -func (value *SchemaRef) Validate(ctx context.Context) error { - if v := value.Value; v != nil { - return v.Validate(ctx) - } - return foundUnresolvedRef(value.Ref) -} - -func (value SchemaRef) JSONLookup(token string) (interface{}, error) { - if token == "$ref" { - return value.Ref, nil - } - - ptr, _, err := jsonpointer.GetForToken(value.Value, token) - return ptr, err -} - -// SecuritySchemeRef represents either a SecurityScheme or a $ref to a SecurityScheme. -// When serializing and both fields are set, Ref is preferred over Value. -type SecuritySchemeRef struct { - Ref string - Value *SecurityScheme -} - -var _ jsonpointer.JSONPointable = (*SecuritySchemeRef)(nil) - -func (value *SecuritySchemeRef) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalRef(value.Ref, value.Value) -} - -func (value *SecuritySchemeRef) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalRef(data, &value.Ref, &value.Value) -} - -func (value *SecuritySchemeRef) Validate(ctx context.Context) error { - if v := value.Value; v != nil { - return v.Validate(ctx) - } - return foundUnresolvedRef(value.Ref) -} - -func (value SecuritySchemeRef) JSONLookup(token string) (interface{}, error) { - if token == "$ref" { - return value.Ref, nil - } - - ptr, _, err := jsonpointer.GetForToken(value.Value, token) - return ptr, err -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/request_body.go b/vendor/github.com/getkin/kin-openapi/openapi3/request_body.go deleted file mode 100644 index 0be098c0..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/request_body.go +++ /dev/null @@ -1,108 +0,0 @@ -package openapi3 - -import ( - "context" - "errors" - "fmt" - - "github.com/getkin/kin-openapi/jsoninfo" - "github.com/go-openapi/jsonpointer" -) - -type RequestBodies map[string]*RequestBodyRef - -var _ jsonpointer.JSONPointable = (*RequestBodyRef)(nil) - -func (r RequestBodies) JSONLookup(token string) (interface{}, error) { - ref, ok := r[token] - if ok == false { - return nil, fmt.Errorf("object has no field %q", token) - } - - if ref != nil && ref.Ref != "" { - return &Ref{Ref: ref.Ref}, nil - } - return ref.Value, nil -} - -// RequestBody is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#requestBodyObject -type RequestBody struct { - ExtensionProps - - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Required bool `json:"required,omitempty" yaml:"required,omitempty"` - Content Content `json:"content" yaml:"content"` -} - -func NewRequestBody() *RequestBody { - return &RequestBody{} -} - -func (requestBody *RequestBody) WithDescription(value string) *RequestBody { - requestBody.Description = value - return requestBody -} - -func (requestBody *RequestBody) WithRequired(value bool) *RequestBody { - requestBody.Required = value - return requestBody -} - -func (requestBody *RequestBody) WithContent(content Content) *RequestBody { - requestBody.Content = content - return requestBody -} - -func (requestBody *RequestBody) WithSchemaRef(value *SchemaRef, consumes []string) *RequestBody { - requestBody.Content = NewContentWithSchemaRef(value, consumes) - return requestBody -} - -func (requestBody *RequestBody) WithSchema(value *Schema, consumes []string) *RequestBody { - requestBody.Content = NewContentWithSchema(value, consumes) - return requestBody -} - -func (requestBody *RequestBody) WithJSONSchemaRef(value *SchemaRef) *RequestBody { - requestBody.Content = NewContentWithJSONSchemaRef(value) - return requestBody -} - -func (requestBody *RequestBody) WithJSONSchema(value *Schema) *RequestBody { - requestBody.Content = NewContentWithJSONSchema(value) - return requestBody -} - -func (requestBody *RequestBody) WithFormDataSchemaRef(value *SchemaRef) *RequestBody { - requestBody.Content = NewContentWithFormDataSchemaRef(value) - return requestBody -} - -func (requestBody *RequestBody) WithFormDataSchema(value *Schema) *RequestBody { - requestBody.Content = NewContentWithFormDataSchema(value) - return requestBody -} - -func (requestBody *RequestBody) GetMediaType(mediaType string) *MediaType { - m := requestBody.Content - if m == nil { - return nil - } - return m[mediaType] -} - -func (requestBody *RequestBody) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(requestBody) -} - -func (requestBody *RequestBody) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, requestBody) -} - -func (value *RequestBody) Validate(ctx context.Context) error { - if value.Content == nil { - return errors.New("content of the request body is required") - } - return value.Content.Validate(ctx) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/response.go b/vendor/github.com/getkin/kin-openapi/openapi3/response.go deleted file mode 100644 index 8e22698f..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/response.go +++ /dev/null @@ -1,122 +0,0 @@ -package openapi3 - -import ( - "context" - "errors" - "fmt" - "strconv" - - "github.com/getkin/kin-openapi/jsoninfo" - "github.com/go-openapi/jsonpointer" -) - -// Responses is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#responsesObject -type Responses map[string]*ResponseRef - -var _ jsonpointer.JSONPointable = (*Responses)(nil) - -func NewResponses() Responses { - r := make(Responses) - r["default"] = &ResponseRef{Value: NewResponse().WithDescription("")} - return r -} - -func (responses Responses) Default() *ResponseRef { - return responses["default"] -} - -func (responses Responses) Get(status int) *ResponseRef { - return responses[strconv.FormatInt(int64(status), 10)] -} - -func (value Responses) Validate(ctx context.Context) error { - if len(value) == 0 { - return errors.New("the responses object MUST contain at least one response code") - } - for _, v := range value { - if err := v.Validate(ctx); err != nil { - return err - } - } - return nil -} - -func (responses Responses) JSONLookup(token string) (interface{}, error) { - ref, ok := responses[token] - if ok == false { - return nil, fmt.Errorf("invalid token reference: %q", token) - } - - if ref != nil && ref.Ref != "" { - return &Ref{Ref: ref.Ref}, nil - } - return ref.Value, nil -} - -// Response is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#responseObject -type Response struct { - ExtensionProps - - Description *string `json:"description,omitempty" yaml:"description,omitempty"` - Headers Headers `json:"headers,omitempty" yaml:"headers,omitempty"` - Content Content `json:"content,omitempty" yaml:"content,omitempty"` - Links Links `json:"links,omitempty" yaml:"links,omitempty"` -} - -func NewResponse() *Response { - return &Response{} -} - -func (response *Response) WithDescription(value string) *Response { - response.Description = &value - return response -} - -func (response *Response) WithContent(content Content) *Response { - response.Content = content - return response -} - -func (response *Response) WithJSONSchema(schema *Schema) *Response { - response.Content = NewContentWithJSONSchema(schema) - return response -} - -func (response *Response) WithJSONSchemaRef(schema *SchemaRef) *Response { - response.Content = NewContentWithJSONSchemaRef(schema) - return response -} - -func (response *Response) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(response) -} - -func (response *Response) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, response) -} - -func (value *Response) Validate(ctx context.Context) error { - if value.Description == nil { - return errors.New("a short description of the response is required") - } - - if content := value.Content; content != nil { - if err := content.Validate(ctx); err != nil { - return err - } - } - for _, header := range value.Headers { - if err := header.Validate(ctx); err != nil { - return err - } - } - - for _, link := range value.Links { - if err := link.Validate(ctx); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/schema.go b/vendor/github.com/getkin/kin-openapi/openapi3/schema.go deleted file mode 100644 index 73506f76..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/schema.go +++ /dev/null @@ -1,1627 +0,0 @@ -package openapi3 - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "math" - "math/big" - "regexp" - "strconv" - "unicode/utf16" - - "github.com/getkin/kin-openapi/jsoninfo" - "github.com/go-openapi/jsonpointer" -) - -const ( - TypeArray = "array" - TypeBoolean = "boolean" - TypeInteger = "integer" - TypeNumber = "number" - TypeObject = "object" - TypeString = "string" -) - -var ( - // SchemaErrorDetailsDisabled disables printing of details about schema errors. - SchemaErrorDetailsDisabled = false - - //SchemaFormatValidationDisabled disables validation of schema type formats. - SchemaFormatValidationDisabled = false - - errSchema = errors.New("input does not match the schema") - - // ErrOneOfConflict is the SchemaError Origin when data matches more than one oneOf schema - ErrOneOfConflict = errors.New("input matches more than one oneOf schemas") - - // ErrSchemaInputNaN may be returned when validating a number - ErrSchemaInputNaN = errors.New("floating point NaN is not allowed") - // ErrSchemaInputInf may be returned when validating a number - ErrSchemaInputInf = errors.New("floating point Inf is not allowed") -) - -// Float64Ptr is a helper for defining OpenAPI schemas. -func Float64Ptr(value float64) *float64 { - return &value -} - -// BoolPtr is a helper for defining OpenAPI schemas. -func BoolPtr(value bool) *bool { - return &value -} - -// Int64Ptr is a helper for defining OpenAPI schemas. -func Int64Ptr(value int64) *int64 { - return &value -} - -// Uint64Ptr is a helper for defining OpenAPI schemas. -func Uint64Ptr(value uint64) *uint64 { - return &value -} - -type Schemas map[string]*SchemaRef - -var _ jsonpointer.JSONPointable = (*Schemas)(nil) - -func (s Schemas) JSONLookup(token string) (interface{}, error) { - ref, ok := s[token] - if ref == nil || ok == false { - return nil, fmt.Errorf("object has no field %q", token) - } - - if ref.Ref != "" { - return &Ref{Ref: ref.Ref}, nil - } - return ref.Value, nil -} - -type SchemaRefs []*SchemaRef - -var _ jsonpointer.JSONPointable = (*SchemaRefs)(nil) - -func (s SchemaRefs) JSONLookup(token string) (interface{}, error) { - i, err := strconv.ParseUint(token, 10, 64) - if err != nil { - return nil, err - } - - if i >= uint64(len(s)) { - return nil, fmt.Errorf("index out of range: %d", i) - } - - ref := s[i] - - if ref == nil || ref.Ref != "" { - return &Ref{Ref: ref.Ref}, nil - } - return ref.Value, nil -} - -// Schema is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schemaObject -type Schema struct { - ExtensionProps - - OneOf SchemaRefs `json:"oneOf,omitempty" yaml:"oneOf,omitempty"` - AnyOf SchemaRefs `json:"anyOf,omitempty" yaml:"anyOf,omitempty"` - AllOf SchemaRefs `json:"allOf,omitempty" yaml:"allOf,omitempty"` - Not *SchemaRef `json:"not,omitempty" yaml:"not,omitempty"` - Type string `json:"type,omitempty" yaml:"type,omitempty"` - Title string `json:"title,omitempty" yaml:"title,omitempty"` - Format string `json:"format,omitempty" yaml:"format,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Enum []interface{} `json:"enum,omitempty" yaml:"enum,omitempty"` - Default interface{} `json:"default,omitempty" yaml:"default,omitempty"` - Example interface{} `json:"example,omitempty" yaml:"example,omitempty"` - ExternalDocs *ExternalDocs `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"` - - // Array-related, here for struct compactness - UniqueItems bool `json:"uniqueItems,omitempty" yaml:"uniqueItems,omitempty"` - // Number-related, here for struct compactness - ExclusiveMin bool `json:"exclusiveMinimum,omitempty" yaml:"exclusiveMinimum,omitempty"` - ExclusiveMax bool `json:"exclusiveMaximum,omitempty" yaml:"exclusiveMaximum,omitempty"` - // Properties - Nullable bool `json:"nullable,omitempty" yaml:"nullable,omitempty"` - ReadOnly bool `json:"readOnly,omitempty" yaml:"readOnly,omitempty"` - WriteOnly bool `json:"writeOnly,omitempty" yaml:"writeOnly,omitempty"` - AllowEmptyValue bool `json:"allowEmptyValue,omitempty" yaml:"allowEmptyValue,omitempty"` - Deprecated bool `json:"deprecated,omitempty" yaml:"deprecated,omitempty"` - XML *XML `json:"xml,omitempty" yaml:"xml,omitempty"` - - // Number - Min *float64 `json:"minimum,omitempty" yaml:"minimum,omitempty"` - Max *float64 `json:"maximum,omitempty" yaml:"maximum,omitempty"` - MultipleOf *float64 `json:"multipleOf,omitempty" yaml:"multipleOf,omitempty"` - - // String - MinLength uint64 `json:"minLength,omitempty" yaml:"minLength,omitempty"` - MaxLength *uint64 `json:"maxLength,omitempty" yaml:"maxLength,omitempty"` - Pattern string `json:"pattern,omitempty" yaml:"pattern,omitempty"` - compiledPattern *regexp.Regexp - - // Array - MinItems uint64 `json:"minItems,omitempty" yaml:"minItems,omitempty"` - MaxItems *uint64 `json:"maxItems,omitempty" yaml:"maxItems,omitempty"` - Items *SchemaRef `json:"items,omitempty" yaml:"items,omitempty"` - - // Object - Required []string `json:"required,omitempty" yaml:"required,omitempty"` - Properties Schemas `json:"properties,omitempty" yaml:"properties,omitempty"` - MinProps uint64 `json:"minProperties,omitempty" yaml:"minProperties,omitempty"` - MaxProps *uint64 `json:"maxProperties,omitempty" yaml:"maxProperties,omitempty"` - AdditionalPropertiesAllowed *bool `multijson:"additionalProperties,omitempty" json:"-" yaml:"-"` // In this order... - AdditionalProperties *SchemaRef `multijson:"additionalProperties,omitempty" json:"-" yaml:"-"` // ...for multijson - Discriminator *Discriminator `json:"discriminator,omitempty" yaml:"discriminator,omitempty"` -} - -var _ jsonpointer.JSONPointable = (*Schema)(nil) - -func NewSchema() *Schema { - return &Schema{} -} - -func (schema *Schema) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(schema) -} - -func (schema *Schema) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, schema) -} - -func (schema Schema) JSONLookup(token string) (interface{}, error) { - switch token { - case "additionalProperties": - if schema.AdditionalProperties != nil { - if schema.AdditionalProperties.Ref != "" { - return &Ref{Ref: schema.AdditionalProperties.Ref}, nil - } - return schema.AdditionalProperties.Value, nil - } - case "not": - if schema.Not != nil { - if schema.Not.Ref != "" { - return &Ref{Ref: schema.Not.Ref}, nil - } - return schema.Not.Value, nil - } - case "items": - if schema.Items != nil { - if schema.Items.Ref != "" { - return &Ref{Ref: schema.Items.Ref}, nil - } - return schema.Items.Value, nil - } - case "oneOf": - return schema.OneOf, nil - case "anyOf": - return schema.AnyOf, nil - case "allOf": - return schema.AllOf, nil - case "type": - return schema.Type, nil - case "title": - return schema.Title, nil - case "format": - return schema.Format, nil - case "description": - return schema.Description, nil - case "enum": - return schema.Enum, nil - case "default": - return schema.Default, nil - case "example": - return schema.Example, nil - case "externalDocs": - return schema.ExternalDocs, nil - case "additionalPropertiesAllowed": - return schema.AdditionalPropertiesAllowed, nil - case "uniqueItems": - return schema.UniqueItems, nil - case "exclusiveMin": - return schema.ExclusiveMin, nil - case "exclusiveMax": - return schema.ExclusiveMax, nil - case "nullable": - return schema.Nullable, nil - case "readOnly": - return schema.ReadOnly, nil - case "writeOnly": - return schema.WriteOnly, nil - case "allowEmptyValue": - return schema.AllowEmptyValue, nil - case "xml": - return schema.XML, nil - case "deprecated": - return schema.Deprecated, nil - case "min": - return schema.Min, nil - case "max": - return schema.Max, nil - case "multipleOf": - return schema.MultipleOf, nil - case "minLength": - return schema.MinLength, nil - case "maxLength": - return schema.MaxLength, nil - case "pattern": - return schema.Pattern, nil - case "minItems": - return schema.MinItems, nil - case "maxItems": - return schema.MaxItems, nil - case "required": - return schema.Required, nil - case "properties": - return schema.Properties, nil - case "minProps": - return schema.MinProps, nil - case "maxProps": - return schema.MaxProps, nil - case "discriminator": - return schema.Discriminator, nil - } - - v, _, err := jsonpointer.GetForToken(schema.ExtensionProps, token) - return v, err -} - -func (schema *Schema) NewRef() *SchemaRef { - return &SchemaRef{ - Value: schema, - } -} - -func NewOneOfSchema(schemas ...*Schema) *Schema { - refs := make([]*SchemaRef, 0, len(schemas)) - for _, schema := range schemas { - refs = append(refs, &SchemaRef{Value: schema}) - } - return &Schema{ - OneOf: refs, - } -} - -func NewAnyOfSchema(schemas ...*Schema) *Schema { - refs := make([]*SchemaRef, 0, len(schemas)) - for _, schema := range schemas { - refs = append(refs, &SchemaRef{Value: schema}) - } - return &Schema{ - AnyOf: refs, - } -} - -func NewAllOfSchema(schemas ...*Schema) *Schema { - refs := make([]*SchemaRef, 0, len(schemas)) - for _, schema := range schemas { - refs = append(refs, &SchemaRef{Value: schema}) - } - return &Schema{ - AllOf: refs, - } -} - -func NewBoolSchema() *Schema { - return &Schema{ - Type: TypeBoolean, - } -} - -func NewFloat64Schema() *Schema { - return &Schema{ - Type: TypeNumber, - } -} - -func NewIntegerSchema() *Schema { - return &Schema{ - Type: TypeInteger, - } -} - -func NewInt32Schema() *Schema { - return &Schema{ - Type: TypeInteger, - Format: "int32", - } -} - -func NewInt64Schema() *Schema { - return &Schema{ - Type: TypeInteger, - Format: "int64", - } -} - -func NewStringSchema() *Schema { - return &Schema{ - Type: TypeString, - } -} - -func NewDateTimeSchema() *Schema { - return &Schema{ - Type: TypeString, - Format: "date-time", - } -} - -func NewUUIDSchema() *Schema { - return &Schema{ - Type: TypeString, - Format: "uuid", - } -} - -func NewBytesSchema() *Schema { - return &Schema{ - Type: TypeString, - Format: "byte", - } -} - -func NewArraySchema() *Schema { - return &Schema{ - Type: TypeArray, - } -} - -func NewObjectSchema() *Schema { - return &Schema{ - Type: TypeObject, - Properties: make(Schemas), - } -} - -func (schema *Schema) WithNullable() *Schema { - schema.Nullable = true - return schema -} - -func (schema *Schema) WithMin(value float64) *Schema { - schema.Min = &value - return schema -} - -func (schema *Schema) WithMax(value float64) *Schema { - schema.Max = &value - return schema -} -func (schema *Schema) WithExclusiveMin(value bool) *Schema { - schema.ExclusiveMin = value - return schema -} - -func (schema *Schema) WithExclusiveMax(value bool) *Schema { - schema.ExclusiveMax = value - return schema -} - -func (schema *Schema) WithEnum(values ...interface{}) *Schema { - schema.Enum = values - return schema -} - -func (schema *Schema) WithDefault(defaultValue interface{}) *Schema { - schema.Default = defaultValue - return schema -} - -func (schema *Schema) WithFormat(value string) *Schema { - schema.Format = value - return schema -} - -func (schema *Schema) WithLength(i int64) *Schema { - n := uint64(i) - schema.MinLength = n - schema.MaxLength = &n - return schema -} - -func (schema *Schema) WithMinLength(i int64) *Schema { - n := uint64(i) - schema.MinLength = n - return schema -} - -func (schema *Schema) WithMaxLength(i int64) *Schema { - n := uint64(i) - schema.MaxLength = &n - return schema -} - -func (schema *Schema) WithLengthDecodedBase64(i int64) *Schema { - n := uint64(i) - v := (n*8 + 5) / 6 - schema.MinLength = v - schema.MaxLength = &v - return schema -} - -func (schema *Schema) WithMinLengthDecodedBase64(i int64) *Schema { - n := uint64(i) - schema.MinLength = (n*8 + 5) / 6 - return schema -} - -func (schema *Schema) WithMaxLengthDecodedBase64(i int64) *Schema { - n := uint64(i) - schema.MinLength = (n*8 + 5) / 6 - return schema -} - -func (schema *Schema) WithPattern(pattern string) *Schema { - schema.Pattern = pattern - schema.compiledPattern = nil - return schema -} - -func (schema *Schema) WithItems(value *Schema) *Schema { - schema.Items = &SchemaRef{ - Value: value, - } - return schema -} - -func (schema *Schema) WithMinItems(i int64) *Schema { - n := uint64(i) - schema.MinItems = n - return schema -} - -func (schema *Schema) WithMaxItems(i int64) *Schema { - n := uint64(i) - schema.MaxItems = &n - return schema -} - -func (schema *Schema) WithUniqueItems(unique bool) *Schema { - schema.UniqueItems = unique - return schema -} - -func (schema *Schema) WithProperty(name string, propertySchema *Schema) *Schema { - return schema.WithPropertyRef(name, &SchemaRef{ - Value: propertySchema, - }) -} - -func (schema *Schema) WithPropertyRef(name string, ref *SchemaRef) *Schema { - properties := schema.Properties - if properties == nil { - properties = make(Schemas) - schema.Properties = properties - } - properties[name] = ref - return schema -} - -func (schema *Schema) WithProperties(properties map[string]*Schema) *Schema { - result := make(Schemas, len(properties)) - for k, v := range properties { - result[k] = &SchemaRef{ - Value: v, - } - } - schema.Properties = result - return schema -} - -func (schema *Schema) WithMinProperties(i int64) *Schema { - n := uint64(i) - schema.MinProps = n - return schema -} - -func (schema *Schema) WithMaxProperties(i int64) *Schema { - n := uint64(i) - schema.MaxProps = &n - return schema -} - -func (schema *Schema) WithAnyAdditionalProperties() *Schema { - schema.AdditionalProperties = nil - t := true - schema.AdditionalPropertiesAllowed = &t - return schema -} - -func (schema *Schema) WithAdditionalProperties(v *Schema) *Schema { - if v == nil { - schema.AdditionalProperties = nil - } else { - schema.AdditionalProperties = &SchemaRef{ - Value: v, - } - } - return schema -} - -func (schema *Schema) IsEmpty() bool { - if schema.Type != "" || schema.Format != "" || len(schema.Enum) != 0 || - schema.UniqueItems || schema.ExclusiveMin || schema.ExclusiveMax || - schema.Nullable || schema.ReadOnly || schema.WriteOnly || schema.AllowEmptyValue || - schema.Min != nil || schema.Max != nil || schema.MultipleOf != nil || - schema.MinLength != 0 || schema.MaxLength != nil || schema.Pattern != "" || - schema.MinItems != 0 || schema.MaxItems != nil || - len(schema.Required) != 0 || - schema.MinProps != 0 || schema.MaxProps != nil { - return false - } - if n := schema.Not; n != nil && !n.Value.IsEmpty() { - return false - } - if ap := schema.AdditionalProperties; ap != nil && !ap.Value.IsEmpty() { - return false - } - if apa := schema.AdditionalPropertiesAllowed; apa != nil && !*apa { - return false - } - if items := schema.Items; items != nil && !items.Value.IsEmpty() { - return false - } - for _, s := range schema.Properties { - if !s.Value.IsEmpty() { - return false - } - } - for _, s := range schema.OneOf { - if !s.Value.IsEmpty() { - return false - } - } - for _, s := range schema.AnyOf { - if !s.Value.IsEmpty() { - return false - } - } - for _, s := range schema.AllOf { - if !s.Value.IsEmpty() { - return false - } - } - return true -} - -func (value *Schema) Validate(ctx context.Context) error { - return value.validate(ctx, []*Schema{}) -} - -func (schema *Schema) validate(ctx context.Context, stack []*Schema) (err error) { - for _, existing := range stack { - if existing == schema { - return - } - } - stack = append(stack, schema) - - if schema.ReadOnly && schema.WriteOnly { - return errors.New("a property MUST NOT be marked as both readOnly and writeOnly being true") - } - - for _, item := range schema.OneOf { - v := item.Value - if v == nil { - return foundUnresolvedRef(item.Ref) - } - if err = v.validate(ctx, stack); err == nil { - return - } - } - - for _, item := range schema.AnyOf { - v := item.Value - if v == nil { - return foundUnresolvedRef(item.Ref) - } - if err = v.validate(ctx, stack); err != nil { - return - } - } - - for _, item := range schema.AllOf { - v := item.Value - if v == nil { - return foundUnresolvedRef(item.Ref) - } - if err = v.validate(ctx, stack); err != nil { - return - } - } - - if ref := schema.Not; ref != nil { - v := ref.Value - if v == nil { - return foundUnresolvedRef(ref.Ref) - } - if err = v.validate(ctx, stack); err != nil { - return - } - } - - schemaType := schema.Type - switch schemaType { - case "": - case TypeBoolean: - case TypeNumber: - if format := schema.Format; len(format) > 0 { - switch format { - case "float", "double": - default: - if !SchemaFormatValidationDisabled { - return unsupportedFormat(format) - } - } - } - case TypeInteger: - if format := schema.Format; len(format) > 0 { - switch format { - case "int32", "int64": - default: - if !SchemaFormatValidationDisabled { - return unsupportedFormat(format) - } - } - } - case TypeString: - if format := schema.Format; len(format) > 0 { - switch format { - // Supported by OpenAPIv3.0.1: - case "byte", "binary", "date", "date-time", "password": - // In JSON Draft-07 (not validated yet though): - case "regex": - case "time", "email", "idn-email": - case "hostname", "idn-hostname", "ipv4", "ipv6": - case "uri", "uri-reference", "iri", "iri-reference", "uri-template": - case "json-pointer", "relative-json-pointer": - default: - // Try to check for custom defined formats - if _, ok := SchemaStringFormats[format]; !ok && !SchemaFormatValidationDisabled { - return unsupportedFormat(format) - } - } - } - if schema.Pattern != "" { - if err = schema.compilePattern(); err != nil { - return err - } - } - case TypeArray: - if schema.Items == nil { - return errors.New("when schema type is 'array', schema 'items' must be non-null") - } - case TypeObject: - default: - return fmt.Errorf("unsupported 'type' value %q", schemaType) - } - - if ref := schema.Items; ref != nil { - v := ref.Value - if v == nil { - return foundUnresolvedRef(ref.Ref) - } - if err = v.validate(ctx, stack); err != nil { - return - } - } - - for _, ref := range schema.Properties { - v := ref.Value - if v == nil { - return foundUnresolvedRef(ref.Ref) - } - if err = v.validate(ctx, stack); err != nil { - return - } - } - - if ref := schema.AdditionalProperties; ref != nil { - v := ref.Value - if v == nil { - return foundUnresolvedRef(ref.Ref) - } - if err = v.validate(ctx, stack); err != nil { - return - } - } - - if v := schema.ExternalDocs; v != nil { - if err = v.Validate(ctx); err != nil { - return fmt.Errorf("invalid external docs: %w", err) - } - } - - return -} - -func (schema *Schema) IsMatching(value interface{}) bool { - settings := newSchemaValidationSettings(FailFast()) - return schema.visitJSON(settings, value) == nil -} - -func (schema *Schema) IsMatchingJSONBoolean(value bool) bool { - settings := newSchemaValidationSettings(FailFast()) - return schema.visitJSON(settings, value) == nil -} - -func (schema *Schema) IsMatchingJSONNumber(value float64) bool { - settings := newSchemaValidationSettings(FailFast()) - return schema.visitJSON(settings, value) == nil -} - -func (schema *Schema) IsMatchingJSONString(value string) bool { - settings := newSchemaValidationSettings(FailFast()) - return schema.visitJSON(settings, value) == nil -} - -func (schema *Schema) IsMatchingJSONArray(value []interface{}) bool { - settings := newSchemaValidationSettings(FailFast()) - return schema.visitJSON(settings, value) == nil -} - -func (schema *Schema) IsMatchingJSONObject(value map[string]interface{}) bool { - settings := newSchemaValidationSettings(FailFast()) - return schema.visitJSON(settings, value) == nil -} - -func (schema *Schema) VisitJSON(value interface{}, opts ...SchemaValidationOption) error { - settings := newSchemaValidationSettings(opts...) - return schema.visitJSON(settings, value) -} - -func (schema *Schema) visitJSON(settings *schemaValidationSettings, value interface{}) (err error) { - switch value := value.(type) { - case nil: - return schema.visitJSONNull(settings) - case float64: - if math.IsNaN(value) { - return ErrSchemaInputNaN - } - if math.IsInf(value, 0) { - return ErrSchemaInputInf - } - } - - if schema.IsEmpty() { - return - } - if err = schema.visitSetOperations(settings, value); err != nil { - return - } - - switch value := value.(type) { - case nil: - return schema.visitJSONNull(settings) - case bool: - return schema.visitJSONBoolean(settings, value) - case float64: - return schema.visitJSONNumber(settings, value) - case string: - return schema.visitJSONString(settings, value) - case []interface{}: - return schema.visitJSONArray(settings, value) - case map[string]interface{}: - return schema.visitJSONObject(settings, value) - case map[interface{}]interface{}: // for YAML cf. issue #444 - values := make(map[string]interface{}, len(value)) - for key, v := range value { - if k, ok := key.(string); ok { - values[k] = v - } - } - if len(value) == len(values) { - return schema.visitJSONObject(settings, values) - } - } - return &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "type", - Reason: fmt.Sprintf("unhandled value of type %T", value), - } -} - -func (schema *Schema) visitSetOperations(settings *schemaValidationSettings, value interface{}) (err error) { - if enum := schema.Enum; len(enum) != 0 { - for _, v := range enum { - if value == v { - return - } - } - if settings.failfast { - return errSchema - } - return &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "enum", - Reason: "value is not one of the allowed values", - } - } - - if ref := schema.Not; ref != nil { - v := ref.Value - if v == nil { - return foundUnresolvedRef(ref.Ref) - } - if err := v.visitJSON(settings, value); err == nil { - if settings.failfast { - return errSchema - } - return &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "not", - } - } - } - - if v := schema.OneOf; len(v) > 0 { - var discriminatorRef string - if schema.Discriminator != nil { - pn := schema.Discriminator.PropertyName - if valuemap, okcheck := value.(map[string]interface{}); okcheck { - discriminatorVal, okcheck := valuemap[pn] - if !okcheck { - return errors.New("input does not contain the discriminator property") - } - - if discriminatorRef, okcheck = schema.Discriminator.Mapping[discriminatorVal.(string)]; len(schema.Discriminator.Mapping) > 0 && !okcheck { - return errors.New("input does not contain a valid discriminator value") - } - } - } - - ok := 0 - validationErrors := []error{} - for _, item := range v { - v := item.Value - if v == nil { - return foundUnresolvedRef(item.Ref) - } - - if discriminatorRef != "" && discriminatorRef != item.Ref { - continue - } - - if err := v.visitJSON(settings, value); err != nil { - validationErrors = append(validationErrors, err) - continue - } - - ok++ - } - - if ok != 1 { - if len(validationErrors) > 1 { - errorMessage := "" - for _, err := range validationErrors { - if errorMessage != "" { - errorMessage += " Or " - } - errorMessage += err.Error() - } - return errors.New("doesn't match schema due to: " + errorMessage) - } - if settings.failfast { - return errSchema - } - e := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "oneOf", - } - if ok > 1 { - e.Origin = ErrOneOfConflict - } else if len(validationErrors) == 1 { - e.Origin = validationErrors[0] - } - - return e - } - } - - if v := schema.AnyOf; len(v) > 0 { - ok := false - for _, item := range v { - v := item.Value - if v == nil { - return foundUnresolvedRef(item.Ref) - } - if err := v.visitJSON(settings, value); err == nil { - ok = true - break - } - } - if !ok { - if settings.failfast { - return errSchema - } - return &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "anyOf", - } - } - } - - for _, item := range schema.AllOf { - v := item.Value - if v == nil { - return foundUnresolvedRef(item.Ref) - } - if err := v.visitJSON(settings, value); err != nil { - if settings.failfast { - return errSchema - } - return &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "allOf", - Origin: err, - } - } - } - return -} - -func (schema *Schema) visitJSONNull(settings *schemaValidationSettings) (err error) { - if schema.Nullable { - return - } - if settings.failfast { - return errSchema - } - return &SchemaError{ - Value: nil, - Schema: schema, - SchemaField: "nullable", - Reason: "Value is not nullable", - } -} - -func (schema *Schema) VisitJSONBoolean(value bool) error { - settings := newSchemaValidationSettings() - return schema.visitJSONBoolean(settings, value) -} - -func (schema *Schema) visitJSONBoolean(settings *schemaValidationSettings, value bool) (err error) { - if schemaType := schema.Type; schemaType != "" && schemaType != TypeBoolean { - return schema.expectedType(settings, TypeBoolean) - } - return -} - -func (schema *Schema) VisitJSONNumber(value float64) error { - settings := newSchemaValidationSettings() - return schema.visitJSONNumber(settings, value) -} - -func (schema *Schema) visitJSONNumber(settings *schemaValidationSettings, value float64) error { - var me MultiError - schemaType := schema.Type - if schemaType == "integer" { - if bigFloat := big.NewFloat(value); !bigFloat.IsInt() { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "type", - Reason: "Value must be an integer", - } - if !settings.multiError { - return err - } - me = append(me, err) - } - } else if schemaType != "" && schemaType != TypeNumber { - return schema.expectedType(settings, "number, integer") - } - - // "exclusiveMinimum" - if v := schema.ExclusiveMin; v && !(*schema.Min < value) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "exclusiveMinimum", - Reason: fmt.Sprintf("number must be more than %g", *schema.Min), - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "exclusiveMaximum" - if v := schema.ExclusiveMax; v && !(*schema.Max > value) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "exclusiveMaximum", - Reason: fmt.Sprintf("number must be less than %g", *schema.Max), - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "minimum" - if v := schema.Min; v != nil && !(*v <= value) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "minimum", - Reason: fmt.Sprintf("number must be at least %g", *v), - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "maximum" - if v := schema.Max; v != nil && !(*v >= value) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "maximum", - Reason: fmt.Sprintf("number must be at most %g", *v), - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "multipleOf" - if v := schema.MultipleOf; v != nil { - // "A numeric instance is valid only if division by this keyword's - // value results in an integer." - if bigFloat := big.NewFloat(value / *v); !bigFloat.IsInt() { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "multipleOf", - } - if !settings.multiError { - return err - } - me = append(me, err) - } - } - - if len(me) > 0 { - return me - } - - return nil -} - -func (schema *Schema) VisitJSONString(value string) error { - settings := newSchemaValidationSettings() - return schema.visitJSONString(settings, value) -} - -func (schema *Schema) visitJSONString(settings *schemaValidationSettings, value string) error { - if schemaType := schema.Type; schemaType != "" && schemaType != TypeString { - return schema.expectedType(settings, TypeString) - } - - var me MultiError - - // "minLength" and "maxLength" - minLength := schema.MinLength - maxLength := schema.MaxLength - if minLength != 0 || maxLength != nil { - // JSON schema string lengths are UTF-16, not UTF-8! - length := int64(0) - for _, r := range value { - if utf16.IsSurrogate(r) { - length += 2 - } else { - length++ - } - } - if minLength != 0 && length < int64(minLength) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "minLength", - Reason: fmt.Sprintf("minimum string length is %d", minLength), - } - if !settings.multiError { - return err - } - me = append(me, err) - } - if maxLength != nil && length > int64(*maxLength) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "maxLength", - Reason: fmt.Sprintf("maximum string length is %d", *maxLength), - } - if !settings.multiError { - return err - } - me = append(me, err) - } - } - - // "pattern" - if schema.Pattern != "" && schema.compiledPattern == nil { - var err error - if err = schema.compilePattern(); err != nil { - if !settings.multiError { - return err - } - me = append(me, err) - } - } - if cp := schema.compiledPattern; cp != nil && !cp.MatchString(value) { - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "pattern", - Reason: fmt.Sprintf(`string doesn't match the regular expression "%s"`, schema.Pattern), - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "format" - var formatErr string - if format := schema.Format; format != "" { - if f, ok := SchemaStringFormats[format]; ok { - switch { - case f.regexp != nil && f.callback == nil: - if cp := f.regexp; !cp.MatchString(value) { - formatErr = fmt.Sprintf(`string doesn't match the format %q (regular expression "%s")`, format, cp.String()) - } - case f.regexp == nil && f.callback != nil: - if err := f.callback(value); err != nil { - formatErr = err.Error() - } - default: - formatErr = fmt.Sprintf("corrupted entry %q in SchemaStringFormats", format) - } - } - } - if formatErr != "" { - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "format", - Reason: formatErr, - } - if !settings.multiError { - return err - } - me = append(me, err) - - } - - if len(me) > 0 { - return me - } - - return nil -} - -func (schema *Schema) VisitJSONArray(value []interface{}) error { - settings := newSchemaValidationSettings() - return schema.visitJSONArray(settings, value) -} - -func (schema *Schema) visitJSONArray(settings *schemaValidationSettings, value []interface{}) error { - if schemaType := schema.Type; schemaType != "" && schemaType != TypeArray { - return schema.expectedType(settings, TypeArray) - } - - var me MultiError - - lenValue := int64(len(value)) - - // "minItems" - if v := schema.MinItems; v != 0 && lenValue < int64(v) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "minItems", - Reason: fmt.Sprintf("minimum number of items is %d", v), - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "maxItems" - if v := schema.MaxItems; v != nil && lenValue > int64(*v) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "maxItems", - Reason: fmt.Sprintf("maximum number of items is %d", *v), - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "uniqueItems" - if sliceUniqueItemsChecker == nil { - sliceUniqueItemsChecker = isSliceOfUniqueItems - } - if v := schema.UniqueItems; v && !sliceUniqueItemsChecker(value) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "uniqueItems", - Reason: "duplicate items found", - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "items" - if itemSchemaRef := schema.Items; itemSchemaRef != nil { - itemSchema := itemSchemaRef.Value - if itemSchema == nil { - return foundUnresolvedRef(itemSchemaRef.Ref) - } - for i, item := range value { - if err := itemSchema.visitJSON(settings, item); err != nil { - err = markSchemaErrorIndex(err, i) - if !settings.multiError { - return err - } - if itemMe, ok := err.(MultiError); ok { - me = append(me, itemMe...) - } else { - me = append(me, err) - } - } - } - } - - if len(me) > 0 { - return me - } - - return nil -} - -func (schema *Schema) VisitJSONObject(value map[string]interface{}) error { - settings := newSchemaValidationSettings() - return schema.visitJSONObject(settings, value) -} - -func (schema *Schema) visitJSONObject(settings *schemaValidationSettings, value map[string]interface{}) error { - if schemaType := schema.Type; schemaType != "" && schemaType != TypeObject { - return schema.expectedType(settings, TypeObject) - } - - var me MultiError - - // "properties" - properties := schema.Properties - lenValue := int64(len(value)) - - // "minProperties" - if v := schema.MinProps; v != 0 && lenValue < int64(v) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "minProperties", - Reason: fmt.Sprintf("there must be at least %d properties", v), - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "maxProperties" - if v := schema.MaxProps; v != nil && lenValue > int64(*v) { - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "maxProperties", - Reason: fmt.Sprintf("there must be at most %d properties", *v), - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "additionalProperties" - var additionalProperties *Schema - if ref := schema.AdditionalProperties; ref != nil { - additionalProperties = ref.Value - } - for k, v := range value { - if properties != nil { - propertyRef := properties[k] - if propertyRef != nil { - p := propertyRef.Value - if p == nil { - return foundUnresolvedRef(propertyRef.Ref) - } - if err := p.visitJSON(settings, v); err != nil { - if settings.failfast { - return errSchema - } - err = markSchemaErrorKey(err, k) - if !settings.multiError { - return err - } - if v, ok := err.(MultiError); ok { - me = append(me, v...) - continue - } - me = append(me, err) - } - continue - } - } - allowed := schema.AdditionalPropertiesAllowed - if additionalProperties != nil || allowed == nil || (allowed != nil && *allowed) { - if additionalProperties != nil { - if err := additionalProperties.visitJSON(settings, v); err != nil { - if settings.failfast { - return errSchema - } - err = markSchemaErrorKey(err, k) - if !settings.multiError { - return err - } - if v, ok := err.(MultiError); ok { - me = append(me, v...) - continue - } - me = append(me, err) - } - } - continue - } - if settings.failfast { - return errSchema - } - err := &SchemaError{ - Value: value, - Schema: schema, - SchemaField: "properties", - Reason: fmt.Sprintf("property %q is unsupported", k), - } - if !settings.multiError { - return err - } - me = append(me, err) - } - - // "required" - for _, k := range schema.Required { - if _, ok := value[k]; !ok { - if s := schema.Properties[k]; s != nil && s.Value.ReadOnly && settings.asreq { - continue - } - if s := schema.Properties[k]; s != nil && s.Value.WriteOnly && settings.asrep { - continue - } - if settings.failfast { - return errSchema - } - err := markSchemaErrorKey(&SchemaError{ - Value: value, - Schema: schema, - SchemaField: "required", - Reason: fmt.Sprintf("property %q is missing", k), - }, k) - if !settings.multiError { - return err - } - me = append(me, err) - } - } - - if len(me) > 0 { - return me - } - - return nil -} - -func (schema *Schema) expectedType(settings *schemaValidationSettings, typ string) error { - if settings.failfast { - return errSchema - } - return &SchemaError{ - Value: typ, - Schema: schema, - SchemaField: "type", - Reason: "Field must be set to " + schema.Type + " or not be present", - } -} - -func (schema *Schema) compilePattern() (err error) { - if schema.compiledPattern, err = regexp.Compile(schema.Pattern); err != nil { - return &SchemaError{ - Schema: schema, - SchemaField: "pattern", - Reason: fmt.Sprintf("cannot compile pattern %q: %v", schema.Pattern, err), - } - } - return nil -} - -type SchemaError struct { - Value interface{} - reversePath []string - Schema *Schema - SchemaField string - Reason string - Origin error -} - -var _ interface{ Unwrap() error } = SchemaError{} - -func markSchemaErrorKey(err error, key string) error { - if v, ok := err.(*SchemaError); ok { - v.reversePath = append(v.reversePath, key) - return v - } - if v, ok := err.(MultiError); ok { - for _, e := range v { - _ = markSchemaErrorKey(e, key) - } - return v - } - return err -} - -func markSchemaErrorIndex(err error, index int) error { - if v, ok := err.(*SchemaError); ok { - v.reversePath = append(v.reversePath, strconv.FormatInt(int64(index), 10)) - return v - } - if v, ok := err.(MultiError); ok { - for _, e := range v { - _ = markSchemaErrorIndex(e, index) - } - return v - } - return err -} - -func (err *SchemaError) JSONPointer() []string { - reversePath := err.reversePath - path := append([]string(nil), reversePath...) - for left, right := 0, len(path)-1; left < right; left, right = left+1, right-1 { - path[left], path[right] = path[right], path[left] - } - return path -} - -func (err *SchemaError) Error() string { - if err.Origin != nil { - return err.Origin.Error() - } - - buf := bytes.NewBuffer(make([]byte, 0, 256)) - if len(err.reversePath) > 0 { - buf.WriteString(`Error at "`) - reversePath := err.reversePath - for i := len(reversePath) - 1; i >= 0; i-- { - buf.WriteByte('/') - buf.WriteString(reversePath[i]) - } - buf.WriteString(`": `) - } - reason := err.Reason - if reason == "" { - buf.WriteString(`Doesn't match schema "`) - buf.WriteString(err.SchemaField) - buf.WriteString(`"`) - } else { - buf.WriteString(reason) - } - if !SchemaErrorDetailsDisabled { - buf.WriteString("\nSchema:\n ") - encoder := json.NewEncoder(buf) - encoder.SetIndent(" ", " ") - if err := encoder.Encode(err.Schema); err != nil { - panic(err) - } - buf.WriteString("\nValue:\n ") - if err := encoder.Encode(err.Value); err != nil { - panic(err) - } - } - return buf.String() -} - -func (err SchemaError) Unwrap() error { - return err.Origin -} - -func isSliceOfUniqueItems(xs []interface{}) bool { - s := len(xs) - m := make(map[string]struct{}, s) - for _, x := range xs { - // The input slice is coverted from a JSON string, there shall - // have no error when covert it back. - key, _ := json.Marshal(&x) - m[string(key)] = struct{}{} - } - return s == len(m) -} - -// SliceUniqueItemsChecker is an function used to check if an given slice -// have unique items. -type SliceUniqueItemsChecker func(items []interface{}) bool - -// By default using predefined func isSliceOfUniqueItems which make use of -// json.Marshal to generate a key for map used to check if a given slice -// have unique items. -var sliceUniqueItemsChecker SliceUniqueItemsChecker = isSliceOfUniqueItems - -// RegisterArrayUniqueItemsChecker is used to register a customized function -// used to check if JSON array have unique items. -func RegisterArrayUniqueItemsChecker(fn SliceUniqueItemsChecker) { - sliceUniqueItemsChecker = fn -} - -func unsupportedFormat(format string) error { - return fmt.Errorf("unsupported 'format' value %q", format) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/schema_formats.go b/vendor/github.com/getkin/kin-openapi/openapi3/schema_formats.go deleted file mode 100644 index 29fbd51f..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/schema_formats.go +++ /dev/null @@ -1,105 +0,0 @@ -package openapi3 - -import ( - "fmt" - "net" - "regexp" - "strings" -) - -const ( - // FormatOfStringForUUIDOfRFC4122 is an optional predefined format for UUID v1-v5 as specified by RFC4122 - FormatOfStringForUUIDOfRFC4122 = `^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$` -) - -//FormatCallback custom check on exotic formats -type FormatCallback func(Val string) error - -type Format struct { - regexp *regexp.Regexp - callback FormatCallback -} - -//SchemaStringFormats allows for validating strings format -var SchemaStringFormats = make(map[string]Format, 8) - -//DefineStringFormat Defines a new regexp pattern for a given format -func DefineStringFormat(name string, pattern string) { - re, err := regexp.Compile(pattern) - if err != nil { - err := fmt.Errorf("format %q has invalid pattern %q: %v", name, pattern, err) - panic(err) - } - SchemaStringFormats[name] = Format{regexp: re} -} - -// DefineStringFormatCallback adds a validation function for a specific schema format entry -func DefineStringFormatCallback(name string, callback FormatCallback) { - SchemaStringFormats[name] = Format{callback: callback} -} - -func validateIP(ip string) error { - parsed := net.ParseIP(ip) - if parsed == nil { - return &SchemaError{ - Value: ip, - Reason: "Not an IP address", - } - } - return nil -} - -func validateIPv4(ip string) error { - if err := validateIP(ip); err != nil { - return err - } - - if !(strings.Count(ip, ":") < 2) { - return &SchemaError{ - Value: ip, - Reason: "Not an IPv4 address (it's IPv6)", - } - } - return nil -} - -func validateIPv6(ip string) error { - if err := validateIP(ip); err != nil { - return err - } - - if !(strings.Count(ip, ":") >= 2) { - return &SchemaError{ - Value: ip, - Reason: "Not an IPv6 address (it's IPv4)", - } - } - return nil -} - -func init() { - // This pattern catches only some suspiciously wrong-looking email addresses. - // Use DefineStringFormat(...) if you need something stricter. - DefineStringFormat("email", `^[^@]+@[^@<>",\s]+$`) - - // Base64 - // The pattern supports base64 and b./ase64url. Padding ('=') is supported. - DefineStringFormat("byte", `(^$|^[a-zA-Z0-9+/\-_]*=*$)`) - - // date - DefineStringFormat("date", `^[0-9]{4}-(0[0-9]|10|11|12)-([0-2][0-9]|30|31)$`) - - // date-time - DefineStringFormat("date-time", `^[0-9]{4}-(0[0-9]|10|11|12)-([0-2][0-9]|30|31)T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?(Z|(\+|-)[0-9]{2}:[0-9]{2})?$`) - -} - -// DefineIPv4Format opts in ipv4 format validation on top of OAS 3 spec -func DefineIPv4Format() { - DefineStringFormatCallback("ipv4", validateIPv4) -} - -// DefineIPv6Format opts in ipv6 format validation on top of OAS 3 spec -func DefineIPv6Format() { - DefineStringFormatCallback("ipv6", validateIPv6) -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/schema_validation_settings.go b/vendor/github.com/getkin/kin-openapi/openapi3/schema_validation_settings.go deleted file mode 100644 index 71db5f23..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/schema_validation_settings.go +++ /dev/null @@ -1,34 +0,0 @@ -package openapi3 - -// SchemaValidationOption describes options a user has when validating request / response bodies. -type SchemaValidationOption func(*schemaValidationSettings) - -type schemaValidationSettings struct { - failfast bool - multiError bool - asreq, asrep bool // exclusive (XOR) fields -} - -// FailFast returns schema validation errors quicker. -func FailFast() SchemaValidationOption { - return func(s *schemaValidationSettings) { s.failfast = true } -} - -func MultiErrors() SchemaValidationOption { - return func(s *schemaValidationSettings) { s.multiError = true } -} - -func VisitAsRequest() SchemaValidationOption { - return func(s *schemaValidationSettings) { s.asreq, s.asrep = true, false } -} -func VisitAsResponse() SchemaValidationOption { - return func(s *schemaValidationSettings) { s.asreq, s.asrep = false, true } -} - -func newSchemaValidationSettings(opts ...SchemaValidationOption) *schemaValidationSettings { - settings := &schemaValidationSettings{} - for _, opt := range opts { - opt(settings) - } - return settings -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/security_requirements.go b/vendor/github.com/getkin/kin-openapi/openapi3/security_requirements.go deleted file mode 100644 index df6b6b2d..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/security_requirements.go +++ /dev/null @@ -1,45 +0,0 @@ -package openapi3 - -import ( - "context" -) - -type SecurityRequirements []SecurityRequirement - -func NewSecurityRequirements() *SecurityRequirements { - return &SecurityRequirements{} -} - -func (srs *SecurityRequirements) With(securityRequirement SecurityRequirement) *SecurityRequirements { - *srs = append(*srs, securityRequirement) - return srs -} - -func (value SecurityRequirements) Validate(ctx context.Context) error { - for _, item := range value { - if err := item.Validate(ctx); err != nil { - return err - } - } - return nil -} - -// SecurityRequirement is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#securityRequirementObject -type SecurityRequirement map[string][]string - -func NewSecurityRequirement() SecurityRequirement { - return make(SecurityRequirement) -} - -func (security SecurityRequirement) Authenticate(provider string, scopes ...string) SecurityRequirement { - if len(scopes) == 0 { - scopes = []string{} // Forces the variable to be encoded as an array instead of null - } - security[provider] = scopes - return security -} - -func (value SecurityRequirement) Validate(ctx context.Context) error { - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/security_scheme.go b/vendor/github.com/getkin/kin-openapi/openapi3/security_scheme.go deleted file mode 100644 index 9b89fb95..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/security_scheme.go +++ /dev/null @@ -1,249 +0,0 @@ -package openapi3 - -import ( - "context" - "errors" - "fmt" - - "github.com/getkin/kin-openapi/jsoninfo" - "github.com/go-openapi/jsonpointer" -) - -type SecuritySchemes map[string]*SecuritySchemeRef - -func (s SecuritySchemes) JSONLookup(token string) (interface{}, error) { - ref, ok := s[token] - if ref == nil || ok == false { - return nil, fmt.Errorf("object has no field %q", token) - } - - if ref.Ref != "" { - return &Ref{Ref: ref.Ref}, nil - } - return ref.Value, nil -} - -var _ jsonpointer.JSONPointable = (*SecuritySchemes)(nil) - -// SecurityScheme is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#securitySchemeObject -type SecurityScheme struct { - ExtensionProps - - Type string `json:"type,omitempty" yaml:"type,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Name string `json:"name,omitempty" yaml:"name,omitempty"` - In string `json:"in,omitempty" yaml:"in,omitempty"` - Scheme string `json:"scheme,omitempty" yaml:"scheme,omitempty"` - BearerFormat string `json:"bearerFormat,omitempty" yaml:"bearerFormat,omitempty"` - Flows *OAuthFlows `json:"flows,omitempty" yaml:"flows,omitempty"` - OpenIdConnectUrl string `json:"openIdConnectUrl,omitempty" yaml:"openIdConnectUrl,omitempty"` -} - -func NewSecurityScheme() *SecurityScheme { - return &SecurityScheme{} -} - -func NewCSRFSecurityScheme() *SecurityScheme { - return &SecurityScheme{ - Type: "apiKey", - In: "header", - Name: "X-XSRF-TOKEN", - } -} - -func NewOIDCSecurityScheme(oidcUrl string) *SecurityScheme { - return &SecurityScheme{ - Type: "openIdConnect", - OpenIdConnectUrl: oidcUrl, - } -} - -func NewJWTSecurityScheme() *SecurityScheme { - return &SecurityScheme{ - Type: "http", - Scheme: "bearer", - BearerFormat: "JWT", - } -} - -func (ss *SecurityScheme) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(ss) -} - -func (ss *SecurityScheme) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, ss) -} - -func (ss *SecurityScheme) WithType(value string) *SecurityScheme { - ss.Type = value - return ss -} - -func (ss *SecurityScheme) WithDescription(value string) *SecurityScheme { - ss.Description = value - return ss -} - -func (ss *SecurityScheme) WithName(value string) *SecurityScheme { - ss.Name = value - return ss -} - -func (ss *SecurityScheme) WithIn(value string) *SecurityScheme { - ss.In = value - return ss -} - -func (ss *SecurityScheme) WithScheme(value string) *SecurityScheme { - ss.Scheme = value - return ss -} - -func (ss *SecurityScheme) WithBearerFormat(value string) *SecurityScheme { - ss.BearerFormat = value - return ss -} - -func (value *SecurityScheme) Validate(ctx context.Context) error { - hasIn := false - hasBearerFormat := false - hasFlow := false - switch value.Type { - case "apiKey": - hasIn = true - case "http": - scheme := value.Scheme - switch scheme { - case "bearer": - hasBearerFormat = true - case "basic", "negotiate", "digest": - default: - return fmt.Errorf("security scheme of type 'http' has invalid 'scheme' value %q", scheme) - } - case "oauth2": - hasFlow = true - case "openIdConnect": - if value.OpenIdConnectUrl == "" { - return fmt.Errorf("no OIDC URL found for openIdConnect security scheme %q", value.Name) - } - default: - return fmt.Errorf("security scheme 'type' can't be %q", value.Type) - } - - // Validate "in" and "name" - if hasIn { - switch value.In { - case "query", "header", "cookie": - default: - return fmt.Errorf("security scheme of type 'apiKey' should have 'in'. It can be 'query', 'header' or 'cookie', not %q", value.In) - } - if value.Name == "" { - return errors.New("security scheme of type 'apiKey' should have 'name'") - } - } else if len(value.In) > 0 { - return fmt.Errorf("security scheme of type %q can't have 'in'", value.Type) - } else if len(value.Name) > 0 { - return errors.New("security scheme of type 'apiKey' can't have 'name'") - } - - // Validate "format" - // "bearerFormat" is an arbitrary string so we only check if the scheme supports it - if !hasBearerFormat && len(value.BearerFormat) > 0 { - return fmt.Errorf("security scheme of type %q can't have 'bearerFormat'", value.Type) - } - - // Validate "flow" - if hasFlow { - flow := value.Flows - if flow == nil { - return fmt.Errorf("security scheme of type %q should have 'flows'", value.Type) - } - if err := flow.Validate(ctx); err != nil { - return fmt.Errorf("security scheme 'flow' is invalid: %v", err) - } - } else if value.Flows != nil { - return fmt.Errorf("security scheme of type %q can't have 'flows'", value.Type) - } - return nil -} - -// OAuthFlows is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#oauthFlowsObject -type OAuthFlows struct { - ExtensionProps - - Implicit *OAuthFlow `json:"implicit,omitempty" yaml:"implicit,omitempty"` - Password *OAuthFlow `json:"password,omitempty" yaml:"password,omitempty"` - ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty" yaml:"clientCredentials,omitempty"` - AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty" yaml:"authorizationCode,omitempty"` -} - -type oAuthFlowType int - -const ( - oAuthFlowTypeImplicit oAuthFlowType = iota - oAuthFlowTypePassword - oAuthFlowTypeClientCredentials - oAuthFlowAuthorizationCode -) - -func (flows *OAuthFlows) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(flows) -} - -func (flows *OAuthFlows) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, flows) -} - -func (flows *OAuthFlows) Validate(ctx context.Context) error { - if v := flows.Implicit; v != nil { - return v.Validate(ctx, oAuthFlowTypeImplicit) - } - if v := flows.Password; v != nil { - return v.Validate(ctx, oAuthFlowTypePassword) - } - if v := flows.ClientCredentials; v != nil { - return v.Validate(ctx, oAuthFlowTypeClientCredentials) - } - if v := flows.AuthorizationCode; v != nil { - return v.Validate(ctx, oAuthFlowAuthorizationCode) - } - return errors.New("no OAuth flow is defined") -} - -// OAuthFlow is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#oauthFlowObject -type OAuthFlow struct { - ExtensionProps - - AuthorizationURL string `json:"authorizationUrl,omitempty" yaml:"authorizationUrl,omitempty"` - TokenURL string `json:"tokenUrl,omitempty" yaml:"tokenUrl,omitempty"` - RefreshURL string `json:"refreshUrl,omitempty" yaml:"refreshUrl,omitempty"` - Scopes map[string]string `json:"scopes" yaml:"scopes"` -} - -func (flow *OAuthFlow) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(flow) -} - -func (flow *OAuthFlow) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, flow) -} - -func (flow *OAuthFlow) Validate(ctx context.Context, typ oAuthFlowType) error { - if typ == oAuthFlowAuthorizationCode || typ == oAuthFlowTypeImplicit { - if v := flow.AuthorizationURL; v == "" { - return errors.New("an OAuth flow is missing 'authorizationUrl in authorizationCode or implicit '") - } - } - if typ != oAuthFlowTypeImplicit { - if v := flow.TokenURL; v == "" { - return errors.New("an OAuth flow is missing 'tokenUrl in not implicit'") - } - } - if v := flow.Scopes; v == nil { - return errors.New("an OAuth flow is missing 'scopes'") - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/serialization_method.go b/vendor/github.com/getkin/kin-openapi/openapi3/serialization_method.go deleted file mode 100644 index 2ec8bd2d..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/serialization_method.go +++ /dev/null @@ -1,17 +0,0 @@ -package openapi3 - -const ( - SerializationSimple = "simple" - SerializationLabel = "label" - SerializationMatrix = "matrix" - SerializationForm = "form" - SerializationSpaceDelimited = "spaceDelimited" - SerializationPipeDelimited = "pipeDelimited" - SerializationDeepObject = "deepObject" -) - -// SerializationMethod describes a serialization method of HTTP request's parameters and body. -type SerializationMethod struct { - Style string - Explode bool -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/server.go b/vendor/github.com/getkin/kin-openapi/openapi3/server.go deleted file mode 100644 index 94092a6e..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/server.go +++ /dev/null @@ -1,179 +0,0 @@ -package openapi3 - -import ( - "context" - "errors" - "fmt" - "math" - "net/url" - "strings" - - "github.com/getkin/kin-openapi/jsoninfo" -) - -// Servers is specified by OpenAPI/Swagger standard version 3. -type Servers []*Server - -// Validate ensures servers are per the OpenAPIv3 specification. -func (value Servers) Validate(ctx context.Context) error { - for _, v := range value { - if err := v.Validate(ctx); err != nil { - return err - } - } - return nil -} - -func (servers Servers) MatchURL(parsedURL *url.URL) (*Server, []string, string) { - rawURL := parsedURL.String() - if i := strings.IndexByte(rawURL, '?'); i >= 0 { - rawURL = rawURL[:i] - } - for _, server := range servers { - pathParams, remaining, ok := server.MatchRawURL(rawURL) - if ok { - return server, pathParams, remaining - } - } - return nil, nil, "" -} - -// Server is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#serverObject -type Server struct { - ExtensionProps - - URL string `json:"url" yaml:"url"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - Variables map[string]*ServerVariable `json:"variables,omitempty" yaml:"variables,omitempty"` -} - -func (server *Server) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(server) -} - -func (server *Server) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, server) -} - -func (server Server) ParameterNames() ([]string, error) { - pattern := server.URL - var params []string - for len(pattern) > 0 { - i := strings.IndexByte(pattern, '{') - if i < 0 { - break - } - pattern = pattern[i+1:] - i = strings.IndexByte(pattern, '}') - if i < 0 { - return nil, errors.New("missing '}'") - } - params = append(params, strings.TrimSpace(pattern[:i])) - pattern = pattern[i+1:] - } - return params, nil -} - -func (server Server) MatchRawURL(input string) ([]string, string, bool) { - pattern := server.URL - var params []string - for len(pattern) > 0 { - c := pattern[0] - if len(pattern) == 1 && c == '/' { - break - } - if c == '{' { - // Find end of pattern - i := strings.IndexByte(pattern, '}') - if i < 0 { - return nil, "", false - } - pattern = pattern[i+1:] - - // Find next matching pattern character or next '/' whichever comes first - np := -1 - if len(pattern) > 0 { - np = strings.IndexByte(input, pattern[0]) - } - ns := strings.IndexByte(input, '/') - - if np < 0 { - i = ns - } else if ns < 0 { - i = np - } else { - i = int(math.Min(float64(np), float64(ns))) - } - if i < 0 { - i = len(input) - } - params = append(params, input[:i]) - input = input[i:] - continue - } - if len(input) == 0 || input[0] != c { - return nil, "", false - } - pattern = pattern[1:] - input = input[1:] - } - if input == "" { - input = "/" - } - if input[0] != '/' { - return nil, "", false - } - return params, input, true -} - -func (value *Server) Validate(ctx context.Context) (err error) { - if value.URL == "" { - return errors.New("value of url must be a non-empty string") - } - opening, closing := strings.Count(value.URL, "{"), strings.Count(value.URL, "}") - if opening != closing { - return errors.New("server URL has mismatched { and }") - } - if opening != len(value.Variables) { - return errors.New("server has undeclared variables") - } - for name, v := range value.Variables { - if !strings.Contains(value.URL, fmt.Sprintf("{%s}", name)) { - return errors.New("server has undeclared variables") - } - if err = v.Validate(ctx); err != nil { - return - } - } - return -} - -// ServerVariable is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#server-variable-object -type ServerVariable struct { - ExtensionProps - - Enum []string `json:"enum,omitempty" yaml:"enum,omitempty"` - Default string `json:"default,omitempty" yaml:"default,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` -} - -func (serverVariable *ServerVariable) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(serverVariable) -} - -func (serverVariable *ServerVariable) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, serverVariable) -} - -func (value *ServerVariable) Validate(ctx context.Context) error { - if value.Default == "" { - data, err := value.MarshalJSON() - if err != nil { - return err - } - return fmt.Errorf("field default is required in %s", data) - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/tag.go b/vendor/github.com/getkin/kin-openapi/openapi3/tag.go deleted file mode 100644 index 6aa9a1ea..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/tag.go +++ /dev/null @@ -1,56 +0,0 @@ -package openapi3 - -import ( - "context" - "fmt" - - "github.com/getkin/kin-openapi/jsoninfo" -) - -// Tags is specified by OpenAPI/Swagger 3.0 standard. -type Tags []*Tag - -func (tags Tags) Get(name string) *Tag { - for _, tag := range tags { - if tag.Name == name { - return tag - } - } - return nil -} - -func (tags Tags) Validate(ctx context.Context) error { - for _, v := range tags { - if err := v.Validate(ctx); err != nil { - return err - } - } - return nil -} - -// Tag is specified by OpenAPI/Swagger 3.0 standard. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#tagObject -type Tag struct { - ExtensionProps - - Name string `json:"name,omitempty" yaml:"name,omitempty"` - Description string `json:"description,omitempty" yaml:"description,omitempty"` - ExternalDocs *ExternalDocs `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"` -} - -func (t *Tag) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(t) -} - -func (t *Tag) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, t) -} - -func (t *Tag) Validate(ctx context.Context) error { - if v := t.ExternalDocs; v != nil { - if err := v.Validate(ctx); err != nil { - return fmt.Errorf("invalid external docs: %w", err) - } - } - return nil -} diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/components/Bar.yml b/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/components/Bar.yml deleted file mode 100644 index cc59fc27..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/components/Bar.yml +++ /dev/null @@ -1,2 +0,0 @@ -type: string -example: bar diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/components/Foo.yml b/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/components/Foo.yml deleted file mode 100644 index 53a23366..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/components/Foo.yml +++ /dev/null @@ -1,4 +0,0 @@ -type: object -properties: - bar: - $ref: ../openapi.yml#/components/schemas/Bar diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/components/Foo/Foo2.yml b/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/components/Foo/Foo2.yml deleted file mode 100644 index aeac81f4..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/components/Foo/Foo2.yml +++ /dev/null @@ -1,4 +0,0 @@ -type: object -properties: - foo: - $ref: ../../openapi.yml#/components/schemas/Foo diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/openapi.yml b/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/openapi.yml deleted file mode 100644 index 3559c8e8..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/openapi.yml +++ /dev/null @@ -1,15 +0,0 @@ -openapi: "3.0.3" -info: - title: Recursive refs example - version: "1.0" -paths: - /foo: - $ref: ./paths/foo.yml -components: - schemas: - Foo: - $ref: ./components/Foo.yml - Foo2: - $ref: ./components/Foo/Foo2.yml - Bar: - $ref: ./components/Bar.yml diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/paths/foo.yml b/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/paths/foo.yml deleted file mode 100644 index 1653c7ac..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/testdata/recursiveRef/paths/foo.yml +++ /dev/null @@ -1,11 +0,0 @@ -get: - responses: - "200": - description: OK - content: - application/json: - schema: - type: object - properties: - foo2: - $ref: ../openapi.yml#/components/schemas/Foo2 diff --git a/vendor/github.com/getkin/kin-openapi/openapi3/xml.go b/vendor/github.com/getkin/kin-openapi/openapi3/xml.go deleted file mode 100644 index 8fd2abde..00000000 --- a/vendor/github.com/getkin/kin-openapi/openapi3/xml.go +++ /dev/null @@ -1,31 +0,0 @@ -package openapi3 - -import ( - "context" - - "github.com/getkin/kin-openapi/jsoninfo" -) - -// XML is specified by OpenAPI/Swagger standard version 3. -// See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#xmlObject -type XML struct { - ExtensionProps - - Name string `json:"name,omitempty" yaml:"name,omitempty"` - Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"` - Prefix string `json:"prefix,omitempty" yaml:"prefix,omitempty"` - Attribute bool `json:"attribute,omitempty" yaml:"attribute,omitempty"` - Wrapped bool `json:"wrapped,omitempty" yaml:"wrapped,omitempty"` -} - -func (value *XML) MarshalJSON() ([]byte, error) { - return jsoninfo.MarshalStrictStruct(value) -} - -func (value *XML) UnmarshalJSON(data []byte) error { - return jsoninfo.UnmarshalStrictStruct(data, value) -} - -func (value *XML) Validate(ctx context.Context) error { - return nil // TODO -} diff --git a/vendor/github.com/ghodss/yaml/.gitignore b/vendor/github.com/ghodss/yaml/.gitignore deleted file mode 100644 index e256a31e..00000000 --- a/vendor/github.com/ghodss/yaml/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -# OSX leaves these everywhere on SMB shares -._* - -# Eclipse files -.classpath -.project -.settings/** - -# Emacs save files -*~ - -# Vim-related files -[._]*.s[a-w][a-z] -[._]s[a-w][a-z] -*.un~ -Session.vim -.netrwhist - -# Go test binaries -*.test diff --git a/vendor/github.com/ghodss/yaml/.travis.yml b/vendor/github.com/ghodss/yaml/.travis.yml deleted file mode 100644 index 0e9d6edc..00000000 --- a/vendor/github.com/ghodss/yaml/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: go -go: - - 1.3 - - 1.4 -script: - - go test - - go build diff --git a/vendor/github.com/ghodss/yaml/LICENSE b/vendor/github.com/ghodss/yaml/LICENSE deleted file mode 100644 index 7805d36d..00000000 --- a/vendor/github.com/ghodss/yaml/LICENSE +++ /dev/null @@ -1,50 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Sam Ghods - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/ghodss/yaml/README.md b/vendor/github.com/ghodss/yaml/README.md deleted file mode 100644 index 0200f75b..00000000 --- a/vendor/github.com/ghodss/yaml/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# YAML marshaling and unmarshaling support for Go - -[![Build Status](https://travis-ci.org/ghodss/yaml.svg)](https://travis-ci.org/ghodss/yaml) - -## Introduction - -A wrapper around [go-yaml](https://github.com/go-yaml/yaml) designed to enable a better way of handling YAML when marshaling to and from structs. - -In short, this library first converts YAML to JSON using go-yaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike go-yaml. For a detailed overview of the rationale behind this method, [see this blog post](http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/). - -## Compatibility - -This package uses [go-yaml](https://github.com/go-yaml/yaml) and therefore supports [everything go-yaml supports](https://github.com/go-yaml/yaml#compatibility). - -## Caveats - -**Caveat #1:** When using `yaml.Marshal` and `yaml.Unmarshal`, binary data should NOT be preceded with the `!!binary` YAML tag. If you do, go-yaml will convert the binary data from base64 to native binary data, which is not compatible with JSON. You can still use binary in your YAML files though - just store them without the `!!binary` tag and decode the base64 in your code (e.g. in the custom JSON methods `MarshalJSON` and `UnmarshalJSON`). This also has the benefit that your YAML and your JSON binary data will be decoded exactly the same way. As an example: - -``` -BAD: - exampleKey: !!binary gIGC - -GOOD: - exampleKey: gIGC -... and decode the base64 data in your code. -``` - -**Caveat #2:** When using `YAMLToJSON` directly, maps with keys that are maps will result in an error since this is not supported by JSON. This error will occur in `Unmarshal` as well since you can't unmarshal map keys anyways since struct fields can't be keys. - -## Installation and usage - -To install, run: - -``` -$ go get github.com/ghodss/yaml -``` - -And import using: - -``` -import "github.com/ghodss/yaml" -``` - -Usage is very similar to the JSON library: - -```go -package main - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -type Person struct { - Name string `json:"name"` // Affects YAML field names too. - Age int `json:"age"` -} - -func main() { - // Marshal a Person struct to YAML. - p := Person{"John", 30} - y, err := yaml.Marshal(p) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - age: 30 - name: John - */ - - // Unmarshal the YAML back into a Person struct. - var p2 Person - err = yaml.Unmarshal(y, &p2) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(p2) - /* Output: - {John 30} - */ -} -``` - -`yaml.YAMLToJSON` and `yaml.JSONToYAML` methods are also available: - -```go -package main - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -func main() { - j := []byte(`{"name": "John", "age": 30}`) - y, err := yaml.JSONToYAML(j) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - name: John - age: 30 - */ - j2, err := yaml.YAMLToJSON(y) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(j2)) - /* Output: - {"age":30,"name":"John"} - */ -} -``` diff --git a/vendor/github.com/ghodss/yaml/fields.go b/vendor/github.com/ghodss/yaml/fields.go deleted file mode 100644 index 58600740..00000000 --- a/vendor/github.com/ghodss/yaml/fields.go +++ /dev/null @@ -1,501 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -package yaml - -import ( - "bytes" - "encoding" - "encoding/json" - "reflect" - "sort" - "strings" - "sync" - "unicode" - "unicode/utf8" -) - -// indirect walks down v allocating pointers as needed, -// until it gets to a non-pointer. -// if it encounters an Unmarshaler, indirect stops and returns that. -// if decodingNull is true, indirect stops at the last pointer so it can be set to nil. -func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { - // If v is a named type and is addressable, - // start with its address, so that if the type has pointer methods, - // we find them. - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { - v = v.Addr() - } - for { - // Load value from interface, but only if the result will be - // usefully addressable. - if v.Kind() == reflect.Interface && !v.IsNil() { - e := v.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { - v = e - continue - } - } - - if v.Kind() != reflect.Ptr { - break - } - - if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { - break - } - if v.IsNil() { - if v.CanSet() { - v.Set(reflect.New(v.Type().Elem())) - } else { - v = reflect.New(v.Type().Elem()) - } - } - if v.Type().NumMethod() > 0 { - if u, ok := v.Interface().(json.Unmarshaler); ok { - return u, nil, reflect.Value{} - } - if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { - return nil, u, reflect.Value{} - } - } - v = v.Elem() - } - return nil, nil, v -} - -// A field represents a single field found in a struct. -type field struct { - name string - nameBytes []byte // []byte(name) - equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent - - tag bool - index []int - typ reflect.Type - omitEmpty bool - quoted bool -} - -func fillField(f field) field { - f.nameBytes = []byte(f.name) - f.equalFold = foldFunc(f.nameBytes) - return f -} - -// byName sorts field by name, breaking ties with depth, -// then breaking ties with "name came from json tag", then -// breaking ties with index sequence. -type byName []field - -func (x byName) Len() int { return len(x) } - -func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byName) Less(i, j int) bool { - if x[i].name != x[j].name { - return x[i].name < x[j].name - } - if len(x[i].index) != len(x[j].index) { - return len(x[i].index) < len(x[j].index) - } - if x[i].tag != x[j].tag { - return x[i].tag - } - return byIndex(x).Less(i, j) -} - -// byIndex sorts field by index sequence. -type byIndex []field - -func (x byIndex) Len() int { return len(x) } - -func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byIndex) Less(i, j int) bool { - for k, xik := range x[i].index { - if k >= len(x[j].index) { - return false - } - if xik != x[j].index[k] { - return xik < x[j].index[k] - } - } - return len(x[i].index) < len(x[j].index) -} - -// typeFields returns a list of fields that JSON should recognize for the given type. -// The algorithm is breadth-first search over the set of structs to include - the top struct -// and then any reachable anonymous structs. -func typeFields(t reflect.Type) []field { - // Anonymous fields to explore at the current level and the next. - current := []field{} - next := []field{{typ: t}} - - // Count of queued names for current level and the next. - count := map[reflect.Type]int{} - nextCount := map[reflect.Type]int{} - - // Types already visited at an earlier level. - visited := map[reflect.Type]bool{} - - // Fields found. - var fields []field - - for len(next) > 0 { - current, next = next, current[:0] - count, nextCount = nextCount, map[reflect.Type]int{} - - for _, f := range current { - if visited[f.typ] { - continue - } - visited[f.typ] = true - - // Scan f.typ for fields to include. - for i := 0; i < f.typ.NumField(); i++ { - sf := f.typ.Field(i) - if sf.PkgPath != "" { // unexported - continue - } - tag := sf.Tag.Get("json") - if tag == "-" { - continue - } - name, opts := parseTag(tag) - if !isValidTag(name) { - name = "" - } - index := make([]int, len(f.index)+1) - copy(index, f.index) - index[len(f.index)] = i - - ft := sf.Type - if ft.Name() == "" && ft.Kind() == reflect.Ptr { - // Follow pointer. - ft = ft.Elem() - } - - // Record found field and index sequence. - if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { - tagged := name != "" - if name == "" { - name = sf.Name - } - fields = append(fields, fillField(field{ - name: name, - tag: tagged, - index: index, - typ: ft, - omitEmpty: opts.Contains("omitempty"), - quoted: opts.Contains("string"), - })) - if count[f.typ] > 1 { - // If there were multiple instances, add a second, - // so that the annihilation code will see a duplicate. - // It only cares about the distinction between 1 or 2, - // so don't bother generating any more copies. - fields = append(fields, fields[len(fields)-1]) - } - continue - } - - // Record new anonymous struct to explore in next round. - nextCount[ft]++ - if nextCount[ft] == 1 { - next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft})) - } - } - } - } - - sort.Sort(byName(fields)) - - // Delete all fields that are hidden by the Go rules for embedded fields, - // except that fields with JSON tags are promoted. - - // The fields are sorted in primary order of name, secondary order - // of field index length. Loop over names; for each name, delete - // hidden fields by choosing the one dominant field that survives. - out := fields[:0] - for advance, i := 0, 0; i < len(fields); i += advance { - // One iteration per name. - // Find the sequence of fields with the name of this first field. - fi := fields[i] - name := fi.name - for advance = 1; i+advance < len(fields); advance++ { - fj := fields[i+advance] - if fj.name != name { - break - } - } - if advance == 1 { // Only one field with this name - out = append(out, fi) - continue - } - dominant, ok := dominantField(fields[i : i+advance]) - if ok { - out = append(out, dominant) - } - } - - fields = out - sort.Sort(byIndex(fields)) - - return fields -} - -// dominantField looks through the fields, all of which are known to -// have the same name, to find the single field that dominates the -// others using Go's embedding rules, modified by the presence of -// JSON tags. If there are multiple top-level fields, the boolean -// will be false: This condition is an error in Go and we skip all -// the fields. -func dominantField(fields []field) (field, bool) { - // The fields are sorted in increasing index-length order. The winner - // must therefore be one with the shortest index length. Drop all - // longer entries, which is easy: just truncate the slice. - length := len(fields[0].index) - tagged := -1 // Index of first tagged field. - for i, f := range fields { - if len(f.index) > length { - fields = fields[:i] - break - } - if f.tag { - if tagged >= 0 { - // Multiple tagged fields at the same level: conflict. - // Return no field. - return field{}, false - } - tagged = i - } - } - if tagged >= 0 { - return fields[tagged], true - } - // All remaining fields have the same length. If there's more than one, - // we have a conflict (two fields named "X" at the same level) and we - // return no field. - if len(fields) > 1 { - return field{}, false - } - return fields[0], true -} - -var fieldCache struct { - sync.RWMutex - m map[reflect.Type][]field -} - -// cachedTypeFields is like typeFields but uses a cache to avoid repeated work. -func cachedTypeFields(t reflect.Type) []field { - fieldCache.RLock() - f := fieldCache.m[t] - fieldCache.RUnlock() - if f != nil { - return f - } - - // Compute fields without lock. - // Might duplicate effort but won't hold other computations back. - f = typeFields(t) - if f == nil { - f = []field{} - } - - fieldCache.Lock() - if fieldCache.m == nil { - fieldCache.m = map[reflect.Type][]field{} - } - fieldCache.m[t] = f - fieldCache.Unlock() - return f -} - -func isValidTag(s string) bool { - if s == "" { - return false - } - for _, c := range s { - switch { - case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): - // Backslash and quote chars are reserved, but - // otherwise any punctuation chars are allowed - // in a tag name. - default: - if !unicode.IsLetter(c) && !unicode.IsDigit(c) { - return false - } - } - } - return true -} - -const ( - caseMask = ^byte(0x20) // Mask to ignore case in ASCII. - kelvin = '\u212a' - smallLongEss = '\u017f' -) - -// foldFunc returns one of four different case folding equivalence -// functions, from most general (and slow) to fastest: -// -// 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8 -// 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S') -// 3) asciiEqualFold, no special, but includes non-letters (including _) -// 4) simpleLetterEqualFold, no specials, no non-letters. -// -// The letters S and K are special because they map to 3 runes, not just 2: -// * S maps to s and to U+017F 'ſ' Latin small letter long s -// * k maps to K and to U+212A 'K' Kelvin sign -// See http://play.golang.org/p/tTxjOc0OGo -// -// The returned function is specialized for matching against s and -// should only be given s. It's not curried for performance reasons. -func foldFunc(s []byte) func(s, t []byte) bool { - nonLetter := false - special := false // special letter - for _, b := range s { - if b >= utf8.RuneSelf { - return bytes.EqualFold - } - upper := b & caseMask - if upper < 'A' || upper > 'Z' { - nonLetter = true - } else if upper == 'K' || upper == 'S' { - // See above for why these letters are special. - special = true - } - } - if special { - return equalFoldRight - } - if nonLetter { - return asciiEqualFold - } - return simpleLetterEqualFold -} - -// equalFoldRight is a specialization of bytes.EqualFold when s is -// known to be all ASCII (including punctuation), but contains an 's', -// 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t. -// See comments on foldFunc. -func equalFoldRight(s, t []byte) bool { - for _, sb := range s { - if len(t) == 0 { - return false - } - tb := t[0] - if tb < utf8.RuneSelf { - if sb != tb { - sbUpper := sb & caseMask - if 'A' <= sbUpper && sbUpper <= 'Z' { - if sbUpper != tb&caseMask { - return false - } - } else { - return false - } - } - t = t[1:] - continue - } - // sb is ASCII and t is not. t must be either kelvin - // sign or long s; sb must be s, S, k, or K. - tr, size := utf8.DecodeRune(t) - switch sb { - case 's', 'S': - if tr != smallLongEss { - return false - } - case 'k', 'K': - if tr != kelvin { - return false - } - default: - return false - } - t = t[size:] - - } - if len(t) > 0 { - return false - } - return true -} - -// asciiEqualFold is a specialization of bytes.EqualFold for use when -// s is all ASCII (but may contain non-letters) and contains no -// special-folding letters. -// See comments on foldFunc. -func asciiEqualFold(s, t []byte) bool { - if len(s) != len(t) { - return false - } - for i, sb := range s { - tb := t[i] - if sb == tb { - continue - } - if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') { - if sb&caseMask != tb&caseMask { - return false - } - } else { - return false - } - } - return true -} - -// simpleLetterEqualFold is a specialization of bytes.EqualFold for -// use when s is all ASCII letters (no underscores, etc) and also -// doesn't contain 'k', 'K', 's', or 'S'. -// See comments on foldFunc. -func simpleLetterEqualFold(s, t []byte) bool { - if len(s) != len(t) { - return false - } - for i, b := range s { - if b&caseMask != t[i]&caseMask { - return false - } - } - return true -} - -// tagOptions is the string following a comma in a struct field's "json" -// tag, or the empty string. It does not include the leading comma. -type tagOptions string - -// parseTag splits a struct field's json tag into its name and -// comma-separated options. -func parseTag(tag string) (string, tagOptions) { - if idx := strings.Index(tag, ","); idx != -1 { - return tag[:idx], tagOptions(tag[idx+1:]) - } - return tag, tagOptions("") -} - -// Contains reports whether a comma-separated list of options -// contains a particular substr flag. substr must be surrounded by a -// string boundary or commas. -func (o tagOptions) Contains(optionName string) bool { - if len(o) == 0 { - return false - } - s := string(o) - for s != "" { - var next string - i := strings.Index(s, ",") - if i >= 0 { - s, next = s[:i], s[i+1:] - } - if s == optionName { - return true - } - s = next - } - return false -} diff --git a/vendor/github.com/ghodss/yaml/yaml.go b/vendor/github.com/ghodss/yaml/yaml.go deleted file mode 100644 index 4fb4054a..00000000 --- a/vendor/github.com/ghodss/yaml/yaml.go +++ /dev/null @@ -1,277 +0,0 @@ -package yaml - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "strconv" - - "gopkg.in/yaml.v2" -) - -// Marshals the object into JSON then converts JSON to YAML and returns the -// YAML. -func Marshal(o interface{}) ([]byte, error) { - j, err := json.Marshal(o) - if err != nil { - return nil, fmt.Errorf("error marshaling into JSON: %v", err) - } - - y, err := JSONToYAML(j) - if err != nil { - return nil, fmt.Errorf("error converting JSON to YAML: %v", err) - } - - return y, nil -} - -// Converts YAML to JSON then uses JSON to unmarshal into an object. -func Unmarshal(y []byte, o interface{}) error { - vo := reflect.ValueOf(o) - j, err := yamlToJSON(y, &vo) - if err != nil { - return fmt.Errorf("error converting YAML to JSON: %v", err) - } - - err = json.Unmarshal(j, o) - if err != nil { - return fmt.Errorf("error unmarshaling JSON: %v", err) - } - - return nil -} - -// Convert JSON to YAML. -func JSONToYAML(j []byte) ([]byte, error) { - // Convert the JSON to an object. - var jsonObj interface{} - // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the - // Go JSON library doesn't try to pick the right number type (int, float, - // etc.) when unmarshalling to interface{}, it just picks float64 - // universally. go-yaml does go through the effort of picking the right - // number type, so we can preserve number type throughout this process. - err := yaml.Unmarshal(j, &jsonObj) - if err != nil { - return nil, err - } - - // Marshal this object into YAML. - return yaml.Marshal(jsonObj) -} - -// Convert YAML to JSON. Since JSON is a subset of YAML, passing JSON through -// this method should be a no-op. -// -// Things YAML can do that are not supported by JSON: -// * In YAML you can have binary and null keys in your maps. These are invalid -// in JSON. (int and float keys are converted to strings.) -// * Binary data in YAML with the !!binary tag is not supported. If you want to -// use binary data with this library, encode the data as base64 as usual but do -// not use the !!binary tag in your YAML. This will ensure the original base64 -// encoded data makes it all the way through to the JSON. -func YAMLToJSON(y []byte) ([]byte, error) { - return yamlToJSON(y, nil) -} - -func yamlToJSON(y []byte, jsonTarget *reflect.Value) ([]byte, error) { - // Convert the YAML to an object. - var yamlObj interface{} - err := yaml.Unmarshal(y, &yamlObj) - if err != nil { - return nil, err - } - - // YAML objects are not completely compatible with JSON objects (e.g. you - // can have non-string keys in YAML). So, convert the YAML-compatible object - // to a JSON-compatible object, failing with an error if irrecoverable - // incompatibilties happen along the way. - jsonObj, err := convertToJSONableObject(yamlObj, jsonTarget) - if err != nil { - return nil, err - } - - // Convert this object to JSON and return the data. - return json.Marshal(jsonObj) -} - -func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (interface{}, error) { - var err error - - // Resolve jsonTarget to a concrete value (i.e. not a pointer or an - // interface). We pass decodingNull as false because we're not actually - // decoding into the value, we're just checking if the ultimate target is a - // string. - if jsonTarget != nil { - ju, tu, pv := indirect(*jsonTarget, false) - // We have a JSON or Text Umarshaler at this level, so we can't be trying - // to decode into a string. - if ju != nil || tu != nil { - jsonTarget = nil - } else { - jsonTarget = &pv - } - } - - // If yamlObj is a number or a boolean, check if jsonTarget is a string - - // if so, coerce. Else return normal. - // If yamlObj is a map or array, find the field that each key is - // unmarshaling to, and when you recurse pass the reflect.Value for that - // field back into this function. - switch typedYAMLObj := yamlObj.(type) { - case map[interface{}]interface{}: - // JSON does not support arbitrary keys in a map, so we must convert - // these keys to strings. - // - // From my reading of go-yaml v2 (specifically the resolve function), - // keys can only have the types string, int, int64, float64, binary - // (unsupported), or null (unsupported). - strMap := make(map[string]interface{}) - for k, v := range typedYAMLObj { - // Resolve the key to a string first. - var keyString string - switch typedKey := k.(type) { - case string: - keyString = typedKey - case int: - keyString = strconv.Itoa(typedKey) - case int64: - // go-yaml will only return an int64 as a key if the system - // architecture is 32-bit and the key's value is between 32-bit - // and 64-bit. Otherwise the key type will simply be int. - keyString = strconv.FormatInt(typedKey, 10) - case float64: - // Stolen from go-yaml to use the same conversion to string as - // the go-yaml library uses to convert float to string when - // Marshaling. - s := strconv.FormatFloat(typedKey, 'g', -1, 32) - switch s { - case "+Inf": - s = ".inf" - case "-Inf": - s = "-.inf" - case "NaN": - s = ".nan" - } - keyString = s - case bool: - if typedKey { - keyString = "true" - } else { - keyString = "false" - } - default: - return nil, fmt.Errorf("Unsupported map key of type: %s, key: %+#v, value: %+#v", - reflect.TypeOf(k), k, v) - } - - // jsonTarget should be a struct or a map. If it's a struct, find - // the field it's going to map to and pass its reflect.Value. If - // it's a map, find the element type of the map and pass the - // reflect.Value created from that type. If it's neither, just pass - // nil - JSON conversion will error for us if it's a real issue. - if jsonTarget != nil { - t := *jsonTarget - if t.Kind() == reflect.Struct { - keyBytes := []byte(keyString) - // Find the field that the JSON library would use. - var f *field - fields := cachedTypeFields(t.Type()) - for i := range fields { - ff := &fields[i] - if bytes.Equal(ff.nameBytes, keyBytes) { - f = ff - break - } - // Do case-insensitive comparison. - if f == nil && ff.equalFold(ff.nameBytes, keyBytes) { - f = ff - } - } - if f != nil { - // Find the reflect.Value of the most preferential - // struct field. - jtf := t.Field(f.index[0]) - strMap[keyString], err = convertToJSONableObject(v, &jtf) - if err != nil { - return nil, err - } - continue - } - } else if t.Kind() == reflect.Map { - // Create a zero value of the map's element type to use as - // the JSON target. - jtv := reflect.Zero(t.Type().Elem()) - strMap[keyString], err = convertToJSONableObject(v, &jtv) - if err != nil { - return nil, err - } - continue - } - } - strMap[keyString], err = convertToJSONableObject(v, nil) - if err != nil { - return nil, err - } - } - return strMap, nil - case []interface{}: - // We need to recurse into arrays in case there are any - // map[interface{}]interface{}'s inside and to convert any - // numbers to strings. - - // If jsonTarget is a slice (which it really should be), find the - // thing it's going to map to. If it's not a slice, just pass nil - // - JSON conversion will error for us if it's a real issue. - var jsonSliceElemValue *reflect.Value - if jsonTarget != nil { - t := *jsonTarget - if t.Kind() == reflect.Slice { - // By default slices point to nil, but we need a reflect.Value - // pointing to a value of the slice type, so we create one here. - ev := reflect.Indirect(reflect.New(t.Type().Elem())) - jsonSliceElemValue = &ev - } - } - - // Make and use a new array. - arr := make([]interface{}, len(typedYAMLObj)) - for i, v := range typedYAMLObj { - arr[i], err = convertToJSONableObject(v, jsonSliceElemValue) - if err != nil { - return nil, err - } - } - return arr, nil - default: - // If the target type is a string and the YAML type is a number, - // convert the YAML type to a string. - if jsonTarget != nil && (*jsonTarget).Kind() == reflect.String { - // Based on my reading of go-yaml, it may return int, int64, - // float64, or uint64. - var s string - switch typedVal := typedYAMLObj.(type) { - case int: - s = strconv.FormatInt(int64(typedVal), 10) - case int64: - s = strconv.FormatInt(typedVal, 10) - case float64: - s = strconv.FormatFloat(typedVal, 'g', -1, 32) - case uint64: - s = strconv.FormatUint(typedVal, 10) - case bool: - if typedVal { - s = "true" - } else { - s = "false" - } - } - if len(s) > 0 { - yamlObj = interface{}(s) - } - } - return yamlObj, nil - } - - return nil, nil -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 7cb07594..efb1ffcd 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -36,12 +36,6 @@ github.com/bgentry/speakeasy github.com/davecgh/go-spew/spew # github.com/fatih/color v1.7.0 github.com/fatih/color -# github.com/getkin/kin-openapi v0.92.0 -## explicit -github.com/getkin/kin-openapi/jsoninfo -github.com/getkin/kin-openapi/openapi3 -# github.com/ghodss/yaml v1.0.0 -github.com/ghodss/yaml # github.com/go-openapi/analysis v0.21.2 github.com/go-openapi/analysis github.com/go-openapi/analysis/internal/debug