-- lx-bundle:true

-- entities_encode.lua
-- Full HTML entity encoder

-- Keep generated helper data on the canonical plugin namespace
local encode_map = require("plugins.htmlentities.encode_map")

local MAP
if type(encode_map) == "table" and type(encode_map.ENTITIES) == "table" then
	MAP = encode_map.ENTITIES
elseif type(encode_map) == "table" then
	MAP = encode_map
else
	error("lib.entities_encode_map returned non-table")
end

local BASIC = {
	["&"] = "&amp;",
	["<"] = "&lt;",
	[">"] = "&gt;",
	['"'] = "&quot;",
	["'"] = "&#39;",
}

local M = {}

-- Encode UTF-8 text to entities using the safe HTML baseline:
-- &, <, >, ", '
function M.encode_basic(text)
	local src = tostring(text or "")
	return (src:gsub("[&<>\"']", BASIC))
end

-- Full encode using generated WHATWG map
-- This can encode many more characters (for example newline -> &NewLine;)
function M.encode_full(text)
	local src = tostring(text or "")
	return (src:gsub("[%z\1-\127\194-\244][\128-\191]*", function(ch)
		return MAP[ch] or BASIC[ch] or ch
	end))
end

return M
