Модуль:Песочница/Pok: различия между версиями

мНет описания правки
Нет описания правки
 
(не показано 289 промежуточных версий этого же участника)
Строка 1: Строка 1:
-- Загрузка данных
local p = {}
local itemData = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data")
 
local BASE_USER = "IanComradeBot/"
 
local function get_module_name(pagePath)
    return "Module:" .. BASE_USER .. pagePath .. "/data"
end


local p = {}
local function load_cached_data(moduleName)
    local ok, loaded = pcall(mw.loadData, moduleName)
    if not ok or not loaded then
        return nil
    end
    return loaded
end


-- Функция для загрузки данных
local function parse_indexed_part(part)
local loadData = function(filePath)
     local key, idx = string.match(part, "^(.-)%[(%d+)%]$")
     local page = mw.title.new(filePath)
    if key then
     local content = page:getContent()
        return key, tonumber(idx)
     return content and mw.text.jsonDecode(content) or nil
    end
     local num = tonumber(part)
     if num then
        return nil, num
    end
    return part, nil
end
end


-- Функция processRolls для преобразования диапазона
local function get_by_path(tbl, path)
local processRolls = function(rolls)
     if not tbl or path == "" then return nil end
     local result = {}
     local cur = tbl
     if rolls and rolls.range then
    for part in string.gmatch(path, "([^%.]+)") do
        -- Если указан range
         local key, idx = parse_indexed_part(part)
        local min, max = rolls.range:match("(%d+),%s*(%d+)")
         if key and key ~= "" then
         min, max = tonumber(min), tonumber(max)
            if type(cur) ~= "table" then return nil end
         if min and max then
             local nextCur = cur[key]
             result[#result + 1] = string.format('[%d-%d]', min + 1, max + 1)
            if nextCur == nil then
         else
                nextCur = cur["!type:" .. key]
             result[#result + 1] = 'Некорректный формат для range.'
            end
            cur = nextCur
        end
         if idx then
             if type(cur) ~= "table" then return nil end
            cur = cur[idx]
         end
         end
    elseif rolls and rolls.value then
         if cur == nil then return nil end
        -- Если указано value
         result[#result + 1] = string.format('[%d]', rolls.value)
    else
        result[#result + 1] = 'Не указан параметр rolls.'
     end
     end
     return table.concat(result)
     return cur
end
end


-- Локальные функции
local function format_value(v)
local findDataById, formatContent, getContentsOutput, processNestedSelectors, getTableOutput, getContainedOutput, getChemOutput, handleGroupSelector, handleAllSelector, handleNestedSelector
    local okJson, json = pcall(mw.text.jsonEncode, v)
    if okJson and json == "null" then
        return "null"
    end
 
    if v == nil then return "" end


-- Функция для создания хэш-таблицы для быстрого поиска по ID
    local t = type(v)
local function buildIndex(itemData)
     if t == "string" or t == "number" or t == "boolean" then
     if not itemData then return {} end
        return tostring(v)
     local index = {}
     elseif t == "table" then
    for _, item in ipairs(itemData) do
        local ok, json2 = pcall(mw.text.jsonEncode, v)
         index[item.id] = item
         if ok and json2 then
            return json2
        end
        return ""
    else
        return tostring(v)
     end
     end
    return index
end
end


-- Поиск данных по ID через индекс
local function to_nowiki(v)
findDataById = function(itemDataIndex, id)
     return "<nowiki>" .. v .. "</nowiki>"
     if not itemDataIndex then return nil end
for _, item in ipairs(itemDataIndex) do
if item.id == id then
return item
end
end
end
end


-- Форматирование содержимого
local function is_array(tbl)
formatContent = function(content)
    local max = 0
    if not content.id then
    local count = 0
         return "Ошибка: отсутствует id у элемента."
    for k in pairs(tbl) do
        if type(k) ~= "number" then
            return false
        end
        if k > max then max = k end
         count = count + 1
     end
     end
    return count > 0 and max == count
end


     local name = string.format('{{#invoke:Entity Lookup|getname|%s}}', content.id)
local function deep_copy(src)
    local image = string.format('%s.png', content.id)
     local dst = {}
local amount = (content.amount and content.amount ~= 1) and string.format(" [%d]", content.amount) or ""
    for k, v in pairs(src) do
     local prob = ""
        if type(v) == "table" then
            dst[k] = deep_copy(v)
        else
            dst[k] = v
        end
    end
     return dst
end


     if content.weight then
local function deep_merge(dst, src)
         content.prob = content.weight / 100
     for k, v in pairs(src) do
        if type(v) == "table" and type(dst[k]) == "table" then
            deep_merge(dst[k], v)
        elseif type(v) == "table" then
            dst[k] = deep_copy(v)
         else
            dst[k] = v
        end
     end
     end
end


     if content.prob then
local function resolve_entry(data, id)
         prob = string.format(" <div>%s%%</div>", content.prob * 100 >= 1 and math.floor(content.prob * 100) or content.prob * 100)
     if type(data) ~= "table" then
         return nil
     end
     end


     return string.format(
     if id and id ~= "" then
        '{{LinkСard|SideStyle=1|background-color=#cbcbff0a|image=%s|name=%s%s%s {{#invoke:Prototypes/Хранилище/Предмет|main|framing|contained|%s}} }}',
        local direct = data[id]
         image, name, amount, prob, content.id
        if direct ~= nil then
     )
            return direct
end
        end
 
        local idsTable = data.id
        if type(idsTable) == "table" then
            local specific = idsTable[id]
            if type(specific) == "table" then
                local base = data["default"]
                if type(base) == "table" then
                    local merged = deep_copy(base)
                    deep_merge(merged, specific)
                    return merged
                end
                return deep_copy(specific)
            end
         end
     end


-- Получение содержимого через таблицу
     local base = data["default"]
getContentsOutput = function(contents)
     if type(base) == "table" then
     local result = {}
         return deep_copy(base)
     for _, content in ipairs(contents) do
         result[#result + 1] = formatContent(content)
     end
     end
     return table.concat(result)
     return nil
end
end


-- Обработка вложенных таблиц
local function collect_id_keys(data)
processNestedSelectors = function(children, visited)
    if type(data) ~= "table" then
visited = visited or {}
        return {}
     if not children or #children == 0 then return "" end
     end


     local results = {}
     local idsTable = data.id
    local ids = {}


     for _, child in ipairs(children) do
     if type(idsTable) == "table" then
        if child.id then
        for k in pairs(idsTable) do
if not visited[child.id] then
             ids[#ids + 1] = k
    results[#results + 1] = formatContent(child)
end
        elseif child["!type"] == "NestedSelector" then
            results[#results + 1] = handleNestedSelector(child, true, visited)
        elseif child["!type"] == "GroupSelector" then
             results[#results + 1] = handleGroupSelector(child, visited)
         end
         end
        return ids
     end
     end


     return table.concat(results)
     for k in pairs(data) do
        if k ~= "default" and k ~= "id" then
            ids[#ids + 1] = k
        end
    end
    return ids
end
end


-- Обработка таблиц
local function contains_target(v, target)
getTableOutput = function(tableId, visited)
    if type(v) == "table" then
    visited = visited or {}
        if is_array(v) then
            for _, item in ipairs(v) do
                if tostring(item) == target then
                    return true
                end
            end
            return false
        end


    if visited[tableId] then
        for _, item in pairs(v) do
         return ''
            if tostring(item) == target then
                return true
            end
        end
         return false
     end
     end


     visited[tableId] = true
     return tostring(v) == target
end


    local tableData = loadData('User:IanComradeBot/prototypes/table.json')
local function is_nonempty_value(v)
     local tableDataIndex = findDataById(tableData, tableId)
     if v == nil then return false end
    if type(v) == "table" then
        return next(v) ~= nil
    end
    return true
end


     if not tableDataIndex then return 'Таблица не найдена.' end
local function find_matching_ids(idsTable, keyPath, searchValue)
     local target = tostring(searchValue)
    local matches = {}


     if tableDataIndex['!type:GroupSelector'] then
     for idKey, entry in pairs(idsTable) do
        return handleGroupSelector(tableDataIndex['!type:GroupSelector'], visited)
        if type(entry) == "table" then
    elseif tableDataIndex['!type:AllSelector'] then
            local v = get_by_path(entry, keyPath)
         return processNestedSelectors(tableDataIndex['!type:AllSelector'].children, visited)
            if v ~= nil and contains_target(v, target) then
                matches[#matches + 1] = idKey
            end
         end
     end
     end


     return 'Таблица не содержит элементов.'
     return matches
end
 
local function preprocess_or_return(frame, text)
    if type(frame.preprocess) == "function" then
        return frame:preprocess(text)
    end
    return text
end
end


-- Формирование списка содержащихся предметов или таблиц
local function get_field_loose(entry, fieldId)
getContainedOutput = function(itemData, id, visited)
    local value = entry[fieldId]
     visited = visited or {}
    if value ~= nil then return value end
    if fieldId == "" then return nil end
 
    local first = string.sub(fieldId, 1, 1)
     local tail = string.sub(fieldId, 2)
    value = entry[string.lower(first) .. tail]
    if value ~= nil then return value end
 
    return entry[string.upper(first) .. tail]
end


     if visited[id] then
local function apply_pattern(s, pattern, repl)
         return ''
     if not pattern or pattern == "" or not s then
         return s
     end
     end


     visited[id] = true
     local text = tostring(s)
    local replacement
    if repl and repl ~= "" then
        replacement = tostring(repl)
        replacement = replacement:gsub("\\(%d)", "%%%1")
    else
        replacement = "%1"
    end


     local item = findDataById(itemData, id)
     local patt = pattern
     if not item then return '' end
     if not patt:find("%^") and not patt:find("%$") then
        patt = "^" .. patt .. "$"
    end


     local result = {}
     return (text:gsub(patt, replacement))
end


    -- Обработка StorageFill
local function flatten_parts(entry)
     if item.StorageFill and item.StorageFill.contents then
     if type(entry) ~= "table" then return {} end
        result[#result + 1] = getContentsOutput(item.StorageFill.contents)


     -- Обработка EntityTableContainerFill
     local parts = {}
     elseif item.EntityTableContainerFill and item.EntityTableContainerFill.containers then
     local function append_table_json(key, value)
        local containers = item.EntityTableContainerFill.containers
        local ok, json = pcall(mw.text.jsonEncode, value)
        if ok and json then
            parts[#parts + 1] = key .. "=" .. to_nowiki(json)
        end
    end


         -- Обработка entity_storage
    local function walk(tbl, prefix)
         if containers.entity_storage then
        local keys = {}
             if containers.entity_storage.children then
         for k in pairs(tbl) do keys[#keys + 1] = k end
                 result[#result + 1] = processNestedSelectors(containers.entity_storage.children, visited)
         table.sort(keys, function(a, b) return tostring(a) < tostring(b) end)
            end
        for _, k in ipairs(keys) do
             if containers.entity_storage.tableId then
            local v = tbl[k]
                 result[#result + 1] = getTableOutput(containers.entity_storage.tableId, visited)
            local kStr = tostring(k)
             local key = (prefix == "" and kStr or prefix .. "." .. kStr)
            if type(v) == "table" then
                if next(v) == nil then
                 else
                    append_table_json(key, v)
                    if is_array(v) then
                        local first = v[1]
                        if type(first) == "table" then
                            walk(first, key)
                        end
                    else
                        walk(v, key)
                    end
                end
             else
                 parts[#parts + 1] = key .. "=" .. tostring(v)
             end
             end
         end
         end
    end
    walk(entry, "")
    return parts
end


         -- Обработка storagebase
local function flatten_entry(entry)
         if containers.storagebase and containers.storagebase.tableId then
    local parts = flatten_parts(entry)
             result[#result + 1] = getTableOutput(containers.storagebase.tableId, visited)
    if #parts == 0 then
         return ""
    end
    return table.concat(parts, "|")
end
 
function p.findInGenerator(frame)
    local args = frame.args or {}
    local searchId = args[1] or ""
    local kind = (args[2] or ""):lower()
    local fieldId = args[3] or ""
 
    if searchId == "" or fieldId == "" then
         return ""
    end
    if kind ~= "prototype" and kind ~= "component" then
        return ""
    end
 
    local storeName = (kind == "prototype") and "prototype_store.json" or "component_store.json"
    local moduleName = get_module_name(storeName)
    local data = load_cached_data(moduleName)
    if not data then
        return ""
    end
 
    local entry = data[searchId]
    if type(entry) ~= "table" then
        return ""
    end
 
    local value = get_field_loose(entry, fieldId)
    if value == nil then
        return ""
    end
 
    local out = {}
    local t = type(value)
    if t == "table" then
        for _, v in ipairs(value) do
             out[#out + 1] = v
         end
         end
    else
        out[1] = value
     end
     end


     return table.concat(result)
     return mw.text.jsonEncode(out)
end
 
function p.flattenField(frame)
    local args = frame.args or {}
    local id = args[1] or ""
    local pagePath = args[2] or ""
    if id == "" or pagePath == "" then return "" end
 
    local moduleName = get_module_name(pagePath)
    local data = load_cached_data(moduleName)
    if not data then return "" end
 
    local entry = resolve_entry(data, id) or {}
    return flatten_entry(entry)
end
end


-- Обработка AllSelector
function p.get(frame)
handleAllSelector = function(allSelector)
    local args = frame.args or {}
     if not allSelector.children then return '' end
    local id = args[1] or ""
     return processNestedSelectors(allSelector.children)
    local pagePath = args[2] or ""
    local keyPath = args[3] or ""
 
    if pagePath == "" then return "" end
 
    local moduleName = get_module_name(pagePath)
    local data = load_cached_data(moduleName)
     if not data then return "" end
 
    local entry = resolve_entry(data, id)
    if entry == nil then return "" end
 
    if keyPath == "" then
        return format_value(entry)
    end
 
    local value = get_by_path(entry, keyPath)
     return format_value(value)
end
end


-- Обработка GroupSelector
function p.getId(frame)
handleGroupSelector = function(groupSelector)
     local args = frame.args or {}
     if not groupSelector.children then return '' end
    local searchValue = args[1] or ""
     local result = {}
     local pagePath = args[2] or ""
     local wrapperStart, wrapperEnd = "", ""
     local keyPath = args[3] or ""
    local searchType = (args.searchType or ""):lower()


    -- Проверка для контейнера EntityTableContainerFill
     if searchValue == "" or pagePath == "" or keyPath == "" then
     if groupSelector.weight and groupSelector.weight ~= "default" then
         return ""
        wrapperStart = string.format('{{LinkСard/Сollapsible|name=Группа предметов %s%%|content=', groupSelector.weight)
     end
         wrapperEnd = "}}"
    if searchType == "" then
     elseif groupSelector["!type"] == "GroupSelector" and not groupSelector.weight then
         searchType = "value"
         wrapperStart = '{{LinkСard/Сollapsible|name=Может выпасть лишь один из:|content='
        wrapperEnd = "}}"
     end
     end


     for _, child in ipairs(groupSelector.children) do
     local moduleName = get_module_name(pagePath)
        if child["!type"] == "GroupSelector" then
    local data = load_cached_data(moduleName)
            result[#result + 1] = handleGroupSelector(child)
    if not data then return "[]" end
        elseif child["!type"] == "AllSelector" then
 
            result[#result + 1] = string.format('{{LinkСard/Сollapsible|name=Выпадают только вместе:|content=%s}}', handleAllSelector(child))
    local ids = collect_id_keys(data)
        elseif child.id then
    if #ids == 0 then
            result[#result + 1] = formatContent(child)
        return ""
        else
    end
            result[#result + 1] = "<div>Ошибка: отсутствует id у элемента.</div>"
 
    local matches
    if searchType == "key" then
        local target = tostring(searchValue)
        matches = {}
        for _, idKey in ipairs(ids) do
            local entry = resolve_entry(data, idKey)
            if type(entry) == "table" then
                local v = get_by_path(entry, keyPath)
                if type(v) == "table" and v[target] ~= nil then
                    matches[#matches + 1] = idKey
                end
            end
        end
    else
        local target = tostring(searchValue)
        matches = {}
        for _, idKey in ipairs(ids) do
            local entry = resolve_entry(data, idKey)
            if type(entry) == "table" then
                local v = get_by_path(entry, keyPath)
                if v ~= nil and contains_target(v, target) then
                    matches[#matches + 1] = idKey
                end
            end
         end
         end
     end
     end


     return wrapperStart .. table.concat(result) .. wrapperEnd
     if #matches == 0 then
        return ""
    end
 
    local ok, json = pcall(mw.text.jsonEncode, matches)
    if ok and json then
        return json
    end
 
    return ""
end
end


-- Обработка NestedSelector
function p.getTplId(frame)
handleNestedSelector = function(nestedSelector, wrapped, visited)
    local args = frame.args or {}
visited = visited or {}
     local searchValue = args[1] or ""
     if not nestedSelector.tableId then return '' end
    local pagePath = args[2] or ""
    local keyPath = args[3] or ""
    local tplPath = mw.text.unstripNoWiki(args[4] or "")
    local searchType = (args.searchType or ""):lower()


     local result = {}
     if searchType == "" then
     local classesRolls, classesProb
        searchType = "value"
    end
    if searchType == "path" then
        searchValue = ""
        pagePath = args[1] or ""
        keyPath = args[2] or ""
        tplPath = mw.text.unstripNoWiki(args[3] or "")
    end
    if pagePath == "" or keyPath == "" or tplPath == "" then
        return ""
    end
    if searchType ~= "path" and searchValue == "" then
        return ""
     end


     if wrapped then
    local moduleName = get_module_name(pagePath)
         if nestedSelector.rolls and nestedSelector.rolls.range then
    local data = load_cached_data(moduleName)
             local rollsResult = processRolls(nestedSelector.rolls)
    if not data then return "" end
             if rollsResult and #rollsResult > 0 then
 
                 classesRolls = ', максимум может выпасть: ' .. rollsResult
    local ids = collect_id_keys(data)
     if #ids == 0 then
         return ""
    end
 
    local matches
    if searchType == "path" then
        matches = {}
        for _, idKey in ipairs(ids) do
             local entry = resolve_entry(data, idKey)
             if type(entry) == "table" then
                 local v = get_by_path(entry, keyPath)
                if is_nonempty_value(v) then
                    matches[#matches + 1] = idKey
                end
             end
             end
         end
         end
         if nestedSelector.prob then
    elseif searchType == "key" then
             classesProb = string.format(" <div>%s%%</div>", nestedSelector.prob * 100 >= 1 and math.floor(nestedSelector.prob * 100) or nestedSelector.prob * 100)
        local target = tostring(searchValue)
        matches = {}
         for _, idKey in ipairs(ids) do
            local entry = resolve_entry(data, idKey)
            if type(entry) == "table" then
                local v = get_by_path(entry, keyPath)
                if type(v) == "table" and v[target] ~= nil then
                    matches[#matches + 1] = idKey
                end
            end
        end
    else
        local target = tostring(searchValue)
        matches = {}
        for _, idKey in ipairs(ids) do
             local entry = resolve_entry(data, idKey)
            if type(entry) == "table" then
                local v = get_by_path(entry, keyPath)
                if v ~= nil and contains_target(v, target) then
                    matches[#matches + 1] = idKey
                end
            end
         end
         end
     end
     end


     if wrapped and (classesRolls or classesProb) then
     if #matches == 0 then
         result[#result + 1] = string.format('{{LinkСard/Сollapsible|name=Группа предметов%s%s|content=', classesRolls or "", classesProb or "")
         return ""
     end
     end


     result[#result + 1] = getTableOutput(nestedSelector.tableId, visited)
     local out = {}
    for _, idKey in ipairs(matches) do
        local tpl = p.getTpl({ args = { idKey, pagePath, tplPath }, data = data })
        if tpl ~= "" then
            out[#out + 1] = tpl
        end
    end


     if wrapped and (classesRolls or classesProb) then
     if #out == 0 then
         result[#result + 1] = "}}"
         return ""
     end
     end


     return table.concat(result)
     local result = table.concat(out, " ")
    return preprocess_or_return(frame, result)
end
end


-- Формирование списка химии
function p.getTpl(frame)
getChemOutput = function(itemData, id)
     local args = frame.args or {}
     local item = findDataById(itemData, id)
    local id = args[1] or ""
     if not item or not item.SolutionContainerManager or not item.SolutionContainerManager.solutions then return '' end
     local pagePath = args[2] or ""
    local tplPath = mw.text.unstripNoWiki(args[3] or "")


     local result = {}
    if id == "" or pagePath == "" or tplPath == "" then
     for _, solution in pairs(item.SolutionContainerManager.solutions) do
        return ""
         for _, reagent in ipairs(solution.reagents) do
    end
            result[#result + 1] = string.format('<li>[[Химия#chem_%s|%s]] (%d ед.)</li>', reagent.ReagentId, reagent.ReagentId, reagent.Quantity)
 
    local moduleName = get_module_name(pagePath)
     local data = frame.data
    if not data then
        data = load_cached_data(moduleName)
    end
    if not data then
        return ""
    end
 
     local entry = resolve_entry(data, id)
    local extra = flatten_entry(entry)
    local tplStr = "{{" .. tostring(tplPath) .. "|id=" .. tostring(id)
    if extra ~= "" then
         tplStr = tplStr .. "|" .. extra
    end
    tplStr = tplStr .. "}}"
 
    return preprocess_or_return(frame, tplStr)
end
 
function p.getTplGenerator(frame)
    local args = frame.args or {}
    local searchId = args[1] or ""
    local kind = (args[2] or ""):lower()
    local generatorId = args[3] or ""
    local tplPath = mw.text.unstripNoWiki(args[4] or "")
 
    if searchId == "" or generatorId == "" or tplPath == "" then
        return ""
    end
    if kind ~= "prototype" and kind ~= "component" then
        return ""
    end
 
    local dir = (kind == "prototype") and "prototype/" or "component/"
    local pagePath = dir .. generatorId .. ".json"
 
    local idsJson = p.findInGenerator({ args = { searchId, kind, generatorId } })
    local ok, ids = pcall(mw.text.jsonDecode, idsJson or "")
    if not ok or type(ids) ~= "table" or #ids == 0 then
        return ""
    end
 
    local moduleName = get_module_name(pagePath)
    local data = load_cached_data(moduleName)
    if not data then
        return ""
    end
 
    local out = {}
    for _, id in ipairs(ids) do
        local tpl = p.getTpl({ args = { id, pagePath, tplPath }, data = data })
        if tpl ~= "" then
            out[#out + 1] = tpl
         end
         end
     end
     end
     return string.format('<ul class="1">%s</ul>', table.concat(result))
 
    local result = table.concat(out, " ")
    return preprocess_or_return(frame, result)
end
 
function p.flattenParams(entry)
     return flatten_parts(entry)
end
 
function p.getGenerator(frame)
    local args = frame.args or {}
    local searchId = args[1] or ""
    local kind = (args[2] or ""):lower()
    local generatorId = args[3] or ""
 
    if searchId == "" or generatorId == "" then
        return ""
    end
    if kind ~= "prototype" and kind ~= "component" then
        return ""
    end
 
    local idsJson = p.findInGenerator({ args = { searchId, kind, generatorId } })
    local ok, ids = pcall(mw.text.jsonDecode, idsJson or "")
    if not ok or type(ids) ~= "table" or #ids == 0 then
        return ""
    end
 
    local okOut, outJson = pcall(mw.text.jsonEncode, ids)
    if okOut and outJson then
        return outJson
    end
 
    return ""
end
end


-- Основная функция модуля
function p.hasComp(frame)
function p.main(frame)
     local args = frame.args or {}
     local mode = frame.args[1]
    local entityId = args[1] or ""
     local id = frame.args[2]
     local compName = args[2] or ""
 
    if entityId == "" or compName == "" then
        return "false"
    end


     if not id then return 'Не указан ID.' end
     local moduleName = get_module_name("component.json")
   
     local data = load_cached_data(moduleName)
     local itemDataIndex = itemData
     if not data then
   
        return "false"
     if not itemData then return 'Не удалось загрузить данные.' end
    end


     if mode == 'framing' then
     if type(data) ~= "table" then
         local subMode = frame.args[2]
         return "false"
        local id = frame.args[3]
    end


         if not id then
    local entry = data[entityId]
             return 'Не указан ID для режима framing.'
    if type(entry) ~= "table" then
        return "false"
    end
 
    local target = tostring(compName)
    for _, v in ipairs(entry) do
         if tostring(v) == target then
             return "true"
         end
         end
    end
    return "false"
end


        if subMode == 'chem' then
function p.GeneratorId(frame)
            return frame:preprocess('{{СollapsibleMenu|' .. getChemOutput(itemDataIndex, id) .. '}}')
    local args = frame.args or {}
        elseif subMode == 'contained' then
    local pagePath = args[1] or ""
            return frame:preprocess('{{СollapsibleMenu|' .. getContainedOutput(itemDataIndex, id) .. '}}')
    local replace = mw.text.unstripNoWiki(args.replace or "")
        else
    local pattern = mw.text.unstripNoWiki(args.pattern or "(.*)")
            return 'Неизвестный подрежим для framing: ' .. subMode
 
        end
     if pagePath == "" then
     elseif mode == 'chem' then
         return ""
         return frame:preprocess(getChemOutput(itemDataIndex, id))
    end
     elseif mode == 'contained' then
 
         return frame:preprocess(getContainedOutput(itemDataIndex, id))
    local moduleName = get_module_name(pagePath)
     elseif mode == 'rolls' then
    local data = load_cached_data(moduleName)
         local entity = findDataById(itemDataIndex, id)
     if not data then
         if not entity then return 'ID не найден в данных.' end
         return ""
    end
 
    local idsTable = data.id
     if type(idsTable) ~= "table" then
         return ""
    end
 
    local ids = {}
    for k in pairs(idsTable) do
         ids[#ids + 1] = k
    end
 
    table.sort(ids)


        if entity.EntityTableContainerFill then
    if replace ~= "" then
             local containers = entity.EntityTableContainerFill.containers
        local out = {}
             if containers.entity_storage and containers.entity_storage.rolls then
        for _, id in ipairs(ids) do
                 return processRolls(containers.entity_storage.rolls)
             local text = apply_pattern(id, pattern, replace)
             if text ~= "" then
                 out[#out + 1] = text
             end
             end
         end
         end
        if #out == 0 then
            return ""
        end
        return preprocess_or_return(frame, table.concat(out, "\n"))
    end
    local ok, json = pcall(mw.text.jsonEncode, ids)
    if ok and json then
        return json
    end
    return ""
end
function p.GeneratorTplId(frame)
    local args = frame.args or {}
    local pagePath = args[1] or ""
    local tplPath = args[2] or ""
    if pagePath == "" or tplPath == "" then
        return ""
    end
    local moduleName = get_module_name(pagePath)
    local data = load_cached_data(moduleName)
    if not data then
        return ""
    end


         return ''
    local idsTable = data.id
     else
    if type(idsTable) ~= "table" then
         return 'Неизвестный режим: ' .. mode
         return ""
    end
 
    local out = {}
 
     for idKey in pairs(idsTable) do
         local tpl = p.getTpl({ args = { idKey, pagePath, tplPath }, data = data })
        if tpl ~= "" then
            out[#out + 1] = tpl
        end
     end
     end
    table.sort(out)
    local result = table.concat(out, " ")
    return preprocess_or_return(frame, result)
end
end


return p
return p