Модуль:Sources: различия между версиями

м
Замена текста — «Википедия:» на «ЭАНМ:»
/>Vlsergey
(Новая страница: «Test»)
м (Замена текста — «Википедия:» на «ЭАНМ:»)
 
(не показано 14 промежуточных версий 7 участников)
Строка 1: Строка 1:
local p = {};
---@alias args table
local u = require('Module:Sources-utils')
---@alias frame { args: args, extensionTag: function, newChild: ( fun( args: args ): frame ) }
---@alias source { publication: source, [string]: any }
---@alias value: string | { id: string }
---@alias snak { datatype: string, snaktype: string, datavalue: { type: string, value: value } }
---@alias snaks table<string, table<number, snak>>
---@alias statement { mainsnak: snak, rank: string, qualifiers: snaks }
---@alias statements table<string, table<number, statement>>
---@alias map { name: string, ids: string[] }[]>


local i18nDefaultLanguage = 'ru';
---@type table
local p = {}


local i18nEtAlDefault = ' et al.';
---@type table<string, string>
local NORMATIVE_DOCUMENTS = {
    Q20754888 = 'Закон Российской Федерации',
    Q20754884 = 'Закон РСФСР',
    Q20873831 = 'Распоряжение Президента Российской Федерации',
    Q20873834 = 'Указ исполняющего обязанности Президента Российской Федерации',
    Q2061228 = 'Указ Президента Российской Федерации',
}
 
---@type table<string, string>
local LANG_CACHE = {
    Q150 = 'fr',
    Q188 = 'de',
    Q1321 = 'es',
    Q1860 = 'en',
    Q652 = 'it',
    Q7737 = 'ru',
    Q8798 = 'uk',
}
 
---@type map
local PROPERTY_MAP = {
    { name = 'sourceId', ids = { 'P248', 'P805' } },
    { name = 'lang', ids = { 'P407', 'P364' } },
    { name = 'author', ids = { 'P50', 'P2093' } },
    { name = 'part', ids = { 'P958', 'P1810' } },
    { name = 'title', ids = { 'P1476' } },
    { name = 'subtitle', ids = { 'P1680' } },
    { name = 'url', ids = { 'P953', 'P1065', 'P854', 'P973', 'P2699', 'P888' } },
    { name = 'editor', ids = { 'P98' } },
    { name = 'translator', ids = { 'P655' } },
    { name = 'publication-id', ids = { 'P1433' } },
    { name = 'edition', ids = { 'P393' } },
    { name = 'publisher', ids = { 'P123' } },
    { name = 'place', ids = { 'P291' } },
    { name = 'volume', ids = { 'P478' } },
    { name = 'issue', ids = { 'P433' } },
    { name = 'dateOfCreation', ids = { 'P571' } },
    { name = 'dateOfPublication', ids = { 'P577' } },
    { name = 'pages', ids = { 'P304' } },
    { name = 'numberOfPages', ids = { 'P1104' } },
    { name = 'tirage', ids = { 'P1092' } },
    { name = 'isbn', ids = { 'P212', 'P957' } },
    { name = 'issn', ids = { 'P236' } },
    -- { name = 'accessdate', ids = { 'P813' } }, -- disable, creates duplicate references
    { name = 'docNumber', ids = { 'P1545' } },
    { name = 'type', ids = { 'P31' } },
    { name = 'arxiv', ids = { 'P818' } },
    { name = 'doi', ids = { 'P356' } },
    { name = 'pmid', ids = { 'P698' } },
}
-- table.insert( PROPERTY_MAP.url, 'P856' ) -- only as qualifier
 
---@type map
local PUBLICATION_PROPERTY_MAP = mw.clone( PROPERTY_MAP )
 
---@type string[]
local monthGen = { 'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря' }
 
---@type string
local i18nDefaultLanguage = mw.language.getContentLanguage():getCode()
p.i18nDefaultLanguage = i18nDefaultLanguage
 
---@type string
local i18nEtAlDefault = ' et al.'
 
---@type table<string, string>
local i18nEtAl = {
local i18nEtAl = {
ru = ' и др.',
    ru = ' и др.',
    uk = ' та ін.',
}
}


---@type table<string, string>
local i18nEditors = {
local i18nEditors = {
fr = '',
    fr = '',
de = 'Hrsg.: ',
    de = 'Hrsg.: ',
es = '',
    es = '',
en = '',
    en = '',
it = '',
    it = '',
ru = 'под ред. ',
    ru = 'под ред. ',
    uk = 'за ред. ',
}
 
---@type table<string, string>
local i18nTranslators = {
    fr = '',
    de = '',
    es = '',
    en = '',
    it = '',
    ru = 'пер. ',
    uk = 'пер. ',
}
}


---@type table<string, string>
local i18nVolume = {
local i18nVolume = {
fr = 'Vol.',
    de  = 'Vol.',
es = 'Vol.',
    fr = 'Vol.',
en = 'Vol.',
    es = 'Vol.',
it = 'Vol.',
    en = 'Vol.',
ru = 'Т.',
    it = 'Vol.',
    ru = 'Т.',
    uk = 'Т.',
}
}
---@type table<string, string>
local i18nIssue = {
local i18nIssue = {
en = 'Iss.',
    en = 'Iss.',
ru = 'вып.',
    ru = 'вып.',
    uk = 'вип.',
}
}
---@type table<string, string>
local i18nPages = {
local i18nPages = {
fr = 'P.',
    fr = 'P.',
de = 'S.',
    de = 'S.',
es = 'P.',
    es = 'P.',
en = 'P.',
    en = 'P.',
it = 'P.',
    it = 'P.',
ru = 'С.',
    ru = 'С.',
    uk = 'С.',
}
}


---@type table<string, string>
local i18nNumberOfPages = {
local i18nNumberOfPages = {
en = 'p.',
    en = 'p.',
ru = 'с.',
    ru = 'с.',
}
 
---@type table<string, string>
local i18nTirage = {
    en = 'ed. size: %d',
    ru = '%d экз.',
}
}


local monthg = {'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', "сентября", "октября", "ноября", "декабря"};
---@param args args
---@return source
local function getFilledArgs( args )
    ---@type source
    local data = {}
 
    for key, value in pairs( args ) do
        if mw.text.trim( value ) ~= '' then
            if key == 1 then
                key = 'sourceId'
            end
            data[ key ] = mw.text.trim( value )
        end
    end
 
    return data
end
 
---Returns formatted pair {Family name(s), First name(s)}
---@param fullName string
---@return table<number, string>
local function tokenizeName( fullName )
    local space = '%s+' -- matches single or more spacing character
    local name = "(%a[%a%-']*)%.?" -- matches single name, have to start with letter, can contain apostrophe and hyphen, may end with dot
    local surname = "(%a[%a%-']*)" -- same as name, but can't end with dot
    local surnamePrefixes = { 'ван', 'van', 'де', 'de' }
 
    local nm, nm2, srn, srn2, pref
 
    fullName = ' ' .. fullName .. ' '
    fullName = mw.ustring.gsub( fullName, ' оглы ', ' ' )
    fullName = mw.text.trim( fullName )
 
    -- Surname, Name
    local pattern = '^' .. surname .. ',' .. space .. name .. '$'
    srn, nm = mw.ustring.match( fullName, pattern )
    if srn then
        return {
            srn,
            mw.ustring.sub( nm, 1, 1 ) .. '.'
        }
    end
 
    -- Surname, Name prefix
    for _, surnamePrefix in pairs( surnamePrefixes ) do
        pattern = '^' .. surname .. ',' .. space .. name .. space .. '(' .. surnamePrefix .. ')' .. '$'
        srn, nm, pref = mw.ustring.match( fullName, pattern )
        if srn then
            return {
                mw.ustring.sub( pref ) .. ' ' .. srn,
                mw.ustring.sub( nm, 1, 1 ) .. '.' }
        end
    end
 
    -- Surname, Name Name
    pattern = '^' .. surname .. ',' .. space .. name .. space .. name .. '$'
    srn, nm, nm2 = mw.ustring.match( fullName, pattern )
    if srn then
        return {
            srn,
            mw.ustring.sub( nm, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( nm2, 1, 1 ) .. '.'
        }
    end
 
    -- Surname Surname, Name
    pattern = '^' .. surname .. space .. surname .. ',' .. space .. name .. '$'
    srn, srn2, nm = mw.ustring.match( fullName, pattern )
    if srn then
        return {
            srn .. '&nbsp;' .. srn2,
            mw.ustring.sub( nm, 1, 1 ) .. '.'
        }
    end
 
    -- Name Name Surname
    pattern = '^' .. name .. space .. name .. space .. surname .. '$'
    nm, nm2, srn = mw.ustring.match( fullName, pattern )
    if srn then
        return {
            srn,
            mw.ustring.sub( nm, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( nm2, 1, 1 ) .. '.'
        }
    end
 
    -- Name Name prefix Surname
    for _, surnamePrefix in pairs( surnamePrefixes ) do
        pattern = '^' .. name .. space .. name .. space .. '(' .. surnamePrefix .. ')' .. space .. surname .. '$'
        nm, nm2, pref, srn = mw.ustring.match( fullName, pattern )
        if srn then
            return {
                mw.ustring.sub( pref ) .. ' ' .. srn,
                mw.ustring.sub( nm, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( nm2, 1, 1 ) .. '.'
            }
        end
    end
 
    -- Surname, Name Name prefix
    for _, surnamePrefix in pairs( surnamePrefixes ) do
        pattern = '^' .. surname .. ',' .. space .. name .. space .. name .. space .. '(' .. surnamePrefix .. ')' .. '$'
        srn, nm, nm2, pref = mw.ustring.match( fullName, pattern )
        if srn then
            return {
            mw.ustring.sub( pref ) .. ' ' .. srn,
            mw.ustring.sub( nm, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( nm2, 1, 1 ) .. '.'
            }
        end
    end
 
    -- Name{1,4} Surname
    for k = 1, 4 do
        pattern = '^' .. string.rep( name .. space, k ) .. surname .. '$'
        ---@type string[]
        local matched = { mw.ustring.match( fullName, pattern ) }
        if #matched ~= 0 then
            for j = 1, k do
                matched[ j ] = mw.ustring.sub( matched[ j ], 1, 1 )
            end
            return {
            matched[ k + 1 ],
            table.concat( matched, '.&nbsp;', 1, k ) .. '.'
            }
        end
    end
 
    -- Surname Name{1,4}
    for k = 1, 4 do
        pattern = '^' .. surname .. string.rep( space .. name, k ) .. '$'
        ---@type string[]
        local matched = { mw.ustring.match( fullName, pattern ) }
        if #matched ~= 0 then
            for j = 2, k + 1 do
                matched[ j ] = mw.ustring.sub( matched[ j ], 1, 1 )
            end
            return {
            matched[ 1 ],
            table.concat( matched, '.&nbsp;', 2, k + 1 ) .. '.'
            }
        end
    end
 
    return { fullName }
end
 
---@param fullName string | nil
---@return string | nil
local function personNameToAuthorName( fullName )
    if not fullName then
        return nil
    end
 
    local tokenized = tokenizeName( fullName )
    if #tokenized == 1 then
        return tokenized[ 1 ]
    end
 
    return tokenized[ 1 ] .. '&nbsp;' .. tokenized[ 2 ]
end
 
---@param fullName string | nil
---@return string | nil
local function personNameToResponsibleName( fullName )
    if not fullName then
        return nil
    end
 
    local tokenized = tokenizeName( fullName )
    if #tokenized == 1 then
        return tokenized[ 1 ]
    end
 
    return tokenized[ 2 ] .. '&nbsp;' .. tokenized[ 1 ]
end
 
---@alias options { separator: string, conjunction: string, format: ( fun( data: string ): string ), nolinks: boolean, preferids: boolean, short: boolean }
 
---@type options
local options_commas = {
    separator = ', ',
    conjunction = ', ',
    format = function( data ) return data end,
    nolinks = false,
    preferids = false,
    short = false,
}
 
---@type options
local options_commas_short = mw.clone( options_commas )
options_commas_short.short = true
 
---@type options
local options_commas_it_short = mw.clone( options_commas_short )
options_commas_it_short.format = function( data ) return "''" .. data .. "''" end
 
---@type options
local options_commas_nolinks = mw.clone( options_commas )
options_commas_nolinks.nolinks = true
 
---@type options
local options_citetypes = {
    separator = ' ',
    conjunction = ' ',
    format = function( data ) return 'citetype_' .. data end,
    nolinks = true ,
    preferids = true,
    short = false,
}


local PREFIX_CITEREF = "CITEREF_";
---@type options
local options_commas_authors = mw.clone( options_commas )
options_commas_authors.format = personNameToAuthorName


local options_commas = { separator = ', ', conjunction = ', ', format = function( src ) return src end, nolinks = false, preferids = false };
---@type options
local options_commas_short = { separator = ', ', conjunction = ', ', format = function( src ) return src end, nolinks = false, preferids = false, short = true };
local options_commas_responsible = mw.clone( options_commas )
local options_commas_nolinks = { separator = ', ', conjunction = ', ', format = function( src ) return src end, nolinks = true, preferids = false };
options_commas_responsible.format = personNameToResponsibleName
local options_commas_it = { separator = ', ', conjunction = ', ', format = function( src ) return "''" .. src .. "''" end, nolinks = false, preferids = false };
local options_commas_it_short = { separator = ', ', conjunction = ', ', format = function( src ) return "''" .. src .. "''" end, nolinks = false, preferids = false, short = true };
local options_commas_it_nolinks = { separator = ', ', conjunction = ', ', format = function( src ) return "''" .. src .. "''" end, nolinks = true , preferids = false };
local options_citetypes = { separator = ' ', conjunction = ' ', format = function( src ) return 'citetype_' .. src end, nolinks = true , preferids = true };


local options_commas_authors = { separator = ', ', conjunction = ', ', format = personNameToAuthorName, nolinks = false, preferids = false };
---@type options
local options_commas_responsible = { separator = ', ', conjunction = ', ', format = personNameToResponsibleName, nolinks = false, preferids = false };
local options_ids = {
    separator = '; ',
    conjunction = '; ',
    format = function( id ) return id end,
    nolinks = true,
    preferids = false,
    short = false,
}


local options_arxiv = { separator = '; ', conjunction = '; ', format = function( id ) return '[http://arxiv.org/abs/' .. id .. ' arXiv:' .. id .. ']' end, nolinks = true, preferids = false };
---@type options
local options_doi = { separator = '; ', conjunction = '; ', format = function( doi ) return '[http://dx.doi.org/' .. doi .. ' doi:' .. doi .. ']' end, nolinks = true, preferids = false };
local options_arxiv = mw.clone( options_ids )
local options_issn = { separator = '; ', conjunction = '; ', format = function( issn ) return '[https://www.worldcat.org/issn/' .. issn .. ' ' .. issn .. ']' end, nolinks = true, preferids = false };
options_arxiv.format = function( id ) return '[https://arxiv.org/abs/' .. id .. ' arXiv:' .. id .. ']' end


function renderSource( context, src )
---@type options
options_commas_authors.format = personNameToAuthorName;
local options_doi = mw.clone( options_ids )
options_commas_responsible.format = personNameToResponsibleName;
options_doi.format = function( doi ) return '[https://dx.doi.org/' .. doi .. ' doi:' .. doi .. ']' end


context.lang = getLangCode( getSingle( src.lang ) ) or i18nDefaultLanguage;
---@type options
local options_issn = mw.clone( options_ids )
options_issn.format = function( issn ) return '[https://www.worldcat.org/issn/' .. issn .. ' ' .. issn .. ']' end


preprocessPlaces( src, context.lang );
---@type options
local options_pmid = mw.clone( options_ids )
options_pmid.format = function( pmid ) return '[https://www.ncbi.nlm.nih.gov/pubmed/?term=' .. pmid .. ' PMID:' .. pmid .. ']' end


src.title = src.title or getSingle( src.url ) or '\'\'(unspecified title)\'\''
---@param str string | nil
---@return boolean
local function isEmpty( str )
    return not str or #str == 0
end


if ( src.sourceId and not src.url ) then
---@param allQualifiers snaks
local entity = getEntity( context, src.sourceId );
---@param qualifierPropertyId string
if ( entity.sitelinks and entity.sitelinks[ context.lang .. 'wikisource'] ) then
---@return string | nil
src.url = ':' .. context.lang .. ':s:' .. entity.sitelinks[ context.lang .. 'wikisource' ].title;
local function getSingleStringQualifierValue( allQualifiers, qualifierPropertyId )
end
    if not allQualifiers or not allQualifiers[ qualifierPropertyId ] then
end
        return nil
    end


if ( not src.year and src.dateOfPublication ) then
    ---@type table<number, snak>
local date = getSingle( src.dateOfPublication );
    local propertyQualifiers = allQualifiers[ qualifierPropertyId ]
src.year = mw.ustring.sub( date, 2, 5 );
end


if ( not src.year and src.dateOfCreation ) then
    for _, qualifier in pairs( propertyQualifiers ) do
local date = getSingle( src.dateOfCreation );
        if ( qualifier
src.year = mw.ustring.sub( date, 2, 5 );
                and qualifier.datatype == 'string'
end
                and qualifier.datavalue
                and qualifier.datavalue.type == 'string'
                and qualifier.datavalue.value ~= ''
        ) then
            return qualifier.datavalue.value
        end
    end


local result;
    return nil
if ( src.author ) then
end
result = getPeopleAsWikitext( context, src.author, options_commas_authors );
end
if ( not isEmpty( result )) then
result = '<i class="wef_low_priority_links">' .. result .. '</i> ';
else
result = '';
end
if ( src.part ) then
if ( src.url ) then
result = result .. wrapInUrl( src.url, toString( context, src.part, options_commas_nolinks ) );
else
result = result .. toString( context, src.part, options_commas );
end
result = result .. ' // ' .. toString( context, src.title, options_commas );
else
-- title only
if ( src.url ) then
result = result .. wrapInUrl( src.url, toString( context, src.title, options_commas_nolinks ) );
else
result = result .. toString( context, src.title, options_commas );
end
end


if ( src.subtitle ) then
---@param data table
result = result .. ": " .. toString( context, src.subtitle, options_commas );
---@param resultProperty string
end
---@return void
local function appendImpl_toTable( data, resultProperty )
    if not data[ resultProperty ] then
        data[ resultProperty ] = {}
    elseif ( type( data[ resultProperty ] ) == 'string' or ( type( data[ resultProperty ] ) == 'table' and type( data[ resultProperty ].id ) == 'string' ) ) then
        data[ resultProperty ] = { data[ resultProperty ] }
    end
end


if ( src.originaltitle ) then
---@param datavalue table
result = result .. ' = ' .. toString( context, src.originaltitle, options_commas );
---@param qualifiers snaks
end
---@param data table
---@param propertyName string
---@param options table
local function appendImpl( datavalue, qualifiers, data, propertyName, options )
    data[ propertyName ] = data[ propertyName ] or {}
    if propertyName == 'issn' then
        table.insert( data[ propertyName ], datavalue.value )
    elseif propertyName == 'url' or datavalue.type == 'url' then
        local value = datavalue.value
        if options.format then
            value = options.format( value )
        end
        appendImpl_toTable( data, propertyName )
        table.insert( data[ propertyName ], value )
    elseif datavalue.type == 'string' then
        local value = getSingleStringQualifierValue( qualifiers, 'P1932' )
        if not value then
            value = getSingleStringQualifierValue( qualifiers, 'P1810' )
        end


if ( src.publication ) then
        if not value then
if ( type( src.publication.title or '') ~= 'string' ) then error('type of src.publication.title is not string but ' .. type( src.publication.title ) ) end;
            value = datavalue.value
            if options.format then
                value = options.format( value )
            end
        end


result = result .. ' // ' .. toString( context, src.publication, options_commas_it_short );
        appendImpl_toTable(data, propertyName)
if ( src.publication.subtitle ) then
        local pos = getSingleStringQualifierValue( qualifiers, 'P1545' )
result = result .. ': ' .. toString( context, src.publication.subtitle, options_commas_it_short );
        if pos then
end
            table.insert( data[ propertyName ], tonumber(pos), value )
end
        else
            table.insert( data[ propertyName ], value )
        end
    elseif datavalue.type == 'monolingualtext' then
        local value = datavalue.value.text
        if options.format then
            value = options.format( value )
        end
        appendImpl_toTable( data, propertyName )
        table.insert( data[ propertyName ], value )
    elseif datavalue.type == 'quantity' then
        local value = datavalue.value.amount
        if ( mw.ustring.sub( value , 1, 1 ) == '+' ) then
            value = mw.ustring.sub( value , 2 )
        end
        if options.format then
            value = options.format( value )
        end
        appendImpl_toTable( data, propertyName )
        table.insert( data[ propertyName ], value )
    elseif datavalue.type == 'wikibase-entityid' then
        local pos = getSingleStringQualifierValue( qualifiers, 'P1545' )
        local value = datavalue.value
        appendImpl_toTable(data, propertyName)
        local label = getSingleStringQualifierValue( qualifiers, 'P1932' )
        if not label then
            label = getSingleStringQualifierValue( qualifiers, 'P1810' )
        end
        local toInsert = {
            id = value.id,
            label = label
        }
        if pos and tonumber( pos ) then
            table.insert( data[ propertyName ], tonumber( pos ), toInsert )
        else
            table.insert( data[ propertyName ], toInsert )
        end
    elseif datavalue.type == 'time' then
        local value = datavalue.value
        if options.format then
            value = options.format( value )
        end
        appendImpl_toTable( data, propertyName )
        table.insert( data[ propertyName ], tostring( value.time ) )
    end
end


result = result .. '<span class="wef_low_priority_links">';
---@param entityId string
---@param propertyId string
---@return table<number, statement>
local function getAllStatements( entityId, propertyId )
    ---@type boolean, table<number, statement>
    local wdStatus, statements = pcall( mw.wikibase.getAllStatements, entityId, propertyId )
    if wdStatus and statements then
        return statements
    end


if ( src.editor ) then
    return {}
local prefix = i18nEditors[ context.lang ] or i18nEditors[ i18nDefaultLanguage ];
end
result = result .. ' / ' .. prefix .. getPeopleAsWikitext( context, src.editor, options_commas_responsible );
end


if ( src.edition ) then
---@param entityId string
result = result .. ' — ' .. toString( context, src.edition, options_commas );
---@param propertyId string
end
---@return table<number, statement>
local function getBestStatements( entityId, propertyId )
    ---@type boolean, table<number, statement>
    local wdStatus, statements = pcall( mw.wikibase.getBestStatements, entityId, propertyId )
    if wdStatus and statements then
        return statements
    end


if ( src.place or src.publisher or src.year ) then
    return {}
result = result .. ' — ';
end
if ( src.place ) then
result = result .. toString( context, src.place, options_commas_short );
if ( src.publisher or src.year ) then
result = result .. ': ';
end
end
if ( src.publisher ) then
result = result .. toString( context, src.publisher, options_commas_short );
if ( src.year ) then
result = result .. ', ';
end
end
if ( src.year ) then
result = result .. toString( context, src.year, options_commas );
end
result = result .. '.';
end
if ( src.volume or src.issue ) then
result = result .. ' — ';
if ( src.volume ) then
local letter = i18nVolume[ context.lang ] or i18nVolume[ i18nDefaultLanguage ];
result = result .. letter .. '&nbsp;' .. toString( context, src.volume, options_commas );
if ( src.issue ) then
local letter = i18nIssue[ context.lang ] or i18nIssue[ i18nDefaultLanguage ];
result = result .. ', ' .. letter .. '&nbsp;' .. toString( context, src.issue, options_commas ) .. '.';
else
result = result .. '.';
end
else
local letter = i18nIssue[ context.lang ] or i18nIssue[ i18nDefaultLanguage ];
result = result .. letter .. '&nbsp;' .. toString( context, src.issue, options_commas ) .. '.';
end
end


if ( src.pages ) then
---@param entityId string
local letter = i18nPages[ context.lang ] or i18nPages[ i18nDefaultLanguage ];
---@param projectToCheck string?
result = result .. ' — ' .. letter .. '&nbsp;' .. toString( context, src.pages, options_commas )  .. '.';
---@return string | nil
end
local function getSitelink( entityId, projectToCheck )
    ---@type boolean, string
    local wbStatus, sitelink


if ( src.numberOfPages ) then
    if projectToCheck then
local letter = i18nNumberOfPages[ context.lang ] or i18nNumberOfPages[ i18nDefaultLanguage ];
        wbStatus, sitelink = pcall( mw.wikibase.getSitelink, entityId, projectToCheck )
result = result .. ' — ' .. toString( context, src.numberOfPages, options_commas ) .. '&nbsp;' .. letter;
    else
end
        wbStatus, sitelink = pcall( mw.wikibase.getSitelink, entityId )
    end


if ( src.bookSeries ) then
    if not wbStatus then
result = result .. ' — (' .. toString( context, src.bookSeries, options_commas )
        return nil
    end


if ( src.bookSeriesVolume or src.bookSeriesIssue ) then
    return sitelink
result = result .. '; ';
end
if ( src.bookSeriesVolume ) then
local letter = i18nVolume[ context.lang ] or i18nVolume[ i18nDefaultLanguage ];
result = result .. letter .. '&nbsp;' .. toString( context, src.bookSeriesVolume, options_commas );
if ( src.bookSeriesIssue ) then
local letter = i18nIssue[ context.lang ] or i18nIssue[ i18nDefaultLanguage ];
result = result .. ', ' .. letter .. '&nbsp;' .. toString( context, src.bookSeriesIssue, options_commas );
else
result = result;
end
else
local letter = i18nIssue[ context.lang ] or i18nIssue[ i18nDefaultLanguage ];
result = result .. letter .. '&nbsp;' .. toString( context, src.bookSeriesIssue, options_commas );
end
end


result = result .. ')';
---@param args any[]
end
---@return any | nil
local function coalesce( args )
    for _, arg in pairs( args ) do
        if not isEmpty( arg ) then return arg end
    end
    return nil
end


if ( src.isbn ) then
---@param value any
result = result .. ' — ISBN ' .. toString( context, src.isbn, options_commas );
---@return string | nil
end
local function getSingle( value )
    if type( value ) == 'string' then
        return tostring( value )
    elseif type( value ) == 'table' then
        if value.id then
            return tostring( value.id )
        end


if ( src.issn ) then
        for _, tableValue in pairs( value ) do
result = result .. ' — ISSN ' .. toString( context, src.issn, options_issn );
            return getSingle( tableValue )
end
        end
    end


if ( src.doi ) then
    return nil
result = result .. ' — ' .. toString( context, src.doi, options_doi );
end
end


if ( src.arxiv ) then
---@param langEntityId string
result = result .. ' — ' .. toString( context, src.arxiv, options_arxiv );
---@return string | nil
end
local function getLangCode( langEntityId )
    if not langEntityId then
        return nil
    end


if ( src.sourceId ) then
    langEntityId = getSingle( langEntityId )
if ( src.type and src.sourceId ) then
-- wrap into span to target from JS
result = '<span class="wikidata_cite ' .. toString( context, src.type, options_citetypes ) .. '" data-entity-id="' .. getSingle( src.sourceId ) .. '">' .. result .. '</span>'
else
result = '<span class="wikidata_cite citetype_unknown" data-entity-id="' .. getSingle( src.sourceId ) .. '">' .. result .. '</span>'
end
end


if ( src.accessdate ) then
    if not string.match( langEntityId, '^Q%d+$' ) then
local date = getSingle( src.accessdate );
        return langEntityId
local pattern = "(%-?%d+)%-(%d+)%-(%d+)T";
    end
local y, m, d = mw.ustring.match( date , pattern );
y,m,d = tonumber(y),tonumber(m),tonumber(d);
result = result .. " <small>Проверено " .. tostring(d) .. " " .. monthg[m]  .. " " .. tostring(y) .. ".</small>";
end


result = result .. '</span>';
    local cached = LANG_CACHE[ langEntityId ]
    if cached then
        if cached == '' then
            return nil
        end
        return cached
    end


    -- append invisible links to all elements used by source for tracking purposes
     local claims = getBestStatements( langEntityId, 'P424' )
     local result = result .. '<div style="display:none">';
    for _, claim in pairs( claims ) do
for key, entity in pairs( context.cache ) do
        if claim
result = result .. '<a href="https://wikidata.org' .. mw.uri.localUrl('Track:' .. key).path .. '"></a>';
                and claim.mainsnak
end
                and claim.mainsnak.datavalue
     result = result ..'</div>'
                and claim.mainsnak.datavalue.value
        then
            LANG_CACHE[ langEntityId ] = claim.mainsnak.datavalue.value
            return claim.mainsnak.datavalue.value
        end
     end


return {text = result, code = src.code};
    LANG_CACHE[ langEntityId ] = ''
    return nil
end
end


function renderShortReference( src )
---@param entityId string
context = {
---@param propertyId string
cache = {},
---@param data source
lang = getSingle( src.lang ) or i18nDefaultLanguage;
---@param propertyName string
};
---@param options table?
src.title = src.title or '\'\'(unspecified title)\'\''
---@return void
local function appendEntitySnaks( entityId, propertyId, data, propertyName, options )
    options = options or {}
 
    -- do not populate twice
    if data[ propertyName ] and ( propertyName ~= 'author' or data[ propertyId ] ) then
        return
    end
 
    local statements = getBestStatements( entityId, propertyId )
 
    if propertyName == 'author' then
        data[ propertyId ] = true
    end
 
    local lang = getLangCode( data.lang ) or i18nDefaultLanguage


local result = '[[#' .. PREFIX_CITEREF .. src.code .. '|';
    if propertyId == 'P1680' then -- if there is a default language
if ( src.author ) then
        for _, statement in pairs( statements ) do
result = result .. toString( context, src.author, options_authors_nolinks );
            if statement and
else
                    statement.mainsnak and
result = result .. toString( context, src.title, options_commas_it_nolinks );
                    statement.mainsnak.datavalue and
end
                    statement.mainsnak.datavalue.value and
result = result .. ']]'
                    statement.mainsnak.datavalue.value.language == lang
            then
                --found default language string
                appendImpl( statement.mainsnak.datavalue, statement.qualifiers, data, propertyName, options )
                return
            end
        end
    end


if ( src.year ) then
    for _, statement in pairs( statements ) do
result = result .. ', ' .. toString( context, src.year, options_commas );
        if statement and statement.mainsnak and statement.mainsnak.datavalue then
end
            appendImpl( statement.mainsnak.datavalue, statement.qualifiers or {}, data, propertyName, options )
            if propertyName == 'publication-id' and statement.qualifiers then
                data[ 'publication-qualifiers' ] = statement.qualifiers
            end
        end
    end
end


if ( src.volume ) then
---@param claims table<number, statement>
local letter = i18nVolume[ context.lang ] or i18nVolume[ i18nDefaultLanguage ];
---@param qualifierPropertyId string
result = result .. ' — ' .. letter .. '&nbsp;' .. toString( context, src.volume, options_commas ) .. '.';
---@param result table
end
---@param resultPropertyId string
---@param options table
---@return void
local function appendQualifiers( claims, qualifierPropertyId, result, resultPropertyId, options )
    -- do not populate twice
    if not claims or result[ resultPropertyId ] then
        return
    end


if ( src.issue ) then
    for _, claim in pairs( claims ) do
local letter = i18nIssue[ context.lang ] or i18nIssue[ i18nDefaultLanguage ];
        if claim.qualifiers and claim.qualifiers[ qualifierPropertyId ] then
result = result .. ' — ' .. letter .. '&nbsp;' .. toString( context, src.issue, options_commas ) .. '.';
            ---@type table<number, snak>
end
            local propertyQualifiers = claim.qualifiers[ qualifierPropertyId ]
            for _, qualifier in pairs( propertyQualifiers ) do
if ( src.pages ) then
                if qualifier and qualifier.datavalue then
local letter = i18nPages[ context.lang ] or i18nPages[ i18nDefaultLanguage ];
                    appendImpl( qualifier.datavalue, nil, result, resultPropertyId, options )
result = result .. ' — ' .. letter .. '&nbsp;' .. toString( context, src.pages, options_commas ) .. '.';
                end
end
            end
        end
    end
end
end


function getPeopleAsWikitext( context, value, options )
---@param entityId string
if ( type( value ) == 'string' ) then
---@param propertyId string
return options.format( value );
---@param value any
elseif ( type( value ) == 'table' ) then
---@return table<number, statement>
if ( value.id ) then
local function findClaimsByValue( entityId, propertyId, value )
-- this is link
    local result = {}
if ( options.preferids ) then
 
return value.id;
    local claims = getAllStatements( entityId, propertyId )
else
    for _, claim in pairs( claims ) do
if ( options.nolinks ) then
        if ( claim.mainsnak and claim.mainsnak.datavalue ) then
return getPersonNameAsLabel( context, value.id, value.label, options );
            local datavalue = claim.mainsnak.datavalue
else
            if ( datavalue.type == "string" and datavalue.value == value ) or
return getPersonNameAsWikitext( context, value.id, value.label, options );
                    ( datavalue.type == "wikibase-entityid" and
end
                            datavalue.value[ "entity-type" ] == "item" and
end
                            tostring( datavalue.value.id ) == value )
end
            then
                table.insert( result, claim )
            end
        end
    end


local resultList = {};
    return result
for i, tableValue in pairs( value ) do
end
local nextWikitext = getPeopleAsWikitext( context, tableValue, options );
if ( not isEmpty( nextWikitext ) ) then
table.insert( resultList, nextWikitext );
if ( #resultList == 4 ) then
-- even 4 is too much, but we preserve 4th to mark that "it's more than 3"
break;
end
end
end


local resultWikitext = '';
---@param entityId string
for i, wikitext in pairs( resultList ) do
---@param typeEntityId string
if ( i == 4 ) then
---@return boolean
resultWikitext = resultWikitext .. ( i18nEtAl[ context.lang ] or i18nEtAlDefault );
local function isInstanceOf( entityId, typeEntityId )
break;
    return findClaimsByValue( entityId, 'P31', typeEntityId )[ 1 ] ~= nil
end
end
if ( i ~= 1 ) then
resultWikitext = resultWikitext .. ', ';
end
resultWikitext = resultWikitext .. wikitext;
end


return resultWikitext;
---@param entityId string
end
---@param typeEntityIds string[]
---@return string
---@todo Rewrite
local function getFirstType( entityId, typeEntityIds )
    for _, typeEntityId in pairs( typeEntityIds ) do
        if isInstanceOf( entityId, typeEntityId ) then
            return typeEntityId
        end
    end


return options.format( '(unknown type)' );
    return nil
end
end


function getPersonNameAsWikitext( context, entityId, customLabel, options )
---@param snaks snaks
local personName = getPersonNameAsLabel( context, entityId, customLabel, options);
---@param data source
if ( personName == nil ) then
---@param map map
return nil;
---@return void
end
local function populateDataFromSnaks( snaks, data, map )
    for _, row in ipairs( map ) do
        local parameterName, propertyIds = row.name, row.ids
        for _, propertyId in pairs( propertyIds ) do
            if not data[ parameterName ] and snaks[ propertyId ] then
                local options = {}
                if propertyId == 'P888' then
                    options = { format = function( id ) return 'http://www.jstor.org/stable/' .. id end }
                end


local link = getElementLink( context, entityId, nil );
                for _, snak in pairs( snaks[ propertyId ] ) do
return wrapInUrl( link, personName );
                    if snak and snak.datavalue then
                        appendImpl( snak.datavalue, {}, data, parameterName, options )
                    end
                end
            end
        end
    end
end
end


function getPersonNameAsLabel( context, entityId, providedLabel, options )
---@param entityId string | nil
-- would custom label provided we don't need to check entity at all
---@param data source
if ( not isEmpty( providedLabel ) ) then
---@param map map
mw.log( 'Custom label provided for ' .. entityId );
---@return void
return options.format( providedLabel );
local function populateDataFromEntity( entityId, data, map )
end
    if not data.title then
        if not isEmpty( entityId ) then
            local optionsAsLinks = { format = function( text ) return { id = entityId, label = text } end }
            appendEntitySnaks( entityId, 'P1476', data, 'title', optionsAsLinks )
        else
            appendEntitySnaks( entityId, 'P1476', data, 'title', {} )
        end
        appendEntitySnaks( entityId, 'P1680', data, 'subtitle', {} )
    end


local entity = getEntity( context, entityId );
    local bookSeriesStatements = getBestStatements( entityId, 'P361' )
if ( not entity ) then return '\'\'(entity ' .. entityId .. ' is missing)\'\'' end;
    for _, statement in pairs( bookSeriesStatements ) do
        if statement and
                statement.mainsnak and
                statement.mainsnak.datavalue and
                statement.mainsnak.datavalue.value and
                statement.mainsnak.datavalue.value.id
        then
            local possibleBookSeriesEntityId = statement.mainsnak.datavalue.value.id
            if isInstanceOf( possibleBookSeriesEntityId, 'Q277759' ) then
                appendImpl_toTable( data, 'bookSeries' )
                table.insert( data.bookSeries, { id = possibleBookSeriesEntityId } )


local personName = nil;
                appendQualifiers( { statement }, 'P478', data, 'bookSeriesVolume', {} )
-- support only labels so far
                appendQualifiers( { statement }, 'P433', data, 'bookSeriesIssue', {} )
if ( entity.labels[ context.lang ] ) then
            end
personName = entity.labels[ context.lang ].value;
        end
mw.log('Got person name of ' .. entityId .. ' from label: «' .. personName .. '»' )
    end
end


if ( not isInstanceOf( entity, 'Q5' ) ) then
    for _, row in ipairs( map ) do
mw.log( 'Entity ' .. entityId .. ' is not a person' );
        local parameterName, propertyIds = row.name, row.ids
return personName;
        for _, propertyId in pairs( propertyIds ) do
end
            local options = {}
            if propertyId == 'P888' then
                options = { format = function( id ) return 'http://www.jstor.org/stable/' .. id end }
            end


if ( isEmpty( personName ) ) then
            appendEntitySnaks( entityId, propertyId, data, parameterName, options )
return '\'\'(not translated to ' .. context.lang .. ')\'\'';
        end
else
    end
return options.format( personName );
end
end
end


function personNameToAuthorName( fullName )
---@param data source
if ( not fullName ) then return fullName; end
---@return void
local function expandPublication( data )
    if not data[ 'publication-id' ] then
        return
    end
 
    local publicationId = getSingle( data[ 'publication-id' ] )
    data.publication = {}
    for key, value in pairs( data ) do
        if not string.match( key, '^publication-' ) then
            data.publication[ key ] = value
        end
    end
    data.publication.sourceId = publicationId
    data.publication.title = data[ 'publication-title' ]
    data.publication.subtitle = data[ 'publication-subtitle' ]


local f, i, o = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)\,%s(%a[%a\-]*)%s(%a[%a\-]*)%s*$' );
    if data[ 'publication-qualifiers' ] then
if ( f ) then
        populateDataFromSnaks( data[ 'publication-qualifiers' ], data.publication, PUBLICATION_PROPERTY_MAP )
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «Fa, I. O.» match' );
    end
return f .. '&nbsp;'
    populateDataFromEntity( publicationId, data.publication, PUBLICATION_PROPERTY_MAP )
.. mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;'
.. mw.ustring.sub( o, 1, 1 ) .. '.';
end


local f1, f2, i = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)%s(%a[%a\-]*)\,%s(%a[%a\-]*)%s*$' );
    if type( data.publication.title ) == 'table' and data.publication.title[ 1 ] then
if ( f1 ) then
        data.publication.title = data.publication.title[ 1 ]
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «Fa Fa, I» match' );
    end
return f1 .. '&nbsp;' .. f2 .. '&nbsp;'
    if type( data.publication.subtitle ) == 'table' and data.publication.subtitle[ 1 ] then
.. mw.ustring.sub( i, 1, 1 ) .. '.';
        data.publication.subtitle = data.publication.subtitle[ 1 ]
end
    end


local i, o, f = mw.ustring.match( fullName, '^%s*(%a)\.%s(%a)\.%s(%a[%a\-]+)%s*$');
    for key, value in pairs( data.publication ) do
if ( f ) then
        if key ~= 'sourceId' and key ~= 'title' and key ~= 'subtitle' and key ~= 'url' and not data[ key ] then
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «I. O. Fa» match' );
            data[ key ] = value
return f .. '&nbsp;' .. i .. '.&nbsp;' .. o .. '.';
        end
end
    end
end


local i1, i2, i3, f = mw.ustring.match( fullName, '^%s*(%a)\.%s(%a)\.%s(%a)\.%s(%a[%a\-]+)%s*$');
---@param data source
if ( f ) then
---@return void
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «I. O. ?. Fa» match' );
local function expandBookSeries( data )
return f .. '&nbsp;' .. i1 .. '.&nbsp;' .. i2 .. '.&nbsp;' .. i3 .. '.';
    local bookSeries = data.bookSeries
end
    if not bookSeries then
        return
    end


     -- Joel J. P. C. Rodrigues
     -- use only first one
local i1, i2, i3, i4, f = mw.ustring.match( fullName, '^%s*(%a)[%a\-]+%s(%a)\.%s(%a)\.%s(%a)\.%s(%a[%a\-]+)%s*$');
    if type( bookSeries ) == 'table' and bookSeries[ 1 ] and bookSeries[ 1 ].id then
if ( f ) then
        data.bookSeries = bookSeries[ 1 ]
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «I. O. ?. Fa» match' );
        bookSeries = data.bookSeries
return f .. '&nbsp;' .. i1 .. '.&nbsp;' .. i2 .. '.&nbsp;' .. i3 .. '.&nbsp;' .. i4 .. '.';
    end
end


local i, o, f = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)%s(%a)\.%s(%a[%a\-]*)%s*$');
    if not bookSeries or not bookSeries.id then
if ( f ) then
        return
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «Im O. Fa» match' );
    end
return f .. '&nbsp;' .. mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. o .. '.';
end


local i, o, f = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)%s(%a[%a\-]*)%s(%a[%a\-]*)%s*$');
    appendEntitySnaks( bookSeries.id, 'P123', data, 'publisher', {} )
if ( f ) then
    appendEntitySnaks( bookSeries.id, 'P291', data, 'place', {} )
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «Im Ot Fa» match' );
    appendEntitySnaks( bookSeries.id, 'P236', data, 'issn', {} )
return f .. '&nbsp;' .. mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( o, 1, 1 ) .. '.';
end
end


local i, o, f = mw.ustring.match( fullName, '^%s*(%a[%a\-]+)%s(%a[%a\-]+)%s+оглы%s+(%a[%a\-]+)%s*$');
---@param entityId string
if ( f ) then
---@return string | nil
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «Im Ot оглы Fa» match' );
local function getNormativeTitle( entityId )
return f .. '&nbsp;' .. mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( o, 1, 1 ) .. '.';
    local possibleTypeIds = {}
end
    for typeId, _ in pairs( NORMATIVE_DOCUMENTS ) do
        table.insert( possibleTypeIds, typeId )
    end


local i, f = mw.ustring.match( fullName, '^%s*(%a[%a\-\']+)%s(%a[%a\-\']+)%s*$');
    local foundTypeId = getFirstType( entityId, possibleTypeIds )
if ( f ) then
    if foundTypeId then
mw.log( 'personNameToAuthorName: «' .. fullName .. '»: have «Im Fa» match' );
        return NORMATIVE_DOCUMENTS[ foundTypeId ]
return f .. '&nbsp;' .. mw.ustring.sub( i, 1, 1 ) .. '.';
    end
end


mw.log( 'Unmatched any pattern: «' .. fullName .. '»' );
    return nil
return fullName;
end
end


function personNameToResponsibleName( fullName )
---@param urls table<number, string> | string
if ( not fullName ) then return fullName; end
---@param text string
---@return string
local function wrapInUrl( urls, text )
    local url = getSingle( urls )


local f, i, o = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)\,%s(%a[%a\-]*)%s(%a[%a\-]*)%s*$' );
    if string.sub( url, 1, 1 ) == ':' then
if ( f ) then
        return '[[' .. url .. '|' .. text .. ']]'
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «Fa, I. O.» match' );
    else
return mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( o, 1, 1 ) .. '.&nbsp;' .. f;
        return '[' .. url .. ' ' .. text .. ']'
end
    end
end


local f1, f2, i = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)%s(%a[%a\-]*)\,%s(%a[%a\-]*)%s*$' );
---@param entityId string
if ( f1 ) then
---@param lang string
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «Fa Fa, I» match' );
---@return string
return  mw.ustring.sub( i, 1, 1 ) .. '&nbsp;' .. f1 .. '&nbsp;' .. f2;
local function getElementLink( entityId, lang )
end
    local sitelink = getSitelink( entityId, nil )
    if sitelink then
        return ':' .. sitelink
    end


local i, o, f = mw.ustring.match( fullName, '^%s*(%a)\.%s(%a)\.%s(%a[%a\-]+)%s*$');
    if lang ~= 'mul' then
if ( f ) then
        -- link to entity in source language
mw.log( 'v: «' .. fullName .. '»: have «I. O. Fa» match' );
        sitelink = getSitelink( entityId, lang .. 'wiki' )
return i .. '.&nbsp;' .. o .. '.&nbsp;' .. f;
        if sitelink then
end
            return ':' .. lang .. ':' .. sitelink
        end
    end


local i1, i2, i3, f = mw.ustring.match( fullName, '^%s*(%a)\.%s(%a)\.%s(%a)\.%s(%a[%a\-]+)%s*$');
    return ':d:' .. entityId
if ( f ) then
end
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «I. O. ?. Fa» match' );
 
return i1 .. '.&nbsp;' .. i2 .. '.&nbsp;' .. i3 .. '.&nbsp;' .. f;
---@param entityId string
end
---@param lang string
---@return string
local function getLabel( entityId, lang )
    local wbStatus, label = pcall( mw.wikibase.getLabelByLang, entityId, lang )
    if not wbStatus then
        return ''
    end
 
    if label and label ~= '' then
        return label
    end
 
    wbStatus, label = pcall( mw.wikibase.getLabel, entityId )
    if not wbStatus then
        return ''
    end
 
    return label or ''
end


    -- Joel J. P. C. Rodrigues
---@param lang string
local i1, i2, i3, i4, f = mw.ustring.match( fullName, '^%s*(%a)[%a\-]+%s(%a)\.%s(%a)\.%s(%a)\.%s(%a[%a\-]+)%s*$');
---@param entityId string
if ( f ) then
---@param customTitle string
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «I. O. ?. Fa» match' );
---@param options table
return  i1 .. '.&nbsp;' .. i2 .. '.&nbsp;' .. i3 .. '.&nbsp;' .. i4 .. '.&nbsp;' .. f;
local function renderLink( lang, entityId, customTitle, options )
end
    if not entityId then
        error( 'entityId is not specified' )
    end
    if type( entityId ) ~= 'string' then
        error( 'entityId is not string, but ' .. type( entityId ) )
    end
    if type( customTitle or '' ) ~= 'string' then
        error( 'customTitle is not string, but ' .. type( customTitle ) )
    end


local i, o, f = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)%s(%a)\.%s(%a[%a\-]*)%s*$');
    local title = customTitle
if ( f ) then
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «Im O. Fa» match' );
return mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. o .. '.&nbsp;' .. f;
end


local i, o, f = mw.ustring.match( fullName, '^%s*(%a[%a\-]*)%s(%a[%a\-]*)%s(%a[%a\-]*)%s*$');
    -- ISO 4
if ( f ) then
    if isEmpty( title ) then
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «Im Ot Fa» match' );
        local propertyStatements = getBestStatements( entityId, 'P1160' )
return mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( o, 1, 1 ) .. '.&nbsp;' .. f;
        for _, claim in pairs( propertyStatements ) do
end
            if ( claim
                    and claim.mainsnak
                    and claim.mainsnak.datavalue
                    and claim.mainsnak.datavalue.value
                    and claim.mainsnak.datavalue.value.language == lang
            ) then
                title = claim.mainsnak.datavalue.value.text
                -- mw.log( 'Got title of ' .. entityId .. ' from ISO 4 claim: «' .. title .. '»' )
                break
            end
        end
    end


local i, o, f = mw.ustring.match( fullName, '^%s*(%a[%a\-]+)%s(%a[%a\-]+)%s+оглы%s+(%a[%a\-]+)%s*$');
    -- official name P1448
if ( f ) then
    -- short name P1813
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «Im Ot оглы Fa» match' );
    if isEmpty( title ) and options.short then
return  mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. mw.ustring.sub( o, 1, 1 ) .. '.&nbsp;' .. f;
        local propertyStatements = getBestStatements( entityId, 'P1813' )
end
        for _, claim in pairs( propertyStatements ) do
            if ( claim
                    and claim.mainsnak
                    and claim.mainsnak.datavalue
                    and claim.mainsnak.datavalue.value
                    and claim.mainsnak.datavalue.value.language == lang
            ) then
                title = claim.mainsnak.datavalue.value.text
                -- mw.log( 'Got title of ' .. entityId .. ' from short name claim: «' .. title .. '» (' .. lang .. ')' )
                break
            end
        end
    end


local i, f = mw.ustring.match( fullName, '^%s*(%a[%a\-\']+)%s(%a[%a\-\']+)%s*$');
    -- person name P1559
if ( f ) then
    -- labels
mw.log( 'personNameToResponsibleName: «' .. fullName .. '»: have «Im Fa» match' );
    if isEmpty( title ) then
return  mw.ustring.sub( i, 1, 1 ) .. '.&nbsp;' .. f;
        title = getLabel( entityId, lang )
end
        -- mw.log( 'Got title of ' .. entityId .. ' from label: «' .. title .. '» (' .. lang .. ')' )
    end


mw.log( 'Unmatched any pattern: «' .. fullName .. '»' );
    local actualText = title or '\'\'(untranslated)\'\''
return fullName;
    local link = getElementLink( entityId, lang )
    return wrapInUrl( link, actualText )
end
end


function p.renderSource( frame )
---@param lang string
p.currentFrame = frame;
---@param value value
---@param options options
---@return string
local function asString( lang, value, options )
    if type( value ) == 'string' then
        return options.format( value )
    end
    if type( value ) ~= 'table' then
        return options.format( '(unknown type)' )
    end
 
    if value.id then
        -- this is link
        if type( value.label or '' ) ~= 'string' then
            mw.logObject( value, 'error value' )
            error( 'label of table value is not string but ' .. type( value.label ) )
        end
 
        local title
        if options.preferids then
            title = value.id
        elseif options.nolinks then
            title = value.label or getLabel( value.id, lang )
        else
            title = renderLink( lang, value.id, value.label, options )
        end
 
        if title == '' then
            title = "''(untranslated title)''"
        end
 
        return options.format( title )
    end


local arg = frame.args[1];
    local resultList = {}
local refAnchor = frame.args['ref'];
    for _, tableValue in pairs( value ) do
local refAnchorYear = frame.args['ref-year'];
        table.insert( resultList, asString( lang, tableValue, options ) )
local args = {};
    end
args.refAnchor = frame.args['ref'];
args.refAnchorYear = frame.args['ref-year'];
args.part = frame.args['part'];
args.pages = frame.args['pages'];


return p.renderSourceImpl( mw.text.trim( arg ), args );
    return mw.text.listToText( resultList, options.separator, options.conjunction )
end
end


function p.renderSourceImpl( entityId, args )
---@param entityId string
args = args or {};
---@param data source
---@return source
local function populateSourceDataImpl( entityId, data, map )
    local wsLink = getSitelink( entityId, 'ruwikisource' )
    if wsLink and not mw.ustring.gmatch( wsLink, 'Категория:' ) then
        data.url = ":ru:s:" .. wsLink
    end
    populateDataFromEntity( entityId, data, map )


local snaks = {};
    local normativeTitle = getNormativeTitle( entityId )
snaks.P248 = { toWikibaseEntityIdSnak( 'P248', entityId ) };
    if normativeTitle then
copyArgsToSnaks( args, snaks );
        local y, m, d = mw.ustring.match( getSingle( data.dateOfCreation ) , "(%-?%d+)%-(%d+)%-(%d+)T" )
        y, m, d = tonumber( y ),tonumber( m ), tonumber( d )
        local title = asString( 'ru', data.title, options_commas_nolinks )
        local docNumber = getSingle( data.docNumber )
        data.title = {
            normativeTitle ..
                    " от&nbsp;" .. tostring( d ) .. "&nbsp;" .. monthGen[ m ]  .. " " .. tostring( y ) .. "&nbsp;г." ..
                    ( docNumber and ( " №&nbsp;" .. docNumber ) or '' ) ..
                    ' «' .. title.. '»'
        }
    end


local rendered = renderReferenceImpl( mw.wikibase.getEntity(), { snaks = snaks }, args.refAnchor, args.refAnchorYear );
    if not data.title then
if ( rendered ) then return rendered.text end;
        local lang = getLangCode( data.lang ) or i18nDefaultLanguage
        local label = getLabel( entityId, lang )
        if label ~= '' then
            data.title = { label }
        end
    end
 
    return data
end
end


function p.renderReference( frame, currentEntity, reference )
---@param entityId string
p.currentFrame = frame;
---@param propertyId string
---@param data source
---@return void
local function expandSpecialsQualifiers( entityId, propertyId, data )
    local statements = getBestStatements( entityId, propertyId )
    for _, statement in pairs( statements ) do
        populateDataFromSnaks( statement.qualifiers or {}, data, PROPERTY_MAP )
    end
end


-- template call
---Expand special types of references when additional data could be found in OTHER entity properties
if ( frame and not currentEntity and not reference ) then
---@param data source
local args = frame.args;
---@return void
if ( #frame.args == 0 ) then
local function expandSpecials( data )
args = frame:getParent().args;
    if not data.entityId then
end
        return
    end


local snaks = {};
    if data.sourceId == 'Q36578' then
        -- Gemeinsame Normdatei -- specified by P227
        appendEntitySnaks( data.entityId, 'P227', data, 'part', { format = function(gnd ) return 'Record #' .. gnd; end } )
        appendEntitySnaks( data.entityId, 'P227', data, 'url', { format = function(gnd ) return 'http://d-nb.info/gnd/' .. gnd .. '/'; end } )
        data.year = '2012—2016'
        expandSpecialsQualifiers( data.entityId, 'P227', data )


if ( args[1] ) then
    elseif data.sourceId == 'Q15222191' then
snaks.P248 = { toWikibaseEntityIdSnak( "P248", args[1] ) };
        -- BNF -- specified by P268
end
        appendEntitySnaks( data.entityId, 'P268', data, 'part', { format = function(id ) return 'Record #' .. id; end } )
copyArgsToSnaks( args, snaks );
        appendEntitySnaks( data.entityId, 'P268', data, 'url', { format = function(id ) return 'http://catalogue.bnf.fr/ark:/12148/cb' .. id; end } )
        expandSpecialsQualifiers( data.entityId, 'P268', data )


currentEntity = mw.wikibase.getEntity();
    elseif data.sourceId == 'Q54919' then
reference = { snaks = snaks };
        -- VIAF -- specified by P214
end
        appendEntitySnaks( data.entityId, 'P214', data, 'part', { format = function(id ) return 'Record #' .. id; end } )
        appendEntitySnaks( data.entityId, 'P214', data, 'url', { format = function(id ) return 'https://viaf.org/viaf/' .. id; end } )
        expandSpecialsQualifiers( data.entityId, 'P214', data )


local rendered = renderReferenceImpl( currentEntity, reference );
    else
        -- generic property search
        for _, sourceClaim in pairs( getBestStatements( data.sourceId, 'P1687' ) ) do
            if sourceClaim.mainsnak.snaktype == 'value' then
                local sourcePropertyId = sourceClaim.mainsnak.datavalue.value.id
                for _, sourcePropertyClaim in pairs( getBestStatements( sourcePropertyId, 'P1630' ) ) do
                    if sourcePropertyClaim.mainsnak.snaktype == 'value' then
                        appendEntitySnaks( data.entityId, sourcePropertyId, data, 'url', {
                            format = function( id )
                                return mw.ustring.gsub( mw.ustring.gsub( sourcePropertyClaim.mainsnak.datavalue.value, '$1', id ), ' ', '%%20' )
                            end
                        } )
                        expandSpecialsQualifiers( data.entityId, sourcePropertyId, data )
                        break
                    end
                end
            end
        end
    end


if ( not rendered ) then
    -- do we have appropriate record in P1433 ?
return '';
    local claims = findClaimsByValue( currentEntityId, 'P1343', data.sourceId )
end
    if claims and #claims ~= 0 then
        for _, claim in pairs( claims ) do
            populateDataFromSnaks( claim.qualifiers, data, PROPERTY_MAP )
            populateDataFromEntity( data.sourceId, data, PROPERTY_MAP )
        end
    end
end


local result;
---@param text string
local code = rendered.code or rendered.text;
---@param tip string
result = frame:extensionTag( 'ref', rendered.text, {name = code} ) .. '[[Category:ЭАНМ:Статьи с источниками из Викиданных]]';
---@return string
local function toTextWithTip( text, tip )
    return '<span title="' .. tip .. '" style="border-bottom: 1px dotted; cursor: help; white-space: nowrap">' .. text .. '</span>'
end


return result;
---@param lang string
---@param placeId string
---@return string
local function getPlaceName( placeId, lang )
    -- ГОСТ Р 7.0.12—2011
    if lang == 'ru' then
        if placeId == 'Q649' then return toTextWithTip( 'М.', 'Москва' ); end
        if placeId == 'Q656' then return toTextWithTip( 'СПб.', 'Санкт-Петербург' ); end
        if placeId == 'Q891' then return toTextWithTip( 'Н. Новгород', 'Нижний Новгород' ); end
        if placeId == 'Q908' then return toTextWithTip( 'Ростов н/Д.', 'Ростов-на-Дону' ); end
    end
    return nil
end
end


function renderReferenceImpl( currentEntity, reference, refAnchor, refAnchorYear )
---@param data source
if ( not reference.snaks ) then
---@param lang string
return nil;
---@return void
end
local function preprocessPlace( data, lang )
    if not data.place then
        return
    end
 
    ---@type table<number, string>
    local newPlace = {}
 
    for index, place in pairs( data.place ) do
        if place.id then
            local newPlaceStr = getPlaceName( place.id, lang )
            if newPlaceStr then
                newPlace[ index ] = newPlaceStr
            else
                newPlace[ index ] = getLabel( place.id, lang )
            end
        else
            newPlace[ index ] = place
        end
    end


-- контекст, содержит также кеш элементов
    data.place = newPlace
local context = {
end
cache = {},
}


-- данные в простом формате, согласованном с модулями формирования библиографического описания
---@param entityId string
local data = {};
---@param lang string
---@param providedLabel string | nil
---@param options options
---@return string
local function getPersonNameAsLabel( entityId, lang, providedLabel, options )
    -- would custom label provided we don't need to check entity at all
    if not isEmpty( providedLabel ) then
        return options.format( providedLabel )
    end
 
    if lang == 'mul' then
        lang = i18nDefaultLanguage
    end
 
    ---@type string | nil
    local personName = getLabel( entityId, lang )
 
    if isEmpty( personName ) then
        return '\'\'(not translated to ' .. lang .. ')\'\''
    end
 
    if not isInstanceOf( entityId, 'Q5' ) then
        return personName
    end
 
    return options.format( personName )
end
 
---@param entityId string
---@param lang string
---@param customLabel string | nil
---@param options options
---@return string
local function getPersonNameAsWikitext( entityId, lang, customLabel, options )
    local personName = getPersonNameAsLabel( entityId, lang, customLabel, options )
    local link = getElementLink( entityId, lang )
    return wrapInUrl( link, personName )
end
 
---@param value value
---@param lang string
---@param options options
---@return string
local function getPeopleAsWikitext( value, lang, options )
    if type( value ) == 'string' then
        return options.format( value )
    elseif type( value ) == 'table' then
        if value.id then
            -- this is link
            if options.preferids then
                return tostring( value.id )
            else
                if options.nolinks then
                    return getPersonNameAsLabel( value.id, lang, value.label, options )
                else
                    return getPersonNameAsWikitext( value.id, lang, value.label, options )
                end
            end
        end
 
        local maxAuthors = 10 -- need some restrictions, as some publications have enormous amount of authors (e.g. 115 authors of Q68951544)
        local resultList = {}
        for _, tableValue in pairs( value ) do
            local nextWikitext = getPeopleAsWikitext( tableValue, lang, options )
            if not isEmpty( nextWikitext ) then
                table.insert( resultList, nextWikitext )
                if #resultList == maxAuthors + 1 then
                    -- keep one more to indicate that there are too many
                    break
                end
            end
        end
 
        local resultWikitext = ''
        for i, wikitext in pairs( resultList ) do
            if i == maxAuthors + 1 then
                resultWikitext = resultWikitext .. ( i18nEtAl[ lang ] or i18nEtAlDefault )
                break
            end
            if i ~= 1 then
                resultWikitext = resultWikitext .. ', '
            end
            resultWikitext = resultWikitext .. wikitext
        end
 
        return resultWikitext
    end
 
    return '' -- options.format( '(unknown type)' )
end
 
---@param lang string
---@param data source
---@return string
local function generateAuthorLinks( lang, data )
    local result = ''
    if data.author then
        result = getPeopleAsWikitext( data.author, lang, options_commas_authors )
        result = '<i class="wef_low_priority_links">' .. result .. '</i> '
    end
    return result
end
 
---@param lang string
---@param data source
---@param conjunction string
---@param propertyName string
---@param urlPropertyName string?
---@return string
local function appendProperty( lang, data, conjunction, propertyName, urlPropertyName )
    if not data[ propertyName ] then
        return ''
    end
 
    local out
    if urlPropertyName and data[ urlPropertyName ] then
        out = wrapInUrl( data[ urlPropertyName ], asString( lang, data[ propertyName ], options_commas_nolinks ) )
    else
        out = asString( lang, data[ propertyName ], options_commas )
    end
 
    if not out or out == '' then
        return ''
    end
 
    return conjunction .. out
end
 
---@param lang string
---@param data source
---@return string
local function appendTitle( lang, data )
    local conjunction = ''
    local result = ''
 
    if data.part then
        result = result .. appendProperty( lang, data, '', 'part', 'parturl' )
        conjunction = ' // '
    end
 
    return result .. appendProperty( lang, data, conjunction, 'title', 'url' )
end
 
---@param lang string
---@return string
local function appendLanguage( lang )
    if lang == i18nDefaultLanguage then
        return ''
    end
 
    ---@type { getRefHtml: ( fun( lang: string ): string ), list_ref: ( fun( frame: frame ): string ) }
    local langs = require( 'Module:Languages' )
    return langs.list_ref( p.currentFrame:newChild{ args = { lang } } )
end
 
---@param lang string
---@param data source
---@return string
local function appendSubtitle( lang, data )
    return appendProperty( lang, data, ': ', 'subtitle', nil )
end
 
---@param lang string
---@param data source
---@return string
local function appendOriginalTitle( lang, data )
    return appendProperty( lang, data, ' = ', 'originaltitle', nil )
end
 
---@param lang string
---@param data source
---@return string
local function appendPublication( lang, data )
    if not data.publication then
        return ''
    end
 
    local result = ' // ' .. asString( lang, data.publication.title, options_commas_it_short )
    if data.publication.subtitle and data.publication.subtitle ~= '' then
        result = result .. ': ' .. asString( lang, data.publication.subtitle, options_commas_it_short )
    end
 
    return result
end
 
---@param lang string
---@param data source
---@return string
local function appendEditor( lang, data )
    if not data.editor and not data.translator then
        return ''
    end
 
    local result = ' / '
    if data.editor then
        local prefix = i18nEditors[ lang ] or i18nEditors[ i18nDefaultLanguage ]
        result = result .. prefix .. getPeopleAsWikitext( data.editor, lang, options_commas_responsible )
        if data.translator then
            result = result .. ', '
        end
    end
    if data.translator then
        local prefix = i18nTranslators[ lang ] or i18nTranslators[ i18nDefaultLanguage ]
        result = result .. prefix .. getPeopleAsWikitext( data.translator, lang, options_commas_responsible )
    end
 
    return result
end
 
---@param lang string
---@param data source
local function appendEdition( lang, data )
    return appendProperty( lang, data, ' — ', 'edition', nil )
end
 
---@param lang string
---@param data source
---@return string
local function appendPublicationData( lang, data )
    if not data.place and not data.publisher and not data.year then
        return ''
    end
 
    local result = ' — '
    if data.place then
        result = result .. asString( lang, data.place, options_commas_short )
        if data.publisher or data.year then
            result = result .. ': '
        end
    end
    if data.publisher then
        result = result .. asString( lang, data.publisher, options_commas_short )
        if data.year then
            result = result .. ', '
        end
    end
    if data.year then
        result = result .. asString( lang, data.year, options_commas )
    end
    result = result .. '.'
 
    return result
end
 
---@param lang string
---@param data source
---@return string
local function appendVolumeAndIssue( lang, data )
    if not data.volume and not data.issue then
        return ''
    end
 
    local result = ' — '
    local letter_vol = i18nVolume[ lang ] or i18nVolume[ i18nDefaultLanguage ]
    local letter_iss = i18nIssue[ lang ] or i18nIssue[ i18nDefaultLanguage ]
    if data.volume then
        result = result .. appendProperty( lang, data, letter_vol .. '&nbsp;', 'volume', nil )
        result = result ..appendProperty( lang, data, ', ' .. letter_iss .. '&nbsp;', 'issue', nil )
    else
        result = result .. appendProperty( lang, data, letter_iss .. '&nbsp;', 'issue', nil )
    end
    result = result .. '.'
 
    return result
end
 
---@param lang string
---@param data source
---@return string
local function appendPages( lang, data )
    if not data.pages then
        return ''
    end
 
    local letter = i18nPages[ lang ] or i18nPages[ i18nDefaultLanguage ]
    local strPages = asString( lang, data.pages, options_commas )
    strPages = mw.ustring.gsub( strPages, '[-—]', '—' )
    return ' — ' .. letter .. '&nbsp;' .. strPages .. '.'
end
 
---@param lang string
---@param data source
---@return string
local function appendNumberOfPages( lang, data )
    if not data.numberOfPages then
        return ''
    end
 
    local letter = i18nNumberOfPages[ lang ] or i18nNumberOfPages[ i18nDefaultLanguage ]
    return appendProperty( lang, data, ' — ', 'numberOfPages', nil ) .. '&nbsp;' .. letter
end
 
---@param lang string
---@param data source
---@return string
local function appendBookSeries( lang, data )
    if not data.bookSeries then
        return ''
    end
 
    local result = appendProperty( lang, data, ' — (', 'bookSeries', nil )
    if data.bookSeriesVolume or data.bookSeriesIssue then
        result = result .. '; '
        local letter_vol = i18nVolume[ lang ] or i18nVolume[ i18nDefaultLanguage ]
        local letter_iss = i18nIssue[ lang ] or i18nIssue[ i18nDefaultLanguage ]
        if data.bookSeriesVolume then
            result = result .. appendProperty( lang, data, letter_vol .. '&nbsp;', 'bookSeriesVolume', nil )
            result = result .. appendProperty( lang, data, ', ' .. letter_iss .. '&nbsp;', 'bookSeriesIssue', nil )
        else
            result = result .. appendProperty( lang, data, letter_iss .. '&nbsp;', 'bookSeriesIssue', nil )
        end
    end
    result = result .. ')'
 
    return result
end
 
---@param lang string
---@param data source
---@return string
local function appendTirage( lang, data )
    if not data.tirage then
        return ''
    end
 
    local tirageTemplate = i18nTirage[ lang ] or i18nTirage[ i18nDefaultLanguage ]
    ---@type options
    local optionsTirage = {
        separator = '; ',
        conjunction = '; ',
        format = function( _data ) return tostring( mw.ustring.format( tirageTemplate, _data ) ) end,
        short = false,
        nolinks = false,
        preferids = false,
    }
    return ' — ' .. asString( lang, data.tirage, optionsTirage )
end
 
---@param lang string
---@param value string | nil
---@param options options
---@param prefix string?
---@return string
local function appendIdentifier( lang, value, options, prefix )
    if not value then
        return ''
    end
 
    return ' — ' .. ( prefix or '' ) .. asString( lang, value, options )
end
 
---@param result string
---@param lang string
---@param data source
---@return string
local function wrapSourceId( result, lang, data )
    if not data.sourceId then
        return result
    end
 
    local citeType = data.type and asString( lang, data.type, options_citetypes ) or 'citetype_unknown'
    return '<span class="wikidata_cite ' .. citeType .. '" data-entity-id="' .. data.sourceId .. '">' .. result .. '</span>'
end
 
---@param data source
---@return string
local function appendAccessDate( data )
    if not data.accessdate then
        return ''
    end
 
    local date = getSingle( data.accessdate )
    local pattern = "(%-?%d+)%-(%d+)%-(%d+)T"
    local y, m, d = mw.ustring.match( date, pattern )
    y, m, d = tonumber( y ), tonumber( m ), tonumber( d )
    local date_str = ( d > 0 and ' ' .. tostring( d ) or '' )
            .. ( m > 0 and ' ' .. monthGen[ m ] or '' )
            .. ( y > 0 and ' ' .. tostring( y ) or '' )
 
 
    return " <small>Проверено" .. date_str .. ".</small>"
end
 
---@param data source
---@param lang string
---@return void
local function populateUrl( data, lang )
    if data.sourceId and not data.url then
        local sitelink = getSitelink( data.sourceId, lang .. 'wikisource' )
        if sitelink then
            data.url = ':' .. lang .. ':s:' .. sitelink
        end
    end
end
 
---@param data source
---@return void
local function populateYear( data )
    if not data.year and data.dateOfPublication then
        local date = getSingle( data.dateOfPublication )
        data.year = mw.ustring.sub( date, 2, 5 )
    end
    if not data.year and data.dateOfCreation then
        local date = getSingle( data.dateOfCreation )
        data.year = mw.ustring.sub( date, 2, 5 )
    end
end
 
---@param data source
---@return void
local function populateTitle( data )
    data.title = data.title or getSingle( data.url )
end
 
---@param data source
---@return string
local function renderSource( data )
    local lang = getLangCode( data.lang ) or i18nDefaultLanguage
 
    preprocessPlace( data, lang )
    populateUrl( data, lang )
    populateTitle( data )
    if not data.title then
        return ''
    end
 
    populateYear( data )
 
    local result = generateAuthorLinks( lang, data )
    result = result .. appendTitle( lang, data )
    result = result .. appendLanguage( lang )
    result = result .. appendSubtitle( lang, data )
    result = result .. appendOriginalTitle( lang, data )
    result = result .. appendPublication( lang, data )
 
    result = result .. '<span class="wef_low_priority_links">'
    result = result .. appendEditor( lang, data ) -- Might take current editor instead of actual. Use with caution
    result = result .. appendEdition( lang, data )
    result = result .. appendPublicationData( lang, data )
    result = result .. appendVolumeAndIssue( lang, data )
    result = result .. appendPages( lang, data )
    result = result .. appendNumberOfPages( lang, data )
    result = result .. appendBookSeries( lang, data )
    result = result .. appendTirage( lang, data )
 
    result = result .. appendIdentifier( lang, data.isbn, options_commas, 'ISBN ' )
    result = result .. appendIdentifier( lang, data.issn, options_issn, 'ISSN ' )
    result = result .. appendIdentifier( lang, data.doi, options_doi, nil )
    result = result .. appendIdentifier( lang, data.pmid, options_pmid, nil )
    result = result .. appendIdentifier( lang, data.arxiv, options_arxiv, nil )
    result = result .. appendAccessDate( data )
    result = result .. '</span>'
 
    return wrapSourceId( result, lang, data )
end
 
---@param data source Данные в простом формате, согласованном с модулями формирования библиографического описания
---@param snaks snaks
---@return string | nil
local function renderReferenceImpl( data, snaks )
    -- не показывать источники с "импортировано из"
    if snaks.P143 then
        return nil
    end


     -- забрать данные из reference
     -- забрать данные из reference
     populateDataFromClaims( context, nil, reference.snaks, data )
     populateDataFromSnaks( snaks or {}, data, PROPERTY_MAP )
    data.sourceId = getSingle( data.sourceId )
    populateDataFromEntity( data.sourceId, data, PROPERTY_MAP )
 
    expandSpecials( data )
    populateSourceDataImpl( data.sourceId, data, PROPERTY_MAP )
 
    expandPublication( data )
    expandBookSeries( data )


-- update ref name with ref-specific properties
    if next( data ) == nil then
if ( data.code ) then
        return nil
if ( data.part ) then data.code = data.code .. '-' .. getSingle( data.part ) end
    end
if ( data.pages ) then data.code = data.code .. '-' .. getSingle( data.pages ) end
if ( data.volume ) then data.code = data.code .. '-' .. getSingle( data.volume ) end
if ( data.issue ) then data.code = data.code .. '-' .. getSingle( data.issue ) end
if ( data.url ) then data.code = data.code .. '-' .. getSingle( data.url ) end
end


expandSpecials( context, currentEntity, reference, data );
    local rendered = renderSource( data )
    if mw.ustring.len( rendered ) == 0 then
        return nil
    end


local sourceEntity = nil;
    if data.ref then
if ( data.sourceId ) then
        local anchorValue = 'CITEREF' .. data.ref .. ( coalesce( { data[ 'ref-year' ], data.year } ) or '' )
sourceEntity = getEntity( context, data.sourceId );
        rendered = '<span class="citation" id="' .. mw.uri.anchorEncode( anchorValue ) .. '">' .. rendered .. '</span>'
if ( sourceEntity ) then
    end
populateSourceDataImpl( context, sourceEntity, data );
end
end


if ( data.publication ) then
    return rendered
expandPublication( context, sourceEntity, data );
end
end


expandBookSeries( context, data );
---@param frame frame
---@param currentEntityId string | { id: string }
---@param reference table{ snaks: snaks }
---@return string | nil
function p.renderSource( frame, currentEntityId, reference )
    reference = reference or { snaks = {} }
    p.currentFrame = frame


if ( next( data ) == nil ) then
    local data = getFilledArgs( frame.args or {} )
return nil;
    populateDataFromSnaks( reference.snaks, data, PROPERTY_MAP )
end
    data.sourceId = getSingle( data.sourceId )


local rendered;
    if not currentEntityId then
if ( p.short ) then
    data.entityId = mw.wikibase.getEntityIdForCurrentPage()
rendered = renderShortReference( data );
    elseif type( currentEntityId ) == 'string' then
if ( mw.ustring.len( rendered.text ) == 0 ) then
        data.entityId = currentEntityId
return nil;
    elseif type( currentEntityId ) == 'table' and currentEntityId.id then
end
        data.entityId = currentEntityId.id
    end


else
    ---@type string
rendered = renderSource( context, data );
    local rendered = renderReferenceImpl( data, reference.snaks or {} )
if ( mw.ustring.len( rendered.text ) == 0 ) then
    if not rendered then
return nil;
        return ''
end
    end


if ( refAnchor ) then
    return rendered
local anchorValue = 'CITEREF' .. refAnchor .. ( coalesce( refAnchorYear, data.year ) or '' );
end
rendered.text = '<span class="citation" id="' .. mw.uri.anchorEncode( anchorValue ) .. '">' .. rendered.text .. '</span>';
 
end
 
end
---@param frame frame
---@param currentEntityId string
---@param reference table
---@return string
function p.renderReference( frame, currentEntityId, reference )
    local rendered = p.renderSource( frame, currentEntityId, reference )
    if not rendered or rendered == '' then
        return ''
    end
 
    -- Про выбор алгоритма хеширования см. [[Модуль:Hash]]. Знак подчёркивания в начале позволяет
    -- исключить ошибку, когда имя сноски — чисто числовое значение, каковыми иногда бывают хеши.
    return frame:extensionTag( 'ref', rendered, { name = '_' .. mw.hash.hashValue( 'fnv164', rendered ) } ) .. '[[Category:ЭАНМ:Статьи с источниками из Викиданных]]'
end
 
---@param frame frame
---@return string | nil
function p.testPersonNameToAuthorName( frame )
    return personNameToAuthorName( frame.args[ 1 ] )
end


return rendered;
---@param frame frame
---@return string | nil
function p.testPersonNameToResponsibleName( frame )
    return personNameToResponsibleName( frame.args[ 1 ] )
end
end


return p;
return p