module Text.Jasmine
    ( minify
    , minifym
    , minifyBb
    , minifyFile
    ) where

import           Data.ByteString.Builder (Builder)
import qualified Data.ByteString.Builder as Builder
import qualified Data.ByteString.Lazy.Char8 as LBS
import           Data.Text.Lazy (unpack)
import           Data.Text.Lazy.Encoding (decodeUtf8With)
import           Data.Text.Encoding.Error (lenientDecode)

import           Language.JavaScript.Parser (readJs, parse, JSAST)
import           Language.JavaScript.Pretty.Printer (renderJS)
import           Language.JavaScript.Process.Minify (minifyJS)



minifym :: LBS.ByteString -> Either String LBS.ByteString
minifym :: ByteString -> Either String ByteString
minifym ByteString
s =
  case ByteString -> Either String JSAST
myParse ByteString
s of
    Left String
msg -> forall a b. a -> Either a b
Left (forall a. Show a => a -> String
show String
msg)
    Right JSAST
p  -> forall a b. b -> Either a b
Right forall a b. (a -> b) -> a -> b
$ Builder -> ByteString
Builder.toLazyByteString forall a b. (a -> b) -> a -> b
$ JSAST -> Builder
renderJS forall a b. (a -> b) -> a -> b
$ JSAST -> JSAST
minifyJS JSAST
p


minifyBb :: LBS.ByteString -> Either String Builder
minifyBb :: ByteString -> Either String Builder
minifyBb ByteString
s =
  case ByteString -> Either String JSAST
myParse ByteString
s  of
    Left String
msg -> forall a b. a -> Either a b
Left (forall a. Show a => a -> String
show String
msg)
    Right JSAST
p  -> forall a b. b -> Either a b
Right (JSAST -> Builder
renderJS forall a b. (a -> b) -> a -> b
$ JSAST -> JSAST
minifyJS JSAST
p)


minify :: LBS.ByteString -> LBS.ByteString
minify :: ByteString -> ByteString
minify =
  Builder -> ByteString
Builder.toLazyByteString forall b c a. (b -> c) -> (a -> b) -> a -> c
. JSAST -> Builder
renderJS forall b c a. (b -> c) -> (a -> b) -> a -> c
. JSAST -> JSAST
minifyJS forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> JSAST
readJs forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> String
lbToStr


minifyFile :: FilePath -> IO LBS.ByteString
minifyFile :: String -> IO ByteString
minifyFile String
filename =
  ByteString -> ByteString
minify forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> IO ByteString
LBS.readFile String
filename


myParse :: LBS.ByteString -> Either String JSAST
myParse :: ByteString -> Either String JSAST
myParse ByteString
input =
  String -> String -> Either String JSAST
parse (ByteString -> String
lbToStr ByteString
input) String
"src"


lbToStr :: LBS.ByteString -> String
lbToStr :: ByteString -> String
lbToStr =
  Text -> String
unpack forall b c a. (b -> c) -> (a -> b) -> a -> c
. OnDecodeError -> ByteString -> Text
decodeUtf8With OnDecodeError
lenientDecode