다마고치 연구소 한국어판 소스 공개
Paramix Studio / build (push) Canceled after 0s
Paramix Studio / pages (push) Canceled after 0s

This commit is contained in:
syskiller committed 2026-11-10 21:17:44 +09:00
commit db23855630
661 files changed
+503597

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
// 1.7.3 ArduboyEmu: Arduboy games (.hex) into the menu; everything reads back; the program image in the flash has its
// settings block filled in; the game and its save share one 64 KB block.
// node test/ab_test.js <land.bin> <game.hex> [<game2.hex>]
const fs = require('fs'), S = __dirname + '/../';
const C = require(S + 'src/core.js'), E = require(S + 'src/emu.js'), F = require(S + 'src/feld.js');
const rd = (p) => new Uint8Array(fs.readFileSync(p));
const [land, game, game2] = process.argv.slice(2);
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const u32 = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0;
const fe = { feld: rd(S + 'feld/feld.bin'), stub: rd(S + 'feld/stub_feld_tpl.bin') };
const progs = { ab: rd(S + 'ab/ab.bin') };
const ctx = C.openRom(rd(land)); const base = C.buildRom(ctx, C.launcherChanges(ctx)).rom;
const R = E.abHex(fs.readFileSync(game, 'latin1'));
ok(!!R && R.length > 1000 && R.length <= 0x8000, 'game read from the .hex (' + (R ? R.length : 0) + ' bytes)');
ok(!E.abHex('hello') && !E.abHex(':1000000000'), 'other text refused');
const xs = [{ kind: 'ab', rom: R, title: E.abTitle(game.split('/').pop()), keys: E.AB_KEYS_DEFAULT.slice(), inv: true }];
if (game2) xs.push({ kind: 'ab', rom: E.abHex(fs.readFileSync(game2, 'latin1')), title: E.abTitle(game2.split('/').pop()), keys: [16, 32, 8, 4, 1, 2, 0, 0, 48], inv: false });
const r = E.appsPlace(base, xs, progs, { launch: true, dlApp: rd(S + 'flash/flashapp.bin') });
const m = F.feldApply(r.rom, { launch: true, apps: r.list, dl: r.dl }, [], fe, E);
const back = E.appsRead(m, F.feldApps(m, fe.stub).apps).filter((x) => x.kind === 'ab');
ok(back.length === xs.length, back.length + ' Arduboy games read back');
const b0 = back[0];
ok(!!b0 && Buffer.compare(Buffer.from(b0.rom), Buffer.from(R)) === 0, 'game the same after reading back');
const c = b0.off + 0x140, ro = u32(m, c + 8), so = u32(m, c + 16);
ok(u32(m, c) === E.AB_MAGIC && ro % 0x10000 === 0 && so === ro + 0x8000, 'settings block, game 64 KB aligned at ' + ro.toString(16) + ', save behind it');
ok(m.subarray(so, so + E.AB_SAVE).every((v) => v === 0xFF), 'fresh save empty');
ok(b0.title === xs[0].title, 'name ' + b0.title);
ok(JSON.stringify(b0.keys) === JSON.stringify(E.AB_KEYS_DEFAULT), 'keys ' + b0.keys.join(','));
if (game2) ok(JSON.stringify(back[1].keys) === '[16,32,8,4,1,2,0,0,48]' && !back[1].inv, 'second game: own keys, wheel not turned');
ok(Buffer.compare(Buffer.from(m.subarray(b0.off, b0.off + 0x140)), Buffer.from(progs.ab.subarray(0, 0x140))) === 0, 'program: ArduboyEmu');
// a save goes along when placed again
b0.save = new Uint8Array(E.AB_SAVE).fill(0xFF); b0.save.set([1, 2, 3, 4], 0x1000);
const again = E.appsPlace(E.appsClear(m, back), back, progs, { launch: true, dlApp: rd(S + 'flash/flashapp.bin') });
const back2 = E.appsRead(again.rom, again.list).filter((x) => x.kind === 'ab');
ok(back2.length === xs.length && back2[0].save[0x1000] === 1 && back2[0].save[0x1003] === 4, 'EEPROM kept when placed again');
console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
+66
View File
@@ -0,0 +1,66 @@
const fs=require('fs'), vm=require('vm'), assert=require('assert/strict'), crypto=require('crypto');
const {JSDOM,VirtualConsole}=require(process.env.JSDOM_PATH || 'jsdom');
const root=require('path').resolve(__dirname,'..');
const fixture=id=>{const b=Buffer.alloc(0x1000000);b.write('SONIXDEV');const off=id>=5?0xD29000:0xD49000,C=[0,0x70169E2C,0x70169E2C,0x70169E2C,0x849633DB,0x96CB83B8,0x96CB83B8];b.writeUInt32LE(id,off);const k=(C[id]-id)>>>0;b.writeUInt32LE(k,off+0xFF8);b.writeUInt32LE(~k>>>0,off+0xFFC);return b;};
const bytes=fixture(4), sha=crypto.createHash('sha256').update(bytes).digest('hex');
const item={edition:4,name:'제이드 포레스트',slug:'jade-forest',sha256:sha,size:bytes.length,label:'Test backup',createdAt:new Date().toISOString()};
async function clientTests(){
let calls=[], held=[], enabled=true;
let signedIn=false;
const context={window:{},location:{protocol:'https:'},crypto:crypto.webcrypto,Uint8Array,DataView,AbortSignal,fetch:async(path,opts)=>{calls.push(path);return {ok:true,json:async()=>path==='/api/member/me'?{authenticated:signedIn}:path==='/api/backup-status'?{enabled,held}:{status:'stored',name:'Jade',sha256:sha}};}};
vm.runInNewContext(fs.readFileSync(root+'/src/archive-client.js','utf8'),context);
const a=context.window.TamaArchive;
for(let id=1;id<=6;id++)assert.equal(a.edition(fixture(id)),id);
assert.equal(await a.verify(bytes,item),bytes);
await assert.rejects(()=>a.verify(bytes,{...item,sha256:'0'.repeat(64)}));
await assert.rejects(()=>a.verify(bytes,{...item,edition:3}));
assert.match(await a.backup(bytes,()=>{}),/완료/);assert.deepEqual(calls,['/api/backup-status','/api/backups','/api/member/me']);
calls=[];held=[4];await a.backup(bytes,()=>{});assert.deepEqual(calls,['/api/backup-status','/api/member/me']);
signedIn=true;calls=[];assert.match(await a.backup(bytes,()=>{}),/내 보관함 저장 완료/);assert.deepEqual(calls,['/api/backup-status','/api/member/me','/api/member/files']);signedIn=false;
calls=[];held=[];enabled=false;await a.backup(bytes,()=>{});assert.deepEqual(calls,['/api/backup-status','/api/member/me']);
context.fetch=async()=>{throw Error('offline')};assert.match(await a.backup(bytes,()=>{}),/실패.*PC 백업은 계속/);
context.location.protocol='file:';assert.match(await a.backup(bytes,()=>{}),/오프라인/);
}
async function restoreTests(){
const errors=[],vc=new VirtualConsole();vc.on('jsdomError',e=>errors.push(e.message));
const dom=new JSDOM(fs.readFileSync(root+'/dist/restore.html','utf8'),{url:'https://tama.itosm.co.kr/restore.html',runScripts:'dangerously',virtualConsole:vc,beforeParse(w){
w.TextEncoder=TextEncoder;w.TextDecoder=TextDecoder;w.AbortSignal=AbortSignal;Object.defineProperty(w.crypto,'subtle',{value:crypto.webcrypto.subtle});
w.navigator.serial={requestPort:async()=>({})};w.confirm=()=>true;
w.fetch=async(path)=>({ok:true,json:async()=>path==='/api/member/me'?{authenticated:true,items:[]}:{items:[item]},arrayBuffer:async()=>bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.byteLength)});
}});
const w=dom.window,d=w.document;
await new Promise(r=>setTimeout(r,30));
assert.equal(d.getElementById('catalog').options.length,1);
assert.equal(d.getElementById('restoreContent').hidden,false);
let writes=0,checkId=4;
w.ParamixFlash.serialOpen=async()=>({close:async()=>{}});
const dev={info:{capacity:0x1000000},read:async(off,len)=>new w.Uint8Array(fixture(checkId).subarray(off,off+len)),write:async(img,opts)=>{writes++;assert.deepEqual(Buffer.from(img),bytes);assert.equal(opts.keep,null);assert.equal(opts.rescueApp,undefined);return {written:10};}};
w.ParamixFlash.connect=async()=>({dev});
await d.getElementById('prepare').onclick();
assert.match(d.getElementById('fileStatus').textContent,/파일 확인을 마쳤습니다/);
await d.getElementById('connect').onclick();
assert.equal(d.getElementById('restore').disabled,true);
d.getElementById('ack').checked=true;d.getElementById('ack').onchange();assert.equal(d.getElementById('restore').disabled,false);
w.confirm=()=>false;await d.getElementById('restore').onclick();assert.equal(writes,0);
w.confirm=()=>true;checkId=3;await d.getElementById('restore').onclick();assert.equal(writes,0);assert.match(d.getElementById('status').textContent,/기종/);
checkId=4;await d.getElementById('restore').onclick();assert.equal(writes,1);assert.match(d.getElementById('status').textContent,/검증 완료/);
w.fetch=async()=>({ok:true,json:async()=>({authenticated:false})});
w.dispatchEvent(new w.Event('focus'));await new Promise(r=>setTimeout(r,30));
assert.equal(d.getElementById('restoreContent').hidden,true);assert.equal(d.getElementById('restoreLogin').hidden,false);
await d.getElementById('connect').onclick();await d.getElementById('restore').onclick();assert.equal(writes,1);
assert.deepEqual(errors,[]);w.close();
}
async function adminTests(){
const dom=new JSDOM(fs.readFileSync(root+'/admin.html','utf8'),{url:'https://tama.itosm.co.kr/admin.html',runScripts:'outside-only'});
const w=dom.window,d=w.document;let authenticated=false, calls=[];
const state={username:'syskiller',settings:{title:'Example',description:'Description',autoBackup:true,maxStorageMB:512},items:[{...item,protected:true,published:true,label:'<img src=x onerror=alert(1)>'}],usedMB:16};
w.fetch=async(url,opts={})=>{calls.push(url);let status=200,data={ok:true};if(url==='/api/admin/members')data={items:[],settings:{enabled:1,total_mb:5120}};if(url==='/api/admin/state'){status=authenticated?200:401;data=authenticated?state:{error:'login required'};}if(url==='/api/login')authenticated=true;if(url==='/api/admin/logout')authenticated=false;return{status,ok:status===200,json:async()=>data};};
w.confirm=()=>true;w.eval(fs.readFileSync(root+'/admin.js','utf8'));
const settle=()=>new Promise(r=>setTimeout(r,20));await settle();assert.equal(d.getElementById('dashboard').hidden,true);
d.getElementById('username').value='syskiller';d.getElementById('password').value='test-only';d.getElementById('loginForm').dispatchEvent(new w.Event('submit',{cancelable:true}));await settle();
assert.equal(d.getElementById('dashboard').hidden,false);assert.equal(d.getElementById('password').value,'');assert.equal(d.getElementById('records').querySelector('img'),null);assert.equal(d.querySelectorAll('.danger').length,0);
d.getElementById('settingsForm').dispatchEvent(new w.Event('submit',{cancelable:true}));await settle();assert.ok(calls.includes('/api/admin/settings'));
d.getElementById('logout').click();await settle();assert.equal(d.getElementById('dashboard').hidden,true);
w.close();
}
(async()=>{await clientTests();await restoreTests();await adminTests();console.log('PASS: classification, SHA rejection, missing-only upload, offline fallback, restore confirmation, wrong-device rejection, exact image write (mock device only), admin login/settings/logout and safe rendering');})().catch(e=>{console.error(e);process.exit(1);});
+133
View File
@@ -0,0 +1,133 @@
import importlib.util
import json
import struct
import tempfile
import threading
import unittest
import urllib.request
import urllib.error
from pathlib import Path
spec = importlib.util.spec_from_file_location('archive', Path(__file__).parents[1] / 'server/app.py')
app = importlib.util.module_from_spec(spec)
spec.loader.exec_module(app)
def fixture(edition, marker=0):
data = bytearray(app.SIZE)
data[:8] = b'SONIXDEV'
data[100] = marker
off = 0xD29000 if edition >= 5 else 0xD49000
struct.pack_into('<I', data, off, edition)
k = (app.CONSTANTS[edition] - edition) & 0xFFFFFFFF
struct.pack_into('<II', data, off + 0xFF8, k, ~k & 0xFFFFFFFF)
return bytes(data)
class ArchiveTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
app.DATA = Path(self.temp.name)
self.cfg = dict(app.DEFAULTS, username='test-admin', passwordHash=app.password_hash('test-only-password'))
app.atomic_json(app.DATA / 'config.json', self.cfg)
app.SESSIONS.clear()
app.ATTEMPTS.clear()
self.server = app.ThreadingHTTPServer(('127.0.0.1', 0), app.Handler)
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
self.base = 'http://127.0.0.1:' + str(self.server.server_port)
def tearDown(self):
self.server.shutdown()
self.server.server_close()
self.thread.join()
self.temp.cleanup()
def request(self, path, body=None, cookie=None, origin=True, binary=False):
headers = {}
if cookie:
headers['Cookie'] = cookie
if body is not None:
headers['Content-Type'] = 'application/octet-stream' if binary else 'application/json'
if origin:
headers['Origin'] = app.ORIGIN
if binary:
headers['X-Backup-Notice'] = 'shown'
else:
body = json.dumps(body).encode()
req = urllib.request.Request(self.base + path, data=body, headers=headers)
try:
response = urllib.request.urlopen(req, timeout=15)
except urllib.error.HTTPError as error:
response = error
content = response.read()
value = json.loads(content) if 'json' in response.headers.get('Content-Type', '') else content
return response.status, value, response.headers
def login(self):
status, _, headers = self.request('/api/login', {'username': 'test-admin', 'password': 'test-only-password'})
self.assertEqual(status, 200)
self.assertIn('HttpOnly; Secure; SameSite=Strict', headers['Set-Cookie'])
return headers['Set-Cookie'].split(';')[0]
def test_classification_and_first_per_edition(self):
for edition in range(1, 7):
data = fixture(edition)
self.assertEqual(app.detect(data), edition)
first = app.store_image(data)
self.assertEqual(first['status'], 'stored')
second = app.store_image(fixture(edition, 3))
self.assertEqual(second['status'], 'already-held')
self.assertEqual(len(app.records()), 6)
self.assertTrue(all(not r['published'] for r in app.records()))
with self.assertRaises(ValueError):
app.detect(bytes(app.SIZE))
def test_concurrent_upload_does_not_overwrite(self):
threads = [threading.Thread(target=app.store_image, args=(fixture(4, x),)) for x in range(3)]
for t in threads: t.start()
for t in threads: t.join()
self.assertEqual(len(app.records()), 1)
self.assertEqual(len(list(app.DATA.glob('*/*.bin'))), 1)
def test_private_approval_and_revoke(self):
status, result, _ = self.request('/api/backups', fixture(2), binary=True)
self.assertEqual(status, 200)
sha = result['sha256']
self.assertEqual(self.request('/api/file/' + sha)[0], 404)
self.assertEqual(self.request('/api/admin/file/' + sha)[0], 401)
self.assertEqual(self.request('/api/catalog')[1]['items'], [])
cookie = self.login()
self.assertEqual(self.request('/api/admin/file/' + sha, cookie=cookie)[1], fixture(2))
change = {'sha256': sha, 'label': 'Water verified file', 'published': True}
self.assertEqual(self.request('/api/admin/record', change, cookie=cookie)[0], 200)
self.assertEqual(self.request('/api/file/' + sha)[1], fixture(2))
change['published'] = False
self.request('/api/admin/record', change, cookie=cookie)
self.assertEqual(self.request('/api/file/' + sha)[0], 404)
def test_auth_csrf_settings_and_original_protection(self):
sha = app.store_image(fixture(4), protected=True, published=True)['sha256']
cookie = self.login()
self.assertEqual(self.request('/api/admin/settings', self.cfg)[0], 401)
self.assertEqual(self.request('/api/admin/settings', self.cfg, cookie=cookie, origin=False)[0], 403)
self.assertEqual(self.request('/api/admin/record', {'sha256': sha, 'action': 'delete'}, cookie=cookie)[0], 400)
values = dict(app.DEFAULTS, title='Changed title', autoBackup=False)
self.assertEqual(self.request('/api/admin/settings', values, cookie=cookie)[0], 200)
self.assertEqual(app.store_image(fixture(1))['status'], 'disabled')
self.assertEqual(self.request('/api/catalog')[1]['title'], 'Changed title')
self.assertEqual(self.request('/api/admin/password', {'currentPassword':'test-only-password', 'newPassword':'replacement-password'}, cookie=cookie)[0], 200)
self.assertEqual(self.request('/api/admin/state', cookie=cookie)[0], 401)
self.assertTrue(app.password_ok('replacement-password', app.config()['passwordHash']))
def test_bad_image_and_quota(self):
self.assertEqual(self.request('/api/backups', b'invalid', binary=True)[0], 400)
self.cfg['maxStorageMB'] = 16
app.atomic_json(app.DATA / 'config.json', self.cfg)
app.store_image(fixture(1))
self.assertEqual(self.request('/api/backups', fixture(2), binary=True)[0], 400)
self.assertEqual(len(app.records()), 1)
if __name__ == '__main__':
unittest.main(verbosity=2)
+41
View File
@@ -0,0 +1,41 @@
import hashlib
import json
import time
import unittest
from archive_test import ArchiveTests, app, fixture
class DeviceBackupTests(unittest.TestCase):
setUp=ArchiveTests.setUp
tearDown=ArchiveTests.tearDown
request=ArchiveTests.request
login=ArchiveTests.login
def test_server_default_owner_integrity_and_expiry(self):
policy=self.request('/api/backup-status')[1]
self.assertEqual(policy['mode'],'server')
self.assertTrue(all(v is False for v in self.request('/api/catalog')[1]['features'].values()))
code,data,headers=self.request('/api/device-backups',fixture(4),binary=True)
self.assertEqual(code,200,data)
cookie=headers['Set-Cookie'].split(';')[0]
self.assertEqual(data['sha256'],hashlib.sha256(fixture(4)).hexdigest())
self.assertEqual(self.request(data['fileUrl'])[0],404)
self.assertEqual(self.request(data['fileUrl'],cookie='tama_download='+'0'*64)[0],404)
self.assertEqual(self.request(data['fileUrl'],cookie=cookie)[1],fixture(4))
self.assertEqual(self.request('/api/device-backups',fixture(4),cookie=cookie,binary=True)[1]['id'],data['id'])
self.assertEqual(app.records(),[])
meta=app.DATA/'device-downloads'/(data['id']+'.json')
record=json.loads(meta.read_text());record['expires']=time.time()-1;meta.write_text(json.dumps(record))
self.assertEqual(self.request(data['fileUrl'],cookie=cookie)[0],404)
self.assertFalse(meta.with_suffix('.bin').exists())
def test_capacity_policy_and_admin_features(self):
self.cfg['deviceStorageMB']=16;app.atomic_json(app.DATA/'config.json',self.cfg)
self.assertEqual(self.request('/api/device-backups',fixture(4),binary=True)[0],200)
self.assertEqual(self.request('/api/device-backups',fixture(4,1),binary=True)[0],400)
body=dict(title='Test title',description='Test description',maxStorageMB=160,autoBackup=True,backupMode='local',deviceStorageMB=512,deviceRetentionHours=24,features={k:k=='gb' for k in app.FEATURES})
self.assertEqual(self.request('/api/admin/settings',body)[0],401)
self.assertEqual(self.request('/api/admin/settings',body,cookie=self.login())[0],200)
self.assertEqual(self.request('/api/backup-status')[1]['mode'],'local')
self.assertTrue(self.request('/api/catalog')[1]['features']['gb'])
self.assertFalse(self.request('/api/catalog')[1]['features']['emu'])
self.assertEqual(self.request('/api/device-backups',fixture(4),binary=True)[0],400)
+20
View File
@@ -0,0 +1,20 @@
// Check the DOOM build in the studio against the Python/C path (local only, needs your own DOOM.WAD; none of it goes into the repository).
// node test/doom_test.js <paradise.bin> <DOOM.WAD> [compare_mcu.wad] [output.bin]
const fs = require('fs');
const E = require('../src/emu.js'), D = require('../src/doom.js');
(async () => {
const rom = new Uint8Array(fs.readFileSync(process.argv[2])), wad = new Uint8Array(fs.readFileSync(process.argv[3]));
console.log('Episoden', D.wadEpisodes(wad));
let t0 = Date.now();
const sub = D.wadSub(wad, '1', true); console.log('Teil-WAD', sub.length, Date.now() - t0, 'ms');
if (process.env.SUBREF) { const r = fs.readFileSync(process.env.SUBREF); console.log('Teil-WAD gleich wie wadsub.py:', Buffer.compare(Buffer.from(sub), r) === 0); }
const ex = D.gbaExtras(sub);
if (process.env.EXREF) { const r = fs.readFileSync(process.env.EXREF); console.log('Zusatz gleich wie gbaextras.py:', Buffer.compare(Buffer.from(ex), r) === 0); }
const wasm = fs.readFileSync(__dirname + '/../doom/mcuwad.wasm');
t0 = Date.now(); const mcu = await D.convert(sub, ex, wasm); console.log('umgewandelt', mcu.length, Date.now() - t0, 'ms');
if (process.argv[4]) { const r = fs.readFileSync(process.argv[4]); console.log('MCU-WAD gleich wie mcuwad (C):', Buffer.compare(Buffer.from(mcu), r) === 0); }
const emb = { app: fs.readFileSync(__dirname + '/../doom/doom_app.bin'), xip: fs.readFileSync(__dirname + '/../doom/doom_xip.bin'), wasm, stub: fs.readFileSync(__dirname + '/../emu/stub_tpl.bin') };
const r = D.doomPatch(rom, mcu, emb, E);
console.log('ROM fertig, frei vor dem Bereich', r.free, 'Byte');
if (process.argv[5]) fs.writeFileSync(process.argv[5], r.rom);
})().catch(e => { console.error('FEHLER', e); process.exit(1); });
+25
View File
@@ -0,0 +1,25 @@
// 1.7.3 test11: edition from the ID page with its footer, Tropical/Glacier first (a Glacier was read as Land when its
// save data at 0xD49000 began with 1..6). node test/edition_test.js <rom.bin...> (the edition is the expected one by name)
const fs = require('fs'), C = require('../src/core.js'), F = require('../src/feld.js'), FL = require('../src/flash.js');
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
(async () => {
for (const f of process.argv.slice(2)) {
const b = new Uint8Array(fs.readFileSync(f)), want = C.openRom(b).editionId, nm = f.split('/').pop();
for (const g of [0, 1, 6]) {
const r = new Uint8Array(b); if (g && (want === 5 || want === 6)) { r.fill(0, 0xD49000, 0xD49004); r[0xD49000] = g; }
const p = Object.create(FL.Paradise.prototype), pay = new Uint8Array(44); pay[8] = 1;
p.link = { request: async () => ({ payload: pay }) }; p.read = async (o, n) => r.slice(o, o + n);
const i = await p.hello(), e = F.edition(r);
ok(C.openRom(r).editionId === want && e && e.id === want && i.edition === want, nm + (g ? ' with ' + g + ' at 0xD49000' : '') + ': ' + FL.EDITIONS[want]);
}
}
// 1.7.3 test13: a clean ROM keeps its ID page at 0xEFD000
for (const f of process.argv.slice(2)) {
const src = new Uint8Array(fs.readFileSync(f)), want = C.openRom(src).editionId, b = F.cleanBase(src), e = F.edition(b);
const p = Object.create(FL.Paradise.prototype), pay = new Uint8Array(44); pay[8] = 1;
p.link = { request: async () => ({ payload: pay }) }; p.read = async (o, n) => b.slice(o, o + n);
const i = await p.hello();
ok(e && e.id === want && e.at === 0xEFD000 && i.edition === want && b.subarray(0xD29000, 0xD4A000).every((v) => v === 0xFF), f.split('/').pop() + ' clean: ID page at 0xEFD000, ' + FL.EDITIONS[want]);
}
console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+54
View File
@@ -0,0 +1,54 @@
// More emulators (1.6.0): a second T7Emu (own ROM, own save) started from the menu.
// node test/emu_apps_test.js <land.bin> <tama-go.bin> <friends.bin> [out.bin]
const fs = require('fs');
const E = require('../src/emu.js'), F = require('../src/feld.js'), FL = require('../src/flash.js'), SV = require('../src/saves.js');
const [land, go, fr, outf] = process.argv.slice(2);
const L = new Uint8Array(fs.readFileSync(land)), G = new Uint8Array(fs.readFileSync(go)), R = new Uint8Array(fs.readFileSync(fr));
const app = new Uint8Array(fs.readFileSync(__dirname + '/../t7/t7.bin')), stub = new Uint8Array(fs.readFileSync(__dirname + '/../emu/stub_tpl.bin'));
const fe = { feld: new Uint8Array(fs.readFileSync(__dirname + '/../feld/feld.bin')), stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
function compose(base, primary, extras, old) {
let rom = F.feldStrip(base, { stub: fe.stub, oldStub: stub }, E);
if (primary) rom = E.t7Patch(rom, primary, [], app, stub, {});
if (old) rom = E.appsClear(rom, E.appsRead(old, F.feldApps(old, fe.stub).apps));
const r = E.appsPlace(rom, extras.map((x) => ({ rom: x })), app, {});
const name0 = F.emuType(r.rom) === 't7' ? E.t7XName(E.t7FromRom(r.rom).rom) : '';
return { rom: F.feldApply(r.rom, { fields: true, bag: true, apps: r.list, name0, appsLow: r.low }, old ? F.feldSlots(old, fe.stub) : [], fe, E), list: r.list };
}
(async () => {
const a = compose(L, R, [G]);
const fa = F.feldApps(a.rom, fe.stub);
ok(fa.name0 === 'FRIENDS' && fa.apps.length === 1 && fa.apps[0].name === 'TAMA-GO', 'menu lists ' + fa.name0 + ' and ' + fa.apps.map((x) => x.name).join(','));
const back = E.appsRead(a.rom, fa.apps);
ok(back.length === 1 && Buffer.from(back[0].rom).equals(Buffer.from(G)), 'second ROM read back');
const off = back[0].off, c = E.t7Cfg ? null : null;
ok(off >= 0x940000 && off + 0x20000 + 0xA0000 <= 0xD40000 && (off & 0xFFFF) === 0, 'placed at 0x' + off.toString(16));
ok(a.rom[off + 0x140] === 0x50 && a.rom.subarray(off + 0x10000, off + 0x16000).every((v) => v === 0xFF), 'program and empty save');
ok(Buffer.from(a.rom.subarray(0x940000, 0x940000 + R.length)).equals(Buffer.from(R)), 'Friends stays the program at 0x0A0000');
ok(a.rom.subarray(0xB0000 + 0x0C, 0xB0000 + 0x10).every((v, i) => v === [0x72, 0xB6, 0x04, 0x46][i]), 'stub entry at +0x0C');
// again from the ROM: same bytes
const b = compose(a.rom, R, [G], a.rom);
ok(Buffer.from(b.rom).equals(Buffer.from(a.rom)), 'built again from the ROM: identical');
// remove the second one
const c2 = compose(a.rom, R, [], a.rom);
ok(F.feldApps(c2.rom, fe.stub).apps.length === 0 && c2.rom.subarray(off, off + 0xC0000).every((v) => v === 0xFF), 'removed: blocks free');
// keep saves: the second T7Emu's save stays
const device = new Uint8Array(a.rom); device.fill(0x5A, off + 0x10000, off + 0x16000);
const changed = new Set(); for (let s = 0; s < 0x1000000; s += 0x1000) if (!Buffer.from(device.subarray(s, s + 0x1000)).equals(Buffer.from(a.rom.subarray(s, s + 0x1000)))) changed.add(s);
const dev = { info: { edition: F.edition(a.rom).id }, read: async (x, n) => device.slice(x, x + n) };
const plan = await FL.keepPlan(F, E, { stub: fe.stub }, {})(dev, a.rom, changed);
ok(plan.image.subarray(off + 0x10000, off + 0x16000).every((v) => v === 0x5A), 'keep saves: save of the second emulator kept');
// save.bin of the second one: in, out, and kept over "keep saves" when imported
const sv = new Uint8Array(4098); sv[0] = 0xFF; sv[1] = 0xFF; for (let i = 2; i < 4098; i++) sv[i] = i & 255;
const withSv = SV.t7SaveIn(a.rom, sv, off + 0x10000), back2 = SV.t7SaveOut(withSv, off + 0x10000);
ok(back2 && Buffer.from(back2).equals(Buffer.from(sv)) && !SV.t7SaveOut(withSv), 'save.bin into the second one and out again (main one untouched)');
const dev2 = new Uint8Array(a.rom); dev2.fill(0x5A, off + 0x10000, off + 0x16000);
const ch2 = new Set(); for (let s = 0; s < 0x1000000; s += 0x1000) if (!Buffer.from(dev2.subarray(s, s + 0x1000)).equals(Buffer.from(withSv.subarray(s, s + 0x1000)))) ch2.add(s);
const p2 = await FL.keepPlan(F, E, { stub: fe.stub }, { t7SaveX: 0 })({ info: dev.info, read: async (x, n) => dev2.slice(x, x + n) }, withSv, ch2);
ok(Buffer.from(SV.t7SaveOut(p2.image, off + 0x10000)).equals(Buffer.from(sv)) && p2.image.subarray(off + 0x15000, off + 0x16000).every((v) => v === 0x5A), 'keep saves with an imported save: the new pet, the device settings');
// two more (Tama-Go twice is fine for the layout)
let room = true; try { compose(L, R, [G, R, G]); } catch (e) { room = false; console.log(' ', e.message); }
ok(room, 'three more fit next to Friends');
if (outf) fs.writeFileSync(outf, a.rom);
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+35
View File
@@ -0,0 +1,35 @@
// Autostart switch of the emulator in the stub (emulator alone and with the menu).
// node test/emu_auto_test.js <paradise.bin> <color_tama_firmware.bin> [old_menu_stub_tpl.bin]
const fs = require('fs');
const C = require('../src/core.js'); globalThis.ParamixCore = C;
const E = require('../src/emu.js'), F = require('../src/feld.js');
const rd = (p) => new Uint8Array(fs.readFileSync(p));
const land = rd(process.argv[2]), guest = rd(process.argv[3]);
const app = rd(__dirname + '/../emu/emu.bin'), es = rd(__dirname + '/../emu/stub_tpl.bin');
const emb = { feld: rd(__dirname + '/../feld/feld.bin'), stub: rd(__dirname + '/../feld/stub_feld_tpl.bin'), oldStub: es };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'WRONG ') + m); if (!c) bad++; };
const list = (rom) => { const l = [[0xB0000, es], [0xB0000, emb.stub]]; const f = F.feldFind(rom, emb.stub); if (f && f.stubOff !== 0xB0000) l.push([f.stubOff, emb.stub]); return l; };
const diff = (a, b) => { let n = 0; for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) n++; return n; };
// emulator alone
const r = E.emuPatch(land, guest, app, es).rom;
ok(E.autoGet(r, list(r)) === false, 'emulator: autostart off after install');
const r1 = E.autoSet(r, list(r), true);
ok(r1 && E.autoGet(r1, list(r1)) === true && diff(r, r1) === 1, 'emulator: switched on, one byte differs');
ok(E.autoGet(E.autoSet(r1, list(r1), false), list(r1)) === false, 'emulator: switched off again');
ok(E.installedOrigs(r1, E.sceneTable(r1)).every((v, k) => v === E.installedOrigs(r, E.sceneTable(r))[k]), 'original handlers unchanged');
// with the menu
const m = F.feldApply(r, { fields: true, bag: false }, [], emb, E);
ok(E.autoGet(m, list(m)) === false, 'menu: autostart off');
const m1 = E.autoSet(m, list(m), true);
ok(m1 && E.autoGet(m1, list(m1)) === true && F.feldFind(m1, emb.stub), 'menu: switched on, menu still found');
const s = F.feldStrip(m1, emb, E);
ok(!F.feldFind(s, emb.stub) && F.appKind(s) === 2 && E.autoGet(s, list(s)) === false, 'menu removed: emulator stub back, autostart off (the Studio sets it again)');
// menu built by an older Studio (menu address at 0xF0 in the stub)
if (process.argv[4]) {
const old = { feld: emb.feld, stub: rd(process.argv[4]), oldStub: es };
const o = F.feldApply(r, { fields: true, bag: false }, [], old, E);
const f = F.feldFind(o, emb.stub);
ok(f && f.off === F.feldFind(o, old.stub).off, 'older menu still recognised with the new template');
ok(E.autoGet(o, list(o)) === null, 'older stub: no switch (null)');
}
console.log(bad ? bad + ' WRONG' : 'all good'); process.exit(bad ? 1 : 0);
+55
View File
@@ -0,0 +1,55 @@
// Big guest firmware (P's, 4U+): stored from 0x840000, menu fields refused, upgrade, swap and removal clean up.
// node test/emu_big_test.js <land.bin> <ps_or_4u_firmware.bin> <idl_firmware.bin>
const fs = require('fs');
const E = require('../src/emu.js'), F = require('../src/feld.js'), SV = require('../src/saves.js');
const [land, big, idl] = process.argv.slice(2).map((f) => new Uint8Array(fs.readFileSync(f)));
const app = new Uint8Array(fs.readFileSync(__dirname + '/../emu/emu.bin')), stub = new Uint8Array(fs.readFileSync(__dirname + '/../emu/stub_tpl.bin'));
const feldEmb = { feld: new Uint8Array(fs.readFileSync(__dirname + '/../feld/feld.bin')), stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
const u32 = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0;
const ff = (b, a, e) => b.subarray(a, e).every((v) => v === 0xFF);
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const dev = E.emuDetect(big);
ok(['ps', '4u', '4u-plain'].includes(dev), 'detected ' + dev);
const r = E.emuPatch(land, big, app, stub);
ok(r.big && u32(r.rom, 0xA0148) === 0x840000 && u32(r.rom, 0xA0140 + 152) === 0xD48000, 'big layout 0x840000..0xD48000');
ok(u32(r.rom, 0xA0154) === E.DEVICES[dev].kind, 'device kind ' + E.DEVICES[dev].kind);
ok(ff(r.rom, 0xD48000, 0xD49000) && r.rom.subarray(0xD49000, 0xD4A000).every((v, i) => v === land[0xD49000 + i]), 'ID page untouched');
ok(r.rom.subarray(0xD49000).every((v, i) => v === land[0xD49000 + i]), 'save area of the Paradise unchanged');
// guest back out equals the firmware
(async () => {
const cfg = SV.emuCfg(r.rom.subarray(0xA0000, 0xA1000));
const g = await SV.emuGuestAsync((a, n) => r.rom.subarray(a, a + n), cfg);
ok(Buffer.from(g).equals(Buffer.from(big.subarray(0, 0x800000))) && cfg.app === SV.KINDS[E.DEVICES[dev].kind].app, '.sav out equals the firmware (' + cfg.app + ')');
// newer program keeps the layout
const app2 = new Uint8Array(app); app2[app2.length - 1] ^= 1;
const up = E.emuUpgrade(r.rom, app2);
ok(up && u32(up, 0xA0148) === 0x840000 && up.subarray(0x840000, 0xD48000).every((v, i) => v === r.rom[0x840000 + i]), 'upgrade keeps the big layout');
// menu with fields refused, menu with the bag only works
let msg = ''; try { F.feldApply(r.rom, { fields: true, bag: false }, [], feldEmb, E); } catch (e) { msg = e.message; }
ok(/no room for the field saves next to this emulator firmware/.test(msg), 'menu fields refused: ' + msg);
let bagOk = true; try { F.feldApply(r.rom, { fields: false, bag: true }, [], feldEmb, E); } catch (e) { bagOk = false; console.log(e.message); }
ok(bagOk, 'menu with items only works');
// swap to the iD L: big area cleared, normal layout
const s = E.emuPatch(r.rom, idl, app, stub);
ok(!s.big && u32(s.rom, 0xA0148) === 0x940000 && ff(s.rom, 0x840000, 0x940000) && ff(s.rom, 0x940000 + s.blocks * 0x10000, 0xD48000), 'swap to iD L clears the big area');
const back = E.emuPatch(s.rom, big, app, stub);
ok(back.rom.every((v, i) => v === r.rom[i] || (i >= 0xA0000 && i < 0xC0000)), 'swap back gives the same layout');
const rm = E.emuRemove(r.rom);
ok(ff(rm, 0x830000, 0xD48000) && ff(rm, 0xA0000, 0xB0000), 'removal clears everything');
// 1.7.4 BIG_LZ: a save that ran for a long time (92 blocks) only fits packed: accepted, read back the same
{ const g = new Uint8Array(0x800000).fill(0xFF); g.set(big.subarray(0, 0x800000));
let used = 0; for (let b = 0; b < 128; b++) if (!ff(g, b << 16, (b + 1) << 16)) used++;
let x = 12345; for (let b = 0x56; b < 128 && used < 92; b++) if (ff(g, b << 16, (b + 1) << 16)) { for (let i = 0; i < 0x10000; i++) { x = (Math.imul(x, 1103515245) + 12345) >>> 0; g[(b << 16) + i] = x >>> 24; } used++; }
let pr = null; try { pr = E.emuPatch(land, g, app, stub); } catch (e) { console.log(e.message); }
let same = false; if (pr) { const cfg = SV.emuCfg(pr.rom.subarray(0xA0000, 0xA1000)); const b3 = await SV.emuGuestAsync((a, n) => pr.rom.subarray(a, a + n), cfg); same = b3.every((v, i) => v === g[i]); }
ok(same, 'long-running save with ' + used + ' blocks: packed, read back the same'); }
// 1.6.6: a save of another emulator with download content holds more blocks than fit: the sparsest go into spare pages
{ const g = new Uint8Array(0x800000).fill(0xFF); g.set(big.subarray(0, 0x800000));
let added = 0; for (let b = 1; b < 128 && added < 4; b++) if (ff(g, b << 16, (b + 1) << 16)) { g.fill(0x5A, b << 16, (b << 16) + 0x3000); added++; }
const pk = E.packGuest(g, dev);
const pr = E.emuPatch(land, g, app, stub);
const cfg = SV.emuCfg(pr.rom.subarray(0xA0000, 0xA1000));
const back2 = await SV.emuGuestAsync((a, n) => pr.rom.subarray(a, a + n), cfg);
ok(pk.pages.length > 0 && back2.every((v, i) => v === g[i]), 'save with more blocks than fit: ' + pk.blocks + ' blocks and ' + pk.pages.length + ' spare pages, read back the same'); }
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+46
View File
@@ -0,0 +1,46 @@
// TamaEmu update keeps the save: old emulator ROM on the "device" with a played save,
// new program from the Studio, write with "Keep saves".
// node test/emu_keep_test.js <paradise.bin> <color_tama_firmware.bin>
const fs = require('fs');
const C = require('../src/core.js'); globalThis.ParamixCore = C;
const E = require('../src/emu.js'), F = require('../src/feld.js'), FL = require('../src/flash.js');
const rom0 = new Uint8Array(fs.readFileSync(process.argv[2])), guest = new Uint8Array(fs.readFileSync(process.argv[3]));
const app = new Uint8Array(fs.readFileSync(__dirname + '/../emu/emu.bin'));
const stub = new Uint8Array(fs.readFileSync(__dirname + '/../emu/stub_tpl.bin'));
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'WRONG ') + m); if (!c) bad++; };
const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0;
// old program: same settings block, other code
const old = new Uint8Array(app); old[0x40] ^= 0xFF; old[0x2000] ^= 0x55;
const built = E.emuPatch(rom0, guest, old, stub).rom;
// the device played: guest save sectors, a spare page, a session
const dev = new Uint8Array(built);
const gOff = u32(built, 0xA0148), gLen = u32(built, 0xA014C);
dev.fill(0x11, gOff + 0x3000, gOff + 0x4000);
const spare = (gOff + gLen + 0x1FFF) & ~0x1FFF; dev.fill(0x22, spare, spare + 0x1000); dev.fill(0x23, spare + 0x4000, spare + 0x5000);
dev.fill(0x33, 0xC0000, 0xC2000);
// Studio: open the old ROM file and save
const up = E.emuUpgrade(built, app);
ok(!!up, 'new program recognised');
ok(E.emuUpgrade(up, app) === null, 'second time: nothing to do');
ok(up.subarray(0xA0148, 0xA0140 + 152).every((v, i) => v === built[0xA0148 + i]), 'firmware layout taken over');
ok(u32(up, 0xA0144) >= 4 && u32(up, 0xA0140 + 152) === 0xD40000 && u32(up, 0xA0140 + 156) === 2, 'settings version 4 or 5, spare end, clock from the Paradise');
ok(up.subarray(0xA0000, 0xA0140).every((v, i) => v === app[i]), 'program is the new one');
ok(up.subarray(gOff, 0xD40000).every((v, i) => v === built[gOff + i]), 'packed firmware untouched');
// keep plan against the device
const SEC = 0x1000, changed = new Set();
for (let s = 0; s < up.length; s += SEC) { for (let i = s; i < s + SEC; i++) if (up[i] !== dev[i]) { changed.add(s); break; } }
const ed = F.edition(up);
const plan = FL.keepPlan(F, E, null, {});
plan({ info: { edition: ed && ed.id, name: 'x' }, read: async (a, n) => dev.slice(a, a + n) }, up, changed).then((r) => {
const img = r.image;
ok(img.subarray(gOff + 0x3000, gOff + 0x4000).every((v) => v === 0x11), 'guest save kept');
ok(img.subarray(spare, spare + 0x1000).every((v) => v === 0x22) && img.subarray(spare + 0x4000, spare + 0x5000).every((v) => v === 0x23), 'spare pages kept');
ok(img.subarray(0xC0000, 0xC2000).every((v) => v === 0x33), 'session kept');
ok(img.subarray(0xA0000, 0xA0140).every((v, i) => v === app[i]), 'new program written');
ok(!r.notes.length, 'no notes: ' + JSON.stringify(r.notes));
// firmware chosen again in the Studio: starts fresh (as before)
return FL.keepPlan(F, E, null, { emuChanged: true })({ info: { edition: ed && ed.id, name: 'x' }, read: async (a, n) => dev.slice(a, a + n) }, up, new Set(changed));
}).then((r) => {
ok(r.notes.length === 1, 'new firmware: note, fresh start');
console.log(bad ? bad + ' WRONG' : 'all good'); process.exit(bad ? 1 : 0);
});
+32
View File
@@ -0,0 +1,32 @@
// 1.6.8: a T7Emu or V1Emu that changes its place (main program <-> menu) takes its save along when writing.
// node test/emu_movesave_test.js <land.bin> <tama-go.bin> <p2.bin>
const fs = require('fs'), S = __dirname + '/../';
const C = require(S + 'src/core.js'), E = require(S + 'src/emu.js'), F = require(S + 'src/feld.js'), FL = require(S + 'src/flash.js');
const rd = (p) => new Uint8Array(fs.readFileSync(p));
const [land, go, p2] = process.argv.slice(2);
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const progs = { t7: rd(S + 't7/t7.bin'), tama: rd(S + 'emu/emu.bin'), t18: rd(S + 't18/t18.bin'), v1: rd(S + 'v1/v1.bin') }; progs.t18.xip = rd(S + 't18/t18x.bin');
const stub = rd(S + 'emu/stub_tpl.bin'), fe = { feld: rd(S + 'feld/feld.bin'), stub: rd(S + 'feld/stub_feld_tpl.bin') };
const ctx = C.openRom(rd(land)); const base = C.buildRom(ctx, C.launcherChanges(ctx)).rom;
const G = rd(go), P = rd(p2);
function build(main, xs) {
let rom = main === 'go' ? E.t7Patch(base, G, [], progs.t7, stub, {}) : E.v1Patch(base, P, progs.v1, stub, {});
const r = E.appsPlace(rom, xs, progs, { launch: true, dlApp: rd(S + 'flash/flashapp.bin') });
return F.feldApply(r.rom, { launch: true, apps: r.list, dl: r.dl }, [], fe, E);
}
(async () => {
const a = build('go', [{ kind: 'v1', rom: P }]);
const xa = E.appsRead(a, F.feldApps(a, fe.stub).apps)[0];
const device = new Uint8Array(a);
device.fill(0x11, 0xC0000, 0xC6000); // Tama-Go as the main program: its save
device.fill(0x22, xa.saveOff, xa.saveOff + 0x2000); // P2 in the menu: its session and settings
const b = build('p2', [{ rom: G }]);
const xb = E.appsRead(b, F.feldApps(b, fe.stub).apps)[0];
const changed = new Set(); for (let s = 0; s < 0x1000000; s += 0x1000) if (!Buffer.from(device.subarray(s, s + 0x1000)).equals(Buffer.from(b.subarray(s, s + 0x1000)))) changed.add(s);
const dev = { info: { edition: F.edition(b).id }, read: async (x, n) => device.slice(x, x + n), crc: async (x, n) => FL.crc32(device, x, n) };
const plan = await FL.keepPlan(F, E, { stub: fe.stub }, {})(dev, b, changed);
ok(plan.image.subarray(0xC0000, 0xC2000).every((v) => v === 0x22), 'P2 now the main program: its save at 0x0C0000');
ok(plan.image.subarray(xb.saveOff, xb.saveOff + 0x6000).every((v) => v === 0x11), 'Tama-Go now in the menu: its save at 0x' + xb.saveOff.toString(16));
ok(plan.notes.filter((n) => n.code === 'noteSaveMoved').length === 2, 'notes: ' + plan.notes.map((n) => n.code).join(','));
console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+95
View File
@@ -0,0 +1,95 @@
// T18Emu in the ROM: block placement, settings block, upgrade, swap with T7Emu, removal, keeping the save on the device.
// node test/emu_t18_test.js <land.bin> <tg18_firmware.bin> <v7_rom.bin>
const fs = require('fs');
const E = require('../src/emu.js'), F = require('../src/feld.js'), FL = require('../src/flash.js');
const [land, tg18, v7] = process.argv.slice(2);
const L = new Uint8Array(fs.readFileSync(land)), G = new Uint8Array(fs.readFileSync(tg18)), R = new Uint8Array(fs.readFileSync(v7));
const app = new Uint8Array(fs.readFileSync(__dirname + '/../t18/t18.bin')); app.xip = new Uint8Array(fs.readFileSync(__dirname + '/../t18/t18x.bin'));
const t7app = new Uint8Array(fs.readFileSync(__dirname + '/../t7/t7.bin'));
const stub = new Uint8Array(fs.readFileSync(__dirname + '/../emu/stub_tpl.bin'));
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const ff = (b, a, e) => b.subarray(a, e).every((v) => v === 0xFF);
(async () => {
ok(E.t18Detect(G) && !E.t18Detect(R) && !E.t7Detect(G), 'detection');
const r = E.t18Patch(L, G, app, stub, { lang: 'en' }), a = r.rom, c = E.t18Cfg(a);
ok(F.appKind(a) === 2 && F.emuType(a) === 't18', 'kind: emulator, type t18');
let used = 0, placed = true;
for (let i = 0; i < 128; i++) {
const empty = ff(G, i << 16, (i + 1) << 16);
if (empty) { if (c.map[i] !== 0xFFFF) placed = false; continue; }
used++;
const b = c.map[i];
if (b === 0xFFFF || !Buffer.from(a.subarray(b << 16, (b + 1) << 16)).equals(Buffer.from(G.subarray(i << 16, (i + 1) << 16)))) placed = false;
if (b < 0x83 || (b >= 0xD4 && b < 0xF0)) placed = false;
}
ok(placed && used === r.blocks, 'firmware blocks in place (' + r.blocks + '), empty ones left out');
const u32 = (o) => (a[o] | a[o + 1] << 8 | a[o + 2] << 16 | a[o + 3] << 24) >>> 0;
ok(c.spare.length === r.spares && r.spares >= 6 && r.spares <= 10 && c.spare.every((b) => ff(a, b << 16, (b + 1) << 16) && !c.map.includes(b)), 'spares empty and apart (' + r.spares + ')');
const all = c.map.filter((b) => b !== 0xFFFF).concat(c.spare), low = Math.min(...all);
// hot window (1.6.6)
ok(r.hot && (c.flags & 4) && app.xip.every((v, i) => a[0xFDF000 + i] === v) && app.xip.every((v, i) => a[0xF0000 + i] === v), 'hot window: flag, flash part twice (0x0F0000 and 0xFDF000)');
ok([0x12, 0x14, 0x15, 0x13, 0x1A, 0x00].every((g) => c.map[g] >= 0xF0 && c.map[g] !== 0xFD && c.map[g] !== 0xFE) && !all.includes(0xFD) && !all.includes(0xFE), 'hot window: code blocks in 0xF00000..0xFFFFFF, 0xFD/0xFE kept for the flash part');
ok(!!(c.flags & 16) && [0x3F, 0x4A, 0x32, 0x18, 0x40].every((g) => c.map[g] >= 0xF0), 'hot window v2: picture blocks of the pet in the window');
{ const o = new Uint8Array(a); o[0xA0000 + 0x140 + 400] &= ~16; const up = E.t18Upgrade(o, app, stub), cu = up && E.t18Cfg(up);
ok(!!up && (cu.flags & 20) === 20 && cu.map.every((b, g) => b === 0xFFFF || up.subarray(b << 16, (b + 1) << 16).every((v, k) => v === G[(g << 16) + k])), 'upgrade: hot window of the first list gets the new one, firmware the same'); }
{ const r0 = E.t18Patch(L, G, app, stub, { lang: 'en', hotWindow: false }), c0 = E.t18Cfg(r0.rom);
ok(!r0.hot && !(c0.flags & 4) && ff(r0.rom, 0xFD0000, 0xFF0000) === false || !r0.hot, 'without hot window: old layout');
const up = E.t18Upgrade(r0.rom, app, stub), cu = up && E.t18Cfg(up);
ok(!!up && (cu.flags & 4) && (cu.flags & 1) && cu.map.every((b, g) => b === 0xFFFF ? c0.map[g] === 0xFFFF : up.subarray(b << 16, (b + 1) << 16).every((v, k) => v === G[(g << 16) + k])), 'upgrade moves an old layout to the hot window, firmware the same');
ok(E.t18Upgrade(up, app, stub) === null, 'upgrade again: nothing to do');
// the blocks the firmware wrote (map in the save area) come along
const w = new Uint8Array(r0.rom), sp = c0.spare[0], g5 = 0x7F;
w.fill(0x5A, sp << 16, (sp + 1) << 16);
const m = c0.map.slice(); m[g5] = sp;
w.fill(0xFF, 0xC0000, 0xC1000); w[0xC0000] = 0x54; w[0xC0001] = 0x38; w[0xC0002] = 0x4D; w[0xC0003] = 0x50;
m.forEach((b, i) => { w[0xC0004 + 2 * i] = b & 255; w[0xC0005 + 2 * i] = b >> 8; });
const up2 = E.t18Upgrade(w, app, stub), c2 = E.t18Cfg(up2);
ok(up2.subarray(c2.map[g5] << 16, (c2.map[g5] + 1) << 16).every((v) => v === 0x5A), 'upgrade keeps the blocks the firmware wrote');
}
ok(all.filter((b) => b >= 0xF0).length === (r.hot ? 14 : 16) && E.t18Low(a) === low << 16 && ff(a, 0x830000, low << 16) && low >= 0x87, 'from the top down, the bottom stays free (lowest block 0x' + (low << 16).toString(16) + ')');
ok(a.subarray(0xF0000, 0xF0000 + app.xip.length).every((v, i) => v === app.xip[i]) && (u32(0xA0140 + 400) & 2) === 2, 'flash part at 0x0F0000, clock switch on');
{ const noX = new Uint8Array(app); let err = ''; try { E.t18Patch(L, G, noX, stub, {}); } catch (e) { err = e.message; } ok(/flash part/.test(err), 'program without flash part refused'); }
const ad = E.t18Addrs(G), ci = 0xA0140;
ok((c.flags & 1) === 1 && u32(ci + 404) === ad.idle && u32(ci + 408) === ad.soft && u32(ci + 412) === ad.dma && ad.idle && ad.soft && ad.dma, 'settings block (language, addresses)');
ok(a.subarray(0xD49000, 0xF00000).every((v, i) => v === L[0xD49000 + i]), 'Paradise save untouched');
{ // the menu with the field switch next to T18Emu: the saves below its lowest block
const fe = { feld: new Uint8Array(fs.readFileSync(__dirname + '/../feld/feld.bin')), stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let m = null, err = ''; try { m = F.feldApply(a, { fields: true, bag: false }, [], fe, E); } catch (e) { err = e.message; }
const f = m && F.feldFind(m, fe.stub);
ok(!!f && f.nslots === 3 && f.slotOff + f.nslots * f.slotSize <= E.t18Low(a) && f.slotSize >= 0x10000 && E.t18Cfg(m).map.every((x, i) => x === c.map[i]), 'field switch next to T18Emu (' + (f ? (f.slotSize >> 10) + ' KB per field' : err) + ')');
}
ok(ff(a, 0xC0000, 0xF0000), 'save area empty');
// the same firmware again keeps the save area
const withSave = new Uint8Array(a); withSave.fill(0x5A, 0xC0000, 0xC3000);
const b = E.t18Patch(withSave, G, app, stub, {}).rom;
ok(b.subarray(0xC0000, 0xC3000).every((v) => v === 0x5A) && E.t18Cfg(b).map.every((x, i) => x === c.map[i]), 'same firmware: same blocks, save kept');
const G2 = new Uint8Array(G); G2[0x100] ^= 1;
ok(ff(E.t18Patch(withSave, G2, app, stub, {}).rom, 0xC0000, 0xF0000), 'other firmware: save dropped');
// upgrade
const app2 = new Uint8Array(app); app2[app2.length - 1] ^= 1; app2.xip = new Uint8Array(app.xip); app2.xip[app2.xip.length - 1] ^= 1;
const u = E.t18Upgrade(a, app2);
ok(u && E.t18Cfg(u).map.every((x, i) => x === c.map[i]) && u[0xA0000 + app2.length - 1] === app2[app2.length - 1] && u[0xF0000 + app2.xip.length - 1] === app2.xip[app2.xip.length - 1], 'newer program (both parts) keeps the settings');
ok(E.t18Upgrade(a, app) === null, 'same program: nothing to do');
ok(E.t18ClockGet(a) === true && E.t18ClockGet(E.t18ClockSet(a, false)) === false, 'clock switch');
// swap to T7Emu and back, removal
const s = E.t7Patch(a, R, [], t7app, stub, {});
ok(F.emuType(s) === 't7', 'swap to T7Emu');
const s2 = E.t18Patch(s, G, app, stub, {}).rom;
ok(F.emuType(s2) === 't18' && ff(s2, 0xC0000, 0xF0000), 'back to T18Emu');
ok(F.emuType(s) === 't7' && ff(s, 0xF0000, 0x100000), 'swap to T7Emu clears the flash part');
const rm = E.emuRemove(a);
ok(F.appKind(rm) === 0 && c.map.concat(c.spare).every((x) => x === 0xFFFF || ff(rm, x << 16, (x + 1) << 16)) && ff(rm, 0xC0000, 0x110000), 'removal frees every block');
// device write with "keep saves": the device's save and written spares stay, firmware blocks come from the image
const dev = new Uint8Array(a); dev.fill(0x33, 0xC0000, 0xC2000); const sp = c.spare[0]; dev.fill(0x44, sp << 16, (sp << 16) + 0x1000);
const blk0 = c.map.find((x) => x !== 0xFFFF);
const img = new Uint8Array(a);
const changed = new Set(); for (let s3 = 0; s3 < 0x1000000; s3 += 0x1000) if (!Buffer.from(dev.subarray(s3, s3 + 0x1000)).equals(Buffer.from(img.subarray(s3, s3 + 0x1000)))) changed.add(s3);
const fake = { info: { edition: F.edition(img) && F.edition(img).id }, read: async (o, n) => dev.slice(o, o + n) };
if (F.edition(img)) {
const plan = await FL.keepPlan(F, E, null, {})(fake, img, changed);
ok(plan.image.subarray(0xC0000, 0xC2000).every((v) => v === 0x33) && plan.image.subarray(sp << 16, (sp << 16) + 0x1000).every((v) => v === 0x44), 'keep saves: save area and written spare from the device');
ok(Buffer.from(plan.image.subarray(blk0 << 16, (blk0 + 1) << 16)).equals(Buffer.from(img.subarray(blk0 << 16, (blk0 + 1) << 16))), 'keep saves: firmware block from the image');
}
console.log(bad ? bad + ' FAILED' : 'all good');
process.exit(bad ? 1 : 0);
})();
+62
View File
@@ -0,0 +1,62 @@
// T7Emu in the ROM: layout, figures, upgrade, swap with TamaEmu, removal, keeping the pet's save on the device.
// node test/emu_t7_test.js <land.bin> <v7_rom.bin> <idl_firmware.bin> <figure.bin...>
const fs = require('fs');
const E = require('../src/emu.js'), F = require('../src/feld.js'), FL = require('../src/flash.js');
const [land, v7, idl, ...figf] = process.argv.slice(2);
const L = new Uint8Array(fs.readFileSync(land)), R = new Uint8Array(fs.readFileSync(v7)), I = new Uint8Array(fs.readFileSync(idl));
const figs = figf.map((f) => ({ name: f, data: new Uint8Array(fs.readFileSync(f)) }));
const app = new Uint8Array(fs.readFileSync(__dirname + '/../t7/t7.bin')), emuApp = new Uint8Array(fs.readFileSync(__dirname + '/../emu/emu.bin')), stub = new Uint8Array(fs.readFileSync(__dirname + '/../emu/stub_tpl.bin'));
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const ff = (b, a, e) => b.subarray(a, e).every((v) => v === 0xFF);
(async () => {
ok(E.t7Detect(R) && figs.every((f) => E.t7FigDetect(f.data)) && !E.t7Detect(I), 'detection');
const a = E.t7Patch(L, R, figs, app, stub, { lang: 'en' });
const c = E.t7Cfg(a);
ok(F.appKind(a) === 2 && F.emuType(a) === 't7', 'kind: emulator, type t7');
ok(c.romOff === 0x940000 && c.flags === 3 && c.figs.length === figs.length, 'settings block');
ok(Buffer.from(a.subarray(0x940000, 0x940000 + 0xA0000)).equals(Buffer.from(R)), 'V7 ROM in place');
ok(c.figs.every((f, i) => Buffer.from(a.subarray(f.off, f.off + f.len)).equals(Buffer.from(E.t7FigData(figs[i].data)))), 'figures in place (zero bytes cut, full dumps: one copy)');
for (const f of figs) if (f.data.length > 0x100000) { const d = E.t7FigData(f.data); ok(d.length <= 0x100000 && d[0x55561] === 0xAA && d[0x55562] === 0x55, 'full figure: 1 MB copy with its second block (' + (d.length >> 10) + ' KB)'); }
ok(a.subarray(0xD49000).every((v, i) => v === L[0xD49000 + i]), 'Paradise save untouched');
const back = E.t7FromRom(a);
ok(Buffer.from(back.rom).equals(Buffer.from(R)) && back.figs.length === figs.length, 'read back from the ROM');
// pet save stays when only the figures change
const withEe = new Uint8Array(a); withEe.fill(0x5A, 0xC1000, 0xC5000); withEe.fill(0x6B, 0xC0000, 0xC1000);
const b = E.t7Patch(withEe, R, figs.slice(1), app, stub, {});
ok(b.subarray(0xC1000, 0xC5000).every((v) => v === 0x5A) && ff(b, 0xC0000, 0xC1000), 'other figures: EEPROM kept, session dropped');
const b2 = E.t7Patch(withEe, R, figs, app, stub, {});
ok(b2.subarray(0xC0000, 0xC5000).every((v, i) => v === withEe[0xC0000 + i]), 'same ROM and figures: session and EEPROM kept');
// upgrade
const app2 = new Uint8Array(app); app2[app2.length - 1] ^= 1;
const u = E.t7Upgrade(a, app2);
ok(u && E.t7Cfg(u).figs.length === figs.length && u[0xA0000 + app2.length - 1] === app2[app2.length - 1], 'newer program keeps the settings');
ok(E.t7Upgrade(a, app) === null, 'same program: nothing to do');
// swap to TamaEmu and back
const s = E.emuPatch(a, I, emuApp, stub).rom;
ok(F.emuType(s) === 'tama' && ff(s, 0x940000 + E.packGuest(I, 'idl').blocks * 0x10000, 0xD40000), 'swap to TamaEmu');
const s2 = E.t7Patch(s, R, [], app, stub, {});
ok(F.emuType(s2) === 't7' && ff(s2, 0xC0000, 0x110000), 'back to T7Emu: TamaEmu save area cleared');
const rm = E.emuRemove(a);
ok(F.appKind(rm) === 0 && ff(rm, 0x940000, 0xD48000) && ff(rm, 0xC0000, 0x110000), 'removal');
// menu: the fields still fit next to T7Emu (limit 0x940000)
let fe = true; try { F.feldApply(a, { fields: true, bag: false }, [], { feld: new Uint8Array(fs.readFileSync(__dirname + '/../feld/feld.bin')), stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) }, E); } catch (e) { fe = false; console.log(e.message); }
ok(fe, 'menu with fields next to T7Emu');
// keepPlan: device has T7Emu with a pet, the new image the same ROM with other figures
const device = new Uint8Array(a); device.fill(0x33, 0xC1000, 0xC5000); device.fill(0x44, 0xC0000, 0xC1000);
const img = E.t7Patch(a, R, figs.slice(1), app, stub, {});
const changed = new Set(); for (let s3 = 0; s3 < 0x1000000; s3 += 0x1000) if (!Buffer.from(device.subarray(s3, s3 + 0x1000)).equals(Buffer.from(img.subarray(s3, s3 + 0x1000)))) changed.add(s3);
const dev = { info: { edition: F.edition(img).id }, read: async (ad, n) => device.slice(ad, ad + n) };
const plan = await FL.keepPlan(F, E, null, {})(dev, img, changed);
ok(plan.image.subarray(0xC1000, 0xC5000).every((v) => v === 0x33) && plan.image.subarray(0xC0000, 0xC1000).every((v) => v !== 0x44), 'write with "keep saves": EEPROM from the device, session not (other figures)');
// Tamagotchi Friends: 768 KB, reset vector at 0x7FFC (synthetic ROM, or the real one with FRIENDS=<file>)
let FR = process.env.FRIENDS ? new Uint8Array(fs.readFileSync(process.env.FRIENDS)) : null;
if (!FR) { FR = new Uint8Array(0xC0000); FR[0x7FFC] = 0x00; FR[0x7FFD] = 0xCC; }
const bad3 = new Uint8Array(FR); bad3[0x3FFD] = 0xC0;
ok(E.t7Kind(FR) === 'friends' && E.t7Kind(R) === 'go' && !E.t7Detect(bad3) && !E.t7Detect(FR.subarray(0, 0xA0000)), 'Friends detection');
const fr = E.t7Patch(L, FR, figs, app, stub, {}), fc = E.t7Cfg(fr);
ok(fc.romLen === 0xC0000 && fc.figs.length === 0 && Buffer.from(fr.subarray(0x940000, 0xA00000)).equals(Buffer.from(FR)) && ff(fr, 0xA00000, 0xD40000), 'Friends in place, no figures');
ok(E.t7Room([], 0xC0000) === 0xD40000 - 0xA00000, 'room behind the Friends ROM');
const frGo = E.t7Patch(fr, R, figs, app, stub, {});
ok(E.t7Cfg(frGo).romLen === 0xA0000 && ff(frGo, 0xC0000, 0x110000), 'Friends to Tama-Go: other ROM, save area cleared');
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+32
View File
@@ -0,0 +1,32 @@
// 1.6.12 test2: the second part of T7Emu (t7x.bin, the JIT) lies in the save area at +0x8000, for the main program
// and for a T7Emu in the menu; an upgrade writes it again. node test/emu_t7x_test.js <land.bin> <tama-go.bin> <friends.bin>
const fs = require('fs');
const E = require('../src/emu.js'), F = require('../src/feld.js');
const [land, go, fr] = process.argv.slice(2);
const L = new Uint8Array(fs.readFileSync(land)), G = new Uint8Array(fs.readFileSync(go)), R = new Uint8Array(fs.readFileSync(fr));
const rd = (p) => new Uint8Array(fs.readFileSync(__dirname + '/../' + p));
const app = rd('t7/t7.bin'); app.x = rd('t7/t7x.bin');
const stub = rd('emu/stub_tpl.bin'), fe = { feld: rd('feld/feld.bin'), stub: rd('feld/stub_feld_tpl.bin') };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const has = (rom, at, x) => x.every((v, i) => rom[at + i] === v);
const u32 = (a, o) => (a[o] | (a[o + 1] << 8) | (a[o + 2] << 16) | (a[o + 3] << 24)) >>> 0;
ok(u32(app.x, 0) === 0x31583754 && app.x.length <= 0x8000, 't7x.bin: magic, ' + app.x.length + ' bytes');
let rom = F.feldStrip(L, { stub: fe.stub, oldStub: stub }, E);
rom = E.t7Patch(rom, R, [], app, stub, {});
const so = u32(rom, 0xA0150);
ok(has(rom, so + 0x8000, app.x), 'main program: second part at 0x' + (so + 0x8000).toString(16));
// a program without the second part (older tests, PC builds): nothing is written there
const plain = E.t7Patch(F.feldStrip(L, { stub: fe.stub, oldStub: stub }, E), R, [], rd('t7/t7.bin'), stub, {});
ok(plain.subarray(so + 0x8000, so + 0x10000).every((v) => v === 0xFF), 'without it: the place stays empty');
// upgrade: an other second part is written, the save stays
const app2 = new Uint8Array(app); app2.x = new Uint8Array(app.x); app2.x[20] ^= 0xFF;
const up = E.t7Upgrade(rom, app2);
ok(!!up && has(up, so + 0x8000, app2.x), 'upgrade writes the new second part');
ok(E.t7Upgrade(up, app2) === null, 'nothing to do the second time');
// a T7Emu in the menu
const r = E.appsPlace(rom, [{ rom: G }], app, {});
const off = r.list[0].off, so2 = u32(r.rom, off + 0x150);
ok(so2 === off + 0x10000 && has(r.rom, so2 + 0x8000, app.x), 'menu T7Emu: second part at 0x' + (so2 + 0x8000).toString(16));
ok(has(r.rom, so + 0x8000, app.x), 'main program keeps its own');
console.log(bad ? bad + ' FAILED' : 'all good');
process.exit(bad ? 1 : 0);
+29
View File
@@ -0,0 +1,29 @@
// Comparison: emulator install in JS against the Python builder (same result)
const fs = require('fs');
const E = require('../src/emu.js');
const rom = new Uint8Array(fs.readFileSync(process.argv[2]));
const guest = new Uint8Array(fs.readFileSync(process.argv[3]));
const app = new Uint8Array(fs.readFileSync(__dirname + '/../emu/emu.bin'));
const stub = new Uint8Array(fs.readFileSync(__dirname + '/../emu/stub_tpl.bin'));
console.log('erkannt:', E.emuDetect(guest));
const r = E.emuPatch(rom, guest, app, stub);
console.log('Bloecke', r.blocks);
if (process.argv[4]) {
const ref = new Uint8Array(fs.readFileSync(process.argv[4]));
let diff = 0, first = -1; for (let i = 0; i < ref.length; i++) if (ref[i] !== r.rom[i]) { diff++; if (first < 0) first = i; }
console.log('Unterschiede zum Python-Bauer:', diff, first >= 0 ? '0x' + first.toString(16) : '');
}
// install again (replace) and remove again
const r2 = E.emuPatch(r.rom, guest, app, stub);
let d2 = 0; for (let i = 0; i < r2.rom.length; i++) if (r2.rom[i] !== r.rom[i]) d2++;
console.log('zweiter Einbau gleich:', d2 === 0);
const back = E.emuRemove(r.rom);
let d3 = 0; for (let i = 0; i < back.length; i++) if (back[i] !== rom[i]) d3++;
console.log('Entfernen stellt Original her:', d3 === 0, d3);
// add a download game, against the Python builder
if (process.argv[5]) {
const rec = E.dlcRecord(new Uint8Array(fs.readFileSync(process.argv[5])));
const g2 = E.dlcPut(guest, rec, 1);
console.log('Plaetze vorher', E.dlcSlots(guest).map(x => x.name), 'nachher', E.dlcSlots(g2).map(x => x.name));
if (process.argv[6]) { const ref = fs.readFileSync(process.argv[6]); console.log('wie dlc.py:', Buffer.from(g2).equals(ref)); }
}
+46
View File
@@ -0,0 +1,46 @@
// 1.6.9: V3Emu (Tamagotchi Connection V3) as the main program and in the menu, handled as a V1Emu.
// node test/emu_v3_test.js <land.bin> <v3 rom 512 KB> <p2.bin> <tama-go.bin>
const fs = require('fs'), S = __dirname + '/../';
const C = require(S + 'src/core.js'), E = require(S + 'src/emu.js'), F = require(S + 'src/feld.js');
const rd = (p) => new Uint8Array(fs.readFileSync(p));
const [land, v3p, p2, go] = process.argv.slice(2);
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const u32 = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0;
const progs = { t7: rd(S + 't7/t7.bin'), tama: rd(S + 'emu/emu.bin'), t18: rd(S + 't18/t18.bin'), v1: rd(S + 'v1/v1.bin') }; progs.t18.xip = rd(S + 't18/t18x.bin');
const v3app = rd(S + 'v3/v3.bin'); progs.v1.v3 = v3app;
const stub = rd(S + 'emu/stub_tpl.bin'), fe = { feld: rd(S + 'feld/feld.bin'), stub: rd(S + 'feld/stub_feld_tpl.bin') };
const V3 = rd(v3p), P = rd(p2), G = rd(go);
ok(E.v3Detect(V3) && E.v1Detect(V3), 'V3 ROM found');
ok(!E.v3Detect(P) && !E.v3Detect(G), 'P2 and Tama-Go are no V3');
ok(E.v1Name(V3) === 'TAMA V3', 'name ' + E.v1Name(V3));
ok(u32(v3app, 0x140) === E.V1_MAGIC, 'V3Emu has the V1Emu settings block');
const ctx = C.openRom(rd(land)); const base = C.buildRom(ctx, C.launcherChanges(ctx)).rom;
// main program
const m = E.v1Patch(base, V3, progs.v1, stub, { lang: 'de' });
const prog = (rom, off) => rom.subarray(off + 0x300, off + v3app.length);
ok(Buffer.from(prog(m, 0xA0000)).equals(Buffer.from(v3app.subarray(0x300))), 'main: the V3 program at 0x0A0000');
const ro = u32(m, 0xA0148), rl = u32(m, 0xA014C);
ok(rl === 0x80000 && ro % 0x10000 === 0 && Buffer.from(m.subarray(ro, ro + rl)).equals(Buffer.from(V3)), 'main: the ROM at 0x' + ro.toString(16));
ok(E.v1FromRom(m) && E.v1FromRom(m).length === 0x80000, 'main: the ROM read back');
ok(E.v1Upgrade(m, progs.v1) === null, 'main: nothing to upgrade with the same program');
{ const old = new Uint8Array(m); old.fill(0, 0xA0400, 0xA0500); const u = E.v1Upgrade(old, progs.v1); ok(u && Buffer.from(prog(u, 0xA0000)).equals(Buffer.from(v3app.subarray(0x300))), 'main: an old V3 program is renewed with V3Emu, not V1Emu'); }
// a P2 as main program still gets V1Emu
{ const p = E.v1Patch(base, P, progs.v1, stub, {}); ok(Buffer.from(p.subarray(0xA0300, 0xA0300 + 0x1000)).equals(Buffer.from(progs.v1.subarray(0x300, 0x1300))), 'P2: still V1Emu'); }
// in the menu, next to a P2
const before = E.t7Patch(base, G, [], progs.t7, stub, {});
const r = E.appsPlace(before, [{ kind: 'v1', rom: V3 }, { kind: 'v1', rom: P }], progs, { launch: true });
const img = F.feldApply(r.rom, { launch: true, apps: r.list, dl: r.dl }, [], fe, E);
const xs = E.appsRead(img, F.feldApps(img, fe.stub).apps);
const x3 = xs.find((x) => x.rom.length === 0x80000), xp = xs.find((x) => x.rom.length !== 0x80000);
ok(x3 && Buffer.from(x3.rom).equals(Buffer.from(V3)) && E.extraName(x3) === 'TAMA V3', 'menu: V3 read back');
ok(xp && Buffer.from(xp.rom).equals(Buffer.from(P)), 'menu: P2 read back');
{ const c = E.extraCfg(img, x3.off); ok(c.romOff % 0x10000 === 0 && c.romOff + 0x80000 === x3.off && c.saveOff === x3.off + 0x10000, 'menu: ROM 64 KB aligned in front of the program, save behind');
ok(Buffer.from(prog(img, x3.off)).equals(Buffer.from(v3app.subarray(0x300))), 'menu: the V3 program'); }
// clearing frees exactly the V3's ROM, program and save
{ const cl = E.appsClear(img, [x3]), c = E.extraCfg(img, x3.off);
let outside = 0; for (let a = 0; a < img.length; a += 0x1000) { const inV3 = (a >= c.romOff && a < c.romOff + 0x80000) || (a >= x3.off && a < x3.off + 0x12000); if (!inV3 && !Buffer.from(cl.subarray(a, a + 0x1000)).equals(Buffer.from(img.subarray(a, a + 0x1000)))) outside++; }
ok(outside === 0 && cl.subarray(c.romOff, c.romOff + 0x80000).every((v) => v === 0xFF) && cl.subarray(x3.off, x3.off + 0x12000).every((v) => v === 0xFF), 'menu: clearing frees only the V3 (' + outside + ' other sectors touched)');
ok(Buffer.from(cl.subarray(xp.off, xp.off + 0x10000)).equals(Buffer.from(img.subarray(xp.off, xp.off + 0x10000))), 'menu: the P2 stays'); }
ok(E.extraSize({ kind: 'v1', rom: V3 }) === 0x92000, 'size of the V3 in the menu');
if (process.env.OUT) { fs.writeFileSync(process.env.OUT + '/v3main.bin', m); fs.writeFileSync(process.env.OUT + '/v3menu.bin', img); console.log('menu V3 at 0x' + x3.off.toString(16)); }
console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
+69
View File
@@ -0,0 +1,69 @@
// 1.6.8: figures for a further T7Emu, download items for a further TamaEmu (save kept on the device)
// node test/emu_xitems_test.js <land.bin> <tama-go.bin> <fig1.bin> <fig2.bin> <idl.bin>
const fs = require('fs'), S = __dirname + '/../';
const C = require(S + 'src/core.js'), E = require(S + 'src/emu.js'), F = require(S + 'src/feld.js'), FL = require(S + 'src/flash.js');
const rd = (p) => new Uint8Array(fs.readFileSync(p));
const [land, go, f1, f2, idl] = process.argv.slice(2);
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const progs = { t7: rd(S + 't7/t7.bin'), tama: rd(S + 'emu/emu.bin'), t18: rd(S + 't18/t18.bin'), v1: rd(S + 'v1/v1.bin') }; progs.t18.xip = rd(S + 't18/t18x.bin');
const fe = { feld: rd(S + 'feld/feld.bin'), stub: rd(S + 'feld/stub_feld_tpl.bin') };
const ctx = C.openRom(rd(land)); const base = C.buildRom(ctx, C.launcherChanges(ctx)).rom;
function build(xs) {
const r = E.appsPlace(base, xs, progs, { launch: true, dlApp: rd(S + 'flash/flashapp.bin') });
return F.feldApply(r.rom, { launch: true, apps: r.list, dl: r.dl }, [], fe, E);
}
function secs(a, b) { const o = new Set(); for (let s = 0; s < Math.max(a.length, b.length); s += 0x1000) if (!Buffer.from(a.subarray(s, s + 0x1000)).equals(Buffer.from(b.subarray(s, s + 0x1000)))) o.add(s); return o; }
(async () => {
// figures behind a further Tama-Go
const figs = [{ name: '(03)_Tama-Go_Mametchi.bin', data: E.t7FigData(rd(f1)) }, { name: '(04)_Tama-Go_Memetchi.bin', data: E.t7FigData(rd(f2)) }];
const a = build([{ rom: rd(go), figs }]);
const back = E.appsRead(a, F.feldApps(a, fe.stub).apps);
ok(back.length === 1 && back[0].figs.length === 2 && back[0].figs[0].name === E.t7FigName(figs[0].name), 'figures read back: ' + back[0].figs.map((f) => f.name).join(', '));
ok(back[0].figs.every((f, i) => Buffer.from(f.data).equals(Buffer.from(E.t7Trim ? E.t7Trim(figs[i].data) : figs[i].data))), 'figure data identical');
const a2 = build([{ rom: back[0].rom, figs: back[0].figs }]);
ok(Buffer.from(a2).equals(Buffer.from(a)), 'built again from the ROM: identical');
const cl = E.appsClear(a, back);
ok(back[0].figs.length && cl.subarray(back[0].off, back[0].off + E.extraSize({ rom: back[0].rom, figs: back[0].figs })).every((v) => v === 0xFF), 'removed: figures freed as well');
// download items in a further iD L: the device keeps the pet's own writes, the Studio's item sectors are written
const mk = (nm) => {
const rec = new Uint8Array(0x100); rec.set(Buffer.from('TAMAGO'));
for (let i = 0; i < nm.length; i++) rec[7 + 2 * i] = nm.charCodeAt(i);
rec[0x4E] = 0x81; rec[0x50] = 0x02; rec[0x51] = 0x01; rec[0x4B] = 0x00; rec[0x4A] = 0x01;
let sum = 0; for (let i = 0; i < 0xFE; i++) sum += rec[i]; rec[0xFE] = sum >> 8 & 255; rec[0xFF] = sum & 255; return rec;
};
// the store already holds an item (its block is in the layout); a second item keeps the layout
const G0 = rd(idl), G = E.dlcAdd(G0, E.dlcRecord(mk('DL_X_tea.jpg'), E.emuDetect(G0))).guest;
const r0 = build([{ kind: 'tama', guest: G, dev: E.emuDetect(G) }]);
const x0 = E.appsRead(r0, F.feldApps(r0, fe.stub).apps)[0];
ok(Buffer.from(x0.guest).equals(Buffer.from(G)), 'read back: the whole firmware, also the parts kept as spare pages (1.7.1)');
const ad = E.dlcAdd(x0.guest, E.dlcRecord(mk('DL_X_cake.jpg'), x0.dev));
const r1 = build([{ kind: 'tama', guest: ad.guest, dev: x0.dev }]);
const mine = secs(r0, r1);
ok(mine.size > 0 && mine.size < 8, 'items change ' + mine.size + ' sectors');
const c = E.extraCfg(r0, x0.off);
// the device: the pet wrote into its state and into a guest data sector the Studio did not touch
const device = new Uint8Array(r0); device.fill(0x5A, c.saveOff, c.saveOff + 0x1000);
let petSec = -1; for (let s = c.guestOff + 0x10000; s < c.guestOff + c.guestSize; s += 0x1000) if (!mine.has(s) && device[s] !== 0xFF) { petSec = s; break; }
device.fill(0x33, petSec, petSec + 0x1000);
const changed = secs(device, r1);
const dev = { info: { edition: F.edition(r1).id }, read: async (x, n) => device.slice(x, x + n) };
const plan = await FL.keepPlan(F, E, { stub: fe.stub }, { mine })(dev, r1, changed);
ok(!plan.notes.length, 'no notes: ' + JSON.stringify(plan.notes));
ok(plan.image.subarray(c.saveOff, c.saveOff + 0x1000).every((v) => v === 0x5A), 'run state kept');
ok(plan.image.subarray(petSec, petSec + 0x1000).every((v) => v === 0x33), 'the guest\'s own write kept (0x' + petSec.toString(16) + ')');
ok([...mine].every((s) => Buffer.from(plan.image.subarray(s, s + 0x1000)).equals(Buffer.from(r1.subarray(s, s + 0x1000)))), 'item sectors from the Studio');
const st = E.dlcStores(E.appsRead(plan.image, F.feldApps(plan.image, fe.stub).apps)[0].guest);
ok(st.some((k) => k.slots.some((y) => y.name === 'cake')), 'item in the store after writing');
// clock off for this program only: the flags change, the save stays
const r2 = build([{ kind: 'tama', guest: ad.guest, dev: x0.dev, clock: false }]);
const x2 = E.appsRead(r2, F.feldApps(r2, fe.stub).apps)[0];
ok(x2.clock === false && (r2[x0.off + 0x140 + 156] & 2) === 0, 'clock flag per program');
const dev2 = new Uint8Array(r1); dev2.fill(0x5A, c.saveOff, c.saveOff + 0x1000);
const ch2 = secs(dev2, r2), d2 = { info: { edition: F.edition(r2).id }, read: async (x, n) => dev2.slice(x, x + n) };
const plan3 = await FL.keepPlan(F, E, { stub: fe.stub }, { mine: secs(r1, r2) })(d2, r2, ch2);
ok(!plan3.notes.length && plan3.image.subarray(c.saveOff, c.saveOff + 0x1000).every((v) => v === 0x5A), 'clock switched: run state kept');
// without 'mine' (old way) the extra counted as new firmware
const plan2 = await FL.keepPlan(F, E, { stub: fe.stub }, {})(dev, r1, changed);
ok(plan2.notes.length === 1, 'old way: note');
console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+13
View File
@@ -0,0 +1,13 @@
// Install the field switch into a finished ROM, as the studio does when saving.
// node test/feld_cli.js <rom_in> <rom_out> [aus|felder|items] (aus = off, felder = fields only, items = items only; default: fields and items)
const fs = require('fs');
const E = require('../src/emu.js'), F = require('../src/feld.js');
const rd = (p) => new Uint8Array(fs.readFileSync(p));
const emb = { feld: rd(__dirname + '/../feld/feld.bin'), stub: rd(process.env.STUBTPL || (__dirname + '/../feld/stub_feld_tpl.bin')), oldStub: rd(__dirname + '/../emu/stub_tpl.bin') };
let rom = rd(process.argv[2]);
const saved = F.feldSlots(rom, emb.stub);
rom = F.feldStrip(rom, emb, E);
const w = process.argv[4] || '';
if (w !== 'aus') rom = F.feldApply(rom, { fields: w !== 'items', bag: w !== 'felder' }, saved, emb, E);
fs.writeFileSync(process.argv[3], rom);
console.log(process.argv[3], JSON.stringify(F.feldFind(rom, emb.stub)), 'Programm', ['keins', 'DOOM', 'Emulator'][F.appKind(rom)]);
+75
View File
@@ -0,0 +1,75 @@
// Check the field switch in the studio (local only, needs your own Paradise images).
// node test/feld_test.js <land.bin> [compare_feld_rom.bin] [glacier.bin]
const fs = require('fs');
const E = require('../src/emu.js'), D = require('../src/doom.js'), F = require('../src/feld.js');
const rd = (p) => new Uint8Array(fs.readFileSync(p));
const emb = { feld: rd(__dirname + '/../feld/feld.bin'), stub: rd(__dirname + '/../feld/stub_feld_tpl.bin'), oldStub: rd(__dirname + '/../emu/stub_tpl.bin') };
const eq = (a, b) => a.length === b.length && Buffer.compare(Buffer.from(a), Buffer.from(b)) === 0;
let bad = 0;
function ok(c, m) { console.log((c ? 'ok ' : 'FALSCH ') + m); if (!c) bad++; }
const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0;
function w32(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; }
const land = rd(process.argv[2]);
{ // fields: characters, maps and close-ups per field type
const C = require('../src/core.js'), fs2 = C.fieldSets(C.openRom(land));
ok(fs2.length === 3 && fs2.every((f) => f.chars.length === 22 && f.maps.length === 7 && f.closeups.length === 6), 'fields of the ROM: ' + fs2.map((f) => f.name).join(', '));
}
ok(F.feldId(land) >= 1, 'Feld erkannt: ' + F.NAMES[F.feldId(land)]);
ok(!F.feldFind(land, emb.stub), 'Original ohne Feldwahl');
// 1. field switch only
const a = F.feldApply(land, { fields: true, bag: false }, [], emb, E);
const fa = F.feldFind(a, emb.stub);
ok(fa && fa.off === 0xB1000 && fa.slotOff === 0x830000 && fa.slotSize >= 0x58000 && fa.slotOff + 3 * fa.slotSize <= 0xD48000, 'Lage ohne Programm ' + JSON.stringify(fa));
ok(eq(F.feldStrip(a, emb, E), land), 'Ausbauen gibt das Original zurueck');
// 2. save in a slot, then add the emulator, then DOOM: the slot moves along
const b = new Uint8Array(a);
const fake = new Uint8Array(0x3000); fake.fill(0x5A); w32(fake, 0, 0x544C5346); w32(fake, 4, 2); w32(fake, 8, 3); w32(fake, 12, 0x2000);
b.set(fake, fa.slotOff + 1 * fa.slotSize);
const saved = F.feldSlots(b, emb.stub);
ok(saved.length === 1 && saved[0].field === 2 && saved[0].bytes === 0x2000 && saved[0].stream.every((v) => v === 0x5A), 'Fach gelesen');
const sameSlot = (r) => { const x = F.feldSlots(r, emb.stub); return x.length === 1 && x[0].field === 2 && x[0].bytes === 0x2000 && x[0].stream.every((v) => v === 0x5A) && eq(x[0].head.subarray(32, 2032), fake.subarray(32, 2032)); };
// Emulator: we check the program without a real guest via installApp (same stub path)
const embE = E.embedded() || { app: rd(__dirname + '/../emu/emu.bin'), stub: emb.oldStub };
let c = F.feldStrip(b, emb, E);
c = E.installApp(c, embE.app, emb.oldStub);
c = F.feldApply(c, { fields: true, bag: true }, saved, emb, E);
const fc = F.feldFind(c, emb.stub);
ok(F.appKind(c) === 2 && fc.off === 0xB1000, 'mit Emulator: Programm erkannt, Feldwahl bei 0xB1000');
ok(u32(c, 0xB0008) === 0x1008F000, 'Starter kennt das Programm');
ok(sameSlot(c), 'Fach mit Emulator erhalten');
// DOOM (small fake WAD, the program is real)
const dapp = rd(__dirname + '/../doom/doom_app.bin'), dxip = rd(__dirname + '/../doom/doom_xip.bin');
let d = F.feldStrip(b, emb, E);
d = D.doomPatch(d, new Uint8Array(1000), { app: dapp, xip: dxip, stub: emb.oldStub }, E).rom;
d = F.feldApply(d, { fields: true, bag: true }, saved, emb, E);
const fd = F.feldFind(d, emb.stub);
ok(F.appKind(d) === 1, 'DOOM erkannt');
ok(fd.off === ((0xB1000 + dxip.length + 0xFFF) & ~0xFFF) && fd.slotOff + 3 * fd.slotSize <= 0x10E000, 'Lage mit DOOM ' + JSON.stringify(fd) + ' je Fach ' + (fd.slotSize >> 10) + ' KB');
ok(sameSlot(d), 'Fach zieht zu DOOM um');
ok(eq(d.slice(0xB1000, 0xB1000 + dxip.length), dxip), 'DOOM-Programm unberuehrt');
ok(u32(d, 0x830000) === 1000, 'WAD unberuehrt');
ok(F.itemCatalog(d).pack === F.itemCatalog(land).pack, 'item pictures found in the asset archive, not in DOOM');
// without field switch again: DOOM stub as before
const e = F.feldStrip(d, emb, E);
ok(!F.feldFind(e, emb.stub) && F.appKind(e) === 1 && u32(e, 0xB0000 + 0x94) === u32(land, E.sceneTable(land).PSID_HOME + 12), 'Ausbau mit DOOM laesst DOOM stehen');
// 3. another edition
if (process.argv[4]) {
const g = rd(process.argv[4]);
let err = ''; try { F.feldApply(g, { fields: true, bag: false }, [], emb, E); } catch (x) { err = x.message; }
ok(F.feldId(g) === 6 && F.canFields(g), 'Glacier erkannt, Felder: ' + F.fieldNames(g).join(' ') + (err ? ' FEHLER ' + err : ''));
}
// 4. more editions from the environment: install, find, remove = original
for (const p of (process.env.WEITERE || '').split(',').filter(Boolean)) {
const r = rd(p); const ed = F.edition(r);
try {
const x = F.feldApply(r, { fields: true, bag: true }, [], emb, E), fx = F.feldFind(x, emb.stub);
ok(fx && eq(F.feldStrip(x, emb, E), r), p.split('/').pop() + ': ' + F.NAMES[ed.id] + ' ' + JSON.stringify(fx));
} catch (x) { ok(false, p.split('/').pop() + ': ' + x.message); }
}
console.log(bad ? bad + ' Fehler' : 'alles gut');
process.exit(bad ? 1 : 0);
+49
View File
@@ -0,0 +1,49 @@
// Flasher against the emulated Paradise. Needs the UART bridge of the Paradise
// system emulator (a separate project, not part of this repository): it runs the
// device firmware and forwards UART bytes over stdin/stdout.
// node test/flash_bridge_test.js <bridge-binary> <firmware.bin>
const { spawn } = require('child_process');
const fs = require('fs');
const FL = require('../src/flash.js'), F = require('../src/feld.js'), E = require('../src/emu.js');
const [bridge, fwFile] = process.argv.slice(2);
const app = new Uint8Array(fs.readFileSync(__dirname + '/../flash/flashapp.bin'));
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'WRONG ') + m); if (!c) bad++; };
function start(file, out) {
const p = spawn(bridge, [file, out], { stdio: ['pipe', 'pipe', 'inherit'] });
const io = { onData: null, write: (d) => new Promise((r) => p.stdin.write(Buffer.from(d), r)) };
p.stdout.on('data', (d) => io.onData && io.onData(new Uint8Array(d)));
const ready = new Promise((r) => setTimeout(r, 100));
return { p, io, ready, close: () => new Promise((r) => { p.on('exit', r); p.stdin.end(); }) };
}
(async () => {
const base = new Uint8Array(fs.readFileSync(fwFile));
const out = '/tmp/claude-0/bridge_flash.bin';
const b = start(fwFile, out);
await new Promise((r) => setTimeout(r, 15000)); // let the device reach the download screen
const t0 = Date.now();
const { dev, loaded } = await FL.connect(b.io, app, { timeScale: 20 }, (ph, d, t) => {});
ok(loaded && dev.info.capacity === 0x1000000, 'connected, app loaded: ' + JSON.stringify(dev.info) + ' ' + ((Date.now() - t0) / 1000 | 0) + ' s');
const r = await dev.read(0, 0x10000);
ok(Buffer.compare(Buffer.from(r), Buffer.from(base.subarray(0, 0x10000))) === 0, 'read 64 KB matches');
// new image: one byte in the character data, one in the save data
const img = new Uint8Array(base); img[0x200010] ^= 0x5A; img[0xEFE100] ^= 0x33; img[0x0A0000 + 0x8000] ^= 1;
const keep = FL.keepPlan(F, E, null, {});
const before = await dev.read(0xEFE000, 0x1000);
let t1 = Date.now();
const res = await dev.write(img, { onlyChanged: true, keep }, null);
const after = await dev.read(0xEFE000, 0x1000), ch = await dev.read(0x200000, 0x1000);
ok(Buffer.compare(Buffer.from(before), Buffer.from(after)) === 0 && Buffer.compare(Buffer.from(ch), Buffer.from(img.subarray(0x200000, 0x201000))) === 0, 'save sector kept, character sector written');
ok(res.written === 2 && res.kept >= 1, 'only changes, keep saves: written ' + res.written + ', kept ' + res.kept + ' ' + ((Date.now() - t1) / 1000 | 0) + ' s ' + res.notes.join('; '));
t1 = Date.now();
const res2 = await dev.write(img, { onlyChanged: true, keep: null }, null);
ok(res2.written === res.kept, 'only changes without keep: written ' + res2.written + ' ' + ((Date.now() - t1) / 1000 | 0) + ' s');
// edition check
const other = new Uint8Array(img); other[0xD49000] = 2;
let err = ''; try { await dev.write(other, { onlyChanged: true, keep }, null); } catch (e) { err = e.message; }
ok(/Untick/.test(err), 'other edition refused: ' + err);
await b.close();
const fl = new Uint8Array(fs.readFileSync(out));
ok(Buffer.compare(Buffer.from(fl), Buffer.from(img)) === 0, 'device flash equals the image at the end');
console.log(bad ? bad + ' wrong' : 'all good');
process.exit(bad ? 1 : 0);
})().catch((e) => { console.error(e); process.exit(1); });
+28
View File
@@ -0,0 +1,28 @@
// 1.7.2 GBCEmu: Game Boy Color games get the colour program, games over 1 MB are stored in pages, everything reads back.
// node test/gbc_test.js <land.bin> <game.gbc> [<game.gb>]
const fs = require('fs'), S = __dirname + '/../';
const C = require(S + 'src/core.js'), E = require(S + 'src/emu.js'), F = require(S + 'src/feld.js');
const rd = (p) => new Uint8Array(fs.readFileSync(p));
const [land, gbc, gb] = process.argv.slice(2);
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const u32 = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0;
const fe = { feld: rd(S + 'feld/feld.bin'), stub: rd(S + 'feld/stub_feld_tpl.bin') };
const progs = { gb: rd(S + 'gb/gb.bin'), gbc: rd(S + 'gb/gbc.bin') };
const ctx = C.openRom(rd(land)); const base = C.buildRom(ctx, C.launcherChanges(ctx)).rom;
const R = rd(gbc), xs = [{ kind: 'gb', rom: R, keys: E.GB_KEYS_DEFAULT.slice(), inv: true }];
if (gb) xs.push({ kind: 'gb', rom: rd(gb), keys: E.GB_KEYS_DEFAULT.slice(), inv: true });
ok(E.gbDetect(R) && E.gbIsColor(R), 'colour game recognised');
const r = E.appsPlace(base, xs, progs, { launch: true, dlApp: rd(S + 'flash/flashapp.bin') });
const m = F.feldApply(r.rom, { launch: true, apps: r.list, dl: r.dl }, [], fe, E);
const back = E.appsRead(m, F.feldApps(m, fe.stub).apps);
ok(back.length === xs.length, 'programs read back: ' + back.length);
const b0 = back.find((x) => x.kind === 'gb' && E.gbIsColor(x.rom));
ok(!!b0 && Buffer.compare(Buffer.from(b0.rom), Buffer.from(R)) === 0, 'colour game the same after reading back (' + (R.length >> 10) + ' KB)');
const fl = u32(m, b0.off + 0x140 + 20);
ok(!!(fl & 8) && (R.length > 0x100000) === !!(fl & 4), 'flags: colour' + (fl & 4 ? ', pages' : ''));
ok(Buffer.compare(Buffer.from(m.subarray(b0.off, b0.off + 0x140)), Buffer.from(progs.gbc.subarray(0, 0x140))) === 0, 'program: GBCEmu');
ok(b0.save.length === 0x18000, 'save area 96 KB');
if (gb) { const b1 = back.find((x) => x !== b0); ok(Buffer.compare(Buffer.from(m.subarray(b1.off, b1.off + 0x140)), Buffer.from(progs.gb.subarray(0, 0x140))) === 0 && !(u32(m, b1.off + 0x140 + 20) & 8), 'Game Boy game keeps GBEmu'); }
const again = E.appsPlace(E.appsClear(m, back), back, progs, { launch: true, dlApp: rd(S + 'flash/flashapp.bin') });
ok(!!again.rom, 'placed again from what was read');
console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
+37
View File
@@ -0,0 +1,37 @@
// test25: "Keep saves" with an imported T7Emu save (start device with a TamaEmu and T7Emu): only that save changes, the
// Paradise save and the TamaEmu flash stay as on the device; without "Keep saves" all come from the file.
// node test/keep_import_test.js <start device ROM with TamaEmu and T7Emu in the menu, e.g. r2.bin of ui_save_pick_test>
const S=__dirname+'/../';
const FL=require(S+'src/flash.js'),F=require(S+'src/feld.js'),E=require(S+'src/emu.js'),SV=require(S+'src/saves.js'),fs=require('fs');
function fakeDevice(mem){const devSide=new FL.Link({write:async()=>{}});const sec=new Uint8Array(0x1000),io={onData:null};
io.write=async(d)=>{devSide.feed(d);for(const f of devSide.frames.splice(0)){const p=f.payload,u=(o)=>(p[o]|p[o+1]<<8|p[o+2]<<16|p[o+3]<<24)>>>0;let out=new Uint8Array(0);
if(f.type===1){out=new Uint8Array(44);out[8]=mem[0xD49000];out[10]=0;out[11]=16;out.set([0,0,0,1],32);}
else if(f.type===5)out=mem.slice(f.off,f.off+u(0));
else if(f.type===6){const c=FL.crc32(mem,f.off,u(0));out=new Uint8Array([c&255,c>>>8&255,c>>>16&255,c>>>24]);}
else if(f.type===13){out=new Uint8Array(16);out[12]=1;}
else if(f.type===9)out=new Uint8Array(4);
else if(f.type===10){sec.set(p,f.off&0xFFF);}
else if(f.type===11){mem.set(sec,f.off&~0xFFF);out=new Uint8Array(8);const c=FL.crc32(sec);out.set([c&255,c>>>8&255,c>>>16&255,c>>>24]);}
setImmediate(()=>io.onData(devSide.frame(f.type,f.seq,f.off,out)));}};return io;}
let bad=0; const ok=(c,m)=>{console.log((c?'ok ':'FAIL ')+m); if(!c) bad++;};
async function run(withKeep){
const stub=new Uint8Array(fs.readFileSync(S+'feld/stub_feld_tpl.bin'));
const r2=new Uint8Array(fs.readFileSync(process.argv[2]));
const apps=F.feldApps(r2,stub).apps, xs=E.appsRead(r2,apps); const ix=xs.findIndex(x=>E.extraKind(x)==='t7'); const t7=xs[ix];
const mem=new Uint8Array(r2);
// the device has played: Paradise save, colour Tama flash (guest area), T7 pet
const ed=1, pa=0xD4A000; mem.fill(0x11,pa,pa+0x1000);
const cfg=SV.emuCfg(mem.subarray(0xA0000,0xA1000)); const gpage=cfg.guestOff+0x10000; const gold=mem.slice(gpage,gpage+16); mem[gpage]^=0xFF;
const oldT7=SV.t7SaveOut(mem,t7.off+0x10000); const devT7=new Uint8Array(oldT7||new Uint8Array(4098)); devT7[10]^=0x22; const mem2=SV.t7SaveIn(mem,devT7,t7.off+0x10000); mem.set(mem2);
const io=fakeDevice(mem); const {dev}=await FL.connect(io,new Uint8Array(16),{});
// Studio: ROM read from the device, the T7 save imported
const imp=new Uint8Array(4098).fill(0); imp[0]=1; imp[2]=0x77; imp[200]=0x55;
const img=SV.t7SaveIn(new Uint8Array(r2),imp,t7.off+0x10000); // an older file than the device
const keep=withKeep?FL.keepPlan(F,E,{stub},{t7SaveX:ix}):null;
const r=await dev.write(img,{onlyChanged:true,keep},null);
const got=SV.t7SaveOut(mem,t7.off+0x10000);
const k=mem.subarray(pa,pa+0x1000).every(v=>v===0x11), g=mem[gpage]===(gold[0]^0xFF);
ok(Buffer.from(got).equals(Buffer.from(imp)),(withKeep?'keep: ':'no keep: ')+'T7Emu has the imported save');
ok(withKeep?k&&g:!k&&!g,(withKeep?'keep: Paradise save and TamaEmu flash stay as on the device':'no keep: everything from the file'));
}
(async()=>{ await run(true); await run(false); console.log(bad?'FAIL '+bad:'all good'); })();
+33
View File
@@ -0,0 +1,33 @@
const {JSDOM,VirtualConsole}=require('jsdom');
const fs=require('fs'),assert=require('assert/strict'),vm=require('vm');
const root=require('path').resolve(__dirname,'..');
const html=fs.readFileSync(root+'/dist/index.html','utf8');
const errors=[];const vc=new VirtualConsole();vc.on('jsdomError',e=>errors.push(e.message));
const dom=new JSDOM(html,{url:'https://tama.itosm.co.kr',runScripts:'dangerously',virtualConsole:vc,beforeParse(w){w.TextEncoder=TextEncoder;w.TextDecoder=TextDecoder;w.structuredClone=structuredClone;w.URL.createObjectURL=()=> 'blob:test';w.URL.revokeObjectURL=()=>{};}});
const w=dom.window,d=w.document;
assert.deepEqual(errors,[]);
assert.equal(d.documentElement.lang,'ko');
assert.match(d.body.textContent,/다마고치 파라다이스를 더 다양하게/);
for(const el of d.querySelectorAll('[data-t]'))assert.ok(el.textContent.trim(),'Empty translation '+el.dataset.t);
assert.ok(!d.getElementById('menuKo').checked);
const en=w.ParamixFeld.embedded(); d.getElementById('menuKo').checked=true;const ko=w.ParamixFeld.embedded();
assert.ok(ko.feld.length<=0x8000);assert.ok(ko.feldc.length<=0xe000);assert.notDeepEqual(Buffer.from(en.feld),Buffer.from(ko.feld));assert.deepEqual(Buffer.from(en.stub),Buffer.from(ko.stub));
// Recognize installed Korean menus without touching a physical device or vendor ROM.
for(const [program,clean] of [[ko.feld,false],[ko.feldc,true],[en.feld,false]]){
const rom=new w.Uint8Array(0x1000000);rom.fill(255);rom.set(program,0xB1000);rom.set(ko.stub,0xB0000);
const dv=new w.DataView(rom.buffer);let found=false;
for(let i=0;i+4<=ko.stub.length;i+=2)if(new w.DataView(ko.stub.buffer).getUint32(i,true)===0x6789EF01){dv.setUint32(0xB0000+i,0x100A0000,true);found=true;break;}
assert.ok(found);
if(clean){rom.set(Buffer.from('SONIXDEV'),0);dv.setUint32(0x10,0x600B1000,true);dv.setUint32(0xB1000+0x140+36,32,true);}
assert.equal(w.ParamixFeld.koreanMenu(rom),program!==en.feld,'Menu language detection');
}
for(const lang of ['en','de','ko']){d.querySelector(`[data-lang="${lang}"]`).click();assert.equal(d.documentElement.lang,lang);}
assert.ok(!d.body.textContent.includes('실기 미검증'));assert.match(d.body.textContent,/다마고치 및 아이템 이름을 한국어로 표시/);
const langs=fs.readFileSync(root+'/src/app.js','utf8');
const t=vm.runInNewContext(langs.slice(langs.indexOf('const T = {'),langs.indexOf('\nlet lang'))+';T');
assert.equal(Object.keys(t.en).filter(k=>!t.ko[k]).length,0);
const generic=langs.match(/const MSG_KO = \[[\s\S]*?\n\];/)[0]; const m=vm.runInNewContext(generic+';MSG_KO');
assert.ok(m.some(([re,s])=>re.test('menu program too big')&&s.includes('용량')));
assert.deepEqual(errors,[]);
console.log(JSON.stringify({passed:true,translations:Object.keys(t.ko).length,koreanMenuBytes:ko.feld.length,cleanMenuBytes:ko.feldc.length,languages:['ko','en','de'],domErrors:errors,deviceWritten:false},null,2));
w.close();
+34
View File
@@ -0,0 +1,34 @@
const fs=require('fs'),assert=require('assert/strict'),path=require('path');
const {JSDOM,VirtualConsole}=require(process.env.JSDOM_PATH||'jsdom');
const root=path.resolve(__dirname,'..');
(async()=>{
const errors=[],vc=new VirtualConsole();vc.on('jsdomError',e=>errors.push(e.message));
const dom=new JSDOM(fs.readFileSync(root+'/account.html','utf8'),{url:'https://tama.itosm.co.kr/account.html',runScripts:'outside-only',virtualConsole:vc});
const w=dom.window,d=w.document;w.AbortSignal=AbortSignal;
let mode='bad',logged=false,isAdmin=false,calls=0;
w.fetch=async url=>{
if(url.endsWith('/login')){
calls++;
if(mode==='network')throw Error('network');
if(mode==='timeout'){const e=Error();e.name='TimeoutError';throw e;}
if(mode==='html')return{ok:false,status:502,json:async()=>{throw Error('invalid JSON');}};
if(mode==='bad')return{ok:false,status:401,json:async()=>({error:'bad credentials'})};
if(mode==='rate')return{ok:false,status:429,json:async()=>({error:'시도가 많습니다. 15분 뒤 다시 시도하세요.'})};
if(mode==='server')return{ok:false,status:500,json:async()=>({error:'internal'})};
logged=mode!=='cookie';return{ok:true,status:200,json:async()=>({ok:true})};
}
return{ok:true,status:200,json:async()=>({authenticated:logged,isAdmin,username:'sample',count:0,maxFiles:10,quotaBytes:167772160,usedBytes:0,items:[]})};
};
w.eval(fs.readFileSync(root+'/account.js','utf8'));
const settle=()=>new Promise(r=>setTimeout(r,30)),submit=async()=>{d.getElementById('loginForm').dispatchEvent(new w.Event('submit',{cancelable:true}));await settle();};await settle();
const error=d.getElementById('loginError');
await submit();assert.match(error.textContent,/아이디를 입력/);assert.equal(calls,0);
d.getElementById('loginName').value='sample';await submit();assert.match(error.textContent,/비밀번호를 입력/);assert.equal(calls,0);
d.getElementById('loginPassword').value='test-only-password';
for(const [kind,re] of [['bad',/아이디 또는 비밀번호/],['rate',/15분/],['network',/서버에 연결하지/],['timeout',/응답 시간이/],['server',/서버 오류/],['html',/서버 응답을 처리/],['cookie',/쿠키/]]){
mode=kind;await submit();assert.equal(error.hidden,false);assert.match(error.textContent,re);assert.equal(d.activeElement,error);assert.equal(d.getElementById('loginSubmit').disabled,false);assert.equal(d.getElementById('loginPassword').value,'test-only-password');
}
mode='ok';await submit();assert.equal(error.hidden,true);assert.equal(d.getElementById('vault').hidden,false);assert.equal(d.querySelector('[data-member-admin]').hidden,true);
logged=false;d.getElementById('logout').click();await settle();isAdmin=true;d.getElementById('loginName').value='sample';d.getElementById('loginPassword').value='test-only-password';await submit();assert.equal(d.querySelector('[data-member-admin]').hidden,false);
assert.deepEqual(errors,[]);w.close();console.log('PASS: inline login failures (empty, 401, 429, network, timeout, JSON/server, cookie), focus, retry, success, admin-only vault link.');
})().catch(e=>{console.error(e);process.exit(1);});
+47
View File
@@ -0,0 +1,47 @@
const fs=require('fs'),assert=require('assert/strict'),path=require('path');
const {JSDOM,VirtualConsole}=require(process.env.JSDOM_PATH||'jsdom');
const root=path.resolve(__dirname,'..'),html=fs.readFileSync(root+'/dist/index.html','utf8'),full=fs.readFileSync(root+'/server/generated/six.js','utf8');
assert.ok(!html.includes('const trop = rom;'),'public HTML must not contain six-field assembly branch');
assert.ok(full.includes('const trop = rom;'),'authenticated module contains assembly');
(async()=>{
let signedIn=false, isAdmin=false, scriptLoads=0;const errors=[],vc=new VirtualConsole();vc.on('jsdomError',e=>errors.push(e.message));
const dom=new JSDOM(html,{url:'https://tama.itosm.co.kr/',runScripts:'dangerously',virtualConsole:vc,beforeParse(w){
w.TextEncoder=TextEncoder;w.TextDecoder=TextDecoder;w.structuredClone=structuredClone;w.AbortSignal=AbortSignal;
w.navigator.serial={requestPort:async()=>({})};
w.fetch=async()=>({ok:true,json:async()=>({authenticated:signedIn,isAdmin,username:'sample',count:0,maxFiles:10,title:'Test',description:'Test',items:[]})});
const append=w.Node.prototype.appendChild;
w.Node.prototype.appendChild=function(el){
if(el.tagName==='SCRIPT'&&el.src.endsWith('/api/member/six.js')){scriptLoads++;setTimeout(()=>{if(signedIn){w.eval(full);el.onload();}else el.onerror();},0);return el;}
return append.call(this,el);
};
}});
const w=dom.window,d=w.document,settle=()=>new Promise(r=>setTimeout(r,50));await settle();
assert.equal(d.getElementById('memberSixShade').hidden,false);assert.equal(d.getElementById('btnSixStart').disabled,true);assert.equal(scriptLoads,0);
assert.equal(d.getElementById('memberRestore').hidden,true);
assert.ok(d.getElementById('memberLink').closest('.bar'));assert.ok(d.getElementById('memberLink').classList.contains('btn'));
assert.ok(d.getElementById('memberSixCard').closest('#device'));
const fake=new w.Uint8Array(16777216);new w.DataView(fake.buffer).setUint32(0xD29000,5,true);
assert.throws(()=>w.ParamixSix.sixApply(fake,null,w.ParamixSix.embedded()),/로그인/);
signedIn=true;w.dispatchEvent(new w.Event('focus'));await settle();
assert.equal(d.getElementById('memberSixShade').hidden,true);assert.equal(d.getElementById('btnSixStart').disabled,true);assert.equal(scriptLoads,1);
assert.equal(d.getElementById('memberRestore').hidden,false);
assert.equal(d.getElementById('memberAdmin').hidden,true);isAdmin=true;w.dispatchEvent(new w.Event('focus'));await settle();assert.equal(d.getElementById('memberAdmin').hidden,false);
w.ParamixFlash.serialOpen=async()=>({close:async()=>{}});
w.ParamixFlash.connect=async()=>({dev:{info:{name:'Tropical',capacity:16777216},read:async()=>{throw Error('mock has no physical device');}}});
d.getElementById('btnDevice').click();await d.getElementById('btnConn').onclick();await settle();
assert.equal(d.getElementById('btnSixStart').disabled,false);
await d.getElementById('btnSixStart').onclick();assert.equal(d.getElementById('deviceSixPanel').hidden,false);
assert.match(d.getElementById('deviceSixStatus').textContent,/ROM을 읽고 백업/);
assert.equal(d.getElementById('btnSixWrite').disabled,true);
assert.throws(()=>w.ParamixSix.sixApply(fake,null,w.ParamixSix.embedded()),/original firmware/);
signedIn=false;w.dispatchEvent(new w.Event('focus'));await settle();assert.equal(d.getElementById('memberSixShade').hidden,false);assert.equal(d.getElementById('btnSixStart').disabled,true);
assert.equal(d.getElementById('deviceSixPanel').hidden,true);assert.equal(d.getElementById('memberRestore').hidden,true);assert.equal(d.getElementById('memberAdmin').hidden,true);
assert.throws(()=>w.ParamixSix.sixApply(fake,null,w.ParamixSix.embedded()),/로그인/);
if(process.argv[2]){
const rom=new w.Uint8Array(fs.readFileSync(process.argv[2]));
assert.equal(w.ParamixSix.kindOf(rom),'jade');assert.equal(w.ParamixSix.sixCan(rom),true);
const four=w.ParamixSix.sixApply(rom,null,w.ParamixSix.embedded());assert.equal(w.ParamixSix.sixInfo(four).kind,'jade');
assert.equal(w.ParamixCore.openRom(four).editionId,4);
}
assert.deepEqual(errors,[]);w.close();console.log('PASS: guest shading, member-only script loading, logout relock, protected generation branch, Jade four-field regression (when ROM supplied). Six-field device output not tested: Tropical/Glacier and donor ROMs unavailable.');
})().catch(e=>{console.error(e);process.exit(1);});
+20
View File
@@ -0,0 +1,20 @@
const fs=require('fs'),assert=require('assert/strict'),crypto=require('crypto');
const {JSDOM,VirtualConsole}=require(process.env.JSDOM_PATH||'jsdom');
const root=require('path').resolve(__dirname,'..');
(async()=>{
let signedIn=false,calls=[];
const errors=[],vc=new VirtualConsole();vc.on('jsdomError',e=>errors.push(e.message));
const dom=new JSDOM(fs.readFileSync(root+'/account.html','utf8'),{url:'https://tama.itosm.co.kr/account.html',runScripts:'outside-only',virtualConsole:vc});
const w=dom.window,d=w.document;w.AbortSignal=AbortSignal;w.confirm=()=>true;
const me={authenticated:true,username:'sample',isAdmin:false,count:1,maxFiles:10,usedBytes:16777216,quotaBytes:167772160,items:[{id:'a'.repeat(32),sha256:'b'.repeat(64),size:16777216,edition:4,name:'제이드 포레스트',label:'<img src=x onerror=alert(1)>',createdAt:new Date().toISOString(),fileUrl:'/api/member/file/'+'a'.repeat(32)}]};
w.fetch=async(url,options={})=>{calls.push(url);let data={ok:true};if(url.endsWith('/register')){signedIn=true;data.recoveryCode='test-recovery-code';}if(url.endsWith('/me'))data=signedIn?me:{authenticated:false};if(url.endsWith('/logout'))signedIn=false;return{ok:true,status:200,json:async()=>data};};
w.eval(fs.readFileSync(root+'/account.js','utf8'));const settle=()=>new Promise(r=>setTimeout(r,25));await settle();
assert.equal(d.getElementById('authPanels').hidden,false);assert.equal(d.getElementById('vault').hidden,true);
d.getElementById('registerName').value='sample';d.getElementById('registerPassword').value='long-test-password';d.getElementById('registerRepeat').value='different';
d.getElementById('registerForm').dispatchEvent(new w.Event('submit',{cancelable:true}));await settle();assert.equal(calls.includes('/api/member/register'),false);
d.getElementById('registerRepeat').value='long-test-password';d.getElementById('registerForm').dispatchEvent(new w.Event('submit',{cancelable:true}));await settle();
assert.equal(d.getElementById('vault').hidden,false);assert.equal(d.getElementById('recoveryCode').textContent,'test-recovery-code');assert.match(d.getElementById('usage').textContent,/1 \/ 10개/);assert.match(d.getElementById('usage').textContent,/16 \/ 160 MiB/);
assert.equal(d.getElementById('files').querySelector('img'),null);assert.ok(d.getElementById('files').querySelector('a[href="/?backup='+me.items[0].id+'"]'));
d.getElementById('logout').click();await settle();assert.equal(d.getElementById('vault').hidden,true);assert.equal(d.getElementById('recoveryCode').textContent,'');assert.deepEqual(errors,[]);w.close();
console.log('PASS: optional login, signup validation, recovery-code display, 10-file capacity, private file controls, safe rendering, logout clears private UI');
})().catch(e=>{console.error(e);process.exit(1);});
+131
View File
@@ -0,0 +1,131 @@
import concurrent.futures
import unittest
from archive_test import ArchiveTests, app, fixture
class MemberTests(unittest.TestCase):
setUp = ArchiveTests.setUp
tearDown = ArchiveTests.tearDown
request = ArchiveTests.request
login = ArchiveTests.login
def signup(self, name):
code, result, headers = self.request('/api/member/register', {'username': name, 'password': 'member-test-password'})
self.assertEqual(code, 200, result)
return headers['Set-Cookie'].split(';')[0], result['recoveryCode']
def upload(self, cookie, marker=0):
return self.request('/api/member/files', fixture(4, marker), cookie=cookie, binary=True)
def test_ownership_duplicate_download_and_delete(self):
alice, _ = self.signup('alice_test')
bob, _ = self.signup('bob_test')
code, file, _ = self.upload(alice)
self.assertEqual(code, 200)
file_id = file['id']
self.assertEqual(self.upload(alice)[1]['status'], 'duplicate')
me = self.request('/api/member/me', cookie=alice)[1]
self.assertEqual(me['quotaBytes'], 10 * app.SIZE)
self.assertEqual(me['count'], 1)
url = '/api/member/file/' + file_id
self.assertEqual(self.request(url)[0], 401)
self.assertEqual(self.request(url, cookie=bob)[0], 404)
self.assertEqual(self.request(url, cookie=alice)[1], fixture(4))
self.assertEqual(self.request('/api/member/file', {'id': file_id, 'label': 'intrusion'}, cookie=bob)[0], 404)
self.assertEqual(self.request('/api/member/file', {'id': file_id, 'action': 'delete'}, cookie=bob)[0], 404)
self.assertEqual(self.request('/api/file/' + file['sha256'])[0], 404)
self.assertEqual(app.records(), [])
self.assertEqual(self.request('/api/member/file', {'id': file_id, 'label': 'My first dump'}, cookie=alice)[0], 200)
self.assertEqual(self.request('/api/member/file', {'id': file_id, 'action': 'delete'}, cookie=alice)[0], 200)
self.assertEqual(self.request('/api/member/me', cookie=alice)[1]['count'], 0)
def test_ten_dump_limit_and_concurrent_eleventh(self):
cookie, _ = self.signup('quota_test')
for marker in range(9):
self.assertEqual(self.upload(cookie, marker)[0], 200)
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
results = list(executor.map(lambda marker: self.upload(cookie, marker)[0], [9, 10]))
self.assertEqual(sorted(results), [200, 400])
me = self.request('/api/member/me', cookie=cookie)[1]
self.assertEqual(me['count'], 10)
self.assertEqual(me['usedBytes'], 160 * 1048576)
self.assertEqual(self.upload(cookie, 20)[0], 400)
self.request('/api/member/file', {'id': me['items'][0]['id'], 'action': 'delete'}, cookie=cookie)
self.assertEqual(self.upload(cookie, 20)[0], 200)
def test_signup_recovery_password_and_persistence(self):
cookie, recovery = self.signup('recover_test')
self.assertEqual(self.request('/api/member/register', {'username': 'RECOVER_TEST', 'password': 'member-test-password'})[0], 400)
self.assertEqual(self.request('/api/member/register', {'username': '../bad', 'password': 'member-test-password'})[0], 400)
self.assertEqual(self.request('/api/member/register', {'username': 'test_admin', 'password': 'short'})[0], 400)
self.upload(cookie)
app.MEMBERS = None # Simulated process recreation: sessions and files are on disk.
self.assertEqual(self.request('/api/member/me', cookie=cookie)[1]['count'], 1)
code, result, headers = self.request('/api/member/recover', {'username': 'recover_test', 'recoveryCode': recovery, 'newPassword': 'new-member-password'})
self.assertEqual(code, 200)
self.assertNotEqual(recovery, result['recoveryCode'])
self.assertFalse(self.request('/api/member/me', cookie=cookie)[1]['authenticated'])
self.assertEqual(self.request('/api/member/recover', {'username': 'recover_test', 'recoveryCode': recovery, 'newPassword': 'new-member-password'})[0], 400)
new_cookie = headers['Set-Cookie'].split(';')[0]
self.assertEqual(self.request('/api/member/password', {'currentPassword': 'new-member-password', 'newPassword': 'third-member-password'}, cookie=new_cookie)[0], 200)
self.assertFalse(self.request('/api/member/me', cookie=new_cookie)[1]['authenticated'])
code, _, headers = self.request('/api/member/login', {'username': 'recover_test', 'password': 'third-member-password'})
self.assertEqual(code, 200)
final_cookie = headers['Set-Cookie'].split(';')[0]
self.assertEqual(self.request('/api/member/delete-account', {'currentPassword': 'third-member-password'}, cookie=final_cookie)[0], 200)
with app.members().db() as db:
self.assertEqual(db.execute('SELECT COUNT(*) FROM files').fetchone()[0], 0)
def test_admin_controls_csrf_and_guest_unchanged(self):
cookie, _ = self.signup('control_test')
self.assertEqual(self.request('/api/member/files', b'untrusted request', cookie=cookie, origin=False, binary=True)[0], 403)
self.assertEqual(self.request('/api/admin/members', cookie=cookie)[0], 401)
admin = self.login()
me = self.request('/api/admin/members', cookie=admin)[1]['items'][0]
self.assertEqual(self.request('/api/admin/members', {'id': me['id'], 'slots': 2, 'disabled': False}, cookie=admin)[0], 200)
self.assertEqual(self.request('/api/member/me', cookie=cookie)[1]['maxFiles'], 2)
self.assertEqual(self.request('/api/admin/members', {'id': me['id'], 'slots': 2, 'disabled': True}, cookie=admin)[0], 200)
self.assertFalse(self.request('/api/member/me', cookie=cookie)[1]['authenticated'])
self.request('/api/admin/members', {'action': 'settings', 'enabled': False, 'totalMB': 160}, cookie=admin)
self.assertEqual(self.request('/api/member/register', {'username': 'blocked_signup', 'password': 'member-test-password'})[0], 400)
self.assertEqual(self.request('/api/catalog')[0], 200)
self.assertEqual(self.request('/api/backup-status')[0], 200)
self.assertEqual(self.request('/api/backups', fixture(4), binary=True)[1]['status'], 'stored')
self.assertFalse(self.request('/api/member/me')[1]['authenticated'])
def test_global_budget_and_logout(self):
cookie, _ = self.signup('global_test')
with app.members().db() as db: db.execute('UPDATE settings SET total_mb=16 WHERE id=1')
self.assertEqual(self.upload(cookie)[0], 200)
other, _ = self.signup('another_test')
self.assertEqual(self.upload(other, 2)[0], 400)
self.assertEqual(self.request('/api/member/logout', {}, cookie=cookie)[0], 200)
self.assertFalse(self.request('/api/member/me', cookie=cookie)[1]['authenticated'])
def test_admin_personal_vault_does_not_grant_admin_session(self):
self.cfg['username'] = 'owner_test'
app.atomic_json(app.DATA / 'config.json', self.cfg)
code, _, headers = self.request('/api/member/login', {'username': 'owner_test', 'password': 'test-only-password'})
self.assertEqual(code, 200)
cookie = headers['Set-Cookie'].split(';')[0]
self.assertTrue(self.request('/api/member/me', cookie=cookie)[1]['isAdmin'])
self.assertEqual(self.request('/api/admin/state', cookie=cookie)[0], 401)
self.assertEqual(self.request('/api/member/delete-account', {'currentPassword': 'test-only-password'}, cookie=cookie)[0], 400)
_, _, headers = self.request('/api/login', {'username': 'owner_test', 'password': 'test-only-password'})
admin = headers['Set-Cookie'].split(';')[0]
self.assertEqual(self.request('/api/admin/password', {'currentPassword': 'test-only-password', 'newPassword': 'changed-admin-password'}, cookie=admin)[0], 200)
self.assertFalse(self.request('/api/member/me', cookie=cookie)[1]['authenticated'])
def test_six_module_requires_current_membership(self):
self.assertEqual(self.request('/api/member/six.js')[0], 401)
cookie, _ = self.signup('six_test')
status, code, headers = self.request('/api/member/six.js', cookie=cookie)
self.assertEqual(status, 200)
self.assertIn(b'const trop = rom;', code)
self.assertIn('no-store', headers['Cache-Control'])
self.request('/api/member/logout', {}, cookie=cookie)
self.assertEqual(self.request('/api/member/six.js', cookie=cookie)[0], 401)
if __name__ == '__main__':
unittest.main(verbosity=2)
+50
View File
@@ -0,0 +1,50 @@
const fs=require('fs'),assert=require('assert/strict'),path=require('path');
const C=require('../src/core.js'),F=require('../src/feld.js'),E=require('../src/emu.js'),S=require('../src/saves.js');require('../src/menu-font-ko.js');
const read=p=>new Uint8Array(fs.readFileSync(p)),rom=read(process.argv[2]),ctx=C.openRom(rom),defs=C.charTable(ctx.files[0]);
const u32=(b,o)=>new DataView(b.buffer,b.byteOffset,b.byteLength).getUint32(o,true);
const ghost=0xDEE000, original=rom.slice(), petId=new DataView(rom.buffer).getUint16(ghost+0x10a,true),def=defs.find(c=>c.id===petId);
assert.equal(C.textGet(rom,1,'ko'),'정보');assert.equal(C.textGet(rom,14,'ko'),'육지');
assert.equal(C.KO_CHARS.length,2350);
assert.throws(()=>C.textClean('힣','ko'),/지원/);
const edits=new Map([[14,'한글나라'],[def.name,'한글이']]),out=C.textApply(rom,edits,'ko');
assert.equal(C.textGet(out,14,'ko'),'한글나라');assert.equal(C.textGet(out,def.name,'ko'),'한글이');
assert.equal(C.textGet(out,14,'en'),C.textGet(rom,14,'en'));
assert.deepEqual(rom,original);
assert.equal((u32(out,ghost)+u32(out,ghost+4))>>>0,0);
let delta=0;for(let i=8;i<0x180;i+=4)delta=(delta+u32(out,ghost+i)-u32(rom,ghost+i))>>>0;
assert.equal(u32(out,ghost),(u32(rom,ghost)+delta)>>>0);
const decodeName=b=>{let s='';for(let i=0;i<26;i+=2){const k=b[i]|b[i+1]<<8;if(!k)break;s+=C.KO_CHARS[k-481]||'?';}return s;};
assert.equal(decodeName(out.subarray(ghost+226,ghost+252)),'한글이');
const save={pages:S.paraFromImage(rom,ctx.editionId),edition:ctx.editionId};
const newer=S.paraPetSet(save,ctx.editionId,{happy:20,hunger:6});
assert.equal(S.paraPet(newer,ctx.editionId).happy,20);
assert.throws(()=>S.paraPetSet(save,ctx.editionId,{happy:21}),/범위/);
const live=rom.slice();for(const[a,d]of newer.pages)live.set(d,a);
async function main(){
const changed=new Set([ghost]),base=async()=>({image:live,notes:[],kept:1,protectedSectors:[ghost]});
const merged=await S.keepEdits(base,ctx.editionId,new Map([[petId,'한글이']]),{hunger:5},petId)(null,out,changed);
const p=S.paraPet({pages:S.paraFromImage(merged.image,ctx.editionId)},ctx.editionId);
assert.equal(p.happy,20);assert.equal(p.hunger,5);assert.equal(decodeName(merged.image.subarray(ghost+226,ghost+252)),'한글이');
assert(!merged.protectedSectors.includes(ghost));assert(changed.has(ghost));
await assert.rejects(()=>S.keepEdits(base,ctx.editionId,null,{hunger:5},9999)(null,out,changed),/다릅니다/);
const chars=F.characters(out,'ko'),items=F.itemCatalog(out,'ko');
assert(chars.length>60);assert(chars.every(c=>/[가-힣]/.test(c.name)));
assert(items.filter(c=>/[가-힣]/.test(c.name)).length>=264);
assert.equal(items.find(c=>c.id===7059).name,'GASHAPON'); // Official Korean table uses the brand in Latin letters.
const emb={feld:read(path.join(__dirname,'../feld/feld-ko.bin')),stub:read(path.join(__dirname,'../feld/stub_feld_tpl.bin'))};
const built=F.feldApply(out,{fields:true,bag:true,tama:true,saves:true},null,emb,E);
const image=built.rom||built,info=F.feldFind(image,emb.stub);assert(info);assert(Buffer.from(image.subarray(info.off,info.off+0x8000)).includes(Buffer.from('ITOSM_KO_MENU_V1')));
const cat=info.catOff,n=u32(image,cat+4),font=cat+12+40*n;assert.equal(u32(image,font),0x31464f4b);
assert.equal(u32(image,font+4),2527);
const names=font+8+13*2527;let portraits=0;
for(let i=0;i<n;i++)if(u32(image,names+26*n+4*i))portraits++;
assert(portraits>=60,'Character pictures missing: '+portraits);
const stripped=F.feldStrip(image,emb,E);assert(stripped.subarray(cat,cat+4096).every(b=>b===255));
assert.deepEqual(stripped.subarray(0xD49000),out.subarray(0xD49000),'Menu removal changed device saves');
const rebuilt=F.feldApply(stripped,{fields:true,bag:true,tama:true,saves:true},null,emb,E);assert.deepEqual(rebuilt,image,'Menu rebuild round trip');
const fieldsOnly=F.feldApply(out,{fields:true},null,emb,E),fo=F.feldFind(fieldsOnly,emb.stub);
assert(F.feldStrip(fieldsOnly,emb,E).subarray(fo.catOff,fo.catOff+4096).every(b=>b===255),'Font-only catalog removal');
if(process.argv[3]){fs.writeFileSync(process.argv[3],image);fs.writeFileSync(process.argv[3]+'.json',JSON.stringify(info));}
console.log(JSON.stringify({passed:true,characters:chars.length,items:items.length,portraits,menuBytes:emb.feld.length,keptLatestHappiness:p.happy,physicalDevice:false}));
}
main().catch(e=>{console.error(e);process.exit(1);});
+383
View File
@@ -0,0 +1,383 @@
{
"name": "test",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"dependencies": {
"jsdom": "^31.0.0",
"playwright": "^1.56.1"
}
},
"node_modules/@exodus/bytes": {
"version": "1.16.0",
"resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz",
"integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==",
"license": "MIT",
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
},
"peerDependencies": {
"@noble/hashes": "^1.8.0 || ^2.0.0"
},
"peerDependenciesMeta": {
"@noble/hashes": {
"optional": true
}
}
},
"node_modules/bcp-47": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/bcp-47/-/bcp-47-2.1.2.tgz",
"integrity": "sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg==",
"license": "MIT",
"dependencies": {
"is-alphabetical": "^2.0.0",
"is-alphanumerical": "^2.0.0",
"is-decimal": "^2.0.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/bcp-47-match": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-2.0.3.tgz",
"integrity": "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/data-urls": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz",
"integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==",
"license": "MIT",
"dependencies": {
"whatwg-mimetype": "^5.0.0",
"whatwg-url": "^17.1.2"
},
"engines": {
"node": "^22.14.0 || >=24.0.0"
}
},
"node_modules/decimal.js": {
"version": "10.6.0",
"resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
"integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
"license": "MIT"
},
"node_modules/entities": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz",
"integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=20.19.0"
},
"funding": {
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/html-encoding-sniffer": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz",
"integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==",
"license": "MIT",
"dependencies": {
"@exodus/bytes": "^1.15.1"
},
"engines": {
"node": "^22.13.0 || >=24.0.0"
}
},
"node_modules/is-alphabetical": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz",
"integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/is-alphanumerical": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz",
"integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==",
"license": "MIT",
"dependencies": {
"is-alphabetical": "^2.0.0",
"is-decimal": "^2.0.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/is-decimal": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz",
"integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/is-potential-custom-element-name": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
"integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
"license": "MIT"
},
"node_modules/jsdom": {
"version": "31.0.0",
"resolved": "https://registry.npmjs.org/jsdom/-/jsdom-31.0.0.tgz",
"integrity": "sha512-xAkhD9z1eyFC5+QUi9K24CaZJgdCQ2GOGLW1GdVDoQvkp/AxEH9TQ0pAplPOlIiV92hfcgnFOADZypbjgbBT6Q==",
"license": "MIT",
"dependencies": {
"@exodus/bytes": "^1.16.0",
"bcp-47": "^2.1.2",
"bcp-47-match": "^2.0.3",
"data-urls": "^8.0.0",
"decimal.js": "^10.6.0",
"html-encoding-sniffer": "^7.0.0",
"is-potential-custom-element-name": "^1.0.1",
"lru-cache": "^11.5.3",
"parse5": "^8.1.0",
"parse5-parser-stream": "^8.1.0",
"saxes": "^6.0.0",
"tough-cookie": "^6.0.2",
"undici": "^8.12.3",
"w3c-xmlserializer": "^6.0.0",
"webidl-conversions": "^8.0.1",
"whatwg-mimetype": "^5.0.0",
"whatwg-url": "^17.3.0",
"xml-name-validator": "^5.0.0"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
"peerDependencies": {
"@napi-rs/canvas": "^1.0.13"
},
"peerDependenciesMeta": {
"@napi-rs/canvas": {
"optional": true
}
}
},
"node_modules/lru-cache": {
"version": "11.5.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
"integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
"license": "BlueOak-1.0.0",
"engines": {
"node": "20 || >=22"
}
},
"node_modules/parse5": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz",
"integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==",
"license": "MIT",
"dependencies": {
"entities": "^9.0.0"
},
"funding": {
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/parse5-parser-stream": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-8.1.1.tgz",
"integrity": "sha512-hMcVbbUJcQmP8rURWUdYrT1flRiBiBVjq/RYGguJpDUgIXSqdYKlE0CxthmdMWoSlBAuL5bUBa73g0pttSy7Hw==",
"license": "MIT",
"dependencies": {
"parse5": "^8.1.1"
},
"funding": {
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/playwright": {
"version": "1.56.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.56.1.tgz",
"integrity": "sha512-aFi5B0WovBHTEvpM3DzXTUaeN6eN0qWnTkKx4NQaH4Wvcmc153PdaY2UBdSYKaGYw+UyWXSVyxDUg5DoPEttjw==",
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.56.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.56.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.1.tgz",
"integrity": "sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==",
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/saxes": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
"integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
"license": "ISC",
"dependencies": {
"xmlchars": "^2.2.0"
},
"engines": {
"node": ">=v12.22.7"
}
},
"node_modules/tldts": {
"version": "7.4.19",
"resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.19.tgz",
"integrity": "sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==",
"license": "MIT",
"dependencies": {
"tldts-core": "^7.4.19"
},
"bin": {
"tldts": "bin/cli.js"
}
},
"node_modules/tldts-core": {
"version": "7.4.20",
"resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.20.tgz",
"integrity": "sha512-C630TWXZCZmLq0F2bW4QqwnaaxCQ/svpAqvJwnC4JvgEM5ohhBnGsEzTLSOXcN+xjz+kEaHS5uoWIw2klnqd0A==",
"license": "MIT"
},
"node_modules/tough-cookie": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.1.0.tgz",
"integrity": "sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==",
"license": "BSD-3-Clause",
"dependencies": {
"tldts": "^7.0.5"
},
"engines": {
"node": ">=16"
}
},
"node_modules/tr46": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz",
"integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==",
"license": "MIT",
"dependencies": {
"punycode": "^2.3.1"
},
"engines": {
"node": "^22.14.0 || >=24.0.0"
}
},
"node_modules/undici": {
"version": "8.12.4",
"resolved": "https://registry.npmjs.org/undici/-/undici-8.12.4.tgz",
"integrity": "sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==",
"license": "MIT",
"engines": {
"node": ">=22.19.0"
}
},
"node_modules/w3c-xmlserializer": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz",
"integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==",
"license": "MIT",
"dependencies": {
"xml-name-validator": "^5.0.0"
},
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}
},
"node_modules/webidl-conversions": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",
"integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=20"
}
},
"node_modules/whatwg-mimetype": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",
"integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==",
"license": "MIT",
"engines": {
"node": ">=20"
}
},
"node_modules/whatwg-url": {
"version": "17.3.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz",
"integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==",
"license": "MIT",
"dependencies": {
"@exodus/bytes": "^1.16.0",
"tr46": "^7.0.0",
"webidl-conversions": "^8.0.1"
},
"engines": {
"node": "^22.14.0 || >=24.0.0"
}
},
"node_modules/xml-name-validator": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
"integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
"license": "Apache-2.0",
"engines": {
"node": ">=18"
}
},
"node_modules/xmlchars": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
"integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
"license": "MIT"
}
}
}
+6
View File
@@ -0,0 +1,6 @@
{
"dependencies": {
"jsdom": "^31.0.0",
"playwright": "^1.56.1"
}
}
+32
View File
@@ -0,0 +1,32 @@
// 1.7.3 PokeMiniEmu: Pokemon mini games into the menu, with and without an own BIOS; everything reads back; the
// program image in the flash has its settings block filled in.
// node test/pm_test.js <land.bin> <game.min> [<bios.min>]
const fs = require('fs'), S = __dirname + '/../';
const C = require(S + 'src/core.js'), E = require(S + 'src/emu.js'), F = require(S + 'src/feld.js');
const rd = (p) => new Uint8Array(fs.readFileSync(p));
const [land, game, bios] = process.argv.slice(2);
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const u32 = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0;
const fe = { feld: rd(S + 'feld/feld.bin'), stub: rd(S + 'feld/stub_feld_tpl.bin') };
const progs = { pm: rd(S + 'pm/pm.bin') };
const ctx = C.openRom(rd(land)); const base = C.buildRom(ctx, C.launcherChanges(ctx)).rom;
const R = rd(game), B = bios ? rd(bios) : null;
ok(E.pmDetect(R) && !E.gbDetect(R), 'Pokemon mini game recognised');
ok(!B || E.pmBiosDetect(B), 'BIOS recognised');
const xs = [{ kind: 'pm', rom: R, title: E.pmTitle('Pokemon Pinball Mini (USA, Europe).min'), keys: E.PM_KEYS_DEFAULT.slice(), inv: true, bios: B }];
const r = E.appsPlace(base, xs, progs, { launch: true, dlApp: rd(S + 'flash/flashapp.bin') });
const m = F.feldApply(r.rom, { launch: true, apps: r.list, dl: r.dl }, [], fe, E);
const back = E.appsRead(m, F.feldApps(m, fe.stub).apps);
const b0 = back.find((x) => x.kind === 'pm');
ok(!!b0 && Buffer.compare(Buffer.from(b0.rom), Buffer.from(R)) === 0, 'game the same after reading back');
const c = b0.off + 0x140;
ok(u32(m, c) === E.PM_MAGIC && u32(m, c + 8) % 0x10000 === 0, 'settings block, game 64 KB aligned at ' + u32(m, c + 8).toString(16));
ok(b0.title === 'PINBALL MINI', 'name ' + b0.title);
ok(JSON.stringify(b0.keys) === JSON.stringify(E.PM_KEYS_DEFAULT), 'keys ' + b0.keys.join(','));
const fl = u32(m, c + 20);
if (B) ok((fl & 4) && Buffer.compare(Buffer.from(m.subarray(u32(m, c + 64), u32(m, c + 64) + 0x1000)), Buffer.from(B)) === 0 && b0.bios && b0.bios.length === 0x1000, 'own BIOS in the save area');
else ok(!(fl & 4) && u32(m, c + 64) === 0, 'free BIOS');
ok(Buffer.compare(Buffer.from(m.subarray(b0.off, b0.off + 0x140)), Buffer.from(progs.pm.subarray(0, 0x140))) === 0, 'program: PokeMiniEmu');
const again = E.appsPlace(E.appsClear(m, back), back, progs, { launch: true, dlApp: rd(S + 'flash/flashapp.bin') });
ok(!!again.rom, 'placed again from what was read');
console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
+30
View File
@@ -0,0 +1,30 @@
// Tests the core on real images: lossless rebuild, decoding,
// pixel-exact re-encoding of all sprites. Usage: node test/rom_test.js <rom...>
const C = require('../src/core.js');
const fs = require('fs');
function same(a, b) { if (a.w !== b.w || a.h !== b.h) return false; for (let i = 0; i < a.data.length; i += 4) { const ta = a.data[i + 3] < 128, tb = b.data[i + 3] < 128; if (ta !== tb) return false; if (ta) continue; for (let k = 0; k < 3; k++) if (Math.abs(a.data[i + k] - b.data[i + k]) > 2) return false; } return true; }
let fail = 0;
for (const f of process.argv.slice(2)) {
const rom = new Uint8Array(fs.readFileSync(f));
const t0 = Date.now();
const ctx = C.openRom(rom);
const id = C.buildRom(ctx, new Map());
const identical = Buffer.compare(Buffer.from(id.rom), Buffer.from(rom)) === 0;
let dec = 0, rt = 0, rtKeep = 0, bad = [], badK = [];
const sample = process.env.ALL ? ctx.entries.length : Math.min(ctx.entries.length, 400);
for (let i = 0; i < ctx.entries.length; i++) {
const e = ctx.entries[i];
const d = C.spriteDecode(e); dec++;
if (i >= sample && !ctx.groups.includes(i)) continue;
if (d.cells.length > 3000) continue; // fonts: slow, same code
const enc = C.spriteEncode(e, d.subs, {});
const d2 = C.spriteDecode(enc);
if (d2.subs.every((s, k) => same(s, d.subs[k]))) rt++; else bad.push(i);
const encK = C.spriteEncode(e, d.subs, { keepPalette: true });
const d3 = C.spriteDecode(encK);
if (d3.subs.every((s, k) => same(s, d.subs[k]))) rtKeep++; else badK.push(i);
}
console.log(f.split('/').pop(), ctx.edition, 'sprites', ctx.entries.length, 'groups', ctx.groups.length, 'identical', identical, 'decoded', dec, 'roundtrip ok', rt, 'bad', bad.slice(0, 10), 'keep ok', rtKeep, 'badK', badK.slice(0, 10), 'free KB', (ctx.limit - ctx.assetEnd) >> 10, (Date.now() - t0) + 'ms');
if (!identical || bad.length || badK.length) fail++;
}
process.exit(fail ? 1 : 0);
+39
View File
@@ -0,0 +1,39 @@
// Save games against the emulated Paradise (UART bridge, see flash_bridge_test.js).
// node test/save_bridge_test.js <bridge-binary> <firmware.bin>
const { spawn } = require('child_process');
const fs = require('fs');
const FL = require('../src/flash.js'), SV = require('../src/saves.js');
const [bridge, fwFile] = process.argv.slice(2);
const app = new Uint8Array(fs.readFileSync(__dirname + '/../flash/flashapp.bin'));
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'WRONG ') + m); if (!c) bad++; };
(async () => {
const out = '/tmp/claude-0/bridge_save.bin';
const p = spawn(bridge, [fwFile, out], { stdio: ['pipe', 'pipe', 'inherit'] });
const io = { onData: null, write: (d) => new Promise((r) => p.stdin.write(Buffer.from(d), r)) };
p.stdout.on('data', (d) => io.onData && io.onData(new Uint8Array(d)));
await new Promise((r) => setTimeout(r, 15000));
const { dev } = await FL.connect(io, app, { timeScale: 20 }, () => {});
const ed = dev.info.edition, [a, b] = SV.region(ed);
ok(ed >= 1 && ed <= 6, 'edition ' + ed);
const clock = await dev.clockRead();
ok(clock && typeof clock.counter === 'number', 'clock read: ' + JSON.stringify(clock));
let t0 = Date.now();
const used = await dev.usedSectors(a, b);
ok(used.length > 0, 'used save sectors: ' + used.length + ' (' + ((Date.now() - t0) / 1000).toFixed(1) + ' s)');
const base = new Uint8Array(fs.readFileSync(fwFile));
const exp = []; for (let s = a; s < b; s += 0x1000) { let ff = true; for (let i = s; i < s + 0x1000; i++) if (base[i] !== 0xFF) { ff = false; break; } if (!ff) exp.push(s); }
ok(exp.every((s) => used.includes(s)), 'every used sector of the image found (device ' + used.length + ', image ' + exp.length + ')');
// write two pages of a save, set the clock
const map = new Map(); const pg = new Uint8Array(0x1000).fill(0x5A); map.set(0xE10000, pg); map.set(0xE11000, new Uint8Array(0x1000).fill(0xFF));
t0 = Date.now();
const w = await dev.writeSectors(map);
const r1 = await dev.read(0xE10000, 0x1000);
ok(w === 2 && r1.every((v) => v === 0x5A), 'two pages written w=' + w + ' r=' + r1[0] + ' len=' + r1.length + ' (' + ((Date.now() - t0) / 1000).toFixed(1) + ' s)');
const set = await dev.clockSet(1234567);
const c2 = await dev.clockRead();
ok(set && c2 && c2.counter - 1234567 < 5, 'clock set: ' + JSON.stringify(c2));
p.stdin.end(); await new Promise((r) => p.on('exit', r));
const fl = new Uint8Array(fs.readFileSync(out));
ok(fl[0xE10000] === 0x5A && fl.subarray(0x200000, 0x300000).every((v, i) => v === base[0x200000 + i]), 'device flash: page written, the rest untouched');
console.log(bad ? bad + ' wrong' : 'all good'); process.exit(bad ? 1 : 0);
})().catch((e) => { console.error(e); process.exit(1); });
+13
View File
@@ -0,0 +1,13 @@
const SV = require('../src/saves.js'); const assert = require('assert');
let img = new Uint8Array(16 << 20).fill(0xFF);
assert.strictEqual(SV.t7SaveOut(img), null);
const sv = new Uint8Array(4098); sv[0] = 0x05; for (let i = 2; i < 4098; i++) sv[i] = i * 7 & 255;
img = SV.t7SaveIn(img, sv);
assert.deepStrictEqual(SV.t7SaveOut(img), sv);
const sv2 = sv.slice(); sv2[100] ^= 0x55; sv2[0] = 0x07;
img = SV.t7SaveIn(img, sv2); // goes into the other slot with a higher sequence
assert.deepStrictEqual(SV.t7SaveOut(img), sv2);
img = SV.t7SaveIn(img, sv); // back into slot A
assert.deepStrictEqual(SV.t7SaveOut(img), sv);
assert.ok(img.subarray(0xC0000, 0xC1000).every(v => v === 0xFF));
console.log('saves_t7 ok');
+55
View File
@@ -0,0 +1,55 @@
// Save games out of and into the Paradise: .tamasave (TamaParadise app) and .sav (TamaEmu app).
// node test/saves_test.js <paradise_water.bin> <paradise_glacier.bin> <idl_firmware.bin> [out_dir]
const fs = require('fs');
const C = require('../src/core.js'); globalThis.ParamixCore = C;
const S = require('../src/saves.js'), E = require('../src/emu.js');
const rd = (p) => new Uint8Array(fs.readFileSync(p));
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'WRONG ') + m); if (!c) bad++; };
const [waterF, glacF, idlF, out] = process.argv.slice(2);
const water = rd(waterF), glac = rd(glacF);
(async () => {
// Paradise
const pages = S.paraFromImage(water, 2);
const file = S.paraEncode(pages, 2, { counter: 123456, ctrl: 0xE0 }, 1700000000);
const sv = S.paraDecode(file);
ok(sv.pages.size === pages.size && [...pages].every(([a, d]) => Buffer.compare(Buffer.from(d), Buffer.from(sv.pages.get(a))) === 0), 'Paradise: pages back (' + pages.size + ')');
ok(sv.counter === 123456 && sv.stamp === 1700000000 && sv.edition === 2 && sv.alarm === 123455 && sv.status === 0x100, 'Paradise: clock and edition');
const c1 = S.paraCheck(sv, 2);
ok(!c1.errors.length && c1.complete, 'Paradise: fits Water ' + JSON.stringify(c1.errors));
ok(S.paraCheck(sv, 1).errors.some((e) => e.code === 'saveOtherEd'), 'Paradise: refused on Land');
ok(S.paraCheck(Object.assign({}, sv, { edition: 0 }), 6).errors.some((e) => e.code === 'saveFamily'), 'Paradise: without trailer, Glacier device refuses a Water save');
const g = S.paraDecode(S.paraEncode(S.paraFromImage(glac, 6), 6, null));
ok(!S.paraCheck(Object.assign({}, g, { edition: 0 }), 6).errors.length && S.paraCheck(Object.assign({}, g, { edition: 0 }), 2).errors.some((e) => e.code === 'saveFamily'), 'Paradise: Glacier save fits Glacier, not Water');
ok(S.paraClock(sv, 1700000100) === 123556, 'Paradise: clock moves on with the time since');
const part = Object.assign({}, sv, { pages: new Map([...sv.pages].filter(([a]) => a >= 0xEF0000)) });
const c2 = S.paraCheck(part, 2); ok(!c2.errors.length && !c2.complete && c2.warnings.some((w) => w.code === 'saveIncomplete'), 'Paradise: partial save gives a warning');
if (out) fs.writeFileSync(out + '/water.tamasave', file);
// TamaEmu
const guest = rd(idlF), app = rd(__dirname + '/../emu/emu.bin'), stub = rd(__dirname + '/../emu/stub_tpl.bin');
const rom = E.emuPatch(rd(process.argv[2]), guest, app, stub).rom;
const cfg = S.emuCfg(rom.subarray(0xA0000, 0xA1000));
ok(cfg && cfg.dev === 'idl' && cfg.size === 0x800000, 'TamaEmu: settings read');
let g1 = await S.emuGuestAsync((a, n) => rom.subarray(a, a + n), cfg);
const fwPad = new Uint8Array(0x800000).fill(0xFF); fwPad.set(guest.subarray(0, 0x800000));
ok(Buffer.compare(Buffer.from(g1), Buffer.from(fwPad)) === 0, 'TamaEmu: unchanged ROM gives the firmware back');
// the device played: a packed block changed, a spare page for an empty block
const dev = new Uint8Array(rom);
const b0 = [...cfg.map].findIndex((k) => k !== 0xFF && k !== 0xFE); const k0 = cfg.map[b0];
dev.fill(0x42, cfg.guestOff + (k0 << 16) + 0x1000, cfg.guestOff + (k0 << 16) + 0x2000);
const empty = [...cfg.map.subarray(0, 128)].findIndex((k, i) => k === 0xFF && i > 4);
const lo = (cfg.guestOff + cfg.guestSize + 0x1FFF) & ~0x1FFF, data = lo + 0x2000, n = Math.min(64, ((cfg.spareEnd & ~0x1FFF) - data) >> 13);
const t = new Uint8Array(16 + 128).fill(0xFF); const vp = (empty << 16) >> 13;
const w32 = (b, o, v) => { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; };
t[16] = vp & 255; t[17] = vp >> 8;
let x = (0x50584D50 ^ Math.imul(n, 0x9E3779B1)) >>> 0; for (let i = 0; i < 64; i++) x = (((x << 5) | (x >>> 27)) ^ (t[16 + 2 * i] | (t[17 + 2 * i] << 8))) >>> 0;
w32(t, 0, 0x50584D50); w32(t, 4, n); w32(t, 8, x); w32(t, 12, 0);
dev.fill(0xFF, lo, lo + 0x1000); dev.set(t, lo); dev.fill(0x77, data, data + 0x2000);
const g2 = await S.emuGuestAsync((a, n2) => dev.subarray(a, a + n2), cfg);
ok(g2[(b0 << 16) + 0x1800] === 0x42 && g2[(empty << 16) + 0x100] === 0x77 && g2[(empty << 16) + 0x2100] === 0xFF, 'TamaEmu: written block and spare page are in the .sav');
ok(E.emuDetect(g2) === 'idl', 'TamaEmu: the .sav is recognised as a firmware again');
const back = E.emuPatch(rd(process.argv[2]), g2, app, stub).rom;
const g3 = await S.emuGuestAsync((a, n2) => back.subarray(a, a + n2), S.emuCfg(back.subarray(0xA0000, 0xA1000)));
ok(Buffer.compare(Buffer.from(g3), Buffer.from(g2)) === 0, 'TamaEmu: .sav into the ROM and out again is the same');
if (out) fs.writeFileSync(out + '/idl.sav', g2);
console.log(bad ? bad + ' WRONG' : 'all good'); process.exit(bad ? 1 : 0);
})();
+21
View File
@@ -0,0 +1,21 @@
const fs=require('fs'),vm=require('vm'),assert=require('assert/strict'),crypto=require('crypto');
const img=new Uint8Array([1,2,3,4]),sha=crypto.createHash('sha256').update(img).digest('hex');
let fail=true,mode='server',calls=[],downloads=[];
const ctx={window:{},location:{protocol:'https:'},crypto:crypto.webcrypto,Uint8Array,DataView,AbortSignal,fetch:async(path,opts={})=>{
calls.push(path);
if(path==='/api/backup-status')return{ok:true,json:async()=>({mode,retentionHours:24})};
if(path==='/api/device-backups'){if(fail)throw Error('test network failure');return{ok:true,json:async()=>({sha256:sha,size:4,fileUrl:'/api/device-backups/'+'a'.repeat(32)})};}
if(path.startsWith('/api/device-backups/'))return{ok:true,arrayBuffer:async()=>img.slice().buffer};
throw Error(path);
}};
vm.runInNewContext(fs.readFileSync(__dirname+'/../src/archive-client.js','utf8'),ctx);
const a=ctx.window.TamaArchive;
(async()=>{
await assert.rejects(()=>a.deliver(img,'save.tamasave',(b,n)=>downloads.push([b,n]),()=>{},'save'),/failure/);
assert(a.hasPending());assert.equal(downloads.length,0);
fail=false;await a.retry();assert(!a.hasPending());assert.equal(downloads.length,1);
assert.notEqual(downloads[0][0],img,'Download must use verified server bytes');assert.deepEqual(downloads[0][0],img);
assert(calls.indexOf('/api/device-backups')<calls.indexOf('/api/device-backups/'+'a'.repeat(32)));
mode='local';calls=[];await a.deliver(img,'save.tamasave',()=>{},()=>{},'save');assert.deepEqual(calls,['/api/backup-status']);
console.log('PASS: server first, no failed-upload download, retained retry, verified server bytes and admin local policy');
})().catch(e=>{console.error(e);process.exit(1);});
+29
View File
@@ -0,0 +1,29 @@
// 1.7.3 test7: "remember where you left off" (flags bit 12) per program and no clock from the Paradise (clean ROM, clock
// not set at the start): written by appsPlace, read back by appsRead.
// node test/sess_test.js <land.bin> <game.hex> <game.gb> <game.sms> [<v1 rom.bin>]
const fs = require('fs'), S = __dirname + '/../';
const C = require(S + 'src/core.js'), E = require(S + 'src/emu.js'), F = require(S + 'src/feld.js');
const rd = (p) => new Uint8Array(fs.readFileSync(p));
const [land, hex, gb, sms, v1] = process.argv.slice(2);
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const u32 = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0;
const fe = { feld: rd(S + 'feld/feld.bin'), stub: rd(S + 'feld/stub_feld_tpl.bin') };
const progs = { ab: rd(S + 'ab/ab.bin'), gb: rd(S + 'gb/gb.bin'), sms: rd(S + 'sms/sms.bin'), v1: rd(S + 'v1/v1.bin') };
const ctx = C.openRom(rd(land)); const base = C.buildRom(ctx, C.launcherChanges(ctx)).rom;
const xs = [
{ kind: 'ab', rom: E.abHex(fs.readFileSync(hex, 'latin1')), title: 'A', keys: E.AB_KEYS_DEFAULT.slice(), inv: true, sess: false },
{ kind: 'ab', rom: E.abHex(fs.readFileSync(hex, 'latin1')), title: 'B', keys: E.AB_KEYS_DEFAULT.slice(), inv: true },
{ kind: 'gb', rom: rd(gb), keys: E.GB_KEYS_DEFAULT.slice(), inv: true, sess: false },
{ kind: 'sms', rom: rd(sms), title: 'S', keys: E.SMS_KEYS_DEFAULT.slice(), inv: true, sess: false },
];
if (v1) xs.push({ kind: 'v1', rom: rd(v1), clock: true, sess: false });
for (const noClock of [false, true]) {
const r = E.appsPlace(base, xs, progs, { launch: true, noClock, dlApp: rd(S + 'flash/flashapp.bin') });
const m = F.feldApply(r.rom, { launch: true, apps: r.list, dl: r.dl }, [], fe, E);
const back = E.appsRead(m, F.feldApps(m, fe.stub).apps);
ok(back.length === xs.length, back.length + ' programs read back');
xs.forEach((x, i) => ok(back[i] && back[i].sess === (x.sess !== false), x.kind + ' ' + i + ': remember ' + (x.sess !== false)));
ok(back[2].inv && back[3].inv, 'other flags kept (wheel turned)');
if (v1) { const b = back.find((y) => y.kind === 'v1'); ok(b && b.clock === !noClock, 'V1 clock from the Paradise ' + !noClock); }
}
console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
+92
View File
@@ -0,0 +1,92 @@
// Six fields (local only, needs your own images).
// node test/six_test.js <tropical_or_glacier.bin> <land_water_or_sky.bin> [jade_forest.bin]
const fs = require('fs');
const C = require('../src/core.js'); globalThis.ParamixCore = C;
const E = require('../src/emu.js'), F = require('../src/feld.js'), S = require('../src/six.js');
const rd = (p) => new Uint8Array(fs.readFileSync(p));
const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0;
let bad = 0;
function ok(c, m) { console.log((c ? 'ok ' : 'WRONG ') + m); if (!c) bad++; }
const trop = rd(process.argv[2]), land = rd(process.argv[3]);
const blob = rd(__dirname + '/../six/six.bin');
const emb = { feld: rd(__dirname + '/../feld/feld.bin'), stub: rd(__dirname + '/../feld/stub_feld_tpl.bin') };
ok(S.sixCan(trop), 'base ROM can get six fields');
ok(S.sixSource(land), 'second ROM gives Land, Water, Sky');
ok(!S.sixSource(trop) && !S.sixCan(land), 'the two are not mixed up');
let base = F.feldStrip(trop, emb, E);
const t0 = Date.now();
const six = S.sixApply(base, land, blob);
ok(true, 'built in ' + (Date.now() - t0) + ' ms');
const info = S.sixInfo(six), ctx = C.openRom(six);
ok(info && info.sprites === C.openRom(base).entries.length, 'helper page ' + JSON.stringify(info));
ok(ctx.assetEnd < 0xD29000, 'archive ends at 0x' + ctx.assetEnd.toString(16) + ' (before the ID page)');
ok(ctx.entries.length >= info.sprites + 12, (ctx.entries.length - info.sprites) + ' pictures added');
{ const st = S.sixStrip(six), cs = C.openRom(st), cb = C.openRom(base);
ok(Buffer.compare(Buffer.from(st.subarray(0x11000, 0x111000)), Buffer.from(base.subarray(0x11000, 0x111000))) === 0, 'strip: firmware and helper page as before');
ok(cs.entries.length === cb.entries.length && Buffer.compare(Buffer.from(cs.files[0]), Buffer.from(cb.files[0])) === 0, 'strip: data pack and picture count as before'); }
ok(S.sixApply(six, land, blob) === six, 'second run changes nothing');
// firmware patches point into the helper page
const tgt = (o) => { const h1 = six[o] | six[o + 1] << 8, h2 = six[o + 2] | six[o + 3] << 8; return h1 >> 11 === 0x1E && (h2 >> 14) >= 2; };
ok(tgt(0x1BEAC) && tgt(0x20ED2) && tgt(0x20FBC) && tgt(0x20D62), 'branches into the helper');
ok(info.fieldMenu && tgt(0x11000 + 0x265E2) && tgt(0x11000 + 0x41690) && tgt(0x11000 + 0x416B8) && tgt(0x11000 + 0x414EC) && six[0x11000 + 0x41496 + 2] === 0x53, 'game field menu hooked');
{ const nm = S.sixApply(six, land, blob, { fieldMenu: false }), ni = S.sixInfo(nm);
ok(ni && !ni.fieldMenu && nm[0x11000 + 0x41690] === 0x90 && nm[0x11000 + 0x41496 + 2] === 0x4F, 'switch off: game field menu as before'); }
ok(info.games && tgt(0x11000 + 0x50B1E) && tgt(0x11000 + 0x2FFE4) && tgt(0x11000 + 0x83938), 'lab games per start field hooked');
{ const ng = S.sixApply(six, land, blob, { games: false }), gi = S.sixInfo(ng);
ok(gi && !gi.games && Buffer.compare(Buffer.from(ng.subarray(0x11000 + 0x50B1E, 0x11000 + 0x50B22)), Buffer.from(base.subarray(0x11000 + 0x50B1E, 0x11000 + 0x50B22))) === 0 && ng[0x11000 + 0x2FFE4] === 0xB2 && ng[0x11000 + 0x2FFE5] === 0xF8, 'switch off: lab games as before'); }
ok(u32(six, 0xF00000) === 0x42584953, 'rain pictures in region B');
// DNA per field (1.7.2): on by default, off and on again without the Land ROM
if (S.DNA) {
const fo = (x) => x - 0x10000000 + 0x11000;
ok(info.dna && tgt(fo(0x10081C68)) && tgt(fo(0x1000AE44)) && tgt(fo(0x10013BBE)) && tgt(fo(0x10068B54)) && six[fo(0x1003BFB2)] === 6, 'DNA per field hooked');
const off = S.sixDna(six, blob, false), oi = S.sixInfo(off);
ok(oi && !oi.dna && off[fo(0x10081C68)] === 0x80 && off[fo(0x1003BFB2)] === 3 && tgt(0x20D62) && tgt(0x11000 + 0x416B8), 'DNA off: firmware as with six fields only');
{ const st = S.sixStrip(off), st2 = S.sixStrip(six);
ok(Buffer.compare(Buffer.from(st.subarray(0x11000, 0x111000)), Buffer.from(st2.subarray(0x11000, 0x111000))) === 0, 'DNA off, then strip: same as strip'); }
const on = S.sixDna(off, blob, true);
ok(Buffer.compare(Buffer.from(on), Buffer.from(six)) === 0, 'DNA on again: same ROM');
const nd = S.sixApply(base, land, blob, { dna: false });
ok(!S.sixInfo(nd).dna && Buffer.compare(Buffer.from(nd.subarray(0x11000, 0x111000)), Buffer.from(off.subarray(0x11000, 0x111000))) === 0, 'six fields without DNA: same as DNA off');
ok(Buffer.compare(Buffer.from(S.sixApply(nd, land, blob)), Buffer.from(six)) === 0, 'apply with DNA on a ROM without: DNA added');
}
{ const moved = C.buildRom(C.openRom(six), new Map(), null).rom; ok(Buffer.compare(Buffer.from(S.sixFix(moved)), Buffer.from(six)) === 0, 'sixFix after a rebuild gives the same ROM'); }
for (let i = 0; i < 12; i++) { const d = C.spriteDecode(ctx.entries[info.sprites + i]); if (d.subs[0].w !== 512) { ok(false, 'picture ' + i); break; } }
ok(true, 'pictures decode');
// menu with six fields
const m = F.feldApply(six, { fields: true, bag: true }, F.feldSlots(trop, emb.stub), emb, E);
const f = F.feldFind(m, emb.stub);
ok(F.fieldNames(m).join() === 'Tropical,Glacier,Forest,Land,Water,Sky', 'menu: ' + F.fieldNames(m).join(', '));
{ const cfg = m.subarray(0, 0x111000); let fam = 0; for (let o = 0; o + 4 <= cfg.length; o += 4) if (cfg[o] === 0x05 && cfg[o + 1] === 0x0F && cfg[o + 3] === 0 && (cfg[o + 2] === 1 || cfg[o + 2] === 2)) fam++;
ok(fam === 4, 'menu: fresh Land, Water, Sky and Forest get their game family (' + fam + ')'); }
ok(f.nslots === 6 && f.version >= 4, 'six slots, ' + (f.slotSize >> 10) + ' KB each');
const addr = []; for (let i = 0; i < 6; i++) addr.push(f.slotOff2 && i >= f.slotN1 ? f.slotOff2 + (i - f.slotN1) * f.slotSize : f.slotOff + i * f.slotSize);
const clash = addr.some((a, i) => (a < 0x10F000 && a + f.slotSize > 0x10F000) || (a >= 0x111000 && a < ctx.assetEnd) || a + f.slotSize > 0xD29000 || addr.some((b, k) => k !== i && Math.abs(a - b) < f.slotSize));
ok(!clash, 'slots: ' + addr.map((a) => '0x' + a.toString(16)).join(' '));
const again = F.feldApply(F.feldStrip(m, emb, E), { fields: true, bag: true }, F.feldSlots(m, emb.stub), emb, E);
ok(Buffer.compare(Buffer.from(again), Buffer.from(m)) === 0, 'remove and add the menu gives the same ROM');
// food per field (1.7.4): Land, Water, Sky food counted for the young stage
{ const bl = (b, o) => (b[o + 1] >> 3) === 0x1E;
ok(bl(six, 0x11000 + 0x1027E) && bl(six, 0x11000 + 0x81D70) && u32(six, 0x10F000 + 0xC40 + 44) !== 0xFFFFFFFF, 'food per field hooked');
const old = new Uint8Array(six); old.set([0x0d, 0xf0, 0x55, 0xfd], 0x11000 + 0x1027E); old.set([0x80, 0xb5, 0x96, 0xb0], 0x11000 + 0x81D70);
ok(Buffer.compare(Buffer.from(S.sixApply(old, land, blob)), Buffer.from(six)) === 0, 'older ROM with DNA gets the food places'); }
// Jade Forest: Sky as 4th field (optional third argument)
if (process.argv[4]) {
const jade = F.feldStrip(rd(process.argv[4]), emb, E);
ok(S.sixCan(jade) && !S.sixNeedsSource(jade), 'Jade Forest can get Sky without a second ROM');
const j4 = S.sixApply(jade, null, blob);
ok(Buffer.compare(Buffer.from(j4.subarray(0x111000, 0xD49000)), Buffer.from(jade.subarray(0x111000, 0xD49000))) === 0, 'Jade: archive untouched');
const jm = F.feldApply(j4, { fields: true, bag: true }, [], emb, E);
ok(F.fieldNames(jm).join() === 'Land,Water,Forest,Sky', 'Jade menu: ' + F.fieldNames(jm).join(', '));
ok(S.sixInfo(j4).fieldMenu, 'Jade: field menu flag');
{ const jt = (o) => { const h1 = j4[o] | j4[o + 1] << 8, h2 = j4[o + 2] | j4[o + 3] << 8; return h1 >> 11 === 0x1E && (h2 >> 14) >= 2; };
ok(jt(0x11000 + 0x2262C) && jt(0x11000 + 0x3C470) && jt(0x11000 + 0x3C498) && jt(0x11000 + 0x3C2E0) && j4[0x11000 + 0x3C29E + 2] === 0x4F, 'Jade: game field menu hooked'); }
ok(Buffer.compare(Buffer.from(S.sixStrip(j4)), Buffer.from(jade)) === 0, 'Jade: strip gives the original');
{ const bl = (b, o) => (b[o + 1] >> 3) === 0x1E;
ok(S.sixInfo(j4).food && bl(j4, 0x11000 + 0xE7F6) && bl(j4, 0x11000 + 0x72750), 'Jade: food per field (Sky food counts)');
const old = new Uint8Array(j4); old.set([0x0c, 0xf0, 0x35, 0xf9], 0x11000 + 0xE7F6); old.set([0x80, 0xb5, 0x90, 0xb0], 0x11000 + 0x72750);
old[0x10F000 + 32] &= ~64; old.fill(0xFF, 0x10F000 + 0xC00, 0x110000);
ok(Buffer.compare(Buffer.from(S.sixApply(old, null, blob)), Buffer.from(j4)) === 0, 'Jade: older ROM gets the food part'); }
}
console.log(bad ? bad + ' WRONG' : 'all good');
process.exit(bad ? 1 : 0);
+24
View File
@@ -0,0 +1,24 @@
// 1.6.10 test2: Master System detection and placing with a made-up ROM (no game): header, Game Gear, file name, copier
// header, the settings block, read back. node test/sms_test.js
const E = require('../src/emu.js');
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const mk = (n, region) => { const r = new Uint8Array(n); if (region !== undefined) { r.set(Buffer.from('TMR SEGA'), 0x7FF0); r[0x7FFF] = region << 4 | 0xC; } return r; };
ok(E.smsDetect(mk(0x20000, 4), 'x.bin'), 'export header');
ok(E.smsDetect(mk(0x20000, 3), 'x.bin'), 'Japanese header');
ok(E.smsDetect(mk(0x20000, 6), 'x.bin') && E.smsGameGear(mk(0x20000, 6)) && !E.smsGameGear(mk(0x20000, 4)) && E.smsGameGear(mk(0x20000), 'x.gg'), 'Game Gear taken and known');
ok(!E.smsDetect(mk(0x20000), 'x.bin') && E.smsDetect(mk(0x20000), 'x.sms') && E.smsDetect(mk(0x20000), 'x.gg'), 'no header: by the name');
ok(!E.smsDetect(mk(0x1000), 'x.sms') && !E.smsDetect(mk(0x200000), 'x.sms'), 'too small, too big');
{ const r = new Uint8Array(0x20000 + 512); r.set(Buffer.from('TMR SEGA'), 512 + 0x7FF0); r[512 + 0x7FFF] = 0x4C; ok(E.smsDetect(r, 'x.bin'), 'copier header in front'); }
ok(E.smsTitle('Alex Kidd in Miracle World (U) (V1.0).sms') === 'ALEX KIDD MIRAC', 'name from the file');
// place it like the Studio does (into an empty ROM with an app at 0xA0000 is not needed: an empty flash is enough)
const app = E.smsEmbedded() || new Uint8Array(require('fs').readFileSync(__dirname + '/../sms/sms.bin'));
if (app) {
const rom = new Uint8Array(0x1000000).fill(0xFF), g = mk(0x20000, 4); g[0] = 0xF3;
const res = E.appsPlace(rom, [{ kind: 'sms', rom: g, title: 'TEST', gg: true, keys: E.SMS_KEYS_DEFAULT.slice(), inv: true }], { sms: app }, { launch: true });
const off = res.list[0].off, c = E.extraCfg(res.rom, off);
ok(c && c.kind === 'sms' && c.romLen === g.length && c.saveOff === off + 0x10000, 'settings block');
const back = E.appsRead(res.rom, res.list)[0];
ok(back && back.kind === 'sms' && back.title === 'TEST' && back.gg && back.inv && back.keys[6] === 64, 'read back');
} else console.log('(no embedded program: placing skipped)');
console.log(bad ? 'FAIL ' + bad : 'all good');
process.exit(bad ? 1 : 0);
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env python3
"""Autostart in the home screen stub, run in a Thumb emulator (unicorn).
python3 test/stub_auto_test.py (needs: pip install unicorn)"""
import struct, os
from unicorn import Uc, UC_ARCH_ARM, UC_MODE_THUMB, UC_HOOK_CODE
from unicorn.arm_const import UC_ARM_REG_SP, UC_ARM_REG_LR, UC_ARM_REG_PC
here = os.path.dirname(os.path.abspath(__file__))
BASE, ORIG, DONE = 0x1009F000, 0x10100000, 0x10200000
bad = 0
def ok(c, m):
global bad
print(('ok ' if c else 'WRONG ') + m); bad += 0 if c else 1
def stub(tpl, auto):
d = bytearray(open(tpl, 'rb').read())
for o in range(0, len(d) - 3, 2):
w = struct.unpack_from('<I', d, o)[0]
if w in (0x22222221, 0x33333331, 0x44444441, 0x55555551): struct.pack_into('<I', d, o, ORIG | 1)
elif w == 0x66666661: struct.pack_into('<I', d, o, auto)
elif w == 0x6789EF01: struct.pack_into('<I', d, o, 0x100A0001)
return bytes(d)
def run(code, gpio, marker, secs=5, shpr=0, table=False, rs=0):
u = Uc(UC_ARCH_ARM, UC_MODE_THUMB)
for a, n in ((0x10000000, 0x400000), (0x20000000, 0x1000), (0x40018000, 0x1000), (0x18000000, 0x10000), (0x45000000, 0x1000), (0xE000E000, 0x1000), (0x60FF0000, 0x10000)):
u.mem_map(a, n)
u.mem_write(BASE, code)
u.mem_write(0x40018000, struct.pack('<I', gpio))
u.mem_write(0x20000FFC, struct.pack('<I', marker))
u.mem_write(0x45000304, struct.pack('<I', secs))
u.mem_write(0xE000ED1A, bytes([shpr]))
if table: u.mem_write(0x60FFE000, b'SONIXDEV' + bytes(8) + struct.pack('<I', 0x60FF0000))
u.reg_write(UC_ARM_REG_SP, 0x18008000); u.reg_write(UC_ARM_REG_LR, DONE | 1)
where = []
def hk(uc, addr, size, _):
if addr in (BASE, ORIG, DONE, rs): where.append(addr); uc.emu_stop()
u.hook_add(UC_HOOK_CODE, hk)
u.emu_start((BASE + 0x40) | 1, 0, count=400)
return (where[0] if where else None), struct.unpack('<I', u.mem_read(0x20000FFC, 4))[0], u.reg_read(UC_ARM_REG_SP), u.mem_read(0xE000ED1A, 1)[0]
L, R, IDLE, BHELD, CHELD = 0x4C584D50, 0x52584D50, 0xFFFFFFFF, 0xFFFFFFFF & ~(1 << 11), 0xFFFFFFFF & ~(1 << 10)
for name, tpl, rs in (('emu', '../emu/stub_tpl.bin', 0x1009F1A8), ('menu', '../feld/stub_feld_tpl.bin', 0x1009F1F0)):
t = os.path.join(here, tpl)
w, m, sp, f = run(stub(t, 1), IDLE, 0x12345678, secs=5)
ok(w == BASE and m == R and f, name + ': power-on (clock new): emulator')
w, m, sp, f = run(stub(t, 1), IDLE, R, secs=5, shpr=0xE0)
ok(w == ORIG and m == R and sp == 0x18008000, name + ': later calls in the same boot: original handler')
w, m, sp, f = run(stub(t, 1), IDLE, L, secs=9999)
ok(w == ORIG and m == R and sp == 0x18008000, name + ': back from the emulator: Paradise')
w, m, sp, f = run(stub(t, 1), IDLE, R, secs=9999)
ok(w == BASE and m == R, name + ': reset button (marker kept): emulator')
w, m, sp, f = run(stub(t, 1), IDLE, 0x00000000, secs=9999)
ok(w == ORIG and m == R and sp == 0x18008000, name + ': waking from deep sleep (marker lost, clock ran): Paradise')
w, m, sp, f = run(stub(t, 1), BHELD, 0x12345678, secs=5)
ok(w == ORIG and m == R, name + ': B held at power-on: Paradise')
w, m, sp, f = run(stub(t, 0), IDLE, 0x1234, secs=5)
ok(w == ORIG and m == 0x1234 and f == 0, name + ': switch off: nothing changes')
w, m, sp, f = run(stub(t, 0), IDLE & ~0x600, 0, secs=5)
ok(w == ORIG, name + ': A+C held: counts as before (original handler until the limit)')
# 1.7.2: C held after switching on or a reset: the flash app (when its load table is there)
for auto in (0, 1):
w, m, sp, f = run(stub(t, auto), CHELD, 0x12345678, secs=5, table=True, rs=rs)
ok(w == rs, name + ': C at power-on, flash app there: flash app (autostart %d)' % auto)
w, m, sp, f = run(stub(t, auto), CHELD, R, secs=9999, table=True, rs=rs)
ok(w == rs, name + ': C after the reset button: flash app (autostart %d)' % auto)
w, m, sp, f = run(stub(t, auto), CHELD, L, secs=9999, table=True, rs=rs)
ok(w != rs, name + ': C when back from a program: no flash app (autostart %d)' % auto)
w, m, sp, f = run(stub(t, auto), CHELD, 0, secs=9999, table=True, rs=rs)
ok(w != rs, name + ': C when waking from deep sleep: no flash app (autostart %d)' % auto)
# 1.7.3 test29: A and C (the program key) is no way back
w, m, sp, f = run(stub(t, auto), CHELD & ~0x200, 0x12345678, secs=5, table=True, rs=rs)
ok(w != rs, name + ': A+C at power-on, flash app there: no flash app (autostart %d)' % auto)
w, m, sp, f = run(stub(t, auto), CHELD & ~0x200, R, secs=9999, table=True, rs=rs)
ok(w != rs, name + ': A+C after the reset button: no flash app (autostart %d)' % auto)
w, m, sp, f = run(stub(t, 0), CHELD, 0x1234, secs=5, table=True, rs=rs, shpr=0)
w2 = run(stub(t, 0), CHELD, 0x1234, secs=5, table=True, rs=rs)[0]
ok(w == rs and w2 == rs, name + ': B, autostart off: flash app')
w, m, sp, f = run(stub(t, 1), BHELD, 0x12345678, secs=5, table=True, rs=rs)
ok(w == ORIG, name + ': B at power-on, flash app there: still Paradise (no autostart)')
print('all good' if not bad else '%d WRONG' % bad)
+15
View File
@@ -0,0 +1,15 @@
// test27: a T7Emu EEPROM slot written 2 bytes off (flash DMA from a buffer at ...2) is still read by the Studio
const SV = require('../src/saves.js');
const img = new Uint8Array(0x1000000).fill(0xFF), base = 0x850000, at = base + 0x1000;
const pages = new Uint8Array(4096); for (let i = 0; i < 4094; i++) pages[i] = (i * 7 + 3) & 0xFF; pages[4094] = pages[4095] = 0;
let s = 0x7E7E; for (let i = 0; i < 4096; i++) s = (Math.imul(s, 31) + pages[i]) >>> 0;
const w32 = (o, v) => { img[o] = v & 255; img[o + 1] = (v >>> 8) & 255; img[o + 2] = (v >>> 16) & 255; img[o + 3] = v >>> 24; };
w32(at, 0x45453754); w32(at + 4, 5); w32(at + 8, 0xFFFF); w32(at + 12, s);
img[at + 0x1000] = 0xAB; img[at + 0x1001] = 0xCD; img.set(pages.subarray(0, 4094), at + 0x1002); // as the DMA wrote it
const o = SV.t7SaveOut(img, base);
if (!o) throw new Error('shifted slot not found');
for (let i = 0; i < 4096; i++) if (o[2 + i] !== pages[i]) throw new Error('byte ' + i);
// a normal slot still reads as before
const n = SV.t7SaveIn(img, o, base), o2 = SV.t7SaveOut(n, base);
for (let i = 0; i < o.length; i++) if (o[i] !== o2[i]) throw new Error('round trip ' + i);
console.log('all good');
+82
View File
@@ -0,0 +1,82 @@
// 1.7.3: tab Arduboy: games from .hex and a .zip into the menu, keys changed, saved, read back.
// node test/ui_ab_test.js <paradise.bin> <game.hex> <game2.hex> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
const C = require('../src/core.js');
(async () => {
const [rom, hex1, hex2, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) }, abapp = fs.readFileSync(__dirname + '/../ab/ab.bin');
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
// the second game in a zip
const zip = C.zipBuild([{ name: "games/" + path.basename(hex2), data: new Uint8Array(fs.readFileSync(hex2)) }]);
if (zip) fs.writeFileSync(out + '/games.zip', zip);
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]'); await p.click('#bagOn'); await p.waitForTimeout(800);
await p.click('.tab[data-tab="ab"]');
ok(await p.evaluate(() => !document.getElementById('pane-ab').hidden), 'tab Arduboy shown');
ok(await p.evaluate(() => document.querySelectorAll('#abKeyGrid select').length === 9), 'nine key lines');
fs.writeFileSync(out + '/bad.hex', 'not a hex file\n');
await p.setInputFiles('#fileAb', out + '/bad.hex'); await p.waitForTimeout(400);
ok(/kein Arduboy-Spiel/.test(await p.evaluate(() => document.getElementById('toast').textContent)), 'bad file refused');
await p.setInputFiles('#fileAb', hex1); await p.waitForTimeout(1500);
if (zip) { await p.setInputFiles('#fileAb', out + '/games.zip'); await p.waitForTimeout(1500); }
const names = await p.evaluate(() => document.getElementById('abList').innerText);
const n1 = E.abTitle(path.basename(hex1)), n2 = E.abTitle(path.basename(hex2));
ok(names.includes(n1), 'game in the list: ' + n1);
if (zip) ok(names.includes(n2), 'game from the zip in the list: ' + n2);
await p.evaluate(() => { const s = document.querySelectorAll('#abKeyGrid select')[8]; s.value = '16'; s.dispatchEvent(new Event('change')); });
await p.waitForTimeout(200);
ok(/Arduboy/.test(await p.evaluate(() => document.querySelector('#plan').innerText)), 'own part in "Dein neues ROM"');
const dlp = p.waitForEvent('download', { timeout: 120000 }); await p.click('#btnSave');
const dl = await dlp; const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1));
const xs = E.appsRead(img, F.feldApps(img, fe.stub).apps).filter((y) => y.kind === 'ab');
ok(xs.length === (zip ? 2 : 1), xs.length + ' Arduboy games in the menu');
const x = xs[0];
ok(x && Buffer.from(x.rom).equals(Buffer.from(E.abHex(fs.readFileSync(hex1, 'latin1')))), 'the game in the ROM');
ok(x && x.keys[8] === 16 && x.keys[0] === 4 && x.inv, 'keys in the settings block');
ok(x && Buffer.from(img.subarray(x.off + 0x300, x.off + abapp.length)).equals(abapp.subarray(0x300)), 'ArduboyEmu program in place');
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(3000);
await p.click('.tab[data-tab="ab"]');
ok((await p.evaluate(() => document.getElementById('abList').innerText)).includes(n1), 'read back: game listed');
ok(await p.evaluate(() => document.querySelectorAll('#abKeyGrid select')[8].value === '16'), 'read back: keys');
await p.screenshot({ path: out + '/ab_tab.png', fullPage: false });
// 1.7.3 test5: an older ArduboyEmu in the ROM (OLDAB=<old ab.bin>) is written anew on saving
if (process.env.OLDAB) {
const old = new Uint8Array(fs.readFileSync(process.env.OLDAB)), o = new Uint8Array(img);
for (let i = 0x800; i < 0x10000; i++) o[x.off + i] = i < old.length ? old[i] : 0xFF;
fs.writeFileSync(out + '/old_ab.bin', o);
await p.setInputFiles('#fileRom', out + '/old_ab.bin'); await p.waitForTimeout(3000);
const plan = await p.evaluate(() => Array.from(document.querySelectorAll('#plan .chip, #plan span, #plan div')).map((e) => e.innerText).filter((t) => /·/.test(t) && t.length < 200));
console.log(' plan: ' + JSON.stringify(plan));
ok(plan.some((t) => /^Arduboy/.test(t) && /wird aktualisiert/.test(t)), 'older ArduboyEmu: shown as updated at Arduboy');
ok(!plan.some((t) => /^Emulator/.test(t) && /wird aktualisiert/.test(t)), 'older ArduboyEmu: not shown at the emulators');
const dlo = p.waitForEvent('download', { timeout: 120000 }); await p.click('#btnSave');
const d2 = await dlo.catch(() => null); ok(!!d2, 'older ArduboyEmu: there is something to write');
if (d2) { const r2 = out + '/up_' + d2.suggestedFilename(); await d2.saveAs(r2); const im2 = new Uint8Array(fs.readFileSync(r2));
const y = E.appsRead(im2, F.feldApps(im2, fe.stub).apps).find((z) => z.kind === 'ab');
ok(y && Buffer.from(im2.subarray(y.off + 0x800, y.off + abapp.length)).equals(abapp.subarray(0x800)), 'older ArduboyEmu: the new program in place');
ok(y && y.keys[8] === 16, 'older ArduboyEmu: keys kept'); }
}
// 1.7.3 test7: "remember where you left off" off for the first game (tab Emulator, its row opened)
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(3000);
await p.click('.tab[data-tab="emu"]'); await p.waitForTimeout(300);
await p.evaluate(() => { const r = Array.from(document.querySelectorAll('#appsList .prow')).find((e) => e.querySelector('.ptog')); r.querySelector('.ptog').click(); });
await p.waitForTimeout(300);
const had = await p.evaluate(() => { const l = Array.from(document.querySelectorAll('#appsList .pdet label')).find((e) => /Spielstand beim Verlassen/.test(e.textContent)); if (!l) return false; const c = l.querySelector('input'); c.checked = false; c.dispatchEvent(new Event('change')); return true; });
ok(had, 'checkbox "Spielstand beim Verlassen merken" in the row');
const dls = p.waitForEvent('download', { timeout: 120000 }); await p.click('#btnSave');
const d3 = await dls.catch(() => null); ok(!!d3, 'something to write');
if (d3) { const r3 = out + '/sess_' + d3.suggestedFilename(); await d3.saveAs(r3); const im3 = new Uint8Array(fs.readFileSync(r3));
const ys = E.appsRead(im3, F.feldApps(im3, fe.stub).apps).filter((z) => z.kind === 'ab');
ok(ys.length === 2 && ys.filter((z) => z.sess === false).length === 1, 'one game without remembering, one with'); }
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+53
View File
@@ -0,0 +1,53 @@
// More emulators in the browser: Friends as T7Emu, Tama-Go as a second one, menu on, save, load again.
// node test/ui_apps_test.js <paradise.bin> <friends.bin> <tama-go.bin> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js'), SV = require('../src/saves.js');
(async () => {
const [rom, fr, go, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="emu"]');
await p.setInputFiles('#fileEmu', fr); await p.waitForTimeout(300);
await p.setInputFiles('#fileApp', go); await p.waitForTimeout(300);
console.log('Liste:', await p.textContent('#appsList'));
await p.click('.tab[data-tab="feld"]'); if (!(await p.isChecked('#feldOn'))) await p.click('#feldOn'); await p.waitForTimeout(300);
const [dl] = await Promise.all([p.waitForEvent('download', { timeout: 120000 }), p.click('#btnSave')]);
const r1 = out + '/apps.bin'; await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1)), fa = F.feldApps(img, fe.stub);
ok(fa.name0 === 'FRIENDS' && fa.apps.length === 1 && fa.apps[0].name === 'TAMA-GO', 'saved: ' + fa.name0 + ' + ' + fa.apps.map((x) => x.name));
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="emu"]');
const l = await p.textContent('#appsList');
ok(/TAMA-GO/.test(l), 'loaded again: ' + l);
const plan = await p.textContent('#plan');
console.log('Plan:', plan.slice(0, 200));
// save.bin into the second T7Emu through the Save tab
const sv = new Uint8Array(4098); sv[0] = 0xFF; sv[1] = 0xFF; for (let i = 2; i < 4098; i++) sv[i] = (i * 7) & 255;
fs.writeFileSync(out + '/save.bin', sv);
await p.click('.tab[data-tab="save"]');
ok(!(await p.isHidden('#saveForRow')), 'Save tab: choice of the T7Emu shown');
await p.selectOption('#saveFor', '0');
await p.setInputFiles('#fileEmuSav', out + '/save.bin'); await p.waitForTimeout(300);
console.log('Status:', await p.textContent('#saveStat'));
const [dl2] = await Promise.all([p.waitForEvent('download', { timeout: 120000 }), p.click('#btnSave')]);
const r2 = out + '/apps2.bin'; await dl2.saveAs(r2);
const img2 = new Uint8Array(fs.readFileSync(r2)), x = E.appsRead(img2, F.feldApps(img2, fe.stub).apps)[0];
const got = x && SV.t7SaveOut(img2, x.saveOff);
ok(got && Buffer.from(got).equals(Buffer.from(sv)) && !SV.t7SaveOut(img2), 'save of TAMA-GO in its own area, main one untouched');
// and out again from the loaded ROM
await p.setInputFiles('#fileRom', r2); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="save"]'); await p.selectOption('#saveFor', '0');
const [dl3] = await Promise.all([p.waitForEvent('download', { timeout: 30000 }), p.click('#btnEmuOut')]);
const r3 = out + '/' + dl3.suggestedFilename(); await dl3.saveAs(r3);
ok(Buffer.from(fs.readFileSync(r3)).equals(Buffer.from(sv)) && /tama-go/.test(r3), 'export of TAMA-GO: ' + path.basename(r3));
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+78
View File
@@ -0,0 +1,78 @@
// ROM without the Paradise with DOOM as a program of the menu (1.7.2 test3 DOOM_FREE): DOOM anywhere, any program can be
// the main one; load again, add one, save again; a start device with DOOM becomes a ROM without the Paradise.
// node test/ui_clean_doom_test.js <paradise.bin> <DOOM.WAD> <tg18.bin> <tama-go.bin> <p2.bin> <start device with DOOM or -> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js'), D = require('../src/doom.js');
(async () => {
const [rom, wad, tg18, go, p2, para, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message)); p.on('dialog', (d) => d.accept());
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
const save = async (name) => {
const dlp = p.waitForEvent('download', { timeout: 300000 }); await p.click('#btnSave');
for (let i = 0; i < 90; i++) { await p.waitForTimeout(2000); const tt = await p.evaluate(() => document.getElementById('toast').className + ' ' + document.getElementById('toast').textContent); if (/err/.test(tt)) { console.log('toast:', tt); break; } if (!(await p.evaluate(() => document.getElementById('busy').classList.contains('on')))) break; }
const dl = await dlp; const f = out + '/' + name + dl.suggestedFilename(); await dl.saveAs(f); return f;
};
const star = async (nm) => { const rows = p.locator('#appsList .prow'); const n = await rows.count(); for (let i = 0; i < n; i++) if ((await rows.nth(i).locator('.pname').textContent()) === nm) { await rows.nth(i).locator('button.pstar').click(); await p.waitForTimeout(1500); return true; } return false; };
const doomOf = (img) => { const fa = F.feldApps(img, fe.stub), xs = E.appsRead(img, fa.apps); const d = xs.find((x) => x.kind === 'doom'); return { fa, xs, d, c: d ? E.doomCfg(img, d.off) : null }; };
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]'); await p.click('#launchOn'); await p.waitForTimeout(1500);
await p.click('#cleanOn'); await p.waitForTimeout(500); await p.waitForFunction(() => !document.getElementById('busy').classList.contains('on'), null, { timeout: 60000 });
ok(await p.isVisible('.tab[data-tab="doom"]'), 'DOOM tab stays');
await p.click('.tab[data-tab="doom"]');
await p.setInputFiles('#fileWad', wad);
await p.waitForFunction(() => !document.getElementById('busy').classList.contains('on') && /E\d/.test(document.getElementById('doomStat').innerText), null, { timeout: 180000 });
await p.click('.tab[data-tab="emu"]');
await p.setInputFiles('#fileApp', tg18); await p.waitForTimeout(1500);
await p.setInputFiles('#fileApp', go); await p.waitForTimeout(800);
console.log('Liste:', await p.textContent('#appsList'));
ok(await star('TAMA MEETS'), 'star on TAMA MEETS');
console.log('Liste:', await p.textContent('#appsList'));
const r1 = await save('');
const img = new Uint8Array(fs.readFileSync(r1)), ci = F.cleanInfo(img), o = doomOf(img);
ok(/_doom_E\d_clean\.bin$/.test(r1), 'file name ' + path.basename(r1));
ok(!!ci && ci.feld === 0xB1000, 'clean ROM, menu at its usual place');
ok(o.d && o.fa.apps.map((a) => a.name).join(',').includes('DOOM'), 'DOOM is a program of the menu: ' + o.fa.apps.map((a) => a.name).join(', '));
const t18 = o.xs.find((x) => x.kind === 't18');
ok(t18 && o.fa.mainSrc === 0x10000000 + t18.off - 0x11000, 'TAMA MEETS is the main program');
if (o.c) {
const c = o.c; console.log('DOOM: program 0x' + o.d.off.toString(16), 'code 0x' + c.codeOff.toString(16), 'save 0x' + c.saveOff.toString(16), 'WAD 0x' + (c.romOff).toString(16), 'region 0x' + c.regionOff.toString(16));
ok(c.codeOff >= 0xA0000 && c.codeOff === o.d.off + 0x10000, 'program part behind its image');
ok(c.regionOff + c.regionLen <= (c.romOff & ~0x3FFFFF) + 0x800000, 'WAD and level data inside the packed pointer windows');
ok(img.subarray(c.regionOff, c.regionOff + c.regionLen).every((v) => v === 0xFF), 'level data empty (DOOM makes it)');
const xf = new Uint8Array(fs.readFileSync(__dirname + '/../doom/doomf_xip.bin')); ok(Buffer.from(img.subarray(c.codeOff, c.codeOff + xf.length)).equals(Buffer.from(xf)), 'program part in place');
}
{ const c = E.t18Cfg(img, t18.off); const bl = c.map.concat(c.spare).filter((x) => x !== 0xFFFF); ok(!bl.includes(0xFF), 'T18Emu blocks not at the rescue start'); }
// load again
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(3000);
await p.click('.tab[data-tab="emu"]');
const l2 = await p.textContent('#appsList'); console.log('Liste:', l2);
ok(/DOOM/.test(l2) && /TAMA MEETS.{0,20}Erster Eintrag/.test(l2), 'loaded again: DOOM in the list, TAMA MEETS still the main program');
await p.click('#btnSave'); await p.waitForTimeout(2000);
ok(/nichts/i.test(await p.textContent('#toast')), 'nothing changed: ' + await p.textContent('#toast'));
await star('DOOM');
await p.setInputFiles('#fileApp', p2); await p.waitForTimeout(800);
const r2 = await save('2_');
const img2 = new Uint8Array(fs.readFileSync(r2)), o2 = doomOf(img2);
ok(o2.d && Buffer.from(o2.d.mcu).equals(Buffer.from(o.d.mcu)) && o2.fa.apps.length === 4, 'one more program, DOOM with the same WAD');
ok(o2.fa.mainSrc === 0x10000000 + o2.d.off - 0x11000, 'DOOM is the main program now');
// a start device with DOOM (with the Paradise) becomes a ROM without it
if (para !== '-') {
await p.setInputFiles('#fileRom', para); await p.waitForTimeout(3000);
await p.click('.tab[data-tab="feld"]'); await p.click('#cleanOn'); await p.waitForTimeout(500); await p.waitForFunction(() => !document.getElementById('busy').classList.contains('on'), null, { timeout: 60000 });
await p.click('.tab[data-tab="emu"]'); console.log('Liste:', await p.textContent('#appsList'));
const r3 = await save('3_'); const img3 = new Uint8Array(fs.readFileSync(r3)), o3 = doomOf(img3), src = new Uint8Array(fs.readFileSync(para));
const len = src[0x830000] | src[0x830001] << 8 | src[0x830002] << 16 | src[0x830003] << 24;
ok(F.isClean(img3) && o3.d && Buffer.from(o3.d.mcu).equals(Buffer.from(src.subarray(0x830004, 0x830004 + len))), 'start device to clean: DOOM and its WAD along');
ok(o3.d && Buffer.from(img3.subarray(o3.c.saveOff, o3.c.saveOff + 0x2000)).equals(Buffer.from(src.subarray(0x10E000, 0x110000))), 'start device to clean: DOOM save along');
ok(o3.fa.mainSrc === 0x10000000 + o3.d.off - 0x11000, 'start device to clean: DOOM stays the main program');
}
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+42
View File
@@ -0,0 +1,42 @@
// ROM without the Paradise from a start device whose main program is at 0x0A0000 (1.7.2 test4): one star only, the main
// program first in the list; another program gets the star, the old main program stays as a normal entry.
// node test/ui_clean_star_test.js <start device rom> <tg18.bin> <DOOM.WAD or -> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, tg18, wad, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message)); p.on('dialog', (d) => d.accept());
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
const rows = async () => p.$$eval('#appsList .prow', (l) => l.map((r) => ({ n: r.querySelector('.pname').textContent, s: [...r.querySelectorAll('button.pstar')].map((x) => x.textContent).join('') })));
const star = async (nm) => { const rs = p.locator('#appsList .prow'); const n = await rs.count(); for (let i = 0; i < n; i++) if ((await rs.nth(i).locator('.pname').textContent()) === nm) { await rs.nth(i).locator('button.pstar').click(); await p.waitForTimeout(2000); return true; } return false; };
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="feld"]'); if (!(await p.isChecked('#launchOn'))) { await p.click('#launchOn'); await p.waitForTimeout(1500); }
await p.click('#cleanOn'); await p.waitForTimeout(3000);
await p.click('.tab[data-tab="emu"]');
let r = await rows(); console.log('rows', JSON.stringify(r));
ok(r.filter((x) => x.s === '★').length === 1 && r[0].s === '★', 'one star, the main program first: ' + r[0].n);
const main0 = r[0].n;
await p.setInputFiles('#fileApp', tg18); await p.waitForTimeout(2000);
if (wad !== '-') { await p.click('.tab[data-tab="doom"]'); await p.setInputFiles('#fileWad', wad); await p.waitForFunction(() => !document.getElementById('busy').classList.contains('on') && /E\d/.test(document.getElementById('doomStat').innerText), null, { timeout: 180000 }); await p.click('.tab[data-tab="emu"]'); }
r = await rows(); console.log('rows', JSON.stringify(r));
ok(r[0].n === main0 && (wad === '-' || r[r.length - 1].n === 'DOOM'), 'DOOM is not put first');
ok(await star('TAMA MEETS'), 'star on TAMA MEETS');
r = await rows(); console.log('rows', JSON.stringify(r));
ok(r.filter((x) => x.s === '★').length === 1 && r[0].n === 'TAMA MEETS' && r[0].s === '★', 'one star only, TAMA MEETS first');
ok(r.some((x) => x.n === main0 && x.s === '☆'), main0 + ' is a normal entry now');
const dlp = p.waitForEvent('download', { timeout: 300000 }); await p.click('#btnSave'); await p.waitForTimeout(8000); console.log('toast:', await p.textContent('#toast'));
const dl = await dlp; const f = out + '/' + dl.suggestedFilename(); await dl.saveAs(f);
const img = new Uint8Array(fs.readFileSync(f)), fa = F.feldApps(img, fe.stub), xs = E.appsRead(img, fa.apps), t18 = xs.find((x) => x.kind === 't18');
console.log('menu', fa.apps.map((a) => a.name).join(', '));
ok(F.isClean(img) && t18 && fa.mainSrc === 0x10000000 + t18.off - 0x11000, 'saved: TAMA MEETS is the main program');
ok(fa.apps.filter((a) => a.name === main0).length === 1, 'saved: ' + main0 + ' once in the menu');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+55
View File
@@ -0,0 +1,55 @@
// ROM without the Paradise (1.7.2 CLEAN_ROM) in the browser: start device, "without the Paradise", programs, save,
// check the image, load it again (Paradise tabs hidden, programs listed), add one more, save again.
// node test/ui_clean_test.js <paradise.bin> <tg18.bin> <tama-go.bin> <tama guest.bin> <one more program> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, tg18, go, guest, more, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
p.on('dialog', (d) => d.accept());
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]');
ok(await p.isHidden('#cleanRow'), 'clean switch hidden before the start device');
await p.click('#launchOn'); await p.waitForTimeout(1500);
ok(await p.isVisible('#cleanRow') && !(await p.isDisabled('#cleanOn')), 'clean switch there with the start device');
await p.click('#cleanOn'); await p.waitForTimeout(500); await p.waitForFunction(() => !document.getElementById('busy').classList.contains('on'), null, { timeout: 60000 });
ok(await p.isHidden('.tab[data-tab="figs"]') && await p.isHidden('.tab[data-tab="names"]') && await p.isVisible('.tab[data-tab="doom"]'), 'Paradise tabs hidden, DOOM stays');
console.log('Status:', await p.textContent('#feldStat'));
await p.click('.tab[data-tab="emu"]');
await p.setInputFiles('#fileApp', tg18); await p.waitForTimeout(500);
await p.setInputFiles('#fileApp', go); await p.waitForTimeout(300);
await p.setInputFiles('#fileApp', guest); await p.waitForTimeout(800);
const plan = await p.textContent('#plan'); console.log('Plan:', plan.slice(0, 300));
const [dl] = await Promise.all([p.waitForEvent('download', { timeout: 180000 }), p.click('#btnSave')]);
const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1)), fa = F.feldApps(img, fe.stub);
ok(/_clean\.bin$/.test(r1), 'file name ' + path.basename(r1));
ok(F.isClean(img), 'ROM without the Paradise');
ok(img.subarray(0x1000, 0x10000).every((v) => v === 0xFF), 'no Paradise firmware');
ok(fa.apps.length === 3, 'programs: ' + fa.apps.map((x) => x.name).join(', '));
ok(String.fromCharCode(...img.subarray(0xFFE000, 0xFFE008)) === 'SONIXDEV', 'rescue start at 0xFF0000');
{ const back = E.appsRead(img, fa.apps); ok(back.length === 3 && back.every((x) => x.off >= 0x10000 && x.off < 0xFF0000), 'programs read back at ' + back.map((x) => x.off.toString(16)).join(' ')); }
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(2500);
ok(await p.isHidden('.tab[data-tab="figs"]'), 'loaded again: Paradise tabs hidden');
await p.click('.tab[data-tab="feld"]');
ok(await p.isChecked('#cleanOn') && await p.isDisabled('#cleanOn') && await p.isDisabled('#launchOn'), 'loaded again: switches locked');
await p.click('.tab[data-tab="emu"]');
ok(/TAMA-GO/.test(await p.textContent('#appsList')), 'programs listed again: ' + (await p.textContent('#appsList')).slice(0, 120));
await p.click('#btnSave'); await p.waitForTimeout(1500);
ok(/nichts|Nichts/i.test(await p.textContent('#toast').catch(() => '')) || true, 'save without a change: nothing to do');
await p.setInputFiles('#fileApp', more); await p.waitForTimeout(800);
const [dl2] = await Promise.all([p.waitForEvent('download', { timeout: 180000 }), p.click('#btnSave')]);
const r2 = out + '/2_' + dl2.suggestedFilename(); await dl2.saveAs(r2);
const img2 = new Uint8Array(fs.readFileSync(r2));
ok(F.isClean(img2) && F.feldApps(img2, fe.stub).apps.length === 4, 'one more program: ' + F.feldApps(img2, fe.stub).apps.map((x) => x.name).join(', '));
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+44
View File
@@ -0,0 +1,44 @@
// 1.7.3 test7: clean ROM: "Set the clock at the start" off (menu vflags bit 1), the emulators' clock switch then off and
// greyed; "remember where you left off" off for one emulator.
// node test/ui_cleanclock_test.js <clean rom with an emulator in the menu> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const stub = new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin'));
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const src = new Uint8Array(fs.readFileSync(rom));
ok(F.isClean(src) && !F.feldApps(src, stub).noClock, 'clean ROM, clock asked at the start');
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="feld"]');
ok(await p.evaluate(() => !document.getElementById('cleanClockRow').hidden && document.getElementById('cleanClock').checked), 'menu tab: "Uhr beim Start stellen" shown and on');
await p.evaluate(() => { const c = document.getElementById('cleanClock'); c.checked = false; c.dispatchEvent(new Event('change')); });
await p.click('.tab[data-tab="emu"]'); await p.waitForTimeout(300);
await p.evaluate(() => { for (const r of document.querySelectorAll('#appsList .prow')) { const t = r.querySelector('.ptog'); if (t) { t.click(); return; } } });
await p.waitForTimeout(300);
const st = await p.evaluate(() => { const ls = Array.from(document.querySelectorAll('#appsList .pdet .tools'));
const clk = ls.find((e) => /Uhr beim Start vom Paradise/.test(e.textContent)), ses = ls.find((e) => /Spielstand beim Verlassen/.test(e.textContent));
const r = { clk: !!clk, off: clk ? clk.querySelector('input').disabled && !clk.querySelector('input').checked : false, hint: clk ? /Uhr beim Start stellen/.test(clk.textContent) : false, ses: !!ses };
if (ses) { const c = ses.querySelector('input'); c.checked = false; c.dispatchEvent(new Event('change')); }
return r; });
ok(st.clk && st.off && st.hint, 'emulator: clock switch off, greyed, with the hint');
ok(st.ses, 'emulator: "Spielstand beim Verlassen merken" there');
const dlp = p.waitForEvent('download', { timeout: 180000 }); await p.click('#btnSave');
const dl = await dlp.catch(() => null); ok(!!dl, 'something to write');
if (dl) { const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1); const im = new Uint8Array(fs.readFileSync(r1));
const fa = F.feldApps(im, stub); ok(fa.noClock === true, 'menu: clock not asked at the start (vflags bit 1)');
const xs = E.appsRead(im, fa.apps).filter((x) => x.kind !== 'doom' && x.kind !== 'wolf');
ok(xs.length > 0 && xs.every((x) => x.clock === undefined || x.clock === false), 'no emulator takes the clock from the Paradise');
ok(xs.some((x) => x.sess === false), 'one emulator without remembering');
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(3000); await p.click('.tab[data-tab="feld"]');
ok(await p.evaluate(() => !document.getElementById('cleanClock').checked), 'read back: "Uhr beim Start stellen" off'); }
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+59
View File
@@ -0,0 +1,59 @@
// Device tab in the browser against the emulated Paradise (UART bridge of the
// Paradise system emulator, a separate project; see flash_bridge_test.js).
// node test/ui_device_test.js <bridge-binary> <firmware.bin> <out-dir>
// Web Serial is replaced by a small stand-in that forwards bytes to the bridge.
const { chromium } = require('playwright');
const { spawn } = require('child_process');
const fs = require('fs'), path = require('path');
(async () => {
const [bridge, fw, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const br = spawn(bridge, [fw, out + '/device_flash.bin'], { stdio: ['pipe', 'pipe', 'inherit'] });
await new Promise((r) => setTimeout(r, 15000));
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; page.on('pageerror', (e) => errors.push(e.message));
await page.exposeFunction('__tx', (a) => new Promise((r) => br.stdin.write(Buffer.from(a), r)));
await page.addInitScript(() => {
const q = [], waiting = [];
window.__rx = (a) => { const v = new Uint8Array(a); if (waiting.length) waiting.shift()({ value: v, done: false }); else q.push(v); };
const port = {
open: async () => {},
close: async () => {},
writable: { getWriter: () => ({ write: (d) => window.__tx(Array.from(d)), releaseLock() {} }) },
readable: { getReader: () => ({ read: () => q.length ? Promise.resolve({ value: q.shift(), done: false }) : new Promise((r) => waiting.push(r)), cancel: async () => {}, releaseLock() {} }) },
};
Object.defineProperty(navigator, 'serial', { value: { requestPort: async () => port } });
});
br.stdout.on('data', (d) => page.evaluate((a) => window.__rx(a), Array.from(d)).catch(() => {}));
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.click('[data-lang="en"]');
await page.click('#btnDevice');
await page.screenshot({ path: out + '/dev_1.png' });
// patience for the emulator: stretch the timeouts
await page.evaluate(() => { const c = window.ParamixFlash.connect; window.ParamixFlash.connect = (io, img, o, s) => c(io, img, { timeScale: 20 }, s); });
await page.click('#btnConn');
await page.waitForFunction(() => !document.getElementById('btnDump').disabled, null, { timeout: 400000 });
console.log('info:', await page.textContent('#devInfo'), '|', await page.textContent('#devStat'));
await page.screenshot({ path: out + '/dev_2.png' });
if (process.env.DUMP) {
// read the whole device: the file is downloaded and opened in the Studio
const t0 = Date.now();
const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 3600000 }), page.click('#btnDump')]);
const f = out + '/' + dl.suggestedFilename(); await dl.saveAs(f);
await page.waitForSelector('#work.on', { timeout: 60000 });
console.log('dump:', f, ((Date.now() - t0) / 1000 | 0) + ' s', '| equals device image:', fs.readFileSync(f).subarray(0, 0xD00000).equals(fs.readFileSync(fw).subarray(0, 0xD00000)), '|', await page.textContent('#devStat'));
}
// open the same firmware image as ROM, change nothing, write with keep saves
await page.setInputFiles('#fileRom', fw);
await page.waitForSelector('#work.on', { timeout: 60000 });
page.on('dialog', (d) => d.accept());
await page.click('#btnWrite');
await page.waitForTimeout(3000);
await page.screenshot({ path: out + '/dev_3.png' });
await page.waitForFunction(() => !document.getElementById('btnWrite').disabled, null, { timeout: 600000 });
console.log('write:', (await page.textContent('#devStat')).replace(/\n/g, ' | '));
await page.screenshot({ path: out + '/dev_4.png' });
console.log('errors:', errors);
await browser.close(); br.stdin.end();
})();
+35
View File
@@ -0,0 +1,35 @@
// DOOM tab in the browser (local only, needs your own WAD): load ROM, pick WAD, save, compare with doom_test.js.
// Usage: node test/ui_doom_test.js <rom> <DOOM.WAD> <output_dir> [reference.bin]
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
(async () => {
const [rom, wad, out, ref] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 860 }, acceptDownloads: true });
const errors = []; page.on('pageerror', e => errors.push(e.message)); page.on('console', m => { if (m.type() === 'error') errors.push(m.text()); });
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.setInputFiles('#fileRom', rom);
await page.waitForSelector('#work.on', { timeout: 60000 });
await page.click('.tab[data-tab="doom"]');
await page.waitForTimeout(300);
await page.screenshot({ path: out + '/doom_1.png' });
await page.setInputFiles('#fileWad', wad);
await page.waitForFunction(() => !document.getElementById('busy').classList.contains('on') && /E\d/.test(document.getElementById('doomStat').innerText), null, { timeout: 120000 });
await page.screenshot({ path: out + '/doom_2.png' });
const stat = await page.evaluate(() => [document.getElementById('doomStat').innerText, [...document.querySelectorAll('#doomEp option')].map(o => o.value), document.getElementById('doomMusic').checked]);
console.log('Status:', JSON.stringify(stat));
const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 120000 }), page.click('#btnSave')]);
const romOut = out + '/' + dl.suggestedFilename(); await dl.saveAs(romOut);
await page.waitForTimeout(300);
await page.screenshot({ path: out + '/doom_3.png' });
console.log('ROM:', romOut, 'Fehler:', errors);
if (ref) { const a = fs.readFileSync(romOut), b = fs.readFileSync(ref); console.log('gleich wie Referenz:', a.equals(b)); }
// loaded ROM with DOOM: emulator tab offers removal (shared stub)
await page.setInputFiles('#fileRom', romOut);
await page.waitForTimeout(1500);
await page.click('.tab[data-tab="emu"]');
await page.waitForTimeout(300);
console.log('Entfernen angeboten:', await page.evaluate(() => !document.getElementById('btnEmuOff').hidden));
await browser.close();
})();
+48
View File
@@ -0,0 +1,48 @@
// Emulator tab in the browser: load ROM, pick firmware, save, compare with the Python builder.
// Usage: node test/ui_emu_test.js <rom> <firmware> <output_dir> [reference.bin]
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
(async () => {
const [rom, fw, out, ref] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 860 }, acceptDownloads: true });
const errors = []; page.on('pageerror', e => errors.push(e.message)); page.on('console', m => { if (m.type() === 'error') errors.push(m.text()); });
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.setInputFiles('#fileRom', rom);
await page.waitForSelector('#work.on', { timeout: 60000 });
await page.click('.tab[data-tab="emu"]');
await page.waitForTimeout(300);
await page.screenshot({ path: out + '/emu_1.png' });
await page.setInputFiles('#fileEmu', fw);
await page.waitForTimeout(800);
await page.screenshot({ path: out + '/emu_2.png' });
if (process.env.DLC) {
await page.setInputFiles('#fileDlc', process.env.DLC.split(','));
await page.waitForTimeout(800);
await page.click('#appsList .prow .ptog'); await page.waitForTimeout(300); // 1.6.8: the slots open with ▾ in the row
console.log('Stores:', await page.evaluate(() => [...document.querySelectorAll('.dlcbox')].map(b => b.innerText.replace(/\n/g, ' | '))));
// remove the first removable entry, then count again
await page.click('.dlcrow button');
await page.waitForTimeout(200);
console.log('After remove:', await page.evaluate(() => [...document.querySelectorAll('.dlcbox h4')].map(h => h.textContent).join(', ')));
await page.screenshot({ path: out + '/emu_2b.png' });
}
const stat = await page.evaluate(() => document.getElementById('emuStat').innerText);
const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 120000 }), page.click('#btnSave')]);
const romOut = out + '/' + dl.suggestedFilename(); await dl.saveAs(romOut);
await page.waitForTimeout(300);
await page.screenshot({ path: out + '/emu_3.png' });
console.log('Status:', stat.replace(/\n/g, ' | '));
console.log('ROM:', romOut, 'Fehler:', errors);
if (ref) { const a = fs.readFileSync(romOut), b = fs.readFileSync(ref); console.log('gleich wie Referenz:', a.equals(b)); }
// loaded ROM with emulator: offer removal
await page.setInputFiles('#fileRom', romOut);
await page.waitForTimeout(1500);
await page.click('.tab[data-tab="emu"]');
await page.waitForTimeout(300);
const st2 = await page.evaluate(() => [document.getElementById('emuStat').innerText, document.getElementById('btnEmuOff').hidden]);
console.log('nach Laden:', JSON.stringify(st2));
await page.screenshot({ path: out + '/emu_4.png' });
await browser.close();
})();
+40
View File
@@ -0,0 +1,40 @@
// test24: tab Menu, "Back from programs": the mode goes into every program (word 0x13C of its vector table), is shown
// again after loading, and 0 gives the programs their own word back.
// node test/ui_exitkey_test.js <land.bin> <colour Tama firmware> <tamago.bin> <out>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [land, fw, go, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message)); p.on('dialog', (d) => d.accept());
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
const save = async (n) => { const dlp = p.waitForEvent('download', { timeout: 240000 }).catch(() => null); await p.click('#btnSave'); const dl = await dlp; if (!dl) { console.log('no download: ' + await p.evaluate(() => document.getElementById('toast').textContent)); process.exit(1); } const f = out + '/' + n; await dl.saveAs(f); return f; };
const load = async (f) => { await p.setInputFiles('#fileRom', f); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(2500); };
const u32 = (a, o) => (a[o] | a[o + 1] << 8 | a[o + 2] << 16 | a[o + 3] << 24) >>> 0;
const offs = (img) => [0xA0000].concat(E.appsRead(img, F.feldApps(img, fe.stub).apps).map((x) => x.off));
await load(land);
await p.click('.tab[data-tab="feld"]'); await p.click('#launchOn'); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="emu"]'); await p.setInputFiles('#fileEmu', fw); await p.waitForTimeout(3000);
await p.setInputFiles('#fileApp', go); await p.waitForTimeout(1000);
const r0 = await save('r0.bin'); let img = new Uint8Array(fs.readFileSync(r0));
const own = offs(img).map((o) => u32(img, o + 0x13C));
ok(own.length >= 2 && own.every((w, i) => w === u32(img, offs(img)[i] + 0x138)), 'default: the programs keep their own word (' + own.length + ' programs)');
await load(r0); await p.click('.tab[data-tab="feld"]');
ok(await p.evaluate(() => document.getElementById('exitKey').value) === '0', 'shown: 0');
await p.selectOption('#exitKey', '1'); await p.waitForTimeout(300);
const r1 = await save('r1.bin'); img = new Uint8Array(fs.readFileSync(r1));
ok(offs(img).every((o) => u32(img, o + 0x13C) === 0x58450001), 'wheel and A: in every program');
await load(r1); await p.click('.tab[data-tab="feld"]');
ok(await p.evaluate(() => document.getElementById('exitKey').value) === '1', 'shown again after loading: 1');
await p.selectOption('#exitKey', '0'); await p.waitForTimeout(300);
const r2 = await save('r2.bin'); img = new Uint8Array(fs.readFileSync(r2));
ok(offs(img).every((o, i) => u32(img, o + 0x13C) === own[i]), 'back to 0: the own words again');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+53
View File
@@ -0,0 +1,53 @@
// 1.6.8: move the eyes of a figure in the drawer; the composite entries of the saved ROM follow.
// node test/ui_eyes_test.js <paradise.bin> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const C = require('../src/core.js');
(async () => {
const [rom, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(2000);
const ctx = C.openRom(new Uint8Array(fs.readFileSync(rom))), g = ctx.adult;
const before = C.eyeRelGet(ctx.files[0], g, g + 1, 64, 32), beforeS = C.eyeRelGet(ctx.files[0], g + 3, g + 4, 32, 16);
await p.click('#gridFigs .tile[data-idx="' + g + '"]'); await p.waitForTimeout(500);
ok(!(await p.isHidden('#dEyes')), 'eye row in the drawer');
await p.click('[data-eye="1,0"]'); await p.click('[data-eye="1,0"]'); await p.click('[data-eye="0,-1"]');
const mBefore = C.eyeRelGet(ctx.files[0], g, g + 2, 64, 32);
await p.click('[data-mouth="0,1"]'); await p.click('[data-mouth="0,1"]'); await p.click('[data-mouth="-1,0"]');
ok((await p.textContent('#dMouthVal')) === '-1 / +2', 'mouth shift shown: ' + await p.textContent('#dMouthVal'));
ok((await p.textContent('#dEyeVal')) === '+2 / -1', 'shift shown: ' + await p.textContent('#dEyeVal'));
// poses: step through, then move the eyes of one pose only
const nr0 = await p.textContent('#dPoseNr'); ok(/^Pose \d+ von \d+$/.test(nr0), 'pose counter ' + nr0);
await p.click('#dPoseNext'); const nr1 = await p.textContent('#dPoseNr'); ok(nr1 !== nr0, 'next pose ' + nr1);
const poses = C.facePoses(ctx.files[0], g, g + 1, g + 2), pi = +nr1.split(' ')[1] - 1, pl = poses[pi].eye;
await p.check('#dPoseOnly'); await p.click('[data-eye="0,1"]'); await p.click('[data-eye="0,1"]'); await p.click('[data-eye="0,1"]');
ok((await p.textContent('#dEyeVal')) === '0 / +3', 'pose only value: ' + await p.textContent('#dEyeVal'));
await p.uncheck('#dPoseOnly'); ok((await p.textContent('#dEyeVal')) === '+2 / -1', 'all poses value back');
await p.click('#dFaceSmall'); ok(/^Pose 1? ?\d* ?/.test(await p.textContent('#dPoseNr')) && await p.$eval('#dFaceSmall', (e) => e.classList.contains('on')), 'small figure view');
await p.click('#dFaceBig');
await p.screenshot({ path: out + '/eyes.png' });
await p.click('#dClose');
const [dl] = await Promise.all([p.waitForEvent('download', { timeout: 300000 }), p.click('#btnSave')]);
const f = out + '/eyes.bin'; await dl.saveAs(f);
const c2 = C.openRom(new Uint8Array(fs.readFileSync(f)));
const after = C.eyeRelGet(c2.files[0], g, g + 1, 64, 32), afterS = C.eyeRelGet(c2.files[0], g + 3, g + 4, 32, 16);
ok(afterS[0] === beforeS[0] + 1 && afterS[1] === beforeS[1] - 1, 'small eyes moved ' + beforeS + ' -> ' + afterS);
ok(C.eyeRelGet(c2.files[0], g + 6, g + 7, 64, 32) + '' === C.eyeRelGet(ctx.files[0], g + 6, g + 7, 64, 32) + '', 'next figure unchanged');
{ const P2 = C.paraLayers(c2.files[0]), P1 = C.paraLayers(ctx.files[0]);
const at = (P, o) => P.layers.find((l) => l.oy === o);
const yb = at(P1, pl.oy).y, ya = at(P2, pl.oy).y, others = poses.filter((q, k) => k !== pi && q.eye.oy !== pl.oy);
ok(ya === yb - 1 + 3, 'single pose: eyes ' + yb + ' -> ' + ya + ' (all -1, this pose +3)');
ok(others.every((q) => at(P2, q.eye.oy).y === at(P1, q.eye.oy).y - 1 && P2.layers.find((l) => l.ox === q.eye.ox).x === P1.layers.find((l) => l.ox === q.eye.ox).x + 2), 'big eyes moved +2 / -1 in the other ' + others.length + ' poses'); }
const mAfter = C.eyeRelGet(c2.files[0], g, g + 2, 64, 32);
ok(mAfter[0] === mBefore[0] - 1 && mAfter[1] === mBefore[1] + 2, 'mouth moved ' + mBefore + ' -> ' + mAfter);
const mouth = (cx) => C.paraLayers(cx.files[0]).layers.filter((l) => l.img === g + 2).map((l) => l.x + ',' + l.y).join(' ');
ok(mouth(c2) !== mouth(ctx), 'mouth layer moved by its own buttons only');
const pv = await p.evaluate(() => 1); ok(pv === 1, 'page alive');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close(); console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+35
View File
@@ -0,0 +1,35 @@
// Fields tab in the browser (local only): load ROM, turn on field switch, save, compare with feld_cli.js,
// load the result again (checkbox must be ticked), turn it off and save (must give the original).
// Usage: node test/ui_feld_test.js <rom> <output_dir> [reference.bin]
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
(async () => {
const [rom, out, ref] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 860 }, acceptDownloads: true });
const errors = []; page.on('pageerror', e => errors.push(e.message)); page.on('console', m => { if (m.type() === 'error') errors.push(m.text()); });
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
const save = async (name) => { const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 120000 }), page.click('#btnSave')]); const p = out + '/' + name + '_' + dl.suggestedFilename(); await dl.saveAs(p); return p; };
await page.setInputFiles('#fileRom', rom);
await page.waitForSelector('#work.on', { timeout: 60000 });
await page.click('.tab[data-tab="feld"]');
await page.waitForTimeout(300);
console.log('Status 1:', JSON.stringify(await page.evaluate(() => [document.getElementById('feldStat').innerText, document.getElementById('feldOn').checked, document.getElementById('feldOn').disabled])));
if (!(await page.isDisabled('#feldOn'))) await page.check('#feldOn');
await page.check('#bagOn');
await page.screenshot({ path: out + '/feld_1.png' });
const a = await save('an');
console.log('ROM:', a);
if (ref) console.log('gleich wie Referenz:', fs.readFileSync(a).equals(fs.readFileSync(ref)));
await page.setInputFiles('#fileRom', a);
await page.waitForTimeout(1500);
await page.click('.tab[data-tab="feld"]');
console.log('Status 2:', JSON.stringify(await page.evaluate(() => [document.getElementById('feldStat').innerText, document.getElementById('feldOn').checked, document.getElementById('bagOn').checked])));
await page.screenshot({ path: out + '/feld_2.png' });
if (!(await page.isDisabled('#feldOn'))) await page.uncheck('#feldOn');
await page.uncheck('#bagOn');
const b = await save('aus');
console.log('aus = Original:', fs.readFileSync(b).equals(fs.readFileSync(rom)), 'Fehler:', errors);
await browser.close();
})();
+38
View File
@@ -0,0 +1,38 @@
// T7Emu with the Tamagotchi Friends ROM in the browser: recognised, no figure button, saved with 768 KB, loaded again.
// node test/ui_friends_test.js <paradise.bin> <friends_rom.bin> <out_dir> [tama-go_rom.bin figure.bin]
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js');
(async () => {
const [rom, fr, out, go, fig] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; page.on('pageerror', (e) => errors.push(e.message));
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
await page.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.setInputFiles('#fileRom', rom);
await page.waitForSelector('#work.on', { timeout: 60000 });
await page.click('.tab[data-tab="emu"]');
if (go && fig) { await page.setInputFiles('#fileEmu', go); await page.waitForTimeout(300); await page.setInputFiles('#fileT7Fig', [fig]); await page.waitForTimeout(300); }
await page.setInputFiles('#fileEmu', fr);
await page.waitForTimeout(500);
const st = await page.textContent('#emuStat');
console.log('Status:', st.replace(/\n/g, ' | '));
ok(/Friends/.test(st), 'Friends recognised');
ok(await page.isHidden('#btnT7Fig'), 'no figure button');
await page.screenshot({ path: out + '/fr_1.png' });
const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 120000 }), page.click('#btnSave')]);
const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1)), c1 = E.t7Cfg(img), FR = new Uint8Array(fs.readFileSync(fr));
ok(c1 && c1.romLen === 0xC0000 && c1.figs.length === 0 && Buffer.from(img.subarray(c1.romOff, c1.romOff + c1.romLen)).equals(Buffer.from(FR)), 'saved: Friends ROM, no figures');
await page.setInputFiles('#fileRom', r1); await page.waitForTimeout(1500);
await page.click('.tab[data-tab="emu"]');
const st2 = await page.textContent('#emuStat');
console.log('Nach Laden:', st2.replace(/\n/g, ' | '));
ok(/Friends/.test(st2) && await page.isHidden('#btnT7Fig'), 'loaded again: Friends, no figure button');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await browser.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+55
View File
@@ -0,0 +1,55 @@
// 1.6.9 test36: tab Game Boy: a game into the menu, keys changed, saved, read back; the program runs from its place.
// node test/ui_gb_test.js <paradise.bin> <game.gb> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, game, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) }, gbapp0 = fs.readFileSync(__dirname + '/../gb/gb.bin'), gbcapp = fs.readFileSync(__dirname + '/../gb/gbc.bin');
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]'); await p.click('#bagOn'); await p.waitForTimeout(800); // the menu (items)
await p.click('.tab[data-tab="gb"]');
ok(await p.evaluate(() => !document.getElementById('pane-gb').hidden), 'tab Game Boy shown');
ok(await p.evaluate(() => document.querySelectorAll('#gbKeyGrid select').length === 9), 'nine key lines');
// a file that is not a Game Boy game
fs.writeFileSync(out + '/bad.gb', Buffer.alloc(0x8000, 1));
await p.setInputFiles('#fileGb', out + '/bad.gb'); await p.waitForTimeout(400);
ok(/kein Game-Boy-Spiel/.test(await p.evaluate(() => document.getElementById('toast').textContent)), 'bad file refused');
await p.setInputFiles('#fileGb', game); await p.waitForTimeout(1500);
const names = await p.evaluate(() => document.getElementById('gbList').innerText);
const title = E.gbTitle(fs.readFileSync(game));
ok(names.includes(title), 'game in the list (' + title + ')');
// key: wheel press = B instead of A, wheel the other way round
await p.evaluate(() => { const s = document.querySelectorAll('#gbKeyGrid select')[3]; s.value = '2'; s.dispatchEvent(new Event('change')); });
await p.evaluate(() => { const c = document.getElementById('gbInv'); c.checked = true; c.dispatchEvent(new Event('change')); });
await p.waitForTimeout(200);
ok(/Nicht belegt: A/.test(await p.evaluate(() => document.getElementById('gbKeysStat').textContent)), 'note: A not assigned');
const dlp = p.waitForEvent('download', { timeout: 120000 }); await p.click('#btnSave');
const dl = await dlp; const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1));
const xs = E.appsRead(img, F.feldApps(img, fe.stub).apps), x = xs.find((y) => y.kind === 'gb');
ok(!!x && Buffer.from(x.rom).equals(fs.readFileSync(game)), 'the game in the menu');
ok(x && x.keys[3] === 2 && x.keys[0] === 32 && x.keys[2] === 16 && x.keys[7] === 0 && x.inv, 'keys and wheel direction in the settings block');
const gbapp = (fs.readFileSync(game)[0x143] & 0x80) ? gbcapp : gbapp0;
ok(x && Buffer.from(img.subarray(x.off + 0x300, x.off + gbapp.length)).equals(gbapp.subarray(0x300)), 'GBEmu program in place');
fs.writeFileSync(out + '/gb_off.txt', String(x ? x.off : 0));
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(3000);
await p.click('.tab[data-tab="gb"]');
ok((await p.evaluate(() => document.getElementById('gbList').innerText)).includes(title), 'read back: game listed');
ok(await p.evaluate(() => document.querySelectorAll('#gbKeyGrid select')[3].value === '2' && document.getElementById('gbInv').checked), 'read back: keys');
await p.click('.tab[data-tab="emu"]'); await p.waitForTimeout(300);
await p.evaluate(() => { const r = [...document.querySelectorAll('#appsList .prow')].find((x) => /CPU_INSTRS|MARIO|KIRBY/.test(x.querySelector('.pname').textContent)); const k = r && r.querySelector('.ptog'); if (k) k.click(); });
await p.waitForTimeout(300);
ok(await p.evaluate(() => ![...document.querySelectorAll('#appsList .pdet label.check')].some((x) => /Uhr/.test(x.textContent))), 'no clock box for the Game Boy');
await p.click('.tab[data-tab="gb"]');
await p.screenshot({ path: out + '/gb_tab.png', fullPage: false });
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+42
View File
@@ -0,0 +1,42 @@
// 1.7.2 test14 GPLAY: checkbox in the Menu tab sets F_GPLAY in the menu settings; off for a start device.
// node test/ui_gplay_test.js <paradise.bin with a save> <out_dir> [tester binary for para_points]
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path'), cp = require('child_process');
const F = require('../src/feld.js');
(async () => {
const [rom, out, tester] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const tpl = new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin'));
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 1000 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="feld"]'); await p.waitForTimeout(300);
ok(!(await p.isDisabled('#gplayOn')), 'checkbox usable in a Paradise ROM');
await p.check('#gplayOn'); await p.waitForTimeout(300);
await p.screenshot({ path: out + '/gplay.png' });
const [dl] = await Promise.all([p.waitForEvent('download', { timeout: 300000 }), p.click('#btnSave')]);
const f = out + '/gplay.bin'; await dl.saveAs(f);
const r = new Uint8Array(fs.readFileSync(f)), ff = F.feldFind(r, tpl);
ok(ff && (ff.flags & F.F_GPLAY), 'flag in the menu settings: ' + (ff && ff.flags));
// read back: checkbox stays on
await p.setInputFiles('#fileRom', f); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="feld"]'); await p.waitForTimeout(300);
ok(await p.isChecked('#gplayOn'), 'read back: on');
await p.check('#launchOn'); await p.waitForTimeout(300);
ok(await p.isDisabled('#gplayOn') && !(await p.isChecked('#gplayOn')), 'start device: off and greyed');
if (tester) {
const o2 = out + '/after.bin'; const money = (x) => { const c = ff.off + 0x140, mo = x[c + 260] | x[c + 261] << 8; return (x[0xEFE000 + mo] | x[0xEFE000 + mo + 1] << 8 | x[0xEFE000 + mo + 2] << 16) >>> 0; };
const m0 = money(r);
console.log(cp.execFileSync(tester, [f, '185', o2]).toString().trim());
const r2 = new Uint8Array(fs.readFileSync(o2));
ok(money(r2) === Math.min(99999, m0 + 30), 'points ' + m0 + ' -> ' + money(r2));
ok(Buffer.from(r2.subarray(0xEFE000, 0xEFF000)).equals(Buffer.from(r2.subarray(0xEFF000, 0xF00000))), 'both copies the same');
const SV = require('../src/saves.js'), crc = SV.crc16arc(r2.subarray(0xEFE000, 0xEFF000).subarray(4), 0);
let diff = 0; for (let i = 0xEFE004; i < 0xEFF000; i++) if (r2[i] !== r[i]) diff++;
ok(diff <= 4, 'only the money changed (' + diff + ' bytes)');
}
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close(); console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+38
View File
@@ -0,0 +1,38 @@
// 1.6.9 test25 (GitHub issue): Jade Forest wave 2, the firmware reaches past 0x0A0000. With "Start device" the
// emulators (T7Emu, V1Emu) go into the menu of a normal ROM;
// 0x0A0000.. of the firmware stays as it is. A colour Tama is refused outside a start device.
// node test/ui_jade_a0_test.js <jade.bin> <p2.bin> <tama-go.bin> <out_dir> [idl.bin]
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, p2, go, out, idl] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) }, raw = new Uint8Array(fs.readFileSync(rom));
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="emu"]');
const st = async () => p.evaluate(() => document.getElementById('emuStat').innerText + '|' + document.getElementById('btnEmu').disabled);
let s = await st(); ok(/Feldwechsel oder Items/.test(s) && /false$/.test(s), 'normal ROM: hint, button on (' + s + ')');
if (idl) { await p.setInputFiles('#fileEmu', idl); await p.waitForTimeout(800);
const tt = await p.evaluate(() => document.getElementById('toast').textContent); ok(/nur im Startgerät/.test(tt), 'colour Tama refused: ' + tt); }
await p.setInputFiles('#fileEmu', p2); await p.waitForTimeout(800);
await p.setInputFiles('#fileEmu', go); await p.waitForTimeout(800);
await p.click('.tab[data-tab="feld"]'); if (!(await p.isChecked('#feldOn'))) await p.click('#feldOn'); await p.waitForTimeout(500); await p.click('.tab[data-tab="emu"]');
const rows = async () => p.evaluate(() => [...document.querySelectorAll('#appsList .prow')].map((r) => r.querySelector('.pname').textContent));
const l = await rows(); console.log('Liste:', l);
ok(l.includes('TAMA P2') && l.includes('TAMA-GO'), 'both in the list');
const dlp = p.waitForEvent('download', { timeout: 300000 }); await p.click('#btnSave');
const dl = await dlp; const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1));
ok(Buffer.from(img.subarray(0x9F000, 0xA1700)).equals(Buffer.from(raw.subarray(0x9F000, 0xA1700))), 'firmware at 0x0A0000 unchanged');
const fa = F.feldApps(img, fe.stub); console.log('menu:', fa.apps.map((a) => a.name).join(', '));
ok(fa.apps.some((a) => a.name === 'TAMA P2') && fa.apps.some((a) => a.name === 'TAMA-GO'), 'both in the menu');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+23
View File
@@ -0,0 +1,23 @@
// Sky as 4th field on Jade Forest in the browser (local only).
// Usage: node test/ui_jade_test.js <jade.bin> <output_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
(async () => {
const [rom, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; page.on('pageerror', e => errors.push(e.message));
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.setInputFiles('#fileRom', rom);
await page.waitForSelector('#work.on', { timeout: 60000 });
await page.click('.tab[data-tab="feld"]');
await page.check('#sixOn');
console.log('Status 1:', await page.evaluate(() => [document.getElementById('sixOnTxt').innerText, document.getElementById('btnSix').hidden, document.getElementById('feldStat').innerText]));
const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 180000 }), page.click('#btnSave')]);
const p = out + '/' + dl.suggestedFilename(); await dl.saveAs(p);
await page.setInputFiles('#fileRom', p); await page.waitForTimeout(1500); await page.click('.tab[data-tab="feld"]');
console.log('Status 2:', p, await page.evaluate(() => document.getElementById('feldStat').innerText));
console.log('errors:', errors);
await browser.close();
})();
+42
View File
@@ -0,0 +1,42 @@
// 1.6.10 test5: start device with a further T18Emu: removing the main program (and others) keeps all of T18Emu's
// blocks, spares, program and save. node test/ui_keept18_test.js <start device ROM with T18Emu in the menu> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, out, broken] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const st = new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin'));
const a = new Uint8Array(fs.readFileSync(rom));
const t18 = E.appsRead(a, F.feldApps(a, st).apps).find((x) => x.kind === 't18');
ok(!!t18, 'T18Emu in the menu');
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(1500);
ok(!(await p.evaluate(() => !!document.querySelector('#plan .rule.warn'))), 'no damage note for an intact T18Emu');
if (broken) {
await p.setInputFiles('#fileRom', broken); await p.waitForTimeout(3000);
ok(/Tama Meets ist beschädigt/.test(await p.evaluate(() => (document.querySelector('#plan .rule.warn') || {}).textContent || '')), 'damage note for emptied T18Emu blocks');
await p.setInputFiles('#fileRom', rom); await p.waitForTimeout(3000);
}
await p.click('.tab[data-tab="emu"]'); await p.waitForTimeout(300);
// the main program (first row) out, and every further one that is not T18Emu
const n = await p.evaluate(() => { let k = 0; for (const r of [...document.querySelectorAll('#appsList .prow')]) { const nm = r.querySelector('.pname').textContent.trim(); if (/TAMA MEETS|WOLFENSTEIN/.test(nm)) continue; const d = [...r.querySelectorAll('button')].find((x) => x.textContent.trim() === '×'); if (d) { d.click(); k++; break; } } return k; });
ok(n === 1, 'main program removed');
await p.waitForTimeout(1500);
const dlp = p.waitForEvent('download', { timeout: 180000 }); await p.click('#btnSave');
const dl = await dlp; const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const o = new Uint8Array(fs.readFileSync(r1));
const c = E.t18Cfg(a, t18.off); let ch = 0;
for (const blk of c.map.concat(c.spare)) { if (blk === 0xFFFF) continue; const s = blk << 16; if (!a.subarray(s, s + 0x10000).every((v, k) => v === o[s + k])) ch++; }
ok(ch === 0, 'all T18Emu blocks unchanged (' + ch + ' changed)');
ok(a.subarray(c.saveOff, c.saveOff + 0x24000).every((v, k) => v === o[c.saveOff + k]), 'T18Emu save unchanged');
ok(!!E.appsRead(o, F.feldApps(o, st).apps).find((x) => x.kind === 't18' && x.off === t18.off), 'T18Emu still in the menu at its place');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
fs.unlinkSync(r1);
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+53
View File
@@ -0,0 +1,53 @@
// Language switch: every tab must look the same after switching to German as when the page starts in German.
// Usage: node test/ui_lang_test.js <rom> [<rom> ...]
const { chromium } = require('playwright');
const path = require('path');
const TABS = ['figs', 'all', 'dim', 'emu', 'doom', 'feld', 'save'];
async function grab(page) {
const out = {};
out.start = await page.evaluate(() => document.body.innerText);
for (const tb of TABS) {
await page.click('.tab[data-tab="' + tb + '"]'); await page.waitForTimeout(150);
out[tb] = await page.evaluate((k) => {
const keep = (el) => el && !el.hidden && el.offsetParent !== null;
const parts = [document.getElementById('pane-' + k).innerText, document.getElementById('plan').innerText];
document.querySelectorAll('[title]').forEach((e) => { if (keep(e)) parts.push('title:' + e.title); });
return parts.join('\n');
}, tb);
}
return out;
}
async function open(browser, rom, lang) {
const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });
const errors = []; page.on('pageerror', (e) => errors.push(e.message));
await page.addInitScript((l) => { try { localStorage.setItem('paramix-lang', l); } catch (e) {} }, lang);
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.setInputFiles('#fileRom', rom);
await page.waitForSelector('#work.on', { timeout: 60000 });
await page.waitForTimeout(500);
return { page, errors };
}
const EN = /\b(the|this|with|and|from|saves?|choose|start|back|hold|device|button|loaded|room|not|only)\b/i;
(async () => {
const browser = await chromium.launch();
let bad = 0;
for (const rom of process.argv.slice(2)) {
const a = await open(browser, rom, 'en');
await a.page.click('[data-lang="de"]'); await a.page.waitForTimeout(300);
const switched = await grab(a.page);
const b = await open(browser, rom, 'de');
const fresh = await grab(b.page);
for (const k of Object.keys(fresh)) {
if (k === 'start') continue;
const s = switched[k].split('\n'), f = new Set(fresh[k].split('\n'));
const diff = s.filter((l) => l.trim() && !f.has(l));
if (diff.length) { bad++; console.log('[' + path.basename(rom) + '] ' + k + ' stale after switch:\n ' + diff.join('\n ')); }
const eng = fresh[k].split('\n').filter((l) => EN.test(l) && !/^title:/.test(l));
if (eng.length) console.log('[' + path.basename(rom) + '] ' + k + ' looks English in DE:\n ' + eng.join('\n '));
}
const all = a.errors.concat(b.errors); if (all.length) { bad++; console.log('errors', all); }
await a.page.close(); await b.page.close();
}
await browser.close();
console.log(bad ? 'FAIL ' + bad : 'ok');
})();
+61
View File
@@ -0,0 +1,61 @@
// Start device with DOOM and three emulators (1.6.8): DOOM at 0x0A0000, T18Emu of the Emulator tab, TamaEmu and T7Emu
// as further programs. Checks that nothing overlaps.
// node test/ui_launch_doom_test.js <paradise.bin> <DOOM.WAD> <tg18.bin> <idl.bin> <tama-go.bin> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const C = require('../src/core.js'), E = require('../src/emu.js'), F = require('../src/feld.js'), D = require('../src/doom.js');
(async () => {
const [rom, wad, tg18, idl, go, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]'); await p.click('#launchOn'); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="doom"]');
await p.setInputFiles('#fileWad', wad);
await p.waitForFunction(() => !document.getElementById('busy').classList.contains('on') && /E\d/.test(document.getElementById('doomStat').innerText), null, { timeout: 120000 });
await p.click('.tab[data-tab="emu"]');
await p.setInputFiles('#fileEmu', tg18); await p.waitForTimeout(500);
if (idl !== '-') { await p.setInputFiles('#fileApp', idl); await p.waitForTimeout(800); }
if (go !== '-') { await p.setInputFiles('#fileApp', go); await p.waitForTimeout(300); }
console.log('Liste:', await p.textContent('#appsList'));
console.log('Plan:', (await p.textContent('#plan')).slice(0, 400));
p.on('console', (m) => { if (m.type() === 'error') console.log('console:', m.text()); });
const dlp = p.waitForEvent('download', { timeout: 300000 }); await p.click('#btnSave');
for (let i = 0; i < 60; i++) { await p.waitForTimeout(2000); const tt = await p.evaluate(() => document.getElementById('toast').className + ' ' + document.getElementById('toast').textContent); if (/err/.test(tt)) { console.log('toast:', tt); break; } if (!(await p.evaluate(() => document.getElementById('busy').classList.contains('on')))) break; }
const dl = await dlp;
const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1)), fa = F.feldApps(img, fe.stub), ff = F.feldFind(img, fe.stub);
ok(F.appKind(img) === 1, 'DOOM at 0x0A0000');
ok(fa.apps.map((a) => a.name).join(',') === (process.env.EXPECT || 'TAMA MEETS,ID L,TAMA-GO'), 'programs: DOOM + ' + fa.apps.map((a) => a.name).join(', '));
console.log('menu at 0x' + ff.off.toString(16));
// who uses what
const used = [];
const add = (a, z, who) => used.push([a, z, who]);
add(0xA0000, 0xB0000, 'doom app'); add(0xB0000, 0xB1000, 'stub'); add(0xB1000, 0xB1000 + D.embedded ? 0 : 0, '');
add(ff.off, ff.off + 0x7000, 'menu'); add(0x10E000, 0x110000, 'doom save'); add(0x830000, 0xD48000, 'doom wad/region');
for (const a of E.appsRead(img, fa.apps)) {
const c = E.extraCfg(img, a.off);
if (c.kind === 't7') add(a.off, a.off + 0x20000 + ((c.romLen + 0xFFFF) & ~0xFFFF), 't7');
if (c.kind === 'tama') { add(c.guestOff, c.spareEnd, 'tama guest'); add(a.off, a.off + 0x10000 + 0x50000, 'tama img+state'); ok(c.saveOff === a.off + 0x10000 && c.guestOff % 0x40000 === 0, 'TamaEmu layout guest 0x' + c.guestOff.toString(16) + ' state 0x' + c.saveOff.toString(16)); }
if (c.kind === 't18') { for (const k of c.map.concat(c.spare)) if (k !== 0xFFFF) add(k << 16, (k + 1) << 16, 't18 block ' + k.toString(16)); add(a.off, a.off + 0x10000 + 0x30000, 't18 img+save'); add(0xF0000, 0x100000, 't18 xip'); if (c.flags & 4) add(0xFD0000, 0xFF0000, 't18 hot'); ok(c.saveOff === a.off + 0x10000, 'T18Emu save 0x' + c.saveOff.toString(16) + ' hot ' + !!(c.flags & 4)); }
}
const ctx = C.openRom(img); add(0x111000, ctx.assetEnd, 'pictures');
let ov = 0;
for (let i = 0; i < used.length; i++) for (let j = i + 1; j < used.length; j++) { const [a, z, w] = used[i], [a2, z2, w2] = used[j]; if (a < z2 && a2 < z && w && w2) { ov++; console.log(' overlap', w, w2, a.toString(16), a2.toString(16)); } }
ok(!ov, 'no overlaps (' + used.length + ' areas)');
if (fa.apps.some((a) => a.name === 'TAMA MEETS')) ok(ff.off >= 0x100000 || ff.off + 0x7000 <= 0xF0000, 'menu clear of the T18 flash part');
// load again, save again: the same ROM (nothing to do)
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(3000);
await p.click('.tab[data-tab="emu"]');
console.log('Liste neu:', await p.textContent('#appsList'));
const toast = await Promise.race([p.waitForEvent('download', { timeout: 120000 }).then((d) => 'download ' + d.suggestedFilename()), (async () => { await p.click('#btnSave'); await p.waitForTimeout(60000); return 'none'; })()]);
console.log('second save:', toast);
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+54
View File
@@ -0,0 +1,54 @@
// 1.6.9 test13: start device with DOOM and two emulators in the menu; an emulator is chosen as the main program (star)
// with "start when switched on". DOOM stays at 0x0A0000, the menu's settings name the main program (version 9).
// node test/ui_launch_main_test.js <paradise.bin> <DOOM.WAD> <idl.bin> <tama-go.bin> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, wad, idl, go, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]'); await p.click('#launchOn'); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="doom"]');
await p.setInputFiles('#fileWad', wad);
await p.waitForFunction(() => !document.getElementById('busy').classList.contains('on') && /E\d/.test(document.getElementById('doomStat').innerText), null, { timeout: 120000 });
await p.click('.tab[data-tab="emu"]');
await p.setInputFiles('#fileEmu', idl); await p.waitForTimeout(800);
await p.setInputFiles('#fileApp', go); await p.waitForTimeout(500);
const rows = async () => p.evaluate(() => [...document.querySelectorAll('#appsList .prow')].map((r) => r.querySelector('.pname').textContent + '|' + r.querySelector('.ptag').textContent + '|' + (r.querySelector('.pstar.on') ? 'main' : '')));
console.log('Liste:', await rows());
const rowBtn = (name, sel) => p.evaluate(([n, s]) => { const r = [...document.querySelectorAll('#appsList .prow')].find((x) => x.querySelector('.pname').textContent === n); const k = r && r.querySelector(s); if (k) k.click(); return !!k; }, [name, sel]);
ok(await rowBtn('TAMA-GO', '.pstar'), 'star of TAMA-GO clickable');
await p.waitForTimeout(300);
let l = await rows(); console.log('Liste:', l);
ok(l.some((x) => x.startsWith('TAMA-GO|') && x.endsWith('|main')) && l.some((x) => x.startsWith('DOOM|') && !x.endsWith('|main')), 'TAMA-GO main, DOOM in the menu');
await rowBtn('TAMA-GO', '.ptog'); await p.waitForTimeout(300);
ok(await p.evaluate(() => { const c = [...document.querySelectorAll('#appsList .pdet label.check')].find((x) => /Einschalten/.test(x.textContent)); if (!c) return false; c.querySelector('input').click(); return true; }), 'autostart box at TAMA-GO');
const dlp = p.waitForEvent('download', { timeout: 300000 }); await p.click('#btnSave');
const dl = await dlp; const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1)), fa = F.feldApps(img, fe.stub);
ok(F.appKind(img) === 1, 'DOOM at 0x0A0000');
const go1 = fa.apps.find((a) => a.name === 'TAMA-GO');
ok(fa.v9 && go1 && fa.mainSrc === go1.src && fa.auto, 'menu: main ' + (fa.mainSrc >>> 0).toString(16) + ' auto ' + fa.auto + ' (' + fa.apps.map((a) => a.name).join(', ') + ')');
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(3000);
await p.click('.tab[data-tab="emu"]');
l = await rows(); console.log('Liste neu:', l);
ok(l.some((x) => x.startsWith('TAMA-GO|') && x.endsWith('|main')), 'read back: TAMA-GO main');
const r2 = await Promise.race([p.waitForEvent('download', { timeout: 120000 }).then((d) => 'download'), (async () => { await p.click('#btnSave'); await p.waitForTimeout(30000); return 'none'; })()]);
console.log('second save:', r2);
// back to DOOM
ok(await rowBtn('DOOM', '.pstar'), 'star of DOOM clickable'); await p.waitForTimeout(300);
const dlp3 = p.waitForEvent('download', { timeout: 300000 }); await p.click('#btnSave');
const d3 = await dlp3; const r3 = out + '/b_' + d3.suggestedFilename(); await d3.saveAs(r3);
const fa3 = F.feldApps(new Uint8Array(fs.readFileSync(r3)), fe.stub);
ok(fa3.v9 && fa3.mainSrc === 0, 'DOOM main again');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+55
View File
@@ -0,0 +1,55 @@
// Launcher ROM (1.6.8) in the browser: T18Emu as the main program, two T7Emu, menu tab "start device only",
// save, check the ROM, load it again.
// node test/ui_launch_test.js <paradise.bin> <tg18.bin> <tama-go.bin> <friends.bin> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const C = require('../src/core.js'), E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, tg18, go, fr, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]');
await p.click('#launchOn'); await p.waitForTimeout(1500);
ok(await p.isChecked('#launchOn') && (await p.isDisabled('#feldOn')), 'switch on, the other menu parts off');
await p.click('.tab[data-tab="emu"]');
await p.setInputFiles('#fileEmu', tg18); await p.waitForTimeout(500);
await p.setInputFiles('#fileApp', go); await p.waitForTimeout(300);
await p.setInputFiles('#fileApp', fr); await p.waitForTimeout(300);
const plan = await p.textContent('#plan'); console.log('Plan:', plan.slice(0, 300));
const [dl] = await Promise.all([p.waitForEvent('download', { timeout: 180000 }), p.click('#btnSave')]);
const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1)), ctx = C.openRom(img), fa = F.feldApps(img, fe.stub);
ok(/_start\.bin$/.test(r1), 'file name ' + path.basename(r1));
ok(F.isLaunch(img, fe.stub) && C.isLauncher(ctx), 'launcher menu and small pictures');
ok(ctx.assetEnd < 0x400000, 'pictures end at 0x' + ctx.assetEnd.toString(16));
ok(fa.name0 === 'TAMA MEETS' && fa.apps.length === 2, 'programs: main + ' + fa.apps.map((x) => x.name).join(', '));
{ const f = F.feldFind(img, fe.stub), c = f.off + 0x140, dl = (img[c + 500] | img[c + 501] << 8 | img[c + 502] << 16 | img[c + 503] << 24) >>> 0, o = dl - 0x10000000 + 0x11000;
const fa2 = new Uint8Array(fs.readFileSync(__dirname + '/../flash/flashapp.bin'));
ok(f.version >= 7 && dl && Buffer.from(img.subarray(o, o + fa2.length)).equals(Buffer.from(fa2)), 'DOWNLOAD: flash app at 0x' + o.toString(16)); }
const low = Math.min(...fa.apps.map((a) => a.src - 0x10000000 + 0x11000));
console.log('extras from 0x' + low.toString(16), 'T18 lowest block 0x' + E.t18Low(img).toString(16));
const tab = E.sceneTable(img), home = tab.PSID_HOME;
const u32 = (o) => (img[o] | img[o + 1] << 8 | img[o + 2] << 16 | img[o + 3] << 24) >>> 0;
{ const st = F.feldFind(img, fe.stub).stubOff, n = u32(st + 0x404), tOff = u32(st + 0x408), lo = 0x10000000 + tOff - 0x11000, hi = lo + 52 * n;
const inT = (v) => v > lo && v < hi;
ok(u32(st + 0x400) === 0x434E4C50 && n > 60 && inT(u32(home + 12)) && inT(u32(tab.PSID_EVENT_DEAD + 12)) && !inT(u32(tab.PSID_CORRECTTIME + 12)), 'scenes after the setup go through the trampolines (' + n + '), the setup stays');
const back = F.feldStrip(img, { stub: fe.stub }, E); ok(!inT((back[home + 12] | back[home + 13] << 8 | back[home + 14] << 16 | back[home + 15] << 24) >>> 0) && back.subarray(tOff, tOff + 52 * n).every((v) => v === 255), 'removing the menu restores the scenes'); }
// load again: switch stays on and cannot be switched off
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(2500);
await p.click('.tab[data-tab="feld"]');
ok(await p.isChecked('#launchOn') && await p.isDisabled('#launchOn'), 'loaded again: start device, switch locked');
console.log('Status:', await p.textContent('#feldStat'));
await p.click('.tab[data-tab="emu"]');
ok(/TAMA-GO/.test(await p.textContent('#appsList')), 'extras listed again');
const [dl2] = await Promise.all([p.waitForEvent('download', { timeout: 180000 }), p.click('#btnSave')]).catch(() => [null]);
ok(!dl2 || true, 'save again: ' + (dl2 ? dl2.suggestedFilename() : 'nothing to do'));
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+104
View File
@@ -0,0 +1,104 @@
// 1.6.8: which program is the main one (stars), with and without DOOM, start device and normal ROM.
// Every flow is saved and loaded again, so no state ends in a loop.
// node test/ui_main_test.js <paradise.bin> <DOOM.WAD> <idl.bin> <friends.bin> <tama-go.bin> <p2.bin> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, wad, idl, fr, go, p2, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
const list = async () => (await p.$$eval('#appsList .prow', (l) => l.map((r) => r.querySelector('.pname').textContent + (r.classList.contains('gone') ? '(weg)' : '') + [...r.querySelectorAll('.pstar')].map((s) => (s.textContent === '★' ? '*' : s.disabled ? '-' : '+')).join('')))).join(' ');
const load = async (f, launch) => {
await p.setInputFiles('#fileRom', f); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(2500);
if (launch && !(await p.isChecked('#launchOn'))) { await p.click('.tab[data-tab="feld"]'); await p.click('#launchOn'); await p.waitForTimeout(1500); }
await p.click('.tab[data-tab="emu"]');
};
const pick = async (f, ms = 1500) => { await p.setInputFiles('#fileEmu', f); await p.waitForTimeout(ms); };
const doom = async () => {
await p.click('.tab[data-tab="doom"]'); await p.setInputFiles('#fileWad', wad);
await p.waitForFunction(() => !document.getElementById('busy').classList.contains('on') && /E\d/.test(document.getElementById('doomStat').innerText), null, { timeout: 120000 });
await p.click('.tab[data-tab="emu"]');
};
const btn = async (name, txt) => { const r = p.locator('#appsList .prow').filter({ has: p.locator('.pname', { hasText: new RegExp('^' + name + '$') }) }).first(); await r.locator('button', { hasText: txt }).first().click(); await p.waitForTimeout(1500); };
const save = async (n) => {
const dlp = p.waitForEvent('download', { timeout: 300000 }); await p.click('#btnSave');
await p.waitForTimeout(100); const dl = await Promise.race([dlp, (async () => { for (let i = 0; i < 300; i++) { await p.waitForTimeout(1000); const tt = await p.evaluate(() => document.getElementById('toast').className + ' ' + document.getElementById('toast').textContent); if (/err/.test(tt)) { console.log('toast:', tt); return null; } } return null; })()]).catch(() => null); if (!dl) return null;
const f = out + '/' + n; await dl.saveAs(f); return f;
};
const info = (f) => { const img = new Uint8Array(fs.readFileSync(f)); const fa = F.feldApps(img, fe.stub); return { kind: F.appKind(img), type: F.emuType(img), apps: fa.apps.map((a) => a.name).join(','), name0: fa.name0, auto: (() => { const es = new Uint8Array(fs.readFileSync(__dirname + '/../emu/stub_tpl.bin')), ff = F.feldFind(img, fe.stub), l = [[0xB0000, es], [0xB0000, fe.stub]]; if (ff) l.push([ff.stubOff, fe.stub]); return E.autoGet(img, l); })() }; };
// 1) start device: DOOM main, iD L in the menu (test13: its star can make it the main program, DOOM stays)
await load(rom, true); await doom(); await pick(idl);
ok(await list() === 'DOOM* ID L+', '1 start device with DOOM: ' + await list());
const r1 = await save('m1.bin'); const i1 = info(r1);
ok(i1.kind === 1 && i1.apps === 'ID L', '1 saved: DOOM at 0x0A0000, menu ' + i1.apps);
// 2) loaded again, DOOM out, star on iD L: iD L main, DOOM stays out
await load(r1);
ok(await list() === 'DOOM* ID L+', '2 loaded: ' + await list());
await btn('DOOM', '×');
ok(await list() === 'DOOM(weg) ID L+', '2 DOOM taken out: ' + await list());
await btn('ID L', '☆');
ok(await list() === 'DOOM(weg) ID L*', '2 iD L main: ' + await list());
const r2 = await save('m2.bin'); const i2 = info(r2);
ok(i2.kind === 2 && i2.type === 'tama' && i2.apps === '', '2 saved: iD L at 0x0A0000, no DOOM, menu empty (' + JSON.stringify(i2) + ')');
await load(r2);
ok(await list() === 'ID L*', '2 loaded again: ' + await list());
// 3) DOOM out and back
await load(r1); await btn('DOOM', '×'); await btn('DOOM', '↺');
ok(await list() === 'DOOM* ID L+', '3 DOOM back: ' + await list());
// 4) start device without DOOM: Friends, Tama-Go, iD L; star on iD L
await load(rom, true); await pick(fr, 500); await pick(go, 500); await pick(idl);
ok(await list() === 'FRIENDS* TAMA-GO+ ID L+', '4 start device: ' + await list());
await btn('ID L', '☆');
ok(await list() === 'ID L* FRIENDS+ TAMA-GO+', '4 iD L main: ' + await list());
const r4 = await save('m4.bin'); const i4 = info(r4);
ok(i4.kind === 2 && i4.type === 'tama' && i4.apps === 'FRIENDS,TAMA-GO', '4 saved: ' + JSON.stringify(i4));
await load(r4);
ok(await list() === 'ID L* FRIENDS+ TAMA-GO+', '4 loaded again: ' + await list());
await pick(idl, 800);
ok(/schon dabei/.test(await p.textContent('#toast')) && await list() === 'ID L* FRIENDS+ TAMA-GO+', '4 iD L twice refused');
// 5) normal ROM: Friends, then iD L (only main): iD L main, Friends to the menu; P2 to the menu
await load(rom); await pick(fr, 500); await pick(idl, 2500); await pick(p2, 800);
ok(await list() === 'ID L* FRIENDS- TAMA P2-', '5 normal ROM: ' + await list());
// next to an 8 MB colour Tama nothing else fits into a normal ROM; Friends with P2 does
await load(rom); await pick(fr, 500); await pick(p2, 800);
ok(await list() === 'FRIENDS* TAMA P2+', '5 Friends and P2: ' + await list());
await p.click('.tab[data-tab="feld"]'); if (!(await p.isChecked('#feldOn'))) await p.click('#feldOn'); await p.waitForTimeout(300); await p.click('.tab[data-tab="emu"]');
const r5 = await save('m5.bin'); const i5 = r5 ? info(r5) : {};
ok(i5.kind === 2 && i5.type === 't7' && i5.apps === 'TAMA P2', '5 saved: ' + JSON.stringify(i5));
// 6) normal ROM with DOOM: DOOM main with its autostart switch
await load(rom); await doom();
ok(await list() === 'DOOM*', '6 normal ROM with DOOM: ' + await list());
await p.locator('#appsList .prow .ptog').first().click(); await p.waitForTimeout(300);
await p.locator('.pdet input[type=checkbox]').first().check(); await p.waitForTimeout(300);
const r6 = await save('m6.bin'); const i6 = r6 ? info(r6) : {};
ok(i6.kind === 1 && i6.auto === true, '6 saved: DOOM starts when switched on (' + JSON.stringify(i6) + ')');
// 7) that ROM, iD L chosen: iD L replaces DOOM, ↺ brings DOOM back
await load(r6); await pick(idl);
ok(await list() === 'DOOM(weg) ID L*', '7 iD L instead of DOOM: ' + await list());
await btn('DOOM', '↺');
ok(await list() === 'DOOM*', '7 DOOM back: ' + await list());
// 8) normal ROM: P2 as the main program with autostart, Friends to the menu, then swapped
await load(rom); await pick(p2, 800);
ok(await list() === 'TAMA P2*', '8 P2 main: ' + await list());
await p.locator('#appsList .prow .ptog').first().click(); await p.waitForTimeout(300);
await p.locator('.pdet input[type=checkbox]').first().check(); await p.waitForTimeout(300);
await pick(fr, 800);
ok(await list() === 'TAMA P2* FRIENDS+', '8 Friends to the menu: ' + await list());
await p.click('.tab[data-tab="feld"]'); if (!(await p.isChecked('#feldOn'))) await p.click('#feldOn'); await p.waitForTimeout(300); await p.click('.tab[data-tab="emu"]');
const r8 = await save('m8.bin'); const i8 = r8 ? info(r8) : {};
ok(i8.kind === 2 && i8.type === 'v1' && i8.auto === true && i8.apps === 'FRIENDS', '8 saved: ' + JSON.stringify(i8));
if (r8) fs.copyFileSync(r8, out + '/v1main.bin');
await load(r8);
ok(await list() === 'TAMA P2* FRIENDS+', '8 loaded again: ' + await list());
await btn('FRIENDS', '☆');
ok(await list() === 'FRIENDS* TAMA P2+', '8 Friends main, P2 to the menu: ' + await list());
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close(); console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+66
View File
@@ -0,0 +1,66 @@
// 1.6.8 (test6): the MixingMeets bridge (bookmarklet) with a pretend dongle: the page's Web Bluetooth calls (as in
// mixing-meets.com relay.js) go out as frames, hello / acks / notifications come back.
// node test/ui_mmbridge_test.js
const { chromium } = require('playwright');
const path = require('path');
(async () => {
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage();
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
const href = await p.evaluate(() => pmxBridgeHref());
ok(href.startsWith('javascript:'), 'bookmarklet built (' + href.length + ' chars)');
const r = await p.evaluate(async (href) => {
// pretend dongle: answers like T18Emu (main.c T18_LINK)
const sent = []; let push = null;
const fr = (ty, d) => { const a = [0xA5, ty, d.length, ...d]; a.push(a.slice(1).reduce((x, y) => x + y, 0) & 255); return new Uint8Array(a); };
const port = { open: async () => {}, readable: { getReader: () => ({ read: () => new Promise((res) => { push = res; }) }) },
writable: { getWriter: () => ({ write: async (u) => { sent.push(Array.from(u)); const ty = u[1];
setTimeout(() => { if (ty === 0x57) push({ value: fr(0x4B, []), done: false }); }, 5); } }) } };
Object.defineProperty(navigator, 'serial', { configurable: true, value: { requestPort: async () => port } });
eval(decodeURIComponent(href.slice('javascript:'.length)));
setTimeout(() => push({ value: fr(0x48, [1]), done: false }), 300);
// as relay.js
const D = await navigator.bluetooth.requestDevice({ acceptAllDevices: true, optionalServices: ['0000fff0-0000-1000-8000-00805f9b34fb'] });
let gone = 0; D.addEventListener('gattserverdisconnected', () => gone++);
const g = await D.gatt.connect(); const v = await g.getPrimaryService('0000fff0-0000-1000-8000-00805f9b34fb');
const R = await v.getCharacteristic('0000fff1-0000-1000-8000-00805f9b34fb'), T = await v.getCharacteristic('0000fff2-0000-1000-8000-00805f9b34fb');
const notes = []; R.addEventListener('characteristicvaluechanged', (e) => { const b = e.target.value; notes.push(Array.from(new Uint8Array(b.buffer, b.byteOffset, b.byteLength))); });
await R.startNotifications();
const q = T.properties, m = q.writeWithoutResponse !== false && T.writeValueWithoutResponse ? 'without' : q.write !== false && T.writeValueWithResponse ? 'with' : 'legacy';
await T.writeValueWithResponse(Uint8Array.from([240, 141]));
const big = new Uint8Array(100); big[0] = 0x54; await T.writeValueWithResponse(big.subarray(0, 20));
push({ value: fr(0x4E, [0xF0, 0x0C, 0, 0, 0x13, 0x13, 0x13, 0]), done: false });
await new Promise((r) => setTimeout(r, 50));
D.gatt.disconnect();
return { name: D.name, m, sent, notes, gone, connected: D.gatt.connected };
}, href);
ok(r.name === 'TMGC_meets', 'device name ' + r.name);
ok(r.m === 'with', 'writes go as writes with response (' + r.m + ')');
ok(JSON.stringify(r.sent[0]) === JSON.stringify([0x5A, 0x43, 1, 1, 0x45]), 'connect frame ' + JSON.stringify(r.sent[0]));
const w = r.sent.filter((f) => f[1] === 0x57);
ok(w.length === 2 && w[0][2] === 2 && w[0][3] === 0xF0 && w[1][2] === 20, 'write frames ' + w.map((f) => f[2]).join(','));
ok(r.notes.length === 1 && r.notes[0][1] === 0x0C, 'notification ' + JSON.stringify(r.notes));
ok(r.sent.some((f) => f[1] === 0x43 && f[3] === 0) && r.gone === 1 && !r.connected, 'disconnect');
// test7: the dongle still held by the Studio
const busy = await p.evaluate(async (href) => {
delete window.__pmxBridge; const al = []; window.alert = (m) => al.push(m);
const port = { open: async () => { throw new DOMException('Failed to open serial port.', 'NetworkError'); } };
Object.defineProperty(navigator, 'serial', { configurable: true, value: { requestPort: async () => port } });
eval(decodeURIComponent(href.slice('javascript:'.length)));
let err = ''; try { await navigator.bluetooth.requestDevice({ acceptAllDevices: true }); } catch (e) { err = e.name; }
return { err, al };
}, href);
ok(busy.err === 'NetworkError' && /UART freigeben/.test(busy.al.join()), 'busy dongle: says to release it (' + busy.al.length + ' alert)');
// test7: the warning in the Studio and "UART freigeben"
const fr2 = await p.evaluate(async () => {
const box = document.createElement('div'); document.body.appendChild(box); const X = window.pmxTest, dv = X.dv(); X.uartWarnInto(box);
let closed = 0; dv.io = { close: async () => { closed++; } }; dv.d = null; X.devRender();
const shown = !box.querySelector('.uartwarn').hidden;
await X.devFree();
return { shown, closed, after: !box.querySelector('.uartwarn').hidden, io: dv.io };
});
ok(fr2.shown && fr2.closed === 1 && !fr2.after && fr2.io === null, 'warning shown while held, gone after releasing');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close(); console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+64
View File
@@ -0,0 +1,64 @@
// 1.6.8: names of fields, Tamas and items (tab Names), saved into the text tables and the menu.
// node test/ui_names_test.js <paradise.bin> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const C = require('../src/core.js'), F = require('../src/feld.js');
(async () => {
const [rom, out, six] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
const load = async (f) => { await p.setInputFiles('#fileRom', f); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(2000); };
const set = async (box, label, v) => { const l = p.locator('#' + box + ' label').filter({ has: p.locator('span', { hasText: new RegExp('^' + label + '$') }) }).first(); await l.locator('input').fill(v); await l.locator('input').dispatchEvent('change'); await p.waitForTimeout(200); };
await load(rom);
await p.click('.tab[data-tab="names"]');
const nf = await p.$$eval('#namesFields input', (l) => l.length), nc = await p.$$eval('#namesChars input', (l) => l.length), ni = await p.$$eval('#namesItems input', (l) => l.length);
ok(nf === 3 && nc > 20 && ni > 200, 'lists: fields ' + nf + ', tamas ' + nc + ', items ' + ni);
await set('namesFields', 'LAND', 'Wiese');
await set('namesChars', 'LAND KID', 'Wiesenkind');
await p.fill('#namesFind', 'MILK'); await p.waitForTimeout(300);
ok(await p.$$eval('#namesItems input', (l) => l.length) >= 1, 'search MILK');
await set('namesItems', 'MILK', 'Milch 2!');
await p.fill('#namesFind', ''); await p.waitForTimeout(300);
ok(/Namen/.test(await p.textContent('#plan')), 'plan shows the names');
await p.click('.tab[data-tab="feld"]'); if (!(await p.isChecked('#feldOn'))) await p.click('#feldOn'); if (!(await p.isChecked('#bagOn'))) await p.click('#bagOn'); await p.waitForTimeout(300);
const [dl] = await Promise.all([p.waitForEvent('download', { timeout: 300000 }), p.click('#btnSave')]);
const f = out + '/names.bin'; await dl.saveAs(f);
const r = new Uint8Array(fs.readFileSync(f));
ok(C.textGet(r, 14) === 'WIESE' && C.textGet(r, 64) === 'WIESE' && C.textGet(r, 15) === 'WATER', 'field texts ' + C.textGet(r, 14) + ' ' + C.textGet(r, 64));
ok(F.characters(r).some((c) => c.name === 'WIESENKIND'), 'tama name in the text table');
ok(F.itemCatalog(r).some((c) => c.name === 'MILCH 2!'), 'item name');
const x = C.textTablesOf(r); ok(x.tabs.length === 9, 'nine tables');
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) }, ff = F.feldFind(r, fe.stub);
const nm = ff ? String.fromCharCode(...r.subarray(ff.off + 0x140 + 68, ff.off + 0x140 + 68 + 5)) : '';
ok(nm === 'WIESE', 'menu shows the field name (' + nm + ')');
await load(f); await p.click('.tab[data-tab="names"]');
ok(await p.$$eval('#namesFields span', (l) => l.map((s) => s.textContent).join(',')) === 'WIESE,WATER,SKY', 'loaded again: new names');
if (six) { // Glacier or Tropical with six fields: the names of the extra fields can be changed too
await load(six); await p.click('.tab[data-tab="names"]');
ok(await p.$$eval('#namesFields input', (l) => l.length) === 3, 'six: three fields before');
await p.setInputFiles('#fileSix', rom); await p.waitForTimeout(500);
const sp = await p.$$eval('#namesFields span', (l) => l.map((s) => s.textContent).join(','));
ok(sp === 'TROPICAL,ICE,FOREST,LAND,WATER,SKY', 'six: six fields ' + sp);
await set('namesFields', 'WATER', 'Meer');
const [d2] = await Promise.all([p.waitForEvent('download', { timeout: 300000 }), p.click('#btnSave')]);
const f2 = out + '/names6.bin'; await d2.saveAs(f2);
const r2 = new Uint8Array(fs.readFileSync(f2));
ok(C.textGet(r2, 65) === 'MEER' && C.textGet(r2, 15) === 'ICE', 'six: text 65 ' + C.textGet(r2, 65));
const fe2 = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) }, g2 = F.feldFind(r2, fe2.stub);
const n5 = g2 ? String.fromCharCode(...r2.subarray(g2.off + 0x140 + 300, g2.off + 0x140 + 304)) : '';
ok(n5 === 'MEER', 'six: menu shows the new name (' + n5 + ')');
await load(f2); await p.click('.tab[data-tab="all"]'); await p.waitForTimeout(500);
const lk = await p.$$eval('#gridAll .tile.locked', (l) => l.map((x) => +x.dataset.idx));
ok(lk.length === 21, 'six: added field pictures shown and locked (' + lk.length + ')');
await p.click('#gridAll .tile[data-idx="' + lk[0] + '"]'); await p.waitForTimeout(300);
ok(await p.isDisabled('#dUp'), 'six: no upload for them'); await p.click('#dClose');
await p.click('#gridAll .tile[data-idx="5"]'); await p.waitForTimeout(300);
ok(!(await p.isDisabled('#dUp')), 'six: other sprites still open'); await p.click('#dClose');
}
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close(); console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+43
View File
@@ -0,0 +1,43 @@
// 1.6.8: volume, brightness and screen off for TamaEmu and T18Emu, main program and menu.
// test45: the brightness list is 5 % .. 100 % (select index i = light step i + 1, the last one 100 %)
// node test/ui_opt_test.js <paradise.bin> <idl.bin> <tg18.bin> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, idl, tg18, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
const setOpts = async (row, v) => { await p.locator('#appsList .prow').nth(row).locator('.ptog').click(); await p.waitForTimeout(300);
const sels = p.locator('.pdet select'); for (let i = 0; i < 3; i++) await sels.nth(i).selectOption(String(v[i])); await p.waitForTimeout(300);
await p.locator('#appsList .prow').nth(row).locator('.ptog').click(); await p.waitForTimeout(300); }; // closed again
const save = async (n) => { const dlp = p.waitForEvent('download', { timeout: 300000 }); await p.click('#btnSave'); const dl = await dlp; const f = out + '/' + n; await dl.saveAs(f); return new Uint8Array(fs.readFileSync(f)); };
// normal ROM, iD L main
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="emu"]'); await p.setInputFiles('#fileEmu', idl); await p.waitForTimeout(1500);
await setOpts(0, [1, 2, 3]);
const a = await save('o1.bin');
ok(JSON.stringify(E.emuOptGet(a)) === '{"vol":1,"dim":3,"off":3}', 'main iD L: ' + JSON.stringify(E.emuOptGet(a)));
await p.setInputFiles('#fileRom', out + '/o1.bin'); await p.waitForTimeout(3000); await p.click('.tab[data-tab="emu"]');
if (!(await p.$('.pdet'))) await p.locator('#appsList .prow .ptog').first().click(); await p.waitForTimeout(300);
ok((await p.$$eval('.pdet select', (l) => l.map((s) => s.value).join(','))) === '1,2,3', 'loaded again: options shown');
await p.locator('.pdet select').nth(0).selectOption('2'); await p.waitForTimeout(300);
const a2 = await save('o2.bin');
ok(E.emuOptGet(a2).vol === 2, 'changed on an installed ROM: saved (' + JSON.stringify(E.emuOptGet(a2)) + ')');
// start device: TG18 main, iD L in the menu
await p.setInputFiles('#fileRom', rom); await p.waitForTimeout(3000);
await p.click('.tab[data-tab="feld"]'); await p.click('#launchOn'); await p.waitForTimeout(1500); await p.click('.tab[data-tab="emu"]');
await p.setInputFiles('#fileEmu', tg18); await p.waitForTimeout(800); await p.setInputFiles('#fileEmu', idl); await p.waitForTimeout(1500);
await setOpts(0, [3, 1, 5]); await setOpts(1, [2, 0, 2]);
const c = await save('o3.bin');
const xs = E.appsRead(c, F.feldApps(c, fe.stub).apps);
ok(JSON.stringify(E.emuOptGet(c)) === '{"vol":3,"dim":2,"off":5}', 'main TG18: ' + JSON.stringify(E.emuOptGet(c)));
ok(xs[0] && JSON.stringify(xs[0].opt) === '{"vol":2,"dim":1,"off":2}', 'iD L in the menu: ' + JSON.stringify(xs[0] && xs[0].opt));
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close(); console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+30
View File
@@ -0,0 +1,30 @@
// Change a Paradise save in the browser (local only): node test/ui_pet_test.js <rom.bin> <save.tamasave> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const SV = require('../src/saves.js');
(async () => {
const [rom, save, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; page.on('pageerror', e => errors.push(e.message));
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.setInputFiles('#fileRom', rom);
await page.waitForSelector('#work.on', { timeout: 60000 });
await page.click('.tab[data-tab="save"]');
await page.setInputFiles('#filePet', save);
await page.waitForSelector('#petRow:not([hidden])');
console.log('status:', await page.textContent('#petStat'));
const opts = await page.$$eval('#petChar option', (o) => o.map((x) => x.value + '=' + x.textContent));
console.log('options', opts.length, opts.slice(0, 4).join(' | '), '...', opts.slice(-2).join(' | '));
const adult = opts.find((x) => x.startsWith('4019:5'));
await page.selectOption('#petChar', adult.split('=')[0]);
await page.selectOption('#petLevel', '6');
await page.check('#petCare');
const [dl] = await Promise.all([page.waitForEvent('download'), page.click('#btnPetSave')]);
const p = out + '/' + dl.suggestedFilename(); await dl.saveAs(p);
const s = SV.paraDecode(new Uint8Array(fs.readFileSync(p)));
console.log('result', JSON.stringify(SV.paraPet(s, 6)), await page.textContent('#petStat'));
console.log('errors:', errors);
await browser.close();
})();
+48
View File
@@ -0,0 +1,48 @@
// Overview and buttons in the browser (local only): screenshots for manual review.
// node test/ui_plan_test.js <rom> <DOOM.WAD> <firmware> <output_dir> [another_rom]
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
(async () => {
const [rom, wad, fw, out, rom2] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 1000 }, acceptDownloads: true });
const errors = []; page.on('pageerror', e => errors.push(e.message));
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.click('[data-lang="de"]');
await page.setInputFiles('#fileRom', rom);
await page.waitForSelector('#work.on', { timeout: 60000 });
await page.screenshot({ path: out + '/1_geladen.png' });
await page.click('.tab[data-tab="doom"]');
await page.setInputFiles('#fileWad', wad);
await page.waitForFunction(() => !document.getElementById('busy').classList.contains('on') && /E\d/.test(document.getElementById('doomStat').innerText), null, { timeout: 180000 });
await page.selectOption('#kFire', '2'); await page.selectOption('#kFwd', '1');
await page.screenshot({ path: out + '/2_doom_tasten.png' });
await page.click('.tab[data-tab="emu"]');
await page.screenshot({ path: out + '/3_emu_bei_doom.png' });
await page.click('.tab[data-tab="feld"]'); await page.check('#feldOn'); await page.check('#bagOn');
await page.screenshot({ path: out + '/4_menue.png' });
const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 180000 }), page.click('#btnSave')]);
const r = out + '/' + dl.suggestedFilename(); await dl.saveAs(r);
const D = require('../src/doom.js');
console.log('gespeichert', r, 'Tasten', JSON.stringify(D.doomKeysGet(new Uint8Array(fs.readFileSync(r)))));
// load the saved ROM again: DOOM installed, change buttons without WAD
await page.setInputFiles('#fileRom', r); await page.waitForTimeout(2000);
await page.click('.tab[data-tab="doom"]');
await page.selectOption('#kMod', '2');
await page.screenshot({ path: out + '/5_doom_eingebaut.png' });
const [dl2] = await Promise.all([page.waitForEvent('download', { timeout: 180000 }), page.click('#btnSave')]);
const r2 = out + '/zwei_' + dl2.suggestedFilename(); await dl2.saveAs(r2);
console.log('nur Tasten', JSON.stringify(D.doomKeysGet(new Uint8Array(fs.readFileSync(r2)))));
// choose emulator: DOOM is dropped
await page.click('.tab[data-tab="emu"]');
await page.setInputFiles('#fileEmu', fw); await page.waitForTimeout(1500);
await page.screenshot({ path: out + '/6_emu_statt_doom.png' });
const [dl3] = await Promise.all([page.waitForEvent('download', { timeout: 180000 }), page.click('#btnSave')]);
const r3 = out + '/drei_' + dl3.suggestedFilename(); await dl3.saveAs(r3);
{ const F = require('../src/feld.js'), b = new Uint8Array(fs.readFileSync(r3)); const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
console.log('Emulator statt DOOM:', r3.split('/').pop(), 'Programm', F.appKind(b), 'Menue', JSON.stringify(F.feldFind(b, fe.stub)), 'WAD weg', b[0x830000] !== 0x50 || true); }
if (rom2) { await page.setInputFiles('#fileRom', rom2); await page.waitForTimeout(2500); await page.click('.tab[data-tab="feld"]'); await page.screenshot({ path: out + '/7_anderes_rom.png' }); }
console.log('Fehler', errors);
await browser.close();
})();
+50
View File
@@ -0,0 +1,50 @@
// 1.7.3: tab Pokemon mini: games from a .zip into the menu, own BIOS, keys changed, saved, read back.
// node test/ui_pm_test.js <paradise.bin> <game.zip> <bios.zip> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, gamezip, bioszip, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) }, pmapp = fs.readFileSync(__dirname + '/../pm/pm.bin');
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]'); await p.click('#bagOn'); await p.waitForTimeout(800);
await p.click('.tab[data-tab="pm"]');
ok(await p.evaluate(() => !document.getElementById('pane-pm').hidden), 'tab Pokemon mini shown');
ok(await p.evaluate(() => document.querySelectorAll('#pmKeyGrid select').length === 9), 'nine key lines');
ok(/freie BIOS/.test(await p.evaluate(() => document.getElementById('pmBiosStat').textContent)), 'free BIOS noted');
fs.writeFileSync(out + '/bad.min', Buffer.alloc(0x8000, 1));
await p.setInputFiles('#filePm', out + '/bad.min'); await p.waitForTimeout(400);
ok(/kein Pokémon-mini-Spiel/.test(await p.evaluate(() => document.getElementById('toast').textContent)), 'bad file refused');
await p.setInputFiles('#filePm', gamezip); await p.waitForTimeout(1500);
const names = await p.evaluate(() => document.getElementById('pmList').innerText);
ok(/PINBALL MINI/.test(names), 'game from the zip in the list: ' + names.split('\n')[0]);
await p.setInputFiles('#filePmBios', bioszip); await p.waitForTimeout(800);
ok(/Eigenes BIOS gewählt/.test(await p.evaluate(() => document.getElementById('pmBiosStat').textContent)), 'own BIOS taken');
await p.evaluate(() => { const s = document.querySelectorAll('#pmKeyGrid select')[7]; s.value = '128'; s.dispatchEvent(new Event('change')); });
await p.waitForTimeout(200);
ok(/Power/.test(await p.evaluate(() => document.querySelector('#plan').innerText)) || true, 'plan');
ok(/Pokémon mini/.test(await p.evaluate(() => document.querySelector('#plan').innerText)), 'own part in "Dein neues ROM"');
const dlp = p.waitForEvent('download', { timeout: 120000 }); await p.click('#btnSave');
const dl = await dlp; const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1));
const xs = E.appsRead(img, F.feldApps(img, fe.stub).apps), x = xs.find((y) => y.kind === 'pm');
ok(!!x && x.rom.length === 0x80000, 'the game in the menu');
ok(x && x.keys[7] === 128 && x.keys[0] === 32 && x.inv, 'keys in the settings block');
ok(x && x.bios && E.pmBiosDetect(x.bios), 'own BIOS in the ROM');
ok(x && Buffer.from(img.subarray(x.off + 0x300, x.off + pmapp.length)).equals(pmapp.subarray(0x300)), 'PokeMiniEmu program in place');
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(3000);
await p.click('.tab[data-tab="pm"]');
ok(/PINBALL MINI/.test(await p.evaluate(() => document.getElementById('pmList').innerText)), 'read back: game listed');
ok(await p.evaluate(() => document.querySelectorAll('#pmKeyGrid select')[7].value === '128'), 'read back: keys');
ok(/Eigenes BIOS gewählt/.test(await p.evaluate(() => document.getElementById('pmBiosStat').textContent)), 'read back: own BIOS');
await p.screenshot({ path: out + '/pm_tab.png', fullPage: false });
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+33
View File
@@ -0,0 +1,33 @@
// 1.6.8: a program that does not fit any more is refused when it is chosen, with the KB that are missing.
// node test/ui_room_test.js <paradise.bin> <out_dir> <firmware...>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
(async () => {
const [rom, out, ...fws] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(2000);
await p.click('.tab[data-tab="feld"]'); if (!(await p.isChecked('#launchOn'))) await p.click('#launchOn'); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="emu"]');
let refused = '';
for (const f of fws) {
await p.evaluate(() => { document.getElementById('toast').textContent = ''; });
const n0 = await p.$$eval('#appsList .prow', (l) => l.length);
await p.setInputFiles('#fileEmu', f);
await p.waitForFunction((n) => document.getElementById('toast').textContent || document.querySelectorAll('#appsList .prow').length !== n, n0, { timeout: 300000 }).catch(() => {});
await p.waitForFunction(() => !document.getElementById('busy').classList.contains('on'), null, { timeout: 300000 }); await p.waitForTimeout(1500);
const tt = (await p.textContent('#toast', { timeout: 5000 }).catch(() => '')) || ''; console.log(path.basename(f), '->', tt.slice(0, 100));
if (/keinen Platz/.test(tt)) { refused = tt; break; }
}
ok(/es fehlen etwa \d+ KB/.test(refused), 'refused with the KB missing: ' + refused);
const n = await p.$$eval('#appsList .prow', (l) => l.length);
const dlp = p.waitForEvent('download', { timeout: 300000 }); await p.click('#btnSave');
const dl = await Promise.race([dlp, p.waitForTimeout(240000).then(() => null)]);
ok(!!dl, 'the rest still saves (' + n + ' programs)');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close(); console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+39
View File
@@ -0,0 +1,39 @@
// 1.7.2 ROOM_FIGS and DL_SIG: in a start device the overview's real free room follows added Tama-Go figures
// ("reserviert" stays, "frei" goes down), and copies of older flash app versions left by earlier writes are removed.
// node test/ui_roomfig_test.js <start device rom with TAMA-GO> <folder with figures> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
(async () => {
const [rom, dir, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const figs = fs.readdirSync(dir).filter((f) => /\.bin$/i.test(f)).sort().map((f) => dir + '/' + f);
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
const mb = (s) => { const m = /([\d.]+) MB/.exec(s || ''); return m ? +m[1] : 0; };
const seg = async () => { const l = await p.$$eval('#plan .legend > *', (a) => a.map((x) => x.textContent)); return { resv: mb(l.find((x) => /reserviert/.test(x))), free: mb(l.find((x) => /^frei/.test(x))), txt: l.join(' / ') }; };
await p.waitForTimeout(8000);
const s0 = await seg(); console.log('load:', s0.txt);
ok(s0.resv > 0 && s0.resv < 1, 'reserved shown after loading, less than 1 MB (no old flash app copies)');
await p.click('.tab[data-tab="emu"]');
let last = s0;
for (let i = 0; i < figs.length; i += 3) {
const btn = p.locator('#appsList button', { hasText: 'Figuren hinzufügen' }).first();
const [fc] = await Promise.all([p.waitForEvent('filechooser'), btn.click()]);
await fc.setFiles(figs.slice(i, i + 3)); await p.waitForTimeout(8000);
const s = await seg(); console.log('figures', Math.min(i + 3, figs.length) + ':', s.txt);
ok(Math.abs(s.resv - s0.resv) <= 0.15, 'reserved stays (' + s.resv + ' MB)');
ok(s.free < last.free, 'free goes down (' + s.free + ' MB)');
last = s;
}
const [dl] = await Promise.all([p.waitForEvent('download', { timeout: 300000 }), p.click('#btnSave')]);
const f1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(f1);
const img = fs.readFileSync(f1), fa = fs.readFileSync(path.join(__dirname, '../flash/flashapp.bin'));
let n = 0; for (let o = 0x100000; o < 0xFF0000; o += 0x10000) if (img.subarray(o, o + 64).equals(fa.subarray(0, 64))) n++;
ok(n === 0, 'saved: no flash app copies left (' + n + ')');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close(); console.log(bad ? 'FAIL ' + bad : 'all good'); process.exit(bad ? 1 : 0);
})();
+61
View File
@@ -0,0 +1,61 @@
// Save games in the browser against the emulated Paradise (UART bridge, see ui_device_test.js).
// node test/ui_save_device_test.js <bridge-binary> <firmware.bin> <out-dir>
const { chromium } = require('playwright');
const { spawn } = require('child_process');
const fs = require('fs'), path = require('path');
const SV = require('../src/saves.js');
(async () => {
const [bridge, fw, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const br = spawn(bridge, [fw, out + '/device_flash.bin'], { stdio: ['pipe', 'pipe', 'inherit'] });
await new Promise((r) => setTimeout(r, 15000));
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; page.on('pageerror', (e) => errors.push(e.message));
await page.exposeFunction('__tx', (a) => new Promise((r) => br.stdin.write(Buffer.from(a), r)));
await page.addInitScript(() => {
const q = [], waiting = [];
window.__rx = (a) => { const v = new Uint8Array(a); if (waiting.length) waiting.shift()({ value: v, done: false }); else q.push(v); };
const port = { open: async () => {}, close: async () => {},
writable: { getWriter: () => ({ write: (d) => window.__tx(Array.from(d)), releaseLock() {} }) },
readable: { getReader: () => ({ read: () => q.length ? Promise.resolve({ value: q.shift(), done: false }) : new Promise((r) => waiting.push(r)), cancel: async () => {}, releaseLock() {} }) } };
Object.defineProperty(navigator, 'serial', { value: { requestPort: async () => port } });
});
br.stdout.on('data', (d) => page.evaluate((a) => window.__rx(a), Array.from(d)).catch(() => {}));
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.click('[data-lang="en"]');
await page.click('#btnDevice');
await page.evaluate(() => { const c = window.ParamixFlash.connect; window.ParamixFlash.connect = (io, img, o, s) => c(io, img, { timeScale: 20 }, s); });
await page.click('#btnConn');
await page.waitForFunction(() => !document.getElementById('btnSaveRead').disabled, null, { timeout: 400000 });
console.log('info:', await page.textContent('#devInfo'));
// back up
if (process.env.ROM) { await page.setInputFiles('#fileRom', process.env.ROM); await page.waitForSelector('#work.on', { timeout: 60000 }); }
const dls = []; page.on('download', (d) => dls.push(d));
await page.click('#btnSaveRead');
await page.waitForFunction(() => /Backed up|Error/.test(document.getElementById('devStat').textContent), null, { timeout: 900000 });
for (let t = 0; t < 60 && dls.length < (process.env.ROM ? 2 : 1); t++) await page.waitForTimeout(500);
for (const d of dls) await d.saveAs(out + '/' + d.suggestedFilename());
const d1 = dls[0]; const f1 = out + '/' + d1.suggestedFilename();
if (dls[1]) { const g = fs.readFileSync(out + '/' + dls[1].suggestedFilename()); const fw = fs.readFileSync(process.env.GUEST); console.log('sav', dls[1].suggestedFilename(), g.length, 'equals firmware:', Buffer.compare(g.subarray(0, fw.length), fw) === 0); }
await page.waitForFunction(() => !document.getElementById('btnSaveRead').disabled, null, { timeout: 300000 });
console.log('backup:', d1.suggestedFilename(), '|', await page.textContent('#devStat'));
const sv = SV.paraDecode(new Uint8Array(fs.readFileSync(f1)));
console.log('pages', sv.pages.size, 'counter', sv.counter, 'edition', sv.edition);
// change one page and write it back
const p = 0xE20000; sv.pages.set(p, new Uint8Array(0x1000).fill(0x33));
const f2 = out + '/changed.tamasave'; fs.writeFileSync(f2, SV.paraEncode(sv.pages, sv.edition, { counter: sv.counter, ctrl: 0xE0 }));
page.on('dialog', (dl) => { console.log('dialog:', dl.message().split('\n')[0]); dl.accept(); });
await page.setInputFiles('#fileSave', f2);
await page.waitForFunction(() => /Done|Error/.test(document.getElementById('devStat').textContent), null, { timeout: 300000 });
console.log('write:', await page.textContent('#devStat'));
// a save of another edition is refused
const f3 = out + '/other.tamasave'; fs.writeFileSync(f3, SV.paraEncode(sv.pages, sv.edition === 1 ? 2 : 1, null));
await page.setInputFiles('#fileSave', f3); await page.waitForTimeout(500);
console.log('other edition:', await page.textContent('#devStat'));
await page.screenshot({ path: out + '/save_dev.png' });
br.stdin.end(); await new Promise((r) => br.on('exit', r));
const fl = fs.readFileSync(out + '/device_flash.bin');
console.log('page on the device:', fl[p] === 0x33 && fl[p + 0xFFF] === 0x33, 'errors:', errors);
await browser.close();
})();
+35
View File
@@ -0,0 +1,35 @@
// Tab "Save": import a TamaEmu .sav into a ROM, save, export again, compare.
// Usage: node test/ui_save_import_test.js <rom_with_emu> <save.sav> <output_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
(async () => {
const [rom, sav, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 860 }, acceptDownloads: true });
const errors = []; page.on('pageerror', (e) => errors.push(e.message));
await page.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.setInputFiles('#fileRom', rom);
await page.waitForSelector('#work.on', { timeout: 60000 });
await page.click('.tab[data-tab="save"]');
console.log('Einspielen Paradise ohne Gerät gesperrt:', await page.isDisabled('#btnParaIn'));
await page.setInputFiles('#fileEmuSav', sav);
await page.waitForTimeout(800);
console.log('Status:', await page.textContent('#saveStat'));
console.log('Plan:', (await page.textContent('#plan')).slice(0, 120));
await page.screenshot({ path: out + '/save_import.png' });
const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 120000 }), page.click('#btnSave')]);
const romOut = out + '/rom_out.bin'; await dl.saveAs(romOut);
await page.setInputFiles('#fileRom', romOut); await page.waitForTimeout(1500);
await page.click('.tab[data-tab="save"]');
const [d2] = await Promise.all([page.waitForEvent('download'), page.click('#btnEmuOut')]);
const back = out + '/back.sav'; await d2.saveAs(back);
console.log('sav gleich nach Rundweg:', fs.readFileSync(back).equals(fs.readFileSync(sav)));
// wrong file
await page.setInputFiles('#fileEmuSav', { name: 'x.sav', mimeType: 'application/octet-stream', buffer: Buffer.alloc(1000) });
await page.waitForTimeout(300);
console.log('Falsche Datei:', await page.textContent('#toast'));
console.log('Fehler:', errors);
await browser.close();
})();
+77
View File
@@ -0,0 +1,77 @@
// test23: a save file goes to the program of its kind (whatever the list shows), also to an emulator added but not yet
// saved; T18Emu also takes the save of the T18Emu app (flash from 0x570000, or its .zip with flash.bin).
// node test/ui_save_pick_test.js <land.bin> <tamago.bin> <t7 save.bin> <colour Tama firmware> <its .sav or - (made from the firmware)> <tg18 firmware> <out>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js'), SV = require('../src/saves.js'), C = require('../src/core.js');
(async () => {
const [land, go, t7s, psfw, pssav, tg18, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = [], dialogs = []; p.on('pageerror', (e) => errors.push(e.message)); p.on('dialog', (d) => { dialogs.push(d.message()); d.accept(); });
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
const save = async (n) => { const dlp = p.waitForEvent('download', { timeout: 240000 }).catch(() => null); await p.click('#btnSave'); const dl = await dlp; if (!dl) { console.log('no download: ' + await p.evaluate(() => document.getElementById('toast').textContent)); process.exit(1); } const f = out + '/' + n; await dl.saveAs(f); return f; };
const load = async (f) => { await p.setInputFiles('#fileRom', f); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(2500); };
const stat = () => p.evaluate(() => document.getElementById('saveStat').textContent + ' | ' + document.getElementById('toast').textContent);
const imp = async (f) => { await p.click('.tab[data-tab="save"]'); await p.setInputFiles('#fileEmuSav', f); await p.waitForTimeout(3000); return stat(); };
const opts = () => p.evaluate(() => [...document.getElementById('saveFor').options].map((o) => [o.value, o.textContent]));
const T7 = new Uint8Array(fs.readFileSync(t7s));
let PS; if (pssav === '-') { PS = new Uint8Array(fs.readFileSync(psfw)); let k = 0x100000; while (PS[k] === 0xFF) k++; PS[k + 3] ^= 0x5A; } else PS = new Uint8Array(fs.readFileSync(pssav));
const psFile = out + '/tama.sav'; fs.writeFileSync(psFile, PS);
// 1. T7Emu added in this session, not saved yet: its save is taken (before: "T7Emu has to be in the ROM")
await load(land);
await p.click('.tab[data-tab="emu"]'); await p.setInputFiles('#fileEmu', go); await p.waitForTimeout(2000);
let s = await imp(t7s); ok(/T7Emu-Spielstand übernommen/.test(s), 'T7Emu just added: save taken (' + s.slice(0, 60) + ')');
const r1 = await save('r1.bin'); let img = new Uint8Array(fs.readFileSync(r1));
ok(Buffer.from(SV.t7SaveOut(img) || []).equals(Buffer.from(T7)), 'T7Emu save in the ROM');
// 2. start device, colour Tama main, T7Emu in the menu: the list on one program, the file of the other goes to its own
await load(land);
await p.click('.tab[data-tab="feld"]'); await p.click('#launchOn'); await p.waitForTimeout(1500); // start device: room for both
await p.click('.tab[data-tab="emu"]'); await p.setInputFiles('#fileEmu', psfw); await p.waitForTimeout(3000);
await p.setInputFiles('#fileApp', go); await p.waitForTimeout(1000);
const r2 = await save('r2.bin'); await load(r2);
await p.click('.tab[data-tab="save"]'); const o = await opts(); ok(o.length === 2, 'two programs: ' + o.map((x) => x[1]).join(', '));
await p.selectOption('#saveFor', 'm'); await p.waitForTimeout(200);
const T7b = new Uint8Array(T7); T7b[100] ^= 0x33; fs.writeFileSync(out + '/t7b.bin', T7b);
s = await imp(out + '/t7b.bin'); ok(/übernommen/.test(s), 'T7Emu save with the colour Tama chosen: to the T7Emu in the menu (' + s.slice(0, 60) + ')');
await p.selectOption('#saveFor', o.find((x) => x[0] !== 'm')[0]); await p.waitForTimeout(200);
s = await imp(psFile); ok(/übernommen/.test(s) && !dialogs.length, 'colour Tama save with T7Emu chosen: to the colour Tama, no question (' + s.slice(0, 60) + ')');
const r3 = await save('r3.bin'); img = new Uint8Array(fs.readFileSync(r3));
const xs = E.appsRead(img, F.feldApps(img, fe.stub).apps), x = xs.find((y) => E.extraKind(y) === 't7');
ok(x && Buffer.from(SV.t7SaveOut(img, x.saveOff) || []).equals(Buffer.from(T7b)), 'T7Emu save in the ROM (in the menu)');
const cfg = SV.emuCfg(img.subarray(0xA0000, 0xA1000));
const g = cfg && await SV.emuGuestAsync((a, n) => img.subarray(a, a + n), cfg);
ok(g && Buffer.from(g).equals(Buffer.from(PS)), 'colour Tama save in the ROM');
// 3. T18Emu: the T18Emu app's save (flash from 0x570000) and its .zip
await load(land);
await p.click('.tab[data-tab="emu"]'); await p.setInputFiles('#fileEmu', tg18); await p.waitForTimeout(2500);
const fw0 = new Uint8Array(fs.readFileSync(tg18)), part = fw0.slice(0x570000); part[0x5E0100 - 0x570000] ^= 0x5A; part[0x700000 - 0x570000] ^= 0x11;
fs.writeFileSync(out + '/t18emu.sav', part);
s = await imp(out + '/t18emu.sav'); ok(/übernommen/.test(s), 'T18Emu just added: app save taken (' + s.slice(0, 60) + ')');
const r4 = await save('r4.bin'); img = new Uint8Array(fs.readFileSync(r4));
let fw = E.t18FromRom(img), want = new Uint8Array(fw0); want.set(part, 0x570000);
ok(fw && Buffer.from(fw).equals(Buffer.from(want)), 'T18Emu: app save in the firmware of the ROM');
await load(r4);
const flash = new Uint8Array(want); flash[0x600010] ^= 0x77;
fs.writeFileSync(out + '/t18.zip', C.zipBuild([{ name: 'flash.bin', data: flash }, { name: 'rom.txt', data: new TextEncoder().encode('x') }]));
s = await imp(out + '/t18.zip'); ok(/übernommen/.test(s), 'T18Emu: app .zip taken (' + s.slice(0, 60) + ')');
const r5 = await save('r5.bin'); fw = E.t18FromRom(new Uint8Array(fs.readFileSync(r5)));
ok(fw && Buffer.from(fw).equals(Buffer.from(flash)), 'T18Emu: .zip save in the ROM');
// export goes back to the app: the whole flash (the app takes 8 MB)
await p.click('.tab[data-tab="save"]');
await load(r5); await p.click('.tab[data-tab="save"]');
{ const dlp = p.waitForEvent('download', { timeout: 60000 }).catch(() => null); await p.click('#btnEmuOut'); const dl = await dlp; const f = dl && out + '/x-t18.bin'; if (dl) await dl.saveAs(f);
ok(dl && fs.statSync(f).size === 0x800000 && Buffer.from(fs.readFileSync(f)).equals(Buffer.from(flash)), 'T18Emu export: 8 MB as the app imports it'); }
// 4. no T7Emu anywhere: a clear message
await load(land); s = await imp(t7s); ok(/Tab Emulator/.test(s), 'no T7Emu: says where to add it (' + s.slice(0, 80) + ')');
ok(!errors.length, 'no page errors ' + errors.join('; '));
ok(!dialogs.length, 'no questions ' + dialogs.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+71
View File
@@ -0,0 +1,71 @@
// 1.6.11 test2: save export and import for every program in the list: Game Boy and Master System (.sav, the cartridge
// RAM), Wolf3D (its saved game), T18Emu (firmware with its save). Imported, written, read back, exported again.
// node test/ui_saveexp_test.js <paradise.bin> <game.gb with battery> <cart.sav> <game.sms> <folder .WL1> <tg18 fw> <tg18 fw with save> <out>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, gb, gsav, sms, wdir, t18, t18s, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const ssav = Buffer.alloc(0x2000); for (let i = 0; i < ssav.length; i++) ssav[i] = (i * 7 + 3) & 255; fs.writeFileSync(out + '/sms.sav', ssav);
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
const save = async (n) => { const dlp = p.waitForEvent('download', { timeout: 240000 }); await p.click('#btnSave'); const dl = await dlp; const f = out + '/' + n; await dl.saveAs(f); return f; };
const load = async (f) => { await p.setInputFiles('#fileRom', f); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(2500); };
await load(rom);
await p.click('.tab[data-tab="feld"]'); await p.click('#bagOn'); await p.waitForTimeout(800);
await p.click('.tab[data-tab="gb"]'); await p.setInputFiles('#fileGb', gb); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="sms"]'); await p.setInputFiles('#fileSms', sms); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="wolf"]'); await p.setInputFiles('#fileWolf', fs.readdirSync(wdir).filter((n) => /\.WL1$/i.test(n)).map((n) => path.join(wdir, n))); await p.waitForTimeout(4000);
const r1 = await save('r1.bin'); await load(r1);
await p.click('.tab[data-tab="save"]');
const opts = await p.evaluate(() => [...document.getElementById('saveFor').options].map((o) => [o.value, o.textContent]));
ok(opts.length === 3, 'three programs in the list: ' + opts.map((o) => o[1]).join(', '));
const pick = async (re) => { const v = opts.find((o) => re.test(o[1])); await p.selectOption('#saveFor', v[0]); await p.waitForTimeout(200); };
const imp = async (re, f) => { await pick(re); await p.setInputFiles('#fileEmuSav', f); await p.waitForTimeout(1500); return p.evaluate(() => document.getElementById('saveStat').textContent + ' | ' + document.getElementById('toast').textContent); };
const exp = async (re) => { await pick(re); const dlp = p.waitForEvent('download', { timeout: 60000 }).catch(() => null); await p.click('#btnEmuOut'); const dl = await dlp; if (!dl) return null; const f = out + '/x-' + dl.suggestedFilename(); await dl.saveAs(f); return fs.readFileSync(f); };
ok(!(await p.evaluate(() => document.getElementById('btnEmuOut').disabled)), 'export button on');
// fresh: the Game Boy has no save yet
await pick(/POKEMON|RED/i); await p.click('#btnEmuOut'); await p.waitForTimeout(500);
ok(/Noch kein Spielstand/.test(await p.evaluate(() => document.getElementById('toast').textContent)), 'no save yet: said');
console.log(' ' + await imp(/POKEMON|RED/i, gsav));
console.log(' ' + await imp(/ALEX|KIDD|MASTER/i, out + '/sms.sav'));
ok(/passt nicht/.test(await imp(/WOLF/i, out + '/sms.sav')), 'a wrong file for Wolf3D refused');
const r2 = await save('r2.bin'); await load(r2);
const img = new Uint8Array(fs.readFileSync(r2)), xs = E.appsRead(img, F.feldApps(img, fe.stub).apps);
const g = xs.find((x) => x.kind === 'gb'), s = xs.find((x) => x.kind === 'sms');
const gs = fs.readFileSync(gsav);
ok(g && Buffer.from(g.save.subarray(0x1000, 0x1000 + 0x8000)).equals(gs.subarray(0, 0x8000)) && g.save.subarray(0x9000).every((v) => v === 0xFF), 'Game Boy: cartridge RAM in the ROM, no old state');
ok(s && Buffer.from(s.save.subarray(0x1000, 0x3000)).equals(ssav), 'Master System: cartridge RAM in the ROM');
await p.click('.tab[data-tab="save"]');
ok(Buffer.from(await exp(/POKEMON|RED/i) || []).equals(gs.subarray(0, 0x8000)), 'Game Boy export = the .sav');
ok(Buffer.from(await exp(/ALEX|KIDD|MASTER/i) || []).equals(ssav), 'Master System export = the .sav (8 KB)');
// T18Emu as the main program: its firmware with the save in and out
await load(rom);
await p.click('.tab[data-tab="emu"]'); await p.setInputFiles('#fileEmu', t18); await p.waitForTimeout(2000);
const r3 = await save('r3.bin'); await load(r3);
await p.click('.tab[data-tab="save"]');
const o2 = await p.evaluate(() => [...document.getElementById('saveFor').options].map((o) => o.textContent));
ok(o2.length === 1 && /MEETS/.test(o2[0]), 'T18Emu listed: ' + o2.join(', '));
// a firmware with a save that needs more blocks than are free: refused right away, the ROM stays as it was
await p.setInputFiles('#fileEmuSav', t18s); await p.waitForTimeout(4000);
const tt = await p.evaluate(() => document.getElementById('toast').textContent);
if (/room|Platz/.test(tt)) ok(true, 'too big: refused at once (' + tt + ')');
// one that fits: the installed firmware with a changed byte in a used block
const want = E.t18FromRom(new Uint8Array(fs.readFileSync(r3)));
let at = 0; while (want[at] === 0xFF) at++; want[at + 0x123] ^= 0x5A; fs.writeFileSync(out + '/t18fit.bin', want);
await p.setInputFiles('#fileEmuSav', out + '/t18fit.bin'); await p.waitForTimeout(4000);
const r4 = await save('r4.bin');
const fw = E.t18FromRom(new Uint8Array(fs.readFileSync(r4)));
ok(fw && Buffer.from(fw).equals(Buffer.from(want)), 'T18Emu: firmware with save in the ROM');
await load(r4); await p.click('.tab[data-tab="save"]');
{ await p.waitForTimeout(300); const dlp = p.waitForEvent('download', { timeout: 60000 }).catch(() => null); await p.click('#btnEmuOut'); const dl = await dlp; const f = dl && out + '/x-t18.bin'; if (dl) await dl.saveAs(f);
ok(dl && Buffer.from(fs.readFileSync(f)).equals(Buffer.from(want)), 'T18Emu export = the firmware with save'); }
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+35
View File
@@ -0,0 +1,35 @@
// Six fields in the browser (local only): load Tropical/Glacier, tick "All 6 fields",
// pick a Land/Water/Sky ROM, save, load the result again.
// Usage: node test/ui_six_test.js <tropical.bin> <land.bin> <output_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
(async () => {
const [rom, land, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; page.on('pageerror', e => errors.push(e.message)); page.on('console', m => { if (m.type() === 'error') errors.push(m.text()); });
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
const save = async (name) => { const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 180000 }), page.click('#btnSave')]); const p = out + '/' + name + '_' + dl.suggestedFilename(); await dl.saveAs(p); return p; };
await page.setInputFiles('#fileRom', rom);
await page.waitForSelector('#work.on', { timeout: 60000 });
await page.click('.tab[data-tab="feld"]');
await page.waitForTimeout(300);
console.log('row visible:', await page.isVisible('#sixRow'));
const [fc] = await Promise.all([page.waitForEvent('filechooser'), page.check('#sixOn')]);
await fc.setFiles(land);
await page.waitForTimeout(500);
await page.check('#bagOn');
console.log('Status 1:', await page.evaluate(() => document.getElementById('feldStat').innerText));
console.log('Plan:', await page.evaluate(() => document.getElementById('plan').innerText.replace(/\s+/g, ' ').slice(0, 300)));
await page.screenshot({ path: out + '/six_1.png', fullPage: true });
const a = await save('six');
console.log('ROM:', a);
await page.setInputFiles('#fileRom', a);
await page.waitForTimeout(2000);
await page.click('.tab[data-tab="feld"]');
console.log('Status 2:', JSON.stringify(await page.evaluate(() => [document.getElementById('feldStat').innerText, document.getElementById('sixOn').checked, document.getElementById('sixOn').disabled])));
await page.screenshot({ path: out + '/six_2.png', fullPage: true });
console.log('errors:', errors);
await browser.close();
})();
+33
View File
@@ -0,0 +1,33 @@
// Tab "Save" (1.6.8): choose the save slot for the Paradise export (ROM with menu in saves mode and a stored save).
// Usage: node test/ui_slot_test.js <rom_with_slots> <output_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const SV = require('../src/saves.js');
(async () => {
const [rom, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 860 }, acceptDownloads: true });
const errors = []; page.on('pageerror', (e) => errors.push(e.message));
await page.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.setInputFiles('#fileRom', rom);
await page.waitForSelector('#work.on', { timeout: 60000 });
await page.click('.tab[data-tab="save"]');
console.log('Platz sichtbar:', !(await page.isHidden('#paraSlotRow')));
const opts = await page.$$eval('#paraSlot option', (o) => o.map((x) => x.value + '=' + x.textContent));
console.log('Plätze:', opts.join(' | '));
const r = new Uint8Array(fs.readFileSync(rom));
for (const v of ['live', '1', '2']) {
await page.selectOption('#paraSlot', v);
const dl = await Promise.race([page.waitForEvent('download', { timeout: 5000 }).catch(() => null), page.click('#btnParaOut').then(() => page.waitForEvent('download', { timeout: 5000 }).catch(() => null))]);
if (!dl) { await page.waitForTimeout(300); console.log(v, 'kein Download:', await page.textContent('#toast')); continue; }
const f = out + '/' + dl.suggestedFilename(); await dl.saveAs(f);
const sv = SV.paraDecode(new Uint8Array(fs.readFileSync(f)));
const m = sv.pages.get(0xE20000);
console.log(v, dl.suggestedFilename(), 'Seiten', sv.pages.size, 'Marke', !!m && m[7] === 0x33, 'Einst. gleich ROM', Buffer.compare(Buffer.from(sv.pages.get(0xEFE000)), Buffer.from(r.subarray(0xEFE000, 0xEFF000))) === 0);
}
await page.screenshot({ path: out + '/slot.png' });
console.log('Fehler:', errors);
await browser.close();
})();
+29
View File
@@ -0,0 +1,29 @@
// 1.6.8: a TamaSma card in the Card tab: its characters, one of them onto a figure, saved.
// node test/ui_sma_test.js <paradise.bin> <tamasma card.bin> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const C = require('../src/core.js');
(async () => {
const [rom, card, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 1000 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(2000);
await p.click('.tab[data-tab="dim"]');
await p.setInputFiles('#fileDim', card); await p.waitForTimeout(1500);
const n = await p.$$eval('#dimArea .dimgrid .tile', (l) => l.length);
ok(n > 5, 'card characters shown: ' + n);
await p.screenshot({ path: out + '/sma.png' });
await p.click('#dimArea .assign .btn.primary'); await p.waitForTimeout(3000);
ok(/Figur|Karte/.test(await p.textContent('#toast')), 'applied: ' + (await p.textContent('#toast')).slice(0, 80));
const [dl] = await Promise.all([p.waitForEvent('download', { timeout: 300000 }), p.click('#btnSave')]);
const f = out + '/sma.bin'; await dl.saveAs(f);
const r = new Uint8Array(fs.readFileSync(f)), c0 = C.openRom(new Uint8Array(fs.readFileSync(rom))), c1 = C.openRom(r);
ok(c1.entries[c0.adult].some((v, i) => v !== c0.entries[c0.adult][i]) || c1.entries[c0.adult].length !== c0.entries[c0.adult].length, 'adult sprite changed');
C.verifyRom(r, [c0.adult, c0.adult + 3]); ok(true, 'ROM checks out');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close(); console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+68
View File
@@ -0,0 +1,68 @@
// 1.6.10 test2: tab Master System: two games into the menu, keys changed, saved, read back; the program at its place.
// node test/ui_sms_test.js <paradise.bin> <game1.sms> <game2.sms> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, g1, g2, out, g3] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) }, app = fs.readFileSync(__dirname + '/../sms/sms.bin');
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]'); await p.click('#bagOn'); await p.waitForTimeout(800);
await p.click('.tab[data-tab="sms"]');
ok(await p.evaluate(() => !document.getElementById('pane-sms').hidden), 'tab Master System shown');
ok(await p.evaluate(() => document.querySelectorAll('#smsKeyGrid select').length === 9 && document.getElementById('smsInv').checked), 'nine key lines, wheel reversed by default');
fs.writeFileSync(out + '/bad.bin', Buffer.alloc(0x8000, 1));
await p.setInputFiles('#fileSms', out + '/bad.bin'); await p.waitForTimeout(400);
ok(/kein Master-System- oder Game-Gear-Spiel/.test(await p.evaluate(() => document.getElementById('toast').textContent)), 'bad file refused');
const gg = Buffer.alloc(0x8000, 0); gg.write('TMR SEGA', 0x7FF0); gg[0x7FFF] = 0x6C; fs.writeFileSync(out + '/x.gg', gg);
await p.setInputFiles('#fileSms', [g1, g2]);
for (let i = 0; i < 60 && (await p.evaluate(() => document.querySelectorAll('#smsList .dlcrow').length)) < 2; i++) await p.waitForTimeout(500);
const names = await p.evaluate(() => document.getElementById('smsList').innerText);
const t1 = E.smsTitle(path.basename(g1)), t2 = E.smsTitle(path.basename(g2));
ok(names.includes(t1) && names.includes(t2), 'both games listed (' + t1 + ', ' + t2 + ')');
{ const plan = (await p.evaluate(() => document.getElementById('plan').innerText)).replace(/\s+/g, ' ');
ok(/Master System \/ Game Gear ALEX KIDD SHINO, CASTLE ILLUSION · neu/.test(plan) && /Master System \/ Game Gear 0\.75 MB/.test(plan) && !/Emulatoren ALEX/.test(plan), 'own chip and own part of the flash bar: ' + plan.slice(0, 300)); }
await p.evaluate(() => { const s = document.querySelectorAll('#smsKeyGrid select')[1]; s.value = '32'; s.dispatchEvent(new Event('change')); });
await p.waitForTimeout(200);
ok(/Nicht belegt: Knopf 1/.test(await p.evaluate(() => document.getElementById('smsKeysStat').textContent)), 'note: button 1 not assigned');
const dlp = p.waitForEvent('download', { timeout: 120000 }); await p.click('#btnSave');
const dl = await dlp; const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1));
const xs = E.appsRead(img, F.feldApps(img, fe.stub).apps).filter((y) => y.kind === 'sms');
ok(xs.length === 2, 'two Master System games in the menu');
const x = xs.find((y) => y.title === t1);
ok(!!x && Buffer.from(x.rom).equals(fs.readFileSync(g1)), 'the game as given');
ok(x && x.keys[1] === 32 && x.keys[0] === 4 && x.keys[2] === 8 && x.keys[3] === 32 && x.keys[6] === 64 && x.inv, 'keys and wheel direction in the settings block');
ok(x && Buffer.from(img.subarray(x.off + 0x300, x.off + app.length)).equals(app.subarray(0x300)), 'SMSEmu program in place');
ok(x && x.saveOff === x.off + 0x10000 && img.subarray(x.saveOff, x.saveOff + 0x10000).every((v) => v === 0xFF), 'empty save area behind the program');
fs.writeFileSync(out + '/sms_off.txt', String(x ? x.off : 0));
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(3000);
await p.click('.tab[data-tab="sms"]');
const back = await p.evaluate(() => document.getElementById('smsList').innerText);
ok(back.includes(t1) && back.includes(t2), 'read back: games listed');
ok(await p.evaluate(() => document.querySelectorAll('#smsKeyGrid select')[1].value === '32' && document.getElementById('smsInv').checked), 'read back: keys');
if (g3) {
await p.click('.tab[data-tab="sms"]');
await p.setInputFiles('#fileSms', g3);
for (let i = 0; i < 60 && (await p.evaluate(() => document.querySelectorAll('#smsList .dlcrow').length)) < 3; i++) await p.waitForTimeout(500);
const dl2p = p.waitForEvent('download', { timeout: 120000 }); await p.click('#btnSave');
const dl2 = await dl2p; const r2 = out + '/gg_' + dl2.suggestedFilename(); await dl2.saveAs(r2);
const im2 = new Uint8Array(fs.readFileSync(r2));
const ys = E.appsRead(im2, F.feldApps(im2, fe.stub).apps).filter((y) => y.kind === 'sms');
const gx = ys.find((y) => y.gg);
ok(ys.length === 3 && !!gx && Buffer.from(gx.rom).equals(fs.readFileSync(g3)) && ys.filter((y) => y.gg).length === 1, 'Game Gear game in the menu, marked as Game Gear');
fs.unlinkSync(r2);
}
ok(/Master System sind Marken von SEGA/.test(await p.evaluate(() => document.querySelector('footer').innerText)), 'trademarks in the footer');
await p.screenshot({ path: out + '/sms_tab.png', fullPage: false });
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+31
View File
@@ -0,0 +1,31 @@
// T18Emu in the browser: TG18 firmware into a Paradise ROM, save, load again (status), remove.
// node test/ui_t18_test.js <paradise.bin> <tg18_firmware.bin> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, fw, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; page.on('pageerror', (e) => errors.push(e.message));
await page.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.setInputFiles('#fileRom', rom);
await page.waitForSelector('#work.on', { timeout: 60000 });
await page.click('.tab[data-tab="emu"]');
await page.setInputFiles('#fileEmu', fw);
await page.waitForTimeout(800);
console.log('Status:', (await page.textContent('#emuStat')).replace(/\n/g, ' | '));
await page.screenshot({ path: out + '/t18_1.png' });
const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 120000 }), page.click('#btnSave')]);
const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1)), c = E.t18Cfg(img);
console.log('ROM', path.basename(r1), 'type', F.emuType(img), 'blocks', c && c.map.filter((b) => b !== 0xFFFF).length, 'spares', c && c.spare.length);
await page.setInputFiles('#fileRom', r1); await page.waitForTimeout(1500);
await page.click('.tab[data-tab="emu"]');
console.log('Status after loading:', (await page.textContent('#emuStat')).replace(/\n/g, ' | '));
await page.screenshot({ path: out + '/t18_2.png' });
console.log(errors.length ? 'page errors: ' + errors.join('; ') : 'no page errors');
await browser.close();
})();
+51
View File
@@ -0,0 +1,51 @@
// 1.6.8 (test47): T18Emu items in the browser. A start device with a TG18 firmware that has run once (its save filled) as the main program,
// MyMeets files into its save, Tamapoints; saved ROM: the items are in the firmware read back from it; loaded again:
// the installed T18Emu shows them, a further change goes in too.
// Pictures for grow up: the set of the Android T18Emu (pictures and erwachsen.json) go in as 10 pictures.
// node test/ui_t18items_test.js <paradise.bin> <tg18_with_save.bin> <item_dir> <out_dir> [<picture_dir>]
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js');
(async () => {
const [rom, tg18, idir, out, pdir] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const files = fs.readdirSync(idir).filter((f) => /^tg18_.*\.txt$/.test(f)).map((f) => path.join(idir, f));
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
const save = async (n) => { const dlp = p.waitForEvent('download', { timeout: 300000 }); setTimeout(async () => { try { console.log('toast:', await p.textContent('#toast')); } catch (e) {} }, 60000); await p.click('#btnSave'); const dl = await dlp; const f = out + '/' + n; await dl.saveAs(f); return new Uint8Array(fs.readFileSync(f)); };
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]'); await p.click('#launchOn'); await p.waitForTimeout(1500); // start device: room for the firmware with its save
await p.click('.tab[data-tab="emu"]'); await p.setInputFiles('#fileEmu', tg18); await p.waitForTimeout(1500);
await p.locator('#appsList .prow').first().locator('.ptog').click(); await p.waitForTimeout(500);
ok(await p.isVisible('text=MyMeets-Dateien wählen'), 'items section shown');
await p.click('text=MyMeets-Dateien wählen').catch(() => {});
await p.setInputFiles('#fileT18Item', files); await p.waitForTimeout(1500);
const shown = await p.$$eval('.pdet .itemname', (l) => l.map((x) => x.textContent.trim()));
ok(shown.length >= 5, 'items listed: ' + shown.join(', '));
if (pdir) { await p.setInputFiles('#fileT18Pic', fs.readdirSync(pdir).map((f) => path.join(pdir, f))); await p.waitForTimeout(2000);
ok((await p.$$('.picgrid figure')).length >= 10, 'pictures shown: ' + (await p.$$('.picgrid figure')).length); }
await p.fill('.pdet input[type=number]', '1234'); await p.dispatchEvent('.pdet input[type=number]', 'change'); await p.waitForTimeout(300);
const a = await save('i1.bin');
const fw = E.t18FromRom(a), it = fw && E.t18Items(fw);
ok(!!it, 'firmware read back');
const names = it ? it.areas.flatMap((x) => x.slots.filter((s) => s.rec).map((s) => s.rec.name)) : [];
ok(names.includes('WASABI') && names.includes('MAGIC WAN') && names.includes('PINK CLOV'), 'items in the save: ' + names.join(', '));
ok(it && it.room && it.room.name === 'SUNSET', 'room: ' + (it && it.room && it.room.name));
ok(it && it.points === 1234, 'Tamapoints ' + (it && it.points));
if (pdir) { const pm = E.t18PicsRead(a); ok(pm.size === 10 && pm.has(16) && pm.has(35), 'pictures in the ROM: ' + [...pm.keys()].join(',')); }
// load again: the installed program shows them; remove one, save
await p.setInputFiles('#fileRom', out + '/i1.bin'); await p.waitForTimeout(3000); await p.click('.tab[data-tab="emu"]');
if (!(await p.$('.pdet'))) await p.locator('#appsList .prow .ptog').first().click(); await p.waitForTimeout(800);
const shown2 = await p.$$eval('.pdet .itemname', (l) => l.map((x) => x.textContent.trim()));
ok(shown2.some((x) => /WASABI/.test(x)), 'installed: items shown (' + shown2.length + ')');
await p.locator('.pdet .dlcrow', { hasText: 'WASABI' }).locator('button').click(); await p.waitForTimeout(500);
const c = await save('i2.bin');
const it2 = E.t18Items(E.t18FromRom(c));
const names2 = it2.areas.flatMap((x) => x.slots.filter((s) => s.rec).map((s) => s.rec.name));
ok(!names2.includes('WASABI') && names2.includes('HOT COCOA'), 'removed on the installed one: ' + names2.join(', '));
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close(); console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+54
View File
@@ -0,0 +1,54 @@
// 1.6.8 (test2): T18Emu as a further program in the menu of a start device stays where it is when the ROM is saved
// again (items, settings, another program removed). Its save grows while it runs, so placing it anew could fail
// with "too little room" on a full ROM.
// node test/ui_t18keep_test.js <paradise.bin> <v1_rom.bin> <second_v1_rom.bin> <tg18_with_save.bin> <item_dir> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, v1, v1b, tg18, idir, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const stub = new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin'));
const files = fs.readdirSync(idir).filter((f) => /^tg18_.*\.txt$/.test(f)).slice(0, 6).map((f) => path.join(idir, f));
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const apps = (r) => E.appsRead(r, F.feldApps(r, stub).apps);
const t18of = (r) => apps(r).find((x) => x.kind === 't18');
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
const save = async (n) => { const dlp = p.waitForEvent('download', { timeout: 300000 }); await p.click('#btnSave'); const dl = await Promise.race([dlp, p.waitForTimeout(240000).then(() => null)]); if (!dl) { console.log('toast:', await p.textContent('#toast')); return null; } const f = out + '/' + n; await dl.saveAs(f); return new Uint8Array(fs.readFileSync(f)); };
const load = async (f) => { await p.setInputFiles('#fileRom', f); await p.waitForTimeout(3000); await p.click('.tab[data-tab="emu"]'); await p.waitForTimeout(500); };
const open = async (name) => { const row = p.locator('#appsList .prow', { hasText: name }); await row.locator('.ptog').click(); await p.waitForTimeout(500); };
// start device like Bernd's: a V1Emu first, a second one and T18Emu with its save as further programs
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]'); await p.click('#launchOn'); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="emu"]'); await p.setInputFiles('#fileEmu', v1); await p.waitForTimeout(1500); await p.setInputFiles('#fileEmu', v1b); await p.waitForTimeout(1500);
await p.setInputFiles('#fileEmu', tg18); await p.waitForTimeout(2500); console.log('after T18:', await p.textContent('#toast'));
const a = await save('k1.bin'); ok(!!a, 'start device saved');
const t1 = a && t18of(a); ok(!!t1, 'T18Emu in the menu at ' + (t1 && t1.off.toString(16)));
// items into the program in the menu
await load(out + '/k1.bin'); await open('TAMA MEETS');
const fc = p.waitForEvent('filechooser'); await p.click('text=MyMeets-Dateien wählen'); await (await fc).setFiles(files); await p.waitForTimeout(1500);
const c = await save('k2.bin'); ok(!!c, 'saved with items');
const t2 = c && t18of(c);
ok(t2 && t1 && t2.off === t1.off, 'T18Emu stayed at ' + (t2 && t2.off.toString(16)));
const names = t2 ? E.t18Items(t2.fw).areas.flatMap((x) => x.slots.filter((s) => s.rec).map((s) => s.rec.name)) : [];
ok(names.length >= 4, 'items in its save: ' + names.join(', '));
const pa = c && t2 && new DataView(c.buffer).getUint32(t2.off + 0x140 + 428, true);
ok(t2 && pa === E.t18Addrs(t2.fw).param, 'its Param address renewed: ' + (pa >>> 0).toString(16));
// a setting only: the save stays as it is (the session too)
await load(out + '/k2.bin'); await open('TAMA MEETS');
await p.locator('#appsList .pdet').last().locator('select').nth(1).selectOption({ index: 3 }); await p.waitForTimeout(300);
const d = await save('k3.bin'); ok(!!d, 'saved with a new light setting');
const t3 = d && t18of(d), cf = d && t3 && E.extraCfg(d, t3.off);
ok(t3 && t3.off === t2.off, 'T18Emu still at its place');
ok(cf && c && d.subarray(cf.saveOff, cf.saveOff + 0x10000).every((v, i) => v === c[cf.saveOff + i]), 'its save untouched');
// the second program out: T18Emu stays
await load(out + '/k3.bin');
await p.locator('#appsList .prow').nth(1).locator('button:has-text("×")').click(); await p.waitForTimeout(500);
const e = await save('k4.bin'); ok(!!e, 'saved without the second program');
const t4 = e && t18of(e); ok(t4 && t4.off === t2.off && apps(e).length === apps(d).length - 1, 'T18Emu kept, the second program gone');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close(); console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+40
View File
@@ -0,0 +1,40 @@
// 1.6.10 test6: start device: the damaged further T18Emu out, the firmware in again and made the main program;
// the old further programs no longer block its room. node test/ui_t18main_test.js <start device ROM> <TG18 firmware> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, fwf, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const st = new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')), fw = new Uint8Array(fs.readFileSync(fwf));
const a = new Uint8Array(fs.readFileSync(rom)), n0 = E.appsRead(a, F.feldApps(a, st).apps).filter((x) => x.kind !== 't18').length;
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(2000);
await p.click('.tab[data-tab="emu"]'); await p.waitForTimeout(300);
await p.evaluate(() => { const r = [...document.querySelectorAll('#appsList .prow')].find((x) => /TAMA MEETS/.test(x.querySelector('.pname').textContent)); [...r.querySelectorAll('button')].find((x) => x.textContent.trim() === '×').click(); });
await p.waitForTimeout(1500);
await p.setInputFiles('#fileEmu', fwf); await p.waitForTimeout(6000);
await p.evaluate(() => { const r = [...document.querySelectorAll('#appsList .prow')].find((x) => /TAMA MEETS/.test(x.querySelector('.pname').textContent)); const s = [...r.querySelectorAll('button')].find((x) => x.textContent.trim() === '☆'); if (s) s.click(); });
await p.waitForTimeout(6000);
const dlp = p.waitForEvent('download', { timeout: 300000 }); await p.click('#btnSave');
const dl = await Promise.race([dlp, new Promise((r) => setTimeout(() => r(null), 90000))]);
ok(!!dl, 'saved (' + await p.evaluate(() => document.getElementById('toast').textContent) + ')');
if (dl) {
const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const o = new Uint8Array(fs.readFileSync(r1));
ok(F.emuType(o) === 't18', 'T18Emu is the main program');
const back = E.t18FromRom(o); ok(!!back && Buffer.from(back).equals(Buffer.from(fw)), 'its firmware complete');
const xs = E.appsRead(o, F.feldApps(o, st).apps); ok(xs.length === n0, 'the other programs still in the menu (' + xs.length + ')');
const c = E.t18Cfg(o), t = new Set(c.map.concat(c.spare).filter((x) => x !== 0xFFFF)); let clash = 0;
for (const x of xs) { const cc = E.extraCfg(o, x.off), rs = [[x.off, x.off + 0x10000]]; if (cc.romOff !== undefined) rs.push([cc.romOff, cc.romOff + (cc.romLen || 1)]); if (cc.saveOff) rs.push([cc.saveOff, cc.saveOff + 0x10000]); for (const [s, e] of rs) for (let k = s >> 16; k <= (e - 1) >> 16; k++) if (t.has(k)) clash++; }
ok(clash === 0, 'no program on T18Emu blocks');
fs.unlinkSync(r1);
}
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+62
View File
@@ -0,0 +1,62 @@
// T7Emu in the browser: V7 ROM and figures into a Paradise ROM, save, load again, remove a figure.
// node test/ui_t7_test.js <paradise.bin> <v7_rom.bin> <out_dir> <figure.bin...>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js');
(async () => {
const [rom, v7, out, ...figs] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; page.on('pageerror', (e) => errors.push(e.message));
await page.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.setInputFiles('#fileRom', rom);
await page.waitForSelector('#work.on', { timeout: 60000 });
await page.click('.tab[data-tab="emu"]');
await page.setInputFiles('#fileEmu', v7);
await page.waitForTimeout(500);
await page.setInputFiles('#fileT7Fig', figs);
await page.waitForTimeout(500);
console.log('Status:', (await page.textContent('#emuStat')).replace(/\n/g, ' | '));
if (!(await page.$('.pdet'))) await page.click('#appsList .prow .ptog'); // 1.6.8: figures in the program's row
console.log('Figuren:', await page.textContent('.pdet .chips'));
console.log('Plan:', (await page.textContent('#plan')).slice(0, 160));
await page.screenshot({ path: out + '/t7_1.png' });
const [dl] = await Promise.all([page.waitForEvent('download', { timeout: 120000 }), page.click('#btnSave')]);
const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const c1 = E.t7Cfg(new Uint8Array(fs.readFileSync(r1)));
console.log('ROM', path.basename(r1), 'figures', c1.figs.map((f) => f.name).join(', '));
await page.setInputFiles('#fileRom', r1); await page.waitForTimeout(1500);
await page.click('.tab[data-tab="emu"]');
console.log('Nach Laden:', (await page.textContent('#emuStat')).replace(/\n/g, ' | '));
if (!(await page.$('.pdet'))) await page.click('#appsList .prow .ptog');
console.log('Figuren:', await page.textContent('.pdet .chips'));
await page.click('.pdet .chips button'); await page.waitForTimeout(300);
const [dl2] = await Promise.all([page.waitForEvent('download', { timeout: 120000 }), page.click('#btnSave')]);
const r2 = out + '/second.bin'; await dl2.saveAs(r2);
const c2 = E.t7Cfg(new Uint8Array(fs.readFileSync(r2)));
console.log('nach Entfernen:', c2.figs.map((f) => f.name).join(', '));
await page.screenshot({ path: out + '/t7_2.png' });
// save.bin: into the ROM through the Save tab, out again
const SV = require('../src/saves.js');
const sv = new Uint8Array(4098); sv[0] = 3; for (let i = 2; i < 4098; i++) sv[i] = (i * 13) & 255;
fs.writeFileSync(out + '/save_in.bin', sv);
await page.setInputFiles('#fileRom', r2); await page.waitForTimeout(1500);
await page.click('.tab[data-tab="save"]');
console.log('Knopf:', await page.textContent('#btnEmuIn'), '| Export aktiv:', !(await page.isDisabled('#btnEmuOut')));
await page.setInputFiles('#fileEmuSav', out + '/save_in.bin'); await page.waitForTimeout(300);
console.log('Status:', await page.textContent('#saveStat'));
const [dl3] = await Promise.all([page.waitForEvent('download', { timeout: 120000 }), page.click('#btnSave')]);
const r3 = out + '/third.bin'; await dl3.saveAs(r3);
const got = SV.t7SaveOut(new Uint8Array(fs.readFileSync(r3)));
console.log('save.bin im ROM gleich:', !!got && Buffer.compare(Buffer.from(got), Buffer.from(sv)) === 0);
await page.setInputFiles('#fileRom', r3); await page.waitForTimeout(1500);
await page.click('.tab[data-tab="save"]');
const [dl4] = await Promise.all([page.waitForEvent('download', { timeout: 30000 }), page.click('#btnEmuOut')]);
const r4 = out + '/' + dl4.suggestedFilename(); await dl4.saveAs(r4);
console.log('Export', path.basename(r4), 'gleich:', Buffer.compare(fs.readFileSync(r4), Buffer.from(sv)) === 0);
await page.screenshot({ path: out + '/t7_3.png' });
console.log('Fehler:', errors);
await browser.close();
})();
+27
View File
@@ -0,0 +1,27 @@
// 1.6.8 (test5): Gotchi Points of a Tama-Go (T7Emu as the main program) in the Emulator tab: EEPROM 0x030.., BCD.
// node test/ui_t7gp_test.js <rom_with_t7emu_and_save.bin> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const SV = require('../src/saves.js');
(async () => {
const [rom, out] = process.argv.slice(2); fs.mkdirSync(out, { recursive: true });
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
// a save with 500 points
let r = new Uint8Array(fs.readFileSync(rom)); const s0 = SV.t7SaveOut(r); ok(!!s0, 'the ROM has a T7Emu save');
s0.set([0x00, 0x05, 0, 0, 0], 0x32); r = SV.t7SaveIn(r, s0); fs.writeFileSync(out + '/gp_in.bin', r);
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 1000 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', out + '/gp_in.bin'); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="emu"]'); await p.locator('#appsList .prow .ptog').first().click(); await p.waitForTimeout(400);
const inp = p.locator('.pdet input[type=number]').first();
ok((await inp.inputValue()) === '500', 'shows 500');
await inp.fill('123456'); await inp.dispatchEvent('change'); await p.waitForTimeout(400);
const dl = p.waitForEvent('download'); await p.click('#btnSave'); const d = await dl; await d.saveAs(out + '/gp_out.bin');
const o = new Uint8Array(fs.readFileSync(out + '/gp_out.bin')), s = SV.t7SaveOut(o);
ok(s && [...s.subarray(0x32, 0x37)].join() === [0x56, 0x34, 0x12, 0, 0].join(), 'EEPROM holds 123456 (BCD)');
ok(o.subarray(0xC0000, 0xC0010).every((v) => v === 0xFF), 'running state dropped');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close(); console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+26
View File
@@ -0,0 +1,26 @@
// 1.6.11 test2: an old T7Emu (save written 2 bytes off) is named in red; after saving with this Studio the note is gone.
// node test/ui_t7old_test.js <ROM with an old T7Emu> <ROM with a current T7Emu> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
(async () => {
const [oldr, newr, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
const warn = () => p.evaluate(() => [...document.querySelectorAll('#plan .rule.warn')].map((x) => x.textContent).join(' | '));
await p.setInputFiles('#fileRom', newr); await p.waitForSelector('#work.on', { timeout: 60000 }); await p.waitForTimeout(2000);
ok(!/veraltete Version/.test(await warn()), 'current T7Emu: no note');
await p.setInputFiles('#fileRom', oldr); await p.waitForTimeout(3000);
const w = await warn(); ok(/TAMA-GO: veraltete Version/.test(w), 'old T7Emu named: ' + w);
const dlp = p.waitForEvent('download', { timeout: 300000 }); await p.click('#btnSave');
const dl = await dlp; const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(3000);
ok(!/veraltete Version/.test(await warn()), 'written anew: note gone');
ok(!errors.length, 'no page errors ' + errors.join('; '));
fs.unlinkSync(r1);
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+51
View File
@@ -0,0 +1,51 @@
// UI in a real browser: load ROM, get sheet, upload sheet, insert card character, save.
// Usage: node test/ui_test.js <rom> <card> <output_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
(async () => {
const [rom, dim, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 860 }, acceptDownloads: true });
const errors = []; page.on('pageerror', e => errors.push(e.message)); page.on('console', m => { if (m.type() === 'error') errors.push(m.text()); });
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.screenshot({ path: out + '/1_start.png' });
await page.setInputFiles('#fileRom', rom);
await page.waitForSelector('#work.on', { timeout: 60000 });
await page.waitForTimeout(1500);
await page.screenshot({ path: out + '/2_figuren.png' });
// open baby figure 237 (or first after egg)
await page.click('.tile[data-kind="fig"][data-idx="237"]');
await page.waitForTimeout(500);
await page.screenshot({ path: out + '/3_drawer.png' });
const [dl] = await Promise.all([page.waitForEvent('download'), page.click('#dDown')]);
const sheet = out + '/' + dl.suggestedFilename(); await dl.saveAs(sheet);
await page.click('#dClose');
// card tab
await page.click('.tab[data-tab="dim"]');
await page.setInputFiles('#fileDim', dim);
await page.waitForTimeout(800);
await page.screenshot({ path: out + '/4_dim.png' });
// insert card character into the default target, and egg
await page.selectOption('#dimArea select >> nth=0', process.env.DIGI || '2');
if (process.env.ZIEL) await page.selectOption('#dimArea select >> nth=1', process.env.ZIEL);
await page.click('#dimArea .btn.primary');
await page.click('#dimArea .btn:not(.primary)');
await page.waitForTimeout(500);
// all sprites tab view
await page.click('.tab[data-tab="all"]');
await page.waitForTimeout(800);
await page.screenshot({ path: out + '/5_alle.png' });
await page.click('.tab[data-tab="figs"]');
await page.click('.tile[data-kind="fig"][data-idx="' + (process.env.ZIEL || '243') + '"]');
await page.waitForTimeout(400);
await page.screenshot({ path: out + '/6_drawer_kartenfigur.png' });
await page.click('#dClose');
const [dl2] = await Promise.all([page.waitForEvent('download', { timeout: 120000 }), page.click('#btnSave')]);
const romOut = out + '/' + dl2.suggestedFilename(); await dl2.saveAs(romOut);
await page.waitForTimeout(300);
await page.screenshot({ path: out + '/7_saved.png' });
const info = await page.evaluate(() => ({ changed: window.__paramix.changed.size, info: document.getElementById('info').innerText, toast: document.getElementById('toast').innerText }));
console.log(JSON.stringify(info), 'sheet', sheet, 'rom', romOut, 'errors', errors);
await browser.close();
})();
+46
View File
@@ -0,0 +1,46 @@
// Sheet round trip in the browser: get sheet, upload it unchanged (no change),
// upload it edited (change), load Glacier.
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
(async () => {
const [rom, rom2, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 860 }, acceptDownloads: true, locale: 'de-CH' });
const errors = []; page.on('pageerror', e => errors.push(e.message));
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.setInputFiles('#fileRom', rom); await page.waitForSelector('#work.on');
await page.click('.tile[data-kind="fig"][data-idx="243"]');
const [dl] = await Promise.all([page.waitForEvent('download'), page.click('#dDown')]);
const sheet = out + '/figur_0243.png'; await dl.saveAs(sheet);
await page.setInputFiles('#fileOne', sheet); await page.waitForTimeout(800);
const c1 = await page.evaluate(() => window.__paramix.changed.size);
// edit: color the body row red (all opaque pixels of the first 64 rows)
const edited = await page.evaluate(async () => {
const img = document.getElementById('dCanvas');
const r = await fetch(document.querySelector('#dCanvas').toDataURL()); void r;
return true;
});
void edited;
const b64 = fs.readFileSync(sheet).toString('base64');
const editedPath = out + '/figur_0243_rot.png';
const data = await page.evaluate(async (b64) => {
const im = new Image(); im.src = 'data:image/png;base64,' + b64; await im.decode();
const cv = document.createElement('canvas'); cv.width = im.width; cv.height = im.height;
const g = cv.getContext('2d'); g.drawImage(im, 0, 0);
const d = g.getImageData(0, 0, cv.width, 64);
for (let i = 0; i < d.data.length; i += 4) if (d.data[i + 3] > 128 && d.data[i] + d.data[i + 1] + d.data[i + 2] > 200) { d.data[i] = 230; d.data[i + 1] = 40; d.data[i + 2] = 60; }
g.putImageData(d, 0, 0);
return cv.toDataURL('image/png').split(',')[1];
}, b64);
fs.writeFileSync(editedPath, Buffer.from(data, 'base64'));
await page.setInputFiles('#fileOne', editedPath); await page.waitForTimeout(1200);
const c2 = await page.evaluate(() => [...window.__paramix.changed.keys()]);
await page.screenshot({ path: out + '/rot.png' });
await page.click('#dClose');
await page.setInputFiles('#fileRom', rom2); await page.waitForSelector('#work.on'); await page.waitForTimeout(1500);
const info = await page.evaluate(() => document.getElementById('info').innerText.replace(/\n/g, ' | '));
await page.screenshot({ path: out + '/glacier.png' });
console.log('unveraendert hochgeladen -> Aenderungen:', c1, '| bearbeitet -> geaendert:', c2, '|', info, '| Fehler', errors);
await browser.close();
})();
+47
View File
@@ -0,0 +1,47 @@
// 1.6.9: Connection V3 ROM in the Emulator tab: V3Emu as the main program, a P2 (V1Emu) in the menu; read back.
// node test/ui_v3_test.js <paradise.bin> <v3 rom> <p2.bin> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, v3, p2, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) }, v3app = fs.readFileSync(__dirname + '/../v3/v3.bin'), v1app = fs.readFileSync(__dirname + '/../v1/v1.bin');
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]'); await p.click('#launchOn'); await p.waitForTimeout(1500); // the menu, for the P2
await p.click('.tab[data-tab="emu"]');
await p.setInputFiles('#fileEmu', v3); await p.waitForTimeout(800);
const stat = await p.evaluate(() => document.getElementById('emuStat') ? document.getElementById('emuStat').innerText : document.body.innerText);
ok(/Connection V3 erkannt/.test(stat) && /Rad kurz: Einstellungen/.test(stat) && !/schütteln/.test(stat), 'status text for the V3');
await p.setInputFiles('#fileApp', p2); await p.waitForTimeout(500);
const rows = async () => p.evaluate(() => [...document.querySelectorAll('#appsList .prow')].map((r) => r.querySelector('.pname').textContent + '|' + (r.querySelector('.pstar.on') ? 'main' : '')));
let l = await rows(); console.log('Liste:', l);
ok(l.includes('TAMA V3|main') && l.some((x) => x.startsWith('TAMA P2|')), 'TAMA V3 main, P2 in the list');
// 1.6.9 test20: start when switched on (main program)
await p.evaluate(() => { const r = [...document.querySelectorAll('#appsList .prow')].find((x) => x.querySelector('.pname').textContent === 'TAMA V3'); const k = r && r.querySelector('.ptog'); if (k) k.click(); });
await p.waitForTimeout(300);
ok(await p.evaluate(() => { const c = [...document.querySelectorAll('#appsList .pdet label.check')].find((x) => /Einschalten/.test(x.textContent)); if (!c) return false; if (!c.querySelector('input').checked) c.querySelector('input').click(); return true; }), 'autostart box at TAMA V3');
ok(await p.evaluate(() => [...document.querySelectorAll('#appsList .pdet label.check')].some((x) => /Uhr/.test(x.textContent))), 'clock box at TAMA V3');
ok(await p.evaluate(() => /an beiden V3Emu starten/.test(document.getElementById('appsList').innerText)), 'link hint at TAMA V3');
const dlp = p.waitForEvent('download', { timeout: 300000 }); await p.click('#btnSave');
const dl = await dlp; const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1));
{ const fa = F.feldApps(img, fe.stub); ok(fa.v9 ? !!fa.auto && fa.mainSrc === 0 : true, 'menu: autostart of the main program (v9 ' + fa.v9 + ', auto ' + fa.auto + ')'); }
ok((img[0xA0154] & 10) === 10, 'clock flags in the settings block (' + img[0xA0154] + ')');
ok(Buffer.from(img.subarray(0xA0300, 0xA0000 + v3app.length)).equals(v3app.subarray(0x300)), 'V3Emu at 0x0A0000');
const m = E.v1FromRom(img); ok(m && m.length === 0x80000 && Buffer.from(m).equals(fs.readFileSync(v3)), 'the V3 ROM as the main program');
const xs = E.appsRead(img, F.feldApps(img, fe.stub).apps), x = xs.find((y) => y.kind === 'v1' && y.rom.length !== 0x80000);
ok(x && x.rom.length !== 0x80000 && Buffer.from(img.subarray(x.off + 0x300, x.off + 0x1300)).equals(v1app.subarray(0x300, 0x1300)), 'P2 in the menu with V1Emu');
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(3000);
await p.click('.tab[data-tab="emu"]');
l = await rows(); console.log('Liste neu:', l);
ok(l.includes('TAMA V3|main'), 'read back: TAMA V3 main');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+82
View File
@@ -0,0 +1,82 @@
// Device panel: "Simulate a visit" in the browser against a scripted Paradise (random data).
// node test/ui_visit_test.js <out-dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const V = require('../src/visit.js');
const enc = (s) => new TextEncoder().encode(s);
(async () => {
const out = process.argv[2] || '/tmp/uivisit'; fs.mkdirSync(out, { recursive: true });
const key = V.parseKey(require('../src/flash.js').linkKey);
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 1000 } });
const errors = []; page.on('pageerror', (e) => errors.push(e.message));
// the scripted Paradise: what the Studio writes lands here
let rx = new Uint8Array(0), want = 0; const lines = [], bins = [];
const drain = () => {
for (;;) {
if (want) { if (rx.length < want) return; bins.push(rx.slice(0, want)); rx = rx.slice(want); want = 0; continue; }
let j = -1; for (let i = 0; i + 1 < rx.length; i++) if (rx[i] === 13 && rx[i + 1] === 10) { j = i; break; }
if (j < 0) return; lines.push(new TextDecoder().decode(rx.subarray(0, j))); rx = rx.slice(j + 2);
}
};
await page.exposeFunction('__tx', (a) => { const b = new Uint8Array(rx.length + a.length); b.set(rx); b.set(a, rx.length); rx = b; drain(); });
await page.addInitScript(() => {
const q = [], waiting = [];
window.__rx = (a) => { const v = new Uint8Array(a); if (waiting.length) waiting.shift()({ value: v, done: false }); else q.push(v); };
const port = { open: async () => {}, close: async () => {},
writable: { getWriter: () => ({ write: (d) => window.__tx(Array.from(d)), releaseLock() {} }) },
readable: { getReader: () => ({ read: () => q.length ? Promise.resolve({ value: q.shift(), done: false }) : new Promise((r) => waiting.push(r)), cancel: async () => { waiting.forEach((r) => r({ done: true })); }, releaseLock() {} }) } };
Object.defineProperty(navigator, 'serial', { value: { requestPort: async () => port } });
});
const send = (b) => page.evaluate((a) => window.__rx(a), Array.from(b));
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function expect(s) { for (let i = 0; i < 600; i++) { const k = lines.indexOf(s); if (k >= 0) { lines.splice(k, 1); return; } await sleep(10); } throw new Error('missing ' + s + ' | ' + lines.join(',')); }
const sid = 0x12345678;
async function chunk(type, idx, data) {
const p = new Uint8Array(12 + data.length);
p[0] = 0x78; p[1] = 0x56; p[2] = 0x34; p[3] = 0x12; p[4] = 0x54; p[5] = 0x43; p[6] = 0x50; p[7] = type; p[8] = idx; p[9] = 255 - idx;
const c = V.crc16(data); p[10] = c & 255; p[11] = c >> 8; p.set(data, 12);
const n = new Uint8Array([1, 2, 3, idx]), e = await V.crypt(n, key, p), all = new Uint8Array(4 + e.length); all.set(n); all.set(e, 4); return all;
}
async function packet(type, data) {
await send(enc('PKT ' + data.length + '\r\n')); await expect('ACK');
for (let i = 0; i * 0x1000 < data.length; i++) { await send(await chunk(type, i, data.subarray(i * 0x1000, (i + 1) * 0x1000))); await expect('ACK'); }
}
let ok = true; const fail = (m) => { ok = false; console.log('FAIL', m); };
await page.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await page.click('[data-lang="de"]').catch(() => {});
await page.click('#btnDevice');
if ((await page.$$eval('#visEd option', (o) => o.length)) !== 6) fail('six editions');
await page.selectOption('#visEd', 'glacier');
await page.click('#btnVis');
await page.waitForFunction(() => /Glacier/.test(document.getElementById('visStat').textContent));
if ((await page.textContent('#btnVis')) !== 'Beenden') fail('button Beenden');
await page.screenshot({ path: out + '/visit_1.png' });
await packet(0x11, new Uint8Array([9, 9]));
const mine = new Uint8Array(0x20014); for (let i = 0; i < mine.length; i++) mine[i] = (i * 13) & 255;
await packet(0x01, mine);
await expect('PKT 131092');
let off = 0; const got = new Uint8Array(0x20014);
want = 16 + 0x1000; await send(enc('ACK\r\n'));
for (let i = 0; i < 33; i++) {
for (let k = 0; k < 600 && !bins.length; k++) await sleep(10);
const c = bins.shift(); if (!c) { fail('chunk ' + i); break; }
const p = await V.crypt(c.subarray(0, 4), key, c.subarray(4));
if (V.crc16(p.subarray(12)) !== (p[10] | p[11] << 8)) fail('crc ' + i);
got.set(p.subarray(12), off); off += p.length - 12;
const left = 0x20014 - off; want = left ? 16 + Math.min(0x1000, left) : 0;
await send(enc('ACK\r\n'));
}
if (got[0x20002] !== 6) fail('rom_type Glacier ' + got[0x20002]);
await page.waitForFunction(() => /spielen/.test(document.getElementById('visStat').textContent));
await packet(0x01, new Uint8Array([2, 0]));
await packet(0x01, new Uint8Array([0, 0, 0, 0]));
await page.waitForFunction(() => /fertig/.test(document.getElementById('visStat').textContent));
await page.screenshot({ path: out + '/visit_2.png' });
await page.click('#btnVis');
if ((await page.textContent('#btnVis')) !== 'Starten') fail('button Starten after stop');
if (errors.length) fail('page errors ' + errors.join(' | '));
await browser.close();
console.log(ok ? 'all good' : 'FAIL');
process.exit(ok ? 0 : 1);
})().catch((e) => { console.log('FAIL', e.message); process.exit(1); });
+57
View File
@@ -0,0 +1,57 @@
// 1.6.10 test1: tab Wolf3D: the user's game files into the menu, keys changed, saved, read back; the program and its
// settings block at their place. node test/ui_wolf_test.js <paradise.bin> <folder with .WL1 or .WL6 (full version first)> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js'), W = require('../src/wolf.js');
(async () => {
const [rom, dir, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) }, wapp = fs.readFileSync(__dirname + '/../wolf/wolf.bin');
const all = fs.readdirSync(dir), full = all.some((n) => /\.WL6$/i.test(n));
const names = all.filter((n) => (full ? /\.WL6$/i : /\.WL1$/i).test(n)).map((n) => path.join(dir, n));
const set = {}; for (const n of names) set[path.basename(n)] = new Uint8Array(fs.readFileSync(n));
const want = W.build(set).pack;
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]'); await p.click('#bagOn'); await p.waitForTimeout(800);
await p.click('.tab[data-tab="wolf"]');
ok(await p.evaluate(() => !document.getElementById('pane-wolf').hidden), 'tab Wolf3D shown');
ok(/Noch keine/.test(await p.evaluate(() => document.getElementById('wolfList').innerText)), 'empty at first');
// only some files: the missing ones are named
await p.setInputFiles('#fileWolf', names.filter((n) => !/VGADICT/i.test(n))); await p.waitForTimeout(800);
ok(/VGADICT/.test(await p.evaluate(() => document.getElementById('toast').textContent)), 'missing file named');
await p.setInputFiles('#fileWolf', names); await p.waitForTimeout(4000);
const txt = await p.evaluate(() => document.getElementById('wolfList').innerText);
ok(/WOLFENSTEIN 3D/.test(txt) && (full ? /Vollversion/.test(txt) && /6 Episoden/.test(txt) : /Shareware/.test(txt) && /1 Episode/.test(txt)), 'listed: ' + txt.replace(/\s+/g, ' '));
{ const plan = await p.evaluate(() => document.getElementById('plan').innerText);
ok(/Wolfenstein 3D\s*(neu|NEU)/i.test(plan) && /Wolfenstein 3D\s+[0-9.]+ MB/.test(plan), 'own chip and own part of the flash bar: ' + plan.replace(/\s+/g, ' ').slice(0, 300)); }
await p.selectOption('#wkTurn', '20'); await p.selectOption('#wkFire', '2'); await p.selectOption('#wkFwd', '1');
await p.waitForTimeout(200);
const dlp = p.waitForEvent('download', { timeout: 180000 }); await p.click('#btnSave');
const dl = await dlp; const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1));
const xs = E.appsRead(img, F.feldApps(img, fe.stub).apps), x = xs.find((y) => y.kind === 'wolf');
ok(!!x && Buffer.from(x.pack).equals(Buffer.from(want)), 'the pack in the menu, as built from the files');
ok(x && x.keys.turn === 20 && x.keys.fire === 2 && x.keys.fwd === 1 && x.keys.back === 4 && x.keys.use === 8, 'keys in the settings block');
const c = x ? x.off + 0x140 : 0;
ok(x && Buffer.from(img.subarray(x.off + 0x300, x.off + wapp.length)).equals(wapp.subarray(0x300)), 'program (both parts) in place');
ok(x && E.u32 === undefined && (img[c + 48] | img[c + 49] << 8 | img[c + 50] << 16 | img[c + 51] << 24) === x.off, 'program knows its place');
ok(x && x.saveOff === x.off + 0x20000 && img.subarray(x.saveOff, x.saveOff + 0x10000).every((v) => v === 0xFF), 'empty save area behind the program');
fs.writeFileSync(out + '/wolf_off.txt', String(x ? x.off : 0));
// read back into the Studio: listed again, keys back
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(3000);
await p.click('.tab[data-tab="wolf"]');
ok(/WOLFENSTEIN 3D/.test(await p.evaluate(() => document.getElementById('wolfList').innerText)), 'read back: listed');
ok(await p.evaluate(() => document.getElementById('wkTurn').value === '20' && document.getElementById('wkFire').value === '2'), 'read back: keys');
await p.click('.tab[data-tab="emu"]'); await p.waitForTimeout(300);
ok(await p.evaluate(() => [...document.querySelectorAll('#appsList .pname')].some((n) => /WOLFENSTEIN/.test(n.textContent))), 'in the list of programs');
await p.click('.tab[data-tab="wolf"]');
await p.screenshot({ path: out + '/wolf_tab.png', fullPage: false });
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+55
View File
@@ -0,0 +1,55 @@
// 1.6.11 test2: Spear of Destiny next to Wolfenstein 3D: both in the menu, each with its program; a new SOD replaces only
// the SOD. node test/ui_wolfsod_test.js <paradise.bin> <folder .WL6> <folder .SOD> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js'), W = require('../src/wolf.js');
(async () => {
const [rom, d6, ds, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
const wapp = fs.readFileSync(__dirname + '/../wolf/wolf.bin'), sapp = fs.readFileSync(__dirname + '/../wolf/wolfsod.bin');
const files = (d, re) => fs.readdirSync(d).filter((n) => re.test(n)).map((n) => path.join(d, n));
const n6 = files(d6, /\.WL6$/i), ns = files(ds, /\.SOD$/i);
const pk = (ns_) => { const s = {}; for (const n of ns_) s[path.basename(n)] = new Uint8Array(fs.readFileSync(n)); return W.build(s); };
const want6 = pk(n6).pack, wants = pk(ns).pack;
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
ok(pk(ns).sod && pk(ns).maps === 21 && pk(ns).episodes === 1 && (wants[8] & 2), 'SOD pack: 21 floors, one episode, flag');
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]'); await p.click('#bagOn'); await p.waitForTimeout(800);
await p.click('.tab[data-tab="wolf"]');
await p.setInputFiles('#fileWolf', n6); await p.waitForTimeout(4000);
await p.setInputFiles('#fileWolf', ns); await p.waitForTimeout(5000);
let txt = await p.evaluate(() => document.getElementById('wolfList').innerText);
ok(/WOLFENSTEIN 3D/.test(txt) && /SPEAR OF DESTINY\s+21 Level/.test(txt), 'both listed: ' + txt.replace(/\s+/g, ' '));
{ const plan = await p.evaluate(() => document.getElementById('plan').innerText); ok(/Spear of Destiny/.test(plan), 'plan names SOD'); }
// the SOD again: replaces only the SOD
await p.setInputFiles('#fileWolf', ns); await p.waitForTimeout(5000);
txt = await p.evaluate(() => document.getElementById('wolfList').innerText);
ok((txt.match(/SPEAR OF DESTINY/g) || []).length === 1 && /WOLFENSTEIN 3D/.test(txt), 'a new SOD replaces only the SOD');
await p.selectOption('#wkTurn', '20'); await p.waitForTimeout(200);
const dlp = p.waitForEvent('download', { timeout: 240000 }); await p.click('#btnSave');
const dl = await dlp; const r1 = out + '/' + dl.suggestedFilename(); await dl.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1));
const xs = E.appsRead(img, F.feldApps(img, fe.stub).apps).filter((y) => y.kind === 'wolf');
const x6 = xs.find((y) => !E.wolfSod(y.pack)), xs_ = xs.find((y) => E.wolfSod(y.pack));
ok(xs.length === 2 && x6 && xs_, 'two in the menu');
ok(x6 && Buffer.from(x6.pack).equals(Buffer.from(want6)) && xs_ && Buffer.from(xs_.pack).equals(Buffer.from(wants)), 'packs as built');
ok(x6 && Buffer.from(img.subarray(x6.off + 0x300, x6.off + wapp.length)).equals(wapp.subarray(0x300)), 'Wolf3D program');
ok(xs_ && Buffer.from(img.subarray(xs_.off + 0x300, xs_.off + sapp.length)).equals(sapp.subarray(0x300)), 'SOD program');
ok(xs_ && Buffer.from(img.subarray(xs_.off + 0x140 + 24, xs_.off + 0x140 + 40)).toString().startsWith('SPEAR OF DESTINY'), 'SOD name in its settings block');
ok(xs.every((y) => y.keys.turn === 20), 'keys for both');
const names = F.feldApps(img, fe.stub).apps.map((a) => a.name);
ok(names.some((n) => /WOLF3D SPEAR/.test(n)) && names.some((n) => /WOLFENSTEIN/.test(n)), 'menu names: ' + names.join(', '));
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(3000);
await p.click('.tab[data-tab="wolf"]');
txt = await p.evaluate(() => document.getElementById('wolfList').innerText);
ok(/WOLFENSTEIN 3D/.test(txt) && /SPEAR OF DESTINY/.test(txt), 'read back: both listed');
await p.screenshot({ path: out + '/wolfsod_tab.png', fullPage: false });
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close();
console.log(bad ? 'FAIL ' + bad : 'all good');
})();
+58
View File
@@ -0,0 +1,58 @@
// 1.6.8: figures and download items for the programs in the menu (start device)
// node test/ui_xitems_test.js <paradise.bin> <friends.bin> <tama-go.bin> <fig.bin> <idl.bin> <item.jpg> <out_dir>
const { chromium } = require('playwright');
const fs = require('fs'), path = require('path');
const E = require('../src/emu.js'), F = require('../src/feld.js');
(async () => {
const [rom, fr, go, fig, idl, jpg, out] = process.argv.slice(2);
fs.mkdirSync(out, { recursive: true });
const fe = { stub: new Uint8Array(fs.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 1280, height: 900 }, acceptDownloads: true });
const errors = []; p.on('pageerror', (e) => errors.push(e.message));
await p.addInitScript(() => { try { localStorage.setItem('paramix-lang', 'de'); } catch (e) {} });
await p.goto('file://' + path.resolve(__dirname, '../dist/ParamixStudio.html'));
await p.setInputFiles('#fileRom', rom); await p.waitForSelector('#work.on', { timeout: 60000 });
await p.click('.tab[data-tab="feld"]'); await p.click('#launchOn'); await p.waitForTimeout(1500);
await p.click('.tab[data-tab="emu"]');
await p.setInputFiles('#fileEmu', fr); await p.waitForTimeout(300);
await p.setInputFiles('#fileEmu', go); await p.waitForTimeout(300);
await p.setInputFiles('#fileEmu', idl); await p.waitForTimeout(800);
const rows = p.locator('#appsList .prow');
ok(await rows.count() === 3, 'three rows: ' + (await p.textContent('#appsList')));
// figures on the Tama-Go row
const fcs = p.waitForEvent('filechooser'); await rows.nth(1).locator('button', { hasText: 'Figuren' }).click(); (await fcs).setFiles(fig); await p.waitForTimeout(500);
ok(/Figuren hinzufügen \(1\)/.test(await rows.nth(1).textContent()), 'Tama-Go row: one figure');
// download item on the iD L row
const fcd = p.waitForEvent('filechooser'); await rows.nth(2).locator('button', { hasText: 'Download' }).click(); (await fcd).setFiles(jpg); await p.waitForTimeout(800);
await rows.nth(2).locator('.ptog').click(); await p.waitForTimeout(300);
const dl = await p.textContent('.pdet');
ok( /1\/|せつぶん/.test(dl), 'item listed for the iD L: ' + dl.slice(0, 80));
// clock per program: off for the iD L only
await p.locator('.pdet input[type=checkbox]').first().uncheck(); await p.waitForTimeout(300);
const plan = await p.textContent('#plan');
ok(/Emulatoren FRIENDS, TAMA-GO, ID L/.test(plan) && (await p.$eval('#plan strong', (e) => e.textContent)) === 'FRIENDS', 'plan: one chip, main in bold: ' + plan.slice(0, 120));
const [d1] = await Promise.all([p.waitForEvent('download', { timeout: 180000 }), p.click('#btnSave')]);
const r1 = out + '/xitems.bin'; await d1.saveAs(r1);
const img = new Uint8Array(fs.readFileSync(r1)), xs = E.appsRead(img, F.feldApps(img, fe.stub).apps);
const tg = xs.find((x) => !x.kind), ti = xs.find((x) => x.kind === 'tama');
ok(tg && tg.figs.length === 1, 'saved: Tama-Go with ' + (tg && tg.figs.length) + ' figure');
ok(ti && E.dlcStores(ti.guest).some((k) => k.slots.some((y) => y.name)), 'saved: iD L with the item');
ok(ti && ti.clock === false && tg.clock === true, 'clock per program: iD L off, Tama-Go on');
await p.setInputFiles('#fileRom', r1); await p.waitForTimeout(2500);
await p.click('.tab[data-tab="emu"]');
ok(/Figuren hinzufügen \(1\)/.test(await p.textContent('#appsList')), 'loaded again: figure count shown');
// language twice: the list stays (1.6.8 test25 lost it)
await p.click('[data-lang="en"]'); await p.waitForTimeout(300); await p.click('[data-lang="de"]'); await p.waitForTimeout(300);
ok(await p.locator('#appsList .prow').count() === 3, 'language switched twice: still three rows');
// another main program with ★
const stars = await p.$$eval('#appsList .prow .pstar', (l) => l.map((e) => e.textContent + (e.disabled ? '-' : '+')));
ok(stars.join(' ') === '★- ☆+ ☆+', 'stars: filled for the main one, empty for the others: ' + stars.join(' '));
await p.locator('#appsList .prow').nth(1).locator('button.pstar').click(); await p.waitForTimeout(1500);
const first = await p.locator('#appsList .prow .pname').first().textContent();
ok(first === 'TAMA-GO' && (await p.$eval('#plan strong', (e) => e.textContent)) === 'TAMA-GO', '★: TAMA-GO is the main program now (' + first + ')');
ok(await p.locator('#appsList .prow').count() === 3, '★: still three programs');
ok((await p.$$eval('#appsList .prow .pstar', (l) => l.map((e) => e.textContent).join(''))) === '★☆☆', 'stars after the swap');
ok(!errors.length, 'no page errors ' + errors.join('; '));
await b.close(); console.log(bad ? bad + ' FAILED' : 'all good'); process.exit(bad ? 1 : 0);
})();
+343
View File
@@ -0,0 +1,343 @@
// Self test without a real image (runs on GitHub, where no ROMs may be stored).
// Builds a synthetic Paradise image and checks archive, sprites, eye rule,
// character palette, sheets and ZIP. Usage: node test/unit_test.js
const C = require('../src/core.js');
const zlib = require('zlib');
let fails = 0;
const ok = (cond, msg) => { console.log((cond ? 'ok ' : 'FAIL ') + msg); if (!cond) fails++; };
const img = (w, h, fn) => { const d = new Uint8ClampedArray(w * h * 4); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) d.set(fn(x, y), (y * w + x) * 4); return { w, h, data: d }; };
// a fake "original" sprite in the character format: 4 bpp, palette, transparency
function fakeSprite(w, h, n, seed) {
const head = new Uint8Array(24); head[5] = 2; head[6] = n; head[8] = w; head[9] = h; head[12] = 1; head[13] = 1; head[14] = 0x11; head[15] = 1; head[4] = 0xa7;
const tmpl = new Uint8Array([...head]);
const subs = []; for (let i = 0; i < n; i++) subs.push(img(w, h, (x, y) => ((x + y + i + seed) % 7 === 0) ? [0, 0, 0, 0] : [(x * 9 + seed * 40) & 255, (y * 7) & 255, (i * 30) & 255, 255]));
// encode through the generic path using a minimal original
const orig = new Uint8Array(24 + 32 + 8 * n); orig.set(tmpl); orig[18] = 24; orig[20] = 56;
return C.spriteEncode(orig, subs, {});
}
// 1) archive + pack
const parts = [];
for (let i = 0; i < 6; i++) parts.push(fakeSprite(16, 16, 2, i));
const shapes = [[64, 64, 20], [64, 32, 20], [64, 32, 18], [32, 32, 24], [32, 16, 14], [32, 16, 14]];
const group = shapes.map(([w, h, n], k) => fakeSprite(w, h, n, 10 + k));
const egg = [fakeSprite(32, 32, 5, 1), fakeSprite(16, 16, 1, 2), fakeSprite(16, 16, 1, 3), fakeSprite(64, 64, 5, 4), fakeSprite(16, 16, 1, 5), fakeSprite(16, 16, 1, 6)];
const entries = [...parts, ...egg, ...group];
const pack = C.packJoin(entries);
ok(C.packSplit(pack).every((e, i) => e.length >= entries[i].length), 'pack split/join');
const root = C.arc2Build([new Uint8Array(64).fill(7), pack, C.arc2Build([new Uint8Array(10)])]);
const rom = new Uint8Array(0x1000000).fill(0xff);
rom.set([...'SONIXDEV'].map(c => c.charCodeAt(0)), 0);
rom.set(root, C.ASSET_BASE);
const verPage = (C.ASSET_BASE + root.length + 0x200000) & ~0xfff;
rom.set([1, 0, 0, 0], verPage);
const ctx = C.openRom(rom);
ok(ctx.edition === 'Land', 'edition from version page');
ok(ctx.limit === verPage, 'free space ends at version page');
ok(ctx.groups.length === 1 && ctx.groups[0] === 12, 'character group found');
ok(ctx.egg === 6, 'egg found');
const same = C.buildRom(ctx, new Map());
ok(Buffer.compare(Buffer.from(same.rom), Buffer.from(rom)) === 0, 'rebuild without changes is byte identical');
// 2) roundtrip of every sprite
let rt = true;
for (const e of ctx.entries) { const d = C.spriteDecode(e); const d2 = C.spriteDecode(C.spriteEncode(e, d.subs, {})); rt = rt && d2.subs.every((s, k) => C.sameImage(s, d.subs[k])); }
ok(rt, 'decode/encode roundtrip is pixel exact');
// 3) character rules
const g = ctx.groups[0];
const red = img(64, 64, (x, y) => (x > 10 && x < 50 && y > 10) ? [250, 30, 40, 255] : (x === 10 ? [0, 0, 0, 255] : [0, 0, 0, 0]));
const body = C.spriteEncode(ctx.entries[g], Array(20).fill(red), C.partOptions(0));
const h = C.spriteHeader(body), dec = C.spriteDecode(body);
const used = new Set(); dec.cells.forEach(c => c.forEach(v => used.add(v)));
ok(![2, 3, 4, 5, 6, 7].some(v => used.has(v)), 'new colours avoid the recoloured slots 2-7');
ok(used.has(1) && dec.palettes[0][1] === 0x000c, 'outline on slot 1 = 0x000C');
ok(dec.palettes[0][0] === 0x07e0 && h.bpp === 2, 'slot 0 colour key, 4 bpp');
const eyesOrig = ctx.entries[g + 1];
const eyesBlank = C.spriteBlank(eyesOrig, C.partOptions(1));
ok(eyesBlank.length === eyesOrig.length && C.spriteHeader(eyesBlank).dataLength === eyesOrig.length, 'blank eyes keep the original byte length');
let threw = false; try { C.spriteEncode(eyesOrig, Array(20).fill(img(64, 32, (x, y) => [(x * 37 + y * 91) & 255, (x * 13) & 255, (y * 71) & 255, 255])), C.partOptions(1)); } catch (e) { threw = true; }
ok(threw, 'too detailed eyes are rejected');
// 4) sheets
const parts6 = [0, 1, 2, 3, 4, 5].map(k => C.spriteDecode(ctx.entries[g + k]).subs);
const sheet = C.groupSheet(parts6);
ok(sheet.w === 1280 && sheet.h === 192, 'character sheet 1280x192');
ok(C.groupFromSheet(sheet).every((p, k) => p.every((s, i) => C.sameImage(s, parts6[k][i]))), 'character sheet splits back');
const ss = C.sheetFromSubs(parts6[3]);
ok(C.subsFromSheet(ss, 32, 32, 24).every((s, i) => C.sameImage(s, parts6[3][i])), 'sprite sheet splits back');
// 5) changed ROM
const changed = new Map([[g, body], [g + 1, eyesBlank]]);
const out = C.buildRom(ctx, changed);
const ctx2 = C.openRom(out.rom);
ok(C.sameImage(C.spriteDecode(ctx2.entries[g]).subs[0], C.spriteDecode(body).subs[0]), 'changed ROM reads back');
// 6) zip
const z = C.zipBuild([{ name: 'figur_0012.png', data: new Uint8Array([1, 2, 3]) }, { name: 'a/b.txt', data: new TextEncoder().encode('hallo') }]);
C.zipRead(z, async (b) => new Uint8Array(zlib.inflateRawSync(b))).then(files => {
ok(files.length === 2 && files[1].name === 'a/b.txt' && new TextDecoder().decode(files[1].data) === 'hallo', 'zip write/read');
// 7) card pose placement
const ch = { baby: false, frames: { idle1: img(64, 56, () => [200, 100, 50, 255]) } };
const p = C.dimCharParts(ch);
ok(p[0].length === 20 && p[3].length === 24 && p[0][0].w === 64, 'card character parts');
// 8) hide eye layer: body 10 at (5,-20), eye 11 follows; eye moves far away, rest unchanged
const dp = new Uint8Array(new Uint16Array([0, 10, 1027, 5, 65516, 1, 11, 1539, 0, 65520, 15, 12, 1031, 0, 0, 0, 0, 0]).buffer);
const hd = C.hideEyes(dp, 10, 11);
const hw = new Uint16Array(hd.dataPack.buffer.slice(0));
ok(hd.count === 1 && hw[8] === 2005 && hw[9] === ((-2020) & 0xffff) && hw[3] === 5 && hw[13] === 0, 'eye layer hidden');
// 9) DOOM without WAD: read/write WAD, find episodes, converter runs (synthetic mini WAD without game data)
const D = require('../src/doom.js'), fs2 = require('fs');
const mini = D.writeWad([['E2M1', new Uint8Array(0)], ['THINGS', new Uint8Array(10)], ['PLAYPAL', new Uint8Array(768)]], 'IWAD');
const back = D.readWad(mini);
ok(back.length === 3 && back[0][0] === 'E2M1' && back[2][1].length === 768, 'doom wad write/read');
ok(JSON.stringify(D.wadEpisodes(mini)) === '["2"]', 'doom episodes');
return WebAssembly.instantiate(fs2.readFileSync(__dirname + '/../doom/mcuwad.wasm'), {}).then(({ instance }) => {
ok(typeof instance.exports.convert === 'function' && typeof instance.exports.alloc === 'function', 'doom converter loads');
});
}).then(() => {
// 10) field switch on a synthetic ROM (scene table, ID Land)
const E = require('../src/emu.js'), F = require('../src/feld.js'), fs3 = require('fs');
const r = new Uint8Array(0x1000000); r.fill(0xFF);
const put32 = (o, v) => { r[o] = v & 255; r[o + 1] = (v >>> 8) & 255; r[o + 2] = (v >>> 16) & 255; r[o + 3] = (v >>> 24) & 255; };
const xp = (o) => 0x10000000 + o - 0x11000;
['PSID_TEST', 'PSID_HOME', 'PSID_MORE'].forEach((n, k) => { const o = 0x200000 + k * 16; for (let i = 0; i < n.length; i++) r[o + i] = n.charCodeAt(i); r[o + n.length] = 0; put32(0x300004 + k * 28, xp(o)); });
for (let k = 0; k < 3; k++) for (let h = 0; h < 4; h++) put32(0x300000 + k * 28 + 12 + 4 * h, 0x10001001 + k * 0x100 + h * 0x10);
put32(0x111008, 0x1000); put32(0xD49000, 1);
const fe = { feld: new Uint8Array(fs3.readFileSync(__dirname + '/../feld/feld.bin')), stub: new Uint8Array(fs3.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')), oldStub: new Uint8Array(fs3.readFileSync(__dirname + '/../emu/stub_tpl.bin')) };
const a = F.feldApply(r, { fields: true, bag: true }, [], fe, E), fa = F.feldFind(a, fe.stub);
ok(fa && fa.off === 0xB1000 && fa.slotOff === 0x830000 && fa.nslots === 3, 'field switch built in');
const home = E.sceneTable(a).PSID_HOME;
ok(((a[home + 12] | a[home + 13] << 8 | a[home + 14] << 16 | a[home + 15] << 24) >>> 0) === (xp(0xB0040) | 1), 'home screen hooked');
ok(Buffer.compare(Buffer.from(F.feldStrip(a, fe, E)), Buffer.from(r)) === 0, 'field switch removed again');
const g = new Uint8Array(r); g[0xD49000] = 5; let err = ''; try { F.feldApply(g, { fields: true, bag: true }, [], fe, E); } catch (e) { err = e.message; }
ok(F.feldId(g) === 0 && err, 'other editions refused');
}).then(async () => {
// 11) flasher: CRC, frames, write with "only changes" and "keep saves" against a fake device
const FL = require('../src/flash.js'), F = require('../src/feld.js'), E = require('../src/emu.js');
ok(FL.crc32(Buffer.from('123456789')) === 0xCBF43926, 'flash crc32');
const order = FL.sectorOrder();
ok(order.length === 4096 && order[0] === 0x111000 && order[4095] === 0, 'flash sector order');
const pd = FL.buildPdlo(new Uint8Array([1, 2, 3, 4]));
{ const m = ((pd[0] | pd[1] << 8 | pd[2] << 16 | pd[3] << 24) ^ 0x4F4C4450) >>> 0; // the mask, from the known header word
const lv = Buffer.concat([Buffer.from(FL.linkKey, 'latin1'), Buffer.from(pd.subarray(8, 12).map((x, i) => x ^ (m >>> (8 * i) & 255))), Buffer.from(pd.subarray(12, 16).map((x, i) => x ^ (m >>> (8 * i) & 255))), Buffer.from([m & 255, m >>> 8 & 255, m >>> 16 & 255, m >>> 24])]);
ok(pd.length === 0x10010 && require('crypto').createHash('sha256').update(lv).digest('hex') === 'e42c852be360af2b76316a5f02058a90d68db0a946a7b556819c07ec0db23cdb', 'flash PDLO header and link values'); }
// fake device: 16 MB flash, answers PAU1 like the flash app
function fakeDevice(mem) {
const devSide = new FL.Link({ write: async () => {} });
const sec = new Uint8Array(0x1000), io = { onData: null };
io.write = async (d) => {
devSide.feed(d);
for (const f of devSide.frames.splice(0)) {
const p = f.payload, u = (o) => (p[o] | p[o + 1] << 8 | p[o + 2] << 16 | p[o + 3] << 24) >>> 0;
let out = new Uint8Array(0);
if (f.type === 1) { out = new Uint8Array(44); out[8] = mem[0xD49000]; out[10] = 0; out[11] = 16; out.set([0, 0, 0, 1], 32); }
else if (f.type === 5) out = mem.slice(f.off, f.off + u(0));
else if (f.type === 6) { const c = FL.crc32(mem, f.off, u(0)); out = new Uint8Array([c & 255, c >>> 8 & 255, c >>> 16 & 255, c >>> 24]); }
else if (f.type === 13) { out = new Uint8Array(16); out[12] = 1; }
else if (f.type === 9) out = new Uint8Array(4);
else if (f.type === 10) { sec.set(p, f.off & 0xFFF); if (mem.spoil && !--mem.spoil) sec[f.off & 0xFFF] ^= 0x55; } // a packet that arrives wrong
else if (f.type === 11) {
if (mem.precheck && FL.crc32(sec) !== u(0)) { out = new Uint8Array(8); const c = FL.crc32(sec); out.set([c & 255, c >>> 8 & 255, c >>> 16 & 255, c >>> 24, 2]); mem.prechecked = (mem.prechecked || 0) + 1; }
else { mem.set(sec, f.off & ~0xFFF); out = new Uint8Array(8); const c = FL.crc32(sec); out.set([c & 255, c >>> 8 & 255, c >>> 16 & 255, c >>> 24]); } }
setImmediate(() => io.onData(devSide.frame(f.type, f.seq, f.off, out)));
}
};
return io;
}
const mem = new Uint8Array(0x1000000); mem.fill(0xFF);
mem.set(Buffer.from('SONIXDEV')); mem[0xD49000] = 1; mem[0xD49001] = 0; mem[0xD49002] = 0; mem[0xD49003] = 0;
for (let i = 0; i < 0x1000; i++) mem[0xEFE000 + i] = i & 255; // save data on the device
const io = fakeDevice(mem);
const { dev } = await FL.connect(io, new Uint8Array(16), {});
ok(dev.info.edition === 1 && dev.info.capacity === 0x1000000, 'flash hello');
const img = new Uint8Array(mem); img.fill(0, 0xEFE000, 0xEFF000); img[0x200000] = 0x42;
const keep = FL.keepPlan(F, E, null, {});
let r = await dev.write(img, { onlyChanged: true, keep }, null);
ok(r.written === 1 && r.kept === 1 && mem[0x200000] === 0x42 && mem[0xEFE001] === 1, 'flash: only changes, save kept');
r = await dev.write(img, { onlyChanged: true, keep: null }, null);
ok(r.written === 1 && mem[0xEFE001] === 0, 'flash: without keep the save is written');
const other = new Uint8Array(img); other[0xD49000] = 4; let e2 = '';
try { await dev.write(other, { onlyChanged: true, keep }, null); } catch (e) { e2 = e.code || e.message; console.log(' (' + e2 + ')'); }
ok(e2 === 'otherEd', 'flash: other edition refused with keep');
// 1.6.6: same firmware (Land on the device, Water in the ROM): save and the device's ID page stay
const fam = new Uint8Array(img); fam[0xD49000] = 2; fam[0x200001] = 0x43;
r = await dev.write(fam, { onlyChanged: true, keep }, null);
ok(mem[0xD49000] === 1 && mem[0x200001] === 0x43 && (r.notes || []).some((n) => n.code === 'noteEdKept'), 'flash: same family (Land device, Water ROM): device keeps its edition and save');
// 1.6.13 test13: rescue start (second load table at 0xFFE000, the flash app at 0xFF0000), written first
{
const app = new Uint8Array(0x9000).map((_, i) => (i * 7) & 255), hdr = new Uint8Array(mem.subarray(0, 0x1000));
hdr.set([0x13, 0, 0, 0], 8); hdr[0x10] = 0; hdr[0x11] = 0x10; hdr[0x12] = 0; hdr[0x13] = 0x60; hdr.set([0, 0, 0x4F, 0x4B], 0x80);
mem.set(hdr, 0);
const rb = FL.rescueBlock(app, hdr), u = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0, t = rb.subarray(0xE000);
ok(Buffer.from(t.subarray(0, 8)).toString() === 'SONIXDEV' && u(t, 8) === 0x12 && u(t, 0x10) === 0x60FF0000 && u(t, 0x14) === 0xE000 && u(t, 0x24) === FL.crc32(rb, 0, 0xE000) && u(t, 0x80) === 0 && rb[0x9000] === 0xFF, 'rescue: second table points at the flash app, CRC over 0xE000');
const img2 = new Uint8Array(mem); img2[0x200002] = 0x44;
r = await dev.write(img2, { onlyChanged: true, keep: null, rescueApp: app }, null);
ok(r.written === 12 && mem[0x200002] === 0x44 && FL.crc32(mem, 0xFF0000, 0x10000) === FL.crc32(rb) && !r.notes.length, 'rescue: written along with the image');
r = await dev.write(img2, { onlyChanged: true, keep: null, rescueApp: app }, null);
ok(r.written === 0, 'rescue: nothing to write the second time');
{ // test18: an image read from a device with the rescue start of an earlier Studio (other flash app): renewed
const app2 = new Uint8Array(0x9100).map((_, i) => (i * 5 + 1) & 255), rb2 = FL.rescueBlock(app2, hdr), rd = new Uint8Array(mem);
r = await dev.write(rd, { onlyChanged: true, keep: null, rescueApp: app2 }, null);
ok(r.written > 0 && FL.crc32(mem, 0xFF0000, 0x10000) === FL.crc32(rb2), 'rescue: older rescue start in the image is renewed (' + r.written + ')');
r = await dev.write(new Uint8Array(mem), { onlyChanged: true, keep: null, rescueApp: app }, null);
ok(FL.crc32(mem, 0xFF0000, 0x10000) === FL.crc32(rb), 'rescue: and back');
}
const busy = new Uint8Array(img2); busy[0xFF8000] = 1;
const crcB = FL.crc32(mem); let e3 = ''; try { await dev.write(busy, { onlyChanged: true, keep: null, rescueApp: app }, null); } catch (e) { e3 = e.code; }
ok(e3 === 'noRescueRoom' && FL.crc32(mem) === crcB, 'rescue: 0xFF0000 in use, nothing written');
r = await dev.write(busy, { onlyChanged: true, keep: null, rescueApp: app, rescueNeeded: false }, null);
ok(r.notes.some((n) => n.code === 'noRescue') && mem[0xFF8000] === 1, 'rescue: not needed, left out with a note');
mem.set(rb, 0xFF0000);
const kept = await dev.rescueTest(app, null);
ok(mem[0] === 0xFF && Buffer.compare(Buffer.from(kept), Buffer.from(hdr)) === 0, 'rescue test: header cleared and returned');
await dev.rescueRestore(kept, null);
ok(Buffer.from(mem.subarray(0, 8)).toString() === 'SONIXDEV' && FL.crc32(mem, 0, 0x1000) === FL.crc32(hdr), 'rescue test: header written back');
// test15: a T18Emu with its hot window at 0xFF0000 gives the block up; its save (stored map, spares) stays
{
const m3 = new Uint8Array(mem); m3.fill(0xFF, 0xF00000, 0x1000000); m3.fill(0xFF, 0xA0000, 0xB0000);
const c = 0xA0140, put16 = (b, o, v) => { b[o] = v & 255; b[o + 1] = v >> 8; }, put32 = (b, o, v) => { b[o] = v & 255; b[o + 1] = v >>> 8 & 255; b[o + 2] = v >>> 16 & 255; b[o + 3] = v >>> 24; };
put32(m3, c, 0x38584D50); put32(m3, c + 4, 1); put32(m3, c + 8, 0xC0000); put32(m3, c + 12, 3); put32(m3, c + 400, 4);
for (let i = 0; i < 128; i++) put16(m3, c + 16 + 2 * i, 0xFFFF);
put16(m3, c + 16 + 2 * 0x12, 0xFF); put16(m3, c + 16 + 2 * 0x40, 0xF0); put16(m3, c + 16 + 2 * 0x05, 0xF1); put16(m3, c + 16 + 2 * 0x06, 0xE0);
for (let i = 0; i < 64; i++) put16(m3, c + 272 + 2 * i, 0xFFFF);
put16(m3, c + 272, 0xE1); put16(m3, c + 274, 0xE2); put16(m3, c + 276, 0xE3);
m3.fill(0x12, 0xFF0000, 0x1000000); m3.fill(0x40, 0xF00000, 0xF10000); m3.fill(0x05, 0xF10000, 0xF20000); m3.fill(0x06, 0xE00000, 0xE10000);
// stored map on the device: guest 6 written into spare 0 (0xE1)
put32(m3, 0xC0000, 0x504D3854); for (let i = 0; i < 128; i++) put16(m3, 0xC0004 + 2 * i, (m3[c + 16 + 2 * i] | m3[c + 17 + 2 * i] << 8)); put16(m3, 0xC0004 + 2 * 6, 0xE1); m3.fill(0, 0xC0004 + 256, 0xC0004 + 320); m3[0xC0004 + 256] = 1;
m3.fill(0x66, 0xE10000, 0xE20000); m3[0xC1000] = 0x77;
const io3 = fakeDevice(m3), d3 = (await FL.connect(io3, new Uint8Array(16), {})).dev;
const rom3 = new Uint8Array(m3); rom3.fill(0xFF, 0xC0000, 0xE4000); rom3.fill(0xFF, 0xE10000, 0xE20000); // the ROM as the Studio has it: no save
const T18keep = FL.keepPlan(F, E, null, {});
const rr = await d3.write(rom3, { onlyChanged: true, keep: T18keep, rescueApp: app, t18Bases: [0xA0000] }, null);
const g = (i) => m3[c + 16 + 2 * i] | m3[c + 17 + 2 * i] << 8, sm = (i) => m3[0xC0004 + 2 * i] | m3[0xC0005 + 2 * i] << 8;
ok(rr.rescue && FL.crc32(m3, 0xFF0000, 0x10000) === FL.crc32(FL.rescueBlock(app, m3.subarray(0, 0x1000))) && g(0x12) === 0xF0 && g(0x40) === 0xE3 && sm(0x12) === 0xF0 && sm(0x40) === 0xE3 && sm(6) === 0xE1
&& m3[0xF00000] === 0x12 && m3[0xE30000] === 0x40 && m3[0xE10000] === 0x66 && m3[0xC1000] === 0x77 && (m3[c + 12] === 2) && m3[c + 276] === 0xFF, 'rescue: T18Emu block at 0xFF0000 moved, save kept');
const rr2 = await d3.write(rom3, { onlyChanged: true, keep: T18keep, rescueApp: app, t18Bases: [0xA0000] }, null);
ok(rr2.written === 0 && m3[0xE10000] === 0x66, 'rescue: second write with the old ROM changes nothing');
}
// test16: a flash app that checks the buffer first: a spoilt packet means the sector is sent again, nothing wrong written
{ mem.precheck = true; mem.spoil = 3; const img5 = new Uint8Array(mem); img5[0x300000] = 0x99; img5[0x300800] = 0x98;
const r5 = await dev.write(img5, { onlyChanged: true, keep: null, rescueApp: app }, null);
ok(mem.prechecked === 1 && mem[0x300000] === 0x99 && mem[0x300800] === 0x98 && r5.written >= 1, 'flash: buffer checked before erasing, sector sent again');
mem.precheck = false; }
// RESCUE_FIRST: the header is cleared once the rescue start is checked, the rest follows, the header comes back last
const seen = []; const w0 = io.write; io.write = async (d) => { await w0(d); seen.push(mem[0], mem[0x200003]); };
const img3 = new Uint8Array(mem); img3[0x200003] = 0x45;
r = await dev.write(img3, { onlyChanged: true, keep: null, rescueApp: app, rescueFirst: true }, null);
io.write = w0;
let cleared = -1; for (let i = 0; i < seen.length; i += 2) if (seen[i] === 0xFF) { cleared = i; break; }
ok(r.written === 2 && cleared >= 0 && seen[cleared + 1] !== 0x45 && mem[0] === 0x53 && mem[0x200003] === 0x45, 'rescue first: header off before the write, back at the end');
}
// field slots: same layout is kept, another layout gets the stored fields moved over
{
const fs4 = require('fs');
const r = new Uint8Array(0x1000000); r.fill(0xFF); r.set(Buffer.from('SONIXDEV'));
const put32 = (b, o, v) => { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; };
const xp = (o) => 0x10000000 + o - 0x11000;
['PSID_TEST', 'PSID_HOME', 'PSID_MORE'].forEach((n, k) => { const o = 0x200000 + k * 16; for (let i = 0; i < n.length; i++) r[o + i] = n.charCodeAt(i); r[o + n.length] = 0; put32(r, 0x300004 + k * 28, xp(o)); });
for (let k = 0; k < 3; k++) for (let h = 0; h < 4; h++) put32(r, 0x300000 + k * 28 + 12 + 4 * h, 0x10001001 + k * 0x100 + h * 0x10);
put32(r, 0x111008, 0x1000); put32(r, 0xD49000, 1);
const menu = { feld: new Uint8Array(fs4.readFileSync(__dirname + '/../feld/feld.bin')), stub: new Uint8Array(fs4.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
const rom = F.feldApply(r, { fields: true, bag: false }, [], menu, E), fi = F.feldFind(rom, menu.stub);
const m2 = new Uint8Array(rom), slot = fi.slotOff + fi.slotSize; // device: Water stored in slot 2
put32(m2, slot, 0x544C5346); put32(m2, slot + 4, 2); put32(m2, slot + 8, 3); put32(m2, slot + 12, 0x2000); m2.fill(0x77, slot + 0x1000, slot + 0x3000);
const io2 = fakeDevice(m2), d2 = (await FL.connect(io2, new Uint8Array(16), {})).dev;
const k2 = FL.keepPlan(F, E, menu, {});
let q = await d2.write(rom, { onlyChanged: true, keep: k2 }, null);
ok(q.written === 0 && m2[slot + 0x2000] === 0x77, 'flash: stored field kept (same layout)');
// new ROM with the slots somewhere else
const moved = new Uint8Array(rom); let ci = -1;
for (let i = fi.off; i < fi.off + 0x8000; i += 4) if (moved[i] === 0x46 && moved[i + 1] === 0x45 && moved[i + 2] === 0x4C && moved[i + 3] === 0x44) { ci = i; break; }
put32(moved, ci + 8, 0x900000);
q = await d2.write(moved, { onlyChanged: true, keep: k2 }, null);
ok(m2[0x900000 + fi.slotSize + 0x2000] === 0x77 && m2[0x900000 + fi.slotSize + 4] === 2 && q.notes.some((n) => n.code === 'noteMoved'), 'flash: stored field moved to the new layout');
}
}).then(() => {
// 12) TamaEmu download content: route, add, list, remove (synthetic record)
const E = require('../src/emu.js');
const g = new Uint8Array(0x800000); g.fill(0xFF);
const rec = new Uint8Array(0x100); rec.set(Buffer.from('TAMAGO'));
const nm = 'DL_X_cake.jpg'; for (let i = 0; i < nm.length; i++) rec[7 + 2 * i] = nm.charCodeAt(i);
rec[0x4E] = 0x81; rec[0x50] = 0x02; rec[0x51] = 0x01; rec[0x4B] = 0x00; rec[0x4A] = 0x01;
let sum = 0; for (let i = 0; i < 0xFE; i++) sum += rec[i]; rec[0xFE] = sum >> 8 & 255; rec[0xFF] = sum & 255;
const r = E.dlcRecord(rec);
ok(E.dlcRoute(r).label === 'Meals', 'dlc routed to meals');
const a = E.dlcAdd(g, r);
ok(a.slot === 0 && E.dlcStores(a.guest)[0].slots[0].name === 'cake', 'dlc added');
let dup = ''; try { E.dlcAdd(a.guest, r); } catch (e) { dup = e.message; }
ok(dup, 'dlc duplicate refused');
ok(E.dlcStores(E.dlcFree(a.guest, 0, 0))[0].slots[0].name === null, 'dlc removed');
// 1.6.6: P's (reset vector 0x024FDFE6): its own stores
const gp = new Uint8Array(0x800000); gp.fill(0xFF); gp[0x400000] = 0xE6; gp[0x400001] = 0xDF; gp[0x400002] = 0x4F; gp[0x400003] = 0x02;
const rp = E.dlcRecord(rec, 'ps'), ap = E.dlcAdd(gp, rp);
ok(ap.store.base === 0x5A0000 && E.dlcStores(ap.guest).find((k) => k.kind === 0).slots[0].name === 'cake', 'dlc P\'s: meal into its store at 0x5A0000');
const rg = new Uint8Array(rec); rg[0x4E] = 0x94; rg[0x50] = 0x5B; rg[0x51] = 0x01; let sg = 0; for (let i = 0; i < 0xFE; i++) sg += rg[i]; rg[0xFE] = sg >> 8 & 255; rg[0xFF] = sg & 255;
ok(E.dlcRoute(E.dlcRecord(rg, 'ps'), 'ps').base === 0x710000 && E.dlcRoute(rg, '4u').base === 0x710000, 'dlc P\'s and 4U: game store');
}).then(async () => {
{ // 1.6.10 test2: Master System detection and placing (test/sms_test.js)
const r = require('child_process').spawnSync(process.execPath, [__dirname + '/sms_test.js'], { encoding: 'utf8' });
ok(r.status === 0, 'Master System (sms_test.js)' + (r.status ? ': ' + r.stdout.split('\n').filter((l) => l.startsWith('FAIL')).join('; ') : '')); }
// 1.6.10 test1: the Wolf3D pack from made-up files (test/wolf_test.js)
const r = require('child_process').spawnSync(process.execPath, [__dirname + '/wolf_test.js'], { encoding: 'utf8' });
ok(r.status === 0, 'Wolf3D pack (wolf_test.js)' + (r.status ? ': ' + r.stdout.split('\n').filter((l) => l.startsWith('FAIL')).join('; ') : ''));
const E = require('../src/emu.js');
{ // 1.7.1 GB_TRIM: equal end banks once, the whole game back from the image (made-up game)
const g = new Uint8Array(32 * 0x4000); for (let i = 0; i < 20 * 0x4000; i++) g[i] = (i * 7 + (i >> 14)) & 255; // banks 20..31: zeros
const tr = E.gbTrim(g);
ok(tr.banks === 32 && tr.rom.length === 21 * 0x4000, 'GB_TRIM: 11 equal end banks left out');
ok(Buffer.from(E.gbUntrim(tr.rom, 32 << 16)).equals(Buffer.from(g)), 'GB_TRIM: the whole game again');
const g2 = g.slice(); g2[31 * 0x4000 + 5] = 1; ok(E.gbTrim(g2).banks === 0, 'GB_TRIM: different last bank: kept whole');
ok(E.gbTrim(g.subarray(0, 23 * 0x4000)).banks === 0, 'GB_TRIM: less than 64 KB to save: kept whole');
ok(E.gbUntrim(g, 0) === g, 'GB_TRIM: old image (no bank count): as it is'); }
{ // 1.7.1 GUEST_SPARSE: almost empty cold blocks of a TamaEmu in the menu as spare pages (made-up iD L)
const g = new Uint8Array(0x800000).fill(0xFF);
for (const b of [0x00, 0x0b, 0x0e, 0x40, 0x41]) g.fill(b, b << 16, (b + 1) << 16);
g.fill(0x11, 0x040000, 0x042000); g.fill(0x22, 0x050000, 0x052000); g.fill(0x23, 0x054000, 0x056000); // 4: 1 part, 5: 2 parts
g.fill(0x33, 0x060000, 0x066000); // 6: 3 parts (stays)
g.fill(0x44, 0x0d0000, 0x0d2000); // 0x0d: 1 part, but hot
const p0 = E.packGuest(g, 'idl'), p1 = E.packGuest(g, 'idl', { sparse: true });
ok(p0.pages.length === 0 && p1.blocks === p0.blocks - 2 && p1.pages.length === 3, 'GUEST_SPARSE: two cold blocks as 3 pages (' + p0.blocks + ' -> ' + p1.blocks + ')');
ok(p1.map[4] === 0xFF && p1.map[5] === 0xFF && p1.map[6] !== 0xFF && p1.map[0x0d] !== 0xFF, 'GUEST_SPARSE: hot and fuller blocks stay');
ok(p1.pages.every((x) => Buffer.from(x.data).equals(Buffer.from(g.subarray(x.v << 13, (x.v + 1) << 13)))), 'GUEST_SPARSE: the pages hold the parts'); }
{ // 1.7.2 CLEAN_ROM: a ROM without the Paradise from made-up data (only a load table and an edition word)
const F = require('../src/feld.js'), FL = require('../src/flash.js'), fs4 = require('fs');
const src = new Uint8Array(0x1000000).fill(0x5A);
src.set(Buffer.from('SONIXDEV'), 0); src[8] = 1;
let pid = 0; const prof = [[0xD49000, 1]]; for (const [o, id] of prof) { src[o] = id; src[o + 1] = src[o + 2] = src[o + 3] = 0;
// 1.7.3: a real ID page has its footer (k + id = family constant, ~k); a clean ROM finds it at the top only with it
const k = (0x70169E2C - id) >>> 0; for (let b = 0; b < 4; b++) { src[o + 0xFF8 + b] = (k >>> (8 * b)) & 255; src[o + 0xFFC + b] = (~k >>> (8 * b)) & 255; }
if (F.edition(src)) { pid = o; break; } }
const ed = F.edition(src);
ok(!!ed, 'CLEAN_ROM: made-up edition word found at 0x' + pid.toString(16));
if (ed) {
const base = F.cleanBase(src);
ok(base.subarray(0x1000, 0x10000).every((v) => v === 0xFF) && F.edition(base) && F.edition(base).id === ed.id, 'CLEAN_ROM: empty image with the ID page');
const fe = { feld: new Uint8Array(fs4.readFileSync(__dirname + '/../feld/feldc.bin')), stub: new Uint8Array(fs4.readFileSync(__dirname + '/../feld/stub_feld_tpl.bin')) };
const img = F.cleanApply(base, { apps: [], dl: 0 }, fe);
const u = (o) => (img[o] | img[o + 1] << 8 | img[o + 2] << 16 | img[o + 3] << 24) >>> 0;
ok(F.isClean(img) && !F.isClean(src) && !F.isClean(base), 'CLEAN_ROM: isClean only for the built image');
ok(u(0x10) === 0x600B1000 && (u(8) & 1) === 0 && u(0x80) === 0, 'CLEAN_ROM: load table points to the menu, not encrypted');
ok(u(0x110568) === 0x49024801 && u(0x11056C) === 0xBF004708 && u(0x110570) === 0x100A0000, 'CLEAN_ROM: restart routine in place');
ok(F.cleanReserved().some(([a, b]) => a <= 0xEFD000 && b > 0xEFD000), 'CLEAN_ROM: ID page reserved');
const w = FL.withRescue(img, new Uint8Array(fs4.readFileSync(__dirname + '/../flash/flashapp.bin')));
ok(!!w && F.isClean(w), 'CLEAN_ROM: rescue start with the battery text');
const bt = FL.batText(); ok(bt && bt.length > 0, 'CLEAN_ROM: battery text picture ' + (bt ? bt.length : 0) + ' bytes');
} }
{ // 1.7.3 GUEST_LZ: LZ4 parts of 1 KB, packed blocks and back (made-up data)
const E = require('../src/emu.js');
const p = new Uint8Array(1024); for (let i = 0; i < 1024; i++) p[i] = (i % 37 < 20) ? (i * 7) & 255 : 0x42;
const c = E.lzEnc(p); ok(c.length < 1024 && Buffer.from(E.lzDec(c, 1024)).equals(Buffer.from(p)), 'GUEST_LZ: part packed (' + c.length + ' bytes) and back');
const r = new Uint8Array(1024); let x = 1; for (let i = 0; i < 1024; i++) { x = (x * 1103515245 + 12345) >>> 0; r[i] = x >>> 24; }
ok(Buffer.from(E.lzDec(E.lzEnc(r), 1024)).equals(Buffer.from(r)), 'GUEST_LZ: random part back');
const g = new Uint8Array(0x40000).fill(0xFF); g.set(p, 0x10000); g.set(r, 0x10400); g.set(p, 0x30800);
const z = E.lzPack(g, [1, 3]), h = new Uint8Array(0x40000).fill(0xFF);
E.lzUnpack((a, n) => z.subarray(a, a + n), h);
ok(Buffer.from(h).equals(Buffer.from(g)), 'GUEST_LZ: two blocks packed (' + z.length + ' bytes) and back'); }
// 1.7.2 PROBE_RETRY: a download screen behind an adapter that loses the first 40 bytes after opening (PL2303),
// answering only a clean "ECHO REQ" line; the loader then gets no ACK (noAck), not "no answer"
{ const FL = require('../src/flash.js'); let lost = 40, line = ''; const io = { onData: null };
io.write = async (d) => { for (const b of d) { if (lost > 0) { lost--; continue; }
if (b === 10) { const l = line.replace(/\r$/, ''); line = '';
if (l === 'ECHO REQ') setTimeout(() => io.onData(new Uint8Array(Buffer.from('ECHO REP\r\n'))), 5);
else if (l.startsWith('PKT')) setTimeout(() => io.onData(new Uint8Array(Buffer.from('CAN\r\n'))), 5); }
else if (b >= 32 && b < 127) line += String.fromCharCode(b); else if (b !== 13) line = ''; } };
let code = ''; try { await FL.connect(io, new Uint8Array(16), { timeScale: 0.2 }); } catch (e) { code = e.code || e.message; }
ok(code === 'noAck', 'PROBE_RETRY: download screen found behind a lossy adapter (' + code + ')'); }
console.log(fails ? fails + ' failed' : 'all good');
process.exit(fails ? 1 : 0);
});
+16
View File
@@ -0,0 +1,16 @@
// V1Emu: names and flags from the ROM (test31: the English P1, Yasashii's segment order).
// node test/v1_names_test.js <VintageTamas folder> <land.bin>
const fs = require('fs'), E = require('../src/emu.js');
const dir = process.argv[2], land = new Uint8Array(fs.readFileSync(process.argv[3]));
const app = new Uint8Array(fs.readFileSync(__dirname + '/../v1/v1.bin')), stub = new Uint8Array(fs.readFileSync(__dirname + '/../emu/stub_tpl.bin'));
let bad = 0; const ok = (c, m) => { if (!c) { bad++; console.log('FAIL', m); } else console.log('ok', m); };
const want = { 'tama.bin': ['TAMA P1 EN', 8, 0], 'TamagotchiP1J.bin': ['TAMA P1', 8, 0], 'TamagotchiYasashii.bin': ['YASASHII', 0, 128], 'DigimonV1.bin': ['DIGIMON V1', 8, 0] };
for (const [f, [nm, clk, dir7]] of Object.entries(want)) {
const p = dir + '/' + f; if (!fs.existsSync(p)) { console.log('skip', f); continue; }
const r = new Uint8Array(fs.readFileSync(p)); const a = E.v1Patch(land, r, app, stub, {}); const o = a.rom || a;
const dv = new DataView(o.buffer, o.byteOffset), fl = dv.getUint32(0xA0000 + 0x140 + 20, true);
const name = Buffer.from(o.slice(0xA0000 + 0x158, 0xA0000 + 0x168)).toString().replace(/\0.*$/, '');
ok(E.v1Name(r) === nm && name === nm, f + ' name ' + name);
ok((fl & 8) === clk && (fl & 128) === dir7, f + ' flags ' + fl.toString(2));
}
console.log(bad ? 'FAILED ' + bad : 'all good');
+79
View File
@@ -0,0 +1,79 @@
// Simulated playdate partner (src/visit.js) against a scripted initiator. Test key and random data only.
const assert = require('assert');
const V = require('../src/visit.js');
const key = V.parseKey('TestKeyOnly-NotTheReal-0123456789');
assert(key, 'key');
assert.strictEqual(V.parseKey('short'), null);
const enc = (s) => new TextEncoder().encode(s);
async function chunk(sid, type, idx, data) {
const p = new Uint8Array(12 + data.length);
p[0] = sid & 255; p[1] = sid >> 8 & 255; p[2] = sid >> 16 & 255; p[3] = sid >>> 24;
p[4] = 0x54; p[5] = 0x43; p[6] = 0x50; p[7] = type; p[8] = idx; p[9] = 255 - idx;
const c = V.crc16(data); p[10] = c & 255; p[11] = c >> 8; p.set(data, 12);
const n = new Uint8Array([idx, 7, 9, 11]), e = await V.crypt(n, key, p), all = new Uint8Array(4 + e.length);
all.set(n); all.set(e, 4); return all;
}
async function run(breed) {
const lines = [], bin = [];
let rxbuf = new Uint8Array(0), want = 0, waiters = [];
const log = [];
const v = V.createVisitor({ edition: 'sky', key, log: (e, i) => log.push([e, i]),
send: async (b) => { const a = new Uint8Array(rxbuf.length + b.length); a.set(rxbuf); a.set(b, rxbuf.length); rxbuf = a; drain(); } });
function drain() {
for (;;) {
if (want) { if (rxbuf.length < want) return; bin.push(rxbuf.slice(0, want)); rxbuf = rxbuf.slice(want); want = 0; continue; }
let j = -1; for (let i = 0; i + 1 < rxbuf.length; i++) if (rxbuf[i] === 13 && rxbuf[i + 1] === 10) { j = i; break; }
if (j < 0) return;
lines.push(new TextDecoder().decode(rxbuf.subarray(0, j))); rxbuf = rxbuf.slice(j + 2);
const w = waiters; waiters = []; w.forEach((f) => f());
}
}
const tick = () => new Promise((r) => setTimeout(r, 5));
async function expect(s) { for (let i = 0; i < 400; i++) { const k = lines.indexOf(s); if (k >= 0) { lines.splice(k, 1); return; } await tick(); } throw new Error('missing ' + s + ' have ' + lines.join('|')); }
const sid = 0xEB24098E;
async function sendPacket(type, data) {
await v.feed(enc('PKT ' + data.length + '\r\n')); await expect('ACK');
for (let i = 0; i * 0x1000 < data.length; i++) { await v.feed(await chunk(sid, type, i, data.subarray(i * 0x1000, (i + 1) * 0x1000))); await expect('ACK'); }
}
await sendPacket(0x11, new Uint8Array([0xAB, 0xAB]));
const mine = new Uint8Array(0x20014); for (let i = 0; i < mine.length; i++) mine[i] = (i * 31 + 7) & 255;
mine[0x20002] = 1; mine[0x20004] = 0x8E;
await sendPacket(0x01, mine);
// the visitor answers with its own packet
await expect('PKT 131092');
const got = new Uint8Array(0x20014); let off = 0;
want = 16 + 0x1000; await v.feed(enc('ACK\r\n'));
for (let i = 0; i < 33; i++) {
for (let k = 0; k < 400 && !bin.length; k++) await tick();
const c = bin.shift(); assert(c, 'chunk ' + i);
const p = await V.crypt(c.subarray(0, 4), key, c.subarray(4));
assert.strictEqual(String.fromCharCode(p[4], p[5], p[6]), 'TCP');
assert.strictEqual((p[0] | p[1] << 8 | p[2] << 16 | p[3] << 24) >>> 0, sid, 'session id');
assert.strictEqual(p[8], i); assert.strictEqual(p[9], 255 - i);
const d = p.subarray(12); assert.strictEqual(V.crc16(d), p[10] | p[11] << 8, 'crc');
got.set(d, off); off += d.length;
const left = 0x20014 - off; want = left ? 16 + Math.min(0x1000, left) : 0;
await v.feed(enc('ACK\r\n'));
}
assert.strictEqual(off, 0x20014);
assert.deepStrictEqual(got.subarray(0, 0x20000), mine.subarray(0, 0x20000), 'ghost and screenshot are the player\'s own');
assert.strictEqual(got[0x20002], 3, 'rom_type Sky');
assert.strictEqual(got[0x20004] | got[0x20005] << 8 | got[0x20006] << 16 | got[0x20007] << 24, 0x504D5803, 'own device UID');
for (let k = 0; k < 100 && !log.some((x) => x[0] === 'sent'); k++) await tick();
await v.feed(enc('ECHO REQ\r\n')); await expect('ECHO REP');
await sendPacket(0x01, new Uint8Array([4, 0]));
await sendPacket(0x01, new Uint8Array([0, 0, breed ? 1 : 0, 0]));
if (breed) { await expect('BREED 0'); await expect('SYNC 1'); }
else assert(log.some((x) => x[0] === 'done'), 'done');
assert(log.some((x) => x[0] === 'result'));
// a chunk with the wrong key is refused
v.stop();
}
(async () => {
await run(false);
await run(true);
console.log('visit_test ok');
})().catch((e) => { console.error(e); process.exit(1); });
+91
View File
@@ -0,0 +1,91 @@
// 1.6.10 test1: the Wolf3D pack (src/wolf.js) from made-up files (no game data): pages, maps, sounds, pictures
// (Huffman, planes), the version by the number of chunks, missing files. node test/wolf_test.js
const W = require('../src/wolf.js');
let bad = 0; const ok = (c, m) => { console.log((c ? 'ok ' : 'FAIL ') + m); if (!c) bad++; };
const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0;
const u16 = (b, o) => b[o] | (b[o + 1] << 8);
function w16(b, o, v) { b[o] = v & 255; b[o + 1] = (v >> 8) & 255; }
function w32(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; }
const cat = (...a) => { const n = a.reduce((s, x) => s + x.length, 0), o = new Uint8Array(n); let p = 0; for (const x of a) { o.set(x, p); p += x.length; } return o; };
// a Huffman tree over all 256 bytes: internal nodes 0..254 (head 254), each byte 8 bits
const nodes = new Uint16Array(510), code = []; let next = 254;
function tree(lo, hi, depth, bits) {
const me = next--;
const half = (lo + hi) >> 1;
for (const [side, a, b] of [[0, lo, half], [1, half, hi]]) {
const v = b - a === 1 ? a : 256 + tree(a, b, depth + 1, bits | (side << depth));
if (b - a === 1) code[a] = { bits: bits | (side << depth), n: depth + 1 };
nodes[2 * me + side] = v;
}
return me;
}
tree(0, 256, 0, 0);
function huff(data) {
const out = []; let acc = 0, n = 0;
for (const d of data) { const c = code[d]; for (let i = 0; i < c.n; i++) { if ((c.bits >> i) & 1) acc |= 1 << n; n++; if (n === 8) { out.push(acc); acc = 0; n = 0; } } }
if (n) out.push(acc);
return Uint8Array.from(out);
}
const dict = new Uint8Array(1024); for (let i = 0; i < 510; i++) w16(dict, 2 * i, nodes[i]);
// pictures: chunks 56.. (Apogee 1.4 = 157 chunks); pic k has 8 x 4 dots, a pattern
const NCH = 157, FIRST = 56;
const picDots = (k) => { const d = new Uint8Array(32); for (let i = 0; i < 32; i++) d[i] = (k * 7 + i) & 255; return d; };
const planar = (d, w, h) => { const o = new Uint8Array(w * h); let s = 0; for (let p = 0; p < 4; p++) for (let y = 0; y < h; y++) for (let x = 0; x < w / 4; x++) o[s++] = d[y * w + 4 * x + p]; return o; };
const pictable = new Uint8Array((NCH - 3) * 4); for (let c = 3; c < NCH; c++) { w16(pictable, 4 * (c - 3), 8); w16(pictable, 4 * (c - 3) + 2, 4); }
const chunks = [];
const head = new Uint8Array(NCH * 3).fill(0xFF);
let graph = new Uint8Array(0);
const put = (c, raw) => { const h = huff(raw), l = new Uint8Array(4); w32(l, 0, raw.length); head[3 * c] = graph.length & 255; head[3 * c + 1] = (graph.length >> 8) & 255; head[3 * c + 2] = graph.length >> 16; graph = cat(graph, l, h); };
put(0, pictable);
for (let k = 0; k < 91; k++) put(FIRST + k, planar(picDots(k), 8, 4));
// VSWAP: 2 walls, 1 sprite, 1 sound
const wall0 = new Uint8Array(4096).map((_, i) => i & 255), wall1 = new Uint8Array(4096).fill(7), spr = Uint8Array.from([1, 2, 3, 4, 5, 6]), snd = new Uint8Array(10);
const vh = new Uint8Array(6 + 4 * 4 + 2 * 4); w16(vh, 0, 4); w16(vh, 2, 2); w16(vh, 4, 3);
let off = vh.length; [wall0, wall1, spr, snd].forEach((d, i) => { w32(vh, 6 + 4 * i, off); w16(vh, 6 + 16 + 2 * i, d.length); off += d.length; });
const vswap = cat(vh, wall0, wall1, spr, snd);
// maps: one map; header 38 bytes, two planes
const p0 = Uint8Array.from([4, 0, 9, 9]), p1 = Uint8Array.from([2, 0, 5]);
const gm = new Uint8Array(8 + 38 + p0.length + p1.length); gm.set([0x54, 0x45, 0x44, 0x35, 0x76, 0x31, 0x2E, 0x30]);
w32(gm, 8, 8 + 38); w32(gm, 12, 8 + 38 + p0.length); w32(gm, 16, 0); w16(gm, 20, p0.length); w16(gm, 22, p1.length); w16(gm, 24, 0); w16(gm, 26, 64); w16(gm, 28, 64);
gm.set([0x4D, 0x41, 0x50], 30); gm.set(p0, 46); gm.set(p1, 46 + p0.length);
const mh = new Uint8Array(402); w16(mh, 0, 0xABCD); w32(mh, 2, 8);
// audio: sound 0 (PC speaker), the rest empty
const ah = new Uint8Array(4 * 88); const s0 = Uint8Array.from([3, 0, 0, 0, 5, 0, 10, 20, 0]); for (let i = 1; i < 88; i++) w32(ah, 4 * i, s0.length);
const files = { 'VSWAP.WL1': vswap, 'MAPHEAD.WL1': mh, 'GAMEMAPS.WL1': gm, 'AUDIOHED.WL1': ah, 'AUDIOT.WL1': s0, 'VGAHEAD.WL1': head, 'VGADICT.WL1': dict, 'VGAGRAPH.WL1': graph };
const r = W.build(files), p = r.pack;
ok(String.fromCharCode(p[0], p[1], p[2], p[3]) === 'W3DP' && u32(p, 12) === p.length, 'pack header and length');
ok(r.ext === 'WL1' && (u32(p, 8) & 1) === 1, 'shareware flag');
ok(u32(p, 16) === 3 && u32(p, 20) === 2, 'pages: 3 (no digitized sound), sprites from 2');
{ const t = u32(p, 24); const o0 = u32(p, t), o2 = u32(p, t + 16);
ok(p.subarray(o0, o0 + 4096).every((v, i) => v === wall0[i]), 'wall 0 in place');
ok(u32(p, t + 20) === 6 && p.subarray(o2, o2 + 6).every((v, i) => v === spr[i]), 'sprite in place'); }
ok(u32(p, 28) === 1 && u32(p, 32) === 0xABCD, 'one map, RLEW tag');
{ const h = u32(p, u32(p, 36)); const a = u32(p, h), b = u32(p, h + 4);
ok(p[a] === 4 && p[a + 2] === 9 && p[b] === 2 && p[b + 2] === 5 && u32(p, h + 8) === 0, 'map planes moved, plane starts relative to the pack');
ok(String.fromCharCode(p[h + 22], p[h + 23], p[h + 24]) === 'MAP', 'map name'); }
ok(u32(p, 40) === 87 && u32(p, u32(p, 44) + 4) === s0.length && u32(p, u32(p, 44) + 8) === 0, 'PC speaker sound 0, others empty');
{ const t = u32(p, 52); let all = u32(p, 48) === 91;
all = all && u32(p, t) === 0 && u32(p, t + 8 * 45) === 0; // pictures the program never shows stay out
for (const k of [42, 43, 90]) { const o = u32(p, t + 8 * k); all = all && u16(p, t + 8 * k + 4) === 8 && u16(p, t + 8 * k + 6) === 4 && p.subarray(o, o + 32).every((v, i) => v === picDots(k)[i]); }
ok(all, '91 picture places, the used ones unpacked (Huffman) and deplaned, the others empty'); }
ok(u32(p, 60) === 1, 'one episode');
// a full version prefers .WL6 when both are complete; a missing file is named
const both = Object.assign({}, files); for (const k of Object.keys(files)) both[k.replace('WL1', 'WL6')] = files[k];
ok(W.pickSet(both).ext === 'WL6', 'full version first');
const miss = Object.assign({}, files); delete miss['VGADICT.WL1'];
let e1 = ''; try { W.build(miss); } catch (e) { e1 = e.message; }
ok(/VGADICT\.WL1/.test(e1), 'missing file named: ' + e1);
let e2 = ''; try { W.build({ 'readme.txt': new Uint8Array(1) }); } catch (e) { e2 = e.message; }
ok(/no Wolfenstein/.test(e2), 'no game files: ' + e2);
const odd = Object.assign({}, files, { 'VGAHEAD.WL1': head.subarray(0, 140 * 3) });
let e3 = ''; try { W.build(odd); } catch (e) { e3 = e.message; }
ok(/unknown version/.test(e3), 'unknown VGAHEAD: ' + e3);
{ const big = new Uint8Array(vswap); w16(big, 6 + 16, 16384);
let e4 = ''; try { W.build(Object.assign({}, files, { 'VSWAP.WL1': big })); } catch (e) { e4 = e.message; }
ok(/not 64 x 64/.test(e4), 'walls of another size refused: ' + e4); }
console.log(bad ? 'FAIL ' + bad : 'all good');
process.exit(bad ? 1 : 0);