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
Created page with "--- Based on Module:DependencyList from RuneScape 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 dpl = require('Module:DPLlua') local tooltip = require('Module:Tooltip') local COLLAPSE_LIST_LENGTH_THRESHOLD = 5 local MAX_DYNAMIC_REQUIRE_LIST_LENGTH = 30 local dynamic..."
 
No edit summary
 
(7 intermediate revisions by the same user not shown)
Line 1: Line 1:
--- Based on Module:DependencyList from RuneScape 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' )


require("strict")
local p = {}
local p = {}
local libraryUtil = require('libraryUtil')
local libraryUtil = require( 'libraryUtil' )
local arr = require('Module:Array')
local arr = require( 'Module:Array' )
local yn = require('Module:Yesno')
local yn = require( 'Module:Yesno' )
local param = require('Module:Paramtest')
local param = require( 'Module:Paramtest' )
local dpl = require('Module:DPLlua')
local userError = require( 'Module:User error' )
local tooltip = require('Module:Tooltip')
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 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_TEMPLATE_NAME = mw.site.namespaces[10].name


local builtins = {
local builtins = {
["libraryUtil"] = {
    ['libraryUtil'] = {
link = "mw:Special:MyLanguage/Extension:Scribunto/Lua reference manual#libraryUtil",
        link = 'mw:Special:MyLanguage/Extension:Scribunto/Lua reference manual#libraryUtil',
categories = {},
        categories = {},
},
    },
["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' },
},
    },
}
}


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


local function extractModuleName( capture, moduleContent )
capture = capture:gsub( '^%(%s*(.-)%s*%)$', '%1' )


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


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


---@param str string
---@return string
local function formatPageName( str )
local function formatPageName( str )
local name = mw.text.trim(str)
    local name = mw.text.trim( str )
:gsub( '^(["\'])(.-)%1$', '%2' ) -- Only remove quotes at start and end of string if both are the same type
        :gsub( '^([\'\"])(.-)%1$', function ( _, x ) return x end )
:gsub( '_', ' ' )
        :gsub( '_', ' ' )
:gsub( '^.', string.upper )
        :gsub( '^.', string.upper )
:gsub( '^([^:]-:)(.)', function(a,b) return a..string.upper(b) end )
        :gsub( ':.', string.upper )


return name
    return name
end
end


---@param str string
---@param allowBuiltins? boolean
---@return string
local function formatModuleName( str, allowBuiltins )
local function formatModuleName( str, allowBuiltins )
if allowBuiltins then
    if allowBuiltins then
local name = mw.text.trim(str)
        local name = mw.text.trim( str )
-- Only remove quotes at start and end of string if both are the same type
            :gsub( [[^(['"])(.-)%1$]], '%2' )
:gsub('^(["\'])(.-)%1$', '%2')


if builtins[name] then
        if builtins[name] then
return name
            return name
end
        end
end
    end


local module = formatPageName( str )
    local module = formatPageName( str )


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


return module
    return module
end
end


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


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


-- Used in case a construct like 'require( "Module:wowee/" .. isTheBest )' is found.
 
-- Will return a list of pages which satisfy this pattern where 'isTheBest' can take any value.
---@param query string
---@return string[]
local function getDynamicRequireList( query )
local function getDynamicRequireList( query )
if query:find( '%.%.' ) then
    if query:find( '%.%.' ) then
query = mw.text.split( query, '..', true )
        query = mw.text.split( query, '..', true )
query = arr.map( query, function(x) return (x:match('^%s*[\'\"](.-)[\'\"]%s*$') or '%') end )
        query = arr.map( query, function ( x ) return mw.text.trim( x ) end )
query = table.concat( query )
        query = arr.map( query, function ( x ) return (x:match( '^[\'\"](.-)[\'\"]$' ) or '%') end )
else
        query = table.concat( query )
local _, _query = query:match( '(["\'])(.-)%1' )
    else
query = _query:gsub( '%%%a', '%%' ) -- Replace lua string.format specifiers with a dpl wildcard
        local _, _query = query:match( '(["\'])(.-)%1' )
end
        query = _query:gsub( '%%%a', '%%' )
query = query:gsub( '^[Mm]odule:', '' )
    end
    query = query:gsub( '^[Mm]odule:', '' )


query = mw.language.getContentLanguage():ucfirst( query )
    if dynamicRequireListQueryCache[query] then
if query:find( '^Exchange/' ) or query:find( '^Data/' ) then
        return dynamicRequireListQueryCache[query]
return { 'Module:' .. query }  -- This format will later be used by formatDynamicQueryLink()
    end
end


if dynamicRequireListQueryCache[ query ] then
    local list = {}
return dynamicRequireListQueryCache[ query ]
end


local list = dpl.ask{
    if QUERY_MODE == 'dpl' then
namespace = 'Module',
        list = dpl.ask( {
titlematch = query,
            namespace = NS_MODULE_NAME,
nottitlematch = '%/doc|'..query..'/%',
            titlematch = query,
distinct = 'strict',
            nottitlematch = '%/doc|' .. query .. '/%',
ordermethod = 'title',
            distinct = 'strict',
count = MAX_DYNAMIC_REQUIRE_LIST_LENGTH + 1,
            ignorecase = true,
skipthispage = 'no',
            ordermethod = 'title',
allowcachedresults = true,
            count = MAX_DYNAMIC_REQUIRE_LIST_LENGTH + 1,
cacheperiod = 604800 -- One week
            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


--- Returns a list of modules loaded and required by module 'moduleName'.
local function getRequireLists( moduleContent )
local requireList = arr{}
local loadDataList = arr{}
local extraCategories = arr{}


local function getList( list, patterns )
---@param moduleName string
for match in multiGmatch( moduleContent, unpack( patterns ) ) do
---@param searchForUsedTemplates boolean|nil
match = mw.text.trim( match )
---@return table<string, string[]>
local name = extractModuleName( match, moduleContent )
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 isDynamicPath( name ) then
    if content == nil then
list:insert( getDynamicRequireList( name ), true )
        return {
elseif name ~= '' then
            requireList = requireList,
name = formatModuleName( name, true )
            loadDataList = loadDataList,
table.insert( list, name )
            loadJsonDataList = loadJsonDataList,
            usedTemplateList = usedTemplateList,
            extraCategories = extraCategories
        }
    end


if builtins[name] then
    content = content:gsub( '%-%-%[(=-)%[.-%]%1%]', '' ):gsub( '%-%-[^\n]*', '' )
extraCategories = extraCategories:insert( builtins[name].categories, true )
end
end
end
end


local requirePatterns = {
    local function getList( pat1, pat2, list, dynList )
'require%s*(%b())',
        for match in dualGmatch( content, pat1, pat2 ) do
'require%s*((["\'])%s*[Mm]odule:.-%2)',
            match = mw.text.trim( match )
'pcall%s*%(%s*require%s*,([^%),]+)'
            local name = extractModuleName( match, content )
}


local loadDataPatterns = {
            if isDynamicPath( name ) then
'mw%.loadData%s*(%b())',
                dynList:insert( getDynamicRequireList( name ), true )
'mw%.loadData%s*((["\'])%s*[Mm]odule:.-%2)',
            elseif name ~= '' then
'pcall%s*%(%s*mw%.loadData%s*,([^%),]+)',
                name = formatModuleName( name, true )
'mw%.loadJsonData%s*(%b())',
                table.insert( list, name )
'mw%.loadJsonData%s*((["\'])%s*[Mm]odule:.-%2)',
'pcall%s*%(%s*mw%.loadJsonData%s*,([^%),]+)'
}


getList( requireList, requirePatterns )
                if builtins[name] then
getList( loadDataList, loadDataPatterns )
                    extraCategories = extraCategories:insert( builtins[name].categories, true )
                end
            end
        end
    end


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


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


local function insertTemplateStyle( styleName, templateStylesList )
                repeat
styleName = formatPageName( styleName )
                    for match in string.gmatch( list[i] or str, pat ) do
if not styleName:find( ':' ) then
                        table.insert( list, match )
styleName = "Template:" .. styleName
                    end
end
                    i = i + 1
if isDynamicPath(styleName) then
                until i > #list or i > 100
templateStylesList:insert( getDynamicRequireList( styleName ), true )
else
templateStylesList:insert( styleName )
end
end


local function extractTemplateStyles( pageContent, templateStylesList )
                i = 0
for _, styleName in string.gmatch( pageContent, '<[Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee][Ss][Tt][Yy][Ll][Ee][Ss]%s+[Ss][Rr][Cc]=(["\'])(.-)%1' ) do
                return function ()
styleName = formatPageName( styleName )
                    i = i + 1
if styleName ~= '' then
                    return list[i]
insertTemplateStyle( styleName, templateStylesList )
                end
end
            end
end
end


local function recursiveGMatch( str, pat )
            for template in recursiveGMatch( preprocess, '{(%b{})}' ) do
local list = {}
                local name = string.match( template, '{(.-)[|{}]' )
local i = 0
                if name ~= '' then
repeat
                    if name:find( ':' ) then
for match in string.gmatch( list[i] or str, pat ) do
                        local ns = name:match( '^(.-):' )
table.insert( list, match )
                        if arr.contains( { '', 'template', 'user' }, ns:lower() ) then
end
                            table.insert( usedTemplateList, name )
i =  i + 1
                        elseif ns == ns:upper() then
until i > #list or i > 100
                            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


i = 0
    requireList = requireList .. dynamicRequirelist
return function()
    requireList = requireList:unique()
i = i + 1
    loadDataList = loadDataList .. dynamicLoadDataList
return list[i]
    loadDataList = loadDataList:unique()
end
    loadJsonDataList = loadJsonDataList .. dynamicLoadJsonDataList
end
    loadJsonDataList = loadJsonDataList:unique()
    usedTemplateList = usedTemplateList:unique()
    extraCategories = extraCategories:unique()
    table.sort( extraCategories )


local function formatTemplate( name )
    return {
if name:find( ':' ) then
        requireList = requireList,
local ns = name:match( '^(.-):' )
        loadDataList = loadDataList,
if arr.contains( {'', 'template', 'calculator', 'user'}, ns:lower() ) then
        loadJsonDataList = loadJsonDataList,
return name
        usedTemplateList = usedTemplateList,
elseif ns == ns:upper() then
        extraCategories = extraCategories
return ns -- Probably a magic word
    }
end
else
if name:match( '^%u+$' ) or name == '!' then
return name -- Probably a magic word
else
return 'Template:'..name
end
end
end
end


local function getUsedTemplatesList( moduleContent )
local usedTemplateList = arr{}
local templateStylesList = arr{}
for preprocess in string.gmatch( moduleContent, ':preprocess%s*(%b())' ) do
for template in recursiveGMatch( preprocess, '{(%b{})}' ) do
local name = string.match( template, '{(.-)[|{}]' )
if name ~= '' then
usedTemplateList:insert( formatTemplate( name ) )
end
end


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


for capture in string.gmatch( moduleContent, 'expandTemplate%s*%(?%s*{%s*title%s*=%s*((["\'])%s*.-%2)' ) do
    assert( content ~= nil, 'Page "' .. templateName .. '" does not exist.' )
local name = formatPageName( capture )
if name ~= '' then
usedTemplateList:insert( formatTemplate( name ) )
end
end


for _, capture in multiGmatch(
    for moduleName, funcName in string.gmatch( content, '{{[{|safeubt:}]-#[Ii]nvoke:([^|]+)|([^}|]+)[^}]*}}' ) do
moduleContent,
        moduleName = formatModuleName( moduleName )
'extensionTag%s*%(%s*'
        funcName = mw.text.trim( funcName )
.. '(["\'])[Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee][Ss][Tt][Yy][Ll][Ee][Ss]%1%s*,'
        if string.find( funcName, '^{{{' ) then
.. '.-,'
             funcName = funcName .. '}}}'
.. '%s*{%s*src%s*=%s*((["\'])%s*.-%3)',
        end
'extensionTag%s*%(?%s*{%s*'
        table.insert( invokeList, { moduleName = moduleName, funcName = funcName } )
            .. 'name%s*=%s*(["\'])[Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee][Ss][Tt][Yy][Ll][Ee][Ss]%1'
    end
            .. '.-'
             .. '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()
    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( usedTemplateList )
table.sort( templateStylesList )


return {
    return invokeList
usedTemplateList = usedTemplateList,
templateStylesList = templateStylesList,
}
end
end


-- Returns all dependencies of the template found on page 'pageName'
local function getTemplateDependencyList( pageName )
local pageContent = mw.title.new( pageName ):getContent()
local invokeList = {}
local templateStylesList = arr{}


assert( pageContent, string.format( 'Failed to retrieve text content of page "%s"', pageName ) )
---@return string
local function messageBoxUnused()
    local category = shouldAddCategories and '[[Category:Unused modules]]' or ''


for moduleName, funcName in string.gmatch( pageContent, '{{[{|safeubt:}]-#[Ii]nvoke:([^|]+)|([^}|]+)[^}]*}}' ) do
    return mbox(
moduleName = formatModuleName( moduleName )
        'This module is unused',
funcName = mw.text.trim( funcName )
        'This module is neither invoked by a template nor required/loaded by another module.',
if string.find( funcName, '^{{{' ) then
        { icon = 'WikimediaUI-Alert.svg' }
funcName = funcName ..  '}}}'
    ) .. category
end
end
table.insert( invokeList, {moduleName=moduleName, funcName=funcName} )
end
 
-- For form calcs invoking the module directly
for config in multiGmatch( pageContent, '<[pd][ri][ev]%s+class%s*=%s*["\']jcConfig["\'](.-)</[pd][ri][ev]>', '{{[Ff]orm calculator%s*|(.+)}}' ) do
local moduleName = string.match( config, 'module%s*=%s*(.-)[\n|]' )
if param.has_content( moduleName ) then
moduleName = formatModuleName( moduleName )
local funcName = string.match( config, 'modulefunc%s*=%s*(.-)[\n|]' ) or 'main'
table.insert( invokeList, {moduleName=moduleName, funcName=funcName} )
end
end
 
extractTemplateStyles( pageContent, templateStylesList )


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 {
---@param pageName string
invokeList = invokeList,
---@param list table
templateStylesList = templateStylesList,
---@param listType string
}
---@param message string
end
---@return string
local function getDependencyListWikitext( pageName, list, listType, message )
    local listLabel = string.format( '%d %s', #list, listType )
    local listContent = mHatlist.andList( list, false )


-- Returns a list with module and function names used in all '{{#Invoke:moduleName|funcName}}' found on page 'templateName'.
    if #list > COLLAPSE_LIST_LENGTH_THRESHOLD then
local function getInvokeCallList( pageName )
        return mbox(
return getTemplateDependencyList( pageName ).invokeList
            string.format( message, pageName, listLabel ),
            listContent,
            { icon = 'WikimediaUI-Code.svg' }
        )
    else
        return hatnote(
            string.format( message, pageName, listContent ),
            { icon = 'WikimediaUI-Code.svg' }
        )
    end
end
end


local function getInvokedByList( moduleName )
local whatTemplatesLinkHere = dpl.ask( {
namespace = 'Template|Calculator',
linksto = moduleName,
distinct = 'strict',
ordermethod = 'title',
allowcachedresults = true,
cacheperiod = 604800 -- One week
} )


local function lcfirst( str )
---@param query string
return string.gsub( str, '^[Mm]odule:.', string.lower )
---@return string
end
local function formatDynamicQueryLink( query )
 
    local prefix = query:match( '^([^/]+)' )
local invokedByList = {}
    local linkText = query:gsub( '%%', '&lt; ... &gt;' )


for _, templateName in ipairs( whatTemplatesLinkHere ) do
    query = query:gsub( '^Module?:', '' )
local invokeList = getInvokeCallList( templateName )


for _, invokeData in ipairs( invokeList ) do
    query = query:gsub( '([^/]+)/?', function ( match )
if lcfirst( invokeData.moduleName ) == lcfirst( moduleName ) then
        if match == '%' then
table.insert( invokedByList, { templateName=templateName, funcName=invokeData.funcName } )
            return '\\/[^\\/]+'
end
        else
end
            return '\\/"' .. match .. '"'
end
        end
 
    end )
return invokedByList
end
 
local function messageBoxUnused()
local html = mw.html.create( 'table' ):addClass( 'messagebox obsolete plainlinks' )
html:tag( 'td' )
:attr( 'width', '40xp' )
:wikitext( '[[File:Iron full helm detail old.png|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. If this is in error, make sure to add <code>{{[[Template:Documentation|Documentation]]}}</code>/<code>{{[[Template:No documentation|No&nbsp;documentation]]}}</code> to the calling template\'s or parent\'s module documentation.' )
:done()
:done()


return tostring( html )
    query = query:gsub( '^\\/', '' )
end


local function collapseList( list, id, listType )
    query = string.format(
local text = string.format( '%d %s', #list, listType )
        'intitle:/%s%s/i -intitle:/%s\\/""/i -intitle:doc prefix:"%s"',
local button = tooltip._span{ name=id, alt=text }
        query,
list = arr.map( list, function(x) return '\n# '..x end )
        query:find( '"$' ) and '' or '""',
local content = tooltip._div{ name=id, content='\n'..table.concat( list )..'\n\n' }
        query,
        prefix
    )


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


-- Creates a link to [[Special:Search]] showing all pages found by getDynamicRequireList() in case it found more than MAX_DYNAMIC_REQUIRE_LIST_LENGTH pages.
-- Input query uses DPL % wildcards like 'Module:Wowee/%' or 'Module:Wowee/%/data'
local function formatDynamicQueryLink( query )
local prefix = query:match( '^([^/]+)' )
local linkText = query:gsub( '%%', '&lt; ... &gt;' )
query = query:gsub( '^Module:',  '' )


query = query:gsub( '([^/]+)/?', function ( match )
---@param currentPageName string
if match == '%' then
---@param pageList table|nil
return '\\/[^\\/]+'
---@param pageType string
else
---@param message string
return '\\/"' .. match .. '"'
---@param category string|nil
end
---@return string
end )
local function formatDependencyList( currentPageName, pageList, pageType, message, category )
    local res = {}


query = query:gsub( '^\\/', '' )
    if type( pageList ) == 'table' and #pageList > 0 then
        table.sort( pageList )
        table.insert( res, getDependencyListWikitext( currentPageName, pageList, pageType, message ) )


query = string.format(
        if shouldAddCategories and category then
'intitle:/%s%s/i -intitle:/%s\\/""/i -intitle:doc prefix:"%s"',
            table.insert( res, string.format( '[[Category:%s]]', category ) )
query,
        end
query:find( '"$' ) and '' or '""',
    end
query,
prefix
)


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


local function formatModuleLinks( pages )
local links = arr{}


for _, moduleName in ipairs(pages) do
---@param templateName string
if moduleName:find( '%%' ) then
---@param invokeList table<string, string>[]
links:insert( formatDynamicQueryLink( moduleName ) )
---@return string
elseif builtins[moduleName] then
local function formatInvokeCallList( templateName, invokeList )
links:insert( '[[' .. builtins[moduleName].link .. '|' .. moduleName .. ']]' )
    local category = shouldAddCategories and '[[Category:Lua-based templates]]' or ''
else
    local res = {}
links:insert( '[[' .. moduleName .. ']]' )
end
end
 
return links
end


local function formatTemplateLinks( pages )
    for _, item in ipairs( invokeList ) do
local links = arr{}
        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


for _, templateName in ipairs(pages) do
    if #invokeList > 0 then
if string.find( templateName, ':' ) then -- Real templates are prefixed by a namespace, magic words are not
        table.insert( res, category )
links:insert( '[['..templateName..']]' )
    end
else
links:insert( "'''&#123;&#123;"..templateName.."&#125;&#125;'''" ) -- Magic words don't have a page so make them bold instead
end
end


return links
    return table.concat( res )
end
end


local function formatTemplateStyleLinks( pages, dynamic )
local links = arr{}


for _, stylesName in ipairs( pages ) do
---@param moduleName string
if dynamic and stylesName:find( '%%' ) then
---@param whatLinksHere table
links:insert( formatDynamicQueryLink( stylesName ) )
---@return string
else
local function formatInvokedByList( moduleName, whatLinksHere )
links:insert( '[[' .. stylesName .. ']]' )
    local function lcfirst( str )
end
        return string.gsub( str, '^[Mm]odule?:.', string.lower )
end
    end


return links
    local templateData = arr.map( whatLinksHere, function ( x )
end
        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 )


--- @param callerName string
    local invokedByList = {}
--- @param templateStylesList string[]
--- @param forModule? boolean
--- @return string
local function formatTemplateStylesList( callerName, templateStylesList, forModule )
templateStylesList = formatTemplateStyleLinks( templateStylesList, forModule )
local res = {}


if #templateStylesList > COLLAPSE_LIST_LENGTH_THRESHOLD then
    for _, template in ipairs( templateData ) do
templateStylesList = collapseList( templateStylesList, 'templateStyles', 'styles' )
        for _, invoke in ipairs( template.invokeList ) do
end
            table.insert( invokedByList,
                string.format( "function '''%s''' invoked by [[%s]]", invoke.funcName, template.templateName )
            )
        end
    end


for _, item in ipairs( templateStylesList ) do
    if #invokedByList > 0 then
table.insert( res, string.format(
        moduleIsUsed = true
"<div class='seealso'>'''%s''' uses styles from %s using [[mw:Special:MyLanguage/Help:TemplateStyles|TemplateStyles]].</div>",
    end
callerName,
item
) )
end


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


local function formatInvokeCallList( templateName, invokeList )
local res = {}


for _, item in ipairs( invokeList ) do
---@param moduleName string
table.insert( res, string.format(
---@param whatLinksHere table
"<div class='seealso'>'''%s''' invokes function '''%s''' in [[%s]] using [[RuneScape:Lua|Lua]].</div>",
---@return string
templateName,
local function formatRequiredByList( moduleName, whatLinksHere )
item.funcName,
    local childModuleData = arr.map( whatLinksHere, function ( title )
item.moduleName
        local lists = getRequireList( title )
) )
        return {
end
            name = title,
            requireList = lists.requireList,
            loadDataList = lists.loadDataList .. lists.loadJsonDataList
        }
    end )


return table.concat( res )
    local requiredByList = arr.map( childModuleData, function ( item )
end
        if arr.any( item.requireList, function ( x ) return x:lower() == moduleName:lower() end ) then
 
            if item.name:find( '%%' ) then
local function formatInvokedByList( moduleName, invokedByList )
                return formatDynamicQueryLink( item.name )
for i, invoke in ipairs( invokedByList ) do
            else
invokedByList[i] = string.format( "function '''%s''' is invoked by [[%s]]", invoke.funcName, invoke.templateName )
                return '[[' .. item.name .. ']]'
end
            end
 
        end
table.sort( invokedByList)
    end )


local res = {}
    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 #invokedByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
    if #requiredByList > 0 or #loadedByList > 0 then
table.insert( res, string.format(
        moduleIsUsed = true
"<div class='seealso'>'''%s''' is invoked by %s.</div>",
    end
moduleName,
collapseList( invokedByList, 'invokedBy', 'templates' )[1]
) )
else
for _, item in ipairs( invokedByList ) do
table.insert( res, string.format(
"<div class='seealso'>'''%s's''' %s.</div>",
moduleName,
item
) )
end
end


return table.concat( res )
    local res = {}
end


local function formatRequiredByList( moduleName, requiredByLists )
    table.insert( res,
local requiredByList = formatModuleLinks( requiredByLists.require )
        formatDependencyList(
local loadedByList = formatModuleLinks( requiredByLists.loadData )
            moduleName,
            requiredByList,
            'modules',
            "'''%s''' is required by %s.",
            'Modules required by modules'
        )
    )


if #requiredByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
    table.insert( res,
requiredByList = collapseList( requiredByList, 'requiredBy', 'modules' )
        formatDependencyList(
end
            moduleName,
            loadedByList,
            'modules',
            "'''%s''' is loaded by %s.",
            'Module data'
        )
    )


if #loadedByList > COLLAPSE_LIST_LENGTH_THRESHOLD then
    return table.concat( res )
loadedByList = collapseList( loadedByList, 'loadedBy', 'modules' )
end
 
local res = {}
 
for _, requiredByModuleName in ipairs( requiredByList ) do
table.insert( res, string.format(
"<div class='seealso'>'''%s''' is required by %s.</div>",
moduleName,
requiredByModuleName
) )
end
 
for _, loadedByModuleName in ipairs( loadedByList ) do
table.insert( res, string.format(
"<div class='seealso'>'''%s''' is loaded by %s.</div>",
moduleName,
loadedByModuleName
) )
end
 
return table.concat( res )
end
end


local function formatImportList( currentPageName, moduleList, id, message )
moduleList = formatModuleLinks( moduleList )


if #moduleList > COLLAPSE_LIST_LENGTH_THRESHOLD then
local function cleanFrom( from )
moduleList = collapseList( moduleList, id, 'modules' )
    from = from or ''
end
    local parts = mw.text.split( from, '|', true )


local res = arr.map( moduleList, function( moduleName )
    if #parts == 2 then
return '<div class="seealso">' .. string.format( message, currentPageName, moduleName ) .. '</div>'
        local name = string.gsub( parts[1], '%[%[:', '' )
end )
        name = string.gsub( name, '/[Dd]o[ck]u?', '' )
        return name
    end


return table.concat( res )
    return nil
end
end


local function formatUsedTemplatesList( currentPageName, usedTemplateList )
usedTemplateList = formatTemplateLinks( usedTemplateList )
local res = {}


if #usedTemplateList > COLLAPSE_LIST_LENGTH_THRESHOLD then
---@param pageName string
usedTemplateList = collapseList( usedTemplateList, 'usedTemplates', 'templates' )
---@return table
end
local function getWhatLinksHere( pageName, namespace, options )
    options = options or {}
    local whatLinksHere = {}


for _, templateName in ipairs( usedTemplateList ) do
    if QUERY_MODE == 'dpl' then
table.insert( res, string.format(
        whatLinksHere = dpl.ask( {
"<div class='seealso'>'''%s''' transcludes %s using <samp>frame:preprocess()</samp> or <samp>frame:expandTemplate()</samp>.</div>",
            namespace = namespace,
currentPageName,
            linksto = pageName,
templateName
            distinct = 'strict',
) )
            ignorecase = true,
end
            ordermethod = 'title',
            allowcachedresults = true,
            cacheperiod = 604800
        } )
    end


return table.concat( res )
    return whatLinksHere
end
end


local function setBucketFields( requireLists )
---@param pageName string
if mw.title.getCurrentTitle().subpageText ~= 'doc' and (#requireLists.require > 0 or #requireLists.loadData > 0) then
---@return table
bucket( 'dependency_list' ).put{
function p.getWhatTemplatesLinkHere( pageName )
require = requireLists.require,
    return getWhatLinksHere( pageName, NS_TEMPLATE_NAME )
load_data = requireLists.loadData
}
end
end
end


local function getRequiredByLists( currentPageName )
---@param pageName string
local requiredByListRaw = bucket( 'dependency_list' ).select( 'page_name' ).where( 'require', currentPageName ).run()
---@return table
local loadedByListRaw = bucket( 'dependency_list' ).select( 'page_name' ).where( 'load_data', currentPageName ).run()
function p.getWhatModulesLinkHere( pageName )
local requiredByList = {}
    return getWhatLinksHere( pageName, NS_MODULE_NAME )
local loadedByList = {}
 
for _, bucketItem in ipairs( requiredByListRaw ) do
table.insert( requiredByList, bucketItem.page_name )
end
for _, bucketItem in ipairs( loadedByListRaw ) do
table.insert( loadedByList, bucketItem.page_name )
end
 
requiredByList = arr.unique( requiredByList )
loadedByList = arr.unique( loadedByList )
table.sort( requiredByList )
table.sort( loadedByList )
 
return {
require = requiredByList,
loadData = loadedByList
}
end
end


local function templateDependencyList( currentPageName, addCategories )
function p.main( frame )
local dependencyList = getTemplateDependencyList( currentPageName )
    local args = frame:getParent().args
local res = arr{}
    return p._main( args[1], args.category, args.isUsed )
 
res:insert( formatInvokeCallList( currentPageName, dependencyList.invokeList ) )
res:insert( formatTemplateStylesList( currentPageName, dependencyList.templateStylesList ) )
 
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
 
return table.concat( res )
end
end


local function moduleDependencyList( currentPageName, addCategories, isUsed )
---@param currentPageName string|nil
local moduleContent = mw.title.new( currentPageName ):getContent()
---@param addCategories boolean|string|nil
assert( moduleContent, string.format( 'Failed to retrieve text content of page "%s"', currentPageName ) )
---@param isUsed boolean|string|nil
moduleContent = moduleContent:gsub( '%-%-%[(=-)%[.-%]%1%]', '' ):gsub( '%-%-[^\n]*', '' ) -- Strip comments
---@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 requireLists = getRequireLists( moduleContent )
    local title = mw.title.getCurrentTitle()
local usedTemplateList = getUsedTemplatesList( moduleContent )
local requiredByLists = getRequiredByLists( currentPageName )
local invokedByList = getInvokedByList( currentPageName )


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


local res = arr{}
    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' ) )


res:insert( formatInvokedByList( currentPageName, invokedByList ) )
    if title.text:lower():find( 'sandbox' ) or title.text:lower():find( 'testcases' ) then
res:insert( formatImportList( currentPageName, requireLists.require, 'require', "'''%s''' requires %s." ) )
        moduleIsUsed = true
res:insert( formatImportList( currentPageName, requireLists.loadData, 'loadData', "'''%s''' loads data from %s." ) )
    end
res:insert( formatUsedTemplatesList( currentPageName, usedTemplateList.usedTemplateList ) )
res:insert( formatTemplateStylesList( currentPageName, usedTemplateList.templateStylesList, true ) )
res:insert( formatRequiredByList( currentPageName, requiredByLists ) )


if addCategories then
    if QUERY_MODE == 'dpl' then
res:insert( requireLists.extraCategories, true )
        dpl = require( 'Module:DPLlua' )
    end


if #usedTemplateList.templateStylesList > 0 then
    if currentPageName:find( '^' .. NS_TEMPLATE_NAME .. ':' ) then
res:insert( '[[Category:Modules using TemplateStyles]]' )
        local ok, invokeList = pcall( getInvokeCallList, currentPageName )
end
        if ok then
if #requireLists.require > 0 then
            return formatInvokeCallList( currentPageName, invokeList )
res:insert( '[[Category:Modules requiring modules]]' )
        else
end
            return userError( invokeList )
if #requireLists.loadData > 0 then
        end
res:insert( '[[Category:Modules using data]]' )
    end
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


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


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


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


function p.main( frame )
    local loadJsonDataList = arr.map( lists.loadJsonDataList, 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 .. ']]'
function p._main( currentPageName, addCategories, isUsed )
        end
libraryUtil.checkType( 'Module:RequireList._main', 1, currentPageName, 'string', true )
    end )
libraryUtil.checkTypeMulti( 'Module:RequireList._main', 2, addCategories, {'boolean', 'string', 'nil'} )
libraryUtil.checkTypeMulti( 'Module:RequireList._main', 3, isUsed, {'boolean', 'string', 'nil'} )


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 )


-- Leave early if not in module, template or calculator namespace or if module is part of exchange or data groups
    local res = {}
if param.is_empty( currentPageName ) and (
( not arr.contains( {'Module', 'Template', 'Calculator'}, title.nsText ) ) or
( title.nsText == 'Module' and ( arr.contains( {'Exchange', 'Exchange historical', 'Data'}, title.text:match( '^(.-)/' ) ) ) )
) then
return ''
end


currentPageName = param.default_to( currentPageName, title.fullText )
    table.insert( res, formatInvokedByList( currentPageName, p.getWhatTemplatesLinkHere( currentPageName ) ) )
currentPageName = string.gsub( currentPageName, '/[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 )
end
            return '[[Category:' .. categoryName .. ']]'
addCategories = yn(addCategories)
        end )
        table.insert( res, table.concat( extraCategories ) )
    end


if currentPageName:find( '^Template:' ) or currentPageName:find( '^Calculator:' ) 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

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