Add reusable content sets publication previews and focused input handling
This commit is contained in:
@@ -1,2 +1,3 @@
|
||||
.catalog-editor{padding:20px;min-width:0}.catalog-heading,.catalog-tabs{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:20px}.catalog-heading h2{font-size:20px;margin-right:auto}.catalog-tabs button[aria-pressed=true]{background:#215944;color:white}.catalog-list{display:grid;gap:12px}.catalog-list>.button{justify-self:start}.catalog-definition{padding:14px;border:1px solid var(--line);border-radius:5px;min-width:0;overflow-wrap:anywhere;font-size:12px;line-height:1.7}.catalog-definition summary{cursor:pointer;font-size:13px;font-weight:600}.catalog-definition p{margin-top:10px}.catalog-form{margin-top:24px;padding-top:20px;border-top:1px solid var(--line);max-width:900px}.catalog-form>h3{margin-bottom:12px}.catalog-form label{display:flex;flex-direction:column;gap:8px;font-size:12px;margin:14px 0;min-width:0}.catalog-form input,.catalog-form select,.catalog-form textarea{width:100%;min-width:0}.catalog-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 14px}.catalog-fields label:has(textarea){grid-column:1/-1}.catalog-repeatable,.catalog-title-choices{padding:14px;min-width:0;border:1px solid var(--line);margin:20px 0}.catalog-repeatable legend,.catalog-title-choices legend{font-size:13px;padding:0 8px}.catalog-row{display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--line);margin-bottom:12px}.catalog-row>.catalog-fields{flex:1}.catalog-row>.button{font-size:11px;padding:8px}.catalog-title-choices{max-height:260px;overflow:auto}.catalog-title-choices label{flex-direction:row-reverse;justify-content:flex-end;align-items:center}.catalog-title-choices input{width:18px;height:18px}.catalog-form footer{display:flex;justify-content:flex-end;gap:12px;margin-top:20px}.catalog-form>.muted{line-height:1.7}.catalog-form details{margin:14px 0}.catalog-form .error{margin-top:14px}.table-tools[hidden]{display:none}@media(max-width:720px){.control-sidebar nav{grid-template-columns:repeat(4,minmax(0,1fr))}.catalog-editor{padding:12px}.catalog-fields{grid-template-columns:1fr}.catalog-row{align-items:flex-end}.catalog-tabs{gap:6px}.catalog-tabs button{padding:9px;font-size:11px}}
|
||||
.player-content{padding:0 0 20px;border-bottom:1px solid var(--line)}.player-content form{display:grid;gap:12px}.player-content label{display:flex;flex-direction:column;gap:7px;font-size:12px;min-width:0}.player-content input,.player-content select,.player-content textarea{width:100%;min-width:0;max-width:100%}.player-content .muted{font-size:12px;line-height:1.7}.player-content [hidden]{display:none}.player-content .button{justify-self:start}
|
||||
.catalog-preview:not(:empty){margin:18px 0;padding:16px;border:1px solid var(--line);border-radius:5px;line-height:1.7;font-size:13px}.catalog-preview h4{margin-bottom:10px}.catalog-preview pre{overflow:auto;max-height:320px;font-size:12px}.catalog-form footer{flex-wrap:wrap}.catalog-form:focus{outline:none}
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
import './content-editor.css';
|
||||
import { api } from './portal-shared';
|
||||
import { derivedStats, itemSlots, modifiersView, node, primaryStats, statLabel } from './character-stats';
|
||||
import type { ItemRequirements, StatModifier, TitleEffects } from './generated';
|
||||
type Requirement={metric:string;atLeast:number};
|
||||
type Title={id:string;name:string;description:string;scope:string;requirements:Requirement[];effects:TitleEffects};
|
||||
type Item={id:string;name:string;description:string;slot:string;weight:number;dropChance:number;requirements:ItemRequirements;modifiers:StatModifier[]};
|
||||
type Rules={version:number;base:Record<string,number>;coefficients:Record<string,Record<string,number>>};
|
||||
type Catalog={version:number;titles:Title[];items:Item[];stats:Rules};
|
||||
import type { ContentCatalog as Catalog, ContentRequirement as Requirement, ContentPreview, StatModifier } from './generated';
|
||||
import { registerMenu } from './menu-focus';
|
||||
type Audit={id:string;actor:string;op:string;target:string;reason:string;version:number;createdAt:number};
|
||||
const statKeys=[...primaryStats,...derivedStats],metrics=['level','kills','worldKills','bossKills','worldsSurvived','gathering','crafting','combat','deaths',...statKeys];
|
||||
const root=node('section','','catalog-editor'),header=node('div','','catalog-heading'),version=node('p'),tabs=node('div','','catalog-tabs'),list=node('div','','catalog-list'),forms=node('div'),message=node('p','','message');
|
||||
const refresh=button('Refresh catalog',()=>void load());header.append(node('h2','Game content'),version,refresh);message.hidden=true;message.setAttribute('role','status');root.append(header,message,tabs,list,forms);
|
||||
let catalog:Catalog,changes:Audit[]=[],section='titles',editing=false,loading=false,saving=false;
|
||||
for(const [key,label] of [['titles','Titles'],['items','Equipment'],['stats','Stat formulas'],['audit','Content audit']]){const b=button(label,()=>{if(editing){show('Finish or cancel the open draft first.');return;}section=key;render()});b.dataset.section=key;tabs.append(b);}
|
||||
for(const [key,label] of [['titles','Titles'],['items','Equipment'],['requirements','Requirement sets'],['effects','Effect sets'],['stats','Stat formulas'],['audit','Content audit']]){const b=button(label,()=>{if(editing||saving){show('Finish or cancel the open draft first.');return;}section=key;render()});b.dataset.section=key;tabs.append(b);}
|
||||
function button(text:string,fn:()=>void){const b=node('button',text,'button secondary');b.type='button';b.onclick=fn;return b;}
|
||||
function show(text:string){message.textContent=text;message.hidden=false;}
|
||||
function field(label:string,input:HTMLElement){const wrap=node('label',label);wrap.append(input);return wrap;}
|
||||
@@ -27,34 +23,74 @@ function repeat<T>(title:string,addLabel:string,make:(value?:T)=>{node:HTMLEleme
|
||||
for(const value of initial)append(value);return {node:group,read:()=>entries.map(e=>e.read())};
|
||||
}
|
||||
function modifiers(){return repeat<StatModifier>('Modifiers','Add modifier',value=>{const group=node('div','','catalog-fields'),stat=select(statKeys,value?.stat),flat=number(value?.flat??0,-1000000),percent=number(value?.percent??0,-100,10000);group.append(field('Stat',stat),field('Flat change',flat),field('Percent change (%)',percent));return {node:group,read:()=>({stat:stat.value,flat:Number(flat.value),percent:Number(percent.value)})}});}
|
||||
function requirementRows(initial:Requirement[]=[]){return repeat<Requirement>('Requirements','Add requirement',value=>{const group=node('div','','catalog-fields'),metric=select(metrics,value?.metric),minimum=number(value?.atLeast??1,1,1000000000,'1');group.append(field('Metric',metric),field('At least',minimum));return {node:group,read:()=>({metric:metric.value,atLeast:Number(minimum.value)})}},initial,8);}
|
||||
function setChoices(equipment=false){
|
||||
const group=node('div'),req=node('fieldset','','catalog-title-choices'),effects=node('fieldset','','catalog-title-choices');req.append(node('legend','Reusable requirement sets'));effects.append(node('legend','Reusable effect sets'));
|
||||
const choices=(sets:{id:string;name:string}[],parent:HTMLElement)=>sets.map(s=>{const input=node('input');input.type='checkbox';parent.append(field(`${s.name} (${s.id})`,input));return {id:s.id,input}});
|
||||
const r=choices((catalog.requirementSets??[]).filter(s=>!equipment||s.requirements.every(r=>r.metric==='level'||statKeys.includes(r.metric))),req),e=choices(catalog.effectSets??[],effects);
|
||||
if(!r.length)req.append(node('p','No compatible sets published yet.','muted'));if(!e.length)effects.append(node('p','No effect sets published yet.','muted'));
|
||||
group.append(req,effects,node('p','Sets are copied into this definition at publication. Repeated thresholds use the highest value; modifiers add together. Preview before publishing.','muted'));
|
||||
return {node:group,read:()=>({requirementSetIds:r.filter(c=>c.input.checked).map(c=>c.id),effectSetIds:e.filter(c=>c.input.checked).map(c=>c.id)})};
|
||||
}
|
||||
function setForm(kind:'requirements'|'effects'){
|
||||
if(editing||saving){show('Finish the open draft or pending request first.');return;}
|
||||
const values=identity(),rows=kind==='requirements'?requirementRows([{metric:'level',atLeast:2}]):modifiers();
|
||||
const fields=form(kind==='requirements'?'Create requirement set':'Create effect set',kind==='requirements'?'create-requirement-set':'create-effect-set',()=>kind==='requirements'?{requirementSet:{...values.read(),requirements:rows.read()}}:{effectSet:{...values.read(),modifiers:rows.read()}});
|
||||
fields.append(values.node,rows.node,node('p','Reusable sets are immutable. Publish a new ID for a variation. Effects currently support flat and percentage stat modifiers.','muted'));
|
||||
}
|
||||
function form(title:string,op:string,payload:()=>object){
|
||||
editing=true;refresh.disabled=true;const expectedVersion=catalog.version,form=node('form','','catalog-form'),error=node('p','','error'),fields=node('div'),reason=node('textarea');
|
||||
editing=true;refresh.disabled=true;const expectedVersion=catalog.version,form=node('form','','catalog-form'),error=node('p','','error'),fields=node('div'),reason=node('textarea'),preview=node('section','','catalog-preview');
|
||||
let requestID=crypto.randomUUID(),lastRequest='';
|
||||
reason.required=true;reason.minLength=5;reason.maxLength=240;reason.rows=2;error.setAttribute('role','alert');
|
||||
const save=node('button','Publish changes','button');save.type='submit';const cancel=button('Cancel',()=>{if(saving)return;editing=false;refresh.disabled=false;forms.replaceChildren()});const footer=node('footer');footer.append(cancel,save);
|
||||
form.append(node('h3',title),node('p',`Based on catalog version ${expectedVersion}. Published title and item IDs cannot be edited or removed.`,'muted'),fields,field('Reason for change',reason),error,footer);forms.replaceChildren(form);
|
||||
const focus=registerMenu(form,()=>{editing=false;refresh.disabled=saving;forms.replaceChildren();focus.dispose()});
|
||||
const save=node('button','Publish changes','button');save.type='submit';const cancel=button('Cancel',()=>focus.close()),check=button('Preview changes',()=>void previewChanges());const footer=node('footer');footer.append(cancel,check,save);
|
||||
form.append(node('h3',title),node('p',`Based on catalog version ${expectedVersion}. Published definitions and sets cannot be edited or removed.`,'muted'),fields,field('Reason for change',reason),error,preview,footer);forms.replaceChildren(form);
|
||||
const previous=document.activeElement;queueMicrotask(()=>{if(form.isConnected)focus.opened(previous)});
|
||||
form.addEventListener('input',()=>preview.replaceChildren());form.addEventListener('change',()=>preview.replaceChildren());
|
||||
fields.addEventListener('click',event=>{if((event.target as HTMLElement).closest('button'))preview.replaceChildren()});
|
||||
function busy(value:boolean){saving=value;save.disabled=value;check.disabled=value;fields.inert=value;reason.disabled=value;refresh.disabled=value||editing;}
|
||||
async function previewChanges(){
|
||||
if(saving||!form.reportValidity())return;error.textContent='';preview.replaceChildren();let body:object;
|
||||
try{body={id:requestID,expectedVersion,op,reason:reason.value.trim(),...payload()}}catch(e){error.textContent=(e as Error).message;return;}
|
||||
busy(true);
|
||||
try{const result=await api<ContentPreview>('/api/control/catalog/preview',body);if(form.isConnected)preview.append(previewView(result));}
|
||||
catch(e){if(form.isConnected)error.textContent=(e as Error).message;else show((e as Error).message)}finally{busy(false)}
|
||||
}
|
||||
form.onsubmit=async event=>{event.preventDefault();if(saving)return;error.textContent='';let body:object;try{body={expectedVersion,op,reason:reason.value.trim(),...payload()}}catch(e){error.textContent=(e as Error).message;return;}
|
||||
const serialized=JSON.stringify(body);if(lastRequest&&lastRequest!==serialized)requestID=crypto.randomUUID();lastRequest=serialized;saving=true;save.disabled=true;cancel.disabled=true;
|
||||
try{await api('/api/control/catalog',{id:requestID,...body});editing=false;forms.replaceChildren();show('Content published. Running world owners will apply the catalog.');await load();}catch(e){error.textContent=(e as Error).message;}finally{saving=false;save.disabled=false;cancel.disabled=false;refresh.disabled=editing;}
|
||||
const serialized=JSON.stringify(body);if(lastRequest&&lastRequest!==serialized)requestID=crypto.randomUUID();lastRequest=serialized;busy(true);
|
||||
try{await api('/api/control/catalog',{id:requestID,...body});focus.close();show('Content published. Running world owners will apply the catalog.');await load();}catch(e){if(form.isConnected)error.textContent=(e as Error).message;else show((e as Error).message);}finally{busy(false)}
|
||||
};return fields;
|
||||
}
|
||||
function previewView(result:ContentPreview){
|
||||
const root=node('div'),r=result.resolved;root.append(node('h4','Validated publication preview'),node('p',`Version ${result.basedOnVersion} → ${result.proposedVersion}. Nothing has been published.`));
|
||||
const definition=r.title??r.item??r.requirementSet??r.effectSet;
|
||||
if(definition)root.append(node('strong',`${definition.name} (${definition.id})`),node('p',definition.description));
|
||||
const requirements=r.title?.requirements??r.requirementSet?.requirements;
|
||||
if(requirements)root.append(node('p',requirements.map(v=>`${statLabel(v.metric)} ≥ ${v.atLeast}`).join(' / ')));
|
||||
if(r.item)root.append(node('p',`Requires level ${r.item.requirements.level}; ${Object.entries(r.item.requirements.stats??{}).map(([key,n])=>`${statLabel(key)} ≥ ${n}`).join(' / ')}`),node('p',`Required titles: ${(r.item.requirements.titles??[]).join(', ')||'None'}`));
|
||||
const modifiers=r.title?.effects.modifiers??r.item?.modifiers??r.effectSet?.modifiers;if(modifiers)root.append(modifiersView(modifiers));
|
||||
if(r.stats){root.append(node('p','Validated base values and primary-to-derived coefficients.'));const details=node('details');details.append(node('summary','Review stat formulas'),node('pre',JSON.stringify(r.stats,null,2)));root.append(details);}
|
||||
return root;
|
||||
}
|
||||
function titleForm(){
|
||||
if(editing){show('Finish or cancel the open draft first.');return;}
|
||||
if(editing||saving){show('Finish or cancel the open draft first.');return;}
|
||||
const values=identity(),scope=select(['personal','world','global'],'personal');scope.options[0].text='Every qualifying player';scope.options[1].text='First in each world';scope.options[2].text='First ever';
|
||||
const requirements=repeat<Requirement>('Requirements','Add requirement',value=>{const group=node('div','','catalog-fields'),metric=select(metrics,value?.metric),minimum=number(value?.atLeast??1,1,1000000000,'1');group.append(field('Metric',metric),field('At least',minimum));return {node:group,read:()=>({metric:metric.value,atLeast:Number(minimum.value)})}},[{metric:'level',atLeast:2}],8),effects=modifiers();
|
||||
const fields=form('Create title','create-title',()=>{const req=requirements.read();if(!req.length)throw new Error('Add at least one requirement.');return {title:{...values.read(),scope:scope.value,requirements:req,effects:{damage:0,moveSpeed:0,modifiers:effects.read()}}}});
|
||||
fields.append(values.node,field('Award scope',scope),node('p','All requirements must be met. Earned titles and their positive or negative effects are permanent.','muted'),requirements.node,effects.node);
|
||||
const sets=setChoices();
|
||||
const fields=form('Create title','create-title',()=>{const req=requirements.read(),refs=sets.read();if(!req.length&&!refs.requirementSetIds.length)throw new Error('Add at least one requirement or requirement set.');return {...refs,title:{...values.read(),scope:scope.value,requirements:req,effects:{damage:0,moveSpeed:0,modifiers:effects.read()}}}});
|
||||
fields.append(values.node,field('Award scope',scope),node('p','All requirements must be met. Earned titles and their positive or negative effects are permanent.','muted'),sets.node,requirements.node,effects.node);
|
||||
}
|
||||
function itemForm(){
|
||||
if(editing){show('Finish or cancel the open draft first.');return;}
|
||||
if(editing||saving){show('Finish or cancel the open draft first.');return;}
|
||||
const values=identity(),slot=select(itemSlots,'weapon'),weight=number(1,0,10000),drop=number(0,0,100),level=number(1,1,10000,'1'),effects=modifiers();
|
||||
const requirements=repeat<{stat:string;value:number}>('Required stats','Add required stat',value=>{const group=node('div','','catalog-fields'),stat=select(statKeys,value?.stat),minimum=number(value?.value??1);group.append(field('Stat',stat),field('Minimum value',minimum));return {node:group,read:()=>({stat:stat.value,value:Number(minimum.value)})}},[],statKeys.length);
|
||||
const titles=node('fieldset','','catalog-title-choices');titles.append(node('legend','Required titles'));const checks=(catalog.titles??[]).map(t=>{const input=node('input');input.type='checkbox';titles.append(field(t.name,input));return {id:t.id,input}});
|
||||
const fields=form('Create equipment','create-item',()=>{const req=requirements.read();if(new Set(req.map(r=>r.stat)).size!==req.length)throw new Error('Each required stat can appear once.');return {item:{...values.read(),slot:slot.value,weight:Number(weight.value),dropChance:Number(drop.value),requirements:{level:Number(level.value),stats:Object.fromEntries(req.map(r=>[r.stat,r.value])),titles:checks.filter(c=>c.input.checked).map(c=>c.id)},modifiers:effects.read()}}});
|
||||
fields.append(values.node,field('Equipment slot',slot),field('Weight',weight),field('Sentinel drop chance (%)',drop),node('p','Zero disables sentinel drops. Drop-rate bonuses apply. Requirements are checked without equipment bonuses.','muted'),field('Required level',level),requirements.node,titles,effects.node);
|
||||
const sets=setChoices(true);
|
||||
const fields=form('Create equipment','create-item',()=>{const req=requirements.read();if(new Set(req.map(r=>r.stat)).size!==req.length)throw new Error('Each required stat can appear once.');return {...sets.read(),item:{...values.read(),slot:slot.value,weight:Number(weight.value),dropChance:Number(drop.value),requirements:{level:Number(level.value),stats:Object.fromEntries(req.map(r=>[r.stat,r.value])),titles:checks.filter(c=>c.input.checked).map(c=>c.id)},modifiers:effects.read()}}});
|
||||
fields.append(values.node,field('Equipment slot',slot),field('Weight',weight),field('Sentinel drop chance (%)',drop),node('p','Zero disables sentinel drops. Drop-rate bonuses apply. Requirements are checked without equipment bonuses.','muted'),sets.node,field('Required level',level),requirements.node,titles,effects.node);
|
||||
}
|
||||
function statsForm(){
|
||||
if(editing){show('Finish or cancel the open draft first.');return;}
|
||||
if(editing||saving){show('Finish or cancel the open draft first.');return;}
|
||||
const source=catalog.stats,base=new Map<string,HTMLInputElement>(),coefficients=new Map<string,Map<string,HTMLInputElement>>();
|
||||
const fields=form('Edit stat formulas','update-stats',()=>({stats:{version:source.version,base:Object.fromEntries([...base].map(([key,i])=>[key,Number(i.value)])),coefficients:Object.fromEntries([...coefficients].map(([key,inputs])=>[key,Object.fromEntries([...inputs].map(([stat,i])=>[stat,Number(i.value)]))]))}}));
|
||||
const bases=node('details','','catalog-definition');bases.open=true;bases.append(node('summary','Base values'));const grid=node('div','','catalog-fields');for(const key of statKeys){const i=number(source.base[key],key==='healthPoints'?50:key==='stamina'?1:0);base.set(key,i);grid.append(field(`${statLabel(key)} base`,i));}bases.append(grid);fields.append(bases);
|
||||
@@ -66,6 +102,12 @@ function render(){
|
||||
list.append(button('Create title',titleForm));for(const t of catalog.titles??[]){const d=node('details','','catalog-definition');d.append(node('summary',t.name),node('p',`${t.id} · ${t.scope} · ${t.description}`),node('p',(t.requirements??[]).map(r=>`${statLabel(r.metric)} ≥ ${r.atLeast}`).join(' / ')),modifiersView(t.effects.modifiers));if(t.effects.damage||t.effects.moveSpeed)d.append(node('p',`Damage ${t.effects.damage}; movement ${t.effects.moveSpeed}`));list.append(d);}
|
||||
}else if(section==='items'){
|
||||
list.append(button('Create equipment',itemForm));for(const i of catalog.items??[]){const d=node('details','','catalog-definition');d.append(node('summary',i.name),node('p',`${i.id} · ${statLabel(i.slot)} · Weight ${i.weight} · Drop chance ${i.dropChance??0}%`),node('p',i.description),node('p',`Requires level ${i.requirements.level}; ${Object.entries(i.requirements.stats??{}).map(([k,v])=>`${statLabel(k)} ${v}`).join(', ')} ${(i.requirements.titles??[]).map(id=>`Title: ${catalog.titles.find(t=>t.id===id)?.name??id}`).join(', ')}`),modifiersView(i.modifiers));list.append(d);}
|
||||
}else if(section==='requirements'){
|
||||
list.append(button('Create requirement set',()=>setForm('requirements')),node('p','Named thresholds reusable in titles and equipment. Equipment supports level/stat thresholds; other metrics are title-only.','muted'));
|
||||
for(const s of catalog.requirementSets??[]){const d=node('details','','catalog-definition');d.append(node('summary',s.name),node('p',`${s.id} · ${s.description}`),node('p',s.requirements.map(r=>`${statLabel(r.metric)} ≥ ${r.atLeast}`).join(' / ')));list.append(d);}
|
||||
}else if(section==='effects'){
|
||||
list.append(button('Create effect set',()=>setForm('effects')),node('p','Reusable signed flat and percentage stat modifiers. Timed combat effects arrive with combat.','muted'));
|
||||
for(const s of catalog.effectSets??[]){const d=node('details','','catalog-definition');d.append(node('summary',s.name),node('p',`${s.id} · ${s.description}`),modifiersView(s.modifiers));list.append(d);}
|
||||
}else if(section==='stats'){
|
||||
list.append(button('Edit stat formulas',statsForm),node('p','Provisional coefficients. Modified primary values feed derived stats; flat changes apply before combined percentages.','muted'));
|
||||
for(const primary of primaryStats){const d=node('details','','catalog-definition');d.append(node('summary',statLabel(primary)),node('p',`Base ${catalog.stats.base[primary]}`));for(const [stat,value] of Object.entries(catalog.stats.coefficients[primary]))d.append(node('p',`${statLabel(stat)}: ${value} per point (base ${catalog.stats.base[stat]})`));list.append(d);}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { permanentTitles, progressionSummary } from './progression';
|
||||
import { statsBreakdown, equipmentDetails } from './character-stats';
|
||||
import { showCatalog, hasCatalogDraft } from './content-editor';
|
||||
import { playerContent } from './player-content';
|
||||
import { registerMenu } from './menu-focus';
|
||||
import { $, api, APIError, badge, cell, date, el, gameURL, icons, icon, table, type Command, type RecordCharacter, type World } from './portal-shared';
|
||||
|
||||
type Data = { worlds: World[]; characters: RecordCharacter[]; commands: Command[]; provisioningEnabled: boolean; characterLimit: number; auditLimit: number };
|
||||
@@ -11,6 +12,8 @@ let data: Data;
|
||||
let tab = 'worlds';
|
||||
let busy = false;
|
||||
let draft: Draft;
|
||||
const commandMenu=registerMenu($('command-dialog'),()=>$<HTMLDialogElement>('command-dialog').close());
|
||||
const characterMenu=registerMenu($('character-dialog'),()=>$<HTMLDialogElement>('character-dialog').close());
|
||||
const labels: Record<string, string> = { 'create-world': 'New world', 'close-admissions': 'Close arrivals', 'open-admissions': 'Open arrivals', 'awaken-boss': 'Awaken Harbinger', 'end-world': 'End world permanently', rename: 'Rename character', heal: 'Restore health', unstuck: 'Return to sanctuary', retire: 'Retire character permanently', 'revoke-sessions': 'Revoke account sessions' };
|
||||
Object.assign(labels, { 'grant-item':'Add item', 'remove-item':'Remove item', 'grant-title':'Add / restore title', 'revoke-title':'Remove title' });
|
||||
function notify(message: string) { $('control-message').textContent = message; $('control-message').hidden = false; }
|
||||
@@ -32,7 +35,7 @@ function openCommand(op: string, worldId = '', target = '', value = '') {
|
||||
$<HTMLInputElement>('confirm-input').required = dangerous;
|
||||
$('submit-command').classList.toggle('danger', dangerous);
|
||||
$('command-error').textContent = '';
|
||||
$<HTMLDialogElement>('command-dialog').showModal();
|
||||
const previous=document.activeElement;$<HTMLDialogElement>('command-dialog').showModal();commandMenu.opened(previous);
|
||||
}
|
||||
function actions(world: string, options: string[], target = '', value = '', disabled = false) {
|
||||
const parent = el('div', '', 'row-actions'); const select = el('select'); select.setAttribute('aria-label', `Action for ${target || world}`);
|
||||
@@ -54,7 +57,7 @@ function detail(r: RecordCharacter) {
|
||||
parent.append(el('h3', 'Progression'), progressionSummary(v), el('h3', 'Permanent titles'), permanentTitles(v.titles));
|
||||
parent.append(el('h3','Full stats'),statsBreakdown(v),el('h3','Equipment'),equipmentDetails(v));
|
||||
for (const [heading, items] of [['Inventory', v.inventory], ['Skills', v.skills]] as const) { parent.append(el('h3', heading)); const section = el('div', '', 'item-list'); for (const [key,value] of Object.entries(items)) { const item = el('span', key.replaceAll('_', ' ')); item.append(el('b', String(value))); section.append(item); } if (!section.children.length) section.append(el('span', 'None', 'muted')); parent.append(section); }
|
||||
$<HTMLDialogElement>('character-dialog').showModal();
|
||||
const previous=document.activeElement;$<HTMLDialogElement>('character-dialog').showModal();characterMenu.opened(previous);
|
||||
}
|
||||
function render() {
|
||||
if (!data) return;
|
||||
@@ -124,8 +127,8 @@ document.querySelectorAll<HTMLButtonElement>('[data-tab]').forEach(button => but
|
||||
$<HTMLInputElement>('search').placeholder = `Search ${tab}`; $<HTMLSelectElement>('state-filter').value = ''; void refresh();
|
||||
});
|
||||
$('search').oninput = render; $('state-filter').onchange = render; $('world-filter').onchange = () => void refresh(); $('refresh').onclick = () => void refresh(); $('create-world').onclick = () => openCommand('create-world');
|
||||
for (const id of ['close-command','cancel-command']) $(id).onclick = () => $<HTMLDialogElement>('command-dialog').close();
|
||||
$('close-character').onclick = () => $<HTMLDialogElement>('character-dialog').close();
|
||||
for (const id of ['close-command','cancel-command']) $(id).onclick = () => commandMenu.close();
|
||||
$('close-character').onclick = () => characterMenu.close();
|
||||
$<HTMLFormElement>('command-form').onsubmit = async event => {
|
||||
event.preventDefault(); const submit = $<HTMLButtonElement>('submit-command'); submit.disabled = true;
|
||||
const body = { ...draft, worldId: draft.op === 'create-world' ? $<HTMLInputElement>('world-input').value : draft.worldId, value: ['rename','create-world'].includes(draft.op) ? $<HTMLInputElement>('value-input').value : '', reason: $<HTMLTextAreaElement>('reason-input').value, confirm: $<HTMLInputElement>('confirm-input').value };
|
||||
|
||||
+97
-20
@@ -1,7 +1,102 @@
|
||||
// Code generated from schemas/protocol.json. DO NOT EDIT.
|
||||
export interface Protocol {
|
||||
intent: Intent;
|
||||
snapshot: Snapshot;
|
||||
catalog?: ContentCatalog;
|
||||
catalogChange?: ContentChange;
|
||||
catalogPreview?: ContentPreview;
|
||||
intent: Intent;
|
||||
snapshot: Snapshot;
|
||||
}
|
||||
|
||||
export interface ContentCatalog {
|
||||
effectSets?: EffectSet[];
|
||||
items: ItemDefinition[];
|
||||
requirementSets?: RequirementSet[];
|
||||
stats: ContentStatsRules;
|
||||
titles: TitleDefinition[];
|
||||
version: number;
|
||||
}
|
||||
|
||||
export interface EffectSet {
|
||||
description: string;
|
||||
id: string;
|
||||
modifiers: StatModifier[];
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface StatModifier {
|
||||
flat: number;
|
||||
percent: number;
|
||||
stat: string;
|
||||
}
|
||||
|
||||
export interface ItemDefinition {
|
||||
description: string;
|
||||
dropChance: number;
|
||||
id: string;
|
||||
modifiers: StatModifier[];
|
||||
name: string;
|
||||
requirements: ItemRequirements;
|
||||
slot: string;
|
||||
weight: number;
|
||||
}
|
||||
|
||||
export interface ItemRequirements {
|
||||
level: number;
|
||||
stats: { [key: string]: number };
|
||||
titles: string[];
|
||||
}
|
||||
|
||||
export interface RequirementSet {
|
||||
description: string;
|
||||
id: string;
|
||||
name: string;
|
||||
requirements: ContentRequirement[];
|
||||
}
|
||||
|
||||
export interface ContentRequirement {
|
||||
atLeast: number;
|
||||
metric: string;
|
||||
}
|
||||
|
||||
export interface ContentStatsRules {
|
||||
base: { [key: string]: number };
|
||||
coefficients: { [key: string]: { [key: string]: number } };
|
||||
version: number;
|
||||
}
|
||||
|
||||
export interface TitleDefinition {
|
||||
description: string;
|
||||
effects: TitleEffects;
|
||||
id: string;
|
||||
name: string;
|
||||
requirements: ContentRequirement[];
|
||||
scope: string;
|
||||
}
|
||||
|
||||
export interface TitleEffects {
|
||||
damage: number;
|
||||
modifiers: StatModifier[];
|
||||
moveSpeed: number;
|
||||
}
|
||||
|
||||
export interface ContentChange {
|
||||
effectSet?: EffectSet;
|
||||
effectSetIds?: string[];
|
||||
expectedVersion: number;
|
||||
id: string;
|
||||
item?: ItemDefinition;
|
||||
op: string;
|
||||
reason: string;
|
||||
requirementSet?: RequirementSet;
|
||||
requirementSetIds?: string[];
|
||||
stats?: ContentStatsRules;
|
||||
title?: TitleDefinition;
|
||||
}
|
||||
|
||||
export interface ContentPreview {
|
||||
basedOnVersion: number;
|
||||
proposedVersion: number;
|
||||
resolved: ContentChange;
|
||||
}
|
||||
|
||||
export interface Intent {
|
||||
@@ -92,18 +187,6 @@ export interface ItemInstance {
|
||||
weight: number;
|
||||
}
|
||||
|
||||
export interface StatModifier {
|
||||
flat: number;
|
||||
percent: number;
|
||||
stat: string;
|
||||
}
|
||||
|
||||
export interface ItemRequirements {
|
||||
level: number;
|
||||
stats: { [key: string]: number };
|
||||
titles: string[];
|
||||
}
|
||||
|
||||
export interface StatValue {
|
||||
base: number;
|
||||
final: number;
|
||||
@@ -121,12 +204,6 @@ export interface TitleAward {
|
||||
worldId: string;
|
||||
}
|
||||
|
||||
export interface TitleEffects {
|
||||
damage: number;
|
||||
modifiers: StatModifier[];
|
||||
moveSpeed: number;
|
||||
}
|
||||
|
||||
export interface WorldInfo {
|
||||
ageSeconds: number;
|
||||
bossHp: number;
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
export type InputAction = 'north' | 'south' | 'west' | 'east' | 'attack' | 'gather' | 'inventory' | 'heal' | 'return';
|
||||
const bindings: Readonly<Record<string, InputAction>> = {
|
||||
KeyW:'north', ArrowUp:'north', KeyS:'south', ArrowDown:'south', KeyA:'west', ArrowLeft:'west',
|
||||
KeyD:'east', ArrowRight:'east', Space:'attack', KeyE:'gather', KeyI:'inventory'
|
||||
};
|
||||
export function isEditing(target: EventTarget | null) {
|
||||
return target instanceof HTMLElement && !!target.closest('input,select,textarea,[contenteditable]:not([contenteditable="false"])');
|
||||
}
|
||||
|
||||
// Physical input is separate from gameplay intents. Rebinding/controller mapping
|
||||
// can feed these same actions later without changing authoritative game commands.
|
||||
export class InputActions {
|
||||
private held = new Map<string, InputAction>();
|
||||
constructor(private blocked: () => boolean, private onAction: (action: InputAction) => void) {
|
||||
window.addEventListener('keydown', event => {
|
||||
const action = bindings[event.code];
|
||||
if (!action || event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey || isEditing(event.target) || blocked()) return;
|
||||
event.preventDefault();
|
||||
if (['north','south','west','east'].includes(action)) this.held.set(event.code, action);
|
||||
else if (!event.repeat) this.trigger(action);
|
||||
});
|
||||
window.addEventListener('keyup', event => this.held.delete(event.code));
|
||||
window.addEventListener('blur', () => this.clear());
|
||||
document.addEventListener('visibilitychange', () => { if (document.hidden) this.clear(); });
|
||||
document.addEventListener('focusin', event => { if (isEditing(event.target) || blocked()) this.clear(); });
|
||||
}
|
||||
trigger(action: InputAction) { if (!this.blocked()) this.onAction(action); }
|
||||
press(source: string, action: InputAction) { if (!this.blocked()) this.held.set(source, action); }
|
||||
release(source: string) { this.held.delete(source); }
|
||||
clear() { this.held.clear(); }
|
||||
get keys() { return [...this.held.keys()]; }
|
||||
get movement() {
|
||||
if (this.blocked()) { this.clear(); return {x:0,z:0}; }
|
||||
const actions = new Set(this.held.values());
|
||||
return {x:Number(actions.has('east'))-Number(actions.has('west')), z:Number(actions.has('south'))-Number(actions.has('north'))};
|
||||
}
|
||||
}
|
||||
+33
-24
@@ -4,6 +4,8 @@ import { WorldView } from './world-view';
|
||||
import type { Character, Chunk, Entity, Intent, Snapshot } from './generated';
|
||||
import { experienceText, permanentTitles, statPointsText, updateExperienceMeter } from './progression';
|
||||
import { characterPanel } from './character-panel';
|
||||
import { InputActions, isEditing, type InputAction } from './input-actions';
|
||||
import { hasOpenMenu, registerMenu } from './menu-focus';
|
||||
|
||||
type Recipe = { Inputs: Record<string, number>; Outputs: Record<string, number> };
|
||||
type Config = { worldId: string; development: boolean; worlds: { id: string; url: string }[]; recipes: Record<string, Recipe>; playerSpeed: number; gatherRange: number; attackRange: number };
|
||||
@@ -43,7 +45,7 @@ function progressSignature(): number | undefined {
|
||||
}
|
||||
const avoidUntil = new Map<string, number>();
|
||||
let requestedClose = false;
|
||||
const keys = new Set<string>();
|
||||
let input: InputActions;
|
||||
let view: WorldView;
|
||||
const selectedWorld = new URLSearchParams(location.search).get('world');
|
||||
const worldPrefix = selectedWorld && /^[a-z][a-z0-9-]{0,30}$/.test(selectedWorld) ? `/worlds/${selectedWorld}` : '';
|
||||
@@ -94,7 +96,7 @@ function connect() {
|
||||
else if (value.self.remainingSeconds <= 0) showEnding('Rest until tomorrow.', 'Your daily play time is complete. Your keystone will return you to your previous location after 00:00 UTC.', false);
|
||||
};
|
||||
ws.onclose = async () => {
|
||||
$('connection-status').textContent = 'Disconnected'; $('connection-dot').parentElement!.classList.add('offline'); keys.clear(); walkTo = undefined;
|
||||
$('connection-status').textContent = 'Disconnected'; $('connection-dot').parentElement!.classList.add('offline'); input.clear(); walkTo = undefined;
|
||||
if (requestedClose || $<HTMLDialogElement>('ending').open) return;
|
||||
let detail = 'The connection ended. Your character state is held by the server.';
|
||||
try { const me = await api<{ character?: Character }>('/api/me'); if (me.character?.entity.state === 'dead') { showEnding('A life, remembered.', 'This character is permanently dead.', false); return; } if (me.character?.remainingSeconds === 0) detail = 'Daily play time is complete. Return after 00:00 UTC.'; } catch { detail = 'Your session ended. Sign in again to continue.'; }
|
||||
@@ -102,7 +104,7 @@ function connect() {
|
||||
};
|
||||
}
|
||||
function showEnding(title: string, detail: string, survivor: boolean) {
|
||||
keys.clear(); walkTo = undefined; pendingAction = undefined;
|
||||
input.clear(); walkTo = undefined; pendingAction = undefined;
|
||||
$('ending-title').textContent = title; $('ending-detail').textContent = detail;
|
||||
$('ending-eyebrow').textContent = survivor ? 'WORLD SURVIVED' : 'JOURNEY PAUSED';
|
||||
if (snapshot?.self.entity.state === 'dead') $('ending-eyebrow').textContent = 'JOURNEY ENDED';
|
||||
@@ -175,11 +177,19 @@ async function boot() {
|
||||
$<HTMLAnchorElement>('login').href = `/auth/login?return=${encodeURIComponent(location.pathname + location.search)}`;
|
||||
createIcons({ icons: { Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } });
|
||||
view = new WorldView($<HTMLCanvasElement>('world'));
|
||||
input = new InputActions(() => hasOpenMenu() || isEditing(document.activeElement) || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open, key => {
|
||||
if(key==='attack'||key==='gather')action(key);
|
||||
else if(key==='inventory')$('inventory-toggle').click();
|
||||
else if(key==='heal'||key==='return')send(key);
|
||||
});
|
||||
view.start(dt => {
|
||||
inputElapsed += dt;
|
||||
if (!snapshot || ws?.readyState !== WebSocket.OPEN || $<HTMLDialogElement>('ending').open) return;
|
||||
let x = Number(keys.has('d') || keys.has('arrowright')) - Number(keys.has('a') || keys.has('arrowleft'));
|
||||
let z = Number(keys.has('s') || keys.has('arrowdown')) - Number(keys.has('w') || keys.has('arrowup'));
|
||||
if(hasOpenMenu()||isEditing(document.activeElement)){
|
||||
input.clear();walkTo=undefined;pendingAction=undefined;view.moving=false;
|
||||
if(inputElapsed>=0.05){send('move');inputElapsed=0;}return;
|
||||
}
|
||||
let {x,z} = input.movement;
|
||||
if (x || z) { walkTo = undefined; pendingAction = undefined; }
|
||||
if (walkTo) {
|
||||
const p = snapshot.self.entity.position, dx = walkTo.x - p.x, dz = walkTo.z - p.z, distance = Math.hypot(dx, dz);
|
||||
@@ -246,9 +256,16 @@ async function boot() {
|
||||
catch (e) { $('arrival-error').textContent = (e as Error).message; }
|
||||
finally { button.disabled = false; }
|
||||
};
|
||||
for (const id of ['inventory', 'settings']) { $(`${id}-toggle`).onclick = () => { visible(id, $(id).hidden); visible('movement', $('inventory').hidden && $('settings').hidden && !!snapshot); if (id === 'inventory' && snapshot) inventory(snapshot.self); }; }
|
||||
document.querySelectorAll<HTMLButtonElement>('[data-close]').forEach(button => button.onclick = () => visible(button.dataset.close!, false));
|
||||
$('attack').onclick = () => action('attack'); $('gather').onclick = () => action('gather'); $('heal').onclick = () => send('heal'); $('keystone').onclick = () => send('return');
|
||||
for (const id of ['inventory', 'settings']) {
|
||||
const menu=registerMenu($(id),()=>{visible(id,false);visible('movement',$('inventory').hidden&&$('settings').hidden&&!!snapshot)});
|
||||
$(`${id}-toggle`).onclick=()=>{
|
||||
if(!$(id).hidden){menu.close();return;}
|
||||
if(id==='inventory'&&snapshot)inventory(snapshot.self);
|
||||
input.clear();walkTo=undefined;pendingAction=undefined;send('move');visible(id,true);visible('movement',false);menu.opened($(`${id}-toggle`));
|
||||
};
|
||||
document.querySelectorAll<HTMLButtonElement>(`[data-close="${id}"]`).forEach(button=>button.onclick=()=>menu.close());
|
||||
}
|
||||
$('attack').onclick = () => input.trigger('attack'); $('gather').onclick = () => input.trigger('gather'); $('heal').onclick = () => input.trigger('heal'); $('keystone').onclick = () => input.trigger('return');
|
||||
$('target-boss').onclick = () => { selection(snapshot?.entities.find(e => e.id === 'boss')); walkTo = { x: 0, z: 0 }; pendingAction = { op: 'attack', target: 'boss' }; lastProgress = undefined; lastProgressAt = Date.now(); };
|
||||
$('dev-boss').onclick = () => void api('/api/dev/boss', {}).catch(e => notice(e.message));
|
||||
$('reconnect').onclick = () => location.reload();
|
||||
@@ -256,28 +273,20 @@ async function boot() {
|
||||
$('logout').onclick = async () => { requestedClose = true; await api('/auth/logout', {}); ws?.close(); location.reload(); };
|
||||
$<HTMLSelectElement>('quality').onchange = event => view.quality((event.target as HTMLSelectElement).value === 'high');
|
||||
$<HTMLInputElement>('zoom').oninput = event => { view.distance = Number((event.target as HTMLInputElement).value); view.resize(); };
|
||||
window.addEventListener('keydown', event => {
|
||||
if ((event.target as HTMLElement).matches('input,select,textarea') || $<HTMLDialogElement>('arrival').open) return;
|
||||
const key = event.key.toLowerCase();
|
||||
if (['w', 'a', 's', 'd', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright', ' '].includes(key)) event.preventDefault();
|
||||
keys.add(key); if (event.repeat) return;
|
||||
if (key === 'e') action('gather'); if (key === ' ') action('attack'); if (key === 'i') $('inventory-toggle').click(); if (key === 'escape') { visible('inventory', false); visible('settings', false); selection(); walkTo = undefined; }
|
||||
});
|
||||
window.addEventListener('keyup', event => keys.delete(event.key.toLowerCase()));
|
||||
window.addEventListener('blur', () => { keys.clear(); walkTo = undefined; send('move'); });
|
||||
document.addEventListener('visibilitychange', () => { if (document.hidden) { keys.clear(); walkTo = undefined; send('move'); } });
|
||||
const movements: Record<string, string> = { up: 'w', down: 's', left: 'a', right: 'd' };
|
||||
window.addEventListener('blur', () => { input.clear(); walkTo = undefined; pendingAction=undefined; send('move'); });
|
||||
document.addEventListener('visibilitychange', () => { if (document.hidden) { input.clear(); walkTo = undefined; pendingAction=undefined; send('move'); } });
|
||||
const movements: Record<string, InputAction> = { up:'north',down:'south',left:'west',right:'east' };
|
||||
document.querySelectorAll<HTMLButtonElement>('[data-move]').forEach(button => {
|
||||
const key = movements[button.dataset.move!];
|
||||
button.onpointerdown = event => { button.setPointerCapture(event.pointerId); keys.add(key); };
|
||||
button.onpointerup = button.onpointercancel = () => keys.delete(key);
|
||||
const key = movements[button.dataset.move!],source=`pointer-${button.dataset.move}`;
|
||||
button.onpointerdown = event => { button.setPointerCapture(event.pointerId); input.press(source,key); };
|
||||
button.onpointerup = button.onpointercancel = button.onlostpointercapture = () => input.release(source);
|
||||
});
|
||||
view.canvas.addEventListener('pointerdown', event => {
|
||||
if (!snapshot || $<HTMLDialogElement>('ending').open || event.button !== 0) return;
|
||||
if (!snapshot || hasOpenMenu() || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open || event.button !== 0) return;
|
||||
const hit = view.pick(event.clientX, event.clientY);
|
||||
if (hit.entity) { selection(hit.entity); action(['boss', 'sentinel'].includes(hit.entity.kind) ? 'attack' : 'gather'); }
|
||||
else if (hit.point) { selection(); walkTo = hit.point; pendingAction = undefined; }
|
||||
});
|
||||
Object.defineProperty(window, '__aeternalis', { value: { diagnostics: () => view.diagnostics(), get snapshot() { return snapshot; }, get walkTo() { return walkTo; }, get pendingAction() { return pendingAction; }, get keys() { return [...keys]; } }, configurable: true });
|
||||
Object.defineProperty(window, '__aeternalis', { value: { diagnostics: () => view.diagnostics(), get snapshot() { return snapshot; }, get walkTo() { return walkTo; }, get pendingAction() { return pendingAction; }, get keys() { return input.keys; } }, configurable: true });
|
||||
}
|
||||
boot().catch(error => { console.error(error); $('arrival-error').textContent = `Unable to enter the world: ${error.message}`; $('connection-status').textContent = 'Unavailable'; });
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
type Menu = { element: HTMLElement; close: () => void; order: number; previous?: HTMLElement };
|
||||
const menus = new Set<Menu>();
|
||||
let order = 0;
|
||||
function visible(menu: Menu) {
|
||||
return menu.element.isConnected && !menu.element.closest('[hidden]') &&
|
||||
!menu.element.matches('dialog:not([open])') && menu.element.getClientRects().length > 0;
|
||||
}
|
||||
export function hasOpenMenu() { return [...menus].some(visible); }
|
||||
|
||||
// Menus use their own close operation, including inline editors and native dialogs.
|
||||
// Capture Escape before input fields or gameplay; close one focused layer only.
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.key !== 'Escape') return;
|
||||
const open = [...menus].filter(visible).sort((a, b) => b.order - a.order);
|
||||
const focused = open.filter(m => m.element.contains(document.activeElement));
|
||||
const menu = focused.find(m => !focused.some(other => other !== m && m.element.contains(other.element))) ?? open[0];
|
||||
if (!menu) return;
|
||||
event.preventDefault(); event.stopImmediatePropagation();
|
||||
if (!event.repeat) menu.close();
|
||||
}, true);
|
||||
|
||||
export function registerMenu(element: HTMLElement, close: () => void) {
|
||||
const menu: Menu = { element, close: () => { close(); if (!visible(menu) && menu.previous?.isConnected) menu.previous.focus({preventScroll:true}); }, order: ++order };
|
||||
const touch = () => { menu.order = ++order; };
|
||||
element.addEventListener('focusin', touch); element.addEventListener('pointerdown', touch);
|
||||
menus.add(menu);
|
||||
return {
|
||||
opened(previous = document.activeElement) {
|
||||
menu.previous = previous instanceof HTMLElement ? previous : undefined;
|
||||
touch(); element.tabIndex = -1;
|
||||
(element.querySelector<HTMLElement>('button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled])') ?? element).focus({preventScroll:true});
|
||||
},
|
||||
close: menu.close,
|
||||
dispose() { menus.delete(menu); element.removeEventListener('focusin', touch); element.removeEventListener('pointerdown', touch); }
|
||||
};
|
||||
}
|
||||
@@ -145,6 +145,14 @@ the simulation lock and checkpoint updates before snapshots. New title requireme
|
||||
are evaluated on the next gameplay event. Published content cannot rewrite earned
|
||||
title awards or acquired equipment snapshots.
|
||||
|
||||
Milestone 2 adds immutable reusable requirement/effect sets to that same catalog.
|
||||
Publication resolves them into concrete title/item requirements and stat modifiers;
|
||||
no live references can rewrite awards or equipment. The admin preview endpoint
|
||||
uses the same semantic validation without writing catalog/audit state. Existing
|
||||
catalogs without set collections remain compatible. Input actions and a shared
|
||||
focused-menu handler separate keyboard/pointer input from intents; Esc closes one
|
||||
focused menu. See [milestone 2 handoff](MILESTONE-2.md) for manual checks and scope.
|
||||
|
||||
Equipment instances retain identity across equip, drop, corpse loot, and passage.
|
||||
All equipment effects are excluded when checking prerequisites, preventing items
|
||||
from enabling themselves or each other. Invalidated equipment returns to the bag.
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
# Milestone 2: content and input foundations
|
||||
|
||||
Implemented for manual testing. Model rigs, equipment attachments, animations, and
|
||||
sound hooks remain in milestone 4.5. Playwright authoring/runs remain deferred.
|
||||
|
||||
## Available in Control -> Content
|
||||
|
||||
- **Requirement sets:** immutable named collections of up to eight integer
|
||||
thresholds. Titles support existing achievement/stat metrics; equipment accepts
|
||||
sets containing only level/stat thresholds. Existing title prerequisites on
|
||||
equipment remain available separately.
|
||||
- **Effect sets:** immutable named collections of signed flat/percentage stat
|
||||
modifiers. These are the first reusable effect building blocks; timed damage,
|
||||
healing, auras, and spell behavior arrive with their later systems.
|
||||
- **Composition:** title/equipment drafts can select up to eight sets of each kind
|
||||
and include inline values. Repeated thresholds resolve to the highest value;
|
||||
modifiers add using the existing stat formula. The final result still obeys
|
||||
title/item limits. Unsupported equipment metrics fail server validation.
|
||||
- **Preview changes:** validates and shows the resolved definition against the
|
||||
draft's catalog version. It does not publish, increment the version, create
|
||||
items/awards, or write an audit event. Form edits clear the previous preview.
|
||||
- **Publish changes:** repeats the same content validation under the existing
|
||||
catalog lock and writes the catalog version and audit atomically. Stale editors,
|
||||
duplicate IDs, missing sets, mixed payloads, unsupported values, and repeated
|
||||
references are rejected. Identical publication retries return the original result.
|
||||
|
||||
Sets are expanded into concrete values at publication, not stored as live links on
|
||||
acquired gear or earned titles. Published definitions/sets are append-only: use a new
|
||||
ID for a variation. Sets cannot reference other sets, so recursive composition is
|
||||
not supported. Old catalogs without these collections remain valid. No new table
|
||||
or title-ownership migration is required for this milestone.
|
||||
|
||||
Server implementations: `content/library.go`, `store/catalog_preview.go`, and the
|
||||
existing catalog publication path. Shared content API models are generated from
|
||||
`schemas/protocol.json` alongside the unchanged gameplay intent/snapshot shapes.
|
||||
The read-only preview uses authenticated same-origin POST
|
||||
`/api/control/catalog/preview` with the same draft body as publication.
|
||||
|
||||
## Input and menus
|
||||
|
||||
Keyboard and movement buttons feed named input actions rather than duplicating
|
||||
gameplay dispatch. Existing bindings remain: WASD/arrows move, E gathers, Space
|
||||
attacks, and I opens inventory. Controller support and rebinding UI arrive later.
|
||||
|
||||
Esc closes one focused menu: game inventory/settings, Control character/command
|
||||
dialogs, or the content draft. With multiple panels open, only the focused/most
|
||||
recent menu closes. Focus returns to its opener where available. Esc works while
|
||||
editing a field and does not trigger an underlying game action.
|
||||
|
||||
Opening a game menu stops movement/auto-approach; typing in fields cannot move or
|
||||
attack. Key release, pointer capture loss, tab hiding, and window blur clear held
|
||||
movement. Closing a draft discards unsaved edits; closing while a request is in
|
||||
flight does not cancel that submitted request. Publication results still appear
|
||||
in the catalog/audit. Arrival/death/disconnect screens retain their existing flows.
|
||||
|
||||
## Manual test checklist
|
||||
|
||||
Use unique test IDs; published test content cannot currently be deleted.
|
||||
|
||||
1. In **Control -> Content -> Requirement sets**, create `m2_level` with level >= 1.
|
||||
Fill a reason, preview, and confirm the catalog version/audit has not changed.
|
||||
Publish; refresh and confirm the new set and one audit/version increment.
|
||||
2. Create effect set `m2_defence` with defence +2 flat and movement speed -5%.
|
||||
Preview/publish it. Create a ring with those two sets, drop chance 0, and any
|
||||
inline modifiers you want to inspect. Preview shows the expanded requirements
|
||||
and effects. Publish and confirm the equipment list contains the same values.
|
||||
3. Use **Control -> Characters -> Manage items and titles** to give the ring to a
|
||||
living character. Equip/unequip it in game and inspect the final stat breakdown.
|
||||
Confirm existing inventory, titles, health, and daily usage were not reset.
|
||||
4. Try publishing an already-used set ID: expect rejection and no version change.
|
||||
For stale editing, open drafts in two Control tabs, publish one, then preview/
|
||||
publish the other: expect a refresh conflict, not silent overwriting.
|
||||
5. Open inventory and settings together. Focus a settings field and press Esc:
|
||||
settings closes, inventory stays open. Press Esc again: inventory closes.
|
||||
Repeat in a Control draft and a character/command dialog; only that menu closes.
|
||||
6. Move with WASD/arrows and the on-screen controls, gather with E, attack with
|
||||
Space. Opening a menu or switching tabs stops movement. Typing in fields must
|
||||
not move/attack; returning focus must not leave a movement key stuck.
|
||||
|
||||
## Verification and limits
|
||||
|
||||
Required verification: TypeScript check, production build, generated-contract
|
||||
freshness, and Go tests. Added server tests cover preview non-mutation, composed
|
||||
publication parity, reference validation, retry identity, immutable IDs, restart
|
||||
persistence, and anonymous/player/cross-origin/strict-JSON boundaries. Existing
|
||||
lifecycle tests remain in the full Go suite. PostgreSQL-specific tests require
|
||||
`TEST_DATABASE_URL`; no new capacity/load claim is made.
|
||||
|
||||
Manual browser testing is the user's handoff; automated Playwright was not run.
|
||||
This milestone does not activate resurrection, hub travel, character-title
|
||||
migration, new resource/mob definitions, or model/animation/audio systems.
|
||||
Pause after commit/push for feedback before milestone 3.
|
||||
@@ -518,7 +518,11 @@ are an in-game feature proposal; no external messages are sent by this plan.
|
||||
Milestone 1 specification: [Lifecycle and ownership contract](../docs/LIFECYCLE-OWNERSHIP.md).
|
||||
The foundation document defines states, identities, transactions, migration
|
||||
boundaries, and a review checklist. It is delivered for user review; it does not
|
||||
activate future gameplay or change existing saves. Milestone 2 has not started.
|
||||
activate future gameplay or change existing saves.
|
||||
Milestone 2 implementation and manual handoff:
|
||||
[Content and input foundations](../docs/MILESTONE-2.md). Reusable requirement/effect
|
||||
sets, server preview, and focused-menu/input actions are ready for manual testing.
|
||||
Milestone 3 has not started.
|
||||
|
||||
This replaces the earlier proposed order. Each milestone produces a reviewable
|
||||
slice, followed by commit/push and a user testing handoff. These are dependency-based
|
||||
|
||||
+68
-1
@@ -5,10 +5,77 @@
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"intent": {"$ref": "#/definitions/Intent"},
|
||||
"snapshot": {"$ref": "#/definitions/Snapshot"}
|
||||
"snapshot": {"$ref": "#/definitions/Snapshot"},
|
||||
"catalog": {"$ref": "#/definitions/ContentCatalog"},
|
||||
"catalogChange": {"$ref": "#/definitions/ContentChange"},
|
||||
"catalogPreview": {"$ref": "#/definitions/ContentPreview"}
|
||||
},
|
||||
"required": ["intent", "snapshot"],
|
||||
"definitions": {
|
||||
"ContentRequirement": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {"metric": {"type": "string"}, "atLeast": {"type": "integer"}},
|
||||
"required": ["metric", "atLeast"]
|
||||
},
|
||||
"RequirementSet": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {"id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, "requirements": {"type": "array", "items": {"$ref": "#/definitions/ContentRequirement"}}},
|
||||
"required": ["id", "name", "description", "requirements"]
|
||||
},
|
||||
"EffectSet": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {"id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, "modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}},
|
||||
"required": ["id", "name", "description", "modifiers"]
|
||||
},
|
||||
"TitleDefinition": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, "scope": {"type": "string"},
|
||||
"requirements": {"type": "array", "items": {"$ref": "#/definitions/ContentRequirement"}}, "effects": {"$ref": "#/definitions/TitleEffects"}
|
||||
},
|
||||
"required": ["id", "name", "description", "scope", "requirements", "effects"]
|
||||
},
|
||||
"ItemDefinition": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}, "slot": {"type": "string"},
|
||||
"weight": {"type": "number"}, "dropChance": {"type": "number"}, "requirements": {"$ref": "#/definitions/ItemRequirements"},
|
||||
"modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}
|
||||
},
|
||||
"required": ["id", "name", "description", "slot", "weight", "dropChance", "requirements", "modifiers"]
|
||||
},
|
||||
"ContentStatsRules": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"version": {"type": "integer"}, "base": {"type": "object", "additionalProperties": {"type": "number"}},
|
||||
"coefficients": {"type": "object", "additionalProperties": {"type": "object", "additionalProperties": {"type": "number"}}}
|
||||
},
|
||||
"required": ["version", "base", "coefficients"]
|
||||
},
|
||||
"ContentCatalog": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"version": {"type": "integer"}, "titles": {"type": "array", "items": {"$ref": "#/definitions/TitleDefinition"}},
|
||||
"items": {"type": "array", "items": {"$ref": "#/definitions/ItemDefinition"}}, "stats": {"$ref": "#/definitions/ContentStatsRules"},
|
||||
"requirementSets": {"type": "array", "items": {"$ref": "#/definitions/RequirementSet"}}, "effectSets": {"type": "array", "items": {"$ref": "#/definitions/EffectSet"}}
|
||||
},
|
||||
"required": ["version", "titles", "items", "stats"]
|
||||
},
|
||||
"ContentChange": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {
|
||||
"id": {"type": "string"}, "expectedVersion": {"type": "integer"}, "op": {"type": "string"}, "reason": {"type": "string"},
|
||||
"title": {"$ref": "#/definitions/TitleDefinition"}, "item": {"$ref": "#/definitions/ItemDefinition"}, "stats": {"$ref": "#/definitions/ContentStatsRules"},
|
||||
"requirementSet": {"$ref": "#/definitions/RequirementSet"}, "effectSet": {"$ref": "#/definitions/EffectSet"},
|
||||
"requirementSetIds": {"type": "array", "items": {"type": "string"}}, "effectSetIds": {"type": "array", "items": {"type": "string"}}
|
||||
},
|
||||
"required": ["id", "expectedVersion", "op", "reason"]
|
||||
},
|
||||
"ContentPreview": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {"basedOnVersion": {"type": "integer"}, "proposedVersion": {"type": "integer"}, "resolved": {"$ref": "#/definitions/ContentChange"}},
|
||||
"required": ["basedOnVersion", "proposedVersion", "resolved"]
|
||||
},
|
||||
"Vec3": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"properties": {"x": {"type": "number"}, "y": {"type": "number"}, "z": {"type": "number"}},
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package content
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Sets are immutable authoring building blocks. Consumers receive expanded
|
||||
// values at publication; earned awards and acquired items never hold live refs.
|
||||
type RequirementSet struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Requirements []TitleRequirement `json:"requirements"`
|
||||
}
|
||||
type EffectSet struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
}
|
||||
|
||||
func ValidRequirement(r TitleRequirement) bool {
|
||||
return (KnownStat(r.Metric) || slices.Contains([]string{"level", "kills", "worldKills", "bossKills", "worldsSurvived", "gathering", "crafting", "combat", "deaths"}, r.Metric)) && r.AtLeast >= 1 && r.AtLeast <= 1000000000
|
||||
}
|
||||
|
||||
func validSetIdentity(id, name, description string) bool {
|
||||
return titleID.MatchString(id) && len(strings.TrimSpace(name)) > 0 && len(name) <= 80 && len(description) <= 500
|
||||
}
|
||||
|
||||
func (c Catalog) validateLibrary() error {
|
||||
if len(c.RequirementSets) > 256 || len(c.EffectSets) > 256 {
|
||||
return fmt.Errorf("too many reusable sets")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, set := range c.RequirementSets {
|
||||
if !validSetIdentity(set.ID, set.Name, set.Description) || seen[set.ID] || len(set.Requirements) < 1 || len(set.Requirements) > 8 {
|
||||
return fmt.Errorf("invalid or duplicate requirement set %q", set.ID)
|
||||
}
|
||||
seen[set.ID] = true
|
||||
metrics := map[string]bool{}
|
||||
for _, r := range set.Requirements {
|
||||
if !ValidRequirement(r) || metrics[r.Metric] {
|
||||
return fmt.Errorf("invalid or repeated metric in requirement set %q", set.ID)
|
||||
}
|
||||
metrics[r.Metric] = true
|
||||
}
|
||||
}
|
||||
seen = map[string]bool{}
|
||||
for _, set := range c.EffectSets {
|
||||
if !validSetIdentity(set.ID, set.Name, set.Description) || seen[set.ID] || len(set.Modifiers) < 1 {
|
||||
return fmt.Errorf("invalid or duplicate effect set %q", set.ID)
|
||||
}
|
||||
seen[set.ID] = true
|
||||
if err := ValidateModifiers(set.Modifiers); err != nil {
|
||||
return fmt.Errorf("effect set %q: %w", set.ID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResolveSets is also used by publication previews. References cannot recurse:
|
||||
// sets contain only concrete predicates/modifiers, never other set references.
|
||||
func (c Catalog) ResolveSets(requirements, effects []string) ([]TitleRequirement, []StatModifier, error) {
|
||||
if len(requirements) > 8 || len(effects) > 8 {
|
||||
return nil, nil, fmt.Errorf("choose at most eight sets of each kind")
|
||||
}
|
||||
var req []TitleRequirement
|
||||
var mods []StatModifier
|
||||
seen := map[string]bool{}
|
||||
for _, id := range requirements {
|
||||
if seen[id] {
|
||||
return nil, nil, fmt.Errorf("repeated requirement set %q", id)
|
||||
}
|
||||
seen[id] = true
|
||||
index := slices.IndexFunc(c.RequirementSets, func(s RequirementSet) bool { return s.ID == id })
|
||||
if index < 0 {
|
||||
return nil, nil, fmt.Errorf("unknown requirement set %q", id)
|
||||
}
|
||||
req = append(req, c.RequirementSets[index].Requirements...)
|
||||
}
|
||||
seen = map[string]bool{}
|
||||
for _, id := range effects {
|
||||
if seen[id] {
|
||||
return nil, nil, fmt.Errorf("repeated effect set %q", id)
|
||||
}
|
||||
seen[id] = true
|
||||
index := slices.IndexFunc(c.EffectSets, func(s EffectSet) bool { return s.ID == id })
|
||||
if index < 0 {
|
||||
return nil, nil, fmt.Errorf("unknown effect set %q", id)
|
||||
}
|
||||
mods = append(mods, c.EffectSets[index].Modifiers...)
|
||||
}
|
||||
return req, mods, nil
|
||||
}
|
||||
@@ -52,7 +52,6 @@ func (b Balance) validateProgression() error {
|
||||
return fmt.Errorf("too many title definitions")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
metrics := map[string]bool{"level": true, "kills": true, "worldKills": true, "bossKills": true, "worldsSurvived": true, "gathering": true, "crafting": true, "combat": true, "deaths": true}
|
||||
for _, title := range b.Titles {
|
||||
if !titleID.MatchString(title.ID) || seen[title.ID] || len(title.Name) < 1 || len(title.Name) > 80 || len(title.Description) > 500 {
|
||||
return fmt.Errorf("invalid or duplicate title %q", title.ID)
|
||||
@@ -65,7 +64,7 @@ func (b Balance) validateProgression() error {
|
||||
return fmt.Errorf("title %q needs bounded requirements", title.ID)
|
||||
}
|
||||
for _, r := range title.Requirements {
|
||||
if (!metrics[r.Metric] && !KnownStat(r.Metric)) || r.AtLeast < 1 || r.AtLeast > 1000000000 {
|
||||
if !ValidRequirement(r) {
|
||||
return fmt.Errorf("invalid title requirement for %q", title.ID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,10 +44,12 @@ type ItemDefinition struct {
|
||||
Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"`
|
||||
}
|
||||
type Catalog struct {
|
||||
Version int64 `json:"version"`
|
||||
Titles []Title `json:"titles"`
|
||||
Items []ItemDefinition `json:"items"`
|
||||
Stats StatsRules `json:"stats"`
|
||||
Version int64 `json:"version"`
|
||||
Titles []Title `json:"titles"`
|
||||
Items []ItemDefinition `json:"items"`
|
||||
Stats StatsRules `json:"stats"`
|
||||
RequirementSets []RequirementSet `json:"requirementSets,omitempty"`
|
||||
EffectSets []EffectSet `json:"effectSets,omitempty"`
|
||||
}
|
||||
|
||||
func KnownStat(stat string) bool {
|
||||
@@ -120,6 +122,9 @@ func (item ItemDefinition) Validate() error {
|
||||
return ValidateModifiers(item.Modifiers)
|
||||
}
|
||||
func (c Catalog) Validate() error {
|
||||
if err := c.validateLibrary(); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.Version < 1 || len(c.Items) > 512 {
|
||||
return fmt.Errorf("invalid catalog version or item count")
|
||||
}
|
||||
|
||||
@@ -2,8 +2,103 @@
|
||||
package protocol
|
||||
|
||||
type Protocol struct {
|
||||
Intent Intent `json:"intent"`
|
||||
Snapshot Snapshot `json:"snapshot"`
|
||||
Catalog *ContentCatalog `json:"catalog,omitempty"`
|
||||
CatalogChange *ContentChange `json:"catalogChange,omitempty"`
|
||||
CatalogPreview *ContentPreview `json:"catalogPreview,omitempty"`
|
||||
Intent Intent `json:"intent"`
|
||||
Snapshot Snapshot `json:"snapshot"`
|
||||
}
|
||||
|
||||
type ContentCatalog struct {
|
||||
EffectSets []EffectSet `json:"effectSets,omitempty"`
|
||||
Items []ItemDefinition `json:"items"`
|
||||
RequirementSets []RequirementSet `json:"requirementSets,omitempty"`
|
||||
Stats ContentStatsRules `json:"stats"`
|
||||
Titles []TitleDefinition `json:"titles"`
|
||||
Version int64 `json:"version"`
|
||||
}
|
||||
|
||||
type EffectSet struct {
|
||||
Description string `json:"description"`
|
||||
ID string `json:"id"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type StatModifier struct {
|
||||
Flat float64 `json:"flat"`
|
||||
Percent float64 `json:"percent"`
|
||||
Stat string `json:"stat"`
|
||||
}
|
||||
|
||||
type ItemDefinition struct {
|
||||
Description string `json:"description"`
|
||||
DropChance float64 `json:"dropChance"`
|
||||
ID string `json:"id"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
Requirements ItemRequirements `json:"requirements"`
|
||||
Slot string `json:"slot"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type ItemRequirements struct {
|
||||
Level int64 `json:"level"`
|
||||
Stats map[string]float64 `json:"stats"`
|
||||
Titles []string `json:"titles"`
|
||||
}
|
||||
|
||||
type RequirementSet struct {
|
||||
Description string `json:"description"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Requirements []ContentRequirement `json:"requirements"`
|
||||
}
|
||||
|
||||
type ContentRequirement struct {
|
||||
AtLeast int64 `json:"atLeast"`
|
||||
Metric string `json:"metric"`
|
||||
}
|
||||
|
||||
type ContentStatsRules struct {
|
||||
Base map[string]float64 `json:"base"`
|
||||
Coefficients map[string]map[string]float64 `json:"coefficients"`
|
||||
Version int64 `json:"version"`
|
||||
}
|
||||
|
||||
type TitleDefinition struct {
|
||||
Description string `json:"description"`
|
||||
Effects TitleEffects `json:"effects"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Requirements []ContentRequirement `json:"requirements"`
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
|
||||
type TitleEffects struct {
|
||||
Damage float64 `json:"damage"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
MoveSpeed float64 `json:"moveSpeed"`
|
||||
}
|
||||
|
||||
type ContentChange struct {
|
||||
EffectSet *EffectSet `json:"effectSet,omitempty"`
|
||||
EffectSetIDS []string `json:"effectSetIds,omitempty"`
|
||||
ExpectedVersion int64 `json:"expectedVersion"`
|
||||
ID string `json:"id"`
|
||||
Item *ItemDefinition `json:"item,omitempty"`
|
||||
Op string `json:"op"`
|
||||
Reason string `json:"reason"`
|
||||
RequirementSet *RequirementSet `json:"requirementSet,omitempty"`
|
||||
RequirementSetIDS []string `json:"requirementSetIds,omitempty"`
|
||||
Stats *ContentStatsRules `json:"stats,omitempty"`
|
||||
Title *TitleDefinition `json:"title,omitempty"`
|
||||
}
|
||||
|
||||
type ContentPreview struct {
|
||||
BasedOnVersion int64 `json:"basedOnVersion"`
|
||||
ProposedVersion int64 `json:"proposedVersion"`
|
||||
Resolved ContentChange `json:"resolved"`
|
||||
}
|
||||
|
||||
type Intent struct {
|
||||
@@ -94,18 +189,6 @@ type ItemInstance struct {
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type StatModifier struct {
|
||||
Flat float64 `json:"flat"`
|
||||
Percent float64 `json:"percent"`
|
||||
Stat string `json:"stat"`
|
||||
}
|
||||
|
||||
type ItemRequirements struct {
|
||||
Level int64 `json:"level"`
|
||||
Stats map[string]float64 `json:"stats"`
|
||||
Titles []string `json:"titles"`
|
||||
}
|
||||
|
||||
type StatValue struct {
|
||||
Base float64 `json:"base"`
|
||||
Final float64 `json:"final"`
|
||||
@@ -123,12 +206,6 @@ type TitleAward struct {
|
||||
WorldID string `json:"worldId"`
|
||||
}
|
||||
|
||||
type TitleEffects struct {
|
||||
Damage float64 `json:"damage"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
MoveSpeed float64 `json:"moveSpeed"`
|
||||
}
|
||||
|
||||
type WorldInfo struct {
|
||||
AgeSeconds float64 `json:"ageSeconds"`
|
||||
BossHP float64 `json:"bossHp"`
|
||||
|
||||
@@ -17,13 +17,17 @@ var ErrCatalogInvalid = errors.New("invalid catalog change")
|
||||
var catalogRequestID = regexp.MustCompile(`^[a-f0-9-]{32,36}$`)
|
||||
|
||||
type CatalogChange struct {
|
||||
ID string `json:"id"`
|
||||
ExpectedVersion int64 `json:"expectedVersion"`
|
||||
Op string `json:"op"`
|
||||
Reason string `json:"reason"`
|
||||
Title *content.Title `json:"title,omitempty"`
|
||||
Item *content.ItemDefinition `json:"item,omitempty"`
|
||||
Stats *content.StatsRules `json:"stats,omitempty"`
|
||||
ID string `json:"id"`
|
||||
ExpectedVersion int64 `json:"expectedVersion"`
|
||||
Op string `json:"op"`
|
||||
Reason string `json:"reason"`
|
||||
Title *content.Title `json:"title,omitempty"`
|
||||
Item *content.ItemDefinition `json:"item,omitempty"`
|
||||
Stats *content.StatsRules `json:"stats,omitempty"`
|
||||
RequirementSet *content.RequirementSet `json:"requirementSet,omitempty"`
|
||||
EffectSet *content.EffectSet `json:"effectSet,omitempty"`
|
||||
RequirementSetIDs []string `json:"requirementSetIds,omitempty"`
|
||||
EffectSetIDs []string `json:"effectSetIds,omitempty"`
|
||||
}
|
||||
type CatalogResult struct {
|
||||
Version int64 `json:"version"`
|
||||
@@ -110,6 +114,12 @@ func (c CatalogChange) validate() error {
|
||||
return fmt.Errorf("%w: request ID, current version and 5-240 character reason required", ErrCatalogInvalid)
|
||||
}
|
||||
valid := false
|
||||
count := 0
|
||||
for _, present := range []bool{c.Title != nil, c.Item != nil, c.Stats != nil, c.RequirementSet != nil, c.EffectSet != nil} {
|
||||
if present {
|
||||
count++
|
||||
}
|
||||
}
|
||||
switch c.Op {
|
||||
case "create-title":
|
||||
valid = c.Title != nil && c.Item == nil && c.Stats == nil
|
||||
@@ -117,8 +127,12 @@ func (c CatalogChange) validate() error {
|
||||
valid = c.Item != nil && c.Title == nil && c.Stats == nil
|
||||
case "update-stats":
|
||||
valid = c.Stats != nil && c.Title == nil && c.Item == nil
|
||||
case "create-requirement-set":
|
||||
valid = c.RequirementSet != nil
|
||||
case "create-effect-set":
|
||||
valid = c.EffectSet != nil
|
||||
}
|
||||
if !valid {
|
||||
if !valid || count != 1 || ((c.Op != "create-title" && c.Op != "create-item") && (len(c.RequirementSetIDs) != 0 || len(c.EffectSetIDs) != 0)) {
|
||||
return fmt.Errorf("%w: operation must have exactly its matching payload", ErrCatalogInvalid)
|
||||
}
|
||||
return nil
|
||||
@@ -176,20 +190,9 @@ func (d *DB) PublishCatalog(ctx context.Context, actor string, change CatalogCha
|
||||
if err != nil {
|
||||
return CatalogResult{}, err
|
||||
}
|
||||
target := "stats"
|
||||
switch change.Op {
|
||||
case "create-title":
|
||||
catalog.Titles = append(catalog.Titles, *change.Title)
|
||||
target = change.Title.ID
|
||||
case "create-item":
|
||||
catalog.Items = append(catalog.Items, *change.Item)
|
||||
target = change.Item.ID
|
||||
case "update-stats":
|
||||
catalog.Stats = *change.Stats
|
||||
}
|
||||
catalog.Version = version + 1
|
||||
if err = catalog.Validate(); err != nil {
|
||||
return CatalogResult{}, fmt.Errorf("%w: %v", ErrCatalogInvalid, err)
|
||||
catalog, target, _, err := buildCatalog(catalog, change)
|
||||
if err != nil {
|
||||
return CatalogResult{}, err
|
||||
}
|
||||
encoded, err := json.Marshal(catalog)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLibraryPreviewPublicationAndRestart(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
dsn := "file:" + filepath.ToSlash(filepath.Join(t.TempDir(), "library.db"))
|
||||
db, err := Open(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { db.Close() }()
|
||||
catalog, err := db.Catalog(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
publish := func(c CatalogChange) CatalogResult {
|
||||
t.Helper()
|
||||
c.ID = game.ID()
|
||||
c.ExpectedVersion = catalog.Version
|
||||
c.Reason = "Library test publication"
|
||||
r, e := db.PublishCatalog(ctx, "operator", c)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
catalog, e = db.Catalog(ctx)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return r
|
||||
}
|
||||
publish(CatalogChange{Op: "create-requirement-set", RequirementSet: &content.RequirementSet{ID: "strong", Name: "Strong", Requirements: []content.TitleRequirement{{Metric: "level", AtLeast: 3}, {Metric: "strength", AtLeast: 4}}}})
|
||||
publish(CatalogChange{Op: "create-effect-set", EffectSet: &content.EffectSet{ID: "sturdy", Name: "Sturdy", Modifiers: []content.StatModifier{{Stat: "strength", Flat: 2, Percent: 10}, {Stat: "moveSpeed", Percent: -5}}}})
|
||||
item := content.ItemDefinition{ID: "library_ring", Name: "Library ring", Slot: "ring", Weight: 1, Requirements: content.ItemRequirements{Level: 1, Stats: map[string]float64{"strength": 5}}, Modifiers: []content.StatModifier{{Stat: "strength", Flat: 1}}}
|
||||
change := CatalogChange{ID: game.ID(), ExpectedVersion: catalog.Version, Op: "create-item", Reason: "Publish composed item", Item: &item, RequirementSetIDs: []string{"strong"}, EffectSetIDs: []string{"sturdy"}}
|
||||
before, _ := json.Marshal(change)
|
||||
audits, err := db.CatalogChanges(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
preview, err := db.PreviewCatalog(ctx, change)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, _ := json.Marshal(change)
|
||||
if string(before) != string(after) {
|
||||
t.Fatal("preview mutated caller input")
|
||||
}
|
||||
unchanged, err := db.Catalog(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newAudits, err := db.CatalogChanges(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(catalog, unchanged) || len(audits) != len(newAudits) {
|
||||
t.Fatal("preview wrote catalog/audit")
|
||||
}
|
||||
resolved := preview.Resolved.Item
|
||||
if len(preview.Resolved.RequirementSetIDs) != 0 || len(preview.Resolved.EffectSetIDs) != 0 {
|
||||
t.Fatal("resolved preview would expand sets twice")
|
||||
}
|
||||
if resolved.Requirements.Level != 3 || resolved.Requirements.Stats["strength"] != 5 || len(resolved.Modifiers) != 3 {
|
||||
t.Fatalf("unexpected resolution: %+v", resolved)
|
||||
}
|
||||
result, err := db.PublishCatalog(ctx, "operator", change)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replay, err := db.PublishCatalog(ctx, "operator", change)
|
||||
if err != nil || replay != result {
|
||||
t.Fatal("replay failed", err)
|
||||
}
|
||||
if _, err = db.PreviewCatalog(ctx, change); !errors.Is(err, ErrCatalogConflict) {
|
||||
t.Fatal("stale preview accepted", err)
|
||||
}
|
||||
changed := change
|
||||
changed.EffectSetIDs = nil
|
||||
if _, err = db.PublishCatalog(ctx, "operator", changed); !errors.Is(err, ErrCatalogRequest) {
|
||||
t.Fatal("changed reference replay accepted", err)
|
||||
}
|
||||
catalog, err = db.Catalog(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(catalog.Items[len(catalog.Items)-1], *resolved) {
|
||||
t.Fatal("publication differs from preview")
|
||||
}
|
||||
// A set used without inline requirements also composes a real title.
|
||||
publish(CatalogChange{Op: "create-title", Title: &content.Title{ID: "library_title", Name: "Library title", Scope: "personal"}, RequirementSetIDs: []string{"strong"}, EffectSetIDs: []string{"sturdy"}})
|
||||
if len(catalog.Titles[len(catalog.Titles)-1].Requirements) != 2 {
|
||||
t.Fatal("title did not expand sets")
|
||||
}
|
||||
if err = db.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db, err = Open(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restored, err := db.Catalog(ctx)
|
||||
if err != nil || !reflect.DeepEqual(catalog, restored) {
|
||||
t.Fatal("restart lost library or expanded definitions", err)
|
||||
}
|
||||
// Immutable set IDs cannot alter already published consumers.
|
||||
duplicate := CatalogChange{ID: game.ID(), ExpectedVersion: catalog.Version, Op: "create-effect-set", Reason: "Duplicate set test", EffectSet: &content.EffectSet{ID: "sturdy", Name: "Changed", Modifiers: []content.StatModifier{{Stat: "strength", Flat: 99}}}}
|
||||
if _, err = db.PublishCatalog(ctx, "operator", duplicate); !errors.Is(err, ErrCatalogInvalid) {
|
||||
t.Fatal("set overwrite accepted", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryRejectsInvalidCompositionWithoutWrites(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "invalid.db")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
initial, err := db.Catalog(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.PublishCatalog(ctx, "operator", CatalogChange{ID: game.ID(), ExpectedVersion: initial.Version, Op: "create-requirement-set", Reason: "Title-only requirements", RequirementSet: &content.RequirementSet{ID: "slayer", Name: "Slayer", Requirements: []content.TitleRequirement{{Metric: "kills", AtLeast: 3}}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
initial, err = db.Catalog(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, mutate := range map[string]func(*CatalogChange){
|
||||
"unknown reference": func(c *CatalogChange) { c.RequirementSetIDs = []string{"missing"} },
|
||||
"duplicate reference": func(c *CatalogChange) { c.RequirementSetIDs = []string{"slayer", "slayer"} },
|
||||
"title metric on equipment": func(c *CatalogChange) { c.RequirementSetIDs = []string{"slayer"} },
|
||||
"unknown effect": func(c *CatalogChange) { c.EffectSetIDs = []string{"missing"} },
|
||||
"mixed payload": func(c *CatalogChange) { c.EffectSet = &content.EffectSet{ID: "bad", Name: "Bad"} },
|
||||
"protected field": func(c *CatalogChange) {
|
||||
c.Op = "create-effect-set"
|
||||
c.Item = nil
|
||||
c.EffectSet = &content.EffectSet{ID: "bad", Name: "Bad", Modifiers: []content.StatModifier{{Stat: "dailySeconds", Flat: 100}}}
|
||||
},
|
||||
"empty set": func(c *CatalogChange) {
|
||||
c.Op = "create-effect-set"
|
||||
c.Item = nil
|
||||
c.EffectSet = &content.EffectSet{ID: "empty", Name: "Empty"}
|
||||
},
|
||||
"set recursion": func(c *CatalogChange) {
|
||||
c.Op = "create-requirement-set"
|
||||
c.Item = nil
|
||||
c.RequirementSetIDs = []string{"slayer"}
|
||||
c.RequirementSet = &content.RequirementSet{ID: "nested", Name: "Nested", Requirements: []content.TitleRequirement{{Metric: "level", AtLeast: 1}}}
|
||||
},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
c := CatalogChange{ID: game.ID(), ExpectedVersion: initial.Version, Op: "create-item", Reason: "Invalid composition test", Item: &content.ItemDefinition{ID: "invalid_ring", Name: "Ring", Slot: "ring", Requirements: content.ItemRequirements{Level: 1}}}
|
||||
mutate(&c)
|
||||
if _, err := db.PreviewCatalog(ctx, c); !errors.Is(err, ErrCatalogInvalid) {
|
||||
t.Fatal("invalid preview accepted", err)
|
||||
}
|
||||
if _, err := db.PublishCatalog(ctx, "operator", c); !errors.Is(err, ErrCatalogInvalid) {
|
||||
t.Fatal("invalid publication accepted", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
final, err := db.Catalog(ctx)
|
||||
if err != nil || !reflect.DeepEqual(initial, final) {
|
||||
t.Fatal("rejected changes wrote catalog", err)
|
||||
}
|
||||
audits, err := db.CatalogChanges(ctx)
|
||||
if err != nil || len(audits) != 1 {
|
||||
t.Fatal("rejected changes wrote audit", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type CatalogPreview struct {
|
||||
BasedOnVersion int64 `json:"basedOnVersion"`
|
||||
ProposedVersion int64 `json:"proposedVersion"`
|
||||
Resolved CatalogChange `json:"resolved"`
|
||||
}
|
||||
|
||||
// Read-only. Publication repeats this exact validation under the catalog lock.
|
||||
func (d *DB) PreviewCatalog(ctx context.Context, change CatalogChange) (CatalogPreview, error) {
|
||||
change.Reason = strings.TrimSpace(change.Reason)
|
||||
if err := change.validate(); err != nil {
|
||||
return CatalogPreview{}, err
|
||||
}
|
||||
c, err := d.Catalog(ctx)
|
||||
if err != nil {
|
||||
return CatalogPreview{}, err
|
||||
}
|
||||
if c.Version != change.ExpectedVersion {
|
||||
return CatalogPreview{}, ErrCatalogConflict
|
||||
}
|
||||
next, _, resolved, err := buildCatalog(c, change)
|
||||
if err != nil {
|
||||
return CatalogPreview{}, err
|
||||
}
|
||||
return CatalogPreview{BasedOnVersion: c.Version, ProposedVersion: next.Version, Resolved: resolved}, nil
|
||||
}
|
||||
|
||||
func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, string, CatalogChange, error) {
|
||||
invalid := func(err error) (content.Catalog, string, CatalogChange, error) {
|
||||
return content.Catalog{}, "", CatalogChange{}, fmt.Errorf("%w: %v", ErrCatalogInvalid, err)
|
||||
}
|
||||
req, mods, err := c.ResolveSets(change.RequirementSetIDs, change.EffectSetIDs)
|
||||
if err != nil {
|
||||
return invalid(err)
|
||||
}
|
||||
resolved := change
|
||||
// The preview is a concrete definition, not another request to expand its sets.
|
||||
resolved.RequirementSetIDs = nil
|
||||
resolved.EffectSetIDs = nil
|
||||
target := "stats"
|
||||
switch change.Op {
|
||||
case "create-title":
|
||||
title := *change.Title
|
||||
if len(title.Requirements) > 8 {
|
||||
return invalid(fmt.Errorf("at most eight inline requirements are allowed"))
|
||||
}
|
||||
// All thresholds are ANDed, so repeated metrics resolve to their maximum.
|
||||
title.Requirements = nil
|
||||
for _, r := range append(slices.Clone(change.Title.Requirements), req...) {
|
||||
if !content.ValidRequirement(r) {
|
||||
return invalid(fmt.Errorf("invalid requirement for %q", title.ID))
|
||||
}
|
||||
i := slices.IndexFunc(title.Requirements, func(v content.TitleRequirement) bool { return v.Metric == r.Metric })
|
||||
if i < 0 {
|
||||
title.Requirements = append(title.Requirements, r)
|
||||
} else if r.AtLeast > title.Requirements[i].AtLeast {
|
||||
title.Requirements[i] = r
|
||||
}
|
||||
}
|
||||
title.Effects.Modifiers = append(slices.Clone(title.Effects.Modifiers), mods...)
|
||||
resolved.Title = &title
|
||||
c.Titles = append(slices.Clone(c.Titles), title)
|
||||
target = title.ID
|
||||
case "create-item":
|
||||
item := *change.Item
|
||||
// Validate inline values before merging, so sets cannot mask invalid input.
|
||||
if err := item.Validate(); err != nil {
|
||||
return invalid(err)
|
||||
}
|
||||
item.Requirements.Stats = maps.Clone(item.Requirements.Stats)
|
||||
if item.Requirements.Stats == nil {
|
||||
item.Requirements.Stats = map[string]float64{}
|
||||
}
|
||||
for _, r := range req {
|
||||
if r.Metric == "level" {
|
||||
item.Requirements.Level = max(item.Requirements.Level, r.AtLeast)
|
||||
} else if content.KnownStat(r.Metric) {
|
||||
item.Requirements.Stats[r.Metric] = max(item.Requirements.Stats[r.Metric], float64(r.AtLeast))
|
||||
} else {
|
||||
return invalid(fmt.Errorf("equipment cannot use metric %q; use level/stat requirement sets", r.Metric))
|
||||
}
|
||||
}
|
||||
item.Modifiers = append(slices.Clone(item.Modifiers), mods...)
|
||||
resolved.Item = &item
|
||||
c.Items = append(slices.Clone(c.Items), item)
|
||||
target = item.ID
|
||||
case "update-stats":
|
||||
c.Stats = *change.Stats
|
||||
case "create-requirement-set":
|
||||
c.RequirementSets = append(slices.Clone(c.RequirementSets), *change.RequirementSet)
|
||||
target = change.RequirementSet.ID
|
||||
case "create-effect-set":
|
||||
c.EffectSets = append(slices.Clone(c.EffectSets), *change.EffectSet)
|
||||
target = change.EffectSet.ID
|
||||
}
|
||||
c.Version++
|
||||
if err := c.Validate(); err != nil {
|
||||
return invalid(err)
|
||||
}
|
||||
return c, target, resolved, nil
|
||||
}
|
||||
@@ -29,38 +29,46 @@ func (h *HTTP) catalogRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
respond(w, 200, map[string]any{"catalog": catalog, "changes": changes})
|
||||
})
|
||||
mux.HandleFunc("POST /api/control/catalog", func(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := h.admin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var change store.CatalogChange
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 32768)
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&change); err != nil {
|
||||
fail(w, 400, "invalid catalog change")
|
||||
return
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); err != io.EOF {
|
||||
fail(w, 400, "invalid catalog change")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
result, err := h.auth.db.PublishCatalog(ctx, actor, change)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrCatalogConflict), errors.Is(err, store.ErrCatalogRequest):
|
||||
fail(w, 409, err.Error())
|
||||
case errors.Is(err, store.ErrCatalogInvalid):
|
||||
fail(w, 400, err.Error())
|
||||
case err != nil:
|
||||
fail(w, 503, "catalog publication unavailable")
|
||||
default:
|
||||
respond(w, 200, result)
|
||||
}
|
||||
})
|
||||
for _, path := range []string{"/api/control/catalog", "/api/control/catalog/preview"} {
|
||||
mux.HandleFunc("POST "+path, func(w http.ResponseWriter, r *http.Request) {
|
||||
actor, ok := h.admin(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var change store.CatalogChange
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 32768)
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&change); err != nil {
|
||||
fail(w, 400, "invalid catalog change")
|
||||
return
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); err != io.EOF {
|
||||
fail(w, 400, "invalid catalog change")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
var result any
|
||||
var err error
|
||||
if r.URL.Path == "/api/control/catalog/preview" {
|
||||
result, err = h.auth.db.PreviewCatalog(ctx, change)
|
||||
} else {
|
||||
result, err = h.auth.db.PublishCatalog(ctx, actor, change)
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, store.ErrCatalogConflict), errors.Is(err, store.ErrCatalogRequest):
|
||||
fail(w, 409, err.Error())
|
||||
case errors.Is(err, store.ErrCatalogInvalid):
|
||||
fail(w, 400, err.Error())
|
||||
case err != nil:
|
||||
fail(w, 503, "catalog publication unavailable")
|
||||
default:
|
||||
respond(w, 200, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Caller holds s.mu. Checkpoint a catalog before it can reach a snapshot.
|
||||
|
||||
@@ -65,15 +65,38 @@ func TestControlAuthorizationAndExecution(t *testing.T) {
|
||||
if request("GET", "/api/control", "", "", "") != 401 {
|
||||
t.Fatal("anonymous admin access")
|
||||
}
|
||||
if request("POST", "/api/control/catalog/preview", "{}", "", server.URL) != 401 {
|
||||
t.Fatal("anonymous preview access")
|
||||
}
|
||||
token := game.ID() + game.ID()
|
||||
_ = db.CreateSession(ctx, hash(token), "operator")
|
||||
if request("GET", "/api/control", "", token, "") != 403 {
|
||||
t.Fatal("player has admin access")
|
||||
}
|
||||
if request("POST", "/api/control/catalog/preview", "{}", token, server.URL) != 403 {
|
||||
t.Fatal("player preview access")
|
||||
}
|
||||
_ = db.GrantAdmin(ctx, hash(token), 600)
|
||||
if request("GET", "/api/control", "", token, "") != 200 {
|
||||
t.Fatal("admin denied")
|
||||
}
|
||||
previewBody := `{"id":"` + game.ID() + `","expectedVersion":1,"op":"create-effect-set","reason":"Preview effects","effectSet":{"id":"test_effect","name":"Test effect","description":"","modifiers":[{"stat":"strength","flat":2,"percent":0}]}}`
|
||||
if request("POST", "/api/control/catalog/preview", previewBody, token, "https://evil.example") != 403 {
|
||||
t.Fatal("cross-origin preview")
|
||||
}
|
||||
if request("POST", "/api/control/catalog/preview", previewBody, token, server.URL) != 200 {
|
||||
t.Fatal("valid preview rejected")
|
||||
}
|
||||
if request("POST", "/api/control/catalog/preview", strings.Replace(previewBody, `"flat":2`, `"flat":2,"script":"bad"`, 1), token, server.URL) != 400 {
|
||||
t.Fatal("unknown nested field accepted")
|
||||
}
|
||||
if request("POST", "/api/control/catalog/preview", previewBody+` {}`, token, server.URL) != 400 {
|
||||
t.Fatal("trailing JSON accepted")
|
||||
}
|
||||
previewCatalog, err := db.Catalog(ctx)
|
||||
if err != nil || previewCatalog.Version != 1 || len(previewCatalog.EffectSets) != 0 {
|
||||
t.Fatal("preview changed catalog", err)
|
||||
}
|
||||
body := `{"id":"` + game.ID() + `","worldId":"control-test","op":"close-admissions","reason":"maintenance window"}`
|
||||
if request("POST", "/api/control/commands", body, token, "https://evil.example") != 403 {
|
||||
t.Fatal("cross-origin admin command")
|
||||
|
||||
Reference in New Issue
Block a user