@@ -1,6 +1,6 @@
1−{-# LANGUAGE CPP #-}
21{-# LANGUAGE DataKinds #-}
32{-# LANGUAGE DeriveDataTypeable #-}
3+{-# LANGUAGE DeriveFunctor #-}
44{-# LANGUAGE DeriveGeneric #-}
55{-# LANGUAGE DeriveTraversable #-}
66{-# LANGUAGE FlexibleContexts #-}
@@ -14,91 +14,87 @@
1414{-# LANGUAGE TemplateHaskell #-}
1515{-# LANGUAGE TypeFamilies #-}
1616{-# LANGUAGE UndecidableInstances #-}
17−module Data.OpenApi.Internal where
17+module Data.Swagger.Internal where
1818
1919import Prelude ()
2020import Prelude.Compat
2121
22+import Control.Lens ((&), (.~), (?~))
2223import Control.Applicative
23−import Control.Lens ((&), (.~), (?~))
24−import Data.Aeson hiding (Encoding)
25−#if MIN_VERSION_aeson(2,0,0)
26−import qualified Data.Aeson.KeyMap as KeyMap
27−#endif
28−import qualified Data.Aeson.Types as JSON
29−import Data.Data (Constr, Data (..), DataType, Fixity (..), Typeable,
30− constrIndex, mkConstr, mkDataType)
31−import Data.Hashable (Hashable (..))
32−import qualified Data.HashMap.Strict as HashMap
33−import Data.HashSet.InsOrd (InsOrdHashSet)
34−import Data.Map (Map)
35−import qualified Data.Map as Map
36−import Data.Monoid (Monoid (..))
37−import Data.Scientific (Scientific)
38−import Data.Semigroup.Compat (Semigroup (..))
39−import Data.String (IsString (..))
40−import Data.Text (Text)
41−import qualified Data.Text as Text
42−import Data.Text.Encoding (encodeUtf8)
43−import GHC.Generics (Generic)
44−import Network.HTTP.Media (MediaType, mainType, parameters, parseAccept, subType, (//),
45− (/:))
46−import Network.Socket (HostName, PortNumber)
47−import Text.Read (readMaybe)
24+import Data.Aeson
25+import qualified Data.Aeson.Types as JSON
26+import Data.Data (Data(..), Typeable, mkConstr, mkDataType, Fixity(..), Constr, DataType, constrIndex)
27+import Data.Hashable (Hashable)
28+import qualified Data.HashMap.Strict as HashMap
29+import Data.HashSet.InsOrd (InsOrdHashSet)
30+import Data.Map (Map)
31+import qualified Data.Map as Map
32+import Data.Monoid (Monoid (..))
33+import Data.Semigroup.Compat (Semigroup (..))
34+import Data.Scientific (Scientific)
35+import Data.String (IsString(..))
36+import Data.Text (Text)
37+import qualified Data.Text as Text
38+import GHC.Generics (Generic)
39+import Network.Socket (HostName, PortNumber)
40+import Network.HTTP.Media (MediaType)
41+import Text.Read (readMaybe)
4842
4943import Data.HashMap.Strict.InsOrd (InsOrdHashMap)
5044import qualified Data.HashMap.Strict.InsOrd as InsOrdHashMap
5145
52−import Data.OpenApi.Aeson.Compat (deleteKey)
53−import Data.OpenApi.Internal.AesonUtils (AesonDefaultValue (..), HasSwaggerAesonOptions (..),
54− mkSwaggerAesonOptions, saoAdditionalPairs, saoSubObject,
55− sopSwaggerGenericParseJSON, sopSwaggerGenericToEncoding,
56− sopSwaggerGenericToJSON, sopSwaggerGenericToJSONWithOpts)
57−import Data.OpenApi.Internal.Utils
5846import Generics.SOP.TH (deriveGeneric)
47+import Data.Swagger.Internal.AesonUtils (sopSwaggerGenericToJSON
48+ ,sopSwaggerGenericToJSONWithOpts
49+ ,sopSwaggerGenericParseJSON
50+ ,HasSwaggerAesonOptions(..)
51+ ,AesonDefaultValue(..)
52+ ,mkSwaggerAesonOptions
53+ ,saoAdditionalPairs
54+ ,saoSubObject)
55+import Data.Swagger.Internal.Utils
56+import Data.Swagger.Internal.AesonUtils (sopSwaggerGenericToEncoding)
5957
6058-- $setup
6159-- >>> :seti -XDataKinds
6260-- >>> import Data.Aeson
63−-- >>> import Data.ByteString.Lazy.Char8 as BSL
64−-- >>> import Data.OpenApi.Internal.Utils
6561
6662-- | A list of definitions that can be used in references.
6763type Definitions = InsOrdHashMap Text
6864
6965-- | This is the root document object for the API specification.
70−data OpenApi = OpenApi
66+data Swagger = Swagger
7167 { -- | Provides metadata about the API.
7268 -- The metadata can be used by the clients if needed.
73− _openApiInfo :: Info
69+ _swaggerInfo :: Info
7470
7571 -- | An array of Server Objects, which provide connectivity information
7672 -- to a target server. If the servers property is not provided, or is an empty array,
7773 -- the default value would be a 'Server' object with a url value of @/@.
78− , _openApiServers :: [Server]
74+ , _swaggerServers :: [Server]
7975
8076 -- | The available paths and operations for the API.
81− , _openApiPaths :: InsOrdHashMap FilePath PathItem
77+ , _swaggerPaths :: InsOrdHashMap FilePath PathItem
8278
8379 -- | An element to hold various schemas for the specification.
84− , _openApiComponents :: Components
80+ , _swaggerComponents :: Components
8581
8682 -- | A declaration of which security mechanisms can be used across the API.
8783 -- The list of values includes alternative security requirement objects that can be used.
8884 -- Only one of the security requirement objects need to be satisfied to authorize a request.
8985 -- Individual operations can override this definition.
9086 -- To make security optional, an empty security requirement can be included in the array.
91− , _openApiSecurity :: [SecurityRequirement]
87+ , _swaggerSecurity :: [SecurityRequirement]
9288
9389 -- | A list of tags used by the specification with additional metadata.
9490 -- The order of the tags can be used to reflect on their order by the parsing tools.
9591 -- Not all tags that are used by the 'Operation' Object must be declared.
9692 -- The tags that are not declared MAY be organized randomly or based on the tools' logic.
9793 -- Each tag name in the list MUST be unique.
98− , _openApiTags :: InsOrdHashSet Tag
94+ , _swaggerTags :: InsOrdHashSet Tag
9995
10096 -- | Additional external documentation.
101− , _openApiExternalDocs :: Maybe ExternalDocs
97+ , _swaggerExternalDocs :: Maybe ExternalDocs
10298 } deriving (Eq, Show, Generic, Data, Typeable)
10399
104100-- | The object provides metadata about the API.
@@ -183,24 +179,51 @@ data ServerVariable = ServerVariable
183179 , _serverVariableDescription :: Maybe Text
184180 } deriving (Eq, Show, Generic, Data, Typeable)
185181
186−instance IsString Server where
187− fromString s = Server (fromString s) Nothing mempty
188−
189182-- | Holds a set of reusable objects for different aspects of the OAS.
190183-- All objects defined within the components object will have no effect on the API
191184-- unless they are explicitly referenced from properties outside the components object.
192185data Components = Components
193− { _componentsSchemas :: Definitions Schema
186+ { _componentsSchemas :: Definitions Schema -- TODO check Schema itself
194187 , _componentsResponses :: Definitions Response
195188 , _componentsParameters :: Definitions Param
196− , _componentsExamples :: Definitions Example
189+-- , _componentsExamples
197190 , _componentsRequestBodies :: Definitions RequestBody
198− , _componentsHeaders :: Definitions Header
199− , _componentsSecuritySchemes :: SecurityDefinitions
200− , _componentsLinks :: Definitions Link
201− , _componentsCallbacks :: Definitions Callback
191+ , _componentsHeader :: Definitions Header
192+ , _componentsSecuritySchemes :: Definitions SecurityScheme
193+-- , _componentsLinks
194+-- , _componentsCallbacks
202195 } deriving (Eq, Show, Generic, Data, Typeable)
203196
197+-- | The host (name or ip) serving the API. It MAY include a port.
198+data Host = Host
199+ { _hostName :: HostName -- ^ Host name.
200+ , _hostPort :: Maybe PortNumber -- ^ Optional port.
201+ } deriving (Eq, Show, Generic, Typeable)
202+
203+instance IsString Host where
204+ fromString s = Host s Nothing
205+
206+hostConstr :: Constr
207+hostConstr = mkConstr hostDataType "Host" [] Prefix
208+
209+hostDataType :: DataType
210+hostDataType = mkDataType "Data.Swagger.Host" [hostConstr]
211+
212+instance Data Host where
213+ gunfold k z c = case constrIndex c of
214+ 1 -> k (k (z (\name mport -> Host name (fromInteger <$> mport))))
215+ _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type Host."
216+ toConstr (Host _ _) = hostConstr
217+ dataTypeOf _ = hostDataType
218+
219+-- | The transfer protocol of the API.
220+data Scheme
221+ = Http
222+ | Https
223+ | Ws
224+ | Wss
225+ deriving (Eq, Show, Generic, Data, Typeable)
226+
204227-- | Describes the operations available on a single path.
205228-- A @'PathItem'@ may be empty, due to ACL constraints.
206229-- The path itself is still exposed to the documentation viewer
@@ -288,11 +311,7 @@ data Operation = Operation
288311 -- | The list of possible responses as they are returned from executing this operation.
289312 , _operationResponses :: Responses
290313
291− -- | A map of possible out-of band callbacks related to the parent operation.
292− -- The key is a unique identifier for the 'Callback' Object.
293− -- Each value in the map is a 'Callback' Object that describes a request
294− -- that may be initiated by the API provider and the expected responses.
295− , _operationCallbacks :: InsOrdHashMap Text (Referenced Callback)
314+ -- TODO callbacks
296315
297316 -- | Declares this operation to be deprecated.
298317 -- Usage of the declared operation should be refrained.
@@ -312,22 +331,6 @@ data Operation = Operation
312331 , _operationServers :: [Server]
313332 } deriving (Eq, Show, Generic, Data, Typeable)
314333
315−-- This instance should be in @http-media@.
316−instance Data MediaType where
317− gunfold k z c = case constrIndex c of
318− 1 -> k (k (k (z (\main sub params -> foldl (/:) (main // sub) (Map.toList params)))))
319− _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type MediaType."
320−
321− toConstr _ = mediaTypeConstr
322−
323− dataTypeOf _ = mediaTypeData
324−
325−mediaTypeConstr = mkConstr mediaTypeData "MediaType" [] Prefix
326−mediaTypeData = mkDataType "MediaType" [mediaTypeConstr]
327−
328−instance Hashable MediaType where
329− hashWithSalt salt mt = salt `hashWithSalt` show mt
330−
331334-- | Describes a single request body.
332335data RequestBody = RequestBody
333336 { -- | A brief description of the request body. This could contain examples of use.
@@ -337,94 +340,21 @@ data RequestBody = RequestBody
337340 -- | The content of the request body.
338341 -- The key is a media type or media type range and the value describes it.
339342 -- For requests that match multiple keys, only the most specific key is applicable.
340− -- e.g. @text/plain@ overrides @text/\*@
341− , _requestBodyContent :: InsOrdHashMap MediaType MediaTypeObject
343+ -- e.g. @text/plain@ overrides @text/*@
344+ , _requestBodyContent :: InsOrdHashMap {-MediaType-} Text MediaTypeObject -- FIXME Data MediaType
342345
343− -- | Determines if the request body is required in the request.
344− -- Defaults to 'False'.
345346 , _requestBodyRequired :: Maybe Bool
346347 } deriving (Eq, Show, Generic, Data, Typeable)
347348
348349-- | Each Media Type Object provides schema and examples for the media type identified by its key.
349350data MediaTypeObject = MediaTypeObject
350− { _mediaTypeObjectSchema :: Maybe (Referenced Schema)
351+ { _mediaTypeSchema :: Maybe (Referenced Schema)
351352
352− -- | Example of the media type.
353− -- The example object SHOULD be in the correct format as specified by the media type.
354− , _mediaTypeObjectExample :: Maybe Value
353+-- TODO
354+-- , _mediaTypeExample
355+-- , _mediaTypeExamples
355356
356− -- | Examples of the media type.
357− -- Each example object SHOULD match the media type and specified schema if present.
358− , _mediaTypeObjectExamples :: InsOrdHashMap Text (Referenced Example)
359−
360− -- | A map between a property name and its encoding information.
361− -- The key, being the property name, MUST exist in the schema as a property.
362− -- The encoding object SHALL only apply to 'RequestBody' objects when the media type
363− -- is @multipart@ or @application/x-www-form-urlencoded@.
364− , _mediaTypeObjectEncoding :: InsOrdHashMap Text Encoding
365− } deriving (Eq, Show, Generic, Data, Typeable)
366−
367−-- | In order to support common ways of serializing simple parameters, a set of style values are defined.
368−data Style
369− = StyleMatrix
370− -- ^ Path-style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7).
371− | StyleLabel
372− -- ^ Label style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7).
373− | StyleForm
374− -- ^ Form style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7).
375− -- This option replaces @collectionFormat@ with a @csv@ (when @explode@ is false) or @multi@
376− -- (when explode is true) value from OpenAPI 2.0.
377− | StyleSimple
378− -- ^ Simple style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7).
379− -- This option replaces @collectionFormat@ with a @csv@ value from OpenAPI 2.0.
380− | StyleSpaceDelimited
381− -- ^ Space separated array values.
382− -- This option replaces @collectionFormat@ equal to @ssv@ from OpenAPI 2.0.
383− | StylePipeDelimited
384− -- ^ Pipe separated array values.
385− -- This option replaces @collectionFormat@ equal to @pipes@ from OpenAPI 2.0.
386− | StyleDeepObject
387− -- ^ Provides a simple way of rendering nested objects using form parameters.
388− deriving (Eq, Show, Generic, Data, Typeable)
389−
390−data Encoding = Encoding
391− { -- | The Content-Type for encoding a specific property.
392− -- Default value depends on the property type: for @string@
393− -- with format being @binary@ – @application/octet-stream@;
394− -- for other primitive types – @text/plain@; for object - @application/json@;
395− -- for array – the default is defined based on the inner type.
396− -- The value can be a specific media type (e.g. @application/json@),
397− -- a wildcard media type (e.g. @image/\*@), or a comma-separated list of the two types.
398− _encodingContentType :: Maybe MediaType
399−
400− -- | A map allowing additional information to be provided as headers,
401− -- for example @Content-Disposition@. @Content-Type@ is described separately
402− -- and SHALL be ignored in this section.
403− -- This property SHALL be ignored if the request body media type is not a @multipart@.
404− , _encodingHeaders :: InsOrdHashMap Text (Referenced Header)
405−
406− -- | Describes how a specific property value will be serialized depending on its type.
407− -- See 'Param' Object for details on the style property.
408− -- The behavior follows the same values as query parameters, including default values.
409− -- This property SHALL be ignored if the request body media type
410− -- is not @application/x-www-form-urlencoded@.
411− , _encodingStyle :: Maybe Style
412−
413− -- | When this is true, property values of type @array@ or @object@ generate
414− -- separate parameters for each value of the array,
415− -- or key-value-pair of the map.
416− -- For other types of properties this property has no effect.
417− -- When style is form, the default value is @true@. For all other styles,
418− -- the default value is @false@. This property SHALL be ignored
419− -- if the request body media type is not @application/x-www-form-urlencoded@.
420− , _encodingExplode :: Maybe Bool
421−
422− -- | Determines whether the parameter value SHOULD allow reserved characters,
423− -- as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2)
424− -- @:/?#[]@!$&'()*+,;=@ to be included without percent-encoding.
425− -- The default value is @false@. This property SHALL be ignored if the request body media type
426− -- is not @application/x-www-form-urlencoded@.
427− , _encodingAllowReserved :: Maybe Bool
357+-- , _mediaTypeEncoding :: InsOrdHashMap Text Encoding
428358 } deriving (Eq, Show, Generic, Data, Typeable)
429359
430360newtype MimeList = MimeList { getMimeList :: [MediaType] }
@@ -434,11 +364,11 @@ mimeListConstr :: Constr
434364mimeListConstr = mkConstr mimeListDataType "MimeList" ["getMimeList"] Prefix
435365
436366mimeListDataType :: DataType
437−mimeListDataType = mkDataType "Data.OpenApi.MimeList" [mimeListConstr]
367+mimeListDataType = mkDataType "Data.Swagger.MimeList" [mimeListConstr]
438368
439369instance Data MimeList where
440370 gunfold k z c = case constrIndex c of
441− 1 -> k (z (MimeList . map fromString))
371+ 1 -> k (z (\xs -> MimeList (map fromString xs)))
442372 _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type MimeList."
443373 toConstr (MimeList _) = mimeListConstr
444374 dataTypeOf _ = mimeListDataType
@@ -452,7 +382,7 @@ data Param = Param
452382
453383 -- | A brief description of the parameter.
454384 -- This could contain examples of use.
455− -- CommonMark syntax MAY be used for rich text representation.
385+ -- GFM syntax can be used for rich text representation.
456386 , _paramDescription :: Maybe Text
457387
458388 -- | Determines whether this parameter is mandatory.
@@ -460,141 +390,159 @@ data Param = Param
460390 -- Otherwise, the property MAY be included and its default value is @False@.
461391 , _paramRequired :: Maybe Bool
462392
463− -- | Specifies that a parameter is deprecated and SHOULD be transitioned out of usage.
464− -- Default value is @false@.
465− , _paramDeprecated :: Maybe Bool
466−
467− -- | The location of the parameter.
468− , _paramIn :: ParamLocation
469−
470− -- | Sets the ability to pass empty-valued parameters.
471− -- This is valid only for 'ParamQuery' parameters and allows sending
472− -- a parameter with an empty value. Default value is @false@.
473− , _paramAllowEmptyValue :: Maybe Bool
474−
475− -- | Determines whether the parameter value SHOULD allow reserved characters,
476− -- as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2)
477− -- @:/?#[]@!$&'()*+,;=@ to be included without percent-encoding.
478− -- This property only applies to parameters with an '_paramIn' value of 'ParamQuery'.
479− -- The default value is 'False'.
480− , _paramAllowReserved :: Maybe Bool
481−
482393 -- | Parameter schema.
483− , _paramSchema :: Maybe (Referenced Schema)
484−
485− -- | Describes how the parameter value will be serialized depending
486− -- on the type of the parameter value. Default values (based on value of '_paramIn'):
487− -- for 'ParamQuery' - 'StyleForm'; for 'ParamPath' - 'StyleSimple'; for 'ParamHeader' - 'StyleSimple';
488− -- for 'ParamCookie' - 'StyleForm'.
489− , _paramStyle :: Maybe Style
490−
491− -- | When this is true, parameter values of type @array@ or @object@
492− -- generate separate parameters for each value of the array or key-value pair of the map.
493− -- For other types of parameters this property has no effect.
494− -- When style is @form@, the default value is true. For all other styles, the default value is false.
495− , _paramExplode :: Maybe Bool
496−
497− -- | Example of the parameter's potential value.
498− -- The example SHOULD match the specified schema and encoding properties if present.
499− -- The '_paramExample' field is mutually exclusive of the '_paramExamples' field.
500− -- Furthermore, if referencing a schema that contains an example, the example value
501− -- SHALL override the example provided by the schema. To represent examples of media types
502− -- that cannot naturally be represented in JSON or YAML, a string value can contain
503− -- the example with escaping where necessary.
504− , _paramExample :: Maybe Value
505−
506− -- | Examples of the parameter's potential value.
507− -- Each example SHOULD contain a value in the correct format as specified
508− -- in the parameter encoding. The '_paramExamples' field is mutually exclusive of the '_paramExample' field.
509− -- Furthermore, if referencing a schema that contains an example,
510− -- the examples value SHALL override the example provided by the schema.
511− , _paramExamples :: InsOrdHashMap Text (Referenced Example)
512−
513− -- TODO
514− -- _paramContent :: InsOrdHashMap MediaType MediaTypeObject
515− -- should be singleton. mutually exclusive with _paramSchema.
394+ , _paramSchema :: ParamAnySchema
516395 } deriving (Eq, Show, Generic, Data, Typeable)
517396
518−data Example = Example
519− { -- | Short description for the example.
520− _exampleSummary :: Maybe Text
521−
522− -- | Long description for the example.
523− -- CommonMark syntax MAY be used for rich text representation.
524− , _exampleDescription :: Maybe Text
525−
526− -- | Embedded literal example.
527− -- The '_exampleValue' field and '_exampleExternalValue' field are mutually exclusive.
528− --
529− -- To represent examples of media types that cannot naturally represented in JSON or YAML,
530− -- use a string value to contain the example, escaping where necessary.
531− , _exampleValue :: Maybe Value
532−
533− -- | A URL that points to the literal example.
534− -- This provides the capability to reference examples that cannot easily be included
535− -- in JSON or YAML documents. The '_exampleValue' field
536− -- and '_exampleExternalValue' field are mutually exclusive.
537− , _exampleExternalValue :: Maybe URL
538− } deriving (Eq, Show, Generic, Typeable, Data)
397+data ParamAnySchema
398+ = ParamBody (Referenced Schema)
399+ | ParamOther ParamOtherSchema
400+ deriving (Eq, Show, Generic, Data, Typeable)
401+
402+data ParamOtherSchema = ParamOtherSchema
403+ { -- | The location of the parameter.
404+ _paramOtherSchemaIn :: ParamLocation
539405
540−data ExpressionOrValue
541− = Expression Text
542− | Value Value
543− deriving (Eq, Show, Generic, Typeable, Data)
544−
545−-- | The Link object represents a possible design-time link for a response.
546−-- The presence of a link does not guarantee the caller's ability to successfully invoke it,
547−-- rather it provides a known relationship and traversal mechanism between responses and other operations.
548−data Link = Link
549− { -- | A relative or absolute URI reference to an OAS operation.
550− -- This field is mutually exclusive of the '_linkOperationId' field,
551− -- and MUST point to an 'Operation' Object. Relative '_linkOperationRef'
552− -- values MAY be used to locate an existing 'Operation' Object in the OpenAPI definition.
553− _linkOperationRef :: Maybe Text
554−
555− -- | The name of an /existing/, resolvable OAS operation, as defined with a unique
556− -- '_operationOperationId'. This field is mutually exclusive of the '_linkOperationRef' field.
557− , _linkOperationId :: Maybe Text
558−
559− -- | A map representing parameters to pass to an operation as specified with '_linkOperationId'
560− -- or identified via '_linkOperationRef'. The key is the parameter name to be used, whereas
561− -- the value can be a constant or an expression to be evaluated and passed to the linked operation.
562− -- The parameter name can be qualified using the parameter location @[{in}.]{name}@
563− -- for operations that use the same parameter name in different locations (e.g. path.id).
564− , _linkParameters :: InsOrdHashMap Text ExpressionOrValue
565−
566− -- | A literal value or @{expression}@ to use as a request body when calling the target operation.
567− , _linkRequestBody :: Maybe ExpressionOrValue
568−
569− -- | A description of the link.
570− , _linkDescription :: Maybe Text
571−
572− -- | A server object to be used by the target operation.
573− , _linkServer :: Maybe Server
406+ -- | Sets the ability to pass empty-valued parameters.
407+ -- This is valid only for either @'ParamQuery'@ or @'ParamFormData'@
408+ -- and allows you to send a parameter with a name only or an empty value.
409+ -- Default value is @False@.
410+ , _paramOtherSchemaAllowEmptyValue :: Maybe Bool
411+
412+ , _paramOtherSchemaParamSchema :: ParamSchema 'SwaggerKindParamOtherSchema
574413 } deriving (Eq, Show, Generic, Typeable, Data)
575414
576−-- | Items for @'OpenApiArray'@ schemas.
415+-- | Items for @'SwaggerArray'@ schemas.
577416--
578−-- __Warning__: OpenAPI 3.0 does not support tuple arrays. However, OpenAPI 3.1 will, as
579−-- it will incorporate Json Schema mostly verbatim.
417+-- @'SwaggerItemsPrimitive'@ should be used only for query params, headers and path pieces.
418+-- The @'CollectionFormat' t@ parameter specifies how elements of an array should be displayed.
419+-- Note that @fmt@ in @'SwaggerItemsPrimitive' fmt schema@ specifies format for elements of type @schema@.
420+-- This is different from the original Swagger's <http://swagger.io/specification/#itemsObject Items Object>.
580421--
581−-- @'OpenApiItemsObject'@ should be used to specify homogenous array @'Schema'@s.
422+-- @'SwaggerItemsObject'@ should be used to specify homogenous array @'Schema'@s.
582423--
583−-- @'OpenApiItemsArray'@ should be used to specify tuple @'Schema'@s.
584−data OpenApiItems where
585− OpenApiItemsObject :: Referenced Schema -> OpenApiItems
586− OpenApiItemsArray :: [Referenced Schema] -> OpenApiItems
587− deriving (Eq, Show, Typeable, Data)
588−
589−data OpenApiType where
590− OpenApiString :: OpenApiType
591− OpenApiNumber :: OpenApiType
592− OpenApiInteger :: OpenApiType
593− OpenApiBoolean :: OpenApiType
594− OpenApiArray :: OpenApiType
595− OpenApiNull :: OpenApiType
596− OpenApiObject :: OpenApiType
597− deriving (Eq, Show, Typeable, Generic, Data)
424+-- @'SwaggerItemsArray'@ should be used to specify tuple @'Schema'@s.
425+data SwaggerItems t where
426+ SwaggerItemsPrimitive :: Maybe (CollectionFormat k) -> ParamSchema k-> SwaggerItems k
427+ SwaggerItemsObject :: Referenced Schema -> SwaggerItems 'SwaggerKindSchema
428+ SwaggerItemsArray :: [Referenced Schema] -> SwaggerItems 'SwaggerKindSchema
429+ deriving (Typeable)
430+
431+deriving instance Eq (SwaggerItems t)
432+deriving instance Show (SwaggerItems t)
433+--deriving instance Typeable (SwaggerItems t)
434+
435+swaggerItemsPrimitiveConstr :: Constr
436+swaggerItemsPrimitiveConstr = mkConstr swaggerItemsDataType "SwaggerItemsPrimitive" [] Prefix
437+
438+swaggerItemsObjectConstr :: Constr
439+swaggerItemsObjectConstr = mkConstr swaggerItemsDataType "SwaggerItemsObject" [] Prefix
440+
441+swaggerItemsArrayConstr :: Constr
442+swaggerItemsArrayConstr = mkConstr swaggerItemsDataType "SwaggerItemsArray" [] Prefix
443+
444+swaggerItemsDataType :: DataType
445+swaggerItemsDataType = mkDataType "Data.Swagger.SwaggerItems" [swaggerItemsPrimitiveConstr]
446+
447+-- Note: unfortunately we have to write these Data instances by hand,
448+-- to get better contexts / avoid duplicate name when using standalone deriving
449+
450+instance Data t => Data (SwaggerItems ('SwaggerKindNormal t)) where
451+ -- TODO: define gfoldl
452+ gunfold k z c = case constrIndex c of
453+ 1 -> k (k (z SwaggerItemsPrimitive))
454+ _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type (SwaggerItems t)."
455+ toConstr _ = swaggerItemsPrimitiveConstr
456+ dataTypeOf _ = swaggerItemsDataType
457+
458+-- SwaggerItems SwaggerKindParamOtherSchema can be constructed using SwaggerItemsPrimitive only
459+instance Data (SwaggerItems 'SwaggerKindParamOtherSchema) where
460+ -- TODO: define gfoldl
461+ gunfold k z c = case constrIndex c of
462+ 1 -> k (k (z SwaggerItemsPrimitive))
463+ _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type (SwaggerItems SwaggerKindParamOtherSchema)."
464+ toConstr _ = swaggerItemsPrimitiveConstr
465+ dataTypeOf _ = swaggerItemsDataType
466+
467+instance Data (SwaggerItems 'SwaggerKindSchema) where
468+ gfoldl _ _ (SwaggerItemsPrimitive _ _) = error " Data.Data.gfoldl: Constructor SwaggerItemsPrimitive used to construct SwaggerItems SwaggerKindSchema"
469+ gfoldl k z (SwaggerItemsObject ref) = z SwaggerItemsObject `k` ref
470+ gfoldl k z (SwaggerItemsArray ref) = z SwaggerItemsArray `k` ref
471+
472+ gunfold k z c = case constrIndex c of
473+ 2 -> k (z SwaggerItemsObject)
474+ 3 -> k (z SwaggerItemsArray)
475+ _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type (SwaggerItems SwaggerKindSchema)."
476+
477+ toConstr (SwaggerItemsPrimitive _ _) = error "Not supported"
478+ toConstr (SwaggerItemsObject _) = swaggerItemsObjectConstr
479+ toConstr (SwaggerItemsArray _) = swaggerItemsArrayConstr
480+
481+ dataTypeOf _ = swaggerItemsDataType
482+
483+-- | Type used as a kind to avoid overlapping instances.
484+data SwaggerKind t
485+ = SwaggerKindNormal t
486+ | SwaggerKindParamOtherSchema
487+ | SwaggerKindSchema
488+ deriving (Typeable)
489+
490+deriving instance Typeable 'SwaggerKindNormal
491+deriving instance Typeable 'SwaggerKindParamOtherSchema
492+deriving instance Typeable 'SwaggerKindSchema
493+
494+type family SwaggerKindType (k :: SwaggerKind *) :: *
495+type instance SwaggerKindType ('SwaggerKindNormal t) = t
496+type instance SwaggerKindType 'SwaggerKindSchema = Schema
497+type instance SwaggerKindType 'SwaggerKindParamOtherSchema = ParamOtherSchema
498+
499+data SwaggerType t where
500+ SwaggerString :: SwaggerType t
501+ SwaggerNumber :: SwaggerType t
502+ SwaggerInteger :: SwaggerType t
503+ SwaggerBoolean :: SwaggerType t
504+ SwaggerArray :: SwaggerType t
505+ SwaggerFile :: SwaggerType 'SwaggerKindParamOtherSchema
506+ SwaggerNull :: SwaggerType 'SwaggerKindSchema
507+ SwaggerObject :: SwaggerType 'SwaggerKindSchema
508+ deriving (Typeable)
509+
510+deriving instance Eq (SwaggerType t)
511+deriving instance Show (SwaggerType t)
512+
513+swaggerTypeConstr :: Data (SwaggerType t) => SwaggerType t -> Constr
514+swaggerTypeConstr t = mkConstr (dataTypeOf t) (show t) [] Prefix
515+
516+swaggerTypeDataType :: {- Data (SwaggerType t) => -} SwaggerType t -> DataType
517+swaggerTypeDataType _ = mkDataType "Data.Swagger.SwaggerType" swaggerTypeConstrs
518+
519+swaggerCommonTypes :: [SwaggerType k]
520+swaggerCommonTypes = [SwaggerString, SwaggerNumber, SwaggerInteger, SwaggerBoolean, SwaggerArray]
521+
522+swaggerParamTypes :: [SwaggerType 'SwaggerKindParamOtherSchema]
523+swaggerParamTypes = swaggerCommonTypes ++ [SwaggerFile]
524+
525+swaggerSchemaTypes :: [SwaggerType 'SwaggerKindSchema]
526+swaggerSchemaTypes = swaggerCommonTypes ++ [error "SwaggerFile is invalid SwaggerType Schema", SwaggerNull, SwaggerObject]
527+
528+swaggerTypeConstrs :: [Constr]
529+swaggerTypeConstrs = map swaggerTypeConstr (swaggerCommonTypes :: [SwaggerType 'SwaggerKindSchema])
530+ ++ [swaggerTypeConstr SwaggerFile, swaggerTypeConstr SwaggerNull, swaggerTypeConstr SwaggerObject]
531+
532+instance Typeable t => Data (SwaggerType ('SwaggerKindNormal t)) where
533+ gunfold = gunfoldEnum "SwaggerType" swaggerCommonTypes
534+ toConstr = swaggerTypeConstr
535+ dataTypeOf = swaggerTypeDataType
536+
537+instance Data (SwaggerType 'SwaggerKindParamOtherSchema) where
538+ gunfold = gunfoldEnum "SwaggerType ParamOtherSchema" swaggerParamTypes
539+ toConstr = swaggerTypeConstr
540+ dataTypeOf = swaggerTypeDataType
541+
542+instance Data (SwaggerType 'SwaggerKindSchema) where
543+ gunfold = gunfoldEnum "SwaggerType Schema" swaggerSchemaTypes
544+ toConstr = swaggerTypeConstr
545+ dataTypeOf = swaggerTypeDataType
598546
599547data ParamLocation
600548 = -- | Parameters that are appended to the URL.
@@ -612,6 +560,42 @@ data ParamLocation
612560
613561type Format = Text
614562
563+-- | Determines the format of the array.
564+data CollectionFormat t where
565+ -- Comma separated values: @foo,bar@.
566+ CollectionCSV :: CollectionFormat t
567+ -- Space separated values: @foo bar@.
568+ CollectionSSV :: CollectionFormat t
569+ -- Tab separated values: @foo\\tbar@.
570+ CollectionTSV :: CollectionFormat t
571+ -- Pipe separated values: @foo|bar@.
572+ CollectionPipes :: CollectionFormat t
573+ -- Corresponds to multiple parameter instances
574+ -- instead of multiple values for a single instance @foo=bar&foo=baz@.
575+ -- This is valid only for parameters in @'ParamQuery'@ or @'ParamFormData'@.
576+ CollectionMulti :: CollectionFormat 'SwaggerKindParamOtherSchema
577+ deriving (Typeable)
578+
579+deriving instance Eq (CollectionFormat t)
580+deriving instance Show (CollectionFormat t)
581+
582+collectionFormatConstr :: CollectionFormat t -> Constr
583+collectionFormatConstr cf = mkConstr collectionFormatDataType (show cf) [] Prefix
584+
585+collectionFormatDataType :: DataType
586+collectionFormatDataType = mkDataType "Data.Swagger.CollectionFormat" $
587+ map collectionFormatConstr collectionCommonFormats
588+
589+collectionCommonFormats :: [CollectionFormat t]
590+collectionCommonFormats = [ CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes ]
591+
592+instance Data t => Data (CollectionFormat ('SwaggerKindNormal t)) where
593+ gunfold = gunfoldEnum "CollectionFormat" collectionCommonFormats
594+ toConstr = collectionFormatConstr
595+ dataTypeOf _ = collectionFormatDataType
596+
597+deriving instance Data (CollectionFormat 'SwaggerKindParamOtherSchema)
598+
615599type ParamName = Text
616600
617601data Schema = Schema
@@ -619,58 +603,20 @@ data Schema = Schema
619603 , _schemaDescription :: Maybe Text
620604 , _schemaRequired :: [ParamName]
621605
622− , _schemaNullable :: Maybe Bool
623606 , _schemaAllOf :: Maybe [Referenced Schema]
624− , _schemaOneOf :: Maybe [Referenced Schema]
625− , _schemaNot :: Maybe (Referenced Schema)
626− , _schemaAnyOf :: Maybe [Referenced Schema]
627607 , _schemaProperties :: InsOrdHashMap Text (Referenced Schema)
628608 , _schemaAdditionalProperties :: Maybe AdditionalProperties
629609
630− , _schemaDiscriminator :: Maybe Discriminator
610+ , _schemaDiscriminator :: Maybe Text
631611 , _schemaReadOnly :: Maybe Bool
632− , _schemaWriteOnly :: Maybe Bool
633612 , _schemaXml :: Maybe Xml
634613 , _schemaExternalDocs :: Maybe ExternalDocs
635614 , _schemaExample :: Maybe Value
636− , _schemaDeprecated :: Maybe Bool
637615
638616 , _schemaMaxProperties :: Maybe Integer
639617 , _schemaMinProperties :: Maybe Integer
640618
641− , -- | Declares the value of the parameter that the server will use if none is provided,
642− -- for example a @"count"@ to control the number of results per page might default to @100@
643− -- if not supplied by the client in the request.
644− -- (Note: "default" has no meaning for required parameters.)
645− -- Unlike JSON Schema this value MUST conform to the defined type for this parameter.
646− _schemaDefault :: Maybe Value
647−
648− , _schemaType :: Maybe OpenApiType
649− , _schemaFormat :: Maybe Format
650− , _schemaItems :: Maybe OpenApiItems
651− , _schemaMaximum :: Maybe Scientific
652− , _schemaExclusiveMaximum :: Maybe Bool
653− , _schemaMinimum :: Maybe Scientific
654− , _schemaExclusiveMinimum :: Maybe Bool
655− , _schemaMaxLength :: Maybe Integer
656− , _schemaMinLength :: Maybe Integer
657− , _schemaPattern :: Maybe Pattern
658− , _schemaMaxItems :: Maybe Integer
659− , _schemaMinItems :: Maybe Integer
660− , _schemaUniqueItems :: Maybe Bool
661− , _schemaEnum :: Maybe [Value]
662− , _schemaMultipleOf :: Maybe Scientific
663− } deriving (Eq, Show, Generic, Data, Typeable)
664−
665−-- | Regex pattern for @string@ type.
666−type Pattern = Text
667−
668−data Discriminator = Discriminator
669− { -- | The name of the property in the payload that will hold the discriminator value.
670− _discriminatorPropertyName :: Text
671−
672− -- | An object to hold mappings between payload values and schema names or references.
673− , _discriminatorMapping :: InsOrdHashMap Text Text
619+ , _schemaParamSchema :: ParamSchema 'SwaggerKindSchema
674620 } deriving (Eq, Show, Generic, Data, Typeable)
675621
676622-- | A @'Schema'@ with an optional name.
@@ -680,9 +626,39 @@ data NamedSchema = NamedSchema
680626 , _namedSchemaSchema :: Schema
681627 } deriving (Eq, Show, Generic, Data, Typeable)
682628
629+-- | Regex pattern for @string@ type.
630+type Pattern = Text
631+
632+data ParamSchema (t :: SwaggerKind *) = ParamSchema
633+ { -- | Declares the value of the parameter that the server will use if none is provided,
634+ -- for example a @"count"@ to control the number of results per page might default to @100@
635+ -- if not supplied by the client in the request.
636+ -- (Note: "default" has no meaning for required parameters.)
637+ -- Unlike JSON Schema this value MUST conform to the defined type for this parameter.
638+ _paramSchemaDefault :: Maybe Value
639+
640+ , _paramSchemaType :: Maybe (SwaggerType t)
641+ , _paramSchemaFormat :: Maybe Format
642+ , _paramSchemaItems :: Maybe (SwaggerItems t)
643+ , _paramSchemaMaximum :: Maybe Scientific
644+ , _paramSchemaExclusiveMaximum :: Maybe Bool
645+ , _paramSchemaMinimum :: Maybe Scientific
646+ , _paramSchemaExclusiveMinimum :: Maybe Bool
647+ , _paramSchemaMaxLength :: Maybe Integer
648+ , _paramSchemaMinLength :: Maybe Integer
649+ , _paramSchemaPattern :: Maybe Pattern
650+ , _paramSchemaMaxItems :: Maybe Integer
651+ , _paramSchemaMinItems :: Maybe Integer
652+ , _paramSchemaUniqueItems :: Maybe Bool
653+ , _paramSchemaEnum :: Maybe [Value]
654+ , _paramSchemaMultipleOf :: Maybe Scientific
655+ } deriving (Eq, Show, Generic, Typeable)
656+
657+deriving instance (Typeable k, Data (Maybe (SwaggerType k)), Data (SwaggerItems k)) => Data (ParamSchema k)
658+
683659data Xml = Xml
684660 { -- | Replaces the name of the element/attribute used for the described schema property.
685− -- When defined within the @'OpenApiItems'@ (items), it will affect the name of the individual XML elements within the list.
661+ -- When defined within the @'SwaggerItems'@ (items), it will affect the name of the individual XML elements within the list.
686662 -- When defined alongside type being array (outside the items),
687663 -- it will affect the wrapping element and only if wrapped is true.
688664 -- If wrapped is false, it will be ignored.
@@ -734,48 +710,43 @@ data Response = Response
734710 -- | A map containing descriptions of potential response payloads.
735711 -- The key is a media type or media type range and the value describes it.
736712 -- For responses that match multiple keys, only the most specific key is applicable.
737− -- e.g. @text/plain@ overrides @text/\*@.
738− , _responseContent :: InsOrdHashMap MediaType MediaTypeObject
713+ -- e.g. @text/plain@ overrides @text/*@.
714+ , _responseContent :: InsOrdHashMap Text MediaTypeObject
739715
740716 -- | Maps a header name to its definition.
741− , _responseHeaders :: InsOrdHashMap HeaderName (Referenced Header)
717+ , _responseHeaders :: InsOrdHashMap HeaderName Header -- FIXME Referenced
742718
743− -- | A map of operations links that can be followed from the response.
744− -- The key of the map is a short name for the link, following the naming
745− -- constraints of the names for 'Component' Objects.
746− , _responseLinks :: InsOrdHashMap Text (Referenced Link)
719+ -- TODO links
747720 } deriving (Eq, Show, Generic, Data, Typeable)
748721
749722instance IsString Response where
750− fromString s = Response (fromString s) mempty mempty mempty
751−
752−-- | A map of possible out-of band callbacks related to the parent operation.
753−-- Each value in the map is a 'PathItem' Object that describes a set of requests that
754−-- may be initiated by the API provider and the expected responses.
755−-- The key value used to identify the path item object is an expression, evaluated at runtime,
756−-- that identifies a URL to use for the callback operation.
757−newtype Callback = Callback (InsOrdHashMap Text PathItem)
758− deriving (Eq, Show, Generic, Data, Typeable)
723+ fromString s = Response (fromString s) mempty mempty
759724
760725type HeaderName = Text
761726
762−-- | Header fields have the same meaning as for 'Param'.
763−--
764−-- Style is always treated as 'StyleSimple', as it is the only value allowed for headers.
765727data Header = Header
766728 { -- | A short description of the header.
767− _headerDescription :: Maybe HeaderName
729+ _headerDescription :: Maybe Text
768730
769− , _headerRequired :: Maybe Bool
770− , _headerDeprecated :: Maybe Bool
771− , _headerAllowEmptyValue :: Maybe Bool
772− , _headerExplode :: Maybe Bool
773− , _headerExample :: Maybe Value
774− , _headerExamples :: InsOrdHashMap Text (Referenced Example)
775−
776− , _headerSchema :: Maybe (Referenced Schema)
731+ , _headerParamSchema :: ParamSchema ('SwaggerKindNormal Header)
777732 } deriving (Eq, Show, Generic, Data, Typeable)
778733
734+data Example = Example { getExample :: Map MediaType Value }
735+ deriving (Eq, Show, Generic, Typeable)
736+
737+exampleConstr :: Constr
738+exampleConstr = mkConstr exampleDataType "Example" ["getExample"] Prefix
739+
740+exampleDataType :: DataType
741+exampleDataType = mkDataType "Data.Swagger.Example" [exampleConstr]
742+
743+instance Data Example where
744+ gunfold k z c = case constrIndex c of
745+ 1 -> k (z (\m -> Example (Map.mapKeys fromString m)))
746+ _ -> error $ "Data.Data.gunfold: Constructor " ++ show c ++ " is not of type Example."
747+ toConstr (Example _) = exampleConstr
748+ dataTypeOf _ = exampleDataType
749+
779750-- | The location of the API key.
780751data ApiKeyLocation
781752 = ApiKeyQuery
@@ -797,96 +768,26 @@ type AuthorizationURL = Text
797768-- | The token URL to be used for OAuth2 flow. This SHOULD be in the form of a URL.
798769type TokenURL = Text
799770
800−newtype OAuth2ImplicitFlow
801− = OAuth2ImplicitFlow {_oAuth2ImplicitFlowAuthorizationUrl :: AuthorizationURL}
802− deriving (Eq, Show, Generic, Data, Typeable)
803−
804−newtype OAuth2PasswordFlow
805− = OAuth2PasswordFlow {_oAuth2PasswordFlowTokenUrl :: TokenURL}
771+data OAuth2Flow
772+ = OAuth2Implicit AuthorizationURL
773+ | OAuth2Password TokenURL
774+ | OAuth2Application TokenURL
775+ | OAuth2AccessCode AuthorizationURL TokenURL
806776 deriving (Eq, Show, Generic, Data, Typeable)
807777
808−newtype OAuth2ClientCredentialsFlow
809− = OAuth2ClientCredentialsFlow {_oAuth2ClientCredentialsFlowTokenUrl :: TokenURL}
810− deriving (Eq, Show, Generic, Data, Typeable)
811−
812−data OAuth2AuthorizationCodeFlow = OAuth2AuthorizationCodeFlow
813− { _oAuth2AuthorizationCodeFlowAuthorizationUrl :: AuthorizationURL
814− , _oAuth2AuthorizationCodeFlowTokenUrl :: TokenURL
815− } deriving (Eq, Show, Generic, Data, Typeable)
816−
817−data OAuth2Flow p = OAuth2Flow
818− { _oAuth2Params :: p
819−
820− -- | The URL to be used for obtaining refresh tokens.
821− , _oAath2RefreshUrl :: Maybe URL
778+data OAuth2Params = OAuth2Params
779+ { -- | The flow used by the OAuth2 security scheme.
780+ _oauth2Flow :: OAuth2Flow
822781
823782 -- | The available scopes for the OAuth2 security scheme.
824− -- A map between the scope name and a short description for it.
825− -- The map MAY be empty.
826− , _oAuth2Scopes :: InsOrdHashMap Text Text
827− } deriving (Eq, Show, Generic, Data, Typeable)
828−
829−data OAuth2Flows = OAuth2Flows
830− { -- | Configuration for the OAuth Implicit flow
831− _oAuth2FlowsImplicit :: Maybe (OAuth2Flow OAuth2ImplicitFlow)
832−
833− -- | Configuration for the OAuth Resource Owner Password flow
834− , _oAuth2FlowsPassword :: Maybe (OAuth2Flow OAuth2PasswordFlow)
835−
836− -- | Configuration for the OAuth Client Credentials flow
837− , _oAuth2FlowsClientCredentials :: Maybe (OAuth2Flow OAuth2ClientCredentialsFlow)
838−
839− -- | Configuration for the OAuth Authorization Code flow
840− , _oAuth2FlowsAuthorizationCode :: Maybe (OAuth2Flow OAuth2AuthorizationCodeFlow)
783+ , _oauth2Scopes :: InsOrdHashMap Text Text
841784 } deriving (Eq, Show, Generic, Data, Typeable)
842785
843−type BearerFormat = Text
844−
845−data HttpSchemeType
846− = HttpSchemeBearer (Maybe BearerFormat)
847− | HttpSchemeBasic
848− | HttpSchemeCustom Text
849− deriving (Eq, Show, Generic, Data, Typeable)
850−
851−-- |
852−--
853−-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeHttp (HttpSchemeBearer Nothing))
854−-- {
855−-- "scheme": "bearer",
856−-- "type": "http"
857−-- }
858−--
859−-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeHttp (HttpSchemeBearer (Just "jwt")))
860−-- {
861−-- "bearerFormat": "jwt",
862−-- "scheme": "bearer",
863−-- "type": "http"
864−-- }
865−--
866−-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeHttp HttpSchemeBasic)
867−-- {
868−-- "scheme": "basic",
869−-- "type": "http"
870−-- }
871−--
872−-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeHttp (HttpSchemeCustom "CANARY"))
873−-- {
874−-- "scheme": "CANARY",
875−-- "type": "http"
876−-- }
877−--
878−-- >>> BSL.putStrLn $ encodePretty (SecuritySchemeApiKey (ApiKeyParams "id" ApiKeyCookie))
879−-- {
880−-- "in": "cookie",
881−-- "name": "id",
882−-- "type": "apiKey"
883−-- }
884−--
885786data SecuritySchemeType
886− = SecuritySchemeHttp HttpSchemeType
787+ = SecuritySchemeHttp
887788 | SecuritySchemeApiKey ApiKeyParams
888− | SecuritySchemeOAuth2 OAuth2Flows
889− | SecuritySchemeOpenIdConnect URL
789+ | SecuritySchemeOAuth2 OAuth2Params
790+-- | SecuritySchemeOpenIdConnect -- FIXME
890791 deriving (Eq, Show, Generic, Data, Typeable)
891792
892793data SecurityScheme = SecurityScheme
@@ -897,6 +798,18 @@ data SecurityScheme = SecurityScheme
897798 , _securitySchemeDescription :: Maybe Text
898799 } deriving (Eq, Show, Generic, Data, Typeable)
899800
801+
802+-- | merge scopes of two OAuth2 security schemes when their flows are identical.
803+-- In other case returns first security scheme
804+mergeSecurityScheme :: SecurityScheme -> SecurityScheme -> SecurityScheme
805+mergeSecurityScheme s1@(SecurityScheme (SecuritySchemeOAuth2 (OAuth2Params flow1 scopes1)) desc)
806+ s2@(SecurityScheme (SecuritySchemeOAuth2 (OAuth2Params flow2 scopes2)) _)
807+ = if flow1 == flow2 then
808+ SecurityScheme (SecuritySchemeOAuth2 (OAuth2Params flow1 (scopes1 <> scopes2))) desc
809+ else
810+ s1
811+mergeSecurityScheme s1 _ = s1
812+
900813newtype SecurityDefinitions
901814 = SecurityDefinitions (Definitions SecurityScheme)
902815 deriving (Eq, Show, Generic, Data, Typeable)
@@ -918,7 +831,7 @@ data Tag = Tag
918831 _tagName :: TagName
919832
920833 -- | A short description for the tag.
921− -- [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation.
834+ -- GFM syntax can be used for rich text representation.
922835 , _tagDescription :: Maybe Text
923836
924837 -- | Additional external documentation for this tag.
@@ -933,7 +846,7 @@ instance IsString Tag where
933846-- | Allows referencing an external resource for extended documentation.
934847data ExternalDocs = ExternalDocs
935848 { -- | A short description of the target documentation.
936− -- [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation.
849+ -- GFM syntax can be used for rich text representation.
937850 _externalDocsDescription :: Maybe Text
938851
939852 -- | The URL for the target documentation.
@@ -966,13 +879,12 @@ data AdditionalProperties
966879-- Generic instances
967880-------------------------------------------------------------------------------
968881
969−deriveGeneric ''Server
970882deriveGeneric ''Components
971883deriveGeneric ''Header
972−deriveGeneric ''OAuth2Flow
973−deriveGeneric ''OAuth2Flows
884+deriveGeneric ''OAuth2Params
974885deriveGeneric ''Operation
975886deriveGeneric ''Param
887+deriveGeneric ''ParamOtherSchema
976888deriveGeneric ''PathItem
977889deriveGeneric ''Response
978890deriveGeneric ''RequestBody
@@ -980,18 +892,16 @@ deriveGeneric ''MediaTypeObject
980892deriveGeneric ''Responses
981893deriveGeneric ''SecurityScheme
982894deriveGeneric ''Schema
983−deriveGeneric ''OpenApi
984−deriveGeneric ''Example
985−deriveGeneric ''Encoding
986−deriveGeneric ''Link
895+deriveGeneric ''ParamSchema
896+deriveGeneric ''Swagger
987897
988898-- =======================================================================
989899-- Monoid instances
990900-- =======================================================================
991901
992−instance Semigroup OpenApi where
902+instance Semigroup Swagger where
993903 (<>) = genericMappend
994−instance Monoid OpenApi where
904+instance Monoid Swagger where
995905 mempty = genericMempty
996906 mappend = (<>)
997907
@@ -1025,39 +935,39 @@ instance Monoid Schema where
1025935 mempty = genericMempty
1026936 mappend = (<>)
1027937
1028−instance Semigroup Param where
938+instance Semigroup (ParamSchema t) where
1029939 (<>) = genericMappend
1030−instance Monoid Param where
940+instance Monoid (ParamSchema t) where
1031941 mempty = genericMempty
1032942 mappend = (<>)
1033943
1034−instance Semigroup Header where
944+instance Semigroup Param where
1035945 (<>) = genericMappend
1036−instance Monoid Header where
946+instance Monoid Param where
1037947 mempty = genericMempty
1038948 mappend = (<>)
1039949
1040−instance Semigroup Responses where
950+instance Semigroup ParamOtherSchema where
1041951 (<>) = genericMappend
1042−instance Monoid Responses where
952+instance Monoid ParamOtherSchema where
1043953 mempty = genericMempty
1044954 mappend = (<>)
1045955
1046−instance Semigroup Response where
956+instance Semigroup Header where
1047957 (<>) = genericMappend
1048−instance Monoid Response where
958+instance Monoid Header where
1049959 mempty = genericMempty
1050960 mappend = (<>)
1051961
1052−instance Semigroup MediaTypeObject where
962+instance Semigroup Responses where
1053963 (<>) = genericMappend
1054−instance Monoid MediaTypeObject where
964+instance Monoid Responses where
1055965 mempty = genericMempty
1056966 mappend = (<>)
1057967
1058−instance Semigroup Encoding where
968+instance Semigroup Response where
1059969 (<>) = genericMappend
1060−instance Monoid Encoding where
970+instance Monoid Response where
1061971 mempty = genericMempty
1062972 mappend = (<>)
1063973
@@ -1073,29 +983,14 @@ instance Monoid Operation where
1073983 mempty = genericMempty
1074984 mappend = (<>)
1075985
1076−instance Semigroup (OAuth2Flow p) where
1077− l@OAuth2Flow{ _oAath2RefreshUrl = lUrl, _oAuth2Scopes = lScopes }
1078− <> OAuth2Flow { _oAath2RefreshUrl = rUrl, _oAuth2Scopes = rScopes } =
1079− l { _oAath2RefreshUrl = swaggerMappend lUrl rUrl, _oAuth2Scopes = lScopes <> rScopes }
1080−
1081−-- swaggerMappend has First-like semantics, and here we need mappend'ing under Maybes.
1082−instance Semigroup OAuth2Flows where
1083− l <> r = OAuth2Flows
1084− { _oAuth2FlowsImplicit = _oAuth2FlowsImplicit l <> _oAuth2FlowsImplicit r
1085− , _oAuth2FlowsPassword = _oAuth2FlowsPassword l <> _oAuth2FlowsPassword r
1086− , _oAuth2FlowsClientCredentials = _oAuth2FlowsClientCredentials l <> _oAuth2FlowsClientCredentials r
1087− , _oAuth2FlowsAuthorizationCode = _oAuth2FlowsAuthorizationCode l <> _oAuth2FlowsAuthorizationCode r
1088− }
1089−
1090−instance Monoid OAuth2Flows where
986+instance Semigroup Example where
987+ (<>) = genericMappend
988+instance Monoid Example where
1091989 mempty = genericMempty
1092990 mappend = (<>)
1093991
1094992instance Semigroup SecurityScheme where
1095− SecurityScheme (SecuritySchemeOAuth2 lFlows) lDesc
1096− <> SecurityScheme (SecuritySchemeOAuth2 rFlows) rDesc =
1097− SecurityScheme (SecuritySchemeOAuth2 $ lFlows <> rFlows) (swaggerMappend lDesc rDesc)
1098− l <> _ = l
993+ (<>) = mergeSecurityScheme
1099994
1100995instance Semigroup SecurityDefinitions where
1101996 (SecurityDefinitions sd1) <> (SecurityDefinitions sd2) =
@@ -1105,12 +1000,6 @@ instance Monoid SecurityDefinitions where
11051000 mempty = SecurityDefinitions InsOrdHashMap.empty
11061001 mappend = (<>)
11071002
1108−instance Semigroup RequestBody where
1109− (<>) = genericMappend
1110−instance Monoid RequestBody where
1111− mempty = genericMempty
1112− mappend = (<>)
1113−
11141003-- =======================================================================
11151004-- SwaggerMonoid helper instances
11161005-- =======================================================================
@@ -1119,19 +1008,21 @@ instance SwaggerMonoid Info
11191008instance SwaggerMonoid Components
11201009instance SwaggerMonoid PathItem
11211010instance SwaggerMonoid Schema
1011+instance SwaggerMonoid (ParamSchema t)
11221012instance SwaggerMonoid Param
1013+instance SwaggerMonoid ParamOtherSchema
11231014instance SwaggerMonoid Responses
11241015instance SwaggerMonoid Response
11251016instance SwaggerMonoid ExternalDocs
11261017instance SwaggerMonoid Operation
1127−instance (Eq a, Hashable a) => SwaggerMonoid (InsOrdHashSet a)
11281018instance SwaggerMonoid SecurityDefinitions
1019+instance (Eq a, Hashable a) => SwaggerMonoid (InsOrdHashSet a)
11291020
11301021instance SwaggerMonoid MimeList
11311022deriving instance SwaggerMonoid URL
11321023
1133−instance SwaggerMonoid OpenApiType where
1134− swaggerMempty = OpenApiString
1024+instance SwaggerMonoid (SwaggerType t) where
1025+ swaggerMempty = SwaggerString
11351026 swaggerMappend _ y = y
11361027
11371028instance SwaggerMonoid ParamLocation where
@@ -1147,16 +1038,16 @@ instance Monoid a => SwaggerMonoid (Referenced a) where
11471038 swaggerMappend (Inline x) (Inline y) = Inline (mappend x y)
11481039 swaggerMappend _ y = y
11491040
1041+instance SwaggerMonoid ParamAnySchema where
1042+ swaggerMempty = ParamOther swaggerMempty
1043+ swaggerMappend (ParamBody x) (ParamBody y) = ParamBody (swaggerMappend x y)
1044+ swaggerMappend (ParamOther x) (ParamOther y) = ParamOther (swaggerMappend x y)
1045+ swaggerMappend _ y = y
1046+
11501047-- =======================================================================
11511048-- Simple Generic-based ToJSON instances
11521049-- =======================================================================
11531050
1154−instance ToJSON Style where
1155− toJSON = genericToJSON (jsonPrefix "Style")
1156−
1157−instance ToJSON OpenApiType where
1158− toJSON = genericToJSON (jsonPrefix "Swagger")
1159−
11601051instance ToJSON ParamLocation where
11611052 toJSON = genericToJSON (jsonPrefix "Param")
11621053
@@ -1169,6 +1060,9 @@ instance ToJSON Contact where
11691060instance ToJSON License where
11701061 toJSON = genericToJSON (jsonPrefix "License")
11711062
1063+instance ToJSON Server where
1064+ toJSON = genericToJSON (jsonPrefix "Server")
1065+
11721066instance ToJSON ServerVariable where
11731067 toJSON = genericToJSON (jsonPrefix "ServerVariable")
11741068
@@ -1178,6 +1072,9 @@ instance ToJSON ApiKeyLocation where
11781072instance ToJSON ApiKeyParams where
11791073 toJSON = genericToJSON (jsonPrefix "apiKey")
11801074
1075+instance ToJSON Scheme where
1076+ toJSON = genericToJSON (jsonPrefix "")
1077+
11811078instance ToJSON Tag where
11821079 toJSON = genericToJSON (jsonPrefix "Tag")
11831080
@@ -1187,31 +1084,10 @@ instance ToJSON ExternalDocs where
11871084instance ToJSON Xml where
11881085 toJSON = genericToJSON (jsonPrefix "Xml")
11891086
1190−instance ToJSON Discriminator where
1191− toJSON = genericToJSON (jsonPrefix "Discriminator")
1192−
1193−instance ToJSON OAuth2ImplicitFlow where
1194− toJSON = genericToJSON (jsonPrefix "OAuth2ImplicitFlow")
1195−
1196−instance ToJSON OAuth2PasswordFlow where
1197− toJSON = genericToJSON (jsonPrefix "OAuth2PasswordFlow")
1198−
1199−instance ToJSON OAuth2ClientCredentialsFlow where
1200− toJSON = genericToJSON (jsonPrefix "OAuth2ClientCredentialsFlow")
1201−
1202−instance ToJSON OAuth2AuthorizationCodeFlow where
1203− toJSON = genericToJSON (jsonPrefix "OAuth2AuthorizationCodeFlow")
1204−
12051087-- =======================================================================
12061088-- Simple Generic-based FromJSON instances
12071089-- =======================================================================
12081090
1209−instance FromJSON Style where
1210− parseJSON = genericParseJSON (jsonPrefix "Style")
1211−
1212−instance FromJSON OpenApiType where
1213− parseJSON = genericParseJSON (jsonPrefix "Swagger")
1214−
12151091instance FromJSON ParamLocation where
12161092 parseJSON = genericParseJSON (jsonPrefix "Param")
12171093
@@ -1224,6 +1100,9 @@ instance FromJSON Contact where
12241100instance FromJSON License where
12251101 parseJSON = genericParseJSON (jsonPrefix "License")
12261102
1103+instance FromJSON Server where
1104+ parseJSON = genericParseJSON (jsonPrefix "Server")
1105+
12271106instance FromJSON ServerVariable where
12281107 parseJSON = genericParseJSON (jsonPrefix "ServerVariable")
12291108
@@ -1233,90 +1112,62 @@ instance FromJSON ApiKeyLocation where
12331112instance FromJSON ApiKeyParams where
12341113 parseJSON = genericParseJSON (jsonPrefix "apiKey")
12351114
1115+instance FromJSON Scheme where
1116+ parseJSON = genericParseJSON (jsonPrefix "")
1117+
12361118instance FromJSON Tag where
12371119 parseJSON = genericParseJSON (jsonPrefix "Tag")
12381120
12391121instance FromJSON ExternalDocs where
12401122 parseJSON = genericParseJSON (jsonPrefix "ExternalDocs")
12411123
1242−instance FromJSON Discriminator where
1243− parseJSON = genericParseJSON (jsonPrefix "Discriminator")
1244−
1245−instance FromJSON OAuth2ImplicitFlow where
1246− parseJSON = genericParseJSON (jsonPrefix "OAuth2ImplicitFlow")
1247−
1248−instance FromJSON OAuth2PasswordFlow where
1249− parseJSON = genericParseJSON (jsonPrefix "OAuth2PasswordFlow")
1250−
1251−instance FromJSON OAuth2ClientCredentialsFlow where
1252− parseJSON = genericParseJSON (jsonPrefix "OAuth2ClientCredentialsFlow")
1253−
1254−instance FromJSON OAuth2AuthorizationCodeFlow where
1255− parseJSON = genericParseJSON (jsonPrefix "OAuth2AuthorizationCodeFlow")
1256−
12571124-- =======================================================================
12581125-- Manual ToJSON instances
12591126-- =======================================================================
12601127
1261−instance ToJSON MediaType where
1262− toJSON = toJSON . show
1263− toEncoding = toEncoding . show
1264−
1265−instance ToJSONKey MediaType where
1266− toJSONKey = JSON.toJSONKeyText (Text.pack . show)
1267−
1268−instance (Eq p, ToJSON p, AesonDefaultValue p) => ToJSON (OAuth2Flow p) where
1269− toJSON = sopSwaggerGenericToJSON
1270− toEncoding = sopSwaggerGenericToEncoding
1271−
1272−instance ToJSON OAuth2Flows where
1128+instance ToJSON OAuth2Flow where
1129+ toJSON (OAuth2Implicit authUrl) = object
1130+ [ "flow" .= ("implicit" :: Text)
1131+ , "authorizationUrl" .= authUrl ]
1132+ toJSON (OAuth2Password tokenUrl) = object
1133+ [ "flow" .= ("password" :: Text)
1134+ , "tokenUrl" .= tokenUrl ]
1135+ toJSON (OAuth2Application tokenUrl) = object
1136+ [ "flow" .= ("application" :: Text)
1137+ , "tokenUrl" .= tokenUrl ]
1138+ toJSON (OAuth2AccessCode authUrl tokenUrl) = object
1139+ [ "flow" .= ("accessCode" :: Text)
1140+ , "authorizationUrl" .= authUrl
1141+ , "tokenUrl" .= tokenUrl ]
1142+
1143+instance ToJSON OAuth2Params where
12731144 toJSON = sopSwaggerGenericToJSON
12741145 toEncoding = sopSwaggerGenericToEncoding
12751146
12761147instance ToJSON SecuritySchemeType where
1277− toJSON (SecuritySchemeHttp ty) = case ty of
1278− HttpSchemeBearer mFmt ->
1279− object $ [ "type" .= ("http" :: Text)
1280− , "scheme" .= ("bearer" :: Text)
1281− ] <> maybe [] (\t -> ["bearerFormat" .= t]) mFmt
1282− HttpSchemeBasic ->
1283− object [ "type" .= ("http" :: Text)
1284− , "scheme" .= ("basic" :: Text)
1285− ]
1286− HttpSchemeCustom t ->
1287− object [ "type" .= ("http" :: Text)
1288− , "scheme" .= t
1289− ]
1148+ toJSON SecuritySchemeHttp
1149+ = object [ "type" .= ("http" :: Text) ]
12901150 toJSON (SecuritySchemeApiKey params)
12911151 = toJSON params
12921152 <+> object [ "type" .= ("apiKey" :: Text) ]
1293− toJSON (SecuritySchemeOAuth2 params) = object
1294− [ "type" .= ("oauth2" :: Text)
1295− , "flows" .= toJSON params
1296− ]
1297− toJSON (SecuritySchemeOpenIdConnect url) = object
1298− [ "type" .= ("openIdConnect" :: Text)
1299− , "openIdConnectUrl" .= url
1300− ]
1153+ toJSON (SecuritySchemeOAuth2 params)
1154+ = toJSON params
1155+ <+> object [ "type" .= ("oauth2" :: Text) ]
13011156
1302−instance ToJSON OpenApi where
1157+instance ToJSON Swagger where
13031158 toJSON a = sopSwaggerGenericToJSON a &
1304− if InsOrdHashMap.null (_openApiPaths a)
1159+ if InsOrdHashMap.null (_swaggerPaths a)
13051160 then (<+> object ["paths" .= object []])
13061161 else id
13071162 toEncoding = sopSwaggerGenericToEncoding
13081163
1309−instance ToJSON Server where
1310− toJSON = sopSwaggerGenericToJSON
1311− toEncoding = sopSwaggerGenericToEncoding
1312−
13131164instance ToJSON SecurityScheme where
13141165 toJSON = sopSwaggerGenericToJSON
13151166 toEncoding = sopSwaggerGenericToEncoding
13161167
13171168instance ToJSON Schema where
1318− toJSON = sopSwaggerGenericToJSONWithOpts $
1319− mkSwaggerAesonOptions "schema" & saoSubObject ?~ "items"
1169+ toJSON = sopSwaggerGenericToJSON
1170+ toEncoding = sopSwaggerGenericToEncoding
13201171
13211172instance ToJSON Header where
13221173 toJSON = sopSwaggerGenericToJSON
@@ -1325,26 +1176,31 @@ instance ToJSON Header where
13251176-- | As for nullary schema for 0-arity type constructors, see
13261177-- <https://github.com/GetShopTV/swagger2/issues/167>.
13271178--
1328−-- >>> BSL.putStrLn $ encodePretty (OpenApiItemsArray [])
1329−-- {
1330−-- "example": [],
1331−-- "items": {},
1332−-- "maxItems": 0
1333−-- }
1179+-- >>> encode (SwaggerItemsArray [])
1180+-- "{\"example\":[],\"items\":{},\"maxItems\":0}"
13341181--
1335−instance ToJSON OpenApiItems where
1336− toJSON (OpenApiItemsObject x) = object [ "items" .= x ]
1337− toJSON (OpenApiItemsArray []) = object
1182+instance ToJSON (ParamSchema t) => ToJSON (SwaggerItems t) where
1183+ toJSON (SwaggerItemsPrimitive fmt schema) = object
1184+ [ "collectionFormat" .= fmt
1185+ , "items" .= schema ]
1186+ toJSON (SwaggerItemsObject x) = object [ "items" .= x ]
1187+ toJSON (SwaggerItemsArray []) = object
13381188 [ "items" .= object []
13391189 , "maxItems" .= (0 :: Int)
13401190 , "example" .= Array mempty
13411191 ]
1342− toJSON (OpenApiItemsArray x) = object [ "items" .= x ]
1192+ toJSON (SwaggerItemsArray x) = object [ "items" .= x ]
13431193
13441194instance ToJSON Components where
13451195 toJSON = sopSwaggerGenericToJSON
13461196 toEncoding = sopSwaggerGenericToEncoding
13471197
1198+instance ToJSON Host where
1199+ toJSON (Host host mport) = toJSON $
1200+ case mport of
1201+ Nothing -> host
1202+ Just port -> host ++ ":" ++ show port
1203+
13481204instance ToJSON MimeList where
13491205 toJSON (MimeList xs) = toJSON (map show xs)
13501206
@@ -1352,6 +1208,14 @@ instance ToJSON Param where
13521208 toJSON = sopSwaggerGenericToJSON
13531209 toEncoding = sopSwaggerGenericToEncoding
13541210
1211+instance ToJSON ParamAnySchema where
1212+ toJSON (ParamBody s) = object [ "in" .= ("body" :: Text), "schema" .= s ]
1213+ toJSON (ParamOther s) = toJSON s
1214+
1215+instance ToJSON ParamOtherSchema where
1216+ toJSON = sopSwaggerGenericToJSON
1217+ toEncoding = sopSwaggerGenericToEncoding
1218+
13551219instance ToJSON Responses where
13561220 toJSON = sopSwaggerGenericToJSON
13571221 toEncoding = sopSwaggerGenericToEncoding
@@ -1377,16 +1241,7 @@ instance ToJSON MediaTypeObject where
13771241 toEncoding = sopSwaggerGenericToEncoding
13781242
13791243instance ToJSON Example where
1380− toJSON = sopSwaggerGenericToJSON
1381− toEncoding = sopSwaggerGenericToEncoding
1382−
1383−instance ToJSON Encoding where
1384− toJSON = sopSwaggerGenericToJSON
1385− toEncoding = sopSwaggerGenericToEncoding
1386−
1387−instance ToJSON Link where
1388− toJSON = sopSwaggerGenericToJSON
1389− toEncoding = sopSwaggerGenericToEncoding
1244+ toJSON = toJSON . Map.mapKeys show . getExample
13901245
13911246instance ToJSON SecurityDefinitions where
13921247 toJSON (SecurityDefinitions sd) = toJSON sd
@@ -1398,63 +1253,69 @@ referencedToJSON :: ToJSON a => Text -> Referenced a -> Value
13981253referencedToJSON prefix (Ref (Reference ref)) = object [ "$ref" .= (prefix <> ref) ]
13991254referencedToJSON _ (Inline x) = toJSON x
14001255
1401−instance ToJSON (Referenced Schema) where toJSON = referencedToJSON "#/components/schemas/"
1402−instance ToJSON (Referenced Param) where toJSON = referencedToJSON "#/components/parameters/"
1403−instance ToJSON (Referenced Response) where toJSON = referencedToJSON "#/components/responses/"
1404−instance ToJSON (Referenced RequestBody) where toJSON = referencedToJSON "#/components/requestBodies/"
1405−instance ToJSON (Referenced Example) where toJSON = referencedToJSON "#/components/examples/"
1406−instance ToJSON (Referenced Header) where toJSON = referencedToJSON "#/components/headers/"
1407−instance ToJSON (Referenced Link) where toJSON = referencedToJSON "#/components/links/"
1408−instance ToJSON (Referenced Callback) where toJSON = referencedToJSON "#/components/callbacks/"
1256+-- FIXME this stuff
1257+instance ToJSON (Referenced Schema) where toJSON = referencedToJSON "#/definitions/"
1258+instance ToJSON (Referenced Param) where toJSON = referencedToJSON "#/parameters/"
1259+instance ToJSON (Referenced Response) where toJSON = referencedToJSON "#/responses/"
1260+instance ToJSON (Referenced RequestBody) where toJSON = referencedToJSON "#/!!!!/"
1261+
1262+instance ToJSON (SwaggerType t) where
1263+ toJSON SwaggerArray = "array"
1264+ toJSON SwaggerString = "string"
1265+ toJSON SwaggerInteger = "integer"
1266+ toJSON SwaggerNumber = "number"
1267+ toJSON SwaggerBoolean = "boolean"
1268+ toJSON SwaggerFile = "file"
1269+ toJSON SwaggerNull = "null"
1270+ toJSON SwaggerObject = "object"
1271+
1272+instance ToJSON (CollectionFormat t) where
1273+ toJSON CollectionCSV = "csv"
1274+ toJSON CollectionSSV = "ssv"
1275+ toJSON CollectionTSV = "tsv"
1276+ toJSON CollectionPipes = "pipes"
1277+ toJSON CollectionMulti = "multi"
1278+
1279+instance ToJSON (ParamSchema k) where
1280+ -- TODO: this is a bit fishy, why we need sub object only in `ToJSON`?
1281+ toJSON = sopSwaggerGenericToJSONWithOpts $
1282+ mkSwaggerAesonOptions "paramSchema" & saoSubObject ?~ "items"
14091283
14101284instance ToJSON AdditionalProperties where
14111285 toJSON (AdditionalPropertiesAllowed b) = toJSON b
14121286 toJSON (AdditionalPropertiesSchema s) = toJSON s
14131287
1414−instance ToJSON ExpressionOrValue where
1415− toJSON (Expression expr) = toJSON expr
1416− toJSON (Value val) = toJSON val
1417−
1418−instance ToJSON Callback where
1419− toJSON (Callback ps) = toJSON ps
1420−
14211288-- =======================================================================
14221289-- Manual FromJSON instances
14231290-- =======================================================================
14241291
1425−instance FromJSON MediaType where
1426− parseJSON = withText "MediaType" $ \str ->
1427− maybe (fail $ "Invalid media type literal " <> Text.unpack str) pure $ parseAccept $ encodeUtf8 str
1428−
1429−instance FromJSONKey MediaType where
1430− fromJSONKey = FromJSONKeyTextParser (parseJSON . String)
1431−
1432−instance (Eq p, FromJSON p, AesonDefaultValue p) => FromJSON (OAuth2Flow p) where
1433− parseJSON = sopSwaggerGenericParseJSON
1292+instance FromJSON OAuth2Flow where
1293+ parseJSON (Object o) = do
1294+ (flow :: Text) <- o .: "flow"
1295+ case flow of
1296+ "implicit" -> OAuth2Implicit <$> o .: "authorizationUrl"
1297+ "password" -> OAuth2Password <$> o .: "tokenUrl"
1298+ "application" -> OAuth2Application <$> o .: "tokenUrl"
1299+ "accessCode" -> OAuth2AccessCode
1300+ <$> o .: "authorizationUrl"
1301+ <*> o .: "tokenUrl"
1302+ _ -> empty
1303+ parseJSON _ = empty
14341304
1435−instance FromJSON OAuth2Flows where
1305+instance FromJSON OAuth2Params where
14361306 parseJSON = sopSwaggerGenericParseJSON
14371307
14381308instance FromJSON SecuritySchemeType where
14391309 parseJSON js@(Object o) = do
14401310 (t :: Text) <- o .: "type"
14411311 case t of
1442− "http" -> do
1443− scheme <- o .: "scheme"
1444− SecuritySchemeHttp <$> case scheme of
1445− "bearer" -> HttpSchemeBearer <$> (o .:! "bearerFormat")
1446− "basic" -> pure HttpSchemeBasic
1447− t -> pure $ HttpSchemeCustom t
1312+ "http" -> pure SecuritySchemeHttp
14481313 "apiKey" -> SecuritySchemeApiKey <$> parseJSON js
1449− "oauth2" -> SecuritySchemeOAuth2 <$> (o .: "flows")
1450− "openIdConnect" -> SecuritySchemeOpenIdConnect <$> (o .: "openIdConnectUrl")
1314+ "oauth2" -> SecuritySchemeOAuth2 <$> parseJSON js
14511315 _ -> empty
14521316 parseJSON _ = empty
14531317
1454−instance FromJSON OpenApi where
1455− parseJSON = sopSwaggerGenericParseJSON
1456−
1457−instance FromJSON Server where
1318+instance FromJSON Swagger where
14581319 parseJSON = sopSwaggerGenericParseJSON
14591320
14601321instance FromJSON SecurityScheme where
@@ -1463,40 +1324,84 @@ instance FromJSON SecurityScheme where
14631324instance FromJSON Schema where
14641325 parseJSON = fmap nullaryCleanup . sopSwaggerGenericParseJSON
14651326 where nullaryCleanup :: Schema -> Schema
1466− nullaryCleanup s =
1467− if _schemaItems s == Just (OpenApiItemsArray [])
1327+ nullaryCleanup s@Schema{_schemaParamSchema=ps} =
1328+ if _paramSchemaItems ps == Just (SwaggerItemsArray [])
14681329 then s { _schemaExample = Nothing
1469− , _schemaMaxItems = Nothing
1470− }
1330+ , _schemaParamSchema = ps { _paramSchemaMaxItems = Nothing } }
14711331 else s
14721332
14731333instance FromJSON Header where
14741334 parseJSON = sopSwaggerGenericParseJSON
14751335
1476−instance FromJSON OpenApiItems where
1336+instance (FromJSON (CollectionFormat ('SwaggerKindNormal t)), FromJSON (ParamSchema ('SwaggerKindNormal t))) => FromJSON (SwaggerItems ('SwaggerKindNormal t)) where
1337+ parseJSON = withObject "SwaggerItemsPrimitive" $ \o -> SwaggerItemsPrimitive
1338+ <$> o .:? "collectionFormat"
1339+ <*> (o .: "items" >>= parseJSON)
1340+
1341+instance FromJSON (SwaggerItems 'SwaggerKindParamOtherSchema) where
1342+ parseJSON = withObject "SwaggerItemsPrimitive" $ \o -> SwaggerItemsPrimitive
1343+ <$> o .:? "collectionFormat"
1344+ <*> ((o .: "items" >>= parseJSON) <|> fail ("foo" ++ show o))
1345+
1346+-- |
1347+--
1348+-- >>> decode "{}" :: Maybe (SwaggerItems 'SwaggerKindSchema)
1349+-- Just (SwaggerItemsArray [])
1350+--
1351+-- >>> eitherDecode "{\"$ref\":\"#/definitions/example\"}" :: Either String (SwaggerItems 'SwaggerKindSchema)
1352+-- Right (SwaggerItemsObject (Ref (Reference {getReference = "example"})))
1353+--
1354+-- >>> eitherDecode "[{\"$ref\":\"#/definitions/example\"}]" :: Either String (SwaggerItems 'SwaggerKindSchema)
1355+-- Right (SwaggerItemsArray [Ref (Reference {getReference = "example"})])
1356+--
1357+instance FromJSON (SwaggerItems 'SwaggerKindSchema) where
14771358 parseJSON js@(Object obj)
1478− | null obj = pure $ OpenApiItemsArray [] -- Nullary schema.
1479− | otherwise = OpenApiItemsObject <$> parseJSON js
1480− parseJSON js@(Array _) = OpenApiItemsArray <$> parseJSON js
1359+ | null obj = pure $ SwaggerItemsArray [] -- Nullary schema.
1360+ | otherwise = SwaggerItemsObject <$> parseJSON js
1361+ parseJSON js@(Array _) = SwaggerItemsArray <$> parseJSON js
14811362 parseJSON _ = empty
14821363
14831364instance FromJSON Components where
14841365 parseJSON = sopSwaggerGenericParseJSON
14851366
1367+instance FromJSON Host where
1368+ parseJSON (String s) = case map Text.unpack $ Text.split (== ':') s of
1369+ [host] -> return $ Host host Nothing
1370+ [host, port] -> case readMaybe port of
1371+ Nothing -> fail $ "Invalid port `" ++ port ++ "'"
1372+ Just p -> return $ Host host (Just (fromInteger p))
1373+ _ -> fail $ "Invalid host `" ++ Text.unpack s ++ "'"
1374+ parseJSON _ = empty
1375+
14861376instance FromJSON MimeList where
1487− parseJSON js = MimeList . map fromString <$> parseJSON js
1377+ parseJSON js = (MimeList . map fromString) <$> parseJSON js
14881378
14891379instance FromJSON Param where
14901380 parseJSON = sopSwaggerGenericParseJSON
14911381
1382+instance FromJSON ParamAnySchema where
1383+ parseJSON js@(Object o) = do
1384+ (i :: Text) <- o .: "in"
1385+ case i of
1386+ "body" -> do
1387+ schema <- o .: "schema"
1388+ ParamBody <$> parseJSON schema
1389+ _ -> ParamOther <$> parseJSON js
1390+ parseJSON _ = empty
1391+
1392+instance FromJSON ParamOtherSchema where
1393+ parseJSON = sopSwaggerGenericParseJSON
1394+
14921395instance FromJSON Responses where
14931396 parseJSON (Object o) = Responses
14941397 <$> o .:? "default"
1495− <*> parseJSON (Object (deleteKey "default" o))
1398+ <*> (parseJSON (Object (HashMap.delete "default" o)))
14961399 parseJSON _ = empty
14971400
14981401instance FromJSON Example where
1499− parseJSON = sopSwaggerGenericParseJSON
1402+ parseJSON js = do
1403+ m <- parseJSON js
1404+ pure $ Example (Map.mapKeys fromString m)
15001405
15011406instance FromJSON Response where
15021407 parseJSON = sopSwaggerGenericParseJSON
@@ -1507,20 +1412,14 @@ instance FromJSON Operation where
15071412instance FromJSON PathItem where
15081413 parseJSON = sopSwaggerGenericParseJSON
15091414
1510−instance FromJSON SecurityDefinitions where
1511− parseJSON js = SecurityDefinitions <$> parseJSON js
1512−
15131415instance FromJSON RequestBody where
15141416 parseJSON = sopSwaggerGenericParseJSON
15151417
15161418instance FromJSON MediaTypeObject where
15171419 parseJSON = sopSwaggerGenericParseJSON
15181420
1519−instance FromJSON Encoding where
1520− parseJSON = sopSwaggerGenericParseJSON
1521−
1522−instance FromJSON Link where
1523− parseJSON = sopSwaggerGenericParseJSON
1421+instance FromJSON SecurityDefinitions where
1422+ parseJSON js = SecurityDefinitions <$> parseJSON js
15241423
15251424instance FromJSON Reference where
15261425 parseJSON (Object o) = Reference <$> o .: "$ref"
@@ -1539,44 +1438,57 @@ referencedParseJSON prefix js@(Object o) = do
15391438 Just suffix -> pure (Reference suffix)
15401439referencedParseJSON _ _ = fail "referenceParseJSON: not an object"
15411440
1542−instance FromJSON (Referenced Schema) where parseJSON = referencedParseJSON "#/components/schemas/"
1543−instance FromJSON (Referenced Param) where parseJSON = referencedParseJSON "#/components/parameters/"
1544−instance FromJSON (Referenced Response) where parseJSON = referencedParseJSON "#/components/responses/"
1545−instance FromJSON (Referenced RequestBody) where parseJSON = referencedParseJSON "#/components/requestBodies/"
1546−instance FromJSON (Referenced Example) where parseJSON = referencedParseJSON "#/components/examples/"
1547−instance FromJSON (Referenced Header) where parseJSON = referencedParseJSON "#/components/headers/"
1548−instance FromJSON (Referenced Link) where parseJSON = referencedParseJSON "#/components/links/"
1549−instance FromJSON (Referenced Callback) where parseJSON = referencedParseJSON "#/components/callbacks/"
1441+-- FIXME this stuff
1442+instance FromJSON (Referenced Schema) where parseJSON = referencedParseJSON "#/definitions/"
1443+instance FromJSON (Referenced Param) where parseJSON = referencedParseJSON "#/parameters/"
1444+instance FromJSON (Referenced Response) where parseJSON = referencedParseJSON "#/responses/"
1445+instance FromJSON (Referenced RequestBody) where parseJSON = referencedParseJSON "#/!!!!/"
15501446
15511447instance FromJSON Xml where
15521448 parseJSON = genericParseJSON (jsonPrefix "xml")
15531449
1450+instance FromJSON (SwaggerType 'SwaggerKindSchema) where
1451+ parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray, SwaggerNull, SwaggerObject]
1452+
1453+instance FromJSON (SwaggerType 'SwaggerKindParamOtherSchema) where
1454+ parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray, SwaggerFile]
1455+
1456+instance FromJSON (SwaggerType ('SwaggerKindNormal t)) where
1457+ parseJSON = parseOneOf [SwaggerString, SwaggerInteger, SwaggerNumber, SwaggerBoolean, SwaggerArray]
1458+
1459+instance FromJSON (CollectionFormat ('SwaggerKindNormal t)) where
1460+ parseJSON = parseOneOf [CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes]
1461+
1462+-- NOTE: There aren't collections of 'Schema'
1463+--instance FromJSON (CollectionFormat (SwaggerKindSchema)) where
1464+-- parseJSON = parseOneOf [CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes]
1465+
1466+instance FromJSON (CollectionFormat 'SwaggerKindParamOtherSchema) where
1467+ parseJSON = parseOneOf [CollectionCSV, CollectionSSV, CollectionTSV, CollectionPipes, CollectionMulti]
1468+
1469+instance (FromJSON (SwaggerType ('SwaggerKindNormal t)), FromJSON (SwaggerItems ('SwaggerKindNormal t))) => FromJSON (ParamSchema ('SwaggerKindNormal t)) where
1470+ parseJSON = sopSwaggerGenericParseJSON
1471+instance FromJSON (ParamSchema 'SwaggerKindParamOtherSchema) where
1472+ parseJSON = sopSwaggerGenericParseJSON
1473+instance FromJSON (ParamSchema 'SwaggerKindSchema) where
1474+ parseJSON = sopSwaggerGenericParseJSON
1475+
15541476instance FromJSON AdditionalProperties where
15551477 parseJSON (Bool b) = pure $ AdditionalPropertiesAllowed b
15561478 parseJSON js = AdditionalPropertiesSchema <$> parseJSON js
15571479
1558−-- | All strings are parsed as expressions
1559−instance FromJSON ExpressionOrValue where
1560− parseJSON (String expr) = pure $ Expression expr
1561− parseJSON v = pure $ Value v
1562−
1563−instance FromJSON Callback where
1564− parseJSON = fmap Callback . parseJSON
1565−
1566−instance HasSwaggerAesonOptions Server where
1567− swaggerAesonOptions _ = mkSwaggerAesonOptions "server"
15681480instance HasSwaggerAesonOptions Components where
15691481 swaggerAesonOptions _ = mkSwaggerAesonOptions "components"
15701482instance HasSwaggerAesonOptions Header where
1571− swaggerAesonOptions _ = mkSwaggerAesonOptions "header"
1572−instance AesonDefaultValue p => HasSwaggerAesonOptions (OAuth2Flow p) where
1573− swaggerAesonOptions _ = mkSwaggerAesonOptions "oauth2" & saoSubObject ?~ "params"
1574−instance HasSwaggerAesonOptions OAuth2Flows where
1575− swaggerAesonOptions _ = mkSwaggerAesonOptions "oauth2Flows"
1483+ swaggerAesonOptions _ = mkSwaggerAesonOptions "header" & saoSubObject ?~ "paramSchema"
1484+instance HasSwaggerAesonOptions OAuth2Params where
1485+ swaggerAesonOptions _ = mkSwaggerAesonOptions "oauth2" & saoSubObject ?~ "flow"
15761486instance HasSwaggerAesonOptions Operation where
15771487 swaggerAesonOptions _ = mkSwaggerAesonOptions "operation"
15781488instance HasSwaggerAesonOptions Param where
1579− swaggerAesonOptions _ = mkSwaggerAesonOptions "param"
1489+ swaggerAesonOptions _ = mkSwaggerAesonOptions "param" & saoSubObject ?~ "schema"
1490+instance HasSwaggerAesonOptions ParamOtherSchema where
1491+ swaggerAesonOptions _ = mkSwaggerAesonOptions "paramOtherSchema" & saoSubObject ?~ "paramSchema"
15801492instance HasSwaggerAesonOptions PathItem where
15811493 swaggerAesonOptions _ = mkSwaggerAesonOptions "pathItem"
15821494instance HasSwaggerAesonOptions Response where
@@ -1584,36 +1496,32 @@ instance HasSwaggerAesonOptions Response where
15841496instance HasSwaggerAesonOptions RequestBody where
15851497 swaggerAesonOptions _ = mkSwaggerAesonOptions "requestBody"
15861498instance HasSwaggerAesonOptions MediaTypeObject where
1587− swaggerAesonOptions _ = mkSwaggerAesonOptions "mediaTypeObject"
1499+ swaggerAesonOptions _ = mkSwaggerAesonOptions "mediaType"
15881500instance HasSwaggerAesonOptions Responses where
15891501 swaggerAesonOptions _ = mkSwaggerAesonOptions "responses" & saoSubObject ?~ "responses"
15901502instance HasSwaggerAesonOptions SecurityScheme where
15911503 swaggerAesonOptions _ = mkSwaggerAesonOptions "securityScheme" & saoSubObject ?~ "type"
15921504instance HasSwaggerAesonOptions Schema where
15931505 swaggerAesonOptions _ = mkSwaggerAesonOptions "schema" & saoSubObject ?~ "paramSchema"
1594−instance HasSwaggerAesonOptions OpenApi where
1595− swaggerAesonOptions _ = mkSwaggerAesonOptions "swagger" & saoAdditionalPairs .~ [("openapi", "3.0.0")]
1596−instance HasSwaggerAesonOptions Example where
1597− swaggerAesonOptions _ = mkSwaggerAesonOptions "example"
1598−instance HasSwaggerAesonOptions Encoding where
1599− swaggerAesonOptions _ = mkSwaggerAesonOptions "encoding"
1506+instance HasSwaggerAesonOptions Swagger where
1507+ swaggerAesonOptions _ = mkSwaggerAesonOptions "swagger" & saoAdditionalPairs .~ [("openapi", "3.0")]
16001508
1601−instance HasSwaggerAesonOptions Link where
1602− swaggerAesonOptions _ = mkSwaggerAesonOptions "link"
1509+instance HasSwaggerAesonOptions (ParamSchema ('SwaggerKindNormal t)) where
1510+ swaggerAesonOptions _ = mkSwaggerAesonOptions "paramSchema" & saoSubObject ?~ "items"
1511+instance HasSwaggerAesonOptions (ParamSchema 'SwaggerKindParamOtherSchema) where
1512+ swaggerAesonOptions _ = mkSwaggerAesonOptions "paramSchema" & saoSubObject ?~ "items"
1513+-- NOTE: Schema doesn't have 'items' sub object!
1514+instance HasSwaggerAesonOptions (ParamSchema 'SwaggerKindSchema) where
1515+ swaggerAesonOptions _ = mkSwaggerAesonOptions "paramSchema"
16031516
1604−instance AesonDefaultValue Server
16051517instance AesonDefaultValue Components
1606−instance AesonDefaultValue OAuth2ImplicitFlow
1607−instance AesonDefaultValue OAuth2PasswordFlow
1608−instance AesonDefaultValue OAuth2ClientCredentialsFlow
1609−instance AesonDefaultValue OAuth2AuthorizationCodeFlow
1610−instance AesonDefaultValue p => AesonDefaultValue (OAuth2Flow p)
1518+instance AesonDefaultValue (ParamSchema s)
1519+instance AesonDefaultValue OAuth2Flow
16111520instance AesonDefaultValue Responses
1521+instance AesonDefaultValue ParamAnySchema
16121522instance AesonDefaultValue SecuritySchemeType
1613−instance AesonDefaultValue OpenApiType
1523+instance AesonDefaultValue (SwaggerType a)
16141524instance AesonDefaultValue MimeList where defaultValue = Just mempty
16151525instance AesonDefaultValue Info
16161526instance AesonDefaultValue ParamLocation
1617−instance AesonDefaultValue Link
1618−instance AesonDefaultValue SecurityDefinitions where
1619− defaultValue = Just mempty
1527+instance AesonDefaultValue SecurityDefinitions where defaultValue = Just $ SecurityDefinitions mempty