packages feed

unkai-core (empty) → 0.1.0.0

raw patch · 10 files changed

+1612/−0 lines, 10 filesdep +aesondep +attoparsecdep +base

Dependencies added: aeson, attoparsec, base, base64, bytestring, case-insensitive, dlist, exceptions, hashable, http-api-data, http-client, http-media, http-types, lens, resourcet, scientific, servant, streamly-core, tasty, tasty-hunit, text, time, unkai-core, unordered-containers

Files

+ CHANGELOG.md view
@@ -0,0 +1,8 @@+# Changelog++## 0.1.0.0 — 2026-11-24++- Provide `Unkai.Prelude` and `Unkai.Types` for generated service libraries, with shared request, response, and OAuth scope types.+- Use `PatchField` from `Unkai.Data.JSON` to distinguish omitted fields, assigned values, and explicit JSON nulls.+- Use Streamly to consume `Stream` values in `ResourceT IO`. Use `sinkLBS` to collect response chunks into a lazy `ByteString`.+- Require GHC 9.12 or newer and use the GHC2024 language edition.
+ LICENSE view
@@ -0,0 +1,367 @@+Mozilla Public License Version 2.0+==================================++1. Definitions+--------------++1.1. "Contributor"+    means each individual or legal entity that creates, contributes to+    the creation of, or owns Covered Software.++1.2. "Contributor Version"+    means the combination of the Contributions of others (if any) used+    by a Contributor and that particular Contributor's Contribution.++1.3. "Contribution"+    means Covered Software of a particular Contributor.++1.4. "Covered Software"+    means Source Code Form to which the initial Contributor has attached+    the notice in Exhibit A, the Executable Form of such Source Code+    Form, and Modifications of such Source Code Form, in each case+    including portions thereof.++1.5. "Incompatible With Secondary Licenses"+    means++    (a) that the initial Contributor has attached the notice described+        in Exhibit B to the Covered Software; or++    (b) that the Covered Software was made available under the terms of+        version 1.1 or earlier of the License, but not also under the+        terms of a Secondary License.++1.6. "Executable Form"+    means any form of the work other than Source Code Form.++1.7. "Larger Work"+    means a work that combines Covered Software with other material, in+    a separate file or files, that is not Covered Software.++1.8. "License"+    means this document.++1.9. "Licensable"+    means having the right to grant, to the maximum extent possible,+    whether at the time of the initial grant or subsequently, any and+    all of the rights conveyed by this License.++1.10. "Modifications"+    means any of the following:++    (a) any file in Source Code Form that results from an addition to,+        deletion from, or modification of the contents of Covered+        Software; or++    (b) any new file in Source Code Form that contains any Covered+        Software.++1.11. "Patent Claims" of a Contributor+    means any patent claim(s), including without limitation, method,+    process, and apparatus claims, in any patent Licensable by such+    Contributor that would be infringed, but for the grant of the+    License, by the making, using, selling, offering for sale, having+    made, import, or transfer of either its Contributions or its+    Contributor Version.++1.12. "Secondary License"+    means either the GNU General Public License, Version 2.0, the GNU+    Lesser General Public License, Version 2.1, the GNU Affero General+    Public License, Version 3.0, or any later versions of those+    licenses.++1.13. "Source Code Form"+    means the form of the work preferred for making modifications.++1.14. "You" (or "Your")+    means an individual or a legal entity exercising rights under this+    License. For legal entities, "You" includes any entity that+    controls, is controlled by, or is under common control with You. For+    purposes of this definition, "control" means (a) the power, direct+    or indirect, to cause the direction or management of such entity,+    whether by contract or otherwise, or (b) ownership of more than+    fifty percent (50%) of the outstanding shares or beneficial+    ownership of such entity.++2. License Grants and Conditions+--------------------------------++2.1. Grants++Each Contributor hereby grants You a world-wide, royalty-free,+non-exclusive license:++(a) under intellectual property rights (other than patent or trademark)+    Licensable by such Contributor to use, reproduce, make available,+    modify, display, perform, distribute, and otherwise exploit its+    Contributions, either on an unmodified basis, with Modifications, or+    as part of a Larger Work; and++(b) under Patent Claims of such Contributor to make, use, sell, offer+    for sale, have made, import, and otherwise transfer either its+    Contributions or its Contributor Version.++2.2. Effective Date++The licenses granted in Section 2.1 with respect to any Contribution+become effective for each Contribution on the date the Contributor first+distributes such Contribution.++2.3. Limitations on Grant Scope++The licenses granted in this Section 2 are the only rights granted under+this License. No additional rights or licenses will be implied from the+distribution or licensing of Covered Software under this License.+Notwithstanding Section 2.1(b) above, no patent license is granted by a+Contributor:++(a) for any code that a Contributor has removed from Covered Software;+    or++(b) for infringements caused by: (i) Your and any other third party's+    modifications of Covered Software, or (ii) the combination of its+    Contributions with other software (except as part of its Contributor+    Version); or++(c) under Patent Claims infringed by Covered Software in the absence of+    its Contributions.++This License does not grant any rights in the trademarks, service marks,+or logos of any Contributor (except as may be necessary to comply with+the notice requirements in Section 3.4).++2.4. Subsequent Licenses++No Contributor makes additional grants as a result of Your choice to+distribute the Covered Software under a subsequent version of this+License (see Section 10.2) or under the terms of a Secondary License (if+permitted under the terms of Section 3.3).++2.5. Representation++Each Contributor represents that the Contributor believes its+Contributions are its original creation(s) or it has sufficient rights+to grant the rights to its Contributions conveyed by this License.++2.6. Fair Use++This License is not intended to limit any rights You have under+applicable copyright doctrines of fair use, fair dealing, or other+equivalents.++2.7. Conditions++Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted+in Section 2.1.++3. Responsibilities+-------------------++3.1. Distribution of Source Form++All distribution of Covered Software in Source Code Form, including any+Modifications that You create or to which You contribute, must be under+the terms of this License. You must inform recipients that the Source+Code Form of the Covered Software is governed by the terms of this+License, and how they can obtain a copy of this License. You may not+attempt to alter or restrict the recipients' rights in the Source Code+Form.++3.2. Distribution of Executable Form++If You distribute Covered Software in Executable Form then:++(a) such Covered Software must also be made available in Source Code+    Form, as described in Section 3.1, and You must inform recipients of+    the Executable Form how they can obtain a copy of such Source Code+    Form by reasonable means in a timely manner, at a charge no more+    than the cost of distribution to the recipient; and++(b) You may distribute such Executable Form under the terms of this+    License, or sublicense it under different terms, provided that the+    license for the Executable Form does not attempt to limit or alter+    the recipients' rights in the Source Code Form under this License.++3.3. Distribution of a Larger Work++You may create and distribute a Larger Work under terms of Your choice,+provided that You also comply with the requirements of this License for+the Covered Software. If the Larger Work is a combination of Covered+Software with a work governed by one or more Secondary Licenses, and the+Covered Software is not Incompatible With Secondary Licenses, this+License permits You to additionally distribute such Covered Software+under the terms of such Secondary License(s), so that the recipient of+the Larger Work may, at their option, further distribute the Covered+Software under the terms of either this License or such Secondary+License(s).++3.4. Notices++You may not remove or alter the substance of any license notices+(including copyright notices, patent notices, disclaimers of warranty,+or limitations of liability) contained within the Source Code Form of+the Covered Software, except that You may alter any license notices to+the extent required to remedy known factual inaccuracies.++3.5. Application of Additional Terms++You may choose to offer, and to charge a fee for, warranty, support,+indemnity or liability obligations to one or more recipients of Covered+Software. However, You may do so only on Your own behalf, and not on+behalf of any Contributor. You must make it absolutely clear that any+such warranty, support, indemnity, or liability obligation is offered by+You alone, and You hereby agree to indemnify every Contributor for any+liability incurred by such Contributor as a result of warranty, support,+indemnity or liability terms You offer. You may include additional+disclaimers of warranty and limitations of liability specific to any+jurisdiction.++4. Inability to Comply Due to Statute or Regulation+---------------------------------------------------++If it is impossible for You to comply with any of the terms of this+License with respect to some or all of the Covered Software due to+statute, judicial order, or regulation then You must: (a) comply with+the terms of this License to the maximum extent possible; and (b)+describe the limitations and the code they affect. Such description must+be placed in a text file included with all distributions of the Covered+Software under this License. Except to the extent prohibited by statute+or regulation, such description must be sufficiently detailed for a+recipient of ordinary skill to be able to understand it.++5. Termination+--------------++5.1. The rights granted under this License will terminate automatically+if You fail to comply with any of its terms. However, if You become+compliant, then the rights granted under this License from a particular+Contributor are reinstated (a) provisionally, unless and until such+Contributor explicitly and finally terminates Your grants, and (b) on an+ongoing basis, if such Contributor fails to notify You of the+non-compliance by some reasonable means prior to 60 days after You have+come back into compliance. Moreover, Your grants from a particular+Contributor are reinstated on an ongoing basis if such Contributor+notifies You of the non-compliance by some reasonable means, this is the+first time You have received notice of non-compliance with this License+from such Contributor, and You become compliant prior to 30 days after+Your receipt of the notice.++5.2. If You initiate litigation against any entity by asserting a patent+infringement claim (excluding declaratory judgment actions,+counter-claims, and cross-claims) alleging that a Contributor Version+directly or indirectly infringes any patent, then the rights granted to+You by any and all Contributors for the Covered Software under Section+2.1 of this License shall terminate.++5.3. In the event of termination under Sections 5.1 or 5.2 above, all+end user license agreements (excluding distributors and resellers) which+have been validly granted by You or Your distributors under this License+prior to termination shall survive termination.++************************************************************************+*                                                                      *+*  6. Disclaimer of Warranty                                           *+*  -------------------------                                           *+*                                                                      *+*  Covered Software is provided under this License on an "as is"       *+*  basis, without warranty of any kind, either expressed, implied, or  *+*  statutory, including, without limitation, warranties that the       *+*  Covered Software is free of defects, merchantable, fit for a        *+*  particular purpose or non-infringing. The entire risk as to the     *+*  quality and performance of the Covered Software is with You.        *+*  Should any Covered Software prove defective in any respect, You     *+*  (not any Contributor) assume the cost of any necessary servicing,   *+*  repair, or correction. This disclaimer of warranty constitutes an   *+*  essential part of this License. No use of any Covered Software is   *+*  authorized under this License except under this disclaimer.         *+*                                                                      *+************************************************************************++************************************************************************+*                                                                      *+*  7. Limitation of Liability                                          *+*  --------------------------                                          *+*                                                                      *+*  Under no circumstances and under no legal theory, whether tort      *+*  (including negligence), contract, or otherwise, shall any           *+*  Contributor, or anyone who distributes Covered Software as          *+*  permitted above, be liable to You for any direct, indirect,         *+*  special, incidental, or consequential damages of any character      *+*  including, without limitation, damages for lost profits, loss of    *+*  goodwill, work stoppage, computer failure or malfunction, or any    *+*  and all other commercial damages or losses, even if such party      *+*  shall have been informed of the possibility of such damages. This   *+*  limitation of liability shall not apply to liability for death or   *+*  personal injury resulting from such party's negligence to the       *+*  extent applicable law prohibits such limitation. Some               *+*  jurisdictions do not allow the exclusion or limitation of           *+*  incidental or consequential damages, so this exclusion and          *+*  limitation may not apply to You.                                    *+*                                                                      *+************************************************************************++8. Litigation+-------------++Any litigation relating to this License may be brought only in the+courts of a jurisdiction where the defendant maintains its principal+place of business and such litigation shall be governed by laws of that+jurisdiction, without reference to its conflict-of-law provisions.+Nothing in this Section shall prevent a party's ability to bring+cross-claims or counter-claims.++9. Miscellaneous+----------------++This License represents the complete agreement concerning the subject+matter hereof. If any provision of this License is held to be+unenforceable, such provision shall be reformed only to the extent+necessary to make it enforceable. Any law or regulation which provides+that the language of a contract shall be construed against the drafter+shall not be used to construe this License against a Contributor.++10. Versions of the License+---------------------------++10.1. New Versions++Mozilla Foundation is the license steward. Except as provided in Section+10.3, no one other than the license steward has the right to modify or+publish new versions of this License. Each version will be given a+distinguishing version number.++10.2. Effect of New Versions++You may distribute the Covered Software under the terms of the version+of the License under which You originally received the Covered Software,+or under the terms of any subsequent version published by the license+steward.++10.3. Modified Versions++If you create software not governed by this License, and you want to+create a new license for such software, you may create and use a+modified version of this License if you rename the license and remove+any references to the name of the license steward (except to note that+such modified license differs from this License).++10.4. Distributing Source Code Form that is Incompatible With Secondary+Licenses++If You choose to distribute Source Code Form that is Incompatible With+Secondary Licenses under the terms of this version of the License, the+notice described in Exhibit B of this License must be attached.++Exhibit A - Source Code Form License Notice+-------------------------------------------++  This Source Code Form is subject to the terms of the Mozilla Public+  License, v. 2.0. If a copy of the MPL was not distributed with this+  file, You can obtain one at http://mozilla.org/MPL/2.0/.++If it is not possible or desirable to put the notice in a particular+file, then You may include the notice in a location (such as a LICENSE+file in a relevant directory) where a recipient would be likely to look+for such a notice.++You may add additional accurate notices of copyright ownership.
+ README.md view
@@ -0,0 +1,8 @@+# unkai-core++Core data types and serialisation primitives shared by the generated+`unkai-*` Google Cloud service libraries. Most users depend on+[`unkai`](../unkai) and a service package such as `unkai-storage` rather than+on this package directly.++Released under the [Mozilla Public License 2.0](LICENSE).
+ src/Unkai/Data/Base64.hs view
@@ -0,0 +1,51 @@+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}++-- |+-- Module      : Unkai.Data.Base64+-- Copyright   : (c) 2013-2022 Brendan Hay+-- License     : Mozilla Public License, v. 2.0.+-- Maintainer  : Nadeem Bitar <nadeem@gmail.com>+-- Stability   : provisional+-- Portability : non-portable (GHC extensions)+module Unkai.Data.Base64+  ( Base64 (..),+    _Base64,+  )+where++import Control.Lens (Iso', iso)+import Data.Aeson (FromJSON (..), ToJSON (..))+import Data.Base64.Types qualified as Base64+import Data.ByteString (ByteString)+import Data.ByteString.Base64 qualified as Base64+import Data.Hashable+import Data.Text.Encoding qualified as Text+import GHC.Generics (Generic)+import Unkai.Data.JSON (parseJSONText, toJSONText)+import Web.HttpApiData (FromHttpApiData (..), ToHttpApiData (..))++-- | Raw bytes that will be transparently base64 encoded\/decoded+-- on tramission to\/from a remote API.+newtype Base64 = Base64 {fromBase64 :: ByteString}+  deriving stock (Eq, Show, Read, Ord, Generic)+  deriving newtype (Hashable)++_Base64 :: Iso' Base64 ByteString+_Base64 = iso fromBase64 Base64++instance ToHttpApiData Base64 where+  toUrlPiece = Base64.extractBase64 . Base64.encodeBase64 . fromBase64+  toQueryParam = Base64.extractBase64 . Base64.encodeBase64 . fromBase64+  toHeader = Base64.extractBase64 . Base64.encodeBase64' . fromBase64++instance FromHttpApiData Base64 where+  parseUrlPiece = fmap Base64 . Base64.decodeBase64Untyped . Text.encodeUtf8+  parseQueryParam = fmap Base64 . Base64.decodeBase64Untyped . Text.encodeUtf8+  parseHeader = fmap Base64 . Base64.decodeBase64Untyped++instance FromJSON Base64 where+  parseJSON = parseJSONText "Base64"++instance ToJSON Base64 where+  toJSON = toJSONText
+ src/Unkai/Data/JSON.hs view
@@ -0,0 +1,78 @@+-- |+-- Module      : Unkai.Data.JSON+-- Copyright   : (c) 2015-2022 Brendan Hay <brendan.g.hay@gmail.com>+-- License     : Mozilla Public License, v. 2.0.+-- Maintainer  : Nadeem Bitar <nadeem@gmail.com>+-- Stability   : provisional+-- Portability : non-portable (GHC extensions)+module Unkai.Data.JSON+  ( Value,+    AsText (..),+    PatchField (..),+    patchField,+    parsePatchField,+    parseJSONObject,+    parseJSONText,+    toJSONText,++    -- * Re-exports+    FromJSON (..),+    FromJSONKey (..),+    ToJSON (..),+    ToJSONKey (..),+    withObject,+    emptyObject,+    object,+    (.=),+    (.:),+    (.:?),+    (.!=),+  )+where++import Data.Aeson+import Data.Aeson.Types+import Data.Text qualified as Text+import Web.HttpApiData (FromHttpApiData (..), ToHttpApiData (..))++import Data.Aeson.KeyMap (KeyMap)+import Data.Aeson.KeyMap qualified as KeyMap++-- | A field in a JSON merge-style patch. 'Omit' leaves it alone,+-- 'Set' assigns a value, and 'Clear' sends an explicit null.+data PatchField a = Omit | Set a | Clear+  deriving stock (Eq, Show, Functor)++patchField :: (a -> Value) -> Key -> PatchField a -> Maybe Pair+patchField encodeValue key = \case+  Omit -> Nothing+  Set value -> Just (key, encodeValue value)+  Clear -> Just (key, Null)++parsePatchField :: (Value -> Parser a) -> Key -> KeyMap Value -> Parser (PatchField a)+parsePatchField decodeValue key fields = case KeyMap.lookup key fields of+  Nothing -> pure Omit+  Just Null -> pure Clear+  Just value -> Set <$> decodeValue value++newtype AsText a = AsText {fromAsText :: a}+  deriving stock (Eq, Ord, Read, Show)+  deriving newtype (Num, Fractional, ToHttpApiData, FromHttpApiData)++instance (FromJSON a, FromHttpApiData a) => FromJSON (AsText a) where+  parseJSON (String s) = either (fail . Text.unpack) (pure . AsText) (parseQueryParam s)+  parseJSON o = AsText <$> parseJSON o++instance (ToHttpApiData a) => ToJSON (AsText a) where+  toJSON (AsText x) = String (toQueryParam x)++parseJSONObject :: (FromJSON a) => KeyMap Value -> Parser a+parseJSONObject = parseJSON . toJSON++parseJSONText :: (FromHttpApiData a) => String -> Value -> Parser a+parseJSONText n = withText n (either (fail . f) pure . parseQueryParam)+  where+    f x = n ++ " - " ++ Text.unpack x++toJSONText :: (ToHttpApiData a) => a -> Value+toJSONText = String . toQueryParam
+ src/Unkai/Data/Time.hs view
@@ -0,0 +1,155 @@+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE OverloadedStrings #-}++-- |+-- Module      : Unkai.Data.Time+-- Copyright   : (c) 2015-2022 Brendan Hay <brendan.g.hay@gmail.com>+-- License     : Mozilla Public License, v. 2.0.+-- Maintainer  : Nadeem Bitar <nadeem@gmail.com>+-- Stability   : provisional+-- Portability : non-portable (GHC extensions)+module Unkai.Data.Time+  ( Time (..),+    Date (..),+    DateTime (..),+    Duration (..),+    _Time,+    _Date,+    _DateTime,+    _Duration,+  )+where++import Control.Lens+import Data.Aeson+import Data.Aeson.Types qualified as Aeson+import Data.Attoparsec.Text+import Data.Bifunctor (first, second)+import Data.Bits ((.&.))+import Data.Char (ord)+import Data.Scientific (Scientific)+import Data.Scientific qualified as Sci+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.Lazy qualified as LText+import Data.Text.Lazy.Builder qualified as Build+import Data.Text.Lazy.Builder.Scientific qualified as Sci+import Data.Time+import GHC.Generics+import Web.HttpApiData+  ( FromHttpApiData (..),+    ToHttpApiData (..),+  )++-- | This SHOULD be a time in the format of hh:mm:ss.  It is+-- recommended that you use the "date-time" format instead of "time"+-- unless you need to transfer only the time part.+newtype Time = Time {fromTime :: TimeOfDay}+  deriving stock (Eq, Ord, Show, Read, Generic)++_Time :: Iso' Time TimeOfDay+_Time = iso fromTime Time++instance ToHttpApiData Time where+  toQueryParam = Text.pack . show . fromTime++instance FromHttpApiData Time where+  parseQueryParam = second Time . parseText timeParser++-- | This SHOULD be a date in the format of YYYY-MM-DD.  It is+-- recommended that you use the "date-time" format instead of "date"+-- unless you need to transfer only the date part.+newtype Date = Date {unDate :: Day}+  deriving stock (Eq, Ord, Show, Read, Generic)+  deriving newtype (ToHttpApiData, FromHttpApiData)++_Date :: Iso' Date Day+_Date = iso unDate Date++-- | This SHOULD be a date in ISO 8601 format of YYYY-MM-+-- DDThh:mm:ssZ in UTC time. This is the recommended form of date/timestamp.+newtype DateTime = DateTime {unDateTime :: UTCTime}+  deriving stock (Eq, Ord, Show, Read, Generic)+  deriving newtype (ToHttpApiData, FromHttpApiData)++_DateTime :: Iso' DateTime UTCTime+_DateTime = iso unDateTime DateTime++-- | A duration in seconds with up to nine fractional digits, terminated by 's'.+--+-- /Example/: @"3.5s"@.+newtype Duration = Duration {unDuration :: Scientific}+  deriving stock (Eq, Ord, Show, Read, Generic)++_Duration :: Iso' Duration Scientific+_Duration = iso unDuration Duration++instance ToHttpApiData Duration where+  toQueryParam =+    LText.toStrict+      . (\seconds -> Build.toLazyText seconds <> "s")+      . Sci.formatScientificBuilder Sci.Fixed (Just 9)+      . unDuration++instance FromHttpApiData Duration where+  parseQueryParam = second Duration . parseText durationParser++instance ToJSON Time where toJSON = String . toQueryParam++instance ToJSON Date where toJSON = String . toQueryParam++instance ToJSON DateTime where toJSON = toJSON . unDateTime++instance ToJSON Duration where toJSON = String . toQueryParam++instance FromJSON Time where+  parseJSON = fmap Time . withText "Time" (run timeParser)++instance FromJSON Date where+  parseJSON = fmap Date . withText "Date" (run dayParser)++instance FromJSON DateTime where+  parseJSON = fmap DateTime . parseJSON++instance FromJSON Duration where+  parseJSON = fmap Duration . withText "Duration" (run durationParser)++parseText :: Parser a -> Text -> Either Text a+parseText p = first Text.pack . parseOnly p++-- | Parse a time of the form @HH:MM:SS@.+timeParser :: Parser TimeOfDay+timeParser = do+  h <- twoDigits <* char ':'+  m <- twoDigits <* char ':'+  s <- twoDigits <&> fromIntegral+  if h < 24 && m < 60 && s < 61+    then pure (TimeOfDay h m s)+    else fail "invalid time"++-- | Parse a date of the form @YYYY-MM-DD@.+dayParser :: Parser Day+dayParser = do+  y <- decimal <* char '-'+  m <- twoDigits <* char '-'+  d <- twoDigits+  maybe (fail "invalid date") pure (fromGregorianValid y m d)++durationParser :: Parser Scientific+durationParser = Sci.fromFloatDigits <$> (double <* char 's')++-- | Parse a two-digit integer (e.g. day of month, hour).+twoDigits :: Parser Int+twoDigits = do+  a <- digit+  b <- digit+  let c2d c = ord c .&. 15+  pure $! c2d a * 10 + c2d b++-- | Run an attoparsec parser as an aeson parser.+run :: Parser a -> Text -> Aeson.Parser a+run p t =+  case parseOnly (p <* endOfInput) t of+    Left err -> fail $ "could not parse date: " ++ err+    Right r -> pure r
+ src/Unkai/Prelude.hs view
@@ -0,0 +1,37 @@+-- |+-- Module      : Unkai.Prelude+-- Copyright   : (c) 2015-2022 Brendan Hay <brendan.g.hay@gmail.com>+-- License     : Mozilla Public License, v. 2.0.+-- Maintainer  : Nadeem Bitar <nadeem@gmail.com>+-- Stability   : provisional+-- Portability : non-portable (GHC extensions)+module Unkai.Prelude+  ( module Export,+  )+where++import Control.Lens as Export (Lens', lens, mapping, (#), (^.), _Just)+import Data.ByteString as Export (ByteString)+import Data.Data as Export (Data, Typeable)+import Data.Functor as Export ((<&>))+import Data.HashMap.Strict as Export (HashMap)+import Data.Hashable as Export (Hashable, hashWithSalt)+import Data.Int as Export (Int32, Int64)+import Data.List.NonEmpty as Export (NonEmpty)+import Data.Maybe as Export+import Data.Proxy as Export+import Data.Scientific as Export (Scientific)+import Data.Text as Export (Text)+import Data.Time as Export (Day, TimeOfDay, UTCTime)+import Data.Word as Export (Word32, Word64, Word8)+import GHC.Generics as Export (Generic)+import Network.HTTP.Client as Export (RequestBody)+import Numeric.Natural as Export (Natural)+import Servant.API as Export hiding (FromHttpApiData, Header, Headers, IsMember, Link, ResponseHeader, Stream, ToHttpApiData, Union, getResponse)+import Servant.Links as Export hiding (Link)+import Unkai.Data.Base64 as Export+import Unkai.Data.JSON as Export+import Unkai.Data.Time as Export+import Unkai.Types as Export+import Web.HttpApiData as Export (FromHttpApiData (..), ToHttpApiData (..))+import Prelude as Export
+ src/Unkai/Types.hs view
@@ -0,0 +1,771 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE KindSignatures #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE UndecidableInstances #-}++-- |+-- Module      : Unkai.Types+-- Copyright   : (c) 2015-2022 Brendan Hay <brendan.g.hay@gmail.com>+-- License     : Mozilla Public License, v. 2.0.+-- Maintainer  : Nadeem Bitar <nadeem@gmail.com>+-- Stability   : provisional+-- Portability : non-portable (GHC extensions)+module Unkai.Types+  ( AltJSON (..),+    AltMedia (..),+    Multipart (..),+    Media (..),+    OAuthScope (..),+    AccessToken (..),+    RefreshToken (..),+    ClientId (..),+    ServiceId (..),+    GSecret (..),+    MediaDownload (..),+    MediaUpload (..),+    _Coerce,+    _Default,+    Stream,+    Error (..),+    SerializeError (..),+    ServiceError (..),+    AsError (..),+    AuthError (..),+    AsAuthError (..),+    ServiceConfig (..),+    defaultService,+    serviceHost,+    servicePort,+    servicePath,+    serviceSecure,+    serviceTimeout,+    GBody (..),+    bodyContentType,+    Request (..),+    appendPath,+    appendPaths,+    appendQuery,+    appendHeader,+    setBody,+    GClient (..),+    clientService,+    mime,+    discard,+    gClient,+    ToBody (..),+    FromStream (..),+    GoogleRequest (..),+    GoogleClient (..),+    Captures,+    CaptureMode,+    CaptureReserved,+    CaptureReservedMode,+    MultipartRelated,+    sinkLBS,+    buildText,+    buildSymbol,+    byteSymbol,+    Seconds (..),+    seconds,+    microseconds,+    FieldMask (..),+  )+where++import Control.Exception (IOException)+import Control.Exception.Lens (exception)+import Control.Lens+import Control.Monad.Catch+import Control.Monad.Trans.Resource+import Data.Aeson+import Data.ByteString (ByteString)+import Data.ByteString.Char8 qualified as BS8+import Data.ByteString.Lazy qualified as LBS+import Data.CaseInsensitive qualified as CI+import Data.Coerce+import Data.DList (DList)+import Data.DList qualified as DList+import Data.Data+import Data.Foldable qualified as Foldable+import Data.Kind (Type)+import Data.List (intersperse)+import Data.String+import Data.Text (Text)+import Data.Text qualified as Text+import Data.Text.Encoding qualified as Text+import Data.Text.Lazy.Builder (Builder)+import Data.Text.Lazy.Builder qualified as Build+import GHC.Generics+import GHC.TypeLits+import Network.HTTP.Client (HttpException, RequestBody (..))+import Network.HTTP.Media hiding (Accept)+import Network.HTTP.Types hiding (Header)+import Network.HTTP.Types qualified as HTTP+import Servant.API hiding (Stream)+import Streamly.Data.Fold qualified as Fold+import Streamly.Data.Stream qualified as Stream++data AltJSON = AltJSON+  deriving stock (Eq, Ord, Show, Read, Generic)++instance ToHttpApiData AltJSON where+  toQueryParam = const "json"++data AltMedia = AltMedia+  deriving stock (Eq, Ord, Show, Read, Generic)++instance ToHttpApiData AltMedia where+  toQueryParam = const "media"++data Multipart = Multipart+  deriving stock (Eq, Ord, Show, Read, Generic)++instance ToHttpApiData Multipart where+  toQueryParam = const "multipart"++-- | The upload protocol for a media-only request.+data Media = Media+  deriving stock (Eq, Show)++instance ToHttpApiData Media where+  toQueryParam Media = "media"++-- | An OAuth2 scope.+newtype OAuthScope = OAuthScope Text+  deriving stock (Eq, Ord, Show, Read, Generic)+  deriving newtype (IsString, FromHttpApiData, ToHttpApiData, FromJSON, ToJSON)++-- | An OAuth2 access token.+newtype AccessToken = AccessToken Text+  deriving stock (Eq, Ord, Show, Read, Generic)+  deriving newtype (IsString, FromHttpApiData, ToHttpApiData, FromJSON, ToJSON)++-- | An OAuth2 refresh token.+newtype RefreshToken = RefreshToken Text+  deriving stock (Eq, Ord, Show, Read, Generic)+  deriving newtype (IsString, FromHttpApiData, ToHttpApiData, FromJSON, ToJSON)++-- | A client identifier.+newtype ClientId = ClientId Text+  deriving stock (Eq, Ord, Show, Read, Generic)+  deriving newtype (IsString, FromHttpApiData, ToHttpApiData, FromJSON, ToJSON)++-- | A service identifier.+newtype ServiceId = ServiceId Text+  deriving stock (Eq, Ord, Show, Read, Generic)+  deriving newtype (IsString, FromHttpApiData, ToHttpApiData, FromJSON, ToJSON)++-- | An opaque client secret.+newtype GSecret = GSecret Text+  deriving stock (Eq, Ord, Read, Generic)+  deriving newtype (IsString, FromHttpApiData, ToHttpApiData, FromJSON, ToJSON)++instance Show GSecret where+  show = const "*****"++newtype MediaDownload a = MediaDownload a++data MediaUpload a = MediaUpload a GBody++_Coerce :: (Coercible a b) => Iso' a b+_Coerce = iso coerce coerce++-- | Invalid Iso, exists for ease of composition with the current 'Lens . Iso'+-- chaining to hide internal types from the user.+_Default :: (Monoid a) => Iso' (Maybe a) a+_Default = iso f Just+  where+    f (Just x) = x+    f Nothing = mempty++-- | A single-pass HTTP response body. Consume it in the resource scope that opened it.+type Stream = Stream.Stream (ResourceT IO) ByteString++data Error+  = AuthenticationError AuthError+  | TransportError HttpException+  | SerializeError SerializeError+  | ServiceError ServiceError+  deriving stock (Show)++instance Exception Error++data SerializeError = SerializeError'+  { _serializeId :: !ServiceId,+    _serializeHeaders :: [HTTP.Header],+    _serializeStatus :: !Status,+    _serializeMessage :: !String,+    _serializeBody :: !(Maybe LBS.ByteString)+  }+  deriving stock (Eq, Show)++data ServiceError = ServiceError'+  { _serviceId :: !ServiceId,+    _serviceStatus :: !Status,+    _serviceHeaders :: ![HTTP.Header],+    _serviceBody :: !(Maybe LBS.ByteString)+  }+  deriving stock (Eq, Show)++class AsError a where+  -- | A general Unkai request error.+  _Error :: Prism' a Error++  {-# MINIMAL _Error #-}++  -- | An error occured while communicating over HTTP with a remote service.+  _TransportError :: Prism' a HttpException++  -- | A serialisation error occured when attempting to deserialise a response.+  _SerializeError :: Prism' a SerializeError++  -- | A service specific error returned by the remote service.+  _ServiceError :: Prism' a ServiceError++  _AuthenticationError :: Prism' a AuthError+  _AuthenticationError = _Error . _AuthenticationError+  _TransportError = _Error . _TransportError+  _SerializeError = _Error . _SerializeError+  _ServiceError = _Error . _ServiceError++instance AsError SomeException where+  _Error = exception++instance AsError Error where+  _Error = id++  _AuthenticationError = prism AuthenticationError $ \case+    AuthenticationError e -> Right e+    x -> Left x++  _TransportError = prism TransportError $ \case+    TransportError e -> Right e+    x -> Left x++  _SerializeError = prism SerializeError $ \case+    SerializeError e -> Right e+    x -> Left x++  _ServiceError = prism ServiceError $ \case+    ServiceError e -> Right e+    x -> Left x++-- | An error thrown when attempting to read/write AuthN/AuthZ information.+data AuthError+  = RetrievalError HttpException+  | MissingFileError FilePath+  | CredentialFileReadError FilePath IOException+  | InvalidFileError FilePath Text+  | TokenRefreshError Status Text (Maybe Text)+  | FileExistError FilePath+  deriving stock (Show)++instance Exception AuthError++class AsAuthError a where+  -- | A general authentication error.+  _AuthError :: Prism' a AuthError++  {-# MINIMAL _AuthError #-}++  -- | A transport error from a metadata or OAuth token endpoint.+  _RetrievalError :: Prism' a HttpException++  -- | The specified default credentials file could not be found.+  _MissingFileError :: Prism' a FilePath++  -- | An error occurred parsing the default credentials file.+  _InvalidFileError :: Prism' a (FilePath, Text)++  -- | An error occurred when attempting to refresh a token.+  _TokenRefreshError :: Prism' a (Status, Text, Maybe Text)++  _RetrievalError = _AuthError . _RetrievalError+  _MissingFileError = _AuthError . _MissingFileError+  _InvalidFileError = _AuthError . _InvalidFileError+  _TokenRefreshError = _AuthError . _TokenRefreshError++instance AsAuthError SomeException where+  _AuthError = exception++instance AsAuthError AuthError where+  _AuthError = id++  _RetrievalError = prism RetrievalError $ \case+    RetrievalError e -> Right e+    x -> Left x++  _MissingFileError = prism MissingFileError $ \case+    MissingFileError f -> Right f+    x -> Left x++  _InvalidFileError =+    prism+      (uncurry InvalidFileError)+      ( \case+          InvalidFileError f e -> Right (f, e)+          x -> Left x+      )++  _TokenRefreshError =+    prism+      (\(s, e, d) -> TokenRefreshError s e d)+      ( \case+          TokenRefreshError s e d -> Right (s, e, d)+          x -> Left x+      )++data ServiceConfig = ServiceConfig+  { _svcId :: !ServiceId,+    _svcHost :: !ByteString,+    _svcPath :: !Builder,+    _svcPort :: !Int,+    _svcSecure :: !Bool,+    _svcTimeout :: !(Maybe Seconds)+  }++defaultService :: ServiceId -> ByteString -> ServiceConfig+defaultService i h =+  ServiceConfig+    { _svcId = i,+      _svcHost = h,+      _svcPath = mempty,+      _svcPort = 443,+      _svcSecure = True,+      _svcTimeout = Just 70+    }++-- | The remote host name, used for both the IP address to connect to and the+-- host request header.+serviceHost :: Lens' ServiceConfig ByteString+serviceHost = lens _svcHost (\s a -> s {_svcHost = a})++-- | The remote port to connect to.+--+-- Defaults to @443@.+servicePort :: Lens' ServiceConfig Int+servicePort = lens _svcPort (\s a -> s {_svcPort = a})++-- | A path prefix that is prepended to any sent HTTP request.+--+-- Defaults to @mempty@.+servicePath :: Lens' ServiceConfig Builder+servicePath = lens _svcPath (\s a -> s {_svcPath = a})++-- | Whether to use HTTPS/SSL.+--+-- Defaults to @True@.+serviceSecure :: Lens' ServiceConfig Bool+serviceSecure = lens _svcSecure (\s a -> s {_svcSecure = a})++-- | Number of seconds to wait for a response.+serviceTimeout :: Lens' ServiceConfig (Maybe Seconds)+serviceTimeout = lens _svcTimeout (\s a -> s {_svcTimeout = a})++-- | A single part of a (potentially multipart) request body.+--+-- /Note:/ The 'IsString' instance defaults to a @text/plain@ MIME type.+data GBody = GBody !MediaType !RequestBody++instance IsString GBody where+  fromString = GBody ("text" // "plain") . fromString++-- | A lens into the 'MediaType' of a request 'Body'.+bodyContentType :: Lens' GBody MediaType+bodyContentType = lens (\(GBody m _) -> m) (\(GBody _ b) m -> GBody m b)++-- | An intermediary request builder.+data Request = Request+  { _rqPath :: !Builder,+    _rqQuery :: !(DList (ByteString, Maybe ByteString)),+    _rqHeaders :: !(DList (HeaderName, ByteString)),+    _rqBody :: ![GBody]+  }++instance Monoid Request where+  mempty = Request mempty mempty mempty mempty+  mappend = (<>)++instance Semigroup Request where+  a <> b =+    Request+      (_rqPath a <> "/" <> _rqPath b)+      (_rqQuery a <> _rqQuery b)+      (_rqHeaders a <> _rqHeaders b)+      (_rqBody b <> _rqBody a)++appendPath :: Request -> Builder -> Request+appendPath rq x = rq {_rqPath = _rqPath rq <> "/" <> x}++appendPaths :: (ToHttpApiData a) => Request -> [a] -> Request+appendPaths rq [] = rq+appendPaths rq xs = appendPath rq (mconcat (intersperse "/" (map buildSegment xs)))++appendQuery :: Request -> ByteString -> Maybe Text -> Request+appendQuery rq k v =+  rq+    { _rqQuery = DList.snoc (_rqQuery rq) (k, Text.encodeUtf8 <$> v)+    }++appendHeader :: Request -> HeaderName -> Maybe Text -> Request+appendHeader rq _ Nothing = rq+appendHeader rq k (Just v) =+  rq+    { _rqHeaders = DList.snoc (_rqHeaders rq) (k, Text.encodeUtf8 v)+    }++setBody :: Request -> [GBody] -> Request+setBody rq bs = rq {_rqBody = bs}++-- | A materialised 'http-client' request and associated response parser.+data GClient a = GClient+  { _cliAccept :: !(Maybe MediaType),+    _cliMethod :: !Method,+    _cliCheck :: !(Status -> Bool),+    _cliService :: !ServiceConfig,+    _cliRequest :: !Request,+    _cliResponse :: !(Stream -> ResourceT IO (Either (String, LBS.ByteString) a))+  }++clientService :: Lens' (GClient a) ServiceConfig+clientService = lens _cliService (\s a -> s {_cliService = a})++mime ::+  (FromStream c a) =>+  Proxy c ->+  Method ->+  [Int] ->+  Request ->+  ServiceConfig ->+  GClient a+mime p = gClient (fromStream p) (Just (contentType p))++discard ::+  Method ->+  [Int] ->+  Request ->+  ServiceConfig ->+  GClient ()+discard = gClient (\b -> Right <$> Stream.fold Fold.drain b) Nothing++gClient ::+  (Stream -> ResourceT IO (Either (String, LBS.ByteString) a)) ->+  Maybe MediaType ->+  Method ->+  [Int] ->+  Request ->+  ServiceConfig ->+  GClient a+gClient f cs m statuses rq s =+  GClient+    { _cliAccept = cs,+      _cliMethod = m,+      _cliCheck = \status -> fromEnum status `elem` statuses,+      _cliService = s,+      _cliRequest = rq,+      _cliResponse = f+    }++class (Accept c) => ToBody c a where+  toBody :: Proxy c -> a -> GBody++instance ToBody OctetStream ByteString where+  toBody p = GBody (contentType p) . RequestBodyBS++instance ToBody OctetStream LBS.ByteString where+  toBody p = GBody (contentType p) . RequestBodyLBS++instance ToBody PlainText ByteString where+  toBody p = GBody (contentType p) . RequestBodyBS++instance ToBody PlainText LBS.ByteString where+  toBody p = GBody (contentType p) . RequestBodyLBS++instance (ToJSON a) => ToBody JSON a where+  toBody p = GBody (contentType p) . RequestBodyLBS . encode++class (Accept c) => FromStream c a where+  fromStream ::+    Proxy c ->+    Stream ->+    ResourceT IO (Either (String, LBS.ByteString) a)++instance FromStream OctetStream Stream where+  fromStream Proxy = pure . Right++instance (FromJSON a) => FromStream JSON a where+  fromStream Proxy s = do+    bs <- sinkLBS s+    case eitherDecode bs of+      Left e -> pure $! Left (e, bs)+      Right x -> pure $! Right x++class GoogleRequest a where+  type Rs a :: Type+  type Scopes a :: [Symbol]++  requestClient :: a -> GClient (Rs a)++class GoogleClient fn where+  type Fn fn :: Type++  buildClient :: Proxy fn -> Request -> Fn fn++-- | Multiple path captures, with @[xs]@ forming @/<x1>/<x2>/<x2>/...@.+data Captures (s :: Symbol) a++-- | Form a Google style sub-resource, such as @/<capture>:<mode>@.+data CaptureMode (s :: Symbol) (m :: Symbol) a++-- | A Discovery template's reserved expansion, allowing a name to span segments.+data CaptureReserved (s :: Symbol) a++data CaptureReservedMode (s :: Symbol) (m :: Symbol) a++data MultipartRelated (cs :: [Type]) m++instance+  ( ToBody c m,+    GoogleClient fn+  ) =>+  GoogleClient (MultipartRelated (c ': cs) m :> fn)+  where+  type Fn (MultipartRelated (c ': cs) m :> fn) = m -> GBody -> Fn fn++  buildClient Proxy rq m b =+    buildClient (Proxy :: Proxy fn) $+      setBody rq [toBody (Proxy :: Proxy c) m, b]++instance (GoogleClient fn) => GoogleClient (AltMedia :> fn) where+  type Fn (AltMedia :> fn) = GBody -> Fn fn++  buildClient Proxy rq b =+    buildClient (Proxy :: Proxy fn) $+      setBody rq [b]++instance (KnownSymbol s, GoogleClient fn) => GoogleClient (s :> fn) where+  type Fn (s :> fn) = Fn fn++  buildClient Proxy rq =+    buildClient (Proxy :: Proxy fn) $+      appendPath rq (buildSymbol (Proxy :: Proxy s))++instance (GoogleClient a, GoogleClient b) => GoogleClient (a :<|> b) where+  type Fn (a :<|> b) = Fn a :<|> Fn b++  buildClient Proxy rq =+    buildClient (Proxy :: Proxy a) rq+      :<|> buildClient (Proxy :: Proxy b) rq++instance+  ( ToHttpApiData a,+    GoogleClient fn+  ) =>+  GoogleClient (Capture s a :> fn)+  where+  type Fn (Capture s a :> fn) = a -> Fn fn++  buildClient Proxy rq =+    buildClient (Proxy :: Proxy fn)+      . appendPath rq+      . buildSegment++instance+  ( ToHttpApiData a,+    GoogleClient fn+  ) =>+  GoogleClient (Captures s a :> fn)+  where+  type Fn (Captures s a :> fn) = [a] -> Fn fn++  buildClient Proxy rq =+    buildClient (Proxy :: Proxy fn)+      . appendPaths rq++instance+  ( KnownSymbol m,+    ToHttpApiData a,+    GoogleClient fn+  ) =>+  GoogleClient (CaptureMode s m a :> fn)+  where+  type Fn (CaptureMode s m a :> fn) = a -> Fn fn++  buildClient Proxy rq x =+    buildClient (Proxy :: Proxy fn)+      . appendPath rq+      $ buildSegment x <> ":" <> buildSymbol (Proxy :: Proxy m)++instance (ToHttpApiData a, GoogleClient fn) => GoogleClient (CaptureReserved s a :> fn) where+  type Fn (CaptureReserved s a :> fn) = a -> Fn fn++  buildClient Proxy rq =+    buildClient (Proxy :: Proxy fn) . appendPath rq . buildReservedPath++instance (KnownSymbol m, ToHttpApiData a, GoogleClient fn) => GoogleClient (CaptureReservedMode s m a :> fn) where+  type Fn (CaptureReservedMode s m a :> fn) = a -> Fn fn++  buildClient Proxy rq x =+    buildClient (Proxy :: Proxy fn) $+      appendPath rq (buildReservedPath x <> ":" <> buildSymbol (Proxy :: Proxy m))++instance+  ( KnownSymbol s,+    ToHttpApiData a,+    GoogleClient fn+  ) =>+  GoogleClient (QueryParam s a :> fn)+  where+  type Fn (QueryParam s a :> fn) = Maybe a -> Fn fn++  buildClient Proxy rq mx = buildClient (Proxy :: Proxy fn) $+    case mx of+      Nothing -> rq+      Just x -> appendQuery rq k v+        where+          k = byteSymbol (Proxy :: Proxy s)+          v = Just (toQueryParam x)++instance+  ( KnownSymbol s,+    ToHttpApiData a,+    GoogleClient fn+  ) =>+  GoogleClient (QueryParams s a :> fn)+  where+  type Fn (QueryParams s a :> fn) = [a] -> Fn fn++  buildClient Proxy rq = buildClient (Proxy :: Proxy fn) . Foldable.foldl' go rq+    where+      go r = appendQuery r k . Just . toQueryParam++      k = byteSymbol (Proxy :: Proxy s)++instance+  ( KnownSymbol s,+    ToHttpApiData a,+    GoogleClient fn+  ) =>+  GoogleClient (Header s a :> fn)+  where+  type Fn (Header s a :> fn) = Maybe a -> Fn fn++  buildClient Proxy rq mx = buildClient (Proxy :: Proxy fn) $+    case mx of+      Nothing -> rq+      Just x -> appendHeader rq (CI.mk k) v+        where+          k = byteSymbol (Proxy :: Proxy s)+          v = Just (toQueryParam x)++instance+  ( ToBody c a,+    GoogleClient fn+  ) =>+  GoogleClient (ReqBody (c ': cs) a :> fn)+  where+  type Fn (ReqBody (c ': cs) a :> fn) = a -> Fn fn++  buildClient Proxy rq x =+    buildClient (Proxy :: Proxy fn) $+      setBody rq [toBody (Proxy :: Proxy c) x]++instance {-# OVERLAPPABLE #-} (FromStream c a) => GoogleClient (Get (c ': cs) a) where+  type Fn (Get (c ': cs) a) = ServiceConfig -> GClient a++  buildClient Proxy = mime (Proxy :: Proxy c) methodGet [200, 203]++instance {-# OVERLAPPING #-} GoogleClient (Get (c ': cs) ()) where+  type Fn (Get (c ': cs) ()) = ServiceConfig -> GClient ()++  buildClient Proxy = discard methodGet [204]++instance {-# OVERLAPPABLE #-} (FromStream c a, cs' ~ (c ': cs)) => GoogleClient (Post cs' a) where+  type Fn (Post cs' a) = ServiceConfig -> GClient a++  buildClient Proxy = mime (Proxy :: Proxy c) methodPost [200, 201]++instance {-# OVERLAPPING #-} GoogleClient (Post cs ()) where+  type Fn (Post cs ()) = ServiceConfig -> GClient ()++  buildClient Proxy = discard methodPost [204]++instance {-# OVERLAPPABLE #-} (FromStream c a) => GoogleClient (Put (c ': cs) a) where+  type Fn (Put (c ': cs) a) = ServiceConfig -> GClient a++  buildClient Proxy = mime (Proxy :: Proxy c) methodPut [200, 201]++instance {-# OVERLAPPING #-} GoogleClient (Put (c ': cs) ()) where+  type Fn (Put (c ': cs) ()) = ServiceConfig -> GClient ()++  buildClient Proxy = discard methodPut [204]++instance {-# OVERLAPPABLE #-} (FromStream c a) => GoogleClient (Patch (c ': cs) a) where+  type Fn (Patch (c ': cs) a) = ServiceConfig -> GClient a++  buildClient Proxy = mime (Proxy :: Proxy c) methodPatch [200, 201]++instance {-# OVERLAPPING #-} GoogleClient (Patch (c ': cs) ()) where+  type Fn (Patch (c ': cs) ()) = ServiceConfig -> GClient ()++  buildClient Proxy = discard methodPatch [204]++instance {-# OVERLAPPABLE #-} (FromStream c a) => GoogleClient (Delete (c ': cs) a) where+  type Fn (Delete (c ': cs) a) = ServiceConfig -> GClient a++  buildClient Proxy = mime (Proxy :: Proxy c) methodDelete [200, 202]++instance {-# OVERLAPPING #-} GoogleClient (Delete (c ': cs) ()) where+  type Fn (Delete (c ': cs) ()) = ServiceConfig -> GClient ()++  buildClient Proxy = discard methodDelete [204]++sinkLBS :: Stream -> ResourceT IO LBS.ByteString+sinkLBS = fmap LBS.fromChunks . Stream.fold Fold.toList++buildSegment :: (ToHttpApiData a) => a -> Builder+buildSegment = Build.fromText . Text.decodeUtf8 . urlEncode True . Text.encodeUtf8 . toQueryParam++buildReservedPath :: (ToHttpApiData a) => a -> Builder+buildReservedPath =+  Build.fromText+    . Text.intercalate "/"+    . map (Text.decodeUtf8 . urlEncode False . Text.encodeUtf8)+    . Text.splitOn "/"+    . toQueryParam++buildText :: (ToHttpApiData a) => a -> Builder+buildText = Build.fromText . toQueryParam++buildSymbol :: forall n proxy. (KnownSymbol n) => proxy n -> Builder+buildSymbol = Build.fromString . symbolVal++byteSymbol :: forall n proxy. (KnownSymbol n) => proxy n -> ByteString+byteSymbol = BS8.pack . symbolVal++-- | An integral value representing seconds.+newtype Seconds = Seconds Int+  deriving stock (Eq, Ord, Read, Show, Generic)+  deriving newtype (Enum, Bounded, Num, Integral, Real)++seconds :: Seconds -> Int+seconds (Seconds n)+  | n < 0 = 0+  | otherwise = n++microseconds :: Seconds -> Int+microseconds = (1000000 *) . seconds++newtype FieldMask = FieldMask {fromFieldMask :: Text}+  deriving stock (Eq, Ord, Show, Read, Generic)+  deriving newtype (IsString, FromHttpApiData, ToHttpApiData, FromJSON, ToJSON)
+ test/Main.hs view
@@ -0,0 +1,35 @@+module Main (main) where++import Data.Aeson qualified as JSON+import Data.Aeson.Types (parseMaybe)+import Data.Text.Lazy.Builder (toLazyText)+import Test.Tasty+import Test.Tasty.HUnit+import Unkai.Prelude++main :: IO ()+main =+  defaultMain $+    testGroup+      "core"+      [ testCase "a simple capture encodes a single UTF-8 segment" $ do+          let client = buildClient (Proxy @("b" :> Capture "object" Text :> Get '[JSON] ())) mempty "x/y%20 á?"+          toLazyText (_rqPath (_cliRequest (client service))) @?= "/b/x%2Fy%2520%20%C3%A1%3F",+        testCase "a repeated capture encodes each segment and inserts one separator" $ do+          let client = buildClient (Proxy @("b" :> Captures "object" Text :> Get '[JSON] ())) mempty ["x/y", "a b"]+          toLazyText (_rqPath (_cliRequest (client service))) @?= "/b/x%2Fy/a%20b"+          toLazyText (_rqPath (appendPaths (appendPath mempty "b") ([] :: [Text]))) @?= "/b",+        testCase "a mode suffix remains literal and reserved expansions retain slashes" $ do+          let simple = buildClient (Proxy @(CaptureMode "name" "move" Text :> Get '[JSON] ())) mempty "x/y"+              reserved = buildClient (Proxy @(CaptureReserved "name" Text :> Get '[JSON] ())) mempty "x/y%20"+          toLazyText (_rqPath (_cliRequest (simple service))) @?= "/x%2Fy:move"+          toLazyText (_rqPath (_cliRequest (reserved service))) @?= "/x/y%2520",+        testCase "patch fields distinguish absence, assignment and null" $ do+          let states = [Omit, Set ("new" :: Text), Clear]+              encode state = object (maybeToList (patchField toJSON "field" state))+              decode = withObject "test" (parsePatchField parseJSON "field")+          map encode states @?= [object [], object ["field" .= ("new" :: Text)], object ["field" .= JSON.Null]]+          map (parseMaybe decode . encode) states @?= map Just states+      ]+  where+    service = defaultService "test" "example.test"
+ unkai-core.cabal view
@@ -0,0 +1,102 @@+cabal-version: 3.12+name: unkai-core+version: 0.1.0.0+synopsis: Core data types and functionality for Unkai libraries.+description:+  Core data types, functionality and serialisation primitives shared by+  the generated Unkai Google Cloud service libraries.+  .+  The external interface of this library is stable with respect to the+  downstream Unkai libraries only, and is not intended for use outside them.++homepage: https://github.com/shinzui/unkai+bug-reports: https://github.com/shinzui/unkai/issues+license: MPL-2.0+license-file: LICENSE+author: Brendan Hay, Nadeem Bitar+maintainer: Nadeem Bitar <nadeem@gmail.com>+copyright: Copyright (c) 2015-2025 Brendan Hay, (c) 2026 Nadeem Bitar+category: Google+build-type: Simple+tested-with: ghc ==9.12.4+extra-doc-files:+  CHANGELOG.md+  README.md++source-repository head+  type: git+  location: https://github.com/shinzui/unkai.git+  subdir: lib/unkai-core++common common+  default-language: GHC2024+  default-extensions:+    DeriveAnyClass+    DuplicateRecordFields+    OverloadedLabels+    OverloadedStrings++  ghc-options:+    -Wall+    -Wcompat+    -Widentities+    -Wincomplete-uni-patterns+    -Wincomplete-record-updates+    -Wredundant-constraints+    -Wunused-packages+    -Wmissing-export-lists+    -Wpartial-fields+    -Wmissing-deriving-strategies+    -fhide-source-paths+    -funbox-strict-fields++library+  import: common+  hs-source-dirs: src+  exposed-modules:+    Unkai.Data.Base64+    Unkai.Data.JSON+    Unkai.Data.Time+    Unkai.Prelude+    Unkai.Types++  build-depends:+    aeson ^>=2.2,+    attoparsec ^>=0.14,+    base >=4.21 && <5,+    base64 ^>=1.0,+    bytestring ^>=0.12,+    case-insensitive ^>=1.2,+    dlist ^>=1.0,+    exceptions ^>=0.10,+    hashable >=1.4 && <1.6,+    http-api-data ^>=0.6,+    http-client ^>=0.7,+    http-media ^>=0.8,+    http-types ^>=0.12,+    lens ^>=5.3,+    resourcet ^>=1.3,+    scientific ^>=0.3,+    servant ^>=0.20.1,+    streamly-core ^>=0.3,+    text ^>=2.1,+    time >=1.12 && <1.15,+    unordered-containers ^>=0.2.20,++test-suite unkai-core-test+  import: common+  type: exitcode-stdio-1.0+  hs-source-dirs: test+  main-is: Main.hs+  ghc-options:+    -threaded+    -rtsopts+    -with-rtsopts=-N++  build-depends:+    aeson,+    base >=4.21 && <5,+    tasty ^>=1.5,+    tasty-hunit,+    text,+    unkai-core,