{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}

{- |
Module      : Singular.Registry.PlainJson
Description : A payload written as plain JSON, and read back as plain JSON
License     : Apache-2.0

A payload is Plutus data. The detailed schema ('datumFromJson') writes
any datum exactly and is how the previous release read every payload
file. The plain mapping lets a file hold ordinary JSON instead, mapped to
data by a table (#719):

* a whole number of at most 'plainDigitLimit' digits is the integer;
* a text is the byte string of its UTF-8;
* @true@ and @false@ are the constructors 1 and 0 without fields;
* an array is the list of its items;
* an object is the map from each key, as a byte string of its UTF-8, to
  its value, entries in ascending order of the key bytes;
* @null@ and a number with a fraction are refused.

'plainFromData' is the reading in the other direction: it returns the
JSON the table started from, and nothing for data the table could not
have produced. 'payloadView' chooses what a command prints: the plain
JSON when there is one, else the detailed schema, with the schema named.

Nothing here reads a file or names a command. The one place that reads a
payload file for a command is @Singular.CLI.Payload@.
-}
module Singular.Registry.PlainJson
    ( -- * The schema setting
      PayloadSchema (..)
    , schemaName
    , parseSchemaName

      -- * The plain mapping and its reading
    , plainDigitLimit
    , plainToData
    , plainFromData

      -- * Refusals
    , PlainRefusal (..)
    , PlainReason (..)
    , PathStep (..)
    , renderPlainRefusal

      -- * A payload document under a schema
    , payloadFromJson

      -- * What a command prints
    , PayloadView (..)
    , payloadView
    ) where

import Data.Aeson (Value (..))
import Data.Aeson qualified as Aeson
import Data.Aeson.Key qualified as Key
import Data.Aeson.KeyMap qualified as KeyMap
import Data.ByteString (ByteString)
import Data.Foldable (toList)
import Data.List (sortOn)
import Data.Scientific (Scientific)
import Data.Scientific qualified as Sci
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Encoding qualified as TE
import PlutusCore.Data qualified as PLC

import Singular.Registry.Application (datumFromJson, datumToJson)

-- | Which form a payload file is written in.
data PayloadSchema
    = -- | Plain JSON, mapped by the table
      PlainSchema
    | -- | The detailed Plutus data schema
      DetailedSchema
    deriving stock (PayloadSchema -> PayloadSchema -> Bool
(PayloadSchema -> PayloadSchema -> Bool)
-> (PayloadSchema -> PayloadSchema -> Bool) -> Eq PayloadSchema
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PayloadSchema -> PayloadSchema -> Bool
== :: PayloadSchema -> PayloadSchema -> Bool
$c/= :: PayloadSchema -> PayloadSchema -> Bool
/= :: PayloadSchema -> PayloadSchema -> Bool
Eq, Int -> PayloadSchema -> ShowS
[PayloadSchema] -> ShowS
PayloadSchema -> String
(Int -> PayloadSchema -> ShowS)
-> (PayloadSchema -> String)
-> ([PayloadSchema] -> ShowS)
-> Show PayloadSchema
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PayloadSchema -> ShowS
showsPrec :: Int -> PayloadSchema -> ShowS
$cshow :: PayloadSchema -> String
show :: PayloadSchema -> String
$cshowList :: [PayloadSchema] -> ShowS
showList :: [PayloadSchema] -> ShowS
Show)

-- | The lower-case name of a schema, as the flag spells it.
schemaName :: PayloadSchema -> Text
schemaName :: PayloadSchema -> Text
schemaName = \case
    PayloadSchema
PlainSchema -> Text
"plain"
    PayloadSchema
DetailedSchema -> Text
"detailed"

-- | The schema a flag value names: exactly the two names, in lower case.
parseSchemaName :: Text -> Maybe PayloadSchema
parseSchemaName :: Text -> Maybe PayloadSchema
parseSchemaName = \case
    Text
"plain" -> PayloadSchema -> Maybe PayloadSchema
forall a. a -> Maybe a
Just PayloadSchema
PlainSchema
    Text
"detailed" -> PayloadSchema -> Maybe PayloadSchema
forall a. a -> Maybe a
Just PayloadSchema
DetailedSchema
    Text
_ -> Maybe PayloadSchema
forall a. Maybe a
Nothing

-- | The most digits a stored whole number may have.
plainDigitLimit :: Int
plainDigitLimit :: Int
plainDigitLimit = Int
1000

-- | One step from the document to the offending value.
data PathStep
    = -- | An object key
      KeyStep Text
    | -- | An array item
      IndexStep Int
    deriving stock (PathStep -> PathStep -> Bool
(PathStep -> PathStep -> Bool)
-> (PathStep -> PathStep -> Bool) -> Eq PathStep
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PathStep -> PathStep -> Bool
== :: PathStep -> PathStep -> Bool
$c/= :: PathStep -> PathStep -> Bool
/= :: PathStep -> PathStep -> Bool
Eq, Int -> PathStep -> ShowS
[PathStep] -> ShowS
PathStep -> String
(Int -> PathStep -> ShowS)
-> (PathStep -> String) -> ([PathStep] -> ShowS) -> Show PathStep
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PathStep -> ShowS
showsPrec :: Int -> PathStep -> ShowS
$cshow :: PathStep -> String
show :: PathStep -> String
$cshowList :: [PathStep] -> ShowS
showList :: [PathStep] -> ShowS
Show)

-- | Why a value has no Plutus data counterpart.
data PlainReason
    = -- | A number with a fraction
      HasFraction Scientific
    | -- | A whole number with more digits than the limit
      TooLarge Scientific
    | -- | @null@
      IsNull
    deriving stock (PlainReason -> PlainReason -> Bool
(PlainReason -> PlainReason -> Bool)
-> (PlainReason -> PlainReason -> Bool) -> Eq PlainReason
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PlainReason -> PlainReason -> Bool
== :: PlainReason -> PlainReason -> Bool
$c/= :: PlainReason -> PlainReason -> Bool
/= :: PlainReason -> PlainReason -> Bool
Eq, Int -> PlainReason -> ShowS
[PlainReason] -> ShowS
PlainReason -> String
(Int -> PlainReason -> ShowS)
-> (PlainReason -> String)
-> ([PlainReason] -> ShowS)
-> Show PlainReason
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PlainReason -> ShowS
showsPrec :: Int -> PlainReason -> ShowS
$cshow :: PlainReason -> String
show :: PlainReason -> String
$cshowList :: [PlainReason] -> ShowS
showList :: [PlainReason] -> ShowS
Show)

-- | A value the plain mapping refuses, and where it is.
data PlainRefusal = PlainRefusal
    { PlainRefusal -> [PathStep]
refusalPath :: [PathStep]
    -- ^ From the document: empty for the document itself
    , PlainRefusal -> PlainReason
refusalReason :: PlainReason
    }
    deriving stock (PlainRefusal -> PlainRefusal -> Bool
(PlainRefusal -> PlainRefusal -> Bool)
-> (PlainRefusal -> PlainRefusal -> Bool) -> Eq PlainRefusal
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PlainRefusal -> PlainRefusal -> Bool
== :: PlainRefusal -> PlainRefusal -> Bool
$c/= :: PlainRefusal -> PlainRefusal -> Bool
/= :: PlainRefusal -> PlainRefusal -> Bool
Eq, Int -> PlainRefusal -> ShowS
[PlainRefusal] -> ShowS
PlainRefusal -> String
(Int -> PlainRefusal -> ShowS)
-> (PlainRefusal -> String)
-> ([PlainRefusal] -> ShowS)
-> Show PlainRefusal
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PlainRefusal -> ShowS
showsPrec :: Int -> PlainRefusal -> ShowS
$cshow :: PlainRefusal -> String
show :: PlainRefusal -> String
$cshowList :: [PlainRefusal] -> ShowS
showList :: [PlainRefusal] -> ShowS
Show)

{- | The sentence naming the value and its path, written as a path from
the document: @$@ is the whole document, @.name@ an object key, @[2]@ an
item.
-}
renderPlainRefusal :: PlainRefusal -> Text
renderPlainRefusal :: PlainRefusal -> Text
renderPlainRefusal (PlainRefusal [PathStep]
path PlainReason
reason) = case PlainReason
reason of
    PlainReason
IsNull ->
        Text
"null at " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
at Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" has no Plutus data counterpart"
    HasFraction Scientific
n ->
        Text
"the number "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Scientific -> Text
renderNumber Scientific
n
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" at "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
at
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" has a fraction; only whole numbers are stored"
    TooLarge Scientific
n ->
        Text
"the number at "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
at
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" is too large: more than "
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> String -> Text
T.pack (Int -> String
forall a. Show a => a -> String
show Int
plainDigitLimit)
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" digits ("
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Scientific -> Text
renderNumber Scientific
n
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
")"
  where
    at :: Text
at = Text
"$" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> [Text] -> Text
T.concat ((PathStep -> Text) -> [PathStep] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map PathStep -> Text
step [PathStep]
path)
    step :: PathStep -> Text
step = \case
        KeyStep Text
k -> Text
"." Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
k
        IndexStep Int
i -> Text
"[" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> String -> Text
T.pack (Int -> String
forall a. Show a => a -> String
show Int
i) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"]"

{- | A number as a reader writes it, without expanding a large exponent and
without printing thousands of digits.
-}
renderNumber :: Scientific -> Text
renderNumber :: Scientific -> Text
renderNumber Scientific
n
    | Integer -> Integer
forall a. Num a => a -> a
abs Integer
exponent10 Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Integer
30 =
        Text -> Text
shorten (String -> Text
T.pack (FPFormat -> Maybe Int -> Scientific -> String
Sci.formatScientific FPFormat
Sci.Fixed Maybe Int
forall a. Maybe a
Nothing Scientific
n))
    | Bool
otherwise =
        Text
sign Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
shortDigits Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"e" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> String -> Text
T.pack (Integer -> String
forall a. Show a => a -> String
show (Integer
exponent10 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
zeros))
  where
    -- the exponent is an Int that may be minBound: all arithmetic on it is on Integer
    exponent10 :: Integer
exponent10 = Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Scientific -> Int
Sci.base10Exponent Scientific
n)
    (Integer
digits, Integer
zeros) = Integer -> (Integer, Integer)
stripZeros (Integer -> Integer
forall a. Num a => a -> a
abs (Scientific -> Integer
Sci.coefficient Scientific
n))
    sign :: Text
sign = if Scientific -> Integer
Sci.coefficient Scientific
n Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
0 then Text
"-" else Text
""
    shortDigits :: Text
shortDigits = Text -> Text
shorten (String -> Text
T.pack (Integer -> String
forall a. Show a => a -> String
show Integer
digits))
    shorten :: Text -> Text
shorten Text
t
        | Text -> Int
T.length Text
t Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
shown = Text
t
        | Bool
otherwise = Int -> Text -> Text
T.take Int
shown Text
t Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"..."
    shown :: Int
shown = Int
40

-- | What the digits and the sign of a number say about storing it.
data Whole
    = Whole Integer
    | Fractional
    | PastLimit

{- | A number judged by its size before it is expanded: normalised, a
number is whole when its exponent is not negative, and then it has the
digits of its coefficient followed by that many zeros.
-}
wholeOf :: Scientific -> Whole
wholeOf :: Scientific -> Whole
wholeOf Scientific
s
    | Integer
coefficient Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
== Integer
0 = Integer -> Whole
Whole Integer
0
    | Integer
e Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
0 = Whole
Fractional
    | Integer
e Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Int -> Integer
forall a. Integral a => a -> Integer
toInteger Int
plainDigitLimit = Whole
PastLimit
    | Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Integer -> Int
integerDigits Integer
c) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
e Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Int -> Integer
forall a. Integral a => a -> Integer
toInteger Int
plainDigitLimit =
        Whole
PastLimit
    | Bool
otherwise = Integer -> Whole
Whole (Integer
c Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
10 Integer -> Integer -> Integer
forall a b. (Num a, Integral b) => a -> b -> a
^ Integer
e)
  where
    coefficient :: Integer
coefficient = Scientific -> Integer
Sci.coefficient Scientific
s
    (Integer
c, Integer
zeros) = Integer -> (Integer, Integer)
stripZeros Integer
coefficient
    -- the exponent is an Int that may be minBound or maxBound: the sum is an Integer
    e :: Integer
e = Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Scientific -> Int
Sci.base10Exponent Scientific
s) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
zeros

{- | A coefficient without its trailing decimal zeros, and how many it had:
the zeros move into the exponent, which is then summed as an Integer so no
exponent an Int can hold overflows.
-}
stripZeros :: Integer -> (Integer, Integer)
stripZeros :: Integer -> (Integer, Integer)
stripZeros Integer
c =
    let stripped :: Scientific
stripped = Scientific -> Scientific
Sci.normalize (Integer -> Int -> Scientific
Sci.scientific Integer
c Int
0)
    in  (Scientific -> Integer
Sci.coefficient Scientific
stripped, Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Scientific -> Int
Sci.base10Exponent Scientific
stripped))

-- | The number of decimal digits of an integer, its sign aside.
integerDigits :: Integer -> Int
integerDigits :: Integer -> Int
integerDigits = String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (String -> Int) -> (Integer -> String) -> Integer -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Integer -> String
forall a. Show a => a -> String
show (Integer -> String) -> (Integer -> Integer) -> Integer -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Integer -> Integer
forall a. Num a => a -> a
abs

{- | The data a plain JSON document stands for, or the first value refused:
objects are walked in ascending order of the key bytes and arrays in
order, so the refusal is a function of the document.
-}
plainToData :: Value -> Either PlainRefusal PLC.Data
plainToData :: Value -> Either PlainRefusal Data
plainToData = [PathStep] -> Value -> Either PlainRefusal Data
go []
  where
    -- the path is kept last step first and written out only on a refusal
    go :: [PathStep] -> Value -> Either PlainRefusal Data
go [PathStep]
path = \case
        Value
Null -> [PathStep] -> PlainReason -> Either PlainRefusal Data
forall {b}. [PathStep] -> PlainReason -> Either PlainRefusal b
refuse [PathStep]
path PlainReason
IsNull
        Bool Bool
b -> Data -> Either PlainRefusal Data
forall a b. b -> Either a b
Right (Integer -> [Data] -> Data
PLC.Constr (if Bool
b then Integer
1 else Integer
0) [])
        String Text
t -> Data -> Either PlainRefusal Data
forall a b. b -> Either a b
Right (ByteString -> Data
PLC.B (Text -> ByteString
TE.encodeUtf8 Text
t))
        Number Scientific
n -> case Scientific -> Whole
wholeOf Scientific
n of
            Whole Integer
i -> Data -> Either PlainRefusal Data
forall a b. b -> Either a b
Right (Integer -> Data
PLC.I Integer
i)
            Whole
Fractional -> [PathStep] -> PlainReason -> Either PlainRefusal Data
forall {b}. [PathStep] -> PlainReason -> Either PlainRefusal b
refuse [PathStep]
path (Scientific -> PlainReason
HasFraction Scientific
n)
            Whole
PastLimit -> [PathStep] -> PlainReason -> Either PlainRefusal Data
forall {b}. [PathStep] -> PlainReason -> Either PlainRefusal b
refuse [PathStep]
path (Scientific -> PlainReason
TooLarge Scientific
n)
        Array Array
xs ->
            [Data] -> Data
PLC.List
                ([Data] -> Data)
-> Either PlainRefusal [Data] -> Either PlainRefusal Data
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ((Int, Value) -> Either PlainRefusal Data)
-> [(Int, Value)] -> Either PlainRefusal [Data]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse
                    (\(Int
i, Value
x) -> [PathStep] -> Value -> Either PlainRefusal Data
go (Int -> PathStep
IndexStep Int
i PathStep -> [PathStep] -> [PathStep]
forall a. a -> [a] -> [a]
: [PathStep]
path) Value
x)
                    ([Int] -> [Value] -> [(Int, Value)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] (Array -> [Value]
forall a. Vector a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList Array
xs))
        Object Object
o ->
            [(Data, Data)] -> Data
PLC.Map
                ([(Data, Data)] -> Data)
-> Either PlainRefusal [(Data, Data)] -> Either PlainRefusal Data
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ((ByteString, Text, Value) -> Either PlainRefusal (Data, Data))
-> [(ByteString, Text, Value)]
-> Either PlainRefusal [(Data, Data)]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse
                    ( \(ByteString
bytes, Text
key, Value
x) -> do
                        value <- [PathStep] -> Value -> Either PlainRefusal Data
go (Text -> PathStep
KeyStep Text
key PathStep -> [PathStep] -> [PathStep]
forall a. a -> [a] -> [a]
: [PathStep]
path) Value
x
                        pure (PLC.B bytes, value)
                    )
                    (Object -> [(ByteString, Text, Value)]
forall {c}. KeyMap c -> [(ByteString, Text, c)]
keyed Object
o)
    refuse :: [PathStep] -> PlainReason -> Either PlainRefusal b
refuse [PathStep]
path = PlainRefusal -> Either PlainRefusal b
forall a b. a -> Either a b
Left (PlainRefusal -> Either PlainRefusal b)
-> (PlainReason -> PlainRefusal)
-> PlainReason
-> Either PlainRefusal b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [PathStep] -> PlainReason -> PlainRefusal
PlainRefusal ([PathStep] -> [PathStep]
forall a. [a] -> [a]
reverse [PathStep]
path)
    keyed :: KeyMap c -> [(ByteString, Text, c)]
keyed KeyMap c
o =
        ((ByteString, Text, c) -> ByteString)
-> [(ByteString, Text, c)] -> [(ByteString, Text, c)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn
            (\(ByteString
bytes, Text
_, c
_) -> ByteString
bytes)
            [ (Text -> ByteString
TE.encodeUtf8 Text
key, Text
key, c
x)
            | (Key
k, c
x) <- KeyMap c -> [(Key, c)]
forall v. KeyMap v -> [(Key, v)]
KeyMap.toList KeyMap c
o
            , let key :: Text
key = Key -> Text
Key.toText Key
k
            ]

{- | The plain JSON a datum stands for, when it has one: an integer of at
most 'plainDigitLimit' digits, a byte string that is UTF-8, a list of
items that have one, a map whose keys are UTF-8 byte strings in strictly
ascending order of bytes and whose values have one, and the constructors 0
and 1 without fields.
-}
plainFromData :: PLC.Data -> Maybe Value
plainFromData :: Data -> Maybe Value
plainFromData = \case
    PLC.I Integer
n
        | Integer -> Int
integerDigits Integer
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
plainDigitLimit -> Value -> Maybe Value
forall a. a -> Maybe a
Just (Scientific -> Value
Number (Integer -> Scientific
forall a. Num a => Integer -> a
fromInteger Integer
n))
        | Bool
otherwise -> Maybe Value
forall a. Maybe a
Nothing
    PLC.B ByteString
bytes -> Text -> Value
String (Text -> Value) -> Maybe Text -> Maybe Value
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Maybe Text
utf8 ByteString
bytes
    PLC.List [Data]
items -> [Value] -> Value
forall a. ToJSON a => a -> Value
Aeson.toJSON ([Value] -> Value) -> Maybe [Value] -> Maybe Value
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Data -> Maybe Value) -> [Data] -> Maybe [Value]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse Data -> Maybe Value
plainFromData [Data]
items
    PLC.Map [(Data, Data)]
entries -> do
        keyed <- ((Data, Data) -> Maybe (ByteString, Text, Value))
-> [(Data, Data)] -> Maybe [(ByteString, Text, Value)]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (Data, Data) -> Maybe (ByteString, Text, Value)
entry [(Data, Data)]
entries
        let keys = [ByteString
bytes | (ByteString
bytes, Text
_, Value
_) <- [(ByteString, Text, Value)]
keyed]
        if and (zipWith (<) keys (drop 1 keys))
            then
                Just $
                    Object $
                        KeyMap.fromList
                            [(Key.fromText key, x) | (_, key, x) <- keyed]
            else Nothing
    PLC.Constr Integer
0 [] -> Value -> Maybe Value
forall a. a -> Maybe a
Just (Bool -> Value
Bool Bool
False)
    PLC.Constr Integer
1 [] -> Value -> Maybe Value
forall a. a -> Maybe a
Just (Bool -> Value
Bool Bool
True)
    PLC.Constr Integer
_ [Data]
_ -> Maybe Value
forall a. Maybe a
Nothing
  where
    entry :: (Data, Data) -> Maybe (ByteString, Text, Value)
entry (Data
k, Data
v) = case Data
k of
        PLC.B ByteString
bytes -> do
            key <- ByteString -> Maybe Text
utf8 ByteString
bytes
            x <- plainFromData v
            Just (bytes, key, x)
        Data
_ -> Maybe (ByteString, Text, Value)
forall a. Maybe a
Nothing

-- | A byte string as text, when it is valid UTF-8.
utf8 :: ByteString -> Maybe Text
utf8 :: ByteString -> Maybe Text
utf8 = (UnicodeException -> Maybe Text)
-> (Text -> Maybe Text)
-> Either UnicodeException Text
-> Maybe Text
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Maybe Text -> UnicodeException -> Maybe Text
forall a b. a -> b -> a
const Maybe Text
forall a. Maybe a
Nothing) Text -> Maybe Text
forall a. a -> Maybe a
Just (Either UnicodeException Text -> Maybe Text)
-> (ByteString -> Either UnicodeException Text)
-> ByteString
-> Maybe Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either UnicodeException Text
TE.decodeUtf8'

{- | A payload document read under a schema. The detailed schema is the
reader of the previous release, refusals unchanged. The plain schema
refuses a whole document that the detailed schema accepts, with the
instruction to say so, and only then maps.
-}
payloadFromJson :: PayloadSchema -> Value -> Either Text PLC.Data
payloadFromJson :: PayloadSchema -> Value -> Either Text Data
payloadFromJson PayloadSchema
schema Value
document = case PayloadSchema
schema of
    PayloadSchema
DetailedSchema -> (String -> Either Text Data)
-> (Data -> Either Text Data)
-> Either String Data
-> Either Text Data
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Text -> Either Text Data
forall a b. a -> Either a b
Left (Text -> Either Text Data)
-> (String -> Text) -> String -> Either Text Data
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
T.pack) Data -> Either Text Data
forall a b. b -> Either a b
Right (Value -> Either String Data
datumFromJson Value
document)
    PayloadSchema
PlainSchema -> case Value -> Either String Data
datumFromJson Value
document of
        Right Data
_ -> Text -> Either Text Data
forall a b. a -> Either a b
Left Text
detailedDocumentInPlainMode
        Left String
_ -> (PlainRefusal -> Either Text Data)
-> (Data -> Either Text Data)
-> Either PlainRefusal Data
-> Either Text Data
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Text -> Either Text Data
forall a b. a -> Either a b
Left (Text -> Either Text Data)
-> (PlainRefusal -> Text) -> PlainRefusal -> Either Text Data
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PlainRefusal -> Text
renderPlainRefusal) Data -> Either Text Data
forall a b. b -> Either a b
Right (Value -> Either PlainRefusal Data
plainToData Value
document)

-- | The sentence for a detailed-schema document read as plain JSON.
detailedDocumentInPlainMode :: Text
detailedDocumentInPlainMode :: Text
detailedDocumentInPlainMode =
    Text
"the file is Plutus data in the detailed schema: say so with \
    \--payload-schema detailed, or nest it in an object to store it as plain \
    \JSON"

-- | What a command prints of a payload: the schema and the JSON in it.
data PayloadView = PayloadView
    { PayloadView -> PayloadSchema
viewSchema :: PayloadSchema
    -- ^ The schema the JSON is in
    , PayloadView -> Value
viewJson :: Value
    -- ^ The payload: plain JSON, or the detailed schema of the data
    }
    deriving stock (PayloadView -> PayloadView -> Bool
(PayloadView -> PayloadView -> Bool)
-> (PayloadView -> PayloadView -> Bool) -> Eq PayloadView
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PayloadView -> PayloadView -> Bool
== :: PayloadView -> PayloadView -> Bool
$c/= :: PayloadView -> PayloadView -> Bool
/= :: PayloadView -> PayloadView -> Bool
Eq, Int -> PayloadView -> ShowS
[PayloadView] -> ShowS
PayloadView -> String
(Int -> PayloadView -> ShowS)
-> (PayloadView -> String)
-> ([PayloadView] -> ShowS)
-> Show PayloadView
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PayloadView -> ShowS
showsPrec :: Int -> PayloadView -> ShowS
$cshow :: PayloadView -> String
show :: PayloadView -> String
$cshowList :: [PayloadView] -> ShowS
showList :: [PayloadView] -> ShowS
Show)

{- | The plain reading when the data has one, else the detailed schema of
the data. Plain exactly when 'plainFromData' returns the JSON.
-}
payloadView :: PLC.Data -> PayloadView
payloadView :: Data -> PayloadView
payloadView Data
d = case Data -> Maybe Value
plainFromData Data
d of
    Just Value
json -> PayloadSchema -> Value -> PayloadView
PayloadView PayloadSchema
PlainSchema Value
json
    Maybe Value
Nothing -> PayloadSchema -> Value -> PayloadView
PayloadView PayloadSchema
DetailedSchema (Data -> Value
datumToJson Data
d)