import assert from 'node:assert/strict'; import test from 'node:test'; import { readFileSync } from 'node:fs'; import { runInNewContext } from 'node:vm'; import { createElement, isValidElement, type ReactElement, type ReactNode } from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import * as jsxRuntime from 'react/jsx-runtime'; import ts from 'typescript'; import * as board from '../game/board'; import * as catalog from '../game/catalog'; import * as coalitionAlliance from '../game/coalition-alliance'; import * as publicDeals from '../game/public-deals'; import { PublicDealList, PublicDeals, publicDealOfferAction } from '../components/public-deals'; import type { Action, GameView } from '../game/engine'; type Element = ReactElement<{children?:ReactNode; [key:string]:unknown}>; function elements(node: ReactNode): Element[] { if (Array.isArray(node)) return node.flatMap(elements); if (!isValidElement<{children?:ReactNode; [key:string]:unknown}>(node)) return []; return [node,...elements(node.props.children)]; } function label(node: ReactNode): string { if (Array.isArray(node)) return node.map(label).join(''); return typeof node === 'string' || typeof node === 'number' ? String(node) : ''; } const first = {kind:'immediateBribe' as const,payer:'a',recipient:'b',amount:2}; const second = {kind:'immediateBribe' as const,payer:'b',recipient:'a',amount:3}; const deferred = {kind:'deferredBribe' as const,payer:'a',recipient:'b',amount:1,dueTurn:3}; const base = {status:'playing',turn:2,me:'a',roomControl:null,coalitionState:null, players:[{id:'a',name:'Alice',faction:'atreides',ally:null},{id:'b',name:'Basil',faction:'harkonnen',ally:null}], deals:[],deferredDealPaymentOptions:{}} as unknown as GameView; void test('offer helper retains each immediate term alongside deferred and travel terms', () => { const travel = {kind:'ship' as const,territory:'carthag',minimum:1,answer:true}; assert.deepEqual(publicDealOfferAction(['b'],' Terms ',first,'a',2,travel,[deferred],[second]), {type:'dealOffer',target:'b',terms:'Terms',payment:first,travel, additionalPayments:[deferred],additionalImmediatePayments:[second]}); assert.deepEqual(publicDealOfferAction(['b'],'Terms',undefined,'a',2,undefined,[],[first,second]), {type:'dealOffer',target:'b',terms:'Terms',additionalImmediatePayments:[first,second]}); for (const terms of [[{...first,payer:'outsider'}],[{...first,recipient:'a'}], [{...first,amount:0}],Array.from({length:13},() => first)]) assert.equal(publicDealOfferAction(['b'],'Terms',undefined,'a',2,undefined,[],terms),null); }); void test('the offer displays all immediate terms to every participant', () => { const deal = {id:'deal',from:'a',to:'b',terms:'Two immediate payments.',turn:2,status:'offered',releaseVotes:[], additionalImmediatePayments:[first,second]}; for (const viewer of ['a','b']) { const game = {...base,me:viewer,deals:[deal]} as unknown as GameView; const html = renderToStaticMarkup(createElement(PublicDealList,{game,disabled:false,act() {}})); assert.match(html,/Additional immediate payment 1/); assert.match(html,/Additional immediate payment 2/); assert.match(html,/Alice \(Atreides\) pays 2 spice to Basil \(Harkonnen\)/); assert.match(html,/Basil \(Harkonnen\) pays 3 spice to Alice \(Atreides\)/); assert.match(html,/final acceptance/); } }); /** Exercise actual hook callbacks with a stateful React-compatible VM. This * verifies the component controls, not a hydrated-browser session. */ function form() { const states:unknown[] = [], refs:{current:unknown}[] = [], sent:Action[] = []; let stateCursor = 0, refCursor = 0; const exported:{PublicDeals?:typeof PublicDeals} = {}; runInNewContext(ts.transpileModule(readFileSync(new URL('../components/public-deals.tsx',import.meta.url),'utf8'),{ compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX}, }).outputText,{exports:exported,require(name:string) { if (name === 'react/jsx-runtime') return jsxRuntime; if (name === 'react') return {useState(initial:unknown) { const index = stateCursor++; if (!(index in states)) states[index] = typeof initial === 'function' ? initial() : initial; return [states[index],(next:unknown) => {states[index] = typeof next === 'function' ? next(states[index]) : next;}]; },useRef(initial:unknown) {const index = refCursor++; return refs[index] ??= {current:initial};},useEffect() {}}; if (name === '@/components/ui/button') return {Button:'button'}; if (name === '@/game/board') return board; if (name === '@/game/catalog') return catalog; if (name === '@/game/coalition-alliance') return coalitionAlliance; if (name === '@/game/public-deals') return publicDeals; throw Error(`Unexpected import ${name}`); }}); assert.ok(exported.PublicDeals); const render = () => {stateCursor = 0; refCursor = 0; return elements(exported.PublicDeals!({game:base,busy:false,act(action) {sent.push(action);}}));}; const click = (name:string) => { const button = render().find(node => node.type === 'button' && label(node.props.children) === name); assert.ok(button); assert.equal(button.props.disabled,false); (button.props.onClick as () => void)(); }; const field = (index:number) => { const sets = render().filter(node => node.type === 'fieldset' && elements(node).some(child => child.type === 'legend' && JSON.stringify(child.props.children).includes('Additional immediate payment'))); assert.ok(sets[index]); return elements(sets[index]); }; return {render,click,field,sent}; } void test('authoring callbacks add, edit and remove immediate terms', () => { const ui = form(); const recipient = ui.render().find(node => node.type === 'input' && node.props.type === 'checkbox'); assert.ok(recipient); (recipient.props.onChange as (event:{target:{checked:boolean}}) => void)({target:{checked:true}}); ui.click('Add immediate payment'); ui.click('Add immediate payment'); for (let index = 0; index < 2; index++) { for (const [position,value] of [[0,index === 0 ? 'a' : 'b'],[1,index === 0 ? 'b' : 'a']] as const) { const select = ui.field(index).filter(node => node.type === 'select')[position]; assert.ok(select); (select.props.onChange as (event:{target:{value:string}}) => void)({target:{value}}); } const input = ui.field(index).find(node => node.type === 'input' && node.props.type === 'number'); assert.ok(input); (input.props.onChange as (event:{target:{value:string}}) => void)({target:{value:String(index+2)}}); } ui.click('Remove immediate payment 1'); const terms = ui.render().find(node => node.type === 'textarea'); assert.ok(terms); (terms.props.onChange as (event:{target:{value:string}}) => void)({target:{value:'One retained immediate payment'}}); const submit = ui.render().find(node => node.type === 'button' && node.props.type === 'submit'); assert.ok(submit); assert.equal(submit.props.disabled,false); const root = ui.render().find(node => node.type === 'form'); assert.ok(root); (root.props.onSubmit as (event:{preventDefault():void}) => void)({preventDefault() {}}); assert.deepEqual(JSON.parse(JSON.stringify(ui.sent)),[{type:'dealOffer',target:'b',terms:'One retained immediate payment', additionalImmediatePayments:[second]}]); });