Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Module:DependencyList: Difference between revisions

From Deepspace Lore
No edit summary
No edit summary
 
(5 intermediate revisions by the same user not shown)
Line 1: Line 1:
--- Based on Module:DependencyList from RuneScape Wiki and Star Citizen Wiki
--- Based on Module:DependencyList from RuneScape Wiki and Star Citizen Wiki
--- @see https://runescape.wiki/w/Module:DependencyList
--- @see https://runescape.wiki/w/Module:DependencyList
require( 'strict' )


-- <nowiki>
local p = {}
require('strict')
local libraryUtil = require( 'libraryUtil' )
local arr = require( 'Module:Array' )
local yn = require( 'Module:Yesno' )
local param = require( 'Module:Paramtest' )
local userError = require( 'Module:User error' )
local hatnote = require( 'Module:Hatnote' )._hatnote
local mHatlist = require( 'Module:Hatnote list' )
local mbox = require( 'Module:Mbox' )._mbox


local p = {}
local dpl -- Lazy load DPL
local libraryUtil = require('libraryUtil')
local arr = require('Module:Array')
local yn = require('Module:Yesno')
local param = require('Module:Paramtest')
local userError = require('Module:User error')
local hatnote = require('Module:Hatnote')._hatnote
local mHatlist = require('Module:Hatnote list')
local mbox = require('Module:Mbox')._mbox
local tooltip = require('Module:Tooltip')


local dpl -- lazy loaded
local QUERY_MODE = 'dpl'
local MAX_DYNAMIC_REQUIRE_LIST_LENGTH = 30


local moduleIsUsed = false
local shouldAddCategories = false
local COLLAPSE_LIST_LENGTH_THRESHOLD = 5
local COLLAPSE_LIST_LENGTH_THRESHOLD = 5
local MAX_DYNAMIC_REQUIRE_LIST_LENGTH = 30
local dynamicRequireListQueryCache = {}
local dynamicRequireListQueryCache = {}


local NS_MODULE_NAME = mw.site.namespaces[828].name
local NS_MODULE_NAME = mw.site.namespaces[828].name
local NS_TEMPLATE_NAME = mw.site.namespaces[10].name
local NS_TEMPLATE_NAME = mw.site.namespaces[10].name


local builtins = {
local builtins = {
Line 32: Line 34:
     ['strict'] = {
     ['strict'] = {
         link = 'mw:Special:MyLanguage/Extension:Scribunto/Lua reference manual#strict',
         link = 'mw:Special:MyLanguage/Extension:Scribunto/Lua reference manual#strict',
         categories = { '[[Category:Strict mode modules]]' },
         categories = { 'Strict mode modules' },
     },
     },
}
}


-- ============================================================
-- String / name utilities
-- ============================================================


local function substVarValue(moduleContent, varName)
---@param content string
     local res = moduleContent:match(varName .. '%s*=%s*(%b""%s-%.*)') or
---@param varName string
                moduleContent:match(varName .. "%s*=%s*(%b''%s-%.*)")or ''
---@return string
     if res:find('^(["\'])[Mm]odule:[%S]+%1') and not res:find('%.%.') and not res:find('%%%a') then
local function substVarValue( content, varName )
         return mw.text.trim(res)
     local res = content:match( varName .. '%s*=%s*(%b""%s-%.*)' ) or content:match( varName .. "%s*=%s*(%b''%s-%.*)" ) or ''
     if res:find( '^(["\'])[Mm]odule?:[%S]+%1' ) and not res:find( '%.%.' ) and not res:find( '%%%a' ) then
         return mw.text.trim( res )
     else
     else
         return ''
         return ''
Line 50: Line 51:
end
end


local function extractModuleName(capture, moduleContent)
 
     capture = capture:gsub('^%(%s*(.-)%s*%)$', '%1')
---@param capture string
     if capture:find('^(["\']).-%1$') then
---@param content string
---@return string
local function extractModuleName( capture, content )
     capture = capture:gsub( '^%(%s*(.-)%s*%)$', '%1' )
 
     if capture:find( '^(["\']).-%1$' ) then
         return capture
         return capture
     elseif capture:find('^[%a_][%w_]*$') then
     elseif capture:find( '^[%a_][%w_]*$' ) then
         return substVarValue(moduleContent, capture)
         return substVarValue( content, capture )
     end
     end
     return capture
     return capture
end
end


local function formatPageName(str)
 
     return mw.text.trim(str)
---@param str string
         :gsub('^(["\'])(.-)%1$', '%2')
---@return string
         :gsub('_', ' ')
local function formatPageName( str )
         :gsub('^.', string.upper)
     local name = mw.text.trim( str )
         :gsub('^([^:]-:)(.)', function(a, b) return a .. string.upper(b) end)
         :gsub( '^([\'\"])(.-)%1$', function ( _, x ) return x end )
         :gsub( '_', ' ' )
         :gsub( '^.', string.upper )
         :gsub( ':.', string.upper )
 
    return name
end
end


local function formatModuleName(str, allowBuiltins)
 
---@param str string
---@param allowBuiltins? boolean
---@return string
local function formatModuleName( str, allowBuiltins )
     if allowBuiltins then
     if allowBuiltins then
         local name = mw.text.trim(str):gsub('^(["\'])(.-)%1$', '%2')
         local name = mw.text.trim( str )
         if builtins[name] then return name end
            :gsub( [[^(['"])(.-)%1$]], '%2' )
 
         if builtins[name] then
            return name
        end
     end
     end
     local module = formatPageName(str)
 
     if not module:find('^[Mm]odule:') then
     local module = formatPageName( str )
 
     if not string.find( module, '^[Mm]odule?:' ) then
         module = NS_MODULE_NAME .. ':' .. module
         module = NS_MODULE_NAME .. ':' .. module
     end
     end
     return module
     return module
end
end


local function isDynamicPath(str)
    return str:find('%.%.') or str:find('%%%a')
end


local function multiGmatch(str, ...)
local function dualGmatch( str, pat1, pat2 )
     local generators = {}
     local f1 = string.gmatch( str, pat1 )
    for i, pat in ipairs({...}) do
     if pat2 then
        generators[i] = string.gmatch(str, pat)
         local f2 = string.gmatch( str, pat2 )
     end
         return function ()
    local function nextCaptures()
             return f1() or f2()
         local captures = {generators[1]()}
         if #captures > 0 then
            return unpack(captures)
        elseif #generators > 1 then
             table.remove(generators, 1)
            return nextCaptures()
         end
         end
    else
        return f1
     end
     end
    return nextCaptures
end
end


-- ============================================================
local function isDynamicPath( str )
-- Dynamic require list (DPL wildcard queries)
    return string.find( str, '%.%.' ) or string.find( str, '%%%a' )
-- ============================================================
end


local function getDynamicRequireList(query)
 
     if query:find('%.%.') then
---@param query string
         query = mw.text.split(query, '..', true)
---@return string[]
         query = arr.map(query, function(x) return (x:match('^%s*[\'\"](.-)[\'\"]%s*$') or '%') end)
local function getDynamicRequireList( query )
         query = table.concat(query)
     if query:find( '%.%.' ) then
         query = mw.text.split( query, '..', true )
        query = arr.map( query, function ( x ) return mw.text.trim( x ) end )
         query = arr.map( query, function ( x ) return (x:match( '^[\'\"](.-)[\'\"]$' ) or '%') end )
         query = table.concat( query )
     else
     else
         local _, _query = query:match('(["\'])(.-)%1')
         local _, _query = query:match( '(["\'])(.-)%1' )
         query = _query:gsub('%%%a', '%%')
         query = _query:gsub( '%%%a', '%%' )
     end
     end
     query = query:gsub('^[Mm]odule:', '')
     query = query:gsub( '^[Mm]odule:', '' )
    query = mw.language.getContentLanguage():ucfirst(query)


     if dynamicRequireListQueryCache[query] then
     if dynamicRequireListQueryCache[query] then
Line 121: Line 139:
     end
     end


     local list = dpl.ask{
     local list = {}
        namespace = NS_MODULE_NAME,
 
        titlematch = query,
    if QUERY_MODE == 'dpl' then
        nottitlematch = '%/doc|' .. query .. '/%',
        list = dpl.ask( {
        distinct = 'strict',
            namespace = NS_MODULE_NAME,
        ordermethod = 'title',
            titlematch = query,
        count = MAX_DYNAMIC_REQUIRE_LIST_LENGTH + 1,
            nottitlematch = '%/doc|' .. query .. '/%',
        skipthispage = 'no',
            distinct = 'strict',
        allowcachedresults = true,
            ignorecase = true,
        cacheperiod = 604800,
            ordermethod = 'title',
     }
            count = MAX_DYNAMIC_REQUIRE_LIST_LENGTH + 1,
            skipthispage = 'no',
            allowcachedresults = true,
            cacheperiod = 604800
        } )
     end


     if #list > MAX_DYNAMIC_REQUIRE_LIST_LENGTH then
     if #list > MAX_DYNAMIC_REQUIRE_LIST_LENGTH then
         list = {'Module:' .. query}
         list = { 'Module:' .. query }
     end
     end


     dynamicRequireListQueryCache[query] = list
     dynamicRequireListQueryCache[query] = list
     return list
     return list
end
end


-- ============================================================
-- Require / loadData list parsing
-- ============================================================


local function getRequireLists(moduleContent)
---@param moduleName string
     local requireList = arr{}
---@param searchForUsedTemplates boolean|nil
     local loadDataList = arr{}
---@return table<string, string[]>
     local extraCategories = arr{}
local function getRequireList( moduleName, searchForUsedTemplates )
    local content = mw.title.new( moduleName ):getContent()
     local requireList = arr {}
     local loadDataList = arr {}
    local loadJsonDataList = arr {}
    local usedTemplateList = arr {}
    local dynamicRequirelist = arr {}
    local dynamicLoadDataList = arr {}
    local dynamicLoadJsonDataList = arr {}
     local extraCategories = arr {}


     local function getList(list, patterns)
    if content == nil then
         for match in multiGmatch(moduleContent, unpack(patterns)) do
        return {
             match = mw.text.trim(match)
            requireList = requireList,
             local name = extractModuleName(match, moduleContent)
            loadDataList = loadDataList,
             if isDynamicPath(name) then
            loadJsonDataList = loadJsonDataList,
                 list:insert(getDynamicRequireList(name), true)
            usedTemplateList = usedTemplateList,
            extraCategories = extraCategories
        }
    end
 
    content = content:gsub( '%-%-%[(=-)%[.-%]%1%]', '' ):gsub( '%-%-[^\n]*', '' )
 
     local function getList( pat1, pat2, list, dynList )
         for match in dualGmatch( content, pat1, pat2 ) do
             match = mw.text.trim( match )
             local name = extractModuleName( match, content )
 
             if isDynamicPath( name ) then
                 dynList:insert( getDynamicRequireList( name ), true )
             elseif name ~= '' then
             elseif name ~= '' then
                 name = formatModuleName(name, true)
                 name = formatModuleName( name, true )
                 table.insert(list, name)
                 table.insert( list, name )
 
                 if builtins[name] then
                 if builtins[name] then
                     extraCategories = extraCategories:insert(builtins[name].categories, true)
                     extraCategories = extraCategories:insert( builtins[name].categories, true )
                 end
                 end
             end
             end
Line 166: Line 210:
     end
     end


     getList(requireList, {
     getList( 'require%s*(%b())', 'require%s*((["\'])%s*[Mm]odule:.-%2)', requireList, dynamicRequirelist )
        'require%s*(%b())',
    getList( 'mw%.loadData%s*(%b())', 'mw%.loadData%s*((["\'])%s*[Mm]odule:.-%2)', loadDataList, dynamicLoadDataList )
        'require%s*((["\'])%s*[Mm]odule:.-%2)',
     getList( 'mw%.loadJsonData%s*(%b())', 'mw%.loadJsonData%s*((["\'])%s*[Mm]odule:.-%2)', loadJsonDataList, dynamicLoadJsonDataList )
        'pcall%s*%(%s*require%s*,([^%),]+)',
    getList( 'pcall%s*%(%s*require%s*,([^%),]+)', nil, requireList, dynamicRequirelist )
    })
    getList( 'pcall%s*%(%s*mw%.loadData%s*,([^%),]+)', nil, loadDataList, dynamicLoadDataList )
     getList(loadDataList, {
    getList( 'pcall%s*%(%s*mw%.loadJsonData%s*,([^%),]+)', nil, loadJsonDataList, dynamicLoadJsonDataList )
        'mw%.loadData%s*(%b())',
        'mw%.loadData%s*((["\'])%s*[Mm]odule:.-%2)',
        'pcall%s*%(%s*mw%.loadData%s*,([^%),]+)',
        'mw%.loadJsonData%s*(%b())',
        'mw%.loadJsonData%s*((["\'])%s*[Mm]odule:.-%2)',
        'pcall%s*%(%s*mw%.loadJsonData%s*,([^%),]+)',
    })


    if searchForUsedTemplates then
        for preprocess in string.gmatch( content, ':preprocess%s*(%b())' ) do
            local function recursiveGMatch( str, pat )
                local list = {}
                local i = 0
                repeat
                    for match in string.gmatch( list[i] or str, pat ) do
                        table.insert( list, match )
                    end
                    i = i + 1
                until i > #list or i > 100
                i = 0
                return function ()
                    i = i + 1
                    return list[i]
                end
            end
            for template in recursiveGMatch( preprocess, '{(%b{})}' ) do
                local name = string.match( template, '{(.-)[|{}]' )
                if name ~= '' then
                    if name:find( ':' ) then
                        local ns = name:match( '^(.-):' )
                        if arr.contains( { '', 'template', 'user' }, ns:lower() ) then
                            table.insert( usedTemplateList, name )
                        elseif ns == ns:upper() then
                            table.insert( usedTemplateList, ns )
                        end
                    else
                        if name:match( '^%u+$' ) or name == '!' then
                            table.insert( usedTemplateList, name )
                        else
                            table.insert( usedTemplateList, 'Template:' .. name )
                        end
                    end
                end
            end
        end
    end
    requireList = requireList .. dynamicRequirelist
     requireList = requireList:unique()
     requireList = requireList:unique()
    loadDataList = loadDataList .. dynamicLoadDataList
     loadDataList = loadDataList:unique()
     loadDataList = loadDataList:unique()
    loadJsonDataList = loadJsonDataList .. dynamicLoadJsonDataList
    loadJsonDataList = loadJsonDataList:unique()
    usedTemplateList = usedTemplateList:unique()
     extraCategories = extraCategories:unique()
     extraCategories = extraCategories:unique()
    table.sort(requireList)
     table.sort( extraCategories )
    table.sort(loadDataList)
     table.sort(extraCategories)


     return {require = requireList, loadData = loadDataList, extraCategories = extraCategories}
     return {
        requireList = requireList,
        loadDataList = loadDataList,
        loadJsonDataList = loadJsonDataList,
        usedTemplateList = usedTemplateList,
        extraCategories = extraCategories
    }
end
end


-- ============================================================
-- TemplateStyles / used-template detection
-- ============================================================


local function insertTemplateStyle(styleName, list)
---@param templateName string
     styleName = formatPageName(styleName)
---@return table<string, string>[]
     if not styleName:find(':') then styleName = 'Template:' .. styleName end
local function getInvokeCallList( templateName )
     if isDynamicPath(styleName) then
     local content = mw.title.new( templateName ):getContent()
         list:insert(getDynamicRequireList(styleName), true)
     local invokeList = {}
    else
 
         list:insert(styleName)
    assert( content ~= nil, 'Page "' .. templateName .. '" does not exist.' )
 
     for moduleName, funcName in string.gmatch( content, '{{[{|safeubt:}]-#[Ii]nvoke:([^|]+)|([^}|]+)[^}]*}}' ) do
         moduleName = formatModuleName( moduleName )
        funcName = mw.text.trim( funcName )
        if string.find( funcName, '^{{{' ) then
            funcName = funcName .. '}}}'
        end
         table.insert( invokeList, { moduleName = moduleName, funcName = funcName } )
     end
     end
    invokeList = arr.unique( invokeList, function ( x ) return x.moduleName .. x.funcName end )
    table.sort( invokeList, function ( x, y ) return x.moduleName .. x.funcName < y.moduleName .. y.funcName end )
    return invokeList
end
end


local function extractTemplateStyles(pageContent, list)
 
     for _, styleName in string.gmatch(
---@return string
        pageContent,
local function messageBoxUnused()
        '<[Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee][Ss][Tt][Yy][Ll][Ee][Ss]%s+[Ss][Rr][Cc]=(["\'])(.-)%1'
     local category = shouldAddCategories and '[[Category:Unused modules]]' or ''
     ) do
 
         styleName = formatPageName(styleName)
     return mbox(
         if styleName ~= '' then insertTemplateStyle(styleName, list) end
        'This module is unused',
     end
         'This module is neither invoked by a template nor required/loaded by another module.',
         { icon = 'WikimediaUI-Alert.svg' }
     ) .. category
end
end


local function recursiveGMatch(str, pat)
    local list = {}
    local i = 0
    repeat
        for match in string.gmatch(list[i] or str, pat) do
            table.insert(list, match)
        end
        i = i + 1
    until i > #list or i > 100
    i = 0
    return function()
        i = i + 1
        return list[i]
    end
end


local function formatTemplate(name)
---@param pageName string
     if name:find(':') then
---@param list table
        local ns = name:match('^(.-):')
---@param listType string
         if arr.contains({'', 'template', 'user'}, ns:lower()) then
---@param message string
             return name
---@return string
        elseif ns == ns:upper() then
local function getDependencyListWikitext( pageName, list, listType, message )
            return ns
     local listLabel = string.format( '%d %s', #list, listType )
         end
    local listContent = mHatlist.andList( list, false )
 
    if #list > COLLAPSE_LIST_LENGTH_THRESHOLD then
         return mbox(
            string.format( message, pageName, listLabel ),
             listContent,
            { icon = 'WikimediaUI-Code.svg' }
         )
     else
     else
         if name:match('^%u+$') or name == '!' then
         return hatnote(
             return name
             string.format( message, pageName, listContent ),
        else
             { icon = 'WikimediaUI-Code.svg' }
             return 'Template:' .. name
         )
         end
     end
     end
end
end


local function getUsedTemplatesList(moduleContent)
    local usedTemplateList = arr{}
    local templateStylesList = arr{}


    for preprocess in string.gmatch(moduleContent, ':preprocess%s*(%b())') do
---@param query string
        for template in recursiveGMatch(preprocess, '{(%b{})}') do
---@return string
            local name = string.match(template, '{(.-)[|{}]')
local function formatDynamicQueryLink( query )
            if name ~= '' then usedTemplateList:insert(formatTemplate(name)) end
    local prefix = query:match( '^([^/]+)' )
    local linkText = query:gsub( '%%', '&lt; ... &gt;' )
 
    query = query:gsub( '^Module?:', '' )
 
    query = query:gsub( '([^/]+)/?', function ( match )
        if match == '%' then
            return '\\/[^\\/]+'
        else
            return '\\/"' .. match .. '"'
         end
         end
        extractTemplateStyles(preprocess, templateStylesList)
     end )
     end


     for capture in string.gmatch(moduleContent, 'expandTemplate%s*%(?%s*{%s*title%s*=%s*((["\'])%s*.-%2)') do
     query = query:gsub( '^\\/', '' )
        local name = formatPageName(capture)
        if name ~= '' then usedTemplateList:insert(formatTemplate(name)) end
    end


     for _, capture in multiGmatch(
     query = string.format(
        moduleContent,
         'intitle:/%s%s/i -intitle:/%s\\/""/i -intitle:doc prefix:"%s"',
         'extensionTag%s*%(%s*'
        query,
            .. '(["\'])[Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee][Ss][Tt][Yy][Ll][Ee][Ss]%1%s*,'
         query:find( '"$' ) and '' or '""',
            .. '.-,'
         query,
            .. '%s*{%s*src%s*=%s*((["\'])%s*.-%3)',
         prefix
         'extensionTag%s*%(?%s*{%s*'
     )
            .. 'name%s*=%s*(["\'])[Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee][Ss][Tt][Yy][Ll][Ee][Ss]%1'
            .. '.-'
            .. 'args%s*=%s*{%s*src%s*=%s*((["\'])%s*.-%3)'
    ) do
         local name = formatPageName(capture)
         if name ~= '' then insertTemplateStyle(name, templateStylesList) end
     end


     usedTemplateList = usedTemplateList:unique()
     return string.format( '<span class="plainlinks">[%s %s]</span>',
    templateStylesList = templateStylesList:unique()
        tostring( mw.uri.fullUrl( 'Special:Search', { search = query } ) ), linkText )
    table.sort(usedTemplateList)
    table.sort(templateStylesList)
 
    return {usedTemplateList = usedTemplateList, templateStylesList = templateStylesList}
end
end


-- ============================================================
-- Template dependency list (invoke + TemplateStyles)
-- ============================================================


local function getTemplateDependencyList(pageName)
---@param currentPageName string
    local pageContent = mw.title.new(pageName):getContent()
---@param pageList table|nil
    local invokeList = {}
---@param pageType string
     local templateStylesList = arr{}
---@param message string
---@param category string|nil
---@return string
local function formatDependencyList( currentPageName, pageList, pageType, message, category )
     local res = {}


     assert(pageContent, string.format('Failed to retrieve text content of page "%s"', pageName))
     if type( pageList ) == 'table' and #pageList > 0 then
        table.sort( pageList )
        table.insert( res, getDependencyListWikitext( currentPageName, pageList, pageType, message ) )


    for moduleName, funcName in string.gmatch(
        if shouldAddCategories and category then
        pageContent,
            table.insert( res, string.format( '[[Category:%s]]', category ) )
        '{{[{|safeubt:}]-#[Ii]nvoke:([^|]+)|([^}|]+)[^}]*}}'
         end
    ) do
        moduleName = formatModuleName(moduleName)
        funcName = mw.text.trim(funcName)
         if funcName:find('^{{{') then funcName = funcName .. '}}}' end
        table.insert(invokeList, {moduleName = moduleName, funcName = funcName})
     end
     end


     extractTemplateStyles(pageContent, templateStylesList)
     return table.concat( res )
end


    invokeList = arr.unique(invokeList, function(x) return x.moduleName .. '#' .. x.funcName end)
    templateStylesList = templateStylesList:unique()
    table.sort(invokeList, function(x, y)
        return (x.moduleName .. '#' .. x.funcName) < (y.moduleName .. '#' .. y.funcName)
    end)
    table.sort(templateStylesList)


    return {invokeList = invokeList, templateStylesList = templateStylesList}
---@param templateName string
end
---@param invokeList table<string, string>[]
---@return string
local function formatInvokeCallList( templateName, invokeList )
    local category = shouldAddCategories and '[[Category:Lua-based templates]]' or ''
    local res = {}


local function getInvokeCallList(pageName)
    for _, item in ipairs( invokeList ) do
    return getTemplateDependencyList(pageName).invokeList
        local msg = string.format(
end
            "'''%s''' invokes function '''%s''' in [[%s]] using [[mw:Special:MyLanguage/Extension:Scribunto|Lua]].",
            templateName, item.funcName, item.moduleName
        )
        table.insert( res, hatnote( msg, { icon = 'WikimediaUI-Code.svg' } ) )
    end


-- ============================================================
    if #invokeList > 0 then
-- DPL-based "what links here" lookups (from RuneScape module)
        table.insert( res, category )
-- ============================================================
    end


local function getWhatLinksHere(pageName, namespace)
     return table.concat( res )
     return dpl.ask{
        namespace = namespace,
        linksto = pageName,
        distinct = 'strict',
        ignorecase = true,
        ordermethod = 'title',
        allowcachedresults = true,
        cacheperiod = 604800,
    }
end
end


local function getInvokedByList(moduleName)
    local whatTemplatesLinkHere = getWhatLinksHere(moduleName, NS_TEMPLATE_NAME)


     local function lcfirst(str)
---@param moduleName string
         return str:gsub('^[Mm]odule:.', string.lower)
---@param whatLinksHere table
---@return string
local function formatInvokedByList( moduleName, whatLinksHere )
     local function lcfirst( str )
         return string.gsub( str, '^[Mm]odule?:.', string.lower )
     end
     end
    local templateData = arr.map( whatLinksHere, function ( x )
        return {
            templateName = x,
            invokeList = getInvokeCallList( x )
        }
    end )
    templateData = arr.filter( templateData, function ( x )
        return arr.any( x.invokeList, function ( y )
            return lcfirst( y.moduleName ) == lcfirst( moduleName )
        end )
    end )


     local invokedByList = {}
     local invokedByList = {}
     for _, templateName in ipairs(whatTemplatesLinkHere) do
 
        local invokeList = getInvokeCallList(templateName)
     for _, template in ipairs( templateData ) do
         for _, invokeData in ipairs(invokeList) do
         for _, invoke in ipairs( template.invokeList ) do
             if lcfirst(invokeData.moduleName) == lcfirst(moduleName) then
             table.insert( invokedByList,
                 table.insert(invokedByList, {templateName = templateName, funcName = invokeData.funcName})
                 string.format( "function '''%s''' invoked by [[%s]]", invoke.funcName, template.templateName )
             end
             )
         end
         end
     end
     end
     return invokedByList
 
    if #invokedByList > 0 then
        moduleIsUsed = true
    end
 
     return formatDependencyList(
        moduleName,
        invokedByList,
        'templates',
        "'''%s''' has functions invoked by %s.",
        'Template invoked modules'
    )
end
end


local function getRequiredByLists(moduleName)
    local whatModulesLinkHere = getWhatLinksHere(moduleName, NS_MODULE_NAME)


     local requiredByList = arr{}
---@param moduleName string
    local loadedByList = arr{}
---@param whatLinksHere table
---@return string
local function formatRequiredByList( moduleName, whatLinksHere )
     local childModuleData = arr.map( whatLinksHere, function ( title )
        local lists = getRequireList( title )
        return {
            name = title,
            requireList = lists.requireList,
            loadDataList = lists.loadDataList .. lists.loadJsonDataList
        }
    end )


     for _, callerName in ipairs(whatModulesLinkHere) do
     local requiredByList = arr.map( childModuleData, function ( item )
        if callerName:lower() ~= moduleName:lower() then
        if arr.any( item.requireList, function ( x ) return x:lower() == moduleName:lower() end ) then
            local lists = getRequireLists(
            if item.name:find( '%%' ) then
                (mw.title.new(callerName):getContent() or '')
                 return formatDynamicQueryLink( item.name )
                    :gsub('%-%-%[(=-)%[.-%]%1%]', '')
            else
                    :gsub('%-%-[^\n]*', '')
                return '[[' .. item.name .. ']]'
            )
            if arr.any(lists.require, function(x) return x:lower() == moduleName:lower() end) then
                 requiredByList:insert(callerName)
             end
             end
            if arr.any(lists.loadData, function(x) return x:lower() == moduleName:lower() end) then
        end
                 loadedByList:insert(callerName)
    end )
 
    local loadedByList = arr.map( childModuleData, function ( item )
        if arr.any( item.loadDataList, function ( x ) return x:lower() == moduleName:lower() end ) then
            if item.name:find( '%%' ) then
                 return formatDynamicQueryLink( item.name )
            else
                return '[[' .. item.name .. ']]'
             end
             end
         end
         end
    end )
    if #requiredByList > 0 or #loadedByList > 0 then
        moduleIsUsed = true
     end
     end


     requiredByList = requiredByList:unique()
     local res = {}
    loadedByList = loadedByList:unique()
    table.sort(requiredByList)
    table.sort(loadedByList)


     return {require = requiredByList, loadData = loadedByList}
     table.insert( res,
end
        formatDependencyList(
            moduleName,
            requiredByList,
            'modules',
            "'''%s''' is required by %s.",
            'Modules required by modules'
        )
    )


-- ============================================================
     table.insert( res,
-- Formatting helpers
        formatDependencyList(
-- ============================================================
            moduleName,
 
            loadedByList,
local function collapseList(list, id, listType)
            'modules',
     local text = string.format('%d %s', #list, listType)
            "'''%s''' is loaded by %s.",
    local button = tooltip._span{name = id, alt = text}
            'Module data'
    list = arr.map(list, function(x) return '\n# ' .. x end)
         )
    local content = tooltip._div{name = id, content = '\n' .. table.concat(list) .. '\n\n'}
    return {tostring(button) .. tostring(content)}
end
 
local function formatDynamicQueryLink(query)
    local prefix = query:match('^([^/]+)')
    local linkText = query:gsub('%%', '&lt; ... &gt;')
    query = query:gsub('^Module?:', '')
    query = query:gsub('([^/]+)/?', function(match)
        if match == '%' then return '\\/[^\\/]+' else return '\\/"' .. match .. '"' end
    end)
    query = query:gsub('^\\/', '')
    query = string.format(
        'intitle:/%s%s/i -intitle:/%s\\/""/i -intitle:doc prefix:"%s"',
         query, query:find('"$') and '' or '""', query, prefix
     )
     )
    return string.format('<span class="plainlinks">[%s %s]</span>',
        tostring(mw.uri.fullUrl('Special:Search', {search = query})), linkText)
end


local function formatModuleLinks(pages)
     return table.concat( res )
     local links = arr{}
    for _, moduleName in ipairs(pages) do
        if moduleName:find('%%') then
            links:insert(formatDynamicQueryLink(moduleName))
        elseif builtins[moduleName] then
            links:insert('[[' .. builtins[moduleName].link .. '|' .. moduleName .. ']]')
        else
            links:insert('[[' .. moduleName .. ']]')
        end
    end
    return links
end
end


local function formatTemplateLinks(pages)
    local links = arr{}
    for _, templateName in ipairs(pages) do
        if templateName:find(':') then
            links:insert('[[' .. templateName .. ']]')
        else
            links:insert("'''&#123;&#123;" .. templateName .. "&#125;&#125;'''")
        end
    end
    return links
end


local function formatTemplateStyleLinks(pages, dynamic)
local function cleanFrom( from )
     local links = arr{}
     from = from or ''
    for _, stylesName in ipairs(pages) do
    local parts = mw.text.split( from, '|', true )
        if dynamic and stylesName:find('%%') then
            links:insert(formatDynamicQueryLink(stylesName))
        else
            links:insert('[[' .. stylesName .. ']]')
        end
    end
    return links
end


local function formatTemplateStylesList(callerName, templateStylesList, forModule)
    if #parts == 2 then
    templateStylesList = formatTemplateStyleLinks(templateStylesList, forModule)
        local name = string.gsub( parts[1], '%[%[:', '' )
    local res = {}
         name = string.gsub( name, '/[Dd]o[ck]u?', '' )
    if #templateStylesList > COLLAPSE_LIST_LENGTH_THRESHOLD then
        return name
         templateStylesList = collapseList(templateStylesList, 'templateStyles', 'styles')
     end
     end
    for _, item in ipairs(templateStylesList) do
        table.insert(res, string.format(
            "<div class='seealso'>'''%s''' uses styles from %s using [[mw:Special:MyLanguage/Help:TemplateStyles|TemplateStyles]].</div>",
            callerName, item
        ))
    end
    return table.concat(res)
end


local function formatInvokeCallList(templateName, invokeList)
     return nil
    local res = {}
    for _, item in ipairs(invokeList) do
        table.insert(res, string.format(
            "<div class='seealso'>'''%s''' invokes function '''%s''' in [[%s]] using [[mw:Special:MyLanguage/Extension:Scribunto|Lua]].</div>",
            templateName, item.funcName, item.moduleName
        ))
    end
     return table.concat(res)
end
end


local function formatInvokedByList(moduleName, invokedByList)
    local items = {}
    for _, invoke in ipairs(invokedByList) do
        table.insert(items, string.format("function '''%s''' is invoked by [[%s]]", invoke.funcName, invoke.templateName))
    end
    table.sort(items)
    local res = {}
    if #items > COLLAPSE_LIST_LENGTH_THRESHOLD then
        table.insert(res, string.format(
            "<div class='seealso'>'''%s''' is invoked by %s.</div>",
            moduleName, collapseList(items, 'invokedBy', 'templates')[1]
        ))
    else
        for _, item in ipairs(items) do
            table.insert(res, string.format(
                "<div class='seealso'>'''%s's''' %s.</div>",
                moduleName, item
            ))
        end
    end
    return table.concat(res)
end


local function formatRequiredByList(moduleName, requiredByLists)
---@param pageName string
     local requiredByList = formatModuleLinks(requiredByLists.require)
---@return table
     local loadedByList = formatModuleLinks(requiredByLists.loadData)
local function getWhatLinksHere( pageName, namespace, options )
     options = options or {}
     local whatLinksHere = {}


     if #requiredByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
     if QUERY_MODE == 'dpl' then
         requiredByList = collapseList(requiredByList, 'requiredBy', 'modules')
         whatLinksHere = dpl.ask( {
    end
            namespace = namespace,
    if #loadedByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
            linksto = pageName,
         loadedByList = collapseList(loadedByList, 'loadedBy', 'modules')
            distinct = 'strict',
            ignorecase = true,
            ordermethod = 'title',
            allowcachedresults = true,
            cacheperiod = 604800
         } )
     end
     end


    local res = {}
     return whatLinksHere
    for _, name in ipairs(requiredByList) do
        table.insert(res, string.format("<div class='seealso'>'''%s''' is required by %s.</div>", moduleName, name))
    end
    for _, name in ipairs(loadedByList) do
        table.insert(res, string.format("<div class='seealso'>'''%s''' is loaded by %s.</div>", moduleName, name))
    end
     return table.concat(res)
end
end


local function formatImportList(currentPageName, moduleList, id, message)
---@param pageName string
    moduleList = formatModuleLinks(moduleList)
---@return table
    if #moduleList > COLLAPSE_LIST_LENGTH_THRESHOLD then
function p.getWhatTemplatesLinkHere( pageName )
        moduleList = collapseList(moduleList, id, 'modules')
     return getWhatLinksHere( pageName, NS_TEMPLATE_NAME )
    end
    local res = arr.map(moduleList, function(moduleName)
        return '<div class="seealso">' .. string.format(message, currentPageName, moduleName) .. '</div>'
    end)
     return table.concat(res)
end
end


local function formatUsedTemplatesList(currentPageName, usedTemplateList)
---@param pageName string
    usedTemplateList = formatTemplateLinks(usedTemplateList)
---@return table
    local res = {}
function p.getWhatModulesLinkHere( pageName )
    if #usedTemplateList > COLLAPSE_LIST_LENGTH_THRESHOLD then
     return getWhatLinksHere( pageName, NS_MODULE_NAME )
        usedTemplateList = collapseList(usedTemplateList, 'usedTemplates', 'templates')
    end
    for _, templateName in ipairs(usedTemplateList) do
        table.insert(res, string.format(
            "<div class='seealso'>'''%s''' transcludes %s using <samp>frame:preprocess()</samp> or <samp>frame:expandTemplate()</samp>.</div>",
            currentPageName, templateName
        ))
    end
     return table.concat(res)
end
end


local function messageBoxUnused()
function p.main( frame )
     local html = mw.html.create('table'):addClass('messagebox obsolete plainlinks')
     local args = frame:getParent().args
     html:tag('td')
     return p._main( args[1], args.category, args.isUsed )
        :attr('width', '40px')
        :wikitext('[[File:WikimediaUI-Alert.svg|center|30px|link=]]')
        :done()
        :tag('td')
        :wikitext("'''This module is unused.'''")
        :tag('div')
            :css{['font-size'] = '0.85em', ['line-height'] = '1.45em'}
            :wikitext('This module is neither invoked by a template nor required/loaded by another module.')
        :done()
    :done()
    return tostring(html)
end
end


-- ============================================================
---@param currentPageName string|nil
-- Main entry points
---@param addCategories boolean|string|nil
-- ============================================================
---@param isUsed boolean|string|nil
---@return string
function p._main( currentPageName, addCategories, isUsed )
    libraryUtil.checkType( 'Module:DependencyList._main', 1, currentPageName, 'string', true )
    libraryUtil.checkTypeMulti( 'Module:DependencyList._main', 2, addCategories, { 'boolean', 'string', 'nil' } )
    libraryUtil.checkTypeMulti( 'Module:DependencyList._main', 3, isUsed, { 'boolean', 'string', 'nil' } )


local function templateDependencyList(currentPageName, addCategories)
     local title = mw.title.getCurrentTitle()
     local dependencyList = getTemplateDependencyList(currentPageName)
    local res = arr{}


     res:insert(formatInvokeCallList(currentPageName, dependencyList.invokeList))
     if param.is_empty( currentPageName ) and
    res:insert(formatTemplateStylesList(currentPageName, dependencyList.templateStylesList))
        ( not arr.contains( { NS_MODULE_NAME, NS_TEMPLATE_NAME }, title.nsText ) ) then
 
         return ''
    if addCategories then
         if #dependencyList.templateStylesList > 0 then
            res:insert('[[Category:Templates using TemplateStyles]]')
        end
        if #dependencyList.invokeList > 0 then
            res:insert('[[Category:Lua-based templates]]')
        end
     end
     end


     return table.concat(res)
     currentPageName = param.default_to( currentPageName, title.fullText )
end
    currentPageName = string.gsub( currentPageName, '/[Dd]o[ck]u?$', '' )
    currentPageName = formatPageName( currentPageName )
    moduleIsUsed = yn( param.default_to( isUsed, false ) )
    shouldAddCategories = yn( param.default_to( addCategories, title.subpageText ~= 'doc' ) )


local function moduleDependencyList(currentPageName, addCategories, isUsed)
     if title.text:lower():find( 'sandbox' ) or title.text:lower():find( 'testcases' ) then
     local moduleContent = mw.title.new(currentPageName):getContent()
        moduleIsUsed = true
    assert(moduleContent, string.format('Failed to retrieve text content of page "%s"', currentPageName))
    end
    moduleContent = moduleContent:gsub('%-%-%[(=-)%[.-%]%1%]', ''):gsub('%-%-[^\n]*', '')


     local requireLists = getRequireLists(moduleContent)
     if QUERY_MODE == 'dpl' then
    local usedTemplateList = getUsedTemplatesList(moduleContent)
        dpl = require( 'Module:DPLlua' )
    local requiredByLists = getRequiredByLists(currentPageName)
     end
     local invokedByList = getInvokedByList(currentPageName)


     local res = arr{}
     if currentPageName:find( '^' .. NS_TEMPLATE_NAME .. ':' ) then
 
         local ok, invokeList = pcall( getInvokeCallList, currentPageName )
    res:insert(formatInvokedByList(currentPageName, invokedByList))
         if ok then
    res:insert(formatImportList(currentPageName, requireLists.require, 'require', "'''%s''' requires %s."))
            return formatInvokeCallList( currentPageName, invokeList )
    res:insert(formatImportList(currentPageName, requireLists.loadData, 'loadData', "'''%s''' loads data from %s."))
         else
    res:insert(formatUsedTemplatesList(currentPageName, usedTemplateList.usedTemplateList))
            return userError( invokeList )
    res:insert(formatTemplateStylesList(currentPageName, usedTemplateList.templateStylesList, true))
         end
    res:insert(formatRequiredByList(currentPageName, requiredByLists))
 
    if addCategories then
         res:insert(requireLists.extraCategories, true)
         if #usedTemplateList.templateStylesList > 0 then res:insert('[[Category:Modules using TemplateStyles]]') end
        if #requireLists.require > 0 then res:insert('[[Category:Modules requiring modules]]') end
        if #requireLists.loadData > 0 then res:insert('[[Category:Modules using data]]') end
         if #requiredByLists.require > 0 then res:insert('[[Category:Modules required by modules]]') end
        if #requiredByLists.loadData > 0 then res:insert('[[Category:Module data]]') end
         if #invokedByList > 0 then res:insert('[[Category:Template invoked modules]]') end
     end
     end


     if not (
     local ok, lists = pcall( getRequireList, currentPageName, true )
        yn(isUsed)
     if not ok then
        or currentPageName:lower():find('sandbox')
         return userError( lists )
        or #requiredByLists.require > 0
        or #requiredByLists.loadData > 0
        or #invokedByList > 0
     ) then
         table.insert(res, 1, messageBoxUnused())
        if addCategories then res:insert('[[Category:Unused modules]]') end
     end
     end


     return table.concat(res)
     local requireList = arr.map( lists.requireList, function ( moduleName )
end
        if moduleName:find( '%%' ) then
            return formatDynamicQueryLink( moduleName )
        elseif builtins[moduleName] then
            return '[[' .. builtins[moduleName].link .. '|' .. moduleName .. ']]'
        else
            return '[[' .. moduleName .. ']]'
        end
    end )


function p.main(frame)
    local loadDataList = arr.map( lists.loadDataList, function ( moduleName )
    local args = frame:getParent().args
        if moduleName:find( '%%' ) then
    return p._main(args[1], args.category, args.isUsed)
            return formatDynamicQueryLink( moduleName )
end
        else
            return '[[' .. moduleName .. ']]'
        end
    end )


function p._main(currentPageName, addCategories, isUsed)
    local loadJsonDataList = arr.map( lists.loadJsonDataList, function ( moduleName )
    libraryUtil.checkType('Module:DependencyList._main', 1, currentPageName, 'string', true)
        if moduleName:find( '%%' ) then
    libraryUtil.checkTypeMulti('Module:DependencyList._main', 2, addCategories, {'boolean', 'string', 'nil'})
            return formatDynamicQueryLink( moduleName )
     libraryUtil.checkTypeMulti('Module:DependencyList._main', 3, isUsed, {'boolean', 'string', 'nil'})
        else
            return '[[' .. moduleName .. ']]'
        end
     end )


     local title = mw.title.getCurrentTitle()
     local usedTemplateList = arr.map( lists.usedTemplateList, function ( templateName )
        if string.find( templateName, ':' ) then
            return '[[' .. templateName .. ']]'
        else
            return "'''&#123;&#123;" .. templateName .. "&#125;&#125;'''"
        end
    end )


     if param.is_empty(currentPageName) and
     local res = {}
        not arr.contains({NS_MODULE_NAME, NS_TEMPLATE_NAME}, title.nsText) then
        return ''
    end


     currentPageName = param.default_to(currentPageName, title.fullText)
     table.insert( res, formatInvokedByList( currentPageName, p.getWhatTemplatesLinkHere( currentPageName ) ) )
     currentPageName = currentPageName:gsub('/[Dd]oc$', '')
    table.insert( res, formatDependencyList( currentPageName, requireList, 'modules', "'''%s''' requires %s.", 'Modules requiring modules' ) )
     currentPageName = formatPageName(currentPageName)
     table.insert( res, formatDependencyList( currentPageName, loadDataList, 'modules', "'''%s''' loads data from %s.", 'Modules using data' ) )
    table.insert( res, formatDependencyList( currentPageName, loadJsonDataList, 'modules', "'''%s''' loads data from %s.", 'Modules using data' ) )
    table.insert( res, formatDependencyList( currentPageName, usedTemplateList, 'templates', "'''%s''' transcludes %s.", nil ) )
     table.insert( res, formatRequiredByList( currentPageName, p.getWhatModulesLinkHere( currentPageName ) ) )


     if addCategories == nil then
     if shouldAddCategories then
         addCategories = title.subpageText ~= 'doc'
         local extraCategories = arr.map( lists.extraCategories, function ( categoryName )
            return '[[Category:' .. categoryName .. ']]'
        end )
        table.insert( res, table.concat( extraCategories ) )
     end
     end
    addCategories = yn(addCategories)
    dpl = require('Module:DPLlua')


     if currentPageName:find('^' .. NS_TEMPLATE_NAME .. ':') then
     if not moduleIsUsed then
         return templateDependencyList(currentPageName, addCategories)
         table.insert( res, 1, messageBoxUnused() )
     end
     end


     return moduleDependencyList(currentPageName, addCategories, isUsed)
     return table.concat( res )
end
end


return p
return p
-- </nowiki>

Latest revision as of 17:28, 24 April 2026

Documentation for this module may be created at Module:DependencyList/doc

--- Based on Module:DependencyList from RuneScape Wiki and Star Citizen Wiki
--- @see https://runescape.wiki/w/Module:DependencyList
require( 'strict' )

local p = {}
local libraryUtil = require( 'libraryUtil' )
local arr = require( 'Module:Array' )
local yn = require( 'Module:Yesno' )
local param = require( 'Module:Paramtest' )
local userError = require( 'Module:User error' )
local hatnote = require( 'Module:Hatnote' )._hatnote
local mHatlist = require( 'Module:Hatnote list' )
local mbox = require( 'Module:Mbox' )._mbox

local dpl -- Lazy load DPL

local QUERY_MODE = 'dpl'
local MAX_DYNAMIC_REQUIRE_LIST_LENGTH = 30

local moduleIsUsed = false
local shouldAddCategories = false
local COLLAPSE_LIST_LENGTH_THRESHOLD = 5
local dynamicRequireListQueryCache = {}

local NS_MODULE_NAME = mw.site.namespaces[828].name
local NS_TEMPLATE_NAME = mw.site.namespaces[10].name


local builtins = {
    ['libraryUtil'] = {
        link = 'mw:Special:MyLanguage/Extension:Scribunto/Lua reference manual#libraryUtil',
        categories = {},
    },
    ['strict'] = {
        link = 'mw:Special:MyLanguage/Extension:Scribunto/Lua reference manual#strict',
        categories = { 'Strict mode modules' },
    },
}


---@param content string
---@param varName string
---@return string
local function substVarValue( content, varName )
    local res = content:match( varName .. '%s*=%s*(%b""%s-%.*)' ) or content:match( varName .. "%s*=%s*(%b''%s-%.*)" ) or ''
    if res:find( '^(["\'])[Mm]odule?:[%S]+%1' ) and not res:find( '%.%.' ) and not res:find( '%%%a' ) then
        return mw.text.trim( res )
    else
        return ''
    end
end


---@param capture string
---@param content string
---@return string
local function extractModuleName( capture, content )
    capture = capture:gsub( '^%(%s*(.-)%s*%)$', '%1' )

    if capture:find( '^(["\']).-%1$' ) then
        return capture
    elseif capture:find( '^[%a_][%w_]*$' ) then
        return substVarValue( content, capture )
    end

    return capture
end


---@param str string
---@return string
local function formatPageName( str )
    local name = mw.text.trim( str )
        :gsub( '^([\'\"])(.-)%1$', function ( _, x ) return x end )
        :gsub( '_', ' ' )
        :gsub( '^.', string.upper )
        :gsub( ':.', string.upper )

    return name
end


---@param str string
---@param allowBuiltins? boolean
---@return string
local function formatModuleName( str, allowBuiltins )
    if allowBuiltins then
        local name = mw.text.trim( str )
            :gsub( [[^(['"])(.-)%1$]], '%2' )

        if builtins[name] then
            return name
        end
    end

    local module = formatPageName( str )

    if not string.find( module, '^[Mm]odule?:' ) then
        module = NS_MODULE_NAME .. ':' .. module
    end

    return module
end


local function dualGmatch( str, pat1, pat2 )
    local f1 = string.gmatch( str, pat1 )
    if pat2 then
        local f2 = string.gmatch( str, pat2 )
        return function ()
            return f1() or f2()
        end
    else
        return f1
    end
end

local function isDynamicPath( str )
    return string.find( str, '%.%.' ) or string.find( str, '%%%a' )
end


---@param query string
---@return string[]
local function getDynamicRequireList( query )
    if query:find( '%.%.' ) then
        query = mw.text.split( query, '..', true )
        query = arr.map( query, function ( x ) return mw.text.trim( x ) end )
        query = arr.map( query, function ( x ) return (x:match( '^[\'\"](.-)[\'\"]$' ) or '%') end )
        query = table.concat( query )
    else
        local _, _query = query:match( '(["\'])(.-)%1' )
        query = _query:gsub( '%%%a', '%%' )
    end
    query = query:gsub( '^[Mm]odule:', '' )

    if dynamicRequireListQueryCache[query] then
        return dynamicRequireListQueryCache[query]
    end

    local list = {}

    if QUERY_MODE == 'dpl' then
        list = dpl.ask( {
            namespace = NS_MODULE_NAME,
            titlematch = query,
            nottitlematch = '%/doc|' .. query .. '/%',
            distinct = 'strict',
            ignorecase = true,
            ordermethod = 'title',
            count = MAX_DYNAMIC_REQUIRE_LIST_LENGTH + 1,
            skipthispage = 'no',
            allowcachedresults = true,
            cacheperiod = 604800
        } )
    end

    if #list > MAX_DYNAMIC_REQUIRE_LIST_LENGTH then
        list = { 'Module:' .. query }
    end

    dynamicRequireListQueryCache[query] = list

    return list
end


---@param moduleName string
---@param searchForUsedTemplates boolean|nil
---@return table<string, string[]>
local function getRequireList( moduleName, searchForUsedTemplates )
    local content = mw.title.new( moduleName ):getContent()
    local requireList = arr {}
    local loadDataList = arr {}
    local loadJsonDataList = arr {}
    local usedTemplateList = arr {}
    local dynamicRequirelist = arr {}
    local dynamicLoadDataList = arr {}
    local dynamicLoadJsonDataList = arr {}
    local extraCategories = arr {}

    if content == nil then
        return {
            requireList = requireList,
            loadDataList = loadDataList,
            loadJsonDataList = loadJsonDataList,
            usedTemplateList = usedTemplateList,
            extraCategories = extraCategories
        }
    end

    content = content:gsub( '%-%-%[(=-)%[.-%]%1%]', '' ):gsub( '%-%-[^\n]*', '' )

    local function getList( pat1, pat2, list, dynList )
        for match in dualGmatch( content, pat1, pat2 ) do
            match = mw.text.trim( match )
            local name = extractModuleName( match, content )

            if isDynamicPath( name ) then
                dynList:insert( getDynamicRequireList( name ), true )
            elseif name ~= '' then
                name = formatModuleName( name, true )
                table.insert( list, name )

                if builtins[name] then
                    extraCategories = extraCategories:insert( builtins[name].categories, true )
                end
            end
        end
    end

    getList( 'require%s*(%b())', 'require%s*((["\'])%s*[Mm]odule:.-%2)', requireList, dynamicRequirelist )
    getList( 'mw%.loadData%s*(%b())', 'mw%.loadData%s*((["\'])%s*[Mm]odule:.-%2)', loadDataList, dynamicLoadDataList )
    getList( 'mw%.loadJsonData%s*(%b())', 'mw%.loadJsonData%s*((["\'])%s*[Mm]odule:.-%2)', loadJsonDataList, dynamicLoadJsonDataList )
    getList( 'pcall%s*%(%s*require%s*,([^%),]+)', nil, requireList, dynamicRequirelist )
    getList( 'pcall%s*%(%s*mw%.loadData%s*,([^%),]+)', nil, loadDataList, dynamicLoadDataList )
    getList( 'pcall%s*%(%s*mw%.loadJsonData%s*,([^%),]+)', nil, loadJsonDataList, dynamicLoadJsonDataList )

    if searchForUsedTemplates then
        for preprocess in string.gmatch( content, ':preprocess%s*(%b())' ) do
            local function recursiveGMatch( str, pat )
                local list = {}
                local i = 0

                repeat
                    for match in string.gmatch( list[i] or str, pat ) do
                        table.insert( list, match )
                    end
                    i = i + 1
                until i > #list or i > 100

                i = 0
                return function ()
                    i = i + 1
                    return list[i]
                end
            end

            for template in recursiveGMatch( preprocess, '{(%b{})}' ) do
                local name = string.match( template, '{(.-)[|{}]' )
                if name ~= '' then
                    if name:find( ':' ) then
                        local ns = name:match( '^(.-):' )
                        if arr.contains( { '', 'template', 'user' }, ns:lower() ) then
                            table.insert( usedTemplateList, name )
                        elseif ns == ns:upper() then
                            table.insert( usedTemplateList, ns )
                        end
                    else
                        if name:match( '^%u+$' ) or name == '!' then
                            table.insert( usedTemplateList, name )
                        else
                            table.insert( usedTemplateList, 'Template:' .. name )
                        end
                    end
                end
            end
        end
    end

    requireList = requireList .. dynamicRequirelist
    requireList = requireList:unique()
    loadDataList = loadDataList .. dynamicLoadDataList
    loadDataList = loadDataList:unique()
    loadJsonDataList = loadJsonDataList .. dynamicLoadJsonDataList
    loadJsonDataList = loadJsonDataList:unique()
    usedTemplateList = usedTemplateList:unique()
    extraCategories = extraCategories:unique()
    table.sort( extraCategories )

    return {
        requireList = requireList,
        loadDataList = loadDataList,
        loadJsonDataList = loadJsonDataList,
        usedTemplateList = usedTemplateList,
        extraCategories = extraCategories
    }
end


---@param templateName string
---@return table<string, string>[]
local function getInvokeCallList( templateName )
    local content = mw.title.new( templateName ):getContent()
    local invokeList = {}

    assert( content ~= nil, 'Page "' .. templateName .. '" does not exist.' )

    for moduleName, funcName in string.gmatch( content, '{{[{|safeubt:}]-#[Ii]nvoke:([^|]+)|([^}|]+)[^}]*}}' ) do
        moduleName = formatModuleName( moduleName )
        funcName = mw.text.trim( funcName )
        if string.find( funcName, '^{{{' ) then
            funcName = funcName .. '}}}'
        end
        table.insert( invokeList, { moduleName = moduleName, funcName = funcName } )
    end

    invokeList = arr.unique( invokeList, function ( x ) return x.moduleName .. x.funcName end )
    table.sort( invokeList, function ( x, y ) return x.moduleName .. x.funcName < y.moduleName .. y.funcName end )

    return invokeList
end


---@return string
local function messageBoxUnused()
    local category = shouldAddCategories and '[[Category:Unused modules]]' or ''

    return mbox(
        'This module is unused',
        'This module is neither invoked by a template nor required/loaded by another module.',
        { icon = 'WikimediaUI-Alert.svg' }
    ) .. category
end


---@param pageName string
---@param list table
---@param listType string
---@param message string
---@return string
local function getDependencyListWikitext( pageName, list, listType, message )
    local listLabel = string.format( '%d %s', #list, listType )
    local listContent = mHatlist.andList( list, false )

    if #list > COLLAPSE_LIST_LENGTH_THRESHOLD then
        return mbox(
            string.format( message, pageName, listLabel ),
            listContent,
            { icon = 'WikimediaUI-Code.svg' }
        )
    else
        return hatnote(
            string.format( message, pageName, listContent ),
            { icon = 'WikimediaUI-Code.svg' }
        )
    end
end


---@param query string
---@return string
local function formatDynamicQueryLink( query )
    local prefix = query:match( '^([^/]+)' )
    local linkText = query:gsub( '%%', '&lt; ... &gt;' )

    query = query:gsub( '^Module?:', '' )

    query = query:gsub( '([^/]+)/?', function ( match )
        if match == '%' then
            return '\\/[^\\/]+'
        else
            return '\\/"' .. match .. '"'
        end
    end )

    query = query:gsub( '^\\/', '' )

    query = string.format(
        'intitle:/%s%s/i -intitle:/%s\\/""/i -intitle:doc prefix:"%s"',
        query,
        query:find( '"$' ) and '' or '""',
        query,
        prefix
    )

    return string.format( '<span class="plainlinks">[%s %s]</span>',
        tostring( mw.uri.fullUrl( 'Special:Search', { search = query } ) ), linkText )
end


---@param currentPageName string
---@param pageList table|nil
---@param pageType string
---@param message string
---@param category string|nil
---@return string
local function formatDependencyList( currentPageName, pageList, pageType, message, category )
    local res = {}

    if type( pageList ) == 'table' and #pageList > 0 then
        table.sort( pageList )
        table.insert( res, getDependencyListWikitext( currentPageName, pageList, pageType, message ) )

        if shouldAddCategories and category then
            table.insert( res, string.format( '[[Category:%s]]', category ) )
        end
    end

    return table.concat( res )
end


---@param templateName string
---@param invokeList table<string, string>[]
---@return string
local function formatInvokeCallList( templateName, invokeList )
    local category = shouldAddCategories and '[[Category:Lua-based templates]]' or ''
    local res = {}

    for _, item in ipairs( invokeList ) do
        local msg = string.format(
            "'''%s''' invokes function '''%s''' in [[%s]] using [[mw:Special:MyLanguage/Extension:Scribunto|Lua]].",
            templateName, item.funcName, item.moduleName
        )
        table.insert( res, hatnote( msg, { icon = 'WikimediaUI-Code.svg' } ) )
    end

    if #invokeList > 0 then
        table.insert( res, category )
    end

    return table.concat( res )
end


---@param moduleName string
---@param whatLinksHere table
---@return string
local function formatInvokedByList( moduleName, whatLinksHere )
    local function lcfirst( str )
        return string.gsub( str, '^[Mm]odule?:.', string.lower )
    end

    local templateData = arr.map( whatLinksHere, function ( x )
        return {
            templateName = x,
            invokeList = getInvokeCallList( x )
        }
    end )
    templateData = arr.filter( templateData, function ( x )
        return arr.any( x.invokeList, function ( y )
            return lcfirst( y.moduleName ) == lcfirst( moduleName )
        end )
    end )

    local invokedByList = {}

    for _, template in ipairs( templateData ) do
        for _, invoke in ipairs( template.invokeList ) do
            table.insert( invokedByList,
                string.format( "function '''%s''' invoked by [[%s]]", invoke.funcName, template.templateName )
            )
        end
    end

    if #invokedByList > 0 then
        moduleIsUsed = true
    end

    return formatDependencyList(
        moduleName,
        invokedByList,
        'templates',
        "'''%s''' has functions invoked by %s.",
        'Template invoked modules'
    )
end


---@param moduleName string
---@param whatLinksHere table
---@return string
local function formatRequiredByList( moduleName, whatLinksHere )
    local childModuleData = arr.map( whatLinksHere, function ( title )
        local lists = getRequireList( title )
        return {
            name = title,
            requireList = lists.requireList,
            loadDataList = lists.loadDataList .. lists.loadJsonDataList
        }
    end )

    local requiredByList = arr.map( childModuleData, function ( item )
        if arr.any( item.requireList, function ( x ) return x:lower() == moduleName:lower() end ) then
            if item.name:find( '%%' ) then
                return formatDynamicQueryLink( item.name )
            else
                return '[[' .. item.name .. ']]'
            end
        end
    end )

    local loadedByList = arr.map( childModuleData, function ( item )
        if arr.any( item.loadDataList, function ( x ) return x:lower() == moduleName:lower() end ) then
            if item.name:find( '%%' ) then
                return formatDynamicQueryLink( item.name )
            else
                return '[[' .. item.name .. ']]'
            end
        end
    end )

    if #requiredByList > 0 or #loadedByList > 0 then
        moduleIsUsed = true
    end

    local res = {}

    table.insert( res,
        formatDependencyList(
            moduleName,
            requiredByList,
            'modules',
            "'''%s''' is required by %s.",
            'Modules required by modules'
        )
    )

    table.insert( res,
        formatDependencyList(
            moduleName,
            loadedByList,
            'modules',
            "'''%s''' is loaded by %s.",
            'Module data'
        )
    )

    return table.concat( res )
end


local function cleanFrom( from )
    from = from or ''
    local parts = mw.text.split( from, '|', true )

    if #parts == 2 then
        local name = string.gsub( parts[1], '%[%[:', '' )
        name = string.gsub( name, '/[Dd]o[ck]u?', '' )
        return name
    end

    return nil
end


---@param pageName string
---@return table
local function getWhatLinksHere( pageName, namespace, options )
    options = options or {}
    local whatLinksHere = {}

    if QUERY_MODE == 'dpl' then
        whatLinksHere = dpl.ask( {
            namespace = namespace,
            linksto = pageName,
            distinct = 'strict',
            ignorecase = true,
            ordermethod = 'title',
            allowcachedresults = true,
            cacheperiod = 604800
        } )
    end

    return whatLinksHere
end

---@param pageName string
---@return table
function p.getWhatTemplatesLinkHere( pageName )
    return getWhatLinksHere( pageName, NS_TEMPLATE_NAME )
end

---@param pageName string
---@return table
function p.getWhatModulesLinkHere( pageName )
    return getWhatLinksHere( pageName, NS_MODULE_NAME )
end

function p.main( frame )
    local args = frame:getParent().args
    return p._main( args[1], args.category, args.isUsed )
end

---@param currentPageName string|nil
---@param addCategories boolean|string|nil
---@param isUsed boolean|string|nil
---@return string
function p._main( currentPageName, addCategories, isUsed )
    libraryUtil.checkType( 'Module:DependencyList._main', 1, currentPageName, 'string', true )
    libraryUtil.checkTypeMulti( 'Module:DependencyList._main', 2, addCategories, { 'boolean', 'string', 'nil' } )
    libraryUtil.checkTypeMulti( 'Module:DependencyList._main', 3, isUsed, { 'boolean', 'string', 'nil' } )

    local title = mw.title.getCurrentTitle()

    if param.is_empty( currentPageName ) and
        ( not arr.contains( { NS_MODULE_NAME, NS_TEMPLATE_NAME }, title.nsText ) ) then
        return ''
    end

    currentPageName = param.default_to( currentPageName, title.fullText )
    currentPageName = string.gsub( currentPageName, '/[Dd]o[ck]u?$', '' )
    currentPageName = formatPageName( currentPageName )
    moduleIsUsed = yn( param.default_to( isUsed, false ) )
    shouldAddCategories = yn( param.default_to( addCategories, title.subpageText ~= 'doc' ) )

    if title.text:lower():find( 'sandbox' ) or title.text:lower():find( 'testcases' ) then
        moduleIsUsed = true
    end

    if QUERY_MODE == 'dpl' then
        dpl = require( 'Module:DPLlua' )
    end

    if currentPageName:find( '^' .. NS_TEMPLATE_NAME .. ':' ) then
        local ok, invokeList = pcall( getInvokeCallList, currentPageName )
        if ok then
            return formatInvokeCallList( currentPageName, invokeList )
        else
            return userError( invokeList )
        end
    end

    local ok, lists = pcall( getRequireList, currentPageName, true )
    if not ok then
        return userError( lists )
    end

    local requireList = arr.map( lists.requireList, function ( moduleName )
        if moduleName:find( '%%' ) then
            return formatDynamicQueryLink( moduleName )
        elseif builtins[moduleName] then
            return '[[' .. builtins[moduleName].link .. '|' .. moduleName .. ']]'
        else
            return '[[' .. moduleName .. ']]'
        end
    end )

    local loadDataList = arr.map( lists.loadDataList, function ( moduleName )
        if moduleName:find( '%%' ) then
            return formatDynamicQueryLink( moduleName )
        else
            return '[[' .. moduleName .. ']]'
        end
    end )

    local loadJsonDataList = arr.map( lists.loadJsonDataList, function ( moduleName )
        if moduleName:find( '%%' ) then
            return formatDynamicQueryLink( moduleName )
        else
            return '[[' .. moduleName .. ']]'
        end
    end )

    local usedTemplateList = arr.map( lists.usedTemplateList, function ( templateName )
        if string.find( templateName, ':' ) then
            return '[[' .. templateName .. ']]'
        else
            return "'''&#123;&#123;" .. templateName .. "&#125;&#125;'''"
        end
    end )

    local res = {}

    table.insert( res, formatInvokedByList( currentPageName, p.getWhatTemplatesLinkHere( currentPageName ) ) )
    table.insert( res, formatDependencyList( currentPageName, requireList, 'modules', "'''%s''' requires %s.", 'Modules requiring modules' ) )
    table.insert( res, formatDependencyList( currentPageName, loadDataList, 'modules', "'''%s''' loads data from %s.", 'Modules using data' ) )
    table.insert( res, formatDependencyList( currentPageName, loadJsonDataList, 'modules', "'''%s''' loads data from %s.", 'Modules using data' ) )
    table.insert( res, formatDependencyList( currentPageName, usedTemplateList, 'templates', "'''%s''' transcludes %s.", nil ) )
    table.insert( res, formatRequiredByList( currentPageName, p.getWhatModulesLinkHere( currentPageName ) ) )

    if shouldAddCategories then
        local extraCategories = arr.map( lists.extraCategories, function ( categoryName )
            return '[[Category:' .. categoryName .. ']]'
        end )
        table.insert( res, table.concat( extraCategories ) )
    end

    if not moduleIsUsed then
        table.insert( res, 1, messageBoxUnused() )
    end

    return table.concat( res )
end

return p