@@ -1,4 +1,4 @@
1−{-# LANGUAGE ConstraintKinds #-}
1+{-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-}
22{-# LANGUAGE CPP #-}
33{-# LANGUAGE DataKinds #-}
44{-# LANGUAGE DefaultSignatures #-}
@@ -14,54 +14,56 @@
1414{-# LANGUAGE TypeFamilies #-}
1515{-# LANGUAGE TypeOperators #-}
1616{-# LANGUAGE UndecidableInstances #-}
17−#include "overlapping-compat.h"
1817module Web.Internal.FormUrlEncoded where
1918
20−import Prelude ()
21−import Prelude.Compat
19+#if __GLASGOW_HASKELL__ < 710
20+import Control.Applicative
21+import Data.Traversable
22+#endif
23+
24+#if __GLASGOW_HASKELL__ < 800
25+import GHC.Exts (IsList (..))
26+#else
27+import GHC.Exts (IsList (..), Constraint)
28+import GHC.TypeLits
29+#endif
2230
23−import Control.Applicative (Const(Const))
2431import Control.Arrow ((***))
2532import Control.Monad ((<=<))
26−import Data.ByteString.Builder (shortByteString, toLazyByteString)
33+import Data.ByteString.Builder (toLazyByteString, shortByteString)
2734import qualified Data.ByteString.Lazy as BSL
2835import qualified Data.ByteString.Lazy.Char8 as BSL8
29−import Data.Coerce (coerce)
3036import qualified Data.Foldable as F
31−import Data.Functor.Identity (Identity(Identity))
3237import Data.Hashable (Hashable)
3338import Data.HashMap.Strict (HashMap)
3439import qualified Data.HashMap.Strict as HashMap
35−import Data.Int (Int16, Int32, Int64, Int8)
40+import Data.Int
3641import Data.IntMap (IntMap)
3742import qualified Data.IntMap as IntMap
38−import Data.List (intersperse, sortBy)
43+import Data.List (intersperse)
3944import Data.Map (Map)
4045import qualified Data.Map as Map
41−import Data.Monoid (All (..), Any (..), Dual (..),
42− Product (..), Sum (..))
43−import Data.Ord (comparing)
44−import Data.Proxy (Proxy (..))
45−import Data.Semigroup (Semigroup (..))
46−import qualified Data.Semigroup as Semi
47−import Data.Tagged (Tagged (..))
46+import Data.Monoid
47+
4848import Data.Text (Text)
4949import qualified Data.Text as Text
50−import qualified Data.Text.Encoding as Text
51−import Data.Text.Encoding.Error (lenientDecode)
5250import qualified Data.Text.Lazy as Lazy
53−import Data.Time.Compat (Day, LocalTime, NominalDiffTime,
54− UTCTime, ZonedTime)
55−import Data.Time.Calendar.Month.Compat (Month)
56−import Data.Time.Calendar.Quarter.Compat (Quarter, QuarterOfYear (..))
57−import Data.Void (Void)
58−import Data.Word (Word16, Word32, Word64, Word8)
59−import GHC.Exts (Constraint, IsList (..))
51+import Data.Text.Encoding as Text
52+import Data.Text.Encoding.Error (lenientDecode)
53+
54+import Data.Time
55+import Data.Proxy
56+import Data.Word
57+
58+#if MIN_VERSION_base(4,8,0)
59+import Data.Void
60+import Numeric.Natural
61+#endif
62+
6063import GHC.Generics
61−import GHC.TypeLits
62−import Network.HTTP.Types.URI (urlDecode, urlEncodeBuilder)
63−import Numeric.Natural (Natural)
64−import Web.Internal.HttpApiData
64+import URI.ByteString (urlEncodeQuery, urlDecodeQuery)
65+
66+import Web.Internal.HttpApiData
6567
6668-- $setup
6769-- >>> :set -XDeriveGeneric
@@ -70,20 +72,11 @@ import Web.Internal.HttpApiData
7072-- >>> :set -XFlexibleContexts
7173-- >>> :set -XScopedTypeVariables
7274-- >>> :set -XTypeFamilies
73−-- >>> import Data.Char (toLower)
74−--
75+-- >>> import Data.Either (isLeft)
76+-- >>> import Data.List (sort)
7577-- >>> data Person = Person { name :: String, age :: Int } deriving (Show, Generic)
7678-- >>> instance ToForm Person
7779-- >>> instance FromForm Person
78−--
79−-- >>> data Post = Post { title :: String, subtitle :: Maybe String, comments :: [String]} deriving (Generic, Show)
80−-- >>> instance ToForm Post
81−-- >>> instance FromForm Post
82−--
83−-- >>> data Project = Project { projectName :: String, projectSize :: Int } deriving (Generic, Show)
84−-- >>> let myOptions = FormOptions { fieldLabelModifier = map toLower . drop (length ("project" :: String)) }
85−-- >>> instance ToForm Project where toForm = genericToForm myOptions
86−-- >>> instance FromForm Project where fromForm = genericFromForm myOptions
8780
8881-- | Typeclass for types that can be used as keys in a 'Form'-like container (like 'Map').
8982class ToFormKey k where
@@ -115,9 +108,6 @@ instance ToFormKey LocalTime where toFormKey = toQueryParam
115108instance ToFormKey ZonedTime where toFormKey = toQueryParam
116109instance ToFormKey UTCTime where toFormKey = toQueryParam
117110instance ToFormKey NominalDiffTime where toFormKey = toQueryParam
118−instance ToFormKey Quarter where toFormKey = toQueryParam
119−instance ToFormKey QuarterOfYear where toFormKey = toQueryParam
120−instance ToFormKey Month where toFormKey = toQueryParam
121111
122112instance ToFormKey String where toFormKey = toQueryParam
123113instance ToFormKey Text where toFormKey = toQueryParam
@@ -126,26 +116,14 @@ instance ToFormKey Lazy.Text where toFormKey = toQueryParam
126116instance ToFormKey All where toFormKey = toQueryParam
127117instance ToFormKey Any where toFormKey = toQueryParam
128118
129−instance ToFormKey a => ToFormKey (Dual a) where toFormKey = coerce (toFormKey :: a -> Text)
130−instance ToFormKey a => ToFormKey (Sum a) where toFormKey = coerce (toFormKey :: a -> Text)
131−instance ToFormKey a => ToFormKey (Product a) where toFormKey = coerce (toFormKey :: a -> Text)
132−
133−instance ToFormKey a => ToFormKey (Semi.Min a) where toFormKey = coerce (toFormKey :: a -> Text)
134−instance ToFormKey a => ToFormKey (Semi.Max a) where toFormKey = coerce (toFormKey :: a -> Text)
135−instance ToFormKey a => ToFormKey (Semi.First a) where toFormKey = coerce (toFormKey :: a -> Text)
136−instance ToFormKey a => ToFormKey (Semi.Last a) where toFormKey = coerce (toFormKey :: a -> Text)
137−
138−instance ToFormKey a => ToFormKey (Tagged b a) where toFormKey = coerce (toFormKey :: a -> Text)
139−
140−-- | @since 0.4.2
141−instance ToFormKey a => ToFormKey (Identity a) where toFormKey = coerce (toFormKey :: a -> Text)
142−
143−-- | @since 0.4.2
144−instance ToFormKey a => ToFormKey (Const a b) where
145− toFormKey = coerce (toFormKey :: a -> Text)
119+instance ToFormKey a => ToFormKey (Dual a) where toFormKey = toFormKey . getDual
120+instance ToFormKey a => ToFormKey (Sum a) where toFormKey = toFormKey . getSum
121+instance ToFormKey a => ToFormKey (Product a) where toFormKey = toFormKey . getProduct
146122
123+#if MIN_VERSION_base(4,8,0)
147124instance ToFormKey Void where toFormKey = toQueryParam
148125instance ToFormKey Natural where toFormKey = toQueryParam
126+#endif
149127
150128-- | Typeclass for types that can be parsed from keys of a 'Form'. This is the reverse of 'ToFormKey'.
151129class FromFormKey k where
@@ -177,9 +155,6 @@ instance FromFormKey LocalTime where parseFormKey = parseQueryParam
177155instance FromFormKey ZonedTime where parseFormKey = parseQueryParam
178156instance FromFormKey UTCTime where parseFormKey = parseQueryParam
179157instance FromFormKey NominalDiffTime where parseFormKey = parseQueryParam
180−instance FromFormKey Quarter where parseFormKey = parseQueryParam
181−instance FromFormKey QuarterOfYear where parseFormKey = parseQueryParam
182−instance FromFormKey Month where parseFormKey = parseQueryParam
183158
184159instance FromFormKey String where parseFormKey = parseQueryParam
185160instance FromFormKey Text where parseFormKey = parseQueryParam
@@ -188,48 +163,30 @@ instance FromFormKey Lazy.Text where parseFormKey = parseQueryParam
188163instance FromFormKey All where parseFormKey = parseQueryParam
189164instance FromFormKey Any where parseFormKey = parseQueryParam
190165
191−instance FromFormKey a => FromFormKey (Dual a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
192−instance FromFormKey a => FromFormKey (Sum a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
193−instance FromFormKey a => FromFormKey (Product a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
194−
195−instance FromFormKey a => FromFormKey (Semi.Min a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
196−instance FromFormKey a => FromFormKey (Semi.Max a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
197−instance FromFormKey a => FromFormKey (Semi.First a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
198−instance FromFormKey a => FromFormKey (Semi.Last a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
199−
200−instance FromFormKey a => FromFormKey (Tagged b a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
201−
202−-- | @since 0.4.2
203−instance FromFormKey a => FromFormKey (Identity a) where parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
204−
205−-- | @since 0.4.2
206−instance FromFormKey a => FromFormKey (Const a b) where
207− parseFormKey = coerce (parseFormKey :: Text -> Either Text a)
166+instance FromFormKey a => FromFormKey (Dual a) where parseFormKey = fmap Dual . parseFormKey
167+instance FromFormKey a => FromFormKey (Sum a) where parseFormKey = fmap Sum . parseFormKey
168+instance FromFormKey a => FromFormKey (Product a) where parseFormKey = fmap Product . parseFormKey
208169
170+#if MIN_VERSION_base(4,8,0)
209171instance FromFormKey Void where parseFormKey = parseQueryParam
210172instance FromFormKey Natural where parseFormKey = parseQueryParam
173+#endif
211174
212175-- | The contents of a form, not yet URL-encoded.
213176--
214177-- 'Form' can be URL-encoded with 'urlEncodeForm' and URL-decoded with 'urlDecodeForm'.
215178newtype Form = Form { unForm :: HashMap Text [Text] }
216− deriving (Eq, Read, Generic, Semigroup, Monoid)
179+ deriving (Eq, Read, Generic, Monoid)
217180
218181instance Show Form where
219182 showsPrec d form = showParen (d > 10) $
220− showString "fromList " . shows (toListStable form)
183+ showString "fromList " . shows (toList form)
221184
222−-- | _NOTE:_ 'toList' is unstable and may result in different key order (but not values).
223−-- For a stable conversion use 'toListStable'.
224185instance IsList Form where
225186 type Item Form = (Text, Text)
226187 fromList = Form . HashMap.fromListWith (flip (<>)) . fmap (\(k, v) -> (k, [v]))
227188 toList = concatMap (\(k, vs) -> map ((,) k) vs) . HashMap.toList . unForm
228189
229−-- | A stable version of 'toList'.
230−toListStable :: Form -> [(Text, Text)]
231−toListStable = sortOn fst . toList
232−
233190-- | Convert a value into 'Form'.
234191--
235192-- An example type and instance:
@@ -266,11 +223,12 @@ toListStable = sortOn fst . toList
266223-- @
267224--
268225-- The default implementation of 'toForm' is 'genericToForm'.
226+-- It only works for records and it will use 'toQueryParam' for each field's value.
269227class ToForm a where
270228 -- | Convert a value into 'Form'.
271229 toForm :: a -> Form
272230 default toForm :: (Generic a, GToForm a (Rep a)) => a -> Form
273− toForm = genericToForm defaultFormOptions
231+ toForm = genericToForm
274232
275233instance ToForm Form where toForm = id
276234
@@ -297,13 +255,11 @@ data Proxy3 a b c = Proxy3
297255
298256type family NotSupported (cls :: k1) (a :: k2) (reason :: Symbol) :: Constraint where
299257#if __GLASGOW_HASKELL__ < 800
300− -- this is just a placeholder case for older GHCs to not freak out on an empty closed type family
301− NotSupported cls a "this type family is actually empty" = ()
302258#else
303259 NotSupported cls a reason = TypeError
304− ( 'Text "Cannot derive a Generic-based " ':<>: 'ShowType cls ':<>: 'Text " instance for " ':<>: 'ShowType a ':<>: 'Text "." ':$$:
305− 'ShowType a ':<>: 'Text " " ':<>: 'Text reason ':<>: 'Text "," ':$$:
306− 'Text "but Generic-based " ':<>: 'ShowType cls ':<>: 'Text " instances can be derived only for records" ':$$:
260+ ( 'Text "Cannot derive a Generic-based " :<>: 'ShowType cls :<>: 'Text " instance for " :<>: 'ShowType a :<>: 'Text "." :$$:
261+ 'ShowType a :<>: 'Text " " :<>: 'Text reason :<>: 'Text "," :$$:
262+ 'Text "but Generic-based " :<>: 'ShowType cls :<>: 'Text " instances can be derived only for records" :$$:
307263 'Text "(i.e. product types with named fields)." )
308264#endif
309265
@@ -318,67 +274,25 @@ type family NotSupported (cls :: k1) (a :: k2) (reason :: Symbol) :: Constraint
318274-- , age :: Int
319275-- } deriving ('Generic')
320276-- @
321−--
322−-- In this implementation each field's value gets encoded using `toQueryParam`.
323−-- Two field types are exceptions:
324−--
325−-- - for values of type @'Maybe' a@ an entry is added to the 'Form' only when it is @'Just' x@
326−-- and the encoded value is @'toQueryParam' x@; 'Nothing' values are omitted from the 'Form';
327−--
328−-- - for values of type @[a]@ (except @['Char']@) an entry is added for every item in the list;
329−-- if the list is empty no entries are added to the 'Form';
330−--
331−-- Here's an example:
332−--
333−-- @
334−-- data Post = Post
335−-- { title :: String
336−-- , subtitle :: Maybe String
337−-- , comments :: [String]
338−-- } deriving ('Generic', 'Show')
339−--
340−-- instance 'ToForm' Post
341−-- @
342−--
343−-- >>> urlEncodeAsFormStable Post { title = "Test", subtitle = Nothing, comments = ["Nice post!", "+1"] }
344−-- "comments=Nice%20post%21&comments=%2B1&title=Test"
345−genericToForm :: forall a. (Generic a, GToForm a (Rep a)) => FormOptions -> a -> Form
346−genericToForm opts = gToForm (Proxy :: Proxy a) opts . from
277+genericToForm :: forall a. (Generic a, GToForm a (Rep a)) => a -> Form
278+genericToForm = gToForm (Proxy :: Proxy a) . from
347279
348280class GToForm t (f :: * -> *) where
349− gToForm :: Proxy t -> FormOptions -> f x -> Form
281+ gToForm :: Proxy t -> f x -> Form
350282
351283instance (GToForm t f, GToForm t g) => GToForm t (f :*: g) where
352− gToForm p opts (a :*: b) = gToForm p opts a <> gToForm p opts b
284+ gToForm p (a :*: b) = gToForm p a <> gToForm p b
353285
354286instance (GToForm t f) => GToForm t (M1 D x f) where
355− gToForm p opts (M1 a) = gToForm p opts a
287+ gToForm p (M1 a) = gToForm p a
356288
357289instance (GToForm t f) => GToForm t (M1 C x f) where
358− gToForm p opts (M1 a) = gToForm p opts a
359−
360−instance OVERLAPPABLE_ (Selector s, ToHttpApiData c) => GToForm t (M1 S s (K1 i c)) where
361− gToForm _ opts (M1 (K1 c)) = fromList [(key, toQueryParam c)]
362− where
363− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
364−
365−instance (Selector s, ToHttpApiData c) => GToForm t (M1 S s (K1 i (Maybe c))) where
366− gToForm _ opts (M1 (K1 c)) =
367− case c of
368− Nothing -> mempty
369− Just x -> fromList [(key, toQueryParam x)]
370− where
371− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
372−
373−instance (Selector s, ToHttpApiData c) => GToForm t (M1 S s (K1 i [c])) where
374− gToForm _ opts (M1 (K1 cs)) = fromList (map (\c -> (key, toQueryParam c)) cs)
375− where
376− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
290+ gToForm p (M1 a) = gToForm p a
377291
378−instance OVERLAPPING_ (Selector s) => GToForm t (M1 S s (K1 i String)) where
379− gToForm _ opts (M1 (K1 c)) = fromList [(key, toQueryParam c)]
292+instance (Selector s, ToHttpApiData c) => GToForm t (M1 S s (K1 i c)) where
293+ gToForm _ (M1 (K1 c)) = fromList [(key, toQueryParam c)]
380294 where
381− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
295+ key = Text.pack $ selName (Proxy3 :: Proxy3 s g p)
382296
383297instance NotSupported ToForm t "is a sum type" => GToForm t (f :+: g) where gToForm = error "impossible"
384298
@@ -392,9 +306,9 @@ instance NotSupported ToForm t "is a sum type" => GToForm t (f :+: g) where gToF
392306-- , age :: Int }
393307--
394308-- instance 'FromForm' Person where
395−-- 'fromForm' f = Person
396−-- '<$>' 'parseUnique' "name" f
397−-- '<*>' 'parseUnique' "age" f
309+-- 'fromForm' (Form m) = Person
310+-- '<$>' 'parseUnique' "name" m
311+-- '<*>' 'parseUnique' "age" m
398312-- @
399313--
400314-- Instead of manually writing @'FromForm'@ instances you can
@@ -421,11 +335,10 @@ class FromForm a where
421335 -- | Parse 'Form' into a value.
422336 fromForm :: Form -> Either Text a
423337 default fromForm :: (Generic a, GFromForm a (Rep a)) => Form -> Either Text a
424− fromForm = genericFromForm defaultFormOptions
338+ fromForm = genericFromForm
425339
426340instance FromForm Form where fromForm = pure
427341
428−-- | _NOTE:_ this conversion is unstable and may result in different key order (but not values).
429342instance (FromFormKey k, FromHttpApiData v) => FromForm [(k, v)] where
430343 fromForm = fmap (concatMap (\(k, vs) -> map ((,) k) vs)) . toEntriesByKey
431344
@@ -440,22 +353,13 @@ instance FromHttpApiData v => FromForm (IntMap [v]) where
440353
441354-- | Parse a 'Form' into a list of entries groupped by key.
442355--
443−-- _NOTE:_ this conversion is unstable and may result in different key order
444−-- (but not values). For a stable encoding see 'toEntriesByKeyStable'.
356+-- >>> toEntriesByKey [("name", "Nick"), ("color", "red"), ("color", "white")] :: Either Text [(Text, [Text])]
357+-- Right [("color",["red","white"]),("name",["Nick"])]
445358toEntriesByKey :: (FromFormKey k, FromHttpApiData v) => Form -> Either Text [(k, [v])]
446359toEntriesByKey = traverse parseGroup . HashMap.toList . unForm
447360 where
448361 parseGroup (k, vs) = (,) <$> parseFormKey k <*> traverse parseQueryParam vs
449362
450−-- | Parse a 'Form' into a list of entries groupped by key.
451−--
452−-- >>> toEntriesByKeyStable [("name", "Nick"), ("color", "red"), ("color", "white")] :: Either Text [(Text, [Text])]
453−-- Right [("color",["red","white"]),("name",["Nick"])]
454−--
455−-- For an unstable (but faster) conversion see 'toEntriesByKey'.
456−toEntriesByKeyStable :: (Ord k, FromFormKey k, FromHttpApiData v) => Form -> Either Text [(k, [v])]
457−toEntriesByKeyStable = fmap (sortOn fst) . toEntriesByKey
458−
459363-- | A 'Generic'-based implementation of 'fromForm'.
460364-- This is used as a default implementation in 'FromForm'.
461365--
@@ -467,115 +371,63 @@ toEntriesByKeyStable = fmap (sortOn fst) . toEntriesByKey
467371-- , age :: Int
468372-- } deriving ('Generic')
469373-- @
470−--
471−-- In this implementation each field's value gets decoded using `parseQueryParam`.
472−-- Two field types are exceptions:
473−--
474−-- - for values of type @'Maybe' a@ an entry is parsed if present in the 'Form'
475−-- and the is decoded with 'parseQueryParam'; if no entry is present result is 'Nothing';
476−--
477−-- - for values of type @[a]@ (except @['Char']@) all entries are parsed to produce a list of parsed values;
478−--
479−-- Here's an example:
480−--
481−-- @
482−-- data Post = Post
483−-- { title :: String
484−-- , subtitle :: Maybe String
485−-- , comments :: [String]
486−-- } deriving ('Generic', 'Show')
487−--
488−-- instance 'FromForm' Post
489−-- @
490−--
491−-- >>> urlDecodeAsForm "comments=Nice%20post%21&comments=%2B1&title=Test" :: Either Text Post
492−-- Right (Post {title = "Test", subtitle = Nothing, comments = ["Nice post!","+1"]})
493−genericFromForm :: forall a. (Generic a, GFromForm a (Rep a)) => FormOptions -> Form -> Either Text a
494−genericFromForm opts f = to <$> gFromForm (Proxy :: Proxy a) opts f
374+genericFromForm :: forall a. (Generic a, GFromForm a (Rep a)) => Form -> Either Text a
375+genericFromForm f = to <$> gFromForm (Proxy :: Proxy a) f
495376
496377class GFromForm t (f :: * -> *) where
497− gFromForm :: Proxy t -> FormOptions -> Form -> Either Text (f x)
378+ gFromForm :: Proxy t -> Form -> Either Text (f x)
498379
499380instance (GFromForm t f, GFromForm t g) => GFromForm t (f :*: g) where
500− gFromForm p opts f = (:*:) <$> gFromForm p opts f <*> gFromForm p opts f
501−
502−instance GFromForm t f => GFromForm t (M1 D x f) where
503− gFromForm p opts f = M1 <$> gFromForm p opts f
504−
505−instance GFromForm t f => GFromForm t (M1 C x f) where
506− gFromForm p opts f = M1 <$> gFromForm p opts f
507−
508−instance OVERLAPPABLE_ (Selector s, FromHttpApiData c) => GFromForm t (M1 S s (K1 i c)) where
509− gFromForm _ opts form = M1 . K1 <$> parseUnique key form
510− where
511− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
381+ gFromForm p f = (:*:) <$> gFromForm p f <*> gFromForm p f
512382
513−instance (Selector s, FromHttpApiData c) => GFromForm t (M1 S s (K1 i (Maybe c))) where
514− gFromForm _ opts form = M1 . K1 <$> parseMaybe key form
383+instance (Selector s, FromHttpApiData f) => GFromForm t (M1 S s (K1 i f)) where
384+ gFromForm _ form = M1 . K1 <$> parseUnique key form
515385 where
516− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
386+ key = Text.pack $ selName (Proxy3 :: Proxy3 s g p)
517387
518−instance (Selector s, FromHttpApiData c) => GFromForm t (M1 S s (K1 i [c])) where
519− gFromForm _ opts form = M1 . K1 <$> parseAll key form
520− where
521− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
388+instance GFromForm t f => GFromForm t (M1 D x f) where
389+ gFromForm p f = M1 <$> gFromForm p f
522390
523−instance OVERLAPPING_ (Selector s) => GFromForm t (M1 S s (K1 i String)) where
524− gFromForm _ opts form = M1 . K1 <$> parseUnique key form
525− where
526− key = Text.pack $ fieldLabelModifier opts $ selName (Proxy3 :: Proxy3 s g p)
391+instance GFromForm t f => GFromForm t (M1 C x f) where
392+ gFromForm p f = M1 <$> gFromForm p f
527393
528394instance NotSupported FromForm t "is a sum type" => GFromForm t (f :+: g) where gFromForm = error "impossible"
529395
530396-- | Encode a 'Form' to an @application/x-www-form-urlencoded@ 'BSL.ByteString'.
531397--
532−-- _NOTE:_ this encoding is unstable and may result in different key order
533−-- (but not values). For a stable encoding see 'urlEncodeFormStable'.
534−urlEncodeForm :: Form -> BSL.ByteString
535−urlEncodeForm = urlEncodeParams . toList
536−
537−-- | Encode a 'Form' to an @application/x-www-form-urlencoded@ 'BSL.ByteString'.
538−--
539−-- For an unstable (but faster) encoding see 'urlEncodeForm'.
540−--
541398-- Key-value pairs get encoded to @key=value@ and separated by @&@:
542399--
543−-- >>> urlEncodeFormStable [("name", "Julian"), ("lastname", "Arni")]
400+-- >>> urlEncodeForm [("name", "Julian"), ("lastname", "Arni")]
544401-- "lastname=Arni&name=Julian"
545402--
546403-- Keys with empty values get encoded to just @key@ (without the @=@ sign):
547404--
548−-- >>> urlEncodeFormStable [("is_test", "")]
405+-- >>> urlEncodeForm [("is_test", "")]
549406-- "is_test"
550407--
551408-- Empty keys are allowed too:
552409--
553−-- >>> urlEncodeFormStable [("", "foobar")]
410+-- >>> urlEncodeForm [("", "foobar")]
554411-- "=foobar"
555412--
556−-- However, if both key and value are empty, the key-value pair is ignored.
557−-- (This prevents @'urlDecodeForm' . 'urlEncodeFormStable'@ from being a true isomorphism).
413+-- However, if not key and value are empty, the key-value pair is ignored.
414+-- (This prevents @'urlDecodeForm' . 'urlEncodeForm'@ from being a true isomorphism).
558415--
559−-- >>> urlEncodeFormStable [("", "")]
416+-- >>> urlEncodeForm [("", "")]
560417-- ""
561418--
562419-- Everything is escaped with @'escapeURIString' 'isUnreserved'@:
563420--
564−-- >>> urlEncodeFormStable [("fullname", "Andres Löh")]
421+-- >>> urlEncodeForm [("fullname", "Andres Löh")]
565422-- "fullname=Andres%20L%C3%B6h"
566−urlEncodeFormStable :: Form -> BSL.ByteString
567−urlEncodeFormStable = urlEncodeParams . sortOn fst . toList
568−
569−-- | Encode a list of key-value pairs to an @application/x-www-form-urlencoded@ 'BSL.ByteString'.
570−--
571−-- See also 'urlEncodeFormStable'.
572−urlEncodeParams :: [(Text, Text)] -> BSL.ByteString
573−urlEncodeParams = toLazyByteString . mconcat . intersperse (shortByteString "&") . map encodePair
423+urlEncodeForm :: Form -> BSL.ByteString
424+urlEncodeForm = toLazyByteString . mconcat . intersperse (shortByteString "&") . map encodePair . toList
574425 where
575− escape = urlEncodeBuilder True . Text.encodeUtf8
426+ escape = urlEncodeQuery . Text.encodeUtf8
576427
577428 encodePair (k, "") = escape k
578− encodePair (k, v) = escape k <> shortByteString "=" <> escape v
429+ encodePair (k, v) = escape k <> shortByteString "=" <> escape v
430+
579431
580432-- | Decode an @application/x-www-form-urlencoded@ 'BSL.ByteString' to a 'Form'.
581433--
@@ -609,17 +461,11 @@ urlEncodeParams = toLazyByteString . mconcat . intersperse (shortByteString "&")
609461-- >>> urlDecodeForm "this=has=too=many=equals"
610462-- Left "not a valid pair: this=has=too=many=equals"
611463urlDecodeForm :: BSL.ByteString -> Either Text Form
612−urlDecodeForm = fmap toForm . urlDecodeParams
613−
614−-- | Decode an @application/x-www-form-urlencoded@ 'BSL.ByteString' to a list of key-value pairs.
615−--
616−-- See also 'urlDecodeForm'.
617−urlDecodeParams :: BSL.ByteString -> Either Text [(Text, Text)]
618−urlDecodeParams bs = traverse parsePair pairs
464+urlDecodeForm bs = toForm <$> traverse parsePair pairs
619465 where
620466 pairs = map (BSL8.split '=') (BSL8.split '&' bs)
621467
622− unescape = Text.decodeUtf8With lenientDecode . urlDecode True . BSL.toStrict
468+ unescape = Text.decodeUtf8With lenientDecode . urlDecodeQuery . BSL.toStrict
623469
624470 parsePair p =
625471 case map unescape p of
@@ -627,7 +473,6 @@ urlDecodeParams bs = traverse parsePair pairs
627473 [k] -> return (k, "")
628474 xs -> Left $ "not a valid pair: " <> Text.intercalate "=" xs
629475
630−
631476-- | This is a convenience function for decoding a
632477-- @application/x-www-form-urlencoded@ 'BSL.ByteString' directly to a datatype
633478-- that has an instance of 'FromForm'.
@@ -645,22 +490,11 @@ urlDecodeAsForm = fromForm <=< urlDecodeForm
645490--
646491-- This is effectively @'urlEncodeForm' . 'toForm'@.
647492--
648−-- _NOTE:_ this encoding is unstable and may result in different key order
649−-- (but not values). For a stable encoding see 'urlEncodeAsFormStable'.
493+-- >>> urlEncodeAsForm Person {name = "Dennis", age = 22}
494+-- "age=22&name=Dennis"
650495urlEncodeAsForm :: ToForm a => a -> BSL.ByteString
651496urlEncodeAsForm = urlEncodeForm . toForm
652497
653−-- | This is a convenience function for encoding a datatype that has instance
654−-- of 'ToForm' directly to a @application/x-www-form-urlencoded@
655−-- 'BSL.ByteString'.
656−--
657−-- This is effectively @'urlEncodeFormStable' . 'toForm'@.
658−--
659−-- >>> urlEncodeAsFormStable Person {name = "Dennis", age = 22}
660−-- "age=22&name=Dennis"
661−urlEncodeAsFormStable :: ToForm a => a -> BSL.ByteString
662−urlEncodeAsFormStable = urlEncodeFormStable . toForm
663−
664498-- | Find all values corresponding to a given key in a 'Form'.
665499--
666500-- >>> lookupAll "name" []
@@ -672,22 +506,6 @@ urlEncodeAsFormStable = urlEncodeFormStable . toForm
672506lookupAll :: Text -> Form -> [Text]
673507lookupAll key = F.concat . HashMap.lookup key . unForm
674508
675−-- | Lookup an optional value for a key.
676−-- Fail if there is more than one value.
677−--
678−-- >>> lookupMaybe "name" []
679−-- Right Nothing
680−-- >>> lookupMaybe "name" [("name", "Oleg")]
681−-- Right (Just "Oleg")
682−-- >>> lookupMaybe "name" [("name", "Oleg"), ("name", "David")]
683−-- Left "Duplicate key \"name\""
684−lookupMaybe :: Text -> Form -> Either Text (Maybe Text)
685−lookupMaybe key form =
686− case lookupAll key form of
687− [] -> pure Nothing
688− [v] -> pure (Just v)
689− _ -> Left $ "Duplicate key " <> Text.pack (show key)
690−
691509-- | Lookup a unique value for a key.
692510-- Fail if there is zero or more than one value.
693511--
@@ -698,11 +516,11 @@ lookupMaybe key form =
698516-- >>> lookupUnique "name" [("name", "Oleg"), ("name", "David")]
699517-- Left "Duplicate key \"name\""
700518lookupUnique :: Text -> Form -> Either Text Text
701−lookupUnique key form = do
702− mv <- lookupMaybe key form
703− case mv of
704− Just v -> pure v
705− Nothing -> Left $ "Could not find key " <> Text.pack (show key)
519+lookupUnique key form =
520+ case lookupAll key form of
521+ [v] -> pure v
522+ [] -> Left $ "Could not find key " <> Text.pack (show key)
523+ _ -> Left $ "Duplicate key " <> Text.pack (show key)
706524
707525-- | Lookup all values for a given key in a 'Form' and parse them with 'parseQueryParams'.
708526--
@@ -717,22 +535,6 @@ lookupUnique key form = do
717535parseAll :: FromHttpApiData v => Text -> Form -> Either Text [v]
718536parseAll key = parseQueryParams . lookupAll key
719537
720−-- | Lookup an optional value for a given key and parse it with 'parseQueryParam'.
721−-- Fail if there is more than one value for the key.
722−--
723−-- >>> parseMaybe "age" [] :: Either Text (Maybe Word8)
724−-- Right Nothing
725−-- >>> parseMaybe "age" [("age", "12"), ("age", "25")] :: Either Text (Maybe Word8)
726−-- Left "Duplicate key \"age\""
727−-- >>> parseMaybe "age" [("age", "seven")] :: Either Text (Maybe Word8)
728−-- Left "could not parse: `seven' (input does not start with a digit)"
729−-- >>> parseMaybe "age" [("age", "777")] :: Either Text (Maybe Word8)
730−-- Left "out of bounds: `777' (should be between 0 and 255)"
731−-- >>> parseMaybe "age" [("age", "7")] :: Either Text (Maybe Word8)
732−-- Right (Just 7)
733−parseMaybe :: FromHttpApiData v => Text -> Form -> Either Text (Maybe v)
734−parseMaybe key = parseQueryParams <=< lookupMaybe key
735−
736538-- | Lookup a unique value for a given key and parse it with 'parseQueryParam'.
737539-- Fail if there is zero or more than one value for the key.
738540--
@@ -749,48 +551,3 @@ parseMaybe key = parseQueryParams <=< lookupMaybe key
749551parseUnique :: FromHttpApiData v => Text -> Form -> Either Text v
750552parseUnique key form = lookupUnique key form >>= parseQueryParam
751553
752−-- | 'Generic'-based deriving options for 'ToForm' and 'FromForm'.
753−--
754−-- A common use case for non-default 'FormOptions'
755−-- is to strip a prefix off of field labels:
756−--
757−-- @
758−-- data Project = Project
759−-- { projectName :: String
760−-- , projectSize :: Int
761−-- } deriving ('Generic', 'Show')
762−--
763−-- myOptions :: 'FormOptions'
764−-- myOptions = 'FormOptions'
765−-- { 'fieldLabelModifier' = 'map' 'toLower' . 'drop' ('length' \"project\") }
766−--
767−-- instance 'ToForm' Project where
768−-- 'toForm' = 'genericToForm' myOptions
769−--
770−-- instance 'FromForm' Project where
771−-- 'fromForm' = 'genericFromForm' myOptions
772−-- @
773−--
774−-- >>> urlEncodeAsFormStable Project { projectName = "http-api-data", projectSize = 172 }
775−-- "name=http-api-data&size=172"
776−-- >>> urlDecodeAsForm "name=http-api-data&size=172" :: Either Text Project
777−-- Right (Project {projectName = "http-api-data", projectSize = 172})
778−data FormOptions = FormOptions
779− { -- | Function applied to field labels. Handy for removing common record prefixes for example.
780− fieldLabelModifier :: String -> String
781− }
782−
783−-- | Default encoding 'FormOptions'.
784−--
785−-- @
786−-- 'FormOptions'
787−-- { 'fieldLabelModifier' = id
788−-- }
789−-- @
790−defaultFormOptions :: FormOptions
791−defaultFormOptions = FormOptions
792− { fieldLabelModifier = id
793− }
794−
795−sortOn :: Ord b => (a -> b) -> [a] -> [a]
796−sortOn f = sortBy (comparing f)