"""Generate typed settings metadata from the pinned, audited OpenWF UI.
Build-time tool only. Neither the server nor the desktop executes JavaScript.
"""
from pathlib import Path
from lxml import html
import json,re
root=Path(__file__).resolve().parents[1]
audit=root/'artifacts/openwf-frontend-audit-20260926'
source=audit/'SpaceNinjaServer/static/webui'
data=json.loads((audit/'source-inventory.json').read_text(encoding='utf-8'))
tree=html.fromstring((source/'index.html').read_text(encoding='utf-8'))
dictionary=json.loads((root/'Server/data/export/dict.zh.json').read_text(encoding='utf-8-sig'))
dictionary.update(json.loads((root/'Server/data/fixed_responses/supplementalDict/zh.json').read_text(encoding='utf-8-sig')))
locales={m[1]:re.sub(r'<[^>]*>','',m[2]) for m in re.finditer(r'^\s*(\w+):\s*`((?:\\.|[^`])*)`',(source/'translations/zh.js').read_text(encoding='utf-8'),re.M)}
def label(e,fallback):
if e is None:return fallback
key=e.get('data-loc-itemmap') or e.get('data-loc-itemmap-tc')
text=dictionary.get(key,locales.get(e.get('data-loc'),e.text_content().strip())) or fallback
text=text.replace('|VAL|',e.get('data-loc-replace','')).replace('|val|',e.get('data-loc-replace',''))
return re.sub(r'<[^>]*>','',text) if not text.startswith('[UNTRANSLATED]') else fallback
def value(raw):
if raw is None:return ''
try:return json.loads(raw)
except ValueError:return raw
groups={}
for scope,group in [('account','account-cheats'),('guild','guild-cheats'),('server','server-config')]:
fields=[]
for c in data['settings'][group]:
if c['id']=='changeSyndicate':continue
e=tree.get_element_by_id(c['id']);a=c['attributes'];elabel=tree.xpath('//label[@for=$id]',id=c['id'])
if not elabel:elabel=e.getparent().xpath('.//*[@data-loc-itemmap or @data-loc]')
title=label(elabel[0] if elabel else None,c['label'] or c['id'])
typ='bool' if a.get('type')=='checkbox' else 'number' if a.get('type')=='number' else 'choice' if c['tag']=='select' else 'strings'
field=dict(key=c['id'],label=title,type=typ,source='static/webui/index.html:'+str(c['line']))
for key in ['min','max','step']:
if a.get(key):field[key]=value(a[key])
if typ=='number':field['integer']=a.get('step','1') not in ('any','0.1','0.01','0.001')
if c['options']:field['options']=[dict(label=label(o,o.get('value','')),value=value(o.get('value'))) for o in e.findall('option')]
fields.append(field)
groups[scope]=fields
output=root/'Server/data/editor/settings.json';output.parent.mkdir(parents=True,exist_ok=True)
output.write_text(json.dumps(dict(schemaVersion=1,sourceCommit=data['source']['serverCommit'],groups=groups),ensure_ascii=False,indent=2),encoding='utf-8')
print({scope:len(fields) for scope,fields in groups.items()})
# Extract literal reference data without evaluating upstream JavaScript.
script=(source/'script.js').read_text(encoding='utf-8')
shards={}
block=script.split('data.archonCrystalUpgrades = {',1)[1].split('\n };',1)[0]
for line in block.splitlines():
if not line.strip():continue
m=re.fullmatch(r'\s*"([^"]+)": getAddDict\("([^"]+)"\)((?:\.replaceAll\("[^"]*", "[^"]*"\))*)[,]?\s*',line)
if not m:raise ValueError('Unrecognized shard expression: '+line)
text=dictionary.get(m[2],m[2]).replace('|OPEN_COLOR|','').replace('|CLOSE_COLOR|','')
for pair in re.finditer(r'\.replaceAll\("([^"]*)", "([^"]*)"\)',m[3]):text=text.replace(pair[1],pair[2])
shards[m[1]]=re.sub(r'<[^>]*>','',text)
choices={'shards':shards}
for key in ['invigoration-offensive','invigoration-defensive']:
choices[key]={o.get('value',''):label(o,o.get('value','')) for o in tree.get_element_by_id(key).findall('option')}
(output.parent/'choices.json').write_text(json.dumps(choices,ensure_ascii=False,indent=2),encoding='utf-8')
samples=(source/'script.importSamples.js').read_text(encoding='utf-8').removeprefix('window.importSamples = ').strip().removesuffix(';')
# The reference file contains only JSON literals and unquoted property names.
# Tokenize strings first so colons or braces inside strings cannot be rewritten.
tokens=re.findall(r'"(?:\\.|[^"\\])*"|//[^\n]*|\s+|[A-Za-z_$][\w$]*|[^\s]',samples)
normalized=[]
for index,token in enumerate(tokens):
if token.startswith('//'):continue
following=next((x for x in tokens[index+1:] if not x.isspace()),'')
normalized.append(json.dumps(token) if re.fullmatch(r'[A-Za-z_$][\w$]*',token) and following==':' else token)
samples=json.loads(''.join(normalized))
(output.parent/'import-samples.json').write_text(json.dumps(samples,ensure_ascii=False,indent=2),encoding='utf-8')
print({'shardChoices':len(shards),'importSamples':len(samples)})
riven=(audit/'riven-tool/package/RivenParser.js').read_text(encoding='utf-8')
tags=json.loads(riven.split('const riven_tags = ',1)[1].split(';',1)[0])
(output.parent/'riven-tags.json').write_text(json.dumps(tags,ensure_ascii=False,indent=2),encoding='utf-8')
item_data=(audit/'SpaceNinjaServer/src/services/itemDataService.ts').read_text(encoding='utf-8')
def literal(text,refs=None):
tokens=re.findall(r'"(?:\\.|[^"\\])*"|//[^\n]*|/\*[\s\S]*?\*/|\s+|[A-Za-z_$][\w$]*|[^\s]',text)
normalized=[]
for i,t in enumerate(tokens):
if t.startswith('//') or t.startswith('/*'):continue
following=next((x for x in tokens[i+1:] if not x.isspace() and not x.startswith('//')),'')
if re.fullmatch(r'[A-Za-z_$][\w$]*',t):
if following==':':t=json.dumps(t)
elif refs and t in refs:t=json.dumps(refs[t])
normalized.append(t)
return json.loads(''.join(normalized))
weapon_stats=literal(item_data.split('const U5WeaponUpgrades: IU5FingerprintUpgrade[] = ',1)[1].split('\n];',1)[0]+'\n]')
legacy=literal(item_data.split('export const U5Modules: Record<string, IU5FingerprintData> = ',1)[1].split('\n};',1)[0]+'\n}',{'U5WeaponUpgrades':weapon_stats})
(output.parent/'legacy-mods.json').write_text(json.dumps(legacy,ensure_ascii=False,indent=2),encoding='utf-8')
print({'legacyMods':len(legacy)})
"""Generate typed settings metadata from the pinned, audited OpenWF UI.
Build-time tool only. Neither the server nor the desktop executes JavaScript.
"""
from pathlib import Path
from lxml import html
import json,re
root=Path(__file__).resolve().parents[1]
audit=root/'artifacts/openwf-frontend-audit-20260926'
source=audit/'SpaceNinjaServer/static/webui'
data=json.loads((audit/'source-inventory.json').read_text(encoding='utf-8'))
tree=html.fromstring((source/'index.html').read_text(encoding='utf-8'))
dictionary=json.loads((root/'Server/data/export/dict.zh.json').read_text(encoding='utf-8-sig'))
dictionary.update(json.loads((root/'Server/data/fixed_responses/supplementalDict/zh.json').read_text(encoding='utf-8-sig')))
locales={m[1]:re.sub(r'<[^>]*>','',m[2]) for m in re.finditer(r'^\s*(\w+):\s*`((?:\\.|[^`])*)`',(source/'translations/zh.js').read_text(encoding='utf-8'),re.M)}
def label(e,fallback):
if e is None:return fallback
key=e.get('data-loc-itemmap') or e.get('data-loc-itemmap-tc')
text=dictionary.get(key,locales.get(e.get('data-loc'),e.text_content().strip())) or fallback
text=text.replace('|VAL|',e.get('data-loc-replace','')).replace('|val|',e.get('data-loc-replace',''))
return re.sub(r'<[^>]*>','',text) if not text.startswith('[UNTRANSLATED]') else fallback
def value(raw):
if raw is None:return ''
try:return json.loads(raw)
except ValueError:return raw
groups={}
for scope,group in [('account','account-cheats'),('guild','guild-cheats'),('server','server-config')]:
fields=[]
for c in data['settings'][group]:
if c['id']=='changeSyndicate':continue
e=tree.get_element_by_id(c['id']);a=c['attributes'];elabel=tree.xpath('//label[@for=$id]',id=c['id'])
if not elabel:elabel=e.getparent().xpath('.//*[@data-loc-itemmap or @data-loc]')
title=label(elabel[0] if elabel else None,c['label'] or c['id'])
typ='bool' if a.get('type')=='checkbox' else 'number' if a.get('type')=='number' else 'choice' if c['tag']=='select' else 'strings'
field=dict(key=c['id'],label=title,type=typ,source='static/webui/index.html:'+str(c['line']))
for key in ['min','max','step']:
if a.get(key):field[key]=value(a[key])
if typ=='number':field['integer']=a.get('step','1') not in ('any','0.1','0.01','0.001')
if c['options']:field['options']=[dict(label=label(o,o.get('value','')),value=value(o.get('value'))) for o in e.findall('option')]
fields.append(field)
groups[scope]=fields
output=root/'Server/data/editor/settings.json';output.parent.mkdir(parents=True,exist_ok=True)
output.write_text(json.dumps(dict(schemaVersion=1,sourceCommit=data['source']['serverCommit'],groups=groups),ensure_ascii=False,indent=2),encoding='utf-8')
print({scope:len(fields) for scope,fields in groups.items()})
# Extract literal reference data without evaluating upstream JavaScript.
script=(source/'script.js').read_text(encoding='utf-8')
shards={}
block=script.split('data.archonCrystalUpgrades = {',1)[1].split('\n };',1)[0]
for line in block.splitlines():
if not line.strip():continue
m=re.fullmatch(r'\s*"([^"]+)": getAddDict\("([^"]+)"\)((?:\.replaceAll\("[^"]*", "[^"]*"\))*)[,]?\s*',line)
if not m:raise ValueError('Unrecognized shard expression: '+line)
text=dictionary.get(m[2],m[2]).replace('|OPEN_COLOR|','').replace('|CLOSE_COLOR|','')
for pair in re.finditer(r'\.replaceAll\("([^"]*)", "([^"]*)"\)',m[3]):text=text.replace(pair[1],pair[2])
shards[m[1]]=re.sub(r'<[^>]*>','',text)
choices={'shards':shards}
for key in ['invigoration-offensive','invigoration-defensive']:
choices[key]={o.get('value',''):label(o,o.get('value','')) for o in tree.get_element_by_id(key).findall('option')}
(output.parent/'choices.json').write_text(json.dumps(choices,ensure_ascii=False,indent=2),encoding='utf-8')
samples=(source/'script.importSamples.js').read_text(encoding='utf-8').removeprefix('window.importSamples = ').strip().removesuffix(';')
# The reference file contains only JSON literals and unquoted property names.
# Tokenize strings first so colons or braces inside strings cannot be rewritten.
tokens=re.findall(r'"(?:\\.|[^"\\])*"|//[^\n]*|\s+|[A-Za-z_$][\w$]*|[^\s]',samples)
normalized=[]
for index,token in enumerate(tokens):
if token.startswith('//'):continue
following=next((x for x in tokens[index+1:] if not x.isspace()),'')
normalized.append(json.dumps(token) if re.fullmatch(r'[A-Za-z_$][\w$]*',token) and following==':' else token)
samples=json.loads(''.join(normalized))
(output.parent/'import-samples.json').write_text(json.dumps(samples,ensure_ascii=False,indent=2),encoding='utf-8')
print({'shardChoices':len(shards),'importSamples':len(samples)})
riven=(audit/'riven-tool/package/RivenParser.js').read_text(encoding='utf-8')
tags=json.loads(riven.split('const riven_tags = ',1)[1].split(';',1)[0])
(output.parent/'riven-tags.json').write_text(json.dumps(tags,ensure_ascii=False,indent=2),encoding='utf-8')
item_data=(audit/'SpaceNinjaServer/src/services/itemDataService.ts').read_text(encoding='utf-8')
def literal(text,refs=None):
tokens=re.findall(r'"(?:\\.|[^"\\])*"|//[^\n]*|/\*[\s\S]*?\*/|\s+|[A-Za-z_$][\w$]*|[^\s]',text)
normalized=[]
for i,t in enumerate(tokens):
if t.startswith('//') or t.startswith('/*'):continue
following=next((x for x in tokens[i+1:] if not x.isspace() and not x.startswith('//')),'')
if re.fullmatch(r'[A-Za-z_$][\w$]*',t):
if following==':':t=json.dumps(t)
elif refs and t in refs:t=json.dumps(refs[t])
normalized.append(t)
return json.loads(''.join(normalized))
weapon_stats=literal(item_data.split('const U5WeaponUpgrades: IU5FingerprintUpgrade[] = ',1)[1].split('\n];',1)[0]+'\n]')
legacy=literal(item_data.split('export const U5Modules: Record<string, IU5FingerprintData> = ',1)[1].split('\n};',1)[0]+'\n}',{'U5WeaponUpgrades':weapon_stats})
(output.parent/'legacy-mods.json').write_text(json.dumps(legacy,ensure_ascii=False,indent=2),encoding='utf-8')
print({'legacyMods':len(legacy)})