跳转到内容

User:SuperGrey/gadgets/AddArchiveURLs/main.js

维基百科,自由的百科全书
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
/* global mw, OO, $ */
( function () {
	'use strict';

	var MODULES = [
		'mediawiki.api',
		'mediawiki.util',
		'oojs-ui-core',
		'oojs-ui-widgets',
		'oojs-ui-windows',
		'ext.gadget.HanAssist'
	];
	var WAYBACK_AVAILABILITY_API = 'https://archive.org/wayback/available';
	var WAYBACK_CDX_API = 'https://web.archive.org/cdx/search/cdx';
	var WAYBACK_CALENDAR_API = 'https://web.archive.org/__wb/calendarcaptures/2';
	var WAYBACK_CALENDAR_LOOKBACK_YEARS = 10;
	var HTTPS_PROXY_PREFIX = 'https://api.allorigins.win/get?url=';
	var CORS_CHECK_TIMEOUT_MS = 5000;
	// This gadget runs on a Wikipedia page. We treat any failure to fetch
	// example.com from that page, whether caused by CORS or the page CSP, as a
	// signal that the browser session is not ready for this script yet.
	var CORS_CHECK_URL = 'https://example.com/?add-archive-urls-cors-check=1';
	var CHROME_CORS_EXTENSION_URL = 'https://chromewebstore.google.com/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino';
	var FIREFOX_CORS_EXTENSION_URL = 'https://addons.mozilla.org/en-US/firefox/addon/cors-unblock/';
	var DEFAULT_DELAY_MS = 500;
	var DEFAULT_LIVE_TIMEOUT_MS = 10000;
	var DEFAULT_ARCHIVE_TIMEOUT_MS = 5000;
	var DEFAULT_RETRIES = 1;
	var DEFAULT_SUMMARY = 'Add archive-url, archive-date, and url-status to citations';
	var PARAM_ALIASES = {
		url: [ 'url' ],
		'dead-url': [ 'dead-url', 'deadurl' ],
		'archive-url': [ 'archive-url', 'archiveurl' ],
		'archive-date': [ 'archive-date', 'archivedate' ],
		'url-status': [ 'url-status', 'urlstatus' ]
	};
	var DEAD_URL_TO_URL_STATUS = {
		yes: 'dead',
		no: 'live',
		unfit: 'unfit'
	};
	var LIVE_HTTP_STATUSES = {
		401: true,
		403: true,
		405: true,
		429: true
	};
	var RETRYABLE_HTTP_STATUSES = {
		429: true,
		500: true,
		502: true,
		503: true,
		504: true
	};
	var STOP_ERROR_CODE = 'archive-url-stop';
	var TEMPLATE_END_RE = /(\s*)}}$/;
	var ARCHIVE_URL_RE = /^https?:\/\/web\.archive\.org\/web\/(\d{14})(?:[A-Za-z_]+)?\/https?:\/\//i;
	var entityDecoder = document.createElement( 'textarea' );
	var convByVar = fallbackConvByVar;
	var dialogState = {
		windowManager: null,
		dialog: null
	};
	var warningDialogState = {
		windowManager: null,
		dialog: null
	};

	function fallbackConvByVar( variants ) {
		return variants.en || '';
	}

	function t( variants ) {
		return convByVar( variants );
	}

	function tf( variants, replacements ) {
		var text = t( variants );
		Object.keys( replacements || {} ).forEach( function ( key ) {
			text = text.replace( new RegExp( '\\$' + key, 'g' ), replacements[ key ] );
		} );
		return text;
	}

	function applyLocalizedStatics() {
		DEFAULT_SUMMARY = t( {
			en: 'Add archive links to citations',
			hans: '为参考文献补充存档链接',
			hant: '為參考文獻補充存檔連結'
		} ) + ' ([[User:SuperGrey/gadgets/AddArchiveURLs|AddArchiveURLs]])';
		ArchiveCitationsDialog.static.title = t( {
			en: 'Archive all URLs in citations',
			hans: '为参考文献中的所有网址添加存档',
			hant: '為參考文獻中的所有網址加入存檔'
		} );
		ArchiveCitationsDialog.static.actions = [
			{
				action: 'confirm',
				label: t( { en: 'Confirm', hans: '确认', hant: '確認' } ),
				flags: [ 'primary', 'progressive' ]
			},
			{
				action: 'cancel',
				label: t( { en: 'Cancel', zh: '取消' } ),
				flags: 'safe'
			}
		];
	}

	function createStopError() {
		var error = new Error( t( {
			en: 'The archive lookup was stopped.',
			hans: '存档查询已停止。',
			hant: '存檔查詢已停止。'
		} ) );
		error.code = STOP_ERROR_CODE;
		return error;
	}

	function isStopError( error ) {
		return !!( error && error.code === STOP_ERROR_CODE );
	}

	function decodeHtmlEntities( value ) {
		entityDecoder.innerHTML = value;
		return entityDecoder.value;
	}

	function normalizeUrl( value ) {
		var trimmed;
		if ( typeof value !== 'string' ) {
			return null;
		}
		trimmed = decodeHtmlEntities( value.trim() );
		if ( /^https?:\/\//i.test( trimmed ) ) {
			return trimmed;
		}
		return null;
	}

	function buildQueryString( pairs ) {
		return pairs.map( function ( pair ) {
			return encodeURIComponent( pair[ 0 ] ) + '=' + encodeURIComponent( pair[ 1 ] );
		} ).join( '&' );
	}

	function buildWaybackAvailabilityUrl( url ) {
		return WAYBACK_AVAILABILITY_API + '?' + buildQueryString( [
			[ 'url', url ]
		] );
	}

	function buildWaybackCdxUrl( url ) {
		return WAYBACK_CDX_API + '?' + buildQueryString( [
			[ 'url', url ],
			[ 'limit', '1' ],
			[ 'sort', 'reverse' ],
			[ 'filter', 'statuscode:200' ],
			[ 'fl', 'timestamp,original,statuscode' ],
			[ 'output', 'json' ]
		] );
	}

	function buildWaybackCalendarUrl( url, year ) {
		return WAYBACK_CALENDAR_API + '?' + buildQueryString( [
			[ 'url', url ],
			[ 'date', String( year ) ],
			[ 'groupby', 'day' ]
		] );
	}

	function buildWaybackDateLocatorUrl( url, date ) {
		return 'https://web.archive.org/web/' + date + '/' + encodeURI( url );
	}

	function normalizeArchiveSnapshotUrl( url ) {
		var prefix = 'http://web.archive.org/';
		if ( !url ) {
			return null;
		}
		url = String( url ).trim();
		if ( url.indexOf( prefix ) === 0 ) {
			return 'https://web.archive.org/' + url.slice( prefix.length );
		}
		return url;
	}

	function toggleUrlTrailingSlash( url ) {
		var parsed;
		var path;
		try {
			parsed = new URL( url );
		} catch ( error ) {
			return null;
		}
		if ( parsed.search || parsed.hash || parsed.pathname === '/' ) {
			return null;
		}
		path = parsed.pathname;
		parsed.pathname = path.slice( -1 ) === '/' ? path.replace( /\/+$/, '' ) : path + '/';
		return parsed.href;
	}

	function toggleUrlScheme( url ) {
		var parsed;
		try {
			parsed = new URL( url );
		} catch ( error ) {
			return null;
		}
		if ( parsed.protocol === 'https:' ) {
			parsed.protocol = 'http:';
		} else if ( parsed.protocol === 'http:' ) {
			parsed.protocol = 'https:';
		} else {
			return null;
		}
		return parsed.href;
	}

	function buildWaybackLookupVariants( url ) {
		var seen = {};
		var variants = [];
		var trailingSlashVariant;
		var schemeVariant;
		var schemeSlashVariant;
		function addVariant( value ) {
			if ( value && !seen[ value ] ) {
				seen[ value ] = true;
				variants.push( value );
			}
		}

		addVariant( url );
		trailingSlashVariant = toggleUrlTrailingSlash( url );
		addVariant( trailingSlashVariant );

		schemeVariant = toggleUrlScheme( url );
		addVariant( schemeVariant );
		if ( schemeVariant ) {
			schemeSlashVariant = toggleUrlTrailingSlash( schemeVariant );
			addVariant( schemeSlashVariant );
		}
		return variants;
	}

	function isHttpUrl( url ) {
		return /^http:\/\//i.test( url );
	}

	function mapDeadUrlToUrlStatus( value ) {
		var normalized = ( value || '' ).trim().toLowerCase();
		if ( DEAD_URL_TO_URL_STATUS[ normalized ] !== undefined ) {
			return DEAD_URL_TO_URL_STATUS[ normalized ];
		}
		return normalized || null;
	}

	function filterTemplateParams( templateText, shouldRemove ) {
		var body;
		var parts;
		var filteredParts;

		if ( templateText.slice( 0, 2 ) !== '{{' || templateText.slice( -2 ) !== '}}' ) {
			return templateText;
		}

		body = templateText.slice( 2, -2 );
		parts = splitTopLevel( body, '|' );
		if ( !parts.length ) {
			return templateText;
		}

		filteredParts = [ parts[ 0 ] ];
		parts.slice( 1 ).forEach( function ( part ) {
			var equalsIndex = findTopLevelChar( part, '=' );
			var key;
			var value;
			if ( equalsIndex === -1 ) {
				filteredParts.push( part );
				return;
			}
			key = part.slice( 0, equalsIndex ).trim().toLowerCase();
			value = part.slice( equalsIndex + 1 ).trim();
			if ( shouldRemove( key, value ) ) {
				return;
			}
			filteredParts.push( part );
		} );

		return '{{' + filteredParts.join( '|' ) + '}}';
	}

	function stripParamAliases( templateText, canonicalName ) {
		var aliases = {};
		PARAM_ALIASES[ canonicalName ].forEach( function ( alias ) {
			aliases[ alias.toLowerCase() ] = true;
		} );
		return filterTemplateParams( templateText, function ( key ) {
			return !!aliases[ key ];
		} );
	}

	function isFilledParamValue( value ) {
		return value !== undefined && value !== null && value.trim() !== '';
	}

	function stripBlankParamAliases( templateText, canonicalName ) {
		var aliases = {};
		PARAM_ALIASES[ canonicalName ].forEach( function ( alias ) {
			aliases[ alias.toLowerCase() ] = true;
		} );
		return filterTemplateParams( templateText, function ( key, value ) {
			return !!aliases[ key ] && !isFilledParamValue( value );
		} );
	}

	function stripDeadUrlParam( templateText ) {
		return stripParamAliases( templateText, 'dead-url' );
	}

	function extractArchiveDate( archiveUrl ) {
		var match = archiveUrl && archiveUrl.match( ARCHIVE_URL_RE );
		var dateText;
		if ( !match ) {
			return null;
		}
		dateText = match[ 1 ].slice( 0, 8 );
		return [
			dateText.slice( 0, 4 ),
			dateText.slice( 4, 6 ),
			dateText.slice( 6, 8 )
		].join( '-' );
	}

	function parseWaybackAvailability( data ) {
		var closest = data && data.archived_snapshots && data.archived_snapshots.closest;
		var archiveUrl;
		if ( !closest || !closest.available || typeof closest.url !== 'string' ) {
			return null;
		}
		if ( closest.status !== undefined && String( closest.status ) !== '200' ) {
			return null;
		}
		archiveUrl = normalizeArchiveSnapshotUrl( closest.url );
		return archiveUrl && ARCHIVE_URL_RE.test( archiveUrl ) ? archiveUrl : null;
	}

	function parseWaybackCdx( data ) {
		var headers;
		var row;
		var record = {};
		var archiveUrl;
		if ( !Array.isArray( data ) || data.length < 2 ) {
			return null;
		}
		headers = data[ 0 ];
		row = data[ 1 ];
		if ( !Array.isArray( headers ) || !Array.isArray( row ) ) {
			return null;
		}
		headers.forEach( function ( key, index ) {
			record[ String( key ) ] = row[ index ];
		} );
		if ( String( record.statuscode ) !== '200' || typeof record.timestamp !== 'string' || typeof record.original !== 'string' ) {
			return null;
		}
		archiveUrl = 'https://web.archive.org/web/' + record.timestamp + '/' + record.original;
		return ARCHIVE_URL_RE.test( archiveUrl ) ? archiveUrl : null;
	}

	function parseWaybackCalendarDates( data, year ) {
		var dates = {};
		if ( !data || !Array.isArray( data.items ) ) {
			return [];
		}
		data.items.forEach( function ( item ) {
			var monthDay;
			var dateText;
			var parsedDate;
			if ( !Array.isArray( item ) || item.length < 2 || String( item[ 1 ] ) !== '200' ) {
				return;
			}
			monthDay = String( parseInt( item[ 0 ], 10 ) );
			if ( monthDay === 'NaN' ) {
				return;
			}
			while ( monthDay.length < 4 ) {
				monthDay = '0' + monthDay;
			}
			dateText = String( year ) + monthDay;
			parsedDate = new Date(
				parseInt( dateText.slice( 0, 4 ), 10 ),
				parseInt( dateText.slice( 4, 6 ), 10 ) - 1,
				parseInt( dateText.slice( 6, 8 ), 10 )
			);
			if (
				parsedDate.getFullYear() === parseInt( dateText.slice( 0, 4 ), 10 ) &&
				parsedDate.getMonth() === parseInt( dateText.slice( 4, 6 ), 10 ) - 1 &&
				parsedDate.getDate() === parseInt( dateText.slice( 6, 8 ), 10 )
			) {
				dates[ dateText ] = true;
			}
		} );
		return Object.keys( dates ).sort().reverse();
	}

	function padDateNumber( value, width ) {
		var text = String( value );
		while ( text.length < width ) {
			text = '0' + text;
		}
		return text;
	}

	function dateOnly( date ) {
		return new Date( date.getFullYear(), date.getMonth(), date.getDate() );
	}

	function addDays( date, days ) {
		var result = dateOnly( date );
		result.setDate( result.getDate() + days );
		return result;
	}

	function formatDateText( date ) {
		return [
			String( date.getFullYear() ),
			padDateNumber( date.getMonth() + 1, 2 ),
			padDateNumber( date.getDate(), 2 )
		].join( '' );
	}

	function buildDescendingYearRange( newestYear, oldestYear ) {
		var years = [];
		var year;
		for ( year = newestYear; year >= oldestYear; year -= 1 ) {
			years.push( year );
		}
		return years;
	}

	function filterWaybackCalendarDates( dates, startDateText, endDateText ) {
		if ( !startDateText && !endDateText ) {
			return dates;
		}
		return dates.filter( function ( dateText ) {
			return ( !startDateText || dateText >= startDateText ) &&
				( !endDateText || dateText <= endDateText );
		} );
	}

	function makeWaybackLookupCache() {
		return {
			calendarResults: {}
		};
	}

	function describeFetchResultFailure( result ) {
		if ( result && result.error ) {
			return result.error;
		}
		if ( result && result.status !== null ) {
			return 'HTTP ' + result.status;
		}
		return 'network error';
	}

	function shouldStopWaybackCalendarScan( result ) {
		if ( !result || result.status === null ) {
			return true;
		}
		return !!RETRYABLE_HTTP_STATUSES[ result.status ] || !!( result.error && !result.data );
	}

	function getCorsCheckUrl() {
		return CORS_CHECK_URL + '&ts=' + Date.now();
	}

	function findTemplateSpans( text ) {
		var spans = [];
		var stack = [];
		var index = 0;
		var limit = text.length - 1;
		var commentEnd;
		var pair;
		while ( index < limit ) {
			if ( text.slice( index, index + 4 ) === '<!--' ) {
				commentEnd = text.indexOf( '-->', index + 4 );
				if ( commentEnd === -1 ) {
					break;
				}
				index = commentEnd + 3;
				continue;
			}
			pair = text.slice( index, index + 2 );
			if ( pair === '{{' ) {
				stack.push( index );
				index += 2;
				continue;
			}
			if ( pair === '}}' && stack.length ) {
				spans.push( [ stack.pop(), index + 2 ] );
				index += 2;
				continue;
			}
			index += 1;
		}
		return spans;
	}

	function splitTopLevel( text, delimiter ) {
		var parts = [];
		var start = 0;
		var curlyDepth = 0;
		var squareDepth = 0;
		var index = 0;
		var commentEnd;
		while ( index < text.length ) {
			if ( text.slice( index, index + 4 ) === '<!--' ) {
				commentEnd = text.indexOf( '-->', index + 4 );
				if ( commentEnd === -1 ) {
					break;
				}
				index = commentEnd + 3;
				continue;
			}
			if ( text.slice( index, index + 2 ) === '{{' ) {
				curlyDepth += 1;
				index += 2;
				continue;
			}
			if ( text.slice( index, index + 2 ) === '}}' && curlyDepth ) {
				curlyDepth -= 1;
				index += 2;
				continue;
			}
			if ( text.slice( index, index + 2 ) === '[[' ) {
				squareDepth += 1;
				index += 2;
				continue;
			}
			if ( text.slice( index, index + 2 ) === ']]' && squareDepth ) {
				squareDepth -= 1;
				index += 2;
				continue;
			}
			if ( text.charAt( index ) === delimiter && curlyDepth === 0 && squareDepth === 0 ) {
				parts.push( text.slice( start, index ) );
				start = index + 1;
			}
			index += 1;
		}
		parts.push( text.slice( start ) );
		return parts;
	}

	function findTopLevelChar( text, target ) {
		var curlyDepth = 0;
		var squareDepth = 0;
		var index = 0;
		var commentEnd;
		while ( index < text.length ) {
			if ( text.slice( index, index + 4 ) === '<!--' ) {
				commentEnd = text.indexOf( '-->', index + 4 );
				if ( commentEnd === -1 ) {
					return -1;
				}
				index = commentEnd + 3;
				continue;
			}
			if ( text.slice( index, index + 2 ) === '{{' ) {
				curlyDepth += 1;
				index += 2;
				continue;
			}
			if ( text.slice( index, index + 2 ) === '}}' && curlyDepth ) {
				curlyDepth -= 1;
				index += 2;
				continue;
			}
			if ( text.slice( index, index + 2 ) === '[[' ) {
				squareDepth += 1;
				index += 2;
				continue;
			}
			if ( text.slice( index, index + 2 ) === ']]' && squareDepth ) {
				squareDepth -= 1;
				index += 2;
				continue;
			}
			if ( text.charAt( index ) === target && curlyDepth === 0 && squareDepth === 0 ) {
				return index;
			}
			index += 1;
		}
		return -1;
	}

	function parseTemplate( templateText ) {
		var body;
		var parts;
		var name;
		var positionalParams = [];
		var params = {};

		if ( templateText.slice( 0, 2 ) !== '{{' || templateText.slice( -2 ) !== '}}' ) {
			return null;
		}

		body = templateText.slice( 2, -2 );
		parts = splitTopLevel( body, '|' );
		if ( !parts.length ) {
			return null;
		}

		name = parts[ 0 ].trim();
		parts.slice( 1 ).forEach( function ( part ) {
			var equalsIndex = findTopLevelChar( part, '=' );
			var key;
			var value;
			if ( equalsIndex === -1 ) {
				value = part.trim();
				if ( value ) {
					positionalParams.push( value );
				}
				return;
			}
			key = part.slice( 0, equalsIndex ).trim().toLowerCase();
			value = part.slice( equalsIndex + 1 ).trim();
			if ( key && params[ key ] === undefined ) {
				params[ key ] = value;
			}
		} );

		return {
			name: name,
			positionalParams: positionalParams,
			params: params
		};
	}

	function hasParamEntry( params, canonicalName ) {
		return PARAM_ALIASES[ canonicalName ].some( function ( alias ) {
			return params[ alias ] !== undefined;
		} );
	}

	function hasParam( params, canonicalName ) {
		return PARAM_ALIASES[ canonicalName ].some( function ( alias ) {
			return isFilledParamValue( params[ alias ] );
		} );
	}

	function getParam( params, canonicalName ) {
		var value;
		PARAM_ALIASES[ canonicalName ].some( function ( alias ) {
			if ( isFilledParamValue( params[ alias ] ) ) {
				value = params[ alias ];
				return true;
			}
			return false;
		} );
		return value;
	}

	function isCitationTemplate( name, positionalParams ) {
		var trimmed = name.trim();
		var normalized = trimmed.toLowerCase();
		var invokeEquivalent;
		var moduleName;
		var functionName;
		if ( normalized.indexOf( 'cite ' ) === 0 || normalized === 'citation' ) {
			return true;
		}
		if ( trimmed.indexOf( '#invoke:' ) !== 0 ) {
			return false;
		}
		moduleName = trimmed.slice( '#invoke:'.length ).trim().toLowerCase();
		if ( moduleName !== 'cite' || !positionalParams.length ) {
			return false;
		}
		functionName = positionalParams[ 0 ].trim().toLowerCase();
		if ( !functionName ) {
			return false;
		}
		invokeEquivalent = functionName === 'citation' ? 'citation' : 'cite ' + functionName;
		return invokeEquivalent.indexOf( 'cite ' ) === 0 || invokeEquivalent === 'citation';
	}

	function collectUniqueUrls( text, stats ) {
		var requirementsByUrl = {};
		var existing;
		findTemplateSpans( text ).forEach( function ( span ) {
			var parsed = parseTemplate( text.slice( span[ 0 ], span[ 1 ] ) );
			var url;
			if ( !parsed || !isCitationTemplate( parsed.name, parsed.positionalParams ) ) {
				return;
			}
			stats.citationTemplates += 1;
			url = normalizeUrl( getParam( parsed.params, 'url' ) );
			if ( !url ) {
				stats.skippedWithoutUrl += 1;
				return;
			}
			stats.citationTemplatesWithUrl += 1;
			if (
				( hasParam( parsed.params, 'dead-url' ) || hasParam( parsed.params, 'url-status' ) ) &&
				hasParam( parsed.params, 'archive-url' ) &&
				hasParam( parsed.params, 'archive-date' )
			) {
				stats.skippedWithExistingFields += 1;
				return;
			}
			existing = requirementsByUrl[ url ] || {
				needLiveCheck: false,
				needArchiveLookup: false
			};
			requirementsByUrl[ url ] = {
				needLiveCheck: existing.needLiveCheck || ( !hasParam( parsed.params, 'dead-url' ) && !hasParam( parsed.params, 'url-status' ) ),
				needArchiveLookup: existing.needArchiveLookup || !hasParam( parsed.params, 'archive-url' )
			};
		} );
		return requirementsByUrl;
	}

	function buildAppendix( templateText, additions ) {
		var match;
		var trailingWhitespace;
		var insertAt;
		var multiline;
		var indentMatches;
		var indent;
		var appendix;

		if ( !additions.length ) {
			return templateText;
		}

		match = templateText.match( TEMPLATE_END_RE );
		if ( !match ) {
			return templateText;
		}

		trailingWhitespace = match[ 1 ];
		insertAt = templateText.length - trailingWhitespace.length - 2;
		multiline = templateText.indexOf( '\n' ) !== -1;

		if ( multiline ) {
			indentMatches = templateText.match( /\n([ \t]*)\|/g ) || [];
			indent = '';
			if ( indentMatches.length ) {
				indent = indentMatches[ indentMatches.length - 1 ].replace( /\n/, '' ).replace( /\|$/, '' );
			}
			appendix = additions.map( function ( addition ) {
				return '\n' + indent + '|' + addition.name + '=' + addition.value;
			} ).join( '' );
		} else {
			appendix = additions.map( function ( addition ) {
				return ' |' + addition.name + '=' + addition.value;
			} ).join( '' );
		}

		return templateText.slice( 0, insertAt ) + appendix + trailingWhitespace + '}}';
	}

	function filterOverlappingUpdates( updates ) {
		var filtered = [];
		var currentEnd = -1;
		updates.sort( function ( a, b ) {
			if ( a.start !== b.start ) {
				return a.start - b.start;
			}
			return a.end - b.end;
		} ).forEach( function ( update ) {
			if ( update.start < currentEnd ) {
				return;
			}
			filtered.push( update );
			currentEnd = update.end;
		} );
		return filtered;
	}

	function buildUpdates( text, metadataByUrl, stats ) {
		var updates = [];
		findTemplateSpans( text ).forEach( function ( span ) {
			var originalTemplateText = text.slice( span[ 0 ], span[ 1 ] );
			var templateText = originalTemplateText;
			var parsed = parseTemplate( templateText );
			var url;
			var metadata;
			var existingArchiveUrl;
			var derivedArchiveDate;
			var hasDeadUrl = false;
			var hasDeadUrlEntry = false;
			var hasUrlStatus = false;
			var mappedUrlStatus;
			var additions = [];
			var additionNames = {};
			var replacement;

			if ( !parsed || !isCitationTemplate( parsed.name, parsed.positionalParams ) ) {
				return;
			}
			hasDeadUrl = hasParam( parsed.params, 'dead-url' );
			hasDeadUrlEntry = hasParamEntry( parsed.params, 'dead-url' );
			hasUrlStatus = hasParam( parsed.params, 'url-status' );
			if (
				!hasDeadUrlEntry &&
				hasUrlStatus &&
				hasParam( parsed.params, 'archive-url' ) &&
				hasParam( parsed.params, 'archive-date' )
			) {
				return;
			}

			url = normalizeUrl( getParam( parsed.params, 'url' ) );
			if ( !url ) {
				return;
			}

			metadata = metadataByUrl[ url ];

			existingArchiveUrl = normalizeUrl( getParam( parsed.params, 'archive-url' ) );
			derivedArchiveDate = extractArchiveDate( existingArchiveUrl );

			if ( !hasUrlStatus ) {
				if ( hasDeadUrl ) {
					mappedUrlStatus = mapDeadUrlToUrlStatus( getParam( parsed.params, 'dead-url' ) );
					if ( mappedUrlStatus ) {
						additions.push( { name: 'url-status', value: mappedUrlStatus } );
					}
				} else if ( metadata && metadata.urlStatus ) {
					additions.push( { name: 'url-status', value: metadata.urlStatus } );
				}
			}
			if ( !hasParam( parsed.params, 'archive-url' ) && metadata && metadata.archiveUrl ) {
				additions.push( { name: 'archive-url', value: metadata.archiveUrl } );
			}
			if ( !hasParam( parsed.params, 'archive-date' ) && ( derivedArchiveDate || ( metadata && metadata.archiveDate ) ) ) {
				additions.push( {
					name: 'archive-date',
					value: derivedArchiveDate || metadata.archiveDate
				} );
			}

			if ( !additions.length && !hasDeadUrlEntry ) {
				return;
			}
			if ( !hasParam( parsed.params, 'archive-url' ) && ( !metadata || !metadata.archiveUrl ) ) {
				stats.templatesWithoutArchiveHit += 1;
			}

			additions.forEach( function ( addition ) {
				additionNames[ addition.name ] = true;
			} );
			if ( additionNames[ 'url-status' ] ) {
				templateText = stripBlankParamAliases( templateText, 'url-status' );
			}
			if ( additionNames[ 'archive-url' ] ) {
				templateText = stripBlankParamAliases( templateText, 'archive-url' );
			}
			if ( additionNames[ 'archive-date' ] ) {
				templateText = stripBlankParamAliases( templateText, 'archive-date' );
			}
			if ( hasDeadUrlEntry ) {
				templateText = stripDeadUrlParam( templateText );
			}
			replacement = buildAppendix( templateText, additions );
			if ( replacement === originalTemplateText ) {
				return;
			}

			updates.push( {
				start: span[ 0 ],
				end: span[ 1 ],
				replacement: replacement
			} );
			stats.updatedTemplates += 1;
		} );
		return filterOverlappingUpdates( updates );
	}

	function applyUpdates( text, updates ) {
		var parts = [];
		var cursor = 0;
		if ( !updates.length ) {
			return text;
		}
		updates.forEach( function ( update ) {
			parts.push( text.slice( cursor, update.start ) );
			parts.push( update.replacement );
			cursor = update.end;
		} );
		parts.push( text.slice( cursor ) );
		return parts.join( '' );
	}

	function makeStats() {
		return {
			citationTemplates: 0,
			citationTemplatesWithUrl: 0,
			skippedWithoutUrl: 0,
			skippedWithExistingFields: 0,
			updatedTemplates: 0,
			templatesWithoutArchiveHit: 0
		};
	}

	function ArchiveCitationsDialog( config ) {
		this.pageTitle = config.pageTitle;
		this.api = new mw.Api();
		this.currentApiRequest = null;
		this.currentFetchController = null;
		this.currentThrottleTimeout = null;
		this.currentThrottleReject = null;
		this.stopRequested = false;
		this.isRunning = false;
		this.lastExternalRequestFinishedAt = 0;
		this.logLines = [];
		ArchiveCitationsDialog.super.call( this, config );
	}

	OO.inheritClass( ArchiveCitationsDialog, OO.ui.ProcessDialog );

	ArchiveCitationsDialog.static.name = 'archiveCitationsDialog';
	ArchiveCitationsDialog.static.title = 'Archive all URLs in citations';
	ArchiveCitationsDialog.static.actions = [
		{ action: 'confirm', label: 'Confirm', flags: [ 'primary', 'progressive' ] },
		{ action: 'cancel', label: 'Cancel', flags: 'safe' }
	];

	ArchiveCitationsDialog.prototype.initialize = function () {
		var hasUnsavedChanges = mw.config.get( 'wgAction' ) === 'edit';

		ArchiveCitationsDialog.super.prototype.initialize.call( this );

		this.content = new OO.ui.PanelLayout( {
			padded: true,
			expanded: false,
			scrollable: true
		} );

		this.pageMessage = new OO.ui.MessageWidget( {
			type: 'notice',
			inline: false,
			label: tf( {
				en: 'Page: $title',
				hans: '页面:$title',
				hant: '頁面:$title'
			}, { title: this.pageTitle.replace( /_/g, ' ' ) } )
		} );

		this.limitationsMessage = new OO.ui.MessageWidget( {
			type: 'notice',
			inline: false,
			label: t( {
				en: 'This tool checks citation URLs one at a time from your browser. Before running it, temporarily relax browser protections by enabling the browser extensions, so direct cross-origin requests can succeed.',
				hans: '此工具会在浏览器中逐条检查参考文献网址。运行前请先启用浏览器扩展以临时放宽浏览器保护,让直接跨域请求可以成功发出。',
				hant: '此工具會在瀏覽器中逐條檢查參考文獻網址。執行前請先啟用瀏覽器擴充套件以暫時放寬瀏覽器保護,讓直接跨網域請求可以成功送出。'
			} )
		} );

		this.editWarningMessage = new OO.ui.MessageWidget( {
			type: 'warning',
			inline: false,
			label: t( {
				en: 'You appear to be on an edit page. This script works from the latest saved revision, not from unsaved text in the edit box.',
				hans: '你当前似乎位于编辑页面。此脚本会基于最近一次已保存的版本运行,而不会读取编辑框中尚未保存的内容。',
				hant: '你目前似乎位於編輯頁面。此腳本會以最近一次已儲存的版本為準,不會讀取編輯框中尚未儲存的內容。'
			} )
		} );
		this.editWarningMessage.toggle( hasUnsavedChanges );

		this.delayInput = new OO.ui.TextInputWidget( {
			value: String( DEFAULT_DELAY_MS ),
			type: 'number'
		} );
		this.liveTimeoutInput = new OO.ui.TextInputWidget( {
			value: String( DEFAULT_LIVE_TIMEOUT_MS ),
			type: 'number'
		} );
		this.archiveTimeoutInput = new OO.ui.TextInputWidget( {
			value: String( DEFAULT_ARCHIVE_TIMEOUT_MS ),
			type: 'number'
		} );
		this.retriesInput = new OO.ui.TextInputWidget( {
			value: String( DEFAULT_RETRIES ),
			type: 'number'
		} );
		this.summaryInput = new OO.ui.TextInputWidget( {
			value: DEFAULT_SUMMARY
		} );
		this.minorEditInput = new OO.ui.CheckboxInputWidget( {
			selected: true
		} );

		this.parameterFieldset = new OO.ui.FieldsetLayout( {
			label: t( { en: 'Parameters', hans: '参数', hant: '參數' } )
		} );
		this.parameterFieldset.addItems( [
			new OO.ui.FieldLayout( this.delayInput, {
				label: t( {
					en: 'Delay between requests (ms)',
					hans: '请求间隔(毫秒)',
					hant: '請求間隔(毫秒)'
				} ),
				align: 'top'
			} ),
			new OO.ui.FieldLayout( this.liveTimeoutInput, {
				label: t( {
					en: 'Live URL timeout (ms)',
					hans: '原始网址超时(毫秒)',
					hant: '原始網址逾時(毫秒)'
				} ),
				align: 'top'
			} ),
			new OO.ui.FieldLayout( this.archiveTimeoutInput, {
				label: t( {
					en: 'Wayback timeout (ms)',
					hans: 'Wayback 超时(毫秒)',
					hant: 'Wayback 逾時(毫秒)'
				} ),
				align: 'top'
			} ),
			new OO.ui.FieldLayout( this.retriesInput, {
				label: t( {
					en: 'Retries per request',
					hans: '每次请求的重试次数',
					hant: '每次請求的重試次數'
				} ),
				align: 'top'
			} ),
			new OO.ui.FieldLayout( this.summaryInput, {
				label: t( { en: 'Edit summary', hans: '编辑摘要', hant: '編輯摘要' } ),
				align: 'top'
			} ),
			new OO.ui.FieldLayout( this.minorEditInput, {
				label: t( {
					en: 'Mark the edit as minor',
					hans: '将编辑标记为小编辑',
					hant: '將編輯標記為小編輯'
				} ),
				align: 'inline'
			} )
		] );

		this.progressBar = new OO.ui.ProgressBarWidget( {
			progress: false
		} );
		this.statusMessage = new OO.ui.MessageWidget( {
			type: 'notice',
			inline: false,
			label: t( {
				en: 'Review the parameters, then confirm to start.',
				hans: '请先检查参数,然后点击确认开始。',
				hant: '請先檢查參數,然後按確認開始。'
			} )
		} );
		this.currentUrlLabel = new OO.ui.LabelWidget( {
			label: ''
		} );
		this.logInput = new OO.ui.MultilineTextInputWidget( {
			readOnly: true,
			autosize: true,
			rows: 8,
			value: ''
		} );

		this.progressFieldset = new OO.ui.FieldsetLayout( {
			label: t( { en: 'Progress', hans: '进度', hant: '進度' } )
		} );
		this.progressFieldset.addItems( [
			new OO.ui.FieldLayout( this.progressBar, {
				label: t( {
					en: 'Citation URL progress',
					hans: '参考文献网址进度',
					hant: '參考文獻網址進度'
				} ),
				align: 'top'
			} ),
			new OO.ui.FieldLayout( this.currentUrlLabel, {
				label: t( { en: 'Current URL', hans: '当前网址', hant: '目前網址' } ),
				align: 'top'
			} ),
			new OO.ui.FieldLayout( this.logInput, {
				label: t( { en: 'Activity log', hans: '活动日志', hant: '活動日誌' } ),
				align: 'top'
			} )
		] );
		this.progressFieldset.toggle( false );

		this.content.$element.append(
			this.pageMessage.$element,
			this.limitationsMessage.$element,
			this.editWarningMessage.$element,
			this.parameterFieldset.$element,
			this.statusMessage.$element,
			this.progressFieldset.$element
		);

		this.$body.append( this.content.$element );
	};

	ArchiveCitationsDialog.prototype.getBodyHeight = function () {
		return 540;
	};

	ArchiveCitationsDialog.prototype.getSetupProcess = function ( data ) {
		return ArchiveCitationsDialog.super.prototype.getSetupProcess.call( this, data )
			.next( function () {
				this.resetDialogState();
			}, this );
	};

	ArchiveCitationsDialog.prototype.getActionProcess = function ( action ) {
		if ( action === 'confirm' ) {
			return new OO.ui.Process( function () {
				return this.startProcess();
			}, this );
		}

		if ( action === 'cancel' ) {
			return new OO.ui.Process( function () {
				if ( !this.isRunning ) {
					this.close( { action: 'cancel' } );
					return;
				}
				this.requestStop();
			}, this );
		}

		return ArchiveCitationsDialog.super.prototype.getActionProcess.call( this, action );
	};

	ArchiveCitationsDialog.prototype.onActionClick = function ( action ) {
		if ( this.isRunning && action.getAction() === 'cancel' ) {
			this.requestStop();
			return;
		}
		ArchiveCitationsDialog.super.prototype.onActionClick.call( this, action );
	};

	ArchiveCitationsDialog.prototype.resetDialogState = function () {
		this.stopRequested = false;
		this.isRunning = false;
		this.lastExternalRequestFinishedAt = 0;
		this.logLines = [];
		this.pageMessage.setLabel( tf( {
			en: 'Page: $title',
			hans: '页面:$title',
			hant: '頁面:$title'
		}, { title: this.pageTitle.replace( /_/g, ' ' ) } ) );
		this.logInput.setValue( '' );
		this.progressBar.setProgress( false );
		this.currentUrlLabel.setLabel( '' );
		this.statusMessage.setType( 'notice' );
		this.statusMessage.setLabel( t( {
			en: 'Review the parameters, then confirm to start.',
			hans: '请先检查参数,然后点击确认开始。',
			hant: '請先檢查參數,然後按確認開始。'
		} ) );
		this.progressFieldset.toggle( false );
		this.setParameterWidgetsDisabled( false );
		this.setActionState( true, true, t( { en: 'Cancel', zh: '取消' } ) );
	};

	ArchiveCitationsDialog.prototype.setParameterWidgetsDisabled = function ( disabled ) {
		this.delayInput.setDisabled( disabled );
		this.liveTimeoutInput.setDisabled( disabled );
		this.archiveTimeoutInput.setDisabled( disabled );
		this.retriesInput.setDisabled( disabled );
		this.summaryInput.setDisabled( disabled );
		this.minorEditInput.setDisabled( disabled );
	};

	ArchiveCitationsDialog.prototype.setActionState = function ( confirmEnabled, cancelEnabled, cancelLabel ) {
		var cancelAction = this.actions.get( { actions: 'cancel' } )[ 0 ];
		this.actions.setAbilities( {
			confirm: confirmEnabled,
			cancel: cancelEnabled
		} );
		if ( cancelAction ) {
			cancelAction.setLabel( cancelLabel );
		}
	};

	ArchiveCitationsDialog.prototype.addLog = function ( line ) {
		this.logLines.push( line );
		this.logInput.setValue( this.logLines.join( '\n' ) );
	};

	ArchiveCitationsDialog.prototype.setStatus = function ( type, message ) {
		this.statusMessage.setType( type );
		this.statusMessage.setLabel( message );
	};

	ArchiveCitationsDialog.prototype.parseNumericSetting = function ( widget, fallback, integerOnly ) {
		var raw = String( widget.getValue() || '' ).trim();
		var value = integerOnly ? parseInt( raw, 10 ) : parseFloat( raw );
		if ( Number.isNaN( value ) || value < 0 ) {
			return fallback;
		}
		return value;
	};

	ArchiveCitationsDialog.prototype.parsePositiveNumericSetting = function ( widget, fallback, integerOnly ) {
		var value = this.parseNumericSetting( widget, fallback, integerOnly );
		return value > 0 ? value : fallback;
	};

	ArchiveCitationsDialog.prototype.getSettings = function () {
		return {
			delayMs: this.parseNumericSetting( this.delayInput, DEFAULT_DELAY_MS, false ),
			liveTimeoutMs: this.parsePositiveNumericSetting( this.liveTimeoutInput, DEFAULT_LIVE_TIMEOUT_MS, false ),
			archiveTimeoutMs: this.parsePositiveNumericSetting( this.archiveTimeoutInput, DEFAULT_ARCHIVE_TIMEOUT_MS, false ),
			retries: this.parseNumericSetting( this.retriesInput, DEFAULT_RETRIES, true ),
			summary: String( this.summaryInput.getValue() || DEFAULT_SUMMARY ).trim() || DEFAULT_SUMMARY,
			minor: this.minorEditInput.isSelected()
		};
	};

	ArchiveCitationsDialog.prototype.ensureNotStopped = function () {
		if ( this.stopRequested ) {
			throw createStopError();
		}
	};

	ArchiveCitationsDialog.prototype.requestStop = function () {
		this.stopRequested = true;
		this.setStatus( 'warning', t( {
			en: 'Stopping now.',
			hans: '正在停止。',
			hant: '正在停止。'
		} ) );
		this.addLog( t( {
			en: 'Stop requested by user.',
			hans: '用户请求停止。',
			hant: '使用者要求停止。'
		} ) );
		if ( this.currentThrottleTimeout !== null ) {
			window.clearTimeout( this.currentThrottleTimeout );
			this.currentThrottleTimeout = null;
		}
		if ( this.currentThrottleReject ) {
			this.currentThrottleReject( createStopError() );
			this.currentThrottleReject = null;
		}
		if ( this.currentFetchController ) {
			this.currentFetchController.abort();
		}
		if ( this.currentApiRequest && typeof this.currentApiRequest.abort === 'function' ) {
			this.currentApiRequest.abort();
		}
		this.api.abort();
	};

	ArchiveCitationsDialog.prototype.waitForThrottle = function ( delayMs ) {
		var remaining;
		var dialog = this;
		if ( !this.lastExternalRequestFinishedAt || delayMs <= 0 ) {
			return Promise.resolve();
		}
		remaining = delayMs - ( Date.now() - this.lastExternalRequestFinishedAt );
		if ( remaining <= 0 ) {
			return Promise.resolve();
		}
		return new Promise( function ( resolve, reject ) {
			dialog.currentThrottleReject = reject;
			dialog.currentThrottleTimeout = window.setTimeout( function () {
				dialog.currentThrottleTimeout = null;
				dialog.currentThrottleReject = null;
				resolve();
			}, remaining );
		} );
	};

	async function checkDirectCrossOriginAccess() {
		var controller = new AbortController();
		var timeoutId = window.setTimeout( function () {
			controller.abort();
		}, CORS_CHECK_TIMEOUT_MS );
		try {
			// This request is sent from the current wiki page to example.com.
			// Any failure here, including CSP connect-src or CORS blocking, means
			// the user still needs to relax browser protections before running.
			await fetch( getCorsCheckUrl(), {
				method: 'GET',
				mode: 'cors',
				redirect: 'follow',
				cache: 'no-store',
				credentials: 'omit',
				referrerPolicy: 'no-referrer',
				signal: controller.signal
			} );
			return {
				allowed: true,
				error: null
			};
		} catch ( error ) {
			return {
				allowed: false,
				error: error && error.message ? error.message : String( error )
			};
		} finally {
			window.clearTimeout( timeoutId );
		}
	}

	function showCorsRequiredDialog() {
		var $content = $( '<div>' );
		var lifecycle;
		var buildLink = function ( href, label ) {
			return $( '<a>', {
				href: href,
				target: '_blank',
				rel: 'noopener noreferrer'
			} ).text( label );
		};
		var buildLabeledLine = function ( labelText, nodes ) {
			var $line = $( '<p>' );
			$line.append( document.createTextNode( labelText ) );
			nodes.forEach( function ( node ) {
				$line.append( node );
			} );
			return $line;
		};

		$content.append(
			$( '<p>' ).text( t( {
				en: 'Disable CORS before running this script.',
				hans: '运行此脚本前,请先禁用 CORS。',
				hant: '執行此腳本前,請先停用 CORS。'
			} ) ),
			$( '<p>' ).text( t( {
				en: 'Enable the required browser extensions below, reload the page if needed, run the script again, and disable the extensions after you finish. Relaxing CORS or CSP protections is unsafe for normal browsing, so these extensions should only stay on while you are using this script. Browser extensions:',
				hans: '请启用下列所需的浏览器扩展,必要时重新加载页面,然后再次运行脚本,并在完成后关闭这些扩展。放宽 CORS 或 CSP 保护不适合平时浏览,因此这些扩展只应在你使用此脚本时临时开启。可用扩展:',
				hant: '請啟用下列所需的瀏覽器擴充套件,必要時重新載入頁面,然後再次執行腳本,並在完成後關閉這些擴充套件。放寬 CORS 或 CSP 保護不適合一般瀏覽,因此這些擴充套件只應在你使用此腳本時暫時開啟。可用擴充套件:'
			} ) ),
			buildLabeledLine( 'Chrome: ', [
				buildLink( CHROME_CORS_EXTENSION_URL, 'CORS Unblock' ),
				document.createTextNode( ' (' + t( {
					en: 'tick "Remove Content-Security-Policy" option',
					hans: '勾选“Remove Content-Security-Policy”选项',
					hant: '勾選「Remove Content-Security-Policy」選項'
				} ) + ')' )
			] ),
			buildLabeledLine( 'Firefox: ', [
				buildLink( FIREFOX_CORS_EXTENSION_URL, 'CORS Unblock' ),
				document.createTextNode( ' (' + t( {
					en: 'tick "Remove Content-Security-Policy" option',
					hans: '勾选“Remove Content-Security-Policy”选项',
					hant: '勾選「Remove Content-Security-Policy」選項'
				} ) + ')' )
			] )
		);

		ensureWarningDialog();
		lifecycle = warningDialogState.windowManager.openWindow( warningDialogState.dialog, {
			title: t( {
				en: 'CORS Must Be Disabled',
				hans: '必须先禁用 CORS',
				hant: '必須先停用 CORS'
			} ),
			message: $content,
			verbose: true,
			actions: [ {
				action: 'accept',
				label: t( { en: 'OK', hans: '确定', hant: '確定' } ),
				flags: [ 'primary', 'progressive' ]
			} ]
		} );
		return lifecycle;
	}

	ArchiveCitationsDialog.prototype.fetchExternal = async function ( url, settings, timeoutMs ) {
		var dialog = this;
		var response;
		var timeoutId = null;
		var timedOut = false;
		this.ensureNotStopped();
		await this.waitForThrottle( settings.delayMs );
		this.ensureNotStopped();

		this.currentFetchController = new AbortController();
		if ( timeoutMs > 0 ) {
			timeoutId = window.setTimeout( function () {
				timedOut = true;
				if ( dialog.currentFetchController ) {
					dialog.currentFetchController.abort();
				}
			}, timeoutMs );
		}
		try {
			response = await fetch( url, {
				method: 'GET',
				mode: 'cors',
				redirect: 'follow',
				cache: 'no-store',
				credentials: 'omit',
				referrerPolicy: 'no-referrer',
				signal: this.currentFetchController.signal
			} );
			return response;
		} catch ( error ) {
			if ( this.stopRequested ) {
				throw createStopError();
			}
			if ( error.name === 'AbortError' ) {
				if ( timedOut ) {
					throw new Error( 'Request timed out after ' + Math.round( timeoutMs ) + ' ms: ' + url );
				}
				throw createStopError();
			}
			throw error;
		} finally {
			if ( timeoutId !== null ) {
				window.clearTimeout( timeoutId );
			}
			this.currentFetchController = null;
			this.lastExternalRequestFinishedAt = Date.now();
		}
	};

	ArchiveCitationsDialog.prototype.fetchExternalWithRetry = async function ( url, settings, timeoutMs ) {
		var attempt;
		var response;
		for ( attempt = 0; attempt <= settings.retries; attempt += 1 ) {
			try {
				response = await this.fetchExternal( url, settings, timeoutMs );
				if ( RETRYABLE_HTTP_STATUSES[ response.status ] && attempt < settings.retries ) {
					this.addLog( 'Retrying ' + url + ' after HTTP ' + response.status + '.' );
					continue;
				}
				return response;
			} catch ( error ) {
				if ( isStopError( error ) ) {
					throw error;
				}
				if ( attempt >= settings.retries ) {
					throw error;
				}
				this.addLog( 'Retrying ' + url + ' after ' + error.message + '.' );
			}
		}
		throw new Error( 'Unreachable retry branch.' );
	};

	ArchiveCitationsDialog.prototype.probeOriginalUrl = async function ( url, settings ) {
		var response, proxyData, httpCode;
		try {
			if ( isHttpUrl( url ) ) {
				this.addLog( tf( {
					en: 'Original URL uses http; proxying via AllOrigins to check $url.',
					hans: '原始网址使用 http,通过 AllOrigins 代理检查 $url。',
					hant: '原始網址使用 http,透過 AllOrigins 代理檢查 $url。'
				}, { url: url } ) );
				response = await this.fetchExternalWithRetry(
					HTTPS_PROXY_PREFIX + encodeURIComponent( url ),
					settings,
					settings.liveTimeoutMs
				);
				try {
					proxyData = await response.json();
				} catch ( _jsonError ) {
					return {
						urlStatus: null,
						liveStatus: null,
						liveError: 'Proxy returned non-JSON response (HTTP ' + response.status + ') for ' + url
					};
				}
				httpCode = proxyData && proxyData.status && proxyData.status.http_code;
				if ( !httpCode ) {
					return {
						urlStatus: null,
						liveStatus: null,
						liveError: 'Proxy returned no status code for ' + url
					};
				}
				return {
					urlStatus: ( httpCode >= 200 && httpCode < 400 ) || LIVE_HTTP_STATUSES[ httpCode ] ? 'live' : 'dead',
					liveStatus: httpCode,
					liveError: null
				};
			}
			response = await this.fetchExternalWithRetry( url, settings, settings.liveTimeoutMs );
			return {
				urlStatus: ( response.status >= 200 && response.status < 400 ) || LIVE_HTTP_STATUSES[ response.status ] ? 'live' : 'dead',
				liveStatus: response.status,
				liveError: null
			};
		} catch ( error ) {
			if ( isStopError( error ) ) {
				throw error;
			}
			return {
				urlStatus: null,
				liveStatus: null,
				liveError: error.message || String( error )
			};
		}
	};

	ArchiveCitationsDialog.prototype.fetchJsonResult = async function ( url, settings, timeoutMs ) {
		var response;
		var data;
		try {
			response = await this.fetchExternalWithRetry( url, settings, timeoutMs );
			try {
				data = await response.json();
			} catch ( jsonError ) {
				return {
					status: response.status,
					data: null,
					error: 'Non-JSON response (HTTP ' + response.status + ') from ' + url
				};
			}
			return {
				status: response.status,
				data: data,
				error: null
			};
		} catch ( error ) {
			if ( isStopError( error ) ) {
				throw error;
			}
			return {
				status: null,
				data: null,
				error: error.message || String( error )
			};
		}
	};

	ArchiveCitationsDialog.prototype.archiveResultFromUrl = function ( archiveUrl, status, error, source ) {
		if ( archiveUrl ) {
			return {
				archiveUrl: archiveUrl,
				archiveDate: extractArchiveDate( archiveUrl ),
				archiveStatus: status,
				archiveError: error,
				archiveSource: source
			};
		}
		return {
			archiveUrl: null,
			archiveDate: null,
			archiveStatus: status,
			archiveError: error,
			archiveSource: source
		};
	};

	ArchiveCitationsDialog.prototype.lookupAvailabilityArchiveUrl = async function ( url, settings ) {
		var result = await this.fetchJsonResult(
			buildWaybackAvailabilityUrl( url ),
			settings,
			settings.archiveTimeoutMs
		);
		var archiveUrl = parseWaybackAvailability( result.data );
		return this.archiveResultFromUrl( archiveUrl, result.status, result.error, 'availability' );
	};

	ArchiveCitationsDialog.prototype.lookupCdxArchiveUrl = async function ( url, settings ) {
		var result = await this.fetchJsonResult(
			buildWaybackCdxUrl( url ),
			settings,
			settings.archiveTimeoutMs
		);
		var archiveUrl = parseWaybackCdx( result.data );
		return this.archiveResultFromUrl( archiveUrl, result.status, result.error, 'cdx' );
	};

	ArchiveCitationsDialog.prototype.resolveWaybackDateLocator = async function ( url, date, settings, source ) {
		var locatorUrl = buildWaybackDateLocatorUrl( url, date );
		var response;
		var finalUrl;
		var archiveUrl;
		try {
			response = await this.fetchExternalWithRetry(
				locatorUrl,
				settings,
				settings.archiveTimeoutMs
			);
			finalUrl = normalizeArchiveSnapshotUrl( response.url || locatorUrl );
			if ( ARCHIVE_URL_RE.test( finalUrl ) ) {
				archiveUrl = finalUrl;
			}
			return this.archiveResultFromUrl( archiveUrl, response.status, null, source || 'calendar' );
		} catch ( error ) {
			if ( isStopError( error ) ) {
				throw error;
			}
			return this.archiveResultFromUrl( null, null, error.message || String( error ), source || 'calendar' );
		}
	};

	ArchiveCitationsDialog.prototype.fetchWaybackCalendarYear = async function ( url, year, settings, cache ) {
		var cacheKey = url + '\n' + String( year );
		var result;
		if ( cache && cache.calendarResults[ cacheKey ] ) {
			return cache.calendarResults[ cacheKey ];
		}
		result = await this.fetchJsonResult(
			buildWaybackCalendarUrl( url, year ),
			settings,
			settings.archiveTimeoutMs
		);
		if ( cache && !shouldStopWaybackCalendarScan( result ) ) {
			cache.calendarResults[ cacheKey ] = result;
		}
		return result;
	};

	ArchiveCitationsDialog.prototype.lookupCalendarArchiveUrl = async function ( url, settings, options ) {
		options = options || {};
		var currentYear = new Date().getFullYear();
		var oldestYear = Math.max( 1996, currentYear - WAYBACK_CALENDAR_LOOKBACK_YEARS + 1 );
		var variants = buildWaybackLookupVariants( url );
		var years = options.years !== undefined ?
			options.years :
			buildDescendingYearRange( currentYear, oldestYear );
		var source = options.source || 'calendar';
		var finalStatus = null;
		var finalError = null;
		var variantIndex;
		var yearIndex;
		var year;
		var calendarResult;
		var dates;
		var dateIndex;
		var locatorResult;
		var stopReason;

		for ( variantIndex = 0; variantIndex < variants.length; variantIndex += 1 ) {
			for ( yearIndex = 0; yearIndex < years.length; yearIndex += 1 ) {
				year = years[ yearIndex ];
				this.ensureNotStopped();
				calendarResult = await this.fetchWaybackCalendarYear(
					variants[ variantIndex ],
					year,
					settings,
					options.cache
				);
				if ( calendarResult.status !== null ) {
					finalStatus = calendarResult.status;
				}
				if ( calendarResult.error ) {
					finalError = calendarResult.error;
				}
				if ( shouldStopWaybackCalendarScan( calendarResult ) ) {
					stopReason = describeFetchResultFailure( calendarResult );
					if ( !finalError ) {
						finalError = stopReason;
					}
					this.addLog( 'Skipping remaining calendar lookups for ' + url + ' after ' + stopReason + '.' );
					return this.archiveResultFromUrl( null, finalStatus, finalError, source );
				}
				dates = filterWaybackCalendarDates(
					parseWaybackCalendarDates( calendarResult.data, year ),
					options.startDateText,
					options.endDateText
				);
				for ( dateIndex = 0; dateIndex < dates.length; dateIndex += 1 ) {
					locatorResult = await this.resolveWaybackDateLocator(
						variants[ variantIndex ],
						dates[ dateIndex ],
						settings,
						source
					);
					if ( locatorResult.archiveUrl ) {
						return locatorResult;
					}
					if ( locatorResult.archiveStatus !== null ) {
						finalStatus = locatorResult.archiveStatus;
					}
					if ( locatorResult.archiveError ) {
						finalError = locatorResult.archiveError;
					}
				}
			}
		}

		return this.archiveResultFromUrl( null, finalStatus, finalError, source );
	};

	ArchiveCitationsDialog.prototype.lookupRecentCalendarArchiveUrl = async function ( url, settings, cache, startDateText, endDateText ) {
		return this.lookupCalendarArchiveUrl( url, settings, {
			years: buildDescendingYearRange(
				parseInt( endDateText.slice( 0, 4 ), 10 ),
				parseInt( startDateText.slice( 0, 4 ), 10 )
			),
			startDateText: startDateText,
			endDateText: endDateText,
			cache: cache,
			source: 'calendar-recent'
		} );
	};

	ArchiveCitationsDialog.prototype.probeArchiveUrl = async function ( url, settings ) {
		var cache = makeWaybackLookupCache();
		var today = dateOnly( new Date() );
		var recentStartDate = addDays( today, -365 );
		var recentStartDateText = formatDateText( recentStartDate );
		var todayText = formatDateText( today );
		var olderEndDate = addDays( recentStartDate, -1 );
		var oldestYear = Math.max( 1996, today.getFullYear() - WAYBACK_CALENDAR_LOOKBACK_YEARS + 1 );
		var olderYears = buildDescendingYearRange( olderEndDate.getFullYear(), oldestYear );
		var recentCalendarResult;
		var availabilityResult;
		var cdxResult;
		var calendarResult;
		try {
			recentCalendarResult = await this.lookupRecentCalendarArchiveUrl(
				url,
				settings,
				cache,
				recentStartDateText,
				todayText
			);
			if ( recentCalendarResult.archiveUrl ) {
				return recentCalendarResult;
			}

			availabilityResult = await this.lookupAvailabilityArchiveUrl( url, settings );
			if ( availabilityResult.archiveUrl ) {
				return availabilityResult;
			}

			cdxResult = await this.lookupCdxArchiveUrl( url, settings );
			if ( cdxResult.archiveUrl ) {
				return cdxResult;
			}

			calendarResult = await this.lookupCalendarArchiveUrl( url, settings, {
				years: olderYears,
				endDateText: formatDateText( olderEndDate ),
				cache: cache,
				source: 'calendar'
			} );
			if ( calendarResult.archiveUrl ) {
				return calendarResult;
			}
			return calendarResult.archiveStatus !== null || calendarResult.archiveError ?
				calendarResult :
				cdxResult || availabilityResult || recentCalendarResult;
		} catch ( error ) {
			if ( isStopError( error ) ) {
				throw error;
			}
			return this.archiveResultFromUrl( null, null, error.message || String( error ), 'lookup' );
		}
	};

	ArchiveCitationsDialog.prototype.fetchUrlMetadata = async function ( url, requirements, settings ) {
		var liveResult = requirements.needLiveCheck ?
			await this.probeOriginalUrl( url, settings ) :
			{ urlStatus: null, liveStatus: null, liveError: null };
		var archiveResult = requirements.needArchiveLookup ?
			await this.probeArchiveUrl( url, settings ) :
			{ archiveUrl: null, archiveDate: null, archiveStatus: null, archiveError: null, archiveSource: null };
		return {
			url: url,
			urlStatus: liveResult.urlStatus,
			liveStatus: liveResult.liveStatus,
			liveError: liveResult.liveError,
			archiveUrl: archiveResult.archiveUrl,
			archiveDate: archiveResult.archiveDate,
			archiveStatus: archiveResult.archiveStatus,
			archiveError: archiveResult.archiveError,
			archiveSource: archiveResult.archiveSource
		};
	};

	ArchiveCitationsDialog.prototype.collectUrlMetadata = async function ( requirementsByUrl, settings ) {
		var metadataByUrl = {};
		var urls = Object.keys( requirementsByUrl ).sort();
		var index;
		var url;
		var host;
		var metadata;
		for ( index = 0; index < urls.length; index += 1 ) {
			url = urls[ index ];
			try {
				host = new URL( url ).host || url;
			} catch ( error ) {
				host = url;
			}
			this.ensureNotStopped();
			this.currentUrlLabel.setLabel( tf( {
				en: '$host ($current of $total)',
				hans: '$host(第 $current / 共 $total 项)',
				hant: '$host(第 $current/共 $total 項)'
			}, {
				host: host,
				current: String( index + 1 ),
				total: String( urls.length )
			} ) );
			this.setStatus( 'notice', t( {
				en: 'Checking citation URLs...',
				hans: '正在检查参考文献网址……',
				hant: '正在檢查參考文獻網址……'
			} ) );
			metadata = await this.fetchUrlMetadata( url, requirementsByUrl[ url ], settings );
			metadataByUrl[ url ] = metadata;
			this.progressBar.setProgress( urls.length ? Math.round( ( ( index + 1 ) / urls.length ) * 100 ) : 100 );
			this.addLog(
				url + ' | url-status=' + ( metadata.urlStatus === null ? '-' : metadata.urlStatus ) +
				' | archive=' + ( metadata.archiveUrl || t( { en: 'none', hans: '无', hant: '無' } ) ) +
				( metadata.archiveSource ? ' (' + metadata.archiveSource + ')' : '' ) +
				' | live=' + ( metadata.liveStatus !== null ? metadata.liveStatus : metadata.liveError || t( { en: 'error', hans: '错误', hant: '錯誤' } ) )
			);
		}
		return metadataByUrl;
	};

	ArchiveCitationsDialog.prototype.apiRequest = async function ( method, params ) {
		var request;
		try {
			this.ensureNotStopped();
			request = this.api[ method ]( params );
			this.currentApiRequest = request;
			return await request;
		} catch ( error ) {
			if ( this.stopRequested ) {
				throw createStopError();
			}
			throw error;
		} finally {
			this.currentApiRequest = null;
		}
	};

	ArchiveCitationsDialog.prototype.fetchPageSource = async function () {
		var data = await this.apiRequest( 'get', {
			action: 'query',
			prop: 'revisions',
			titles: this.pageTitle,
			rvprop: 'content|timestamp',
			rvslots: 'main',
			curtimestamp: 1,
			formatversion: 2
		} );
		var page = data && data.query && data.query.pages && data.query.pages[ 0 ];
		var revision = page && page.revisions && page.revisions[ 0 ];
		if ( !page || page.missing ) {
			throw new Error( t( {
				en: 'The page could not be loaded.',
				hans: '无法载入页面。',
				hant: '無法載入頁面。'
			} ) );
		}
		if ( !revision || !revision.slots || !revision.slots.main ) {
			throw new Error( t( {
				en: 'No wikitext content was returned for the page.',
				hans: '页面没有返回 wikitext 内容。',
				hant: '頁面沒有回傳 wikitext 內容。'
			} ) );
		}
		return {
			title: page.title,
			content: revision.slots.main.content || '',
			basetimestamp: revision.timestamp,
			starttimestamp: data.curtimestamp || null
		};
	};

	ArchiveCitationsDialog.prototype.savePage = async function ( revisionData, text, settings ) {
		var params = {
			action: 'edit',
			title: revisionData.title,
			text: text,
			summary: settings.summary,
			basetimestamp: revisionData.basetimestamp,
			starttimestamp: revisionData.starttimestamp,
			formatversion: 2,
			watchlist: 'nochange'
		};
		if ( settings.minor ) {
			params.minor = true;
		}
		try {
			this.ensureNotStopped();
			this.currentApiRequest = this.api.postWithToken( 'csrf', params );
			return await this.currentApiRequest;
		} catch ( error ) {
			if ( this.stopRequested ) {
				throw createStopError();
			}
			throw error;
		} finally {
			this.currentApiRequest = null;
		}
	};

	ArchiveCitationsDialog.prototype.openDiffTab = function ( editResponse, title ) {
		var edit = editResponse && editResponse.edit;
		var newRevId = edit && edit.newrevid;
		var diffUrl;
		if ( !newRevId ) {
			return;
		}
		diffUrl = mw.util.getUrl( title, {
			diff: String( newRevId ),
			oldid: 'prev'
		} );
		window.open( diffUrl, '_blank', 'noopener' );
	};

	ArchiveCitationsDialog.prototype.finishRun = function () {
		this.isRunning = false;
		this.currentFetchController = null;
		this.currentApiRequest = null;
		if ( this.currentThrottleTimeout !== null ) {
			window.clearTimeout( this.currentThrottleTimeout );
			this.currentThrottleTimeout = null;
		}
		this.currentThrottleReject = null;
		this.setParameterWidgetsDisabled( false );
		this.setActionState( true, true, t( { en: 'Cancel', zh: '取消' } ) );
	};

	ArchiveCitationsDialog.prototype.startProcess = async function () {
		var settings = this.getSettings();
		var initialRevision;
		var initialStats = makeStats();
		var requirementsByUrl;
		var urls;
		var metadataByUrl;
		var latestRevision;
		var latestStats = makeStats();
		var updates;
		var updatedText;
		var archiveHits;

		if ( this.isRunning ) {
			return;
		}

		this.isRunning = true;
		this.stopRequested = false;
		this.lastExternalRequestFinishedAt = 0;
		this.logLines = [];
		this.logInput.setValue( '' );
		this.progressFieldset.toggle( true );
		this.progressBar.setProgress( false );
		this.currentUrlLabel.setLabel( '' );
		this.setParameterWidgetsDisabled( true );
		this.setActionState( false, true, t( {
			en: 'Force Stop',
			hans: '强制停止',
			hant: '強制停止'
		} ) );
		this.pushPending();

		try {
			this.setStatus( 'notice', t( {
				en: 'Fetching the current page source...',
				hans: '正在获取当前页面源码……',
				hant: '正在取得目前頁面原始碼……'
			} ) );
			this.addLog( t( {
				en: 'Fetching current wikitext.',
				hans: '正在获取当前 wikitext。',
				hant: '正在取得目前 wikitext。'
			} ) );
			initialRevision = await this.fetchPageSource();
			requirementsByUrl = collectUniqueUrls( initialRevision.content, initialStats );
			urls = Object.keys( requirementsByUrl ).sort();
			this.addLog( tf( {
				en: 'Found $templates citation templates with URLs ($urls unique URLs needing network checks).',
				hans: '找到 $templates 个带网址的参考文献模板(其中 $urls 个唯一网址需要网络检查)。',
				hant: '找到 $templates 個帶網址的參考文獻模板(其中 $urls 個唯一網址需要網路檢查)。'
			}, {
				templates: String( initialStats.citationTemplatesWithUrl ),
				urls: String( urls.length )
			} ) );
			this.addLog( tf( {
				en: 'Skipped network checks for $count citation templates that already contain a URL status, archive-url, and archive-date.',
				hans: '已跳过 $count 个已有网址状态、archive-url 和 archive-date 的参考文献模板的网络检查。',
				hant: '已略過 $count 個已有網址狀態、archive-url 與 archive-date 的參考文獻模板的網路檢查。'
			}, {
				count: String( initialStats.skippedWithExistingFields )
			} ) );

			metadataByUrl = {};
			if ( !urls.length ) {
				this.progressBar.setProgress( 100 );
				this.setStatus( 'notice', t( {
					en: 'No citation URLs need network checks. Applying local updates if possible.',
					hans: '没有参考文献网址需要网络检查。如有可能,将只应用本地更新。',
					hant: '沒有參考文獻網址需要網路檢查。如有可能,將只套用本地更新。'
				} ) );
				this.addLog( t( {
					en: 'No network checks needed; continuing with local template updates only.',
					hans: '无需网络检查;继续仅应用本地模板更新。',
					hant: '無須網路檢查;繼續僅套用本地模板更新。'
				} ) );
			} else {
				this.progressBar.setProgress( 0 );
				metadataByUrl = await this.collectUrlMetadata( requirementsByUrl, settings );
				archiveHits = Object.keys( metadataByUrl ).filter( function ( key ) {
					return !!metadataByUrl[ key ].archiveUrl;
				} ).length;
				this.addLog( tf( {
					en: 'Archive hits found for $hits of $total URLs.',
					hans: '$total 个网址中有 $hits 个找到了存档。',
					hant: '$total 個網址中有 $hits 個找到了存檔。'
				}, {
					hits: String( archiveHits ),
					total: String( urls.length )
				} ) );
			}

			this.ensureNotStopped();
			this.setStatus( 'notice', t( {
				en: 'Refetching the latest page source before saving...',
				hans: '正在在保存前重新获取最新页面源码……',
				hant: '正在於儲存前重新取得最新頁面原始碼……'
			} ) );
			this.addLog( t( {
				en: 'Refetching latest wikitext before save.',
				hans: '正在在保存前重新获取最新 wikitext。',
				hant: '正在於儲存前重新取得最新 wikitext。'
			} ) );
			latestRevision = await this.fetchPageSource();
			updates = buildUpdates( latestRevision.content, metadataByUrl, latestStats );
			updatedText = applyUpdates( latestRevision.content, updates );

			if ( updatedText === latestRevision.content ) {
				this.progressBar.setProgress( 100 );
				this.setStatus( 'notice', t( {
					en: 'No changes were needed after refetching the latest source.',
					hans: '重新获取最新源码后无需任何修改。',
					hant: '重新取得最新原始碼後無須作出任何修改。'
				} ) );
				mw.notify( t( {
					en: 'No citation changes were needed.',
					hans: '无需修改任何参考文献。',
					hant: '無須修改任何參考文獻。'
				} ), { type: 'info' } );
				return;
			}

			this.setStatus( 'notice', t( {
				en: 'Saving the updated wikitext...',
				hans: '正在保存更新后的 wikitext……',
				hant: '正在儲存更新後的 wikitext……'
			} ) );
			this.addLog( tf( {
				en: 'Saving page with $count updated citation templates.',
				hans: '正在保存页面,共更新 $count 个参考文献模板。',
				hant: '正在儲存頁面,共更新 $count 個參考文獻模板。'
			}, {
				count: String( latestStats.updatedTemplates )
			} ) );
			var saveResponse = await this.savePage( latestRevision, updatedText, settings );
			this.openDiffTab( saveResponse, latestRevision.title );
			this.progressBar.setProgress( 100 );
			this.setStatus( 'success', t( {
				en: 'Saved successfully.',
				hans: '保存成功。',
				hant: '儲存成功。'
			} ) );
			mw.notify(
				tf( {
					en: 'Saved citation archives: $count templates updated.',
					hans: '参考文献存档已保存:共更新 $count 个模板。',
					hant: '參考文獻存檔已儲存:共更新 $count 個模板。'
				}, { count: String( latestStats.updatedTemplates ) } ),
				{ type: 'success' }
			);
			this.close( { action: 'confirm' } );
		} catch ( error ) {
			if ( isStopError( error ) ) {
				this.setStatus( 'warning', t( {
					en: 'The archive lookup was stopped.',
					hans: '存档查询已停止。',
					hant: '存檔查詢已停止。'
				} ) );
				this.addLog( t( {
					en: 'Process stopped before save.',
					hans: '流程已在保存前停止。',
					hant: '流程已在儲存前停止。'
				} ) );
				mw.notify( t( {
					en: 'Archive lookup stopped before save.',
					hans: '存档查询已在保存前停止。',
					hant: '存檔查詢已在儲存前停止。'
				} ), { type: 'warn' } );
				return;
			}
			this.setStatus( 'error', error && error.message ? error.message : String( error ) );
			this.addLog( tf( {
				en: 'Error: $message',
				hans: '错误:$message',
				hant: '錯誤:$message'
			}, {
				message: error && error.message ? error.message : String( error )
			} ) );
			mw.notify(
				tf( {
					en: 'Archive lookup failed: $message',
					hans: '存档查询失败:$message',
					hant: '存檔查詢失敗:$message'
				}, {
					message: error && error.message ? error.message : String( error )
				} ),
				{ type: 'error' }
			);
		} finally {
			this.popPending();
			this.finishRun();
		}
	};

	function ensureDialog( pageTitle ) {
		if ( !dialogState.windowManager ) {
			dialogState.windowManager = new OO.ui.WindowManager();
			$( document.body ).append( dialogState.windowManager.$element );
		}
		if ( !dialogState.dialog ) {
			dialogState.dialog = new ArchiveCitationsDialog( {
				pageTitle: pageTitle,
				size: 'larger'
			} );
			dialogState.windowManager.addWindows( [ dialogState.dialog ] );
		}
	}

	function openDialog( pageTitle ) {
		ensureDialog( pageTitle );
		dialogState.dialog.pageTitle = pageTitle;
		dialogState.windowManager.openWindow( dialogState.dialog );
	}

	async function handlePortletClick() {
		var pageTitle = mw.config.get( 'wgRelevantPageName' ) || mw.config.get( 'wgPageName' );
		var corsCheck;

		if ( !pageTitle ) {
			mw.notify( t( {
				en: 'No page title was found for the current view.',
				hans: '当前视图找不到页面标题。',
				hant: '目前檢視找不到頁面標題。'
			} ), { type: 'error' } );
			return;
		}

		corsCheck = await checkDirectCrossOriginAccess();
		if ( corsCheck.allowed ) {
			console.info( '[AddArchiveURLs] Browser setup check passed: cross-origin fetch to example.com succeeded.' );
			openDialog( pageTitle );
			return;
		}

		console.warn(
			'[AddArchiveURLs] Browser setup check failed: fetch to example.com failed, so browser protections are still active.',
			corsCheck.error
		);
		return showCorsRequiredDialog();
	}

	function ensureWarningDialog() {
		if ( !warningDialogState.windowManager ) {
			warningDialogState.windowManager = new OO.ui.WindowManager();
			$( document.body ).append( warningDialogState.windowManager.$element );
		} else {
			$( document.body ).append( warningDialogState.windowManager.$element );
		}
		if ( !warningDialogState.dialog ) {
			warningDialogState.dialog = new OO.ui.MessageDialog( {
				size: 'medium'
			} );
			warningDialogState.windowManager.addWindows( [ warningDialogState.dialog ] );
		}
	}

	function addPortletLink() {
		var label = t( {
			en: 'Archive all URLs in citations',
			hans: '为参考文献添加存档',
			hant: '為參考文獻加入存檔'
		} );
		var tooltip = t( {
			en: 'Fetch archive URLs for citation templates and save the page',
			hans: '为参考文献模板抓取存档网址并保存页面',
			hant: '為參考文獻模板抓取存檔網址並儲存頁面'
		} );
		var node = mw.util.addPortletLink(
			'p-cactions',
			'#',
			label,
			'ca-archive-all-urls',
			tooltip
		);
		if ( !node ) {
			node = mw.util.addPortletLink(
				'p-tb',
				'#',
				label,
				't-archive-all-urls',
				tooltip
			);
		}
		if ( !node ) {
			return;
		}
		$( node ).on( 'click', function ( event ) {
			event.preventDefault();
			handlePortletClick();
		} );
	}

	function shouldEnableScript() {
		return !!(
			mw.config.get( 'wgRelevantPageName' ) &&
			mw.config.get( 'wgPageContentModel' ) === 'wikitext' &&
			mw.config.get( 'wgNamespaceNumber' ) >= 0
		);
	}

	mw.loader.using( MODULES ).then( function ( require ) {
		if ( typeof require === 'function' ) {
			try {
				convByVar = require( 'ext.gadget.HanAssist' ).convByVar || convByVar;
			} catch ( error ) {
				convByVar = convByVar;
			}
		}
		applyLocalizedStatics();
		if ( shouldEnableScript() ) {
			addPortletLink();
		} else {
			console.info( '[AddArchiveURLs] Script not enabled on this page due to content model, namespace, or missing page title.' );
		}
	} );
}() );