-- Copyright 2026 Biglup Labs
-- SPDX-License-Identifier: Apache-2.0
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}

-- | Validated transaction metadata. Nested maps preserve pair order and duplicate
-- keys. Transaction labels are unique unsigned 64-bit numbers. Imported encodings
-- remain exact until the caller explicitly encodes their semantic view again.
--
-- @
-- {-# LANGUAGE OverloadedStrings #-}
-- import Cometa.Error (Error)
-- import qualified Cometa.Metadata as Metadata
--
-- message :: Either Error Metadata.Metadata
-- message = Metadata.singleton 674 . Metadata.list . pure <$> Metadata.mkText "hello"
-- @
module Cometa.Metadata
  ( -- * Nested values
    Metadatum,
    View (..),
    mkInteger,
    integerFromText,
    mkBytes,
    mkText,
    list,
    map,
    view,

    -- * Transaction labels
    Metadata,
    singleton,
    mkMetadata,
    toList,
    lookup,

    -- * CBOR and encoding identity
    EncodedMetadata,
    EncodedMetadatum,
    encodeCbor,
    decodeCbor,
    toCbor,
    toMetadata,
    encodeMetadatumCbor,
    decodeMetadatumCbor,
    toMetadatumCbor,
    toMetadatum,

    -- * Detailed JSON
    toDetailedJson,
    fromDetailedJson,
    metadatumToDetailedJson,
    metadatumFromDetailedJson,

    -- * Plain JSON
    metadatumToJson,
    metadatumFromJson,
  )
where

-- IMPORTS --------------------------------------------------------------------

import qualified Codec.CBOR.Decoding as Decode
import qualified Codec.CBOR.Encoding as Encode
import Codec.CBOR.Read (deserialiseFromBytes)
import Codec.CBOR.Write (toStrictByteString)
import qualified Cometa.Encoding.Integer as Integer
import Cometa.Error (Error (..))
import qualified Cometa.Internal.Hex as Hex
import Control.Monad (replicateM)
import Data.Aeson (Value (..), object, toJSON, (.=))
import qualified Data.Aeson.Key as Key
import qualified Data.Aeson.KeyMap as KeyMap
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Lazy as LazyByteString
import qualified Data.Foldable
import Data.Int (Int64)
import qualified Data.Map.Strict as Map
import Data.Scientific (Scientific, base10Exponent, coefficient)
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import Data.Word (Word64)
import Text.Read (readMaybe)
import Prelude hiding (lookup, map)
import qualified Prelude

-- TYPES ----------------------------------------------------------------------

-- | A metadata value whose integers fit primitive CBOR and whose byte/text
-- strings contain at most 64 bytes. Equality compares values and nested ordering.
newtype Metadatum = Metadatum View deriving (Metadatum -> Metadatum -> Bool
(Metadatum -> Metadatum -> Bool)
-> (Metadatum -> Metadatum -> Bool) -> Eq Metadatum
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Metadatum -> Metadatum -> Bool
== :: Metadatum -> Metadatum -> Bool
$c/= :: Metadatum -> Metadatum -> Bool
/= :: Metadatum -> Metadatum -> Bool
Eq, Int -> Metadatum -> ShowS
[Metadatum] -> ShowS
Metadatum -> String
(Int -> Metadatum -> ShowS)
-> (Metadatum -> String)
-> ([Metadatum] -> ShowS)
-> Show Metadatum
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Metadatum -> ShowS
showsPrec :: Int -> Metadatum -> ShowS
$cshow :: Metadatum -> String
show :: Metadatum -> String
$cshowList :: [Metadatum] -> ShowS
showList :: [Metadatum] -> ShowS
Show)

-- | A read-only view. Constructing a view cannot bypass 'Metadatum' validation.
data View
  = -- | A primitive CBOR integer in the inclusive range @-2^64 .. 2^64-1@.
    IntegerValue Integer
  | -- | Zero through 64 arbitrary bytes.
    BytesValue ByteString
  | -- | Text containing at most 64 UTF-8 bytes, without normalization.
    TextValue Text
  | -- | An ordered list of validated values.
    ListValue [Metadatum]
  | -- | Ordered key/value pairs; duplicate keys are preserved.
    MapValue [(Metadatum, Metadatum)]
  deriving (View -> View -> Bool
(View -> View -> Bool) -> (View -> View -> Bool) -> Eq View
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: View -> View -> Bool
== :: View -> View -> Bool
$c/= :: View -> View -> Bool
/= :: View -> View -> Bool
Eq, Int -> View -> ShowS
[View] -> ShowS
View -> String
(Int -> View -> ShowS)
-> (View -> String) -> ([View] -> ShowS) -> Show View
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> View -> ShowS
showsPrec :: Int -> View -> ShowS
$cshow :: View -> String
show :: View -> String
$cshowList :: [View] -> ShowS
showList :: [View] -> ShowS
Show)

-- | Unique labels. Equality ignores insertion order. Combining values is
-- left-biased on duplicate labels, with empty metadata as identity.
newtype Metadata = Metadata (Map.Map Word64 Metadatum) deriving (Metadata -> Metadata -> Bool
(Metadata -> Metadata -> Bool)
-> (Metadata -> Metadata -> Bool) -> Eq Metadata
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Metadata -> Metadata -> Bool
== :: Metadata -> Metadata -> Bool
$c/= :: Metadata -> Metadata -> Bool
/= :: Metadata -> Metadata -> Bool
Eq, Int -> Metadata -> ShowS
[Metadata] -> ShowS
Metadata -> String
(Int -> Metadata -> ShowS)
-> (Metadata -> String) -> ([Metadata] -> ShowS) -> Show Metadata
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Metadata -> ShowS
showsPrec :: Int -> Metadata -> ShowS
$cshow :: Metadata -> String
show :: Metadata -> String
$cshowList :: [Metadata] -> ShowS
showList :: [Metadata] -> ShowS
Show)

instance Semigroup Metadata where
  Metadata Map Word64 Metadatum
left <> :: Metadata -> Metadata -> Metadata
<> Metadata Map Word64 Metadatum
right = Map Word64 Metadatum -> Metadata
Metadata (Map Word64 Metadatum
-> Map Word64 Metadatum -> Map Word64 Metadatum
forall k a. Ord k => Map k a -> Map k a -> Map k a
Map.union Map Word64 Metadatum
left Map Word64 Metadatum
right)

instance Monoid Metadata where
  mempty :: Metadata
mempty = Map Word64 Metadatum -> Metadata
Metadata Map Word64 Metadatum
forall k a. Map k a
Map.empty

-- | Validated metadata plus its original bytes. Equality compares exact bytes.
data EncodedMetadata = EncodedMetadata ByteString Metadata deriving (Int -> EncodedMetadata -> ShowS
[EncodedMetadata] -> ShowS
EncodedMetadata -> String
(Int -> EncodedMetadata -> ShowS)
-> (EncodedMetadata -> String)
-> ([EncodedMetadata] -> ShowS)
-> Show EncodedMetadata
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> EncodedMetadata -> ShowS
showsPrec :: Int -> EncodedMetadata -> ShowS
$cshow :: EncodedMetadata -> String
show :: EncodedMetadata -> String
$cshowList :: [EncodedMetadata] -> ShowS
showList :: [EncodedMetadata] -> ShowS
Show)

instance Eq EncodedMetadata where
  EncodedMetadata ByteString
a Metadata
_ == :: EncodedMetadata -> EncodedMetadata -> Bool
== EncodedMetadata ByteString
b Metadata
_ = ByteString
a ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
b

-- | Validated metadatum plus its original bytes. Equality compares exact bytes.
data EncodedMetadatum = EncodedMetadatum ByteString Metadatum deriving (Int -> EncodedMetadatum -> ShowS
[EncodedMetadatum] -> ShowS
EncodedMetadatum -> String
(Int -> EncodedMetadatum -> ShowS)
-> (EncodedMetadatum -> String)
-> ([EncodedMetadatum] -> ShowS)
-> Show EncodedMetadatum
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> EncodedMetadatum -> ShowS
showsPrec :: Int -> EncodedMetadatum -> ShowS
$cshow :: EncodedMetadatum -> String
show :: EncodedMetadatum -> String
$cshowList :: [EncodedMetadatum] -> ShowS
showList :: [EncodedMetadatum] -> ShowS
Show)

instance Eq EncodedMetadatum where
  EncodedMetadatum ByteString
a Metadatum
_ == :: EncodedMetadatum -> EncodedMetadatum -> Bool
== EncodedMetadatum ByteString
b Metadatum
_ = ByteString
a ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
== ByteString
b

-- DEFINITIONS ----------------------------------------------------------------

-- | Validate the inclusive range @-2^64 .. 2^64-1@. Tagged bignums are excluded.
mkInteger :: Integer -> Either Error Metadatum
mkInteger :: Integer -> Either Error Metadatum
mkInteger Integer
n
  | Integer
n Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer -> Integer
forall a. Num a => a -> a
negate (Integer
2 Integer -> Int -> Integer
forall a b. (Num a, Integral b) => a -> b -> a
^ (Int
64 :: Int)) Bool -> Bool -> Bool
|| Integer
n Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Integer
2 Integer -> Int -> Integer
forall a b. (Num a, Integral b) => a -> b -> a
^ (Int
64 :: Int) = Error -> Either Error Metadatum
forall a b. a -> Either a b
Left (Integer -> Error
InvalidMetadataInteger Integer
n)
  | Bool
otherwise = Metadatum -> Either Error Metadatum
forall a b. b -> Either a b
Right (View -> Metadatum
Metadatum (Integer -> View
IntegerValue Integer
n))

-- | Parse native-compatible integer text in a validated radix, then apply the
-- ledger metadata integer bounds. Parsing errors are 'InvalidIntegerText';
-- out-of-range values return 'InvalidMetadataInteger'.
integerFromText :: Integer.Radix -> Text -> Either Error Metadatum
integerFromText :: Radix -> Text -> Either Error Metadatum
integerFromText Radix
radix Text
text = Radix -> Text -> Either Error Integer
Integer.fromText Radix
radix Text
text Either Error Integer
-> (Integer -> Either Error Metadatum) -> Either Error Metadatum
forall a b.
Either Error a -> (a -> Either Error b) -> Either Error b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Integer -> Either Error Metadatum
mkInteger

-- | Validate a byte string of 0 through 64 bytes.
mkBytes :: ByteString -> Either Error Metadatum
mkBytes :: ByteString -> Either Error Metadatum
mkBytes ByteString
b
  | ByteString -> Int
ByteString.length ByteString
b Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
64 = Error -> Either Error Metadatum
forall a b. a -> Either a b
Left (Int -> Error
InvalidMetadataBytesLength (ByteString -> Int
ByteString.length ByteString
b))
  | Bool
otherwise = Metadatum -> Either Error Metadatum
forall a b. b -> Either a b
Right (View -> Metadatum
Metadatum (ByteString -> View
BytesValue ByteString
b))

-- | Validate at most 64 UTF-8 bytes; no Unicode normalization is performed.
mkText :: Text -> Either Error Metadatum
mkText :: Text -> Either Error Metadatum
mkText Text
t
  | Int
size Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
64 = Error -> Either Error Metadatum
forall a b. a -> Either a b
Left (Int -> Error
InvalidMetadataTextLength Int
size)
  | Bool
otherwise = Metadatum -> Either Error Metadatum
forall a b. b -> Either a b
Right (View -> Metadatum
Metadatum (Text -> View
TextValue Text
t))
  where
    size :: Int
size = ByteString -> Int
ByteString.length (Text -> ByteString
Text.encodeUtf8 Text
t)

-- | Assemble a list, preserving order. Empty lists are valid.
list :: [Metadatum] -> Metadatum
list :: [Metadatum] -> Metadatum
list = View -> Metadatum
Metadatum (View -> Metadatum)
-> ([Metadatum] -> View) -> [Metadatum] -> Metadatum
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Metadatum] -> View
ListValue

-- | Assemble a map, preserving pair order and duplicate keys. Empty maps are valid.
map :: [(Metadatum, Metadatum)] -> Metadatum
map :: [(Metadatum, Metadatum)] -> Metadatum
map = View -> Metadatum
Metadatum (View -> Metadatum)
-> ([(Metadatum, Metadatum)] -> View)
-> [(Metadatum, Metadatum)]
-> Metadatum
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [(Metadatum, Metadatum)] -> View
MapValue

-- | Inspect a value without validation or effects.
view :: Metadatum -> View
view :: Metadatum -> View
view (Metadatum View
v) = View
v

-- | Assemble one transaction label and its validated value.
singleton :: Word64 -> Metadatum -> Metadata
singleton :: Word64 -> Metadatum -> Metadata
singleton Word64
label Metadatum
value = Map Word64 Metadatum -> Metadata
Metadata (Word64 -> Metadatum -> Map Word64 Metadatum
forall k a. k -> a -> Map k a
Map.singleton Word64
label Metadatum
value)

-- | Validate label uniqueness; duplicate labels return 'DuplicateMetadataLabel'.
mkMetadata :: [(Word64, Metadatum)] -> Either Error Metadata
mkMetadata :: [(Word64, Metadatum)] -> Either Error Metadata
mkMetadata = Map Word64 Metadatum
-> [(Word64, Metadatum)] -> Either Error Metadata
go Map Word64 Metadatum
forall k a. Map k a
Map.empty
  where
    go :: Map Word64 Metadatum
-> [(Word64, Metadatum)] -> Either Error Metadata
go Map Word64 Metadatum
values [] = Metadata -> Either Error Metadata
forall a b. b -> Either a b
Right (Map Word64 Metadatum -> Metadata
Metadata Map Word64 Metadatum
values)
    go Map Word64 Metadatum
values ((Word64
label, Metadatum
value) : [(Word64, Metadatum)]
rest)
      | Word64 -> Map Word64 Metadatum -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.member Word64
label Map Word64 Metadatum
values = Error -> Either Error Metadata
forall a b. a -> Either a b
Left (Word64 -> Error
DuplicateMetadataLabel Word64
label)
      | Bool
otherwise = Map Word64 Metadatum
-> [(Word64, Metadatum)] -> Either Error Metadata
go (Word64 -> Metadatum -> Map Word64 Metadatum -> Map Word64 Metadatum
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert Word64
label Metadatum
value Map Word64 Metadatum
values) [(Word64, Metadatum)]
rest

-- | Inspect entries in ascending numeric label order.
toList :: Metadata -> [(Word64, Metadatum)]
toList :: Metadata -> [(Word64, Metadatum)]
toList (Metadata Map Word64 Metadatum
m) = Map Word64 Metadatum -> [(Word64, Metadatum)]
forall k a. Map k a -> [(k, a)]
Map.toAscList Map Word64 Metadatum
m

-- | Find a label; missing labels are ordinary absence.
lookup :: Word64 -> Metadata -> Maybe Metadatum
lookup :: Word64 -> Metadata -> Maybe Metadatum
lookup Word64
key (Metadata Map Word64 Metadatum
m) = Word64 -> Map Word64 Metadatum -> Maybe Metadatum
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Word64
key Map Word64 Metadatum
m

-- | Encode a semantic value with minimal integers and definite strings and
-- collections. Labels are ascending; nested map order is preserved. This is
-- normalization, not a claim of canonical sorting of arbitrary metadata keys.
encodeCbor :: Metadata -> ByteString
encodeCbor :: Metadata -> ByteString
encodeCbor Metadata
metadata = Encoding -> ByteString
toStrictByteString (Word -> Encoding
Encode.encodeMapLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([(Word64, Metadatum)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Word64, Metadatum)]
entries)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ((Word64, Metadatum) -> Encoding)
-> [(Word64, Metadatum)] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (Word64, Metadatum) -> Encoding
encodeEntry [(Word64, Metadatum)]
entries)
  where
    entries :: [(Word64, Metadatum)]
entries = Metadata -> [(Word64, Metadatum)]
Cometa.Metadata.toList Metadata
metadata
    encodeEntry :: (Word64, Metadatum) -> Encoding
encodeEntry (Word64
label, Metadatum
value) = Word64 -> Encoding
Encode.encodeWord64 Word64
label Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Metadatum -> Encoding
encodeValue Metadatum
value

-- | Decode exactly one metadata map. Rejects duplicate labels, trailing input,
-- invalid UTF-8, unsupported CBOR types, and out-of-bound values. Definite and
-- indefinite collections and strings are accepted; original bytes are retained.
decodeCbor :: ByteString -> Either Error EncodedMetadata
decodeCbor :: ByteString -> Either Error EncodedMetadata
decodeCbor ByteString
bytes = do
  [(Word64, Metadatum)]
entries <- (forall s. Decoder s [(Word64, Metadatum)])
-> ByteString -> Either Error [(Word64, Metadatum)]
forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
decodeFull (Decoder s (Maybe Int)
-> Decoder s (Word64, Metadatum) -> Decoder s [(Word64, Metadatum)]
forall s a. Decoder s (Maybe Int) -> Decoder s a -> Decoder s [a]
decodeCollection Decoder s (Maybe Int)
forall s. Decoder s (Maybe Int)
Decode.decodeMapLenOrIndef ((,) (Word64 -> Metadatum -> (Word64, Metadatum))
-> Decoder s Word64 -> Decoder s (Metadatum -> (Word64, Metadatum))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s Word64
forall s. Decoder s Word64
Decode.decodeWord64 Decoder s (Metadatum -> (Word64, Metadatum))
-> Decoder s Metadatum -> Decoder s (Word64, Metadatum)
forall a b. Decoder s (a -> b) -> Decoder s a -> Decoder s b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Decoder s Metadatum
forall s. Decoder s Metadatum
decodeValue)) ByteString
bytes
  ByteString -> Metadata -> EncodedMetadata
EncodedMetadata ByteString
bytes (Metadata -> EncodedMetadata)
-> Either Error Metadata -> Either Error EncodedMetadata
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [(Word64, Metadatum)] -> Either Error Metadata
mkMetadata [(Word64, Metadatum)]
entries

-- | Retrieve the exact imported bytes without normalization.
toCbor :: EncodedMetadata -> ByteString
toCbor :: EncodedMetadata -> ByteString
toCbor (EncodedMetadata ByteString
bytes Metadata
_) = ByteString
bytes

-- | Inspect the semantic metadata view; encoding it again explicitly normalizes.
toMetadata :: EncodedMetadata -> Metadata
toMetadata :: EncodedMetadata -> Metadata
toMetadata (EncodedMetadata ByteString
_ Metadata
metadata) = Metadata
metadata

-- | Encode a metadatum with minimal integers and definite strings/collections.
-- Map pair order and duplicate keys are preserved.
encodeMetadatumCbor :: Metadatum -> ByteString
encodeMetadatumCbor :: Metadatum -> ByteString
encodeMetadatumCbor = Encoding -> ByteString
toStrictByteString (Encoding -> ByteString)
-> (Metadatum -> Encoding) -> Metadatum -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Metadatum -> Encoding
encodeValue

-- | Decode one bounded metadatum, preserving exact bytes. The same restrictions
-- as 'decodeCbor' apply.
decodeMetadatumCbor :: ByteString -> Either Error EncodedMetadatum
decodeMetadatumCbor :: ByteString -> Either Error EncodedMetadatum
decodeMetadatumCbor ByteString
bytes = ByteString -> Metadatum -> EncodedMetadatum
EncodedMetadatum ByteString
bytes (Metadatum -> EncodedMetadatum)
-> Either Error Metadatum -> Either Error EncodedMetadatum
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (forall s. Decoder s Metadatum)
-> ByteString -> Either Error Metadatum
forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
decodeFull Decoder s Metadatum
forall s. Decoder s Metadatum
decodeValue ByteString
bytes

-- | Retrieve exact imported metadatum bytes.
toMetadatumCbor :: EncodedMetadatum -> ByteString
toMetadatumCbor :: EncodedMetadatum -> ByteString
toMetadatumCbor (EncodedMetadatum ByteString
bytes Metadatum
_) = ByteString
bytes

-- | Retrieve the validated semantic metadatum.
toMetadatum :: EncodedMetadatum -> Metadatum
toMetadatum :: EncodedMetadatum -> Metadatum
toMetadatum (EncodedMetadatum ByteString
_ Metadatum
value) = Metadatum
value

encodeValue :: Metadatum -> Encode.Encoding
encodeValue :: Metadatum -> Encoding
encodeValue (Metadatum View
value) = case View
value of
  IntegerValue Integer
n -> Integer -> Encoding
Encode.encodeInteger Integer
n
  BytesValue ByteString
b -> ByteString -> Encoding
Encode.encodeBytes ByteString
b
  TextValue Text
t -> Text -> Encoding
Encode.encodeString Text
t
  ListValue [Metadatum]
xs -> Word -> Encoding
Encode.encodeListLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([Metadatum] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Metadatum]
xs)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (Metadatum -> Encoding) -> [Metadatum] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap Metadatum -> Encoding
encodeValue [Metadatum]
xs
  MapValue [(Metadatum, Metadatum)]
xs -> Word -> Encoding
Encode.encodeMapLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([(Metadatum, Metadatum)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Metadatum, Metadatum)]
xs)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ((Metadatum, Metadatum) -> Encoding)
-> [(Metadatum, Metadatum)] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (\(Metadatum
k, Metadatum
v) -> Metadatum -> Encoding
encodeValue Metadatum
k Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Metadatum -> Encoding
encodeValue Metadatum
v) [(Metadatum, Metadatum)]
xs

decodeFull :: (forall s. Decode.Decoder s a) -> ByteString -> Either Error a
decodeFull :: forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
decodeFull forall s. Decoder s a
decoder ByteString
bytes = case (forall s. Decoder s a)
-> ByteString -> Either DeserialiseFailure (ByteString, a)
forall a.
(forall s. Decoder s a)
-> ByteString -> Either DeserialiseFailure (ByteString, a)
deserialiseFromBytes Decoder s a
forall s. Decoder s a
decoder (ByteString -> ByteString
LazyByteString.fromStrict ByteString
bytes) of
  Left DeserialiseFailure
_ -> Error -> Either Error a
forall a b. a -> Either a b
Left (Text -> Error
InvalidMetadataCbor Text
"invalid metadata encoding")
  Right (ByteString
rest, a
value)
    | ByteString -> Bool
LazyByteString.null ByteString
rest -> a -> Either Error a
forall a b. b -> Either a b
Right a
value
    | Bool
otherwise -> Error -> Either Error a
forall a b. a -> Either a b
Left (Text -> Error
InvalidMetadataCbor Text
"trailing input")

decodeValue :: Decode.Decoder s Metadatum
decodeValue :: forall s. Decoder s Metadatum
decodeValue = do
  TokenType
token <- Decoder s TokenType
forall s. Decoder s TokenType
Decode.peekTokenType
  case TokenType
token of
    TokenType
Decode.TypeUInt -> Decoder s Metadatum
forall s. Decoder s Metadatum
integer
    TokenType
Decode.TypeUInt64 -> Decoder s Metadatum
forall s. Decoder s Metadatum
integer
    TokenType
Decode.TypeNInt -> Decoder s Metadatum
forall s. Decoder s Metadatum
integer
    TokenType
Decode.TypeNInt64 -> Decoder s Metadatum
forall s. Decoder s Metadatum
integer
    TokenType
Decode.TypeBytes -> Decoder s ByteString
forall s. Decoder s ByteString
Decode.decodeBytes Decoder s ByteString
-> (ByteString -> Decoder s Metadatum) -> Decoder s Metadatum
forall a b. Decoder s a -> (a -> Decoder s b) -> Decoder s b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Either Error Metadatum -> Decoder s Metadatum
forall a s. Either Error a -> Decoder s a
checked (Either Error Metadatum -> Decoder s Metadatum)
-> (ByteString -> Either Error Metadatum)
-> ByteString
-> Decoder s Metadatum
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either Error Metadatum
mkBytes
    TokenType
Decode.TypeBytesIndef -> Decoder s ()
forall s. Decoder s ()
Decode.decodeBytesIndef Decoder s () -> Decoder s ByteString -> Decoder s ByteString
forall a b. Decoder s a -> Decoder s b -> Decoder s b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Decoder s ByteString
-> (ByteString -> Int)
-> ([ByteString] -> ByteString)
-> Decoder s ByteString
forall s a b.
Decoder s a -> (a -> Int) -> ([a] -> b) -> Decoder s b
boundedChunks Decoder s ByteString
forall s. Decoder s ByteString
Decode.decodeBytes ByteString -> Int
ByteString.length [ByteString] -> ByteString
ByteString.concat Decoder s ByteString
-> (ByteString -> Decoder s Metadatum) -> Decoder s Metadatum
forall a b. Decoder s a -> (a -> Decoder s b) -> Decoder s b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Either Error Metadatum -> Decoder s Metadatum
forall a s. Either Error a -> Decoder s a
checked (Either Error Metadatum -> Decoder s Metadatum)
-> (ByteString -> Either Error Metadatum)
-> ByteString
-> Decoder s Metadatum
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either Error Metadatum
mkBytes
    TokenType
Decode.TypeString -> Decoder s Text
forall s. Decoder s Text
Decode.decodeString Decoder s Text
-> (Text -> Decoder s Metadatum) -> Decoder s Metadatum
forall a b. Decoder s a -> (a -> Decoder s b) -> Decoder s b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Either Error Metadatum -> Decoder s Metadatum
forall a s. Either Error a -> Decoder s a
checked (Either Error Metadatum -> Decoder s Metadatum)
-> (Text -> Either Error Metadatum) -> Text -> Decoder s Metadatum
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Either Error Metadatum
mkText
    TokenType
Decode.TypeStringIndef -> Decoder s ()
forall s. Decoder s ()
Decode.decodeStringIndef Decoder s () -> Decoder s Text -> Decoder s Text
forall a b. Decoder s a -> Decoder s b -> Decoder s b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Decoder s Text
-> (Text -> Int) -> ([Text] -> Text) -> Decoder s Text
forall s a b.
Decoder s a -> (a -> Int) -> ([a] -> b) -> Decoder s b
boundedChunks Decoder s Text
forall s. Decoder s Text
Decode.decodeString (ByteString -> Int
ByteString.length (ByteString -> Int) -> (Text -> ByteString) -> Text -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> ByteString
Text.encodeUtf8) [Text] -> Text
Text.concat Decoder s Text
-> (Text -> Decoder s Metadatum) -> Decoder s Metadatum
forall a b. Decoder s a -> (a -> Decoder s b) -> Decoder s b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Either Error Metadatum -> Decoder s Metadatum
forall a s. Either Error a -> Decoder s a
checked (Either Error Metadatum -> Decoder s Metadatum)
-> (Text -> Either Error Metadatum) -> Text -> Decoder s Metadatum
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Either Error Metadatum
mkText
    TokenType
Decode.TypeListLen -> Decoder s Metadatum
forall s. Decoder s Metadatum
array
    TokenType
Decode.TypeListLen64 -> Decoder s Metadatum
forall s. Decoder s Metadatum
array
    TokenType
Decode.TypeListLenIndef -> Decoder s Metadatum
forall s. Decoder s Metadatum
array
    TokenType
Decode.TypeMapLen -> Decoder s Metadatum
forall s. Decoder s Metadatum
pairs
    TokenType
Decode.TypeMapLen64 -> Decoder s Metadatum
forall s. Decoder s Metadatum
pairs
    TokenType
Decode.TypeMapLenIndef -> Decoder s Metadatum
forall s. Decoder s Metadatum
pairs
    TokenType
_ -> String -> Decoder s Metadatum
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"unsupported metadata type"
  where
    integer :: Decoder s Metadatum
integer = Decoder s Integer
forall s. Decoder s Integer
Decode.decodeInteger Decoder s Integer
-> (Integer -> Decoder s Metadatum) -> Decoder s Metadatum
forall a b. Decoder s a -> (a -> Decoder s b) -> Decoder s b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Either Error Metadatum -> Decoder s Metadatum
forall a s. Either Error a -> Decoder s a
checked (Either Error Metadatum -> Decoder s Metadatum)
-> (Integer -> Either Error Metadatum)
-> Integer
-> Decoder s Metadatum
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Integer -> Either Error Metadatum
mkInteger
    array :: Decoder s Metadatum
array = [Metadatum] -> Metadatum
list ([Metadatum] -> Metadatum)
-> Decoder s [Metadatum] -> Decoder s Metadatum
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s (Maybe Int)
-> Decoder s Metadatum -> Decoder s [Metadatum]
forall s a. Decoder s (Maybe Int) -> Decoder s a -> Decoder s [a]
decodeCollection Decoder s (Maybe Int)
forall s. Decoder s (Maybe Int)
Decode.decodeListLenOrIndef Decoder s Metadatum
forall s. Decoder s Metadatum
decodeValue
    pairs :: Decoder s Metadatum
pairs = [(Metadatum, Metadatum)] -> Metadatum
Cometa.Metadata.map ([(Metadatum, Metadatum)] -> Metadatum)
-> Decoder s [(Metadatum, Metadatum)] -> Decoder s Metadatum
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s (Maybe Int)
-> Decoder s (Metadatum, Metadatum)
-> Decoder s [(Metadatum, Metadatum)]
forall s a. Decoder s (Maybe Int) -> Decoder s a -> Decoder s [a]
decodeCollection Decoder s (Maybe Int)
forall s. Decoder s (Maybe Int)
Decode.decodeMapLenOrIndef ((,) (Metadatum -> Metadatum -> (Metadatum, Metadatum))
-> Decoder s Metadatum
-> Decoder s (Metadatum -> (Metadatum, Metadatum))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s Metadatum
forall s. Decoder s Metadatum
decodeValue Decoder s (Metadatum -> (Metadatum, Metadatum))
-> Decoder s Metadatum -> Decoder s (Metadatum, Metadatum)
forall a b. Decoder s (a -> b) -> Decoder s a -> Decoder s b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Decoder s Metadatum
forall s. Decoder s Metadatum
decodeValue)

checked :: Either Error a -> Decode.Decoder s a
checked :: forall a s. Either Error a -> Decoder s a
checked = (Error -> Decoder s a)
-> (a -> Decoder s a) -> Either Error a -> Decoder s a
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Decoder s a -> Error -> Decoder s a
forall a b. a -> b -> a
const (String -> Decoder s a
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"metadata value outside bounds")) a -> Decoder s a
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure

decodeCollection :: Decode.Decoder s (Maybe Int) -> Decode.Decoder s a -> Decode.Decoder s [a]
decodeCollection :: forall s a. Decoder s (Maybe Int) -> Decoder s a -> Decoder s [a]
decodeCollection Decoder s (Maybe Int)
start Decoder s a
item = do
  Maybe Int
count <- Decoder s (Maybe Int)
start
  case Maybe Int
count of
    Just Int
n -> Int -> Decoder s a -> Decoder s [a]
forall (m :: * -> *) a. Applicative m => Int -> m a -> m [a]
replicateM Int
n Decoder s a
item
    Maybe Int
Nothing -> Decoder s a -> ([a] -> [a]) -> Decoder s [a]
forall s a b. Decoder s a -> ([a] -> b) -> Decoder s b
chunks Decoder s a
item [a] -> [a]
forall a. a -> a
id

chunks :: Decode.Decoder s a -> ([a] -> b) -> Decode.Decoder s b
chunks :: forall s a b. Decoder s a -> ([a] -> b) -> Decoder s b
chunks Decoder s a
item [a] -> b
assemble = [a] -> Decoder s b
go []
  where
    go :: [a] -> Decoder s b
go [a]
acc = do
      Bool
end <- Decoder s Bool
forall s. Decoder s Bool
Decode.decodeBreakOr
      if Bool
end then b -> Decoder s b
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([a] -> b
assemble ([a] -> [a]
forall a. [a] -> [a]
reverse [a]
acc)) else Decoder s a
item Decoder s a -> (a -> Decoder s b) -> Decoder s b
forall a b. Decoder s a -> (a -> Decoder s b) -> Decoder s b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \a
value -> [a] -> Decoder s b
go (a
value a -> [a] -> [a]
forall a. a -> [a] -> [a]
: [a]
acc)

-- Reject accumulated overlength strings before retaining further chunks.
boundedChunks :: Decode.Decoder s a -> (a -> Int) -> ([a] -> b) -> Decode.Decoder s b
boundedChunks :: forall s a b.
Decoder s a -> (a -> Int) -> ([a] -> b) -> Decoder s b
boundedChunks Decoder s a
item a -> Int
size [a] -> b
assemble = Int -> [a] -> Decoder s b
go Int
0 []
  where
    go :: Int -> [a] -> Decoder s b
go Int
used [a]
acc = do
      Bool
end <- Decoder s Bool
forall s. Decoder s Bool
Decode.decodeBreakOr
      if Bool
end
        then b -> Decoder s b
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([a] -> b
assemble ([a] -> [a]
forall a. [a] -> [a]
reverse [a]
acc))
        else do
          a
value <- Decoder s a
item
          let next :: Int
next = Int
used Int -> Int -> Int
forall a. Num a => a -> a -> a
+ a -> Int
size a
value
          if Int
next Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
64 then String -> Decoder s b
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail String
"metadata string outside bounds" else Int -> [a] -> Decoder s b
go Int
next (a
value a -> [a] -> [a]
forall a. a -> [a] -> [a]
: [a]
acc)

-- | Lossless cardano-api detailed-schema JSON: top-level object keys are decimal
-- labels. This is distinct from CIP-116 inspector JSON. JSON object key order is
-- insignificant; nested map pair arrays preserve order and duplicates.
toDetailedJson :: Metadata -> Value
toDetailedJson :: Metadata -> Value
toDetailedJson = Object -> Value
Object (Object -> Value) -> (Metadata -> Object) -> Metadata -> Value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Pair] -> Object
forall v. [(Key, v)] -> KeyMap v
KeyMap.fromList ([Pair] -> Object) -> (Metadata -> [Pair]) -> Metadata -> Object
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((Word64, Metadatum) -> Pair) -> [(Word64, Metadatum)] -> [Pair]
forall a b. (a -> b) -> [a] -> [b]
Prelude.map (\(Word64
k, Metadatum
v) -> (Text -> Key
Key.fromText (String -> Text
Text.pack (Word64 -> String
forall a. Show a => a -> String
show Word64
k)), Metadatum -> Value
metadatumToDetailedJson Metadatum
v)) ([(Word64, Metadatum)] -> [Pair])
-> (Metadata -> [(Word64, Metadatum)]) -> Metadata -> [Pair]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Metadata -> [(Word64, Metadatum)]
Cometa.Metadata.toList

-- | Import detailed-schema JSON, validating labels and every leaf. Labels must
-- be canonical unsigned decimal strings, without leading zeros except zero.
fromDetailedJson :: Value -> Either Error Metadata
fromDetailedJson :: Value -> Either Error Metadata
fromDetailedJson (Object Object
values) = (Pair -> Either Error (Word64, Metadatum))
-> [Pair] -> Either Error [(Word64, Metadatum)]
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 Pair -> Either Error (Word64, Metadatum)
entry (Object -> [Pair]
forall v. KeyMap v -> [(Key, v)]
KeyMap.toList Object
values) Either Error [(Word64, Metadatum)]
-> ([(Word64, Metadatum)] -> Either Error Metadata)
-> Either Error Metadata
forall a b.
Either Error a -> (a -> Either Error b) -> Either Error b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= [(Word64, Metadatum)] -> Either Error Metadata
mkMetadata
  where
    entry :: Pair -> Either Error (Word64, Metadatum)
entry (Key
key, Value
value) = do
      let label :: Text
label = Key -> Text
Key.toText Key
key
      Word64
n <- Either Error Word64
-> (Word64 -> Either Error Word64)
-> Maybe Word64
-> Either Error Word64
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Error -> Either Error Word64
forall a b. a -> Either a b
Left (Text -> Error
InvalidMetadataJson Text
"invalid metadata label")) Word64 -> Either Error Word64
forall a b. b -> Either a b
Right (String -> Maybe Word64
forall a. Read a => String -> Maybe a
readMaybe (Text -> String
Text.unpack Text
label) :: Maybe Word64)
      if String -> Text
Text.pack (Word64 -> String
forall a. Show a => a -> String
show Word64
n) Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
/= Text
label
        then Error -> Either Error (Word64, Metadatum)
forall a b. a -> Either a b
Left (Text -> Error
InvalidMetadataJson Text
"noncanonical metadata label")
        else (,) Word64
n (Metadatum -> (Word64, Metadatum))
-> Either Error Metadatum -> Either Error (Word64, Metadatum)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Value -> Either Error Metadatum
metadatumFromDetailedJson Value
value
fromDetailedJson Value
_ = Error -> Either Error Metadata
forall a b. a -> Either a b
Left (Text -> Error
InvalidMetadataJson Text
"metadata must be an object")

-- | Convert every metadatum constructor without loss. Shapes are @{"int":n}@,
-- @{"bytes":"hex"}@, @{"string":"text"}@, @{"list":[...]}@ and
-- @{"map":[{"k":...,"v":...}]}@. Hex is lowercase without a prefix.
metadatumToDetailedJson :: Metadatum -> Value
metadatumToDetailedJson :: Metadatum -> Value
metadatumToDetailedJson (Metadatum View
value) = case View
value of
  IntegerValue Integer
n -> [Pair] -> Value
object [Key
"int" Key -> Integer -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Integer
n]
  BytesValue ByteString
b -> [Pair] -> Value
object [Key
"bytes" Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= ByteString -> Text
Hex.encodeHex ByteString
b]
  TextValue Text
t -> [Pair] -> Value
object [Key
"string" Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Text
t]
  ListValue [Metadatum]
xs -> [Pair] -> Value
object [Key
"list" Key -> [Value] -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= (Metadatum -> Value) -> [Metadatum] -> [Value]
forall a b. (a -> b) -> [a] -> [b]
Prelude.map Metadatum -> Value
metadatumToDetailedJson [Metadatum]
xs]
  MapValue [(Metadatum, Metadatum)]
xs -> [Pair] -> Value
object [Key
"map" Key -> [Value] -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= ((Metadatum, Metadatum) -> Value)
-> [(Metadatum, Metadatum)] -> [Value]
forall a b. (a -> b) -> [a] -> [b]
Prelude.map (\(Metadatum
k, Metadatum
v) -> [Pair] -> Value
object [Key
"k" Key -> Value -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Metadatum -> Value
metadatumToDetailedJson Metadatum
k, Key
"v" Key -> Value -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Metadatum -> Value
metadatumToDetailedJson Metadatum
v]) [(Metadatum, Metadatum)]
xs]

-- | Validate a detailed-schema metadatum. Integers remain exact; fractional
-- numbers, unsupported shapes, invalid hex and overlong strings fail.
metadatumFromDetailedJson :: Value -> Either Error Metadatum
metadatumFromDetailedJson :: Value -> Either Error Metadatum
metadatumFromDetailedJson = Value -> Either Error Metadatum
go
  where
    go :: Value -> Either Error Metadatum
    go :: Value -> Either Error Metadatum
go (Object Object
fields) = case Object -> [Pair]
forall v. KeyMap v -> [(Key, v)]
KeyMap.toList Object
fields of
      [(Key
"int", Number Scientific
n)] -> Scientific -> Either Error Integer
scientificInteger Scientific
n Either Error Integer
-> (Integer -> Either Error Metadatum) -> Either Error Metadatum
forall a b.
Either Error a -> (a -> Either Error b) -> Either Error b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Integer -> Either Error Metadatum
mkInteger
      [(Key
"bytes", String Text
s)] -> Either Error Metadatum
-> (ByteString -> Either Error Metadatum)
-> Maybe ByteString
-> Either Error Metadatum
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Text -> Either Error Metadatum
forall {b}. Text -> Either Error b
bad Text
"invalid metadata hex") ByteString -> Either Error Metadatum
mkBytes (Text -> Maybe ByteString
Hex.decodeHex Text
s)
      [(Key
"string", String Text
s)] -> Text -> Either Error Metadatum
mkText Text
s
      [(Key
"list", Array Array
xs)] -> [Metadatum] -> Metadatum
list ([Metadatum] -> Metadatum)
-> Either Error [Metadatum] -> Either Error Metadatum
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Value -> Either Error Metadatum)
-> [Value] -> Either Error [Metadatum]
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 Value -> Either Error Metadatum
go (Array -> [Value]
forall a. Vector a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
Data.Foldable.toList Array
xs)
      [(Key
"map", Array Array
xs)] -> [(Metadatum, Metadatum)] -> Metadatum
Cometa.Metadata.map ([(Metadatum, Metadatum)] -> Metadatum)
-> Either Error [(Metadatum, Metadatum)] -> Either Error Metadatum
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Value -> Either Error (Metadatum, Metadatum))
-> [Value] -> Either Error [(Metadatum, Metadatum)]
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 Value -> Either Error (Metadatum, Metadatum)
pair (Array -> [Value]
forall a. Vector a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
Data.Foldable.toList Array
xs)
      [Pair]
_ -> Text -> Either Error Metadatum
forall {b}. Text -> Either Error b
bad Text
"invalid detailed metadata shape"
    go Value
_ = Text -> Either Error Metadatum
forall {b}. Text -> Either Error b
bad Text
"detailed metadata must be an object"
    pair :: Value -> Either Error (Metadatum, Metadatum)
pair (Object Object
fields)
      | Object -> Int
forall v. KeyMap v -> Int
KeyMap.size Object
fields Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
2, Just Value
k <- Key -> Object -> Maybe Value
forall v. Key -> KeyMap v -> Maybe v
KeyMap.lookup Key
"k" Object
fields, Just Value
v <- Key -> Object -> Maybe Value
forall v. Key -> KeyMap v -> Maybe v
KeyMap.lookup Key
"v" Object
fields = (,) (Metadatum -> Metadatum -> (Metadatum, Metadatum))
-> Either Error Metadatum
-> Either Error (Metadatum -> (Metadatum, Metadatum))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Value -> Either Error Metadatum
go Value
k Either Error (Metadatum -> (Metadatum, Metadatum))
-> Either Error Metadatum -> Either Error (Metadatum, Metadatum)
forall a b.
Either Error (a -> b) -> Either Error a -> Either Error b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Value -> Either Error Metadatum
go Value
v
    pair Value
_ = Text -> Either Error (Metadatum, Metadatum)
forall {b}. Text -> Either Error b
bad Text
"metadata map pair requires k and v"
    bad :: Text -> Either Error b
bad = Error -> Either Error b
forall a b. a -> Either a b
Left (Error -> Either Error b)
-> (Text -> Error) -> Text -> Either Error b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Error
InvalidMetadataJson

-- Convert without negating an Int exponent or constructing an enormous power.
-- Negative exponents are consumed only while the coefficient has trailing zeros.
scientificInteger :: Scientific -> Either Error Integer
scientificInteger :: Scientific -> Either Error Integer
scientificInteger Scientific
number
  | Integer
coefficientValue Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
== Integer
0 = Integer -> Either Error Integer
forall a b. b -> Either a b
Right Integer
0
  | Int
decimalExponent Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
0 =
      if Int
decimalExponent Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
19 then Either Error Integer
forall {b}. Either Error b
invalid else Integer -> Either Error Integer
forall a b. b -> Either a b
Right (Integer
coefficientValue Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
10 Integer -> Int -> Integer
forall a b. (Num a, Integral b) => a -> b -> a
^ Int
decimalExponent)
  | Bool
otherwise = Integer -> Integer -> Either Error Integer
forall {t} {t}.
(Integral t, Num t, Eq t) =>
t -> t -> Either Error t
divide (Integer -> Integer
forall a. Num a => a -> a
negate (Int -> Integer
forall a. Integral a => a -> Integer
toInteger Int
decimalExponent)) Integer
coefficientValue
  where
    coefficientValue :: Integer
coefficientValue = Scientific -> Integer
coefficient Scientific
number
    decimalExponent :: Int
decimalExponent = Scientific -> Int
base10Exponent Scientific
number
    invalid :: Either Error b
invalid = Error -> Either Error b
forall a b. a -> Either a b
Left (Text -> Error
InvalidMetadataJson Text
"metadata integer required or outside bounds")
    divide :: t -> t -> Either Error t
divide t
0 t
value = t -> Either Error t
forall a b. b -> Either a b
Right t
value
    divide t
remaining t
value = case t -> t -> (t, t)
forall a. Integral a => a -> a -> (a, a)
quotRem t
value t
10 of
      (t
next, t
0) -> t -> t -> Either Error t
divide (t
remaining t -> t -> t
forall a. Num a => a -> a -> a
- t
1) t
next
      (t, t)
_ -> Either Error t
forall {b}. Either Error b
invalid

-- | Convert a metadatum to ordinary JSON, matching cardano-c's plain JSON
-- schema: integers, text, arrays and objects with text keys. Bytes, nontext map
-- keys and duplicate object keys return 'InvalidMetadataJson' instead of losing
-- information. Object member ordering is not preserved by JSON. Integer output
-- retains the full metadata range, including negatives below -2^63 which the
-- native plain JSON importer does not accept. Use detailed JSON for all metadata
-- alternatives and exact ordered map pairs.
metadatumToJson :: Metadatum -> Either Error Value
metadatumToJson :: Metadatum -> Either Error Value
metadatumToJson Metadatum
value = case Metadatum -> View
view Metadatum
value of
  IntegerValue Integer
number -> Value -> Either Error Value
forall a b. b -> Either a b
Right (Scientific -> Value
Number (Integer -> Scientific
forall a. Num a => Integer -> a
fromInteger Integer
number))
  TextValue Text
text -> Value -> Either Error Value
forall a b. b -> Either a b
Right (Text -> Value
String Text
text)
  BytesValue ByteString
_ -> Error -> Either Error Value
forall a b. a -> Either a b
Left (Text -> Error
InvalidMetadataJson Text
"Plain JSON cannot represent metadata bytes")
  ListValue [Metadatum]
values -> [Value] -> Value
forall a. ToJSON a => a -> Value
toJSON ([Value] -> Value) -> Either Error [Value] -> Either Error Value
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Metadatum -> Either Error Value)
-> [Metadatum] -> Either Error [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 Metadatum -> Either Error Value
metadatumToJson [Metadatum]
values
  MapValue [(Metadatum, Metadatum)]
pairs -> do
    [Pair]
entries <- ((Metadatum, Metadatum) -> Either Error Pair)
-> [(Metadatum, Metadatum)] -> Either Error [Pair]
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 (Metadatum, Metadatum) -> Either Error Pair
pair [(Metadatum, Metadatum)]
pairs
    let fields :: Object
fields = [Pair] -> Object
forall v. [(Key, v)] -> KeyMap v
KeyMap.fromList [Pair]
entries
    if Object -> Int
forall v. KeyMap v -> Int
KeyMap.size Object
fields Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [Pair] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Pair]
entries
      then Value -> Either Error Value
forall a b. b -> Either a b
Right (Object -> Value
Object Object
fields)
      else Error -> Either Error Value
forall a b. a -> Either a b
Left (Text -> Error
InvalidMetadataJson Text
"Plain JSON cannot preserve duplicate metadata map keys")
  where
    pair :: (Metadatum, Metadatum) -> Either Error Pair
pair (Metadatum
key, Metadatum
item) = case Metadatum -> View
view Metadatum
key of
      TextValue Text
text -> (,) (Text -> Key
Key.fromText Text
text) (Value -> Pair) -> Either Error Value -> Either Error Pair
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Metadatum -> Either Error Value
metadatumToJson Metadatum
item
      View
_ -> Error -> Either Error Pair
forall a b. a -> Either a b
Left (Text -> Error
InvalidMetadataJson Text
"Plain JSON metadata map keys must be text")

-- | Import ordinary JSON as metadata, matching native plain JSON conversion.
-- Strings stay text, including @0x@ prefixes; object keys stay text, including
-- decimal names. Objects assemble pairs in lexicographic key order. Integers
-- must be in -2^63 through 2^64-1; fractions, booleans and null return
-- 'InvalidMetadataJson'. Text and object keys retain the 64 UTF-8 byte bound.
-- Invalid integer/text lengths return their existing metadata validation errors.
-- This is not cardano-api's no-schema conversion, which infers bytes and numeric
-- keys. Use 'metadatumFromDetailedJson' when those distinctions are needed.
metadatumFromJson :: Value -> Either Error Metadatum
metadatumFromJson :: Value -> Either Error Metadatum
metadatumFromJson Value
json = case Value
json of
  Number Scientific
number -> do
    Integer
integer <- Scientific -> Either Error Integer
scientificInteger Scientific
number
    if Integer
integer Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64
forall a. Bounded a => a
minBound :: Int64)
      then Error -> Either Error Metadatum
forall a b. a -> Either a b
Left (Text -> Error
InvalidMetadataJson Text
"Plain JSON integer is below native signed 64-bit range")
      else Integer -> Either Error Metadatum
mkInteger Integer
integer
  String Text
text -> Text -> Either Error Metadatum
mkText Text
text
  Array Array
values -> [Metadatum] -> Metadatum
list ([Metadatum] -> Metadatum)
-> Either Error [Metadatum] -> Either Error Metadatum
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Value -> Either Error Metadatum)
-> [Value] -> Either Error [Metadatum]
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 Value -> Either Error Metadatum
metadatumFromJson (Array -> [Value]
forall a. Vector a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
Data.Foldable.toList Array
values)
  Object Object
fields -> [(Metadatum, Metadatum)] -> Metadatum
Cometa.Metadata.map ([(Metadatum, Metadatum)] -> Metadatum)
-> Either Error [(Metadatum, Metadatum)] -> Either Error Metadatum
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Pair -> Either Error (Metadatum, Metadatum))
-> [Pair] -> Either Error [(Metadatum, Metadatum)]
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 Pair -> Either Error (Metadatum, Metadatum)
pair (Object -> [Pair]
forall v. KeyMap v -> [(Key, v)]
KeyMap.toAscList Object
fields)
  Value
_ -> Error -> Either Error Metadatum
forall a b. a -> Either a b
Left (Text -> Error
InvalidMetadataJson Text
"Plain JSON metadata accepts integers, text, arrays and objects")
  where
    pair :: Pair -> Either Error (Metadatum, Metadatum)
pair (Key
key, Value
item) = (,) (Metadatum -> Metadatum -> (Metadatum, Metadatum))
-> Either Error Metadatum
-> Either Error (Metadatum -> (Metadatum, Metadatum))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text -> Either Error Metadatum
mkText (Key -> Text
Key.toText Key
key) Either Error (Metadatum -> (Metadatum, Metadatum))
-> Either Error Metadatum -> Either Error (Metadatum, Metadatum)
forall a b.
Either Error (a -> b) -> Either Error a -> Either Error b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Value -> Either Error Metadatum
metadatumFromJson Value
item