-- SPDX-FileCopyrightText: 2026 Alexandra de Wit
--
-- SPDX-License-Identifier: MIT
{-# LANGUAGE MagicHash #-}

{- | Shared text parsing, character classes, rendering and storage without dependencies on other core modules.
Inbound routes and outbound artifact filenames share the same path-component gate.
-}
module Ecluse.Core.Text (
    nonBlank,
    stripTrailingSlash,
    joinUrlPath,
    urlFilename,
    urlFilenameComponent,
    isSafeComponent,
    afterFirst,
    LowerPrefix,
    httpsPrefix,
    httpPrefix,
    lowerPrefixChars,
    isPrefixOfLowered,
    toLowerUnlessAsciiUnchanged,
    registryPath,
    isAsciiAlphaNum,
    readDecimalText,
    readHexText,
    writeDigits,
    displayExceptionT,
    joinAlternatives,
    textStorageBytes,
) where

import Control.Monad.ST (ST)
import Data.Array.Byte (ByteArray (..))
import Data.Char (isAsciiLower, isAsciiUpper, isControl, isDigit)
import Data.Primitive.ByteArray (MutableByteArray, writeByteArray)
import Data.Text qualified as T
import Data.Text.Encoding qualified as TE
import Data.Text.Internal qualified as TI
import Data.Text.Read qualified as TR
import GHC.Exts (Int (I#), sizeofByteArray#)
import Network.HTTP.Types.URI (urlDecode)

-- | The text trimmed of surrounding whitespace, or 'Nothing' when nothing remains. An empty or all-whitespace value therefore counts as absent.
nonBlank :: Text -> Maybe Text
nonBlank :: Text -> Maybe Text
nonBlank Text
t =
    let trimmed :: Text
trimmed = Text -> Text
T.strip Text
t
     in if Text -> Bool
T.null Text
trimmed then Maybe Text
forall a. Maybe a
Nothing else Text -> Maybe Text
forall a. a -> Maybe a
Just Text
trimmed

-- | Drop every trailing slash from a URL base, so @https:\/\/host\/\/@ and @https:\/\/host@ agree.
stripTrailingSlash :: Text -> Text
stripTrailingSlash :: Text -> Text
stripTrailingSlash = (Char -> Bool) -> Text -> Text
T.dropWhileEnd (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'/')

-- | Join a URL base and an already-encoded path with exactly one slash, whatever trailing slashes the base writes. It appends the path verbatim, and neither encodes nor validates it.
joinUrlPath :: Text -> Text -> Text
joinUrlPath :: Text -> Text -> Text
joinUrlPath Text
b Text
path = Text -> Text
stripTrailingSlash Text
b Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"/" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
path

-- | The final URL path component, preserving its encoded spelling without query or fragment. Both the raw and once-decoded component must pass 'isSafeComponent', with valid decoded UTF-8.
urlFilename :: Text -> Maybe Text
urlFilename :: Text -> Maybe Text
urlFilename Text
url = do
    let filename :: Text
filename = Text -> Text
urlFilenameComponent Text
url
    Bool -> Maybe ()
forall (f :: * -> *). Alternative f => Bool -> f ()
guard (Text -> Bool
isSafeComponent Text
filename)
    Bool -> Maybe () -> Maybe ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when ((Char -> Bool) -> Text -> Bool
T.any (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'%') Text
filename) (Maybe () -> Maybe ()) -> Maybe () -> Maybe ()
forall a b. (a -> b) -> a -> b
$ do
        decoded <- Either UnicodeException Text -> Maybe Text
forall l r. Either l r -> Maybe r
rightToMaybe (ByteString -> Either UnicodeException Text
TE.decodeUtf8' (Bool -> ByteString -> ByteString
urlDecode Bool
False (Text -> ByteString
forall a b. ConvertUtf8 a b => a -> b
encodeUtf8 Text
filename)))
        guard (isSafeComponent decoded)
    Text -> Maybe Text
forall a. a -> Maybe a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Text
filename

-- | The raw final URL path component without query or fragment, possibly empty. No decoding or validation occurs. Callers must validate and encode it before URL construction.
urlFilenameComponent :: Text -> Text
urlFilenameComponent :: Text -> Text
urlFilenameComponent = (Char -> Bool) -> Text -> Text
T.takeWhileEnd (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'/') (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Char -> Bool) -> Text -> Text
T.takeWhile Char -> Bool
inPath
  where
    inPath :: Char -> Bool
inPath Char
ch = Char
ch Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'?' Bool -> Bool -> Bool
&& Char
ch Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'#'

-- | Refuse empty components, traversal, separators, and controls. Callers must still percent-encode on URL construction.
isSafeComponent :: Text -> Bool
isSafeComponent :: Text -> Bool
isSafeComponent Text
c =
    Bool -> Bool
not (Text -> Bool
T.null Text
c)
        Bool -> Bool -> Bool
&& Text
c Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
/= Text
"."
        Bool -> Bool -> Bool
&& Text
c Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
/= Text
".."
        Bool -> Bool -> Bool
&& (Char -> Bool) -> Text -> Bool
T.all Char -> Bool
safeChar Text
c
  where
    safeChar :: Char -> Bool
safeChar Char
ch = Char
ch Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'/' Bool -> Bool -> Bool
&& Char
ch Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\\' Bool -> Bool -> Bool
&& Bool -> Bool
not (Char -> Bool
isControl Char
ch)

-- | The text after @needle@'s first occurrence, or all of @hay@ if absent. The scheme separator matches first, so a crafted "https://169.254.169.254/x?u=https://ok" gates on the host dialled.
afterFirst :: Text -> Text -> Text
afterFirst :: Text -> Text -> Text
afterFirst Text
needle Text
hay = Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
hay (Text -> Text -> Maybe Text
T.stripPrefix Text
needle ((Text, Text) -> Text
forall a b. (a, b) -> b
snd (HasCallStack => Text -> Text -> (Text, Text)
Text -> Text -> (Text, Text)
T.breakOn Text
needle Text
hay)))

-- | A lower-case prefix with its length in characters, so checking for it never measures a text. The constructor stays private, so each count sits beside its prefix in this module.
data LowerPrefix = LowerPrefix Int Text
    deriving stock (Int -> LowerPrefix -> ShowS
[LowerPrefix] -> ShowS
LowerPrefix -> String
(Int -> LowerPrefix -> ShowS)
-> (LowerPrefix -> String)
-> ([LowerPrefix] -> ShowS)
-> Show LowerPrefix
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> LowerPrefix -> ShowS
showsPrec :: Int -> LowerPrefix -> ShowS
$cshow :: LowerPrefix -> String
show :: LowerPrefix -> String
$cshowList :: [LowerPrefix] -> ShowS
showList :: [LowerPrefix] -> ShowS
Show)

-- | The @https://@ scheme prefix.
httpsPrefix :: LowerPrefix
httpsPrefix :: LowerPrefix
httpsPrefix = Int -> Text -> LowerPrefix
LowerPrefix Int
8 Text
"https://"

-- | The @http://@ scheme prefix.
httpPrefix :: LowerPrefix
httpPrefix :: LowerPrefix
httpPrefix = Int -> Text -> LowerPrefix
LowerPrefix Int
7 Text
"http://"

-- | The prefix's length in characters.
lowerPrefixChars :: LowerPrefix -> Int
lowerPrefixChars :: LowerPrefix -> Int
lowerPrefixChars (LowerPrefix Int
chars Text
_) = Int
chars

-- | Whether the prefix begins the lower-cased text. It lowers only the prefix's length of the text, which suffices because 'Data.Text.toLower' maps each character on its own to at least one.
isPrefixOfLowered :: LowerPrefix -> Text -> Bool
isPrefixOfLowered :: LowerPrefix -> Text -> Bool
isPrefixOfLowered (LowerPrefix Int
chars Text
prefix) Text
t = Text
lowered Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
prefix
  where
    -- Equality, not 'Data.Text.isPrefixOf', which streams both texts and allocates for each character.
    lowered :: Text
lowered = Int -> Text -> Text
T.take Int
chars (Text -> Text
T.toLower (Int -> Text -> Text
T.take Int
chars Text
t))

-- | Unicode lowercase, retaining the input when every character is ASCII and none is uppercase.
toLowerUnlessAsciiUnchanged :: Text -> Text
toLowerUnlessAsciiUnchanged :: Text -> Text
toLowerUnlessAsciiUnchanged Text
t
    | (Char -> Bool) -> Text -> Bool
T.all Char -> Bool
unchanged Text
t = Text
t
    | Bool
otherwise = Text -> Text
T.toLower Text
t
  where
    unchanged :: Char -> Bool
unchanged Char
c = Char
c Char -> Char -> Bool
forall a. Ord a => a -> a -> Bool
<= Char
'\x7f' Bool -> Bool -> Bool
&& Bool -> Bool
not (Char -> Bool
isAsciiUpper Char
c)

-- | The path half of an absolute URL, from the first slash after the authority. It splits on the first scheme separator, so a later one inside the URL cannot move where the path starts.
registryPath :: Text -> Text
registryPath :: Text -> Text
registryPath Text
raw = (Char -> Bool) -> Text -> Text
T.dropWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'/') (Text -> Text -> Text
afterFirst Text
"://" Text
raw)

-- | An ASCII letter or an ASCII digit. 'Data.Char.isAlphaNum' also takes the letters and digits outside ASCII.
isAsciiAlphaNum :: Char -> Bool
isAsciiAlphaNum :: Char -> Bool
isAsciiAlphaNum Char
c = Char -> Bool
isAsciiUpper Char
c Bool -> Bool -> Bool
|| Char -> Bool
isAsciiLower Char
c Bool -> Bool -> Bool
|| Char -> Bool
isDigit Char
c

-- | The non-negative integer a bare decimal digit run spells, 'Nothing' for anything else. Stricter than 'readMaybe', which also takes a sign, @0x10@, @0o10@, @  5@, and @(5)@.
readDecimalText :: (Integral a) => Text -> Maybe a
readDecimalText :: forall a. Integral a => Text -> Maybe a
readDecimalText = Reader a -> Text -> Maybe a
forall a. Reader a -> Text -> Maybe a
readWholly Reader a
forall a. Integral a => Reader a
TR.decimal

-- | The non-negative integer a bare hexadecimal digit run spells. The @0x@ prefix that @Data.Text.Read.hexadecimal@ takes is refused, so a caller strips and judges the prefix itself.
readHexText :: (Integral a) => Text -> Maybe a
readHexText :: forall a. Integral a => Text -> Maybe a
readHexText Text
t
    | LowerPrefix -> Text -> Bool
isPrefixOfLowered LowerPrefix
hexPrefix Text
t = Maybe a
forall a. Maybe a
Nothing
    | Bool
otherwise = Reader a -> Text -> Maybe a
forall a. Reader a -> Text -> Maybe a
readWholly Reader a
forall a. Integral a => Reader a
TR.hexadecimal Text
t

hexPrefix :: LowerPrefix
hexPrefix :: LowerPrefix
hexPrefix = Int -> Text -> LowerPrefix
LowerPrefix Int
2 Text
"0x"

-- The value a reader produced, only when it consumed the whole input. Trailing text is a
-- refusal rather than a silent prefix parse.
readWholly :: TR.Reader a -> Text -> Maybe a
readWholly :: forall a. Reader a -> Text -> Maybe a
readWholly Reader a
textReader Text
t = case Reader a
textReader Text
t of
    Right (a
n, Text
rest) | Text -> Bool
T.null Text
rest -> a -> Maybe a
forall a. a -> Maybe a
Just a
n
    Either String (a, Text)
_ -> Maybe a
forall a. Maybe a
Nothing

-- | Write a magnitude in decimal, its last digit at the offset and the digits before it at the offsets below. No write is bounds-checked: the caller must have reserved room for every digit.
writeDigits :: MutableByteArray st -> Int -> Word -> ST st ()
writeDigits :: forall st. MutableByteArray st -> Int -> Word -> ST st ()
writeDigits MutableByteArray st
buffer !Int
at !Word
value = do
    MutableByteArray (PrimState (ST st)) -> Int -> Word8 -> ST st ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray MutableByteArray st
MutableByteArray (PrimState (ST st))
buffer Int
at (Word8
0x30 Word8 -> Word8 -> Word8
forall a. Num a => a -> a -> a
+ Word -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word
value Word -> Word -> Word
forall a. Integral a => a -> a -> a
`rem` Word
10) :: Word8)
    if Word
value Word -> Word -> Bool
forall a. Ord a => a -> a -> Bool
>= Word
10 then MutableByteArray st -> Int -> Word -> ST st ()
forall st. MutableByteArray st -> Int -> Word -> ST st ()
writeDigits MutableByteArray st
buffer (Int
at Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1) (Word
value Word -> Word -> Word
forall a. Integral a => a -> a -> a
`quot` Word
10) else ST st ()
forall (f :: * -> *). Applicative f => f ()
pass

-- | Render an exception as 'Text' for a log line or error value.
displayExceptionT :: (Exception e) => e -> Text
displayExceptionT :: forall e. Exception e => e -> Text
displayExceptionT = String -> Text
forall a. ToText a => a -> Text
toText (String -> Text) -> (e -> String) -> e -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. e -> String
forall e. Exception e => e -> String
displayException

-- | Join items as prose alternatives: @a@, @a or b@, @a, b or c@.
joinAlternatives :: [Text] -> Text
joinAlternatives :: [Text] -> Text
joinAlternatives [Text]
items = case [Text] -> [Text]
forall a. [a] -> [a]
reverse [Text]
items of
    Text
final : earlier :: [Text]
earlier@(Text
_ : [Text]
_) -> Text -> [Text] -> Text
T.intercalate Text
", " ([Text] -> [Text]
forall a. [a] -> [a]
reverse [Text]
earlier) Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
" or " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
final
    [Text]
_ -> Text -> [Text] -> Text
T.intercalate Text
", " [Text]
items

-- | The byte size of the array behind a text. A slice keeps the whole array of the text it came from.
textStorageBytes :: Text -> Int
textStorageBytes :: Text -> Int
textStorageBytes (TI.Text (ByteArray ByteArray#
array) Int
_ Int
_) = Int# -> Int
I# (ByteArray# -> Int#
sizeofByteArray# ByteArray#
array)