Add Player Workshop 2.0.0

This commit is contained in:
Jason committed 2026-12-02 21:10:42 -05:00
1 parent 193f82a729
commit 17b06810c8
11 files changed
+494 -1

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {ID,PLAYERS,ROWS,PACKS,ENABLE,DISABLE,lookup,preflight,applyPlan,routeNew,artPaths,desiredPermissions} from '../scripts/core.mjs';
function fixture(){
const roles={PLAYER:1,TRUSTED:2,ASSISTANT:3,GAMEMASTER:4};
const constants={USER_ROLES:roles,USER_PERMISSIONS:Object.fromEntries([...ENABLE,...DISABLE].map(k=>[k,{requiredRoles:[4]}]))};
const users=new Map([...PLAYERS,'Jason','Gamemaster'].map((name,i)=>[name,{id:`u${i}`,name,role:name==='Austin'?2:name==='Jason'?3:name==='Gamemaster'?4:1}]));
const folders=new Map(), packs=new Map(), actors=new Map();let seq=0;const mutations=[];
const game={user:users.get('Gamemaster'),release:{generation:14},system:{id:'dnd5e'},world:{id:'the-phandelver'},users,folders,packs,actors,permissions:{...Object.fromEntries([...ENABLE,...DISABLE].map(k=>[k,[2,3,4]])),OTHER:[1,4]},settings:{get(ns,k){return ns===ID?true:game.permissions;},async set(ns,k,v){game.permissions=v;mutations.push(k);}}};
const Folder={async create(data){const f={...data,id:`f${++seq}`,folder:folders.get(data.folder),toObject(){return {...data};}};folders.set(f.id,f);mutations.push('folder');return f;}};
for(const [,name] of ROWS){const actor={id:`a${++seq}`,name,folder:null,ownership:{default:2,old:3},system:{hp:55},toObject(){return {ownership:{...this.ownership}};},async update(p){this.folder=folders.get(p.folder);for(const [k,v] of Object.entries(p)){if(k.startsWith('ownership.-='))delete this.ownership[k.slice(12)];else if(k.startsWith('ownership.'))this.ownership[k.slice(10)]=v;}mutations.push('actor');}};actors.set(actor.id,actor);}
const official={title:'Official',collection:'dnd5e.official',locked:true,ownership:{PLAYER:'OBSERVER'}};packs.set(official.collection,official);
const Compendium={async createCompendium({label,name,type}){const p={title:label,collection:`world.${name}`,documentName:type,locked:true,ownership:{},folder:null,async configure(c){Object.assign(this,c);mutations.push('configure');},async setFolder(id){this.folder=folders.get(id);mutations.push('file');}};packs.set(p.collection,p);mutations.push('pack');return p;}};
const dirs=new Set(['worlds/the-phandelver']);
const Picker={async browse(_source,path){if(!dirs.has(path))throw Error('missing directory');return {dirs:[...dirs].filter(d=>d.slice(0,d.lastIndexOf('/'))===path)};},async createDirectory(_source,path){assert(!dirs.has(path));dirs.add(path);mutations.push('dir');return {};}};
return {game,constants,api:{Folder,Compendium,Picker},official,dirs,mutations};
}
test('preflight read-only; full apply; repeat makes zero mutations',async()=>{const f=fixture();const {game,constants,api,mutations}=f;const old=JSON.stringify(f.official);const active=await api.Folder.create({name:'Active Campaign',type:'Actor',folder:null});mutations.length=0;const plan=preflight(game,constants);assert.equal(mutations.length,0);await applyPlan(game,constants,api,plan,[]);assert.equal(lookup(game,'Actor',['Active Campaign']).id,active.id);assert.equal(game.packs.size,5);assert.equal(f.dirs.size,18);assert.equal(JSON.stringify(f.official),old);for(const row of plan.actors){assert.deepEqual(row.actor.ownership,row.ownership);assert.equal(row.actor.system.hp,55);}assert.deepEqual(game.permissions.OTHER,[1,4]);mutations.length=0;await applyPlan(game,constants,api,preflight(game,constants),[]);assert.deepEqual(mutations,[]);});
test('missing or duplicate actor blocks before writes',()=>{const f=fixture();const actor=[...f.game.actors.values()][0];f.game.actors.delete(actor.id);assert.throws(()=>preflight(f.game,f.constants),/Expected exactly one/);f.game.actors.set(actor.id,actor);f.game.actors.set('dupe',{...actor,id:'dupe'});assert.throws(()=>preflight(f.game,f.constants),/found 2/);assert.equal(f.mutations.length,0);});
test('wrong user role, system or core version blocks',()=>{const f=fixture();f.game.users.get('Austin').role=1;assert.throws(()=>preflight(f.game,f.constants),/Austin/);f.game.users.get('Austin').role=2;f.game.release.generation=13;assert.throws(()=>preflight(f.game,f.constants),/v14/);f.game.release.generation=14;f.game.user=f.game.users.get('Jason');assert.throws(()=>preflight(f.game,f.constants),/Gamemaster/);});
test('pack collisions block before writes',()=>{const f=fixture();f.game.packs.set('world.player-homebrew-items',{title:'Different',documentName:'Item'});assert.throws(()=>preflight(f.game,f.constants),/collision/);assert.equal(f.mutations.length,0);});
test('ambiguous folders block',async()=>{const f=fixture();for(let i=0;i<2;i++)await f.api.Folder.create({name:'Active Campaign',type:'Actor',folder:null});assert.throws(()=>preflight(f.game,f.constants),/Ambiguous/);});
test('permissions preserve unrelated roles and keys, disable and enable both player roles',()=>{const f=fixture();const p=desiredPermissions(f.game.permissions,f.constants);for(const k of ENABLE)assert.deepEqual(p[k],[1,2,3,4]);for(const k of DISABLE)assert.deepEqual(p[k],[3,4]);assert.deepEqual(p.OTHER,[1,4]);});
test('auto-file only root world character/item; skip explicit folders, embedded, compendium, NPC, GM',async()=>{const f=fixture();await applyPlan(f.game,f.constants,f.api,preflight(f.game,f.constants),[]);f.game.user=f.game.users.get('Austin');let result;const doc={documentName:'Actor',type:'character',updateSource(x){result=x;}};routeNew(f.game,doc,{}, {},f.game.user.id);assert.equal(result.folder,lookup(f.game,'Actor',['Player Workshop','Austin','Test Characters']).id);result=null;for(const [d,data,opt,uid] of [[doc,{folder:'other'},{},f.game.user.id],[{...doc,parent:{}},{},{},f.game.user.id],[{...doc,pack:'world.pack'},{},{},f.game.user.id],[{...doc,type:'npc'},{},{},f.game.user.id],[doc,{},{},'different']]){routeNew(f.game,d,data,opt,uid);assert.equal(result,null);}routeNew(f.game,{...doc,documentName:'Item'},{},{},f.game.user.id);assert.equal(result.folder,lookup(f.game,'Item',['Player Homebrew Drafts','Austin']).id);});
test('unsafe world path rejected',()=>assert.throws(()=>artPaths('../evil'),/Unexpected/));
+59
View File
@@ -0,0 +1,59 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {makeArchive} from '../scripts/portable.mjs';
import {openVault} from '../scripts/vault.mjs';
test('vault import requests stable embedded IDs and remaps the actor in embedded UUIDs', async t => {
const actorId = 'ABCDEFGHIJKLMNOP';
const itemId = '1234567890abcdef';
const newId = 'ZYXWVUTSRQPONMLK';
const user = {id: 'recipient', name: 'Recipient', role: 1};
const sourceActor = {
documentName: 'Actor',
uuid: `Actor.${actorId}`,
toObject: () => ({
_id: actorId,
name: 'Hero',
type: 'character',
items: [{_id: itemId, name: 'Spell', type: 'spell'}],
system: {details: {biography: {value: `@UUID[Actor.${actorId}.Item.${itemId}]{Spell}`}}}
})
};
const {blob} = await makeArchive({docs: [sourceActor], metadata: {system: 'dnd5e', systemVersion: '6.1.2'}});
const calls = [];
const DialogV2 = {
wait: async () => 'import',
confirm: async () => true,
prompt: async ({ok}) => ok.callback(null, null, {
element: {querySelector: () => ({files: [blob]})}
})
};
const create = async (data, options) => {
calls.push({data, options});
return {id: data._id, toObject: () => data};
};
const globals = {
CONST: {USER_ROLES: {GAMEMASTER: 4}},
CONFIG: {Actor: {documentClass: {create}}},
game: {user, system: {version: '6.1.2'}, folders: new Map(), actors: [], items: []},
foundry: {applications: {api: {DialogV2}}, utils: {randomID: () => newId}},
ui: {notifications: {info: () => {}, error: message => assert.fail(message)}}
};
for (const [key, value] of Object.entries(globals)) {
const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
Object.defineProperty(globalThis, key, {value, configurable: true});
t.after(() => {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else delete globalThis[key];
});
}
await openVault();
assert.equal(calls.length, 1);
const [{data, options}] = calls;
assert.deepEqual(options, {keepId: true, keepEmbeddedIds: true});
assert.deepEqual(data.ownership, {default: 0, [user.id]: 3});
assert.equal(data.items[0]._id, itemId);
assert.equal(data.system.details.biography.value, `@UUID[Actor.${newId}.Item.${itemId}]{Spell}`);
});
+12
View File
@@ -0,0 +1,12 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {zip,unzip,parseJSON} from '../scripts/archive.mjs';
import {own,snapshot,cleanImport,replaceRefs,makeArchive,readArchive} from '../scripts/portable.mjs';
const uid='user1', id='ABCDEFGHIJKLMNOP', iid='1234567890abcdef';
const actor={uuid:`Actor.${id}`,documentName:'Actor',toObject:()=>({_id:id,name:'Hero',type:'character',ownership:{default:0,[uid]:3},folder:'a',img:'worlds/demo/PlayerAssets/Me/Portraits/hero.webp',items:[{_id:iid,name:'Spell',type:'spell'}],system:{details:{note:`@UUID[Item.${iid}]{Custom}`}}})};
test('ownership only explicitly owned world documents',()=>{assert(own(actor,{id:uid}));assert(!own(actor,{id:'other'}));assert(!own({...actor,pack:'world.pack'},{id:uid}));assert(!own({...actor,parent:{}},{id:uid}));});
test('snapshot preserves embedded data, removes source ownership; import reassigns owner',()=>{const snap=snapshot(actor);assert.equal(snap.data.items[0]._id,iid);assert(!('ownership' in snap.data));assert(!('folder' in snap.data));const data=cleanImport(snap.data,'new-user','new-id');assert.deepEqual(data.ownership,{default:0,'new-user':3});assert.equal(data._id,'new-id');});
test('ZIP archive round trip with bundled art and separate JSON',async()=>{const {blob,warnings}=await makeArchive({docs:[actor],canBundle:()=>true,readAsset:async()=>new Uint8Array([1,2,3]).buffer,metadata:{system:'dnd5e',systemVersion:'6.1.2'}});assert.equal(warnings.length,0);const {manifest,files}=readArchive(await blob.arrayBuffer());assert.equal(manifest.records[0].uuid,actor.uuid);assert.equal(manifest.assets.length,1);assert.deepEqual([...files.get('art/0.webp')],[1,2,3]);assert.equal(parseJSON(files.get('documents/0-Actor.json')).name,'Hero');});
test('external art reported; source references remapped',async()=>{const {blob,warnings}=await makeArchive({docs:[actor],canBundle:()=>false,readAsset:async()=>{throw Error('should not read');},metadata:{system:'dnd5e'}});assert.equal(warnings.length,1);assert.equal(readArchive(await blob.arrayBuffer()).manifest.assets.length,0);assert.equal(replaceRefs(`@UUID[Item.${iid}]{Custom}`,new Map([[`Item.${iid}`,'Item.NEW']])), '@UUID[Item.NEW]{Custom}');});
test('bad paths, corrupted CRC and prototype keys rejected',async()=>{assert.throws(()=>zip(new Map([['../bad','bad']])),/Unsafe/);const b=new Uint8Array(await zip(new Map([['manifest.json','abc']])).arrayBuffer());b[30+'manifest.json'.length]^=1;assert.throws(()=>unzip(b),/CRC/);assert.throws(()=>parseJSON(new TextEncoder().encode('{"__proto__":{"x":1}}')),/Unsafe/);});
test('duplicate record or invalid archive format blocked',async()=>{const snap=snapshot(actor),m={format:'player-workshop-vault/1',system:'dnd5e',records:[snap,snap],assets:[]};const b=await zip(new Map([['manifest.json',JSON.stringify(m)]])).arrayBuffer();assert.throws(()=>readArchive(b),/duplicate/);});