-- Restricted generated-data grammar and resource limits.
package.path = "./?.lua;./?/init.lua;" .. package.path
local T = require("tests.modkit")
local SaveSerializer = require("src.core.SaveSerializer")

local limits = {
  allowArray = true, allowComments = true,
  maxBytes = 256, maxDepth = 4, maxNodes = 7,
  maxStringBytes = 8, maxTableEntries = 5, rootName = "generated data",
}

local value, err = SaveSerializer.decode(
  '-- Generated by tools/build_data.py. DO NOT EDIT.\n'
    .. 'return { rows = { "A", "B" }, [3] = true }\n', limits)
T.same(value, { rows = { "A", "B" }, [3] = true },
  "LuaWriter array and keyed-table grammar decodes as data")
T.eq(err, nil, "valid generated data has no error")

local invalid = {
  { "return function() end", "function literal" },
  { "owned = true; return {}", "global assignment" },
  { "return {}; print('x')", "trailing executable syntax" },
  { string.char(27) .. "Lua", "binary chunk" },
  { "return " .. string.rep(" ", 260) .. "{}", "source-size limit" },
  { 'return { a = { b = { c = { d = { e = {} } } } } }', "depth limit" },
  { 'return { a = "123456789" }', "string limit" },
  { 'return { 1, 2, 3, 4, 5, 6 }', "table-entry limit" },
  { 'return { a = 1, b = 2, c = 3, d = 4, e = { f = 6, g = 7 } }',
    "node limit" },
  { "return 7", "non-table root" },
}
for _, row in ipairs(invalid) do
  local got = SaveSerializer.decode(row[1], limits)
  T.eq(got, nil, row[2] .. " fails closed")
end

T.finish("generated_data_decoder")
