Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
//<syntaxhighlight lang="js">//jshint maxerr:256varapi=newmw.Api();vartitlePrefix="Module:Sandbox/Ahecht/flag/";varstatusText='';functionapiGet(titles){varquery={action:"query",prop:"revisions",rvprop:"content",titles:titles};api.get(query).done(function(data){if(typeofdata!=='undefined'&&data.query&&data.query.pages){page=Object.entries(data.query.pages)[0][1];if(typeofpage.revisions!=='undefined'){returnprocessTemplate(page.revisions[0]['*']);}else{statusText="Error: Revisions not found!";showStatus(statusText);returnstatusText;}}statusText="Error: Data not found!";showStatus(statusText);returnstatusText;}).fail(function(err){statusText="Error: API error:"+err;showStatus(statusText);returnstatusText;});return;}functionprocessTemplate(content){varoutput={};if(typeofcontent!=='undefined'&&/^\{\{\s*(?:safesubst<noinclude\s*\/>:|)\s*\{\{\{1/.test(content)){//Valid data templatevarmatches=content.replace(/<noinclude\>[\S\s]*?<\/noinclude\>/gmi,"").matchAll(/(?<=\n)[ \t]*\|[ \t]*([^=]*?)[ \t]*=[ \t]*([^\n]*?)[ \t]*(?=\n)/g);for(varmatchofmatches){// Don't store passthrough valuesif(match[2]!="{{{"+match[1]+"|}}}"){output[match[1]]=match[2];}}}if(typeofoutput.alias!=='undefined'){returngenerateLua(output,1);}else{statusText="Error processing template!";showStatus(statusText);returnstatusText;}return;}functiongenerateLua(args,depth){varparams={};vark,resolvedkey,ifeq;//Find subparametersfor(varkeyinargs){//Resolve #ifeq statement in keyifeq=key.match(/\{\{\s*#ifeq:\s*\{\{\{altlink\}\}\}\s*\|(.*?)\|(.*?)\|.*?\}\}/);if(ifeq!==null&&ifeq[1]!==null&&ifeq[2]!==null){resolvedkey=ifeq[2].trim()+'-'+ifeq[1].trim().split(' ')[0];}else{resolvedkey=key;}//Split by hyphensif(!/[{}]/.test(resolvedkey)&&/[-]/.test(resolvedkey)){k=resolvedkey.split("-");}else{k=[resolvedkey];}//Create subkey for prefix if it doesn't already existif(typeofparams[k[0]]==='undefined'){params[k[0]]={};}varvalue=args[key];//Assign either suffix subarray or #defaultvarsubkey="#default";if(typeofk[1]!=='undefined'){subkey=k.slice(1).join("-");}//Check if value has a switch or #ifeq statement and storeif(typeofvalue==='string'){if(/^\{\{\s*(?:safesubst<noinclude\s*\/>:|)\s*#switch:\s*\{\{\{variant\|?\}\}\}/.test(value)){params[k[0]][subkey]=doSwitch(value);}else{varparseIfeq=value.match(/\{\{\s*(?:safesubst<noinclude\s*\/>:|)\s*#ifeq:\s*\{\{\{name\|?\}\}\}\s*\|(.*?)\s*\|\s*(.*?)\s*\|\s*\{\{\{name\|?\}\}\}\s*\}\}/);if(parseIfeq!==null&&parseIfeq[1]!==null&&parseIfeq[2]!==null){params[k[0]][subkey]={};params[k[0]][subkey][parseIfeq[1]]=parseIfeq[2];}else{params[k[0]][subkey]=value;}}}elseif(typeofvalue==='undefined'){params[k[0]][subkey]="false";}else{params[k[0]][subkey]=value;}}//Move parameters up a level if only #default existsfor(keyinparams){varcount=0;for(kinparams[key]){count++;}if((count==1)&&(typeofparams[key]['#default']!=='undefined')){params[key]=params[key]['#default'];}}varoutput=[];//Generate lua outputfor(keyinparams){k='\t'.repeat(depth+1)+'["'+key+'"] = ';if(typeof(params[key])==='string'){varoutString=k;// Set blank to falseif(params[key]===''){outString+="false";}else{outString+='"'+params[key]+'"';}// Put #default at start of outStringif(key=="#default"){output.unshift(outString);}else{output.push(outString);}}elseif(typeof(params[key])==='object'){//Remove redundant levelsfor(varsubinparams[key]){if(sub=='#default'&&typeof(params[key][sub])==='object'){for(varsubsubinparams[key][sub]){params[key][subsub]=params[key][sub][subsub];deleteparams[key][sub][subsub];}}}for(subinparams[key]){if(sub.search(key+'-')===0){params[key][sub.replace(key+'-','')]=params[key][sub];deleteparams[key][sub];}elseif(sub==key){params[key]['#default']=params[key][sub];deleteparams[key][sub];}}varsubout=generateLua(params[key],depth+1);output.push(k+'{\n'+subout.join(",\n")+'\n'+'\t'.repeat(depth+1)+'}');}}if(depth!=1){returnoutput;}else{varouttext='return {\n\t["'+args.alias+'"] = {\n'+output.join(',\n')+'\n\t},\n}';showStatus(outtext);returnapiPost(args.alias,outtext);}return;}functiondoSwitch(value){vartrimmedValue=value.replace(/^\{\{\s*(?:safesubst<noinclude\s*\/>:|)\s*#switch:\s*\{\{\{variant\|?\}\}\}\s*(.*)\}\}$/,'$1|');varmatches=trimmedValue.match(/(?<=\|)(.*?)(?=\|)/g);varvalueObj={};for(i=0;i<matches.length;i++){varmi=matches[i].split("=");for(j=i;j<matches.length;j++){varmj=matches[j].split("=");if(typeofmj[1]!=='undefined'){valueObj[mi[0]]=mj[1];break;}elseif(j==(matches.length-1)){if(i==j){valueObj['#default']=mj[0];}else{valueObj[mi[0]]=mj[0];}}}}returnvalueObj;}functionapiPost(alias,text){varparams={action:"edit"};vartype;if(text=='documentation'){type=text;params.title=titlePrefix+alias.replace(/\s/,"_")+'/doc';params.summary="Creating documentation for [["+titlePrefix+alias+"]]";params.text="{{:"+titlePrefix+"doc|Country data "+alias+"}}";}else{type='module';params.title=titlePrefix+alias.replace(/\s/,"_");params.summary="Extracting data from [[Template:Country data "+alias+"]]";params.text=text;}api.postWithEditToken(params).done(function(data){if(typeofdata!=='undefined'&&data){if(data.edit&&data.edit.result&&data.edit.result==="Success"){statusText="Edit saved successfully to https:"+mw.config.values.wgServer+mw.config.values.wgArticlePath.replace("$1",data.edit.title.replace(/\s/,"_"));}else{statusText="Couldn't save "+type+" due to data error: "+JSON.stringify(data);}}else{statusText="Couldn't save "+type+" due to data error.";}showStatus(statusText);if(text!='documentation'){apiPost(alias,'documentation');}}).fail(function(err){statusText="Couldn't save "+type+" due to post error: "+err;showStatus(statusText);});return;}functionshowStatus(statusText){console.log(statusText);return;}if(mw.config.values.wgPageName.search("Template:Country_data_")===0){apiGet(mw.config.values.wgPageName);}elseif(mw.config.values.wgPageName.search(titlePrefix)===0){apiGet("Template:Country_data_"+mw.config.values.wgPageName.split('/').pop());}else{showStatus("Script must be run from Country Data template or Country-specific module");}//</syntaxhighlight>