1.0.1.1: shared Realm CP copies, JARVIS key families and Realm Nexus navigation

This commit is contained in:
unimatrix 2026-11-17 19:10:09 +00:00
commit 73aa88b670
4 changed files with 594 additions and 379 deletions

View file

@ -1,56 +1,57 @@
import {HOUSE_STYLE_CSS} from './house-style.mjs';
import {bankRatesPage} from './bank-rates-page.mjs';
import{withCanonicalMenu,MAIN_MENU}from'./main-menu.mjs';
import{withMenuBadges}from'./menu-updates.mjs';
import{updatePortalNavigation}from'./portal-navigation.mjs';
// Package the authored web and worker sources without rewriting their content.
import {readFileSync,writeFileSync,openSync,writeSync,closeSync,readdirSync,statSync,mkdirSync,existsSync,rmSync,cpSync} from 'node:fs';import path from 'node:path';import {fileURLToPath} from 'node:url';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'),web=path.join(root,'web'),dist=path.join(root,'dist');
// Fail before packaging if a public menu destination or illustration is missing.
for(const [label,href,icon] of MAIN_MENU){
const url=new URL(href);
if(url.hostname==='www.dunerealms.com'){
const relative=url.pathname==='/'?'index.html':decodeURIComponent(url.pathname.slice(1));
if(!existsSync(path.join(web,relative)))throw Error('Broken public menu link: '+label+' -> '+relative);
}
if(!existsSync(path.join(web,'assets',icon)))throw Error('Missing menu artwork: '+label+' -> '+icon);
}
for(const [page,dependencies] of [['shop.html',['shop-landing.css','shop-embed.js']],['kits.html',['kits.css','kits.js']]]){
for(const file of dependencies)if(!existsSync(path.join(web,file)))throw Error('Missing '+page+' dependency: '+file);
}
// Menu badges are now published manually through Imperial Bureau.
const homepage=readFileSync(path.join(web,'index.html'),'utf8');
const legalNotice=homepage.match(/<aside class="legal-notice"[\s\S]*?<\/aside>/)?.[0];
if(!legalNotice)throw Error('Homepage legal notice is missing');
function preparePublicHtml(html){
let result=updatePortalNavigation(html);
if(!result.includes('class="legal-notice"')){
if(!result.includes('</body>'))throw Error('Public HTML page missing closing body');
result=result.replace('</body>',legalNotice+'</body>');
}
return result;
}
import {withRealmSwitch,REALM_SWITCH_CSS} from './realm-switch.mjs';
import {HOUSE_STYLE_CSS} from './house-style.mjs';
import {bankRatesPage} from './bank-rates-page.mjs';
import{withCanonicalMenu,MAIN_MENU}from'./main-menu.mjs';
import{withMenuBadges}from'./menu-updates.mjs';
import{updatePortalNavigation}from'./portal-navigation.mjs';
// Package the authored web and worker sources without rewriting their content.
import {readFileSync,writeFileSync,openSync,writeSync,closeSync,readdirSync,statSync,mkdirSync,existsSync,rmSync,cpSync} from 'node:fs';import path from 'node:path';import {fileURLToPath} from 'node:url';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'),web=path.join(root,'web'),dist=path.join(root,'dist');
// Fail before packaging if a public menu destination or illustration is missing.
for(const [label,href,icon] of MAIN_MENU){
const url=new URL(href);
if(url.hostname==='www.dunerealms.com'){
const relative=url.pathname==='/'?'index.html':decodeURIComponent(url.pathname.slice(1));
if(!existsSync(path.join(web,relative)))throw Error('Broken public menu link: '+label+' -> '+relative);
}
if(!existsSync(path.join(web,'assets',icon)))throw Error('Missing menu artwork: '+label+' -> '+icon);
}
for(const [page,dependencies] of [['shop.html',['shop-landing.css','shop-embed.js']],['kits.html',['kits.css','kits.js']]]){
for(const file of dependencies)if(!existsSync(path.join(web,file)))throw Error('Missing '+page+' dependency: '+file);
}
// Menu badges are now published manually through Imperial Bureau.
const homepage=readFileSync(path.join(web,'index.html'),'utf8');
const legalNotice=homepage.match(/<aside class="legal-notice"[\s\S]*?<\/aside>/)?.[0];
if(!legalNotice)throw Error('Homepage legal notice is missing');
function preparePublicHtml(html){
let result=updatePortalNavigation(html);
if(!result.includes('class="legal-notice"')){
if(!result.includes('</body>'))throw Error('Public HTML page missing closing body');
result=result.replace('</body>',legalNotice+'</body>');
}
return result;
}
// Publish the shared Exchange presentation on the public origin for strict CSP.
for(const [source,target] of [['cp-v2/cp-v2-exchange-design.mjs','codex-exchange.js'],['cp-v2/cp-v2-exchange-design.css','codex-exchange.css'],['organisation-tabs.mjs','codex-tabs.js'],['organisation-tabs.css','codex-tabs.css']]){
let content=readFileSync(path.join(root,'control-panel/public',source),'utf8');
if(target.endsWith('.js'))content=content.replaceAll('../organisation-tabs.mjs','./codex-tabs.js').replaceAll('./organisation-tabs.css','./codex-tabs.css').replaceAll('./cp-v2-exchange-design.css','./codex-exchange.css');
writeFileSync(path.join(web,target),content);
}
writeFileSync(path.join(web,'rates-and-charges.html'),bankRatesPage());
let assetCount=0;let assetWriter=null;const types={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.webp':'image/webp','.png':'image/png','.mp4':'video/mp4','.zip':'application/zip','.svg':'image/svg+xml'};
function collect(directory){for(const entry of readdirSync(directory).sort()){const p=path.join(directory,entry);if(statSync(p).isDirectory())collect(p);else{const relative=path.relative(web,p).split(path.sep).join('/');if(/^assets\/seals\/[^/]+-provenance\.txt$/.test(relative)||/^assets\/organisation-deed(?:s)?-[a-z0-9-]+\.png$/.test(relative))continue;const type=types[path.extname(entry)];if(!type)throw Error('Unexpected asset: '+entry);const bytes=readFileSync(p);const payload=relative.endsWith('.html')?Buffer.from(preparePublicHtml(bytes.toString('utf8'))):relative==='portal-navigation.js'?Buffer.from(withCanonicalMenu(withMenuBadges(bytes.toString('utf8')))):relative==='portal-navigation.css'?Buffer.concat([bytes,Buffer.from(HOUSE_STYLE_CSS)]):bytes;writeSync(assetWriter,JSON.stringify('/'+relative)+':['+JSON.stringify(type)+','+JSON.stringify(payload.toString('base64'))+'],');assetCount++}}}if(existsSync(dist)){const resolved=path.resolve(dist);if(resolved!==path.join(root,'dist'))throw Error('Invalid dist directory');rmSync(resolved,{recursive:true,force:true})}
mkdirSync(path.join(dist,'server'),{recursive:true});mkdirSync(path.join(dist,'.openai'),{recursive:true});assetWriter=openSync(path.join(dist,'server/index.js'),'w');writeSync(assetWriter,'const ASSET_DATA={');collect(web);const buildCommit=process.env.GITHUB_SHA;if(buildCommit&&/^[0-9a-f]{40}$/.test(buildCommit)){writeSync(assetWriter,JSON.stringify('/ci-build.json')+':'+JSON.stringify(['application/json; charset=utf-8',Buffer.from(JSON.stringify({commit:buildCommit})).toString('base64')])+',');}writeSync(assetWriter,'};\n');
let api=['feed-api.mjs','exchange-api.mjs','forum-api.mjs','community-api.mjs','portal-api.mjs'].map(file=>readFileSync(path.join(root,'worker',file),'utf8').replace(/export /g,'')).join('\n');let runtime=readFileSync(path.join(root,'worker/runtime.mjs'),'utf8').replace(/^import .*;$/gm,'');
writeSync(assetWriter,api+'\n'+runtime);closeSync(assetWriter);cpSync(path.join(root,'.openai/hosting.json'),path.join(dist,'.openai/hosting.json'));console.log('Built Worker with',assetCount,'embedded website assets');
if(existsSync(path.join(root,'drizzle')))cpSync(path.join(root,'drizzle'),path.join(dist,'.openai/drizzle'),{recursive:true});
// Native applications consume the same compiled chrome as the public Worker.
// nginx follows the atomically promoted current release, so no stale host copy
// can retain an old Alpha version, navigation badge or rates page.
const shared=path.join(dist,'shared-chrome');mkdirSync(shared,{recursive:true});
for(const name of ['portal-navigation.js','portal-navigation.css','release.json','menu-new-items.json','rates-and-charges.html','bank-rates.css']){
let content=readFileSync(path.join(web,name));
if(name==='portal-navigation.js')content=Buffer.from(withCanonicalMenu(withMenuBadges(content.toString('utf8'))));
if(name==='portal-navigation.css')content=Buffer.concat([content,Buffer.from(HOUSE_STYLE_CSS)]);
if(name.endsWith('.html'))content=Buffer.from(preparePublicHtml(content.toString('utf8')));
writeFileSync(path.join(shared,name),content);
}
writeFileSync(path.join(web,'rates-and-charges.html'),bankRatesPage());
let assetCount=0;let assetWriter=null;const types={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.webp':'image/webp','.png':'image/png','.mp4':'video/mp4','.zip':'application/zip','.svg':'image/svg+xml'};
function collect(directory){for(const entry of readdirSync(directory).sort()){const p=path.join(directory,entry);if(statSync(p).isDirectory())collect(p);else{const relative=path.relative(web,p).split(path.sep).join('/');if(/^assets\/seals\/[^/]+-provenance\.txt$/.test(relative)||/^assets\/organisation-deed(?:s)?-[a-z0-9-]+\.png$/.test(relative))continue;const type=types[path.extname(entry)];if(!type)throw Error('Unexpected asset: '+entry);const bytes=readFileSync(p);const payload=relative.endsWith('.html')?Buffer.from(preparePublicHtml(bytes.toString('utf8'))):relative==='portal-navigation.js'?Buffer.from(withRealmSwitch(withCanonicalMenu(withMenuBadges(bytes.toString('utf8'))))):relative==='portal-navigation.css'?Buffer.concat([bytes,Buffer.from(HOUSE_STYLE_CSS+REALM_SWITCH_CSS)]):bytes;writeSync(assetWriter,JSON.stringify('/'+relative)+':['+JSON.stringify(type)+','+JSON.stringify(payload.toString('base64'))+'],');assetCount++}}}if(existsSync(dist)){const resolved=path.resolve(dist);if(resolved!==path.join(root,'dist'))throw Error('Invalid dist directory');rmSync(resolved,{recursive:true,force:true})}
mkdirSync(path.join(dist,'server'),{recursive:true});mkdirSync(path.join(dist,'.openai'),{recursive:true});assetWriter=openSync(path.join(dist,'server/index.js'),'w');writeSync(assetWriter,'const ASSET_DATA={');collect(web);const buildCommit=process.env.GITHUB_SHA;if(buildCommit&&/^[0-9a-f]{40}$/.test(buildCommit)){writeSync(assetWriter,JSON.stringify('/ci-build.json')+':'+JSON.stringify(['application/json; charset=utf-8',Buffer.from(JSON.stringify({commit:buildCommit})).toString('base64')])+',');}writeSync(assetWriter,'};\n');
let api=['feed-api.mjs','exchange-api.mjs','forum-api.mjs','community-api.mjs','portal-api.mjs'].map(file=>readFileSync(path.join(root,'worker',file),'utf8').replace(/export /g,'')).join('\n');let runtime=readFileSync(path.join(root,'worker/runtime.mjs'),'utf8').replace(/^import .*;$/gm,'');
writeSync(assetWriter,api+'\n'+runtime);closeSync(assetWriter);cpSync(path.join(root,'.openai/hosting.json'),path.join(dist,'.openai/hosting.json'));console.log('Built Worker with',assetCount,'embedded website assets');
if(existsSync(path.join(root,'drizzle')))cpSync(path.join(root,'drizzle'),path.join(dist,'.openai/drizzle'),{recursive:true});
// Native applications consume the same compiled chrome as the public Worker.
// nginx follows the atomically promoted current release, so no stale host copy
// can retain an old Alpha version, navigation badge or rates page.
const shared=path.join(dist,'shared-chrome');mkdirSync(shared,{recursive:true});
for(const name of ['portal-navigation.js','portal-navigation.css','release.json','menu-new-items.json','rates-and-charges.html','bank-rates.css']){
let content=readFileSync(path.join(web,name));
if(name==='portal-navigation.js')content=Buffer.from(withRealmSwitch(withCanonicalMenu(withMenuBadges(content.toString('utf8')))));
if(name==='portal-navigation.css')content=Buffer.concat([content,Buffer.from(HOUSE_STYLE_CSS+REALM_SWITCH_CSS)]);
if(name.endsWith('.html'))content=Buffer.from(preparePublicHtml(content.toString('utf8')));
writeFileSync(path.join(shared,name),content);
}

View file

@ -1,14 +1,14 @@
export const MAIN_MENU=[["Home","https://www.dunerealms.com/","nav-home-v2.webp"],["Shop","https://shop.dunerealms.com/","nav-shop-v1.webp"],["Boards","https://forums.dunerealms.com/","nav-boards-v2.webp"],["Roster","https://www.dunerealms.com/staff.html","nav-staff-v2.webp"],["Discord","https://www.dunerealms.com/discord.html","nav-discord-v2.webp"],["Exchange","https://www.dunerealms.com/exchange.html","nav-exchange-v2.webp"],["Kits","https://www.dunerealms.com/exchange.html?type=kits","items/office_water.png"],["Politics","https://www.dunerealms.com/government.html","seals/office-landsraad.png"],["Clans","https://clans.dunerealms.com/","nav-clan-v2.webp"],["Companies","https://corp.dunerealms.com/","guild.webp"],["CP","https://cp.dunerealms.com/","nav-account-v2.webp"],["Support","https://support.dunerealms.com/","nav-support-v2.webp"],["Dunopedia","https://wiki.dunerealms.com/","nav-manual-v2.webp"]];
export function canonicalMenuHref(value){const u=new URL(value,'https://www.dunerealms.com');if(u.hostname==='dunerealms.com')u.hostname='www.dunerealms.com';if(u.hostname==='www.dunerealms.com'&&/^\/(manual|wiki)\.html$/.test(u.pathname))return'https://wiki.dunerealms.com/';if(u.hostname==='cp.dunerealms.com'&&u.pathname==='/'){if(u.hash==='#shop')return'https://shop.dunerealms.com/';if(u.hash==='#exchange')return'https://www.dunerealms.com/exchange.html';}if(['forums','support','cp','clans','corp','wiki'].some(h=>u.hostname===h+'.dunerealms.com'))return u.origin+'/';const kits=u.pathname==='/exchange.html'&&/^kits(?:-(?:clan|office|player|legendary))?$/.test(u.searchParams.get('type')||'');return u.origin+(u.pathname==='/index.html'?'/':u.pathname)+(kits?'?type=kits':'');}
export function normalizeMainMenus(doc,currentUrl,links=MAIN_MENU){let changes=0;const set=(node,key,value)=>{if(node.getAttribute(key)!==value){node.setAttribute(key,value);changes++;}};
for(const nav of doc.querySelectorAll('header nav[aria-label="Main navigation"]')){const old=[...nav.querySelectorAll('a')],ordered=[];for(const[name,href,icon]of links){let a=old.find(x=>!ordered.includes(x)&&canonicalMenuHref(x.href)===href);if(!a){a=doc.createElement('a');changes++;}set(a,'href',href);let image=a.querySelector('img');if(!image){image=doc.createElement('img');a.insertBefore(image,a.firstChild);changes++;}set(image,'src','https://www.dunerealms.com/assets/'+icon);set(image,'alt','');set(image,'width','34');set(image,'height','34');let label=[...a.children].find(x=>x.tagName==='SPAN'&&!x.classList.contains('dune-new-overlay')&&!x.classList.contains('dune-sales-overlay'));if(!label){label=doc.createElement('span');a.append(label);changes++;}set(label,'data-dune-nav-label','1');if(label.textContent!==name){label.textContent=name;changes++;}for(const n of [...a.childNodes])if(n.nodeType===3){n.remove();changes++;}const active=canonicalMenuHref(currentUrl)===href;if(active)set(a,'aria-current','page');else if(a.hasAttribute('aria-current')){a.removeAttribute('aria-current');changes++;}ordered.push(a);}
for(const a of old)if(!ordered.includes(a)){a.remove();changes++;}let cursor=nav.firstElementChild;for(const a of ordered){if(a!==cursor){nav.insertBefore(a,cursor);changes++;}cursor=a.nextElementSibling;}}
return changes;
}
export const CANONICAL_MENU_SCRIPT='\n/* Dune canonical menu begin */\n(()=>{if(window.top!==window.self)return;const MAIN_MENU='+JSON.stringify(MAIN_MENU)+';const canonicalMenuHref='+canonicalMenuHref.toString()+';const normalizeMainMenus='+normalizeMainMenus.toString()+';const sync=()=>normalizeMainMenus(document,location.href,MAIN_MENU);sync();new MutationObserver(sync).observe(document.body,{childList:true,subtree:true});})();\n/* Dune canonical menu end */\n';
export function withCanonicalMenu(script){
// Older published assets may contain a generated controller without its marker comments.
// Remove both forms before installing the single current controller.
return script.replace(/\n?\/\* Dune canonical menu begin \*\/[^]*?\/\* Dune canonical menu end \*\/\n?/g,'')
.replace(/\(\(\)=>\{if\(window\.top!==window\.self\)return;const MAIN_MENU=[^]*?const sync=\(\)=>normalizeMainMenus\(document,location\.href,MAIN_MENU\);sync\(\);new MutationObserver\(sync\)\.observe\(document\.body,\{childList:true,subtree:true\}\);\}\)\(\);/g,'')+CANONICAL_MENU_SCRIPT;
}
export const MAIN_MENU=[["Home","https://www.dunerealms.com/","nav-home-v2.webp"],["Shop","https://shop.dunerealms.com/","nav-shop-v1.webp"],["Imperial Forums","https://forums.dunerealms.com/","nav-boards-v2.webp"],["Guild Comms","https://www.dunerealms.com/discord.html","nav-discord-v2.webp"],["Imperial Directorate","https://www.dunerealms.com/staff.html","nav-staff-v2.webp"],["Starport","https://www.dunerealms.com/exchange.html","nav-exchange-v2.webp"],["Realm Nexus","https://www.dunerealms.com/realm-hub.html","nav-clan-v2.webp"],["Citizen Passport","https://cp.dunerealms.com/","nav-account-v2.webp"],["Support","https://support.dunerealms.com/","nav-support-v2.webp"],["Imperial Archives","https://wiki.dunerealms.com/","nav-manual-v2.webp"]];
export function canonicalMenuHref(value){const u=new URL(value,'https://www.dunerealms.com');if(u.hostname==='dunerealms.com')u.hostname='www.dunerealms.com';if(u.hostname==='www.dunerealms.com'&&/^\/(manual|wiki)\.html$/.test(u.pathname))return'https://wiki.dunerealms.com/';if(u.hostname==='cp.dunerealms.com'&&u.pathname==='/'){if(u.hash==='#shop')return'https://shop.dunerealms.com/';if(u.hash==='#exchange')return'https://www.dunerealms.com/exchange.html';}if(['forums','support','cp','clans','corp','wiki'].some(h=>u.hostname===h+'.dunerealms.com'))return u.origin+'/';const kits=u.pathname==='/exchange.html'&&/^kits(?:-(?:clan|office|player|legendary))?$/.test(u.searchParams.get('type')||'');return u.origin+(u.pathname==='/index.html'?'/':u.pathname)+(kits?'?type=kits':'');}
export function normalizeMainMenus(doc,currentUrl,links=MAIN_MENU){let changes=0;const set=(node,key,value)=>{if(node.getAttribute(key)!==value){node.setAttribute(key,value);changes++;}};
for(const nav of doc.querySelectorAll('header nav[aria-label="Main navigation"]')){const old=[...nav.querySelectorAll('a')],ordered=[];for(const[name,href,icon]of links){let a=old.find(x=>!ordered.includes(x)&&canonicalMenuHref(x.href)===href);if(!a){a=doc.createElement('a');changes++;}set(a,'href',href);let image=a.querySelector('img');if(!image){image=doc.createElement('img');a.insertBefore(image,a.firstChild);changes++;}set(image,'src','https://www.dunerealms.com/assets/'+icon);set(image,'alt','');set(image,'width','34');set(image,'height','34');let label=[...a.children].find(x=>x.tagName==='SPAN'&&!x.classList.contains('dune-new-overlay')&&!x.classList.contains('dune-sales-overlay'));if(!label){label=doc.createElement('span');a.append(label);changes++;}set(label,'data-dune-nav-label','1');if(label.textContent!==name){label.textContent=name;changes++;}for(const n of [...a.childNodes])if(n.nodeType===3){n.remove();changes++;}const active=canonicalMenuHref(currentUrl)===href;if(active)set(a,'aria-current','page');else if(a.hasAttribute('aria-current')){a.removeAttribute('aria-current');changes++;}ordered.push(a);}
for(const a of old)if(!ordered.includes(a)){a.remove();changes++;}let cursor=nav.firstElementChild;for(const a of ordered){if(a!==cursor){nav.insertBefore(a,cursor);changes++;}cursor=a.nextElementSibling;}}
return changes;
}
export const CANONICAL_MENU_SCRIPT='\n/* Dune canonical menu begin */\n(()=>{if(window.top!==window.self)return;const MAIN_MENU='+JSON.stringify(MAIN_MENU)+';const canonicalMenuHref='+canonicalMenuHref.toString()+';const normalizeMainMenus='+normalizeMainMenus.toString()+';const sync=()=>normalizeMainMenus(document,location.href,MAIN_MENU);sync();new MutationObserver(sync).observe(document.body,{childList:true,subtree:true});})();\n/* Dune canonical menu end */\n';
export function withCanonicalMenu(script){
// Older published assets may contain a generated controller without its marker comments.
// Remove both forms before installing the single current controller.
return script.replace(/\n?\/\* Dune canonical menu begin \*\/[^]*?\/\* Dune canonical menu end \*\/\n?/g,'')
.replace(/\(\(\)=>\{if\(window\.top!==window\.self\)return;const MAIN_MENU=[^]*?const sync=\(\)=>normalizeMainMenus\(document,location\.href,MAIN_MENU\);sync\(\);new MutationObserver\(sync\)\.observe\(document\.body,\{childList:true,subtree:true\}\);\}\)\(\);/g,'')+CANONICAL_MENU_SCRIPT;
}

View file

@ -1,7 +1,7 @@
import {MAIN_MENU} from './main-menu.mjs';
import{existsSync,readFileSync,writeFileSync}from'node:fs';import{execFileSync}from'node:child_process';import{fileURLToPath}from'node:url';import path from'node:path';import{RELEASE_VERSION}from'./release-branding.mjs';
export function pagesForChanges(paths){const pages=new Set();for(let p of paths){p=p.replaceAll('\\','/');if(!p.includes('/tests/')){if(/^website\/(?:web\/portal-navigation\.(?:css|js)|scripts\/(?:portal-navigation|main-menu)\.mjs)$/.test(p))for(const [,href]of MAIN_MENU)pages.add(href);const scopes=[[/postbank|bank-rates/,'bank'],[/politic|election|charter/,'politics'],[/internal-mail|mail-service|post-pages/,'post'],[/organisation-|citizen-directory|account-admin|honours|permissions/,'bureau'],[/forge-pages|dev-request|git-identity/,'forge'],[/exchange-public|commodity/,'market'],[/passport|personal-records|user-pages/,'realm']];for(const [pattern,scope]of scopes)if(pattern.test(p)){pages.add('https://cp.dunerealms.com/');pages.add('https://cp.dunerealms.com/#'+scope);}}if(/website\/node\/staff-roster\.mjs$/.test(p))pages.add('https://www.dunerealms.com/staff.html');if(/website\/node\/memorials\.mjs$|website\/node\/public\/memorial\./.test(p))pages.add('https://www.dunerealms.com/');if(/website\/control-panel\//.test(p)||/website\/node\/(auth|permissions|account-admin|account-archive|honours|profile)\.mjs$/.test(p))pages.add('https://cp.dunerealms.com/');if(/website\/integrations\/azuriom\//.test(p))pages.add('https://www.dunerealms.com/shop.html');if(/website\/integrations\/osticket\//.test(p))pages.add('https://support.dunerealms.com/');if(/website\/web\/([a-z-]+)\.html$/.test(p)){const name=p.match(/([^/]+)\.html$/)[1];pages.add('https://www.dunerealms.com/'+(['index','portal'].includes(name)?'':name+'.html'));}}return[...pages].sort();}
export function recordPageUpdates({root=fileURLToPath(new URL('../',import.meta.url)),paths,newPages=[],version=RELEASE_VERSION}={}){if(!/^\d+(?:\.\d+){3}$/.test(version))throw Error('Invalid release');const repo=path.resolve(root,'..');const publication=path.join(root,'publication-changes.json');if(paths===undefined&&existsSync(publication)){const change=JSON.parse(readFileSync(publication,'utf8'));if(!Array.isArray(change.paths)||!Array.isArray(change.added))throw Error('Invalid publication change record.');paths=change.paths;newPages=pagesForChanges(change.added).filter(href=>!href.startsWith('https://cp.dunerealms.com/'));}if(paths===undefined){let changed='';try{const gitRoot=execFileSync('git',['rev-parse','--show-toplevel'],{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim();if(path.resolve(gitRoot)===repo)changed=execFileSync('git',['diff','--name-only','HEAD'],{cwd:repo,encoding:'utf8'}).trim();}catch(error){if(error?.status!==128&&error?.status!==129&&error?.code!=='ENOENT')throw error;}paths=changed?changed.split('\n'):[];}const file=path.join(root,'web/menu-new-items.json'),data=JSON.parse(readFileSync(file,'utf8'));const pages=pagesForChanges(paths);if(paths.includes('website/web/release.json')){const releaseFile=path.join(root,'web/release.json');if(existsSync(releaseFile)){const release=JSON.parse(readFileSync(releaseFile,'utf8'));if(release.version===version&&Array.isArray(release.menuUpdates)){const allowed=new Set([...MAIN_MENU.map(([,href])=>href),...['realm','bureau','forge','politics','post','bank','market'].map(id=>'https://cp.dunerealms.com/#'+id)]);for(const update of release.menuUpdates){if(!allowed.has(update.href)||!['NEW','UPDATE'].includes(update.badge))throw Error('Invalid release menu highlight.');if(!pages.includes(update.href))pages.push(update.href);if(update.badge==='NEW'&&!newPages.includes(update.href))newPages.push(update.href);}}}}if(paths.length||existsSync(publication)){for(const item of data.items)delete item.badge;}for(const href of pages){let entry=data.items.find(x=>x.href===href);if(!entry){entry={href};data.items.push(entry);}entry.updatedIn=version;entry.badge=newPages.includes(href)?'NEW':'UPDATE';}if(data.headerBadges){for(const item of data.items){if(!item.href.includes('/#')){delete item.badge;if(['NEW','UPDATE'].includes(data.headerBadges[item.href]))item.badge=data.headerBadges[item.href];}}}writeFileSync(file,JSON.stringify(data,null,2)+'\n');return pages;}
export function pagesForChanges(paths){const pages=new Set();for(let p of paths){p=p.replaceAll('\\','/');if(!p.includes('/tests/')){if(/^website\/(?:web\/portal-navigation\.(?:css|js)|scripts\/(?:portal-navigation|main-menu)\.mjs)$/.test(p))for(const href of [...MAIN_MENU.map(([,href])=>href),'https://clans.dunerealms.com/','https://corp.dunerealms.com/','https://www.dunerealms.com/government.html'])pages.add(href);const scopes=[[/postbank|bank-rates/,'bank'],[/politic|election|charter/,'politics'],[/internal-mail|mail-service|post-pages/,'post'],[/organisation-|citizen-directory|account-admin|honours|permissions/,'bureau'],[/forge-pages|dev-request|git-identity/,'forge'],[/exchange-public|commodity/,'market'],[/passport|personal-records|user-pages/,'realm']];for(const [pattern,scope]of scopes)if(pattern.test(p)){pages.add('https://cp.dunerealms.com/');pages.add('https://cp.dunerealms.com/#'+scope);}}if(/website\/node\/staff-roster\.mjs$/.test(p))pages.add('https://www.dunerealms.com/staff.html');if(/website\/node\/memorials\.mjs$|website\/node\/public\/memorial\./.test(p))pages.add('https://www.dunerealms.com/');if(/website\/control-panel\//.test(p)||/website\/node\/(auth|permissions|account-admin|account-archive|honours|profile)\.mjs$/.test(p))pages.add('https://cp.dunerealms.com/');if(/website\/integrations\/azuriom\//.test(p))pages.add('https://www.dunerealms.com/shop.html');if(/website\/integrations\/osticket\//.test(p))pages.add('https://support.dunerealms.com/');if(/website\/web\/([a-z-]+)\.html$/.test(p)){const name=p.match(/([^/]+)\.html$/)[1];pages.add('https://www.dunerealms.com/'+(['index','portal'].includes(name)?'':name+'.html'));}}return[...pages].sort();}
export function recordPageUpdates({root=fileURLToPath(new URL('../',import.meta.url)),paths,newPages=[],version=RELEASE_VERSION}={}){if(!/^\d+(?:\.\d+){3}$/.test(version))throw Error('Invalid release');const repo=path.resolve(root,'..');const publication=path.join(root,'publication-changes.json');if(paths===undefined&&existsSync(publication)){const change=JSON.parse(readFileSync(publication,'utf8'));if(!Array.isArray(change.paths)||!Array.isArray(change.added))throw Error('Invalid publication change record.');paths=change.paths;newPages=pagesForChanges(change.added).filter(href=>!href.startsWith('https://cp.dunerealms.com/'));}if(paths===undefined){let changed='';try{const gitRoot=execFileSync('git',['rev-parse','--show-toplevel'],{cwd:repo,encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim();if(path.resolve(gitRoot)===repo)changed=execFileSync('git',['diff','--name-only','HEAD'],{cwd:repo,encoding:'utf8'}).trim();}catch(error){if(error?.status!==128&&error?.status!==129&&error?.code!=='ENOENT')throw error;}paths=changed?changed.split('\n'):[];}const file=path.join(root,'web/menu-new-items.json'),data=JSON.parse(readFileSync(file,'utf8'));const pages=pagesForChanges(paths);if(paths.includes('website/web/release.json')){const releaseFile=path.join(root,'web/release.json');if(existsSync(releaseFile)){const release=JSON.parse(readFileSync(releaseFile,'utf8'));if(release.version===version&&Array.isArray(release.menuUpdates)){const allowed=new Set([...MAIN_MENU.map(([,href])=>href),'https://clans.dunerealms.com/','https://corp.dunerealms.com/','https://www.dunerealms.com/government.html',...['realm','bureau','forge','politics','post','bank','market'].map(id=>'https://cp.dunerealms.com/#'+id)]);for(const update of release.menuUpdates){if(!allowed.has(update.href)||!['NEW','UPDATE'].includes(update.badge))throw Error('Invalid release menu highlight.');if(!pages.includes(update.href))pages.push(update.href);if(update.badge==='NEW'&&!newPages.includes(update.href))newPages.push(update.href);}}}}if(paths.length||existsSync(publication)){for(const item of data.items)delete item.badge;}for(const href of pages){let entry=data.items.find(x=>x.href===href);if(!entry){entry={href};data.items.push(entry);}entry.updatedIn=version;entry.badge=newPages.includes(href)?'NEW':'UPDATE';}if(data.headerBadges){for(const item of data.items){if(!item.href.includes('/#')){delete item.badge;if(['NEW','UPDATE'].includes(data.headerBadges[item.href]))item.badge=data.headerBadges[item.href];}}}writeFileSync(file,JSON.stringify(data,null,2)+'\n');return pages;}
export function menuBadgeScript(){const data=JSON.parse(readFileSync(new URL('../web/menu-new-items.json',import.meta.url),'utf8'));return `\n/* Central automatic release menu badges */\n(()=>{let items=${JSON.stringify(data.items)};function mark(){const release=document.querySelector('.dune-release-badge')?.textContent.match(/\\d+(?:\\.\\d+){3}/)?.[0];for(const a of document.querySelectorAll('header nav[aria-label="Main navigation"] a,#portals .portal[data-id]')){const href=a.matches('#portals .portal')?(document.body.dataset.cpMode==='clan'?'https://clans.dunerealms.com/#':'https://cp.dunerealms.com/#')+a.dataset.id:a.href;const item=items.find(x=>x.href===href),label=['NEW','UPDATE'].includes(item?.badge)?item.badge:null;let tag=a.querySelector('.dune-new-overlay');if(label){if(!tag){tag=document.createElement('span');tag.className='dune-new-overlay';a.append(tag);}if(tag.textContent!==label)tag.textContent=label;tag.classList.toggle('dune-update-overlay',label==='UPDATE');tag.setAttribute('aria-label',label==='NEW'?'New this release':'Updated this release');}else if(tag)tag.remove();}}fetch('https://cp.dunerealms.com/api/menu-badges',{cache:'no-store'}).then(r=>r.ok?r.json():null).then(data=>{if(Array.isArray(data?.items)){items=data.items;mark();}}).catch(()=>{});mark();new MutationObserver(mark).observe(document.body,{childList:true,subtree:true,characterData:true});})();\n`;}
const legacyMenuBadges=/\(\(\)=>\{(?:let|const) items=\[[^]*?new MutationObserver\(mark\)\.observe\(document.body,\{childList:true,subtree:true,characterData:true\}\);\}\)\(\);/g;
export function withMenuBadges(s){return s.replace(legacyMenuBadges,'').replace(/\n?\/\* Central automatic release menu badges \*\/[\s\S]*?(?=\n\/\*|$)/,'').replace(/\(\(\)=>\{const items=\[[\s\S]*?new MutationObserver\(mark\)\.observe\(document.body,\{childList:true,subtree:true,characterData:true\}\);\}\)\(\);/,'')+menuBadgeScript();}

View file

@ -0,0 +1,7 @@
export function realmSurface(url){const u=new URL(url,'https://www.dunerealms.com');if(u.hostname==='clans.dunerealms.com')return 'clan';if(u.hostname==='corp.dunerealms.com')return 'company';if(u.hostname==='pol.dunerealms.com'||u.hostname==='www.dunerealms.com'&&u.pathname==='/government.html')return 'politics';return null;}
export function renderRealmSwitch(doc,url){const kind=realmSurface(url),existing=doc.querySelector('[data-realm-switch]');if(!kind){existing?.remove();return;}const banner=doc.querySelector('.dune-context-banner');if(!banner||existing)return;const nav=doc.createElement('nav');nav.className='dune-realm-switch';nav.dataset.realmSwitch='';nav.setAttribute('aria-label','Realm workspace');for(const [id,title,sub,href,art]of [['clan','Clans','Houses & alliances','https://clans.dunerealms.com/','nav-clan-v2.webp'],['company','Companies','Trade & enterprise','https://corp.dunerealms.com/','guild.webp'],['politics','Politics','Offices & the realm','https://www.dunerealms.com/government.html','seals/office-landsraad.png']]){const a=doc.createElement('a'),image=doc.createElement('img'),copy=doc.createElement('span'),label=doc.createElement('strong'),detail=doc.createElement('small');a.href=href;a.className='dune-realm-choice dune-realm-'+id;a.target='_top';image.src='https://www.dunerealms.com/assets/'+art;image.alt='';label.textContent=title;detail.textContent=sub;copy.append(label,detail);a.append(image,copy);if(id===kind){a.setAttribute('aria-current','page');const seal=doc.createElement('span');seal.className='dune-realm-active';seal.textContent='ACTIVE';a.append(seal);}nav.append(a);}banner.append(nav);}
export const REALM_SWITCH_CSS=`
.dune-context-banner:has(.dune-realm-switch){flex-wrap:wrap;gap:18px;padding-top:14px;padding-bottom:14px}.dune-realm-switch{display:flex;gap:12px;justify-content:center;order:1;margin:auto;max-width:100%;box-sizing:border-box}.dune-realm-choice{position:relative;display:flex;align-items:center;gap:12px;min-width:150px;padding:12px 20px;border:3px double #b99a55;border-radius:10px;background:linear-gradient(145deg,#214939ed,#0d241fed);color:#efd797;text-decoration:none;box-shadow:inset 0 0 0 3px #122b23,0 4px 9px #0005;box-sizing:border-box}.dune-realm-company{background:linear-gradient(145deg,#28495bed,#102831ed)}.dune-realm-politics{background:linear-gradient(145deg,#493954ed,#182a2aed)}.dune-realm-choice img{width:52px;height:52px;object-fit:contain;filter:drop-shadow(0 3px 4px #0008)}.dune-realm-choice strong{display:block;font:700 20px Georgia,serif}.dune-realm-choice small{display:block;margin-top:5px;color:#d1c29d;font:11px Arial,sans-serif}.dune-realm-choice[aria-current]{border-color:#f2d17e;box-shadow:inset 0 0 0 3px #b2954d55,0 0 16px #e3bb5633}.dune-realm-active{position:absolute;right:8px;top:-9px;padding:3px 7px;background:#bd9c53;color:#10251e;font:700 9px Arial,sans-serif;letter-spacing:.08em;border-radius:4px}.dune-realm-choice:hover,.dune-realm-choice:focus-visible{outline:2px solid #f1d58f;outline-offset:3px}@media(max-width:1100px){.dune-realm-switch{flex-basis:100%;order:3}}@media(max-width:600px){.dune-realm-switch{gap:7px;width:100%}.dune-realm-choice{flex:1;min-width:0;padding:12px 5px;gap:6px;flex-direction:column;text-align:center}.dune-realm-choice img{width:38px;height:38px}.dune-realm-choice strong{font-size:15px}.dune-realm-choice small{display:none}.dune-realm-active{font-size:8px;right:4px}}
`;
export const REALM_SWITCH_SCRIPT='\n/* Dune realm switch begin */\n(()=>{if(window.top!==window.self)return;const realmSurface='+realmSurface.toString()+';const renderRealmSwitch='+renderRealmSwitch.toString()+';const sync=()=>renderRealmSwitch(document,location.href);sync();new MutationObserver(sync).observe(document.body,{childList:true,subtree:true});})();\n/* Dune realm switch end */\n';
export function withRealmSwitch(source){return source.replace(/\n?\/\* Dune realm switch begin \*\/[^]*?\/\* Dune realm switch end \*\/\n?/g,'')+REALM_SWITCH_SCRIPT;}