@champions-digital-game/mod-sdk 0.53.0 → 0.54.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/chunks/{chunk-D5S6EHFQ.js → chunk-7NRC6TLV.js} +1 -1
- package/dist/mc-pack.js +2 -2
- package/dist/testing.js +1 -1
- package/package.json +1 -1
- package/types/content/src/index.d.ts +1 -1
- package/types/engine/src/index.d.ts +1 -1
- package/types/mod-sdk/src/smoke.d.ts +44 -0
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# @champions-digital-game/mod-sdk
|
|
2
2
|
|
|
3
3
|
The mod SDK for [Marvel Champions Digital](https://github.com/quincarter/marvel-champions-digital-game) content
|
|
4
|
-
packs, version 0.
|
|
4
|
+
packs, version 0.54.0: the pack schema, the ability DSL the game's own cards are written in, and the `mc-pack`
|
|
5
5
|
tool that validates, builds, tests and imports packs. It carries the game's rules engine, so `mc-pack test` plays
|
|
6
6
|
real headless games.
|
|
7
7
|
|
|
@@ -11,10 +11,10 @@ of Fantasy Flight Games and Marvel.
|
|
|
11
11
|
## Install
|
|
12
12
|
|
|
13
13
|
```sh
|
|
14
|
-
npm install --save-dev @champions-digital-game/mod-sdk@0.
|
|
14
|
+
npm install --save-dev @champions-digital-game/mod-sdk@0.54.0
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
The SDK is versioned with the game: a pack built with SDK 0.
|
|
17
|
+
The SDK is versioned with the game: a pack built with SDK 0.54.0 runs on app 0.54.0 and later. Every game
|
|
18
18
|
release also carries this package as a tarball, which installs the same way (`npm install --save-dev ./<file>.tgz`).
|
|
19
19
|
|
|
20
20
|
## A pack's source folder
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{campaignDepsWithPacks,campaignGameWithPacks,gameDepsWithPack,packCampaignRecords,packModularSetChoices,packScenarioRecords,scenarioWithPacks}from"./chunk-S3JH4WL4.js";import{CORE_SCENARIOS,CORE_STARTER_DECKS,PLAYABLE_CARDS,PLAYABLE_DEPS,applyCampaignResult,applyCommand,campaignResultOf,canAttack,cardOf,cardsInPlay,characterProfile,controllerOf,createCampaignLog,createGame,getInstance,getPlayer,isVillain,legalActions,mainSchemeStage,outstandingForcedActions,printedResources,replay,resolveBetweenGames,scale,schemesInPlay,sessionApply,startGameFromLog,startSession,wildDeclarationFault,wildDeclarations}from"./chunk-ACT4TJXC.js";function playToOutcome(initial,deps,options={}){let maxCommands=options.maxCommands??2e4,memory={key:"",used:new Set,commands:0,maxPerTurn:options.maxCommandsPerTurn??60},session=startSession(initial),commands=0;for(;!session.state.outcome&&commands<maxCommands;){let command=nextCommand(session.state,deps,memory),result=sessionApply(session,command,deps);if(!result.ok)throw new Error(`driver issued an illegal ${command.type}: ${result.error.code}: ${result.error.message}`);session=result.session,commands++}return{session,outcome:session.state.outcome,rounds:session.state.round,commands}}function nextCommand(state,deps,memory){let choice=state.pendingChoice;if(choice)return{type:"resolveChoice",playerId:choice.playerId,choiceId:choice.choiceId,selectedOptionIds:answerChoice(state,choice)};if(state.step.phase!=="player"||state.step.kind!=="turn")throw new Error(`no choice pending and not a player turn (${state.step.phase}/${state.step.kind})`);let playerId=state.step.activePlayerId,key=`${state.round}:${playerId}`;memory.key!==key&&(memory.key=key,memory.used=new Set,memory.commands=0),memory.commands++;let endTurn={type:"endTurn",playerId};if(memory.commands>memory.maxPerTurn)return endTurn;for(let candidate of turnCandidates(state,deps,playerId,memory))if(applyCommand(state,candidate.command,deps).ok)return candidate.memo&&memory.used.add(candidate.memo),candidate.command;let owed=outstandingForcedActions(state,playerId,deps)[0];return owed?owed.example:endTurn}var card=(state,id)=>cardOf(state,id),resourceValue=(state,id)=>{let c=card(state,id);if(!c)return 0;let pool=printedResources(c);return pool.physical+pool.mental+pool.energy+pool.wild};function liveRefs(state,id){let c=card(state,id);return c?c.type==="hero_identity"?(state.players.find(p=>p.identity.instanceId===id)?.identity.form==="hero"?c.hero.abilities:c.alterEgo.abilities).map(r=>r.id):c.type==="villain"||c.type==="main_scheme"?[]:"abilities"in c?c.abilities.map(r=>r.id):[]:[]}function*turnCandidates(state,deps,playerId,memory){let player=getPlayer(state,playerId);if(!player)return;let identityId=player.identity.instanceId,identity=getInstance(state,identityId),profile=characterProfile(state,identityId,deps);if(!identity||!profile)return;let hpLeft=profile.maxHp-identity.damage,form=player.identity.form;form==="alterEgo"&&(!identity.exhausted&&identity.damage>0&&hpLeft*2<=profile.maxHp&&(yield{command:{type:"basicRecover",playerId}}),!player.identity.changedFormThisRound&&hpLeft*2>profile.maxHp&&(yield{command:{type:"changeForm",playerId}},yield*paidFormChanges(state,deps,playerId)));for(let id of player.hand){let c=card(state,id);if(!c||c.type==="resource"||!("cost"in c))continue;let action=actionAbility(deps,c);if(!(c.type==="event"&&!action))for(let payment of payments(state,deps,playerId,id,c.cost))for(let extra of playExtras(state,deps,playerId,id,c,action,payment))yield{command:{type:"playCard",playerId,cardInstanceId:id,payment,attachToInstanceId:extra.attachTo,...extra.costChoices?{costChoices:extra.costChoices}:{}}}}for(let id of cardsInPlay(state)){let controller=controllerOf(state,id);if(!(controller!==null&&controller!==playerId))for(let ability of liveRefs(state,id)){let definition=deps.abilities[ability];if(definition?.trigger.kind!=="action")continue;let memo=`${id}:${ability}`;if(memory.used.has(memo))continue;let choices=definition.cost?.discardFromHand?{discard:player.hand.slice(0,definition.cost.discardFromHand.min)}:void 0;for(let payment of payments(state,deps,playerId,null,0,definition))yield{memo,command:{type:"useAbility",playerId,cardInstanceId:id,abilityId:ability,payment,...choices?{costChoices:choices}:{}}}}}let stage=mainSchemeStage(state),target=scale(stage.targetThreat,state.startingPlayerCount),mainThreat=getInstance(state,state.mainScheme.instanceId)?.threat??0,sideSchemes=schemesInPlay(state).filter(id=>id!==state.mainScheme.instanceId&&(getInstance(state,id)?.threat??0)>0),thwartFirst=mainThreat*2>=target||sideSchemes.length>0,thwartTarget=mainThreat*2>=target||sideSchemes.length===0?state.mainScheme.instanceId:sideSchemes[0],enemies=cardsInPlay(state).filter(id=>{let c=card(state,id);return isVillain(state,id)||c?.type==="minion"||getInstance(state,id)?.facedownAs}),attackers=[identityId,...player.playArea.filter(id=>card(state,id)?.type==="ally")];for(let attacker of attackers){if(!!getInstance(state,attacker)?.exhausted||attacker===identityId&&form!=="hero")continue;let thwart={command:{type:"basicThwart",playerId,thwarterInstanceId:attacker,schemeInstanceId:thwartTarget}},attacks=enemies.filter(enemy=>canAttack(state,attacker,enemy,deps)).map(enemy=>({command:{type:"basicAttack",playerId,attackerInstanceId:attacker,targetInstanceId:enemy}}));thwartFirst?(yield thwart,yield*attacks):(yield*attacks,yield thwart)}form==="hero"&&!player.identity.changedFormThisRound&&hpLeft<=4&&(yield{command:{type:"changeForm",playerId}},yield*paidFormChanges(state,deps,playerId))}function*paidFormChanges(state,deps,playerId){let actions=legalActions(state,playerId,deps);if(actions.kind==="turn")for(let legal of actions.legal)legal.action.kind==="changeForm"&&legal.needsPayment&&(yield{command:legal.example})}function actionAbility(deps,c){if("abilities"in c)for(let ref of c.abilities){let definition=deps.abilities[ref.id];if(definition?.trigger.kind==="action")return definition}}function*payments(state,deps,playerId,playing,printedCost,ability){let player=getPlayer(state,playerId);if(!player)return;let fixed=ability?.cost?.resources,needed=printedCost+(typeof fixed=="number"?fixed:fixed?Object.values(fixed).reduce((a,b)=>a+(b??0),0):0),extra=ability?.cost?.resourcesX?1:0,abilityPayments=[];for(let id of cardsInPlay(state))if(controllerOf(state,id)===playerId)for(let ref of liveRefs(state,id))deps.abilities[ref]?.trigger.kind==="resource"&&abilityPayments.push({ability:{instanceId:id,abilityId:ref}});let hand=player.hand.filter(id=>id!==playing),byValue=[...hand].sort((a,b)=>+(card(state,b)?.type==="resource")-+(card(state,a)?.type==="resource")),total=needed+extra;if(total===0){yield[];return}let tried=new Set,offer=payment=>{let key=JSON.stringify(payment);return tried.has(key)?!1:(tried.add(key),!0)};for(let order of[byValue,hand]){let sum=0,picks=[];for(let id of order)if(picks.push({fromHand:id}),sum+=resourceValue(state,id),sum>=total)break;if(sum>=total&&offer(picks)&&(yield picks),sum>=total&&picks.length<order.length){let one=[...picks,{fromHand:order[picks.length]}];offer(one)&&(yield one)}}for(let ability2 of abilityPayments){let sum=1,picks=[ability2];for(let id of byValue){if(sum>=total)break;picks.push({fromHand:id}),sum+=resourceValue(state,id)}sum>=total&&offer(picks)&&(yield picks)}}function*playExtras(state,deps,playerId,id,c,action,payment){let reserved=new Set(payment.flatMap(p=>"fromHand"in p?[p.fromHand]:[])),spare=(getPlayer(state,playerId)?.hand??[]).filter(h=>h!==id&&!reserved.has(h)),costChoices={};if(action?.cost?.discardFromHand){let n=Math.max(action.cost.discardFromHand.min,Math.min(action.cost.discardFromHand.max??spare.length,spare.length,2));if(spare.length<n)return;costChoices.discard=spare.slice(0,n)}let pay=action?.cost?.payPrintedCostOf,pickSlots=pay?state.players.flatMap(p=>p.discard.filter(d=>card(state,d)?.type==="ally")).map(d=>({...costChoices,[pay.slot]:[d]})):[costChoices],hosts=c.type==="upgrade"&&c.attachesTo?cardsInPlay(state).filter(h=>getInstance(state,h)?.faceup!==void 0):[null];for(let choices of pickSlots)for(let host of hosts)yield Object.keys(choices).length>0?{attachTo:host,costChoices:choices}:{attachTo:host}}function answerChoice(state,choice){let ids=choice.options.map(o=>o.optionId),fewest=ids.slice(0,choice.minSelections);switch(choice.prompt.kind){case"mulligan":return[];case"takeStartingCard":return ids.slice(0,1);case"declareDefender":{let allies=ids.filter(id=>id!=="decline"&&card(state,id)?.type==="ally");if(allies[0])return[allies[0]];let attacked=choice.prompt.attack.targetCharacterInstanceId,identity=getInstance(state,attacked),profile=characterProfile(state,attacked);return(identity&&profile?profile.maxHp-identity.damage<=6:!1)&&ids.includes(attacked)?[attacked]:ids.includes("decline")?["decline"]:fewest}case"chooseTriggers":case"orderTriggers":case"orderSpecials":return ids.slice(0,Math.max(choice.minSelections,choice.maxSelections));case"payForAbility":return choice.prompt.chosenResources?spendUpTo(state,choice,choice.prompt.chosenResources):payFromOptions(state,choice,choice.prompt.cost,null);case"payForCard":return payFromOptions(state,choice,choice.prompt.cost,null);case"spendResources":{let r=choice.prompt.requirement;return payFromOptions(state,choice,(r.generic??0)+(r.physical??0)+(r.mental??0)+(r.energy??0),r)}case"divide":{let picked=[],cards=[];for(let id of ids){if(picked.length>=choice.prompt.amount)break;let cardId=id.slice(0,id.lastIndexOf("#"));if(!cards.includes(cardId)){if(choice.prompt.maxTargets!==void 0&&cards.length>=choice.prompt.maxTargets)continue;cards.push(cardId)}picked.push(id)}return picked}case"declareWildTypes":{let{wilds,pool,requirement,only}=choice.prompt,resolved={generic:requirement.generic??0,physical:requirement.physical??0,mental:requirement.mental??0,energy:requirement.energy??0,...requirement.wild===void 0?{}:{wild:requirement.wild}},declared=wildDeclarations(wilds).find(d=>wildDeclarationFault(pool,d,resolved,only)===null);return declared?declared.map((type,index)=>`${index}:${type}`):fewest}case"discardDownToHandSize":case"discardOverAllyLimit":case"discardOverPlayerSideSchemeLimit":case"discardRestricted":return fewest;default:return ids.slice(0,Math.min(Math.max(choice.minSelections,1),choice.maxSelections))}}function spendUpTo(state,choice,range){let picks=[],sum=0;for(let option of choice.options){let value=option.optionId.startsWith("ability:")?1:resourceValue(state,option.optionId.slice(5));value>0&&sum+value<=range.max&&(picks.push(option.optionId),sum+=value)}return sum>=range.min?picks:[]}function payFromOptions(state,choice,cost,typed){if(cost<=0)return[];let value=optionId=>optionId.startsWith("ability:")?1:resourceValue(state,optionId.slice(5)),matchesType=optionId=>{if(!typed||optionId.startsWith("ability:"))return optionId.startsWith("ability:");let c=card(state,optionId.slice(5));if(!c)return!1;let pool=printedResources(c);return pool.wild>0||["physical","mental","energy"].some(t=>(typed[t]??0)>0&&pool[t]>0)},ordered=choice.options.map(o=>o.optionId).sort((a,b)=>Number(matchesType(b))-Number(matchesType(a))),picks=[],sum=0;for(let optionId of ordered){if(sum>=cost)break;picks.push(optionId),sum+=value(optionId)}return sum>=cost?picks:[]}import{isDeepStrictEqual}from"node:util";var SMOKE_BASE_DECK="core-spider-man-justice",SMOKE_SCENARIOS=CORE_SCENARIOS.map(s=>String(s.id)),errorText=error=>error instanceof Error?error.message:String(error);function smokeTestPack(pack,options={}){let games=options.games??3,scenario=options.scenario??"rhino",maxCommands=options.maxCommands??4e3;if(!Number.isInteger(games)||games<1)throw new Error("games must be a whole number of at least 1");if(!SMOKE_SCENARIOS.includes(scenario))throw new Error(`unknown scenario "${scenario}" (one of ${SMOKE_SCENARIOS.join(", ")})`);let prefix=`x.${pack.manifest.id}.`,notes=[],deps=gameDepsWithPack(PLAYABLE_DEPS,pack),plans=(pack.decks??[]).map(deck=>({name:String(deck.id),deck,scenario}));plans.length===0&&pack.cards.some(card2=>card2.type==="hero_identity")&¬es.push("the pack has a hero but no deck in decks/: add its precon so mc-pack test can play it");let ownScenarios=packScenarioRecords([pack]);for(let record of ownScenarios)plans.push({name:SMOKE_BASE_DECK,scenario:String(record.id)}),plans.push({name:SMOKE_BASE_DECK,scenario:String(record.id),difficulty:"expert"});let baseRecord=CORE_SCENARIOS.find(candidate=>String(candidate.id)===scenario);for(let set of baseRecord?packModularSetChoices(baseRecord,[pack]):[])plans.push({name:SMOKE_BASE_DECK,scenario,modularSet:String(set.id),modularSetIds:[String(set.id)]});plans.length===0&&(notes.push(`the pack has no hero deck, scenario or modular set of its own, so a base precon (${SMOKE_BASE_DECK}) played ${scenario} with the pack's cards in the pool`),plans.push({name:SMOKE_BASE_DECK,scenario}));let open=(plan,seed)=>{let seat=plan.deck?{identityCardId:plan.deck.identityCardId,...plan.deck.aspects?{aspects:plan.deck.aspects}:{},deck:plan.deck.cards.flatMap(({cardId,quantity})=>Array.from({length:quantity},()=>cardId))}:{starterDeckId:SMOKE_BASE_DECK},config=scenarioWithPacks(plan.scenario,{players:[seat],seed,difficulty:plan.difficulty??"standard",...plan.modularSetIds?{modularSetIds:plan.modularSetIds}:{}},[pack]),created=createGame(config,deps);if(!created.ok)throw new Error(`setup failed: ${created.error.message}`);return created.state},results=[],everPlayed=new Set;for(let plan of plans)for(let seed=1;seed<=games;seed++){let game;try{let run=playToOutcome(open(plan,seed),deps,{maxCommands}),state=run.session.state,base={deck:plan.name,scenario:plan.scenario,...plan.modularSet?{modularSet:plan.modularSet}:{},...plan.difficulty?{difficulty:plan.difficulty}:{},seed,rounds:run.rounds,commands:run.commands},replayed=replay(run.session.log,deps),played=replayed.ok?[...new Set(replayed.events.flatMap(e=>(e.type==="cardPlayed"||e.type==="encounterCardRevealed")&&String(e.cardId).startsWith(prefix)?[String(e.cardId)]:[]))]:[],error;run.outcome===null?error=`stuck: no outcome after ${run.commands} commands (round ${run.rounds})`:state.pendingChoice!==null?error="a prompt was still open when the game ended":replayed.ok?isDeepStrictEqual(replayed.state,state)||(error="the game's log replays to a different state"):error=`the game's log does not replay: ${replayed.error.message}`,game={...base,ok:error===void 0,...run.outcome?{outcome:`${run.outcome.result} (${run.outcome.reason})`}:{},...error!==void 0?{error}:{},packCardsPlayed:played}}catch(caught){game={deck:plan.name,scenario:plan.scenario,...plan.modularSet?{modularSet:plan.modularSet}:{},...plan.difficulty?{difficulty:plan.difficulty}:{},seed,ok:!1,rounds:0,commands:0,error:errorText(caught),packCardsPlayed:[]}}for(let code of game.packCardsPlayed)everPlayed.add(code);results.push(game),options.onGame?.(game)}for(let campaign of packCampaignRecords([pack])){let lostAt=[];notes.push(`campaign ${campaign.id}: ${CAMPAIGN_DRIVER_LIMITS}`);for(let seed=1;seed<=games;seed++){let run=playCampaign(pack,campaign,seed,deps,maxCommands);lostAt.push(run.lostAt),notes.push(...run.notes);for(let game of run.games){for(let code of game.packCardsPlayed)everPlayed.add(code);results.push(game),options.onGame?.(game)}}let first=lostAt[0];if(options.failOnAlwaysLost&&first!==null&&first!==void 0&&lostAt.every(node=>node===first)){let failed={deck:SMOKE_BASE_DECK,scenario:campaign.record.scenarioIds[campaign.definition.graph.nodes.findIndex(n=>n.id===first)]??"",campaign:campaign.id,node:first,seed:0,ok:!1,rounds:0,commands:0,error:`every seed lost at node "${first}": the greedy driver never won it, so the later nodes were reached only with staged wins`,packCardsPlayed:[]};results.push(failed),options.onGame?.(failed)}}return results.length>0&&everPlayed.size===0&¬es.push("no game played or revealed one of the pack's own cards; try more games (--games)"),{ok:results.every(g=>g.ok),scenario,games:results,notes}}var CAMPAIGN_DRIVER_LIMITS="the greedy driver wins or loses on its own, so a Defeat block runs only if a game is lost (and a node that is always won never runs it); optional between-games choices are declined; every other choice takes its first options; and an instruction behind a `when` gate or mode that is false in these runs is not exercised";function settleCampaign(step){let answers=[];for(let guard=0;guard<64;guard++){let result=step(answers);if(result.kind==="done")return result.value;let{instructionId,slot,seatNumber,optional,options,count}=result.choice;answers.push({instructionId,slot,seatNumber,picked:optional?[]:options.slice(0,count)})}throw new Error("the campaign runner kept asking questions")}var hasWrittenField=log=>Object.keys(log.shared).length>0||log.seats.some(seat=>Object.keys(seat.fields).length>0);function playCampaign(pack,campaign,seed,deps,maxCommands){let definition=campaign.definition,games=[],notes=[],lostAt=null,budget=definition.graph.nodes.length*3+2,failure=(node,scenario2,error)=>({deck:SMOKE_BASE_DECK,scenario:scenario2,campaign:campaign.id,node,seed,ok:!1,rounds:0,commands:0,error,packCardsPlayed:[]}),starter=CORE_STARTER_DECKS.find(deck=>String(deck.id)===SMOKE_BASE_DECK);if(!starter)throw new Error(`no starter deck "${SMOKE_BASE_DECK}"`);let prefix=`x.${pack.manifest.id}.`,campaignDeps=campaignDepsWithPacks(PLAYABLE_CARDS,[pack]),nodeId="(start)",scenario="(campaign)";try{let log=createCampaignLog(definition,{id:`smoke-${campaign.id}-${seed}`,seats:[{seatNumber:1,identityCardId:starter.identityCardId,deck:{identityCardId:starter.identityCardId,aspects:starter.aspects,cards:starter.cards}}],modes:{campaign:{campaignId:definition.campaignId}},poolVersion:"smoke",seed});for(let turn=0;turn<budget&&log.status==="active";turn++){let before=log,composed=settleCampaign(answers=>resolveBetweenGames(definition,before,campaignDeps,before.modes,answers)),start=startGameFromLog(definition,composed);nodeId=start.nodeId,scenario=String(start.scenarioId);let created=createGame(campaignGameWithPacks(start,[pack]),deps);if(!created.ok)throw new Error(`setup failed: ${created.error.message}`);let run=playToOutcome(created.state,deps,{maxCommands}),state=run.session.state,replayed=replay(run.session.log,deps),error;run.outcome===null?error=`stuck: no outcome after ${run.commands} commands (round ${run.rounds})`:state.pendingChoice!==null?error="a prompt was still open when the game ended":replayed.ok?isDeepStrictEqual(replayed.state,state)||(error="the game's log replays to a different state"):error=`the game's log does not replay: ${replayed.error.message}`;let events=replayed.ok?replayed.events:[],played=[...new Set(events.flatMap(e=>(e.type==="cardPlayed"||e.type==="encounterCardRevealed")&&String(e.cardId).startsWith(prefix)?[String(e.cardId)]:[]))];if(games.push({deck:SMOKE_BASE_DECK,scenario,campaign:campaign.id,node:nodeId,seed,ok:error===void 0,...run.outcome?{outcome:`${run.outcome.result} (${run.outcome.reason})`}:{},...error!==void 0?{error}:{},rounds:run.rounds,commands:run.commands,packCardsPlayed:played}),error!==void 0)return{games,notes,lostAt};let result=campaignResultOf(definition,composed,state,events,deps);if(log=settleCampaign(answers=>applyCampaignResult(definition,composed,result,{at:1},campaignDeps,answers)),result.outcome==="lost"&&(lostAt??=nodeId),result.outcome==="lost"&&log.status==="active"){let lost=log,again=settleCampaign(answers=>resolveBetweenGames(definition,lost,campaignDeps,lost.modes,answers)),staged={...state,outcome:{result:"win",reason:"villainDefeated"},campaignWrites:{logWrites:[],removedFromCampaign:[]}},stagedResult=campaignResultOf(definition,again,staged,events,deps);log=settleCampaign(answers=>applyCampaignResult(definition,again,stagedResult,{at:1},campaignDeps,answers)),notes.push(`campaign ${campaign.id} seed ${seed}: lost at "${nodeId}", then advanced with a staged win`)}}log.status==="active"?games.push(failure(nodeId,scenario,`the campaign was still open after ${budget} games`)):definition.logFields.length>0&&!hasWrittenField(log)&&games.push(failure(nodeId,scenario,"the campaign ended with none of its log fields written"))}catch(caught){games.push(failure(nodeId,scenario,errorText(caught)))}return{games,notes,lostAt}}export{playToOutcome,SMOKE_BASE_DECK,SMOKE_SCENARIOS,smokeTestPack};
|
|
1
|
+
import{campaignDepsWithPacks,campaignGameWithPacks,gameDepsWithPack,packCampaignRecords,packModularSetChoices,packScenarioRecords,scenarioWithPacks}from"./chunk-S3JH4WL4.js";import{CORE_SCENARIOS,CORE_STARTER_DECKS,PLAYABLE_CARDS,PLAYABLE_DEPS,applyCampaignResult,applyCommand,campaignResultOf,canAttack,cardOf,cardsInPlay,characterProfile,controllerOf,createCampaignLog,createGame,getInstance,getPlayer,isVillain,legalActions,mainSchemeStage,outstandingForcedActions,printedResources,replay,resolveBetweenGames,scale,schemesInPlay,sessionApply,startGameFromLog,startSession,wildDeclarationFault,wildDeclarations}from"./chunk-ACT4TJXC.js";function playToOutcome(initial,deps,options={}){let maxCommands=options.maxCommands??2e4,memory={key:"",used:new Set,commands:0,maxPerTurn:options.maxCommandsPerTurn??60},session=startSession(initial),commands=0;for(;!session.state.outcome&&commands<maxCommands;){let command=nextCommand(session.state,deps,memory),result=sessionApply(session,command,deps);if(!result.ok)throw new Error(`driver issued an illegal ${command.type}: ${result.error.code}: ${result.error.message}`);session=result.session,commands++}return{session,outcome:session.state.outcome,rounds:session.state.round,commands}}function nextCommand(state,deps,memory){let choice=state.pendingChoice;if(choice)return{type:"resolveChoice",playerId:choice.playerId,choiceId:choice.choiceId,selectedOptionIds:answerChoice(state,choice)};if(state.step.phase!=="player"||state.step.kind!=="turn")throw new Error(`no choice pending and not a player turn (${state.step.phase}/${state.step.kind})`);let playerId=state.step.activePlayerId,key=`${state.round}:${playerId}`;memory.key!==key&&(memory.key=key,memory.used=new Set,memory.commands=0),memory.commands++;let endTurn={type:"endTurn",playerId};if(memory.commands>memory.maxPerTurn)return endTurn;for(let candidate of turnCandidates(state,deps,playerId,memory))if(applyCommand(state,candidate.command,deps).ok)return candidate.memo&&memory.used.add(candidate.memo),candidate.command;let owed=outstandingForcedActions(state,playerId,deps)[0];return owed?owed.example:endTurn}var card=(state,id)=>cardOf(state,id),resourceValue=(state,id)=>{let c=card(state,id);if(!c)return 0;let pool=printedResources(c);return pool.physical+pool.mental+pool.energy+pool.wild};function liveRefs(state,id){let c=card(state,id);return c?c.type==="hero_identity"?(state.players.find(p=>p.identity.instanceId===id)?.identity.form==="hero"?c.hero.abilities:c.alterEgo.abilities).map(r=>r.id):c.type==="villain"||c.type==="main_scheme"?[]:"abilities"in c?c.abilities.map(r=>r.id):[]:[]}function*turnCandidates(state,deps,playerId,memory){let player=getPlayer(state,playerId);if(!player)return;let identityId=player.identity.instanceId,identity=getInstance(state,identityId),profile=characterProfile(state,identityId,deps);if(!identity||!profile)return;let hpLeft=profile.maxHp-identity.damage,form=player.identity.form;form==="alterEgo"&&(!identity.exhausted&&identity.damage>0&&hpLeft*2<=profile.maxHp&&(yield{command:{type:"basicRecover",playerId}}),!player.identity.changedFormThisRound&&hpLeft*2>profile.maxHp&&(yield{command:{type:"changeForm",playerId}},yield*paidFormChanges(state,deps,playerId)));for(let id of player.hand){let c=card(state,id);if(!c||c.type==="resource"||!("cost"in c))continue;let action=actionAbility(deps,c);if(!(c.type==="event"&&!action))for(let payment of payments(state,deps,playerId,id,c.cost))for(let extra of playExtras(state,deps,playerId,id,c,action,payment))yield{command:{type:"playCard",playerId,cardInstanceId:id,payment,attachToInstanceId:extra.attachTo,...extra.costChoices?{costChoices:extra.costChoices}:{}}}}for(let id of cardsInPlay(state)){let controller=controllerOf(state,id);if(!(controller!==null&&controller!==playerId))for(let ability of liveRefs(state,id)){let definition=deps.abilities[ability];if(definition?.trigger.kind!=="action")continue;let memo=`${id}:${ability}`;if(memory.used.has(memo))continue;let choices=definition.cost?.discardFromHand?{discard:player.hand.slice(0,definition.cost.discardFromHand.min)}:void 0;for(let payment of payments(state,deps,playerId,null,0,definition))yield{memo,command:{type:"useAbility",playerId,cardInstanceId:id,abilityId:ability,payment,...choices?{costChoices:choices}:{}}}}}let stage=mainSchemeStage(state),target=scale(stage.targetThreat,state.startingPlayerCount),mainThreat=getInstance(state,state.mainScheme.instanceId)?.threat??0,sideSchemes=schemesInPlay(state).filter(id=>id!==state.mainScheme.instanceId&&(getInstance(state,id)?.threat??0)>0),thwartFirst=mainThreat*2>=target||sideSchemes.length>0,thwartTarget=mainThreat*2>=target||sideSchemes.length===0?state.mainScheme.instanceId:sideSchemes[0],enemies=cardsInPlay(state).filter(id=>{let c=card(state,id);return isVillain(state,id)||c?.type==="minion"||getInstance(state,id)?.facedownAs}),attackers=[identityId,...player.playArea.filter(id=>card(state,id)?.type==="ally")];for(let attacker of attackers){if(!!getInstance(state,attacker)?.exhausted||attacker===identityId&&form!=="hero")continue;let thwart={command:{type:"basicThwart",playerId,thwarterInstanceId:attacker,schemeInstanceId:thwartTarget}},attacks=enemies.filter(enemy=>canAttack(state,attacker,enemy,deps)).map(enemy=>({command:{type:"basicAttack",playerId,attackerInstanceId:attacker,targetInstanceId:enemy}}));thwartFirst?(yield thwart,yield*attacks):(yield*attacks,yield thwart)}form==="hero"&&!player.identity.changedFormThisRound&&hpLeft<=4&&(yield{command:{type:"changeForm",playerId}},yield*paidFormChanges(state,deps,playerId))}function*paidFormChanges(state,deps,playerId){let actions=legalActions(state,playerId,deps);if(actions.kind==="turn")for(let legal of actions.legal)legal.action.kind==="changeForm"&&legal.needsPayment&&(yield{command:legal.example})}function actionAbility(deps,c){if("abilities"in c)for(let ref of c.abilities){let definition=deps.abilities[ref.id];if(definition?.trigger.kind==="action")return definition}}function*payments(state,deps,playerId,playing,printedCost,ability){let player=getPlayer(state,playerId);if(!player)return;let fixed=ability?.cost?.resources,needed=printedCost+(typeof fixed=="number"?fixed:fixed?Object.values(fixed).reduce((a,b)=>a+(b??0),0):0),extra=ability?.cost?.resourcesX?1:0,abilityPayments=[];for(let id of cardsInPlay(state))if(controllerOf(state,id)===playerId)for(let ref of liveRefs(state,id))deps.abilities[ref]?.trigger.kind==="resource"&&abilityPayments.push({ability:{instanceId:id,abilityId:ref}});let hand=player.hand.filter(id=>id!==playing),byValue=[...hand].sort((a,b)=>+(card(state,b)?.type==="resource")-+(card(state,a)?.type==="resource")),total=needed+extra;if(total===0){yield[];return}let tried=new Set,offer=payment=>{let key=JSON.stringify(payment);return tried.has(key)?!1:(tried.add(key),!0)};for(let order of[byValue,hand]){let sum=0,picks=[];for(let id of order)if(picks.push({fromHand:id}),sum+=resourceValue(state,id),sum>=total)break;if(sum>=total&&offer(picks)&&(yield picks),sum>=total&&picks.length<order.length){let one=[...picks,{fromHand:order[picks.length]}];offer(one)&&(yield one)}}for(let ability2 of abilityPayments){let sum=1,picks=[ability2];for(let id of byValue){if(sum>=total)break;picks.push({fromHand:id}),sum+=resourceValue(state,id)}sum>=total&&offer(picks)&&(yield picks)}}function*playExtras(state,deps,playerId,id,c,action,payment){let reserved=new Set(payment.flatMap(p=>"fromHand"in p?[p.fromHand]:[])),spare=(getPlayer(state,playerId)?.hand??[]).filter(h=>h!==id&&!reserved.has(h)),costChoices={};if(action?.cost?.discardFromHand){let n=Math.max(action.cost.discardFromHand.min,Math.min(action.cost.discardFromHand.max??spare.length,spare.length,2));if(spare.length<n)return;costChoices.discard=spare.slice(0,n)}let pay=action?.cost?.payPrintedCostOf,pickSlots=pay?state.players.flatMap(p=>p.discard.filter(d=>card(state,d)?.type==="ally")).map(d=>({...costChoices,[pay.slot]:[d]})):[costChoices],hosts=c.type==="upgrade"&&c.attachesTo?cardsInPlay(state).filter(h=>getInstance(state,h)?.faceup!==void 0):[null];for(let choices of pickSlots)for(let host of hosts)yield Object.keys(choices).length>0?{attachTo:host,costChoices:choices}:{attachTo:host}}function answerChoice(state,choice){let ids=choice.options.map(o=>o.optionId),fewest=ids.slice(0,choice.minSelections);switch(choice.prompt.kind){case"mulligan":return[];case"takeStartingCard":return ids.slice(0,1);case"declareDefender":{let allies=ids.filter(id=>id!=="decline"&&card(state,id)?.type==="ally");if(allies[0])return[allies[0]];let attacked=choice.prompt.attack.targetCharacterInstanceId,identity=getInstance(state,attacked),profile=characterProfile(state,attacked);return(identity&&profile?profile.maxHp-identity.damage<=6:!1)&&ids.includes(attacked)?[attacked]:ids.includes("decline")?["decline"]:fewest}case"chooseTriggers":case"orderTriggers":case"orderSpecials":return ids.slice(0,Math.max(choice.minSelections,choice.maxSelections));case"payForAbility":return choice.prompt.chosenResources?spendUpTo(state,choice,choice.prompt.chosenResources):payFromOptions(state,choice,choice.prompt.cost,null);case"payForCard":return payFromOptions(state,choice,choice.prompt.cost,null);case"spendResources":{let r=choice.prompt.requirement;return payFromOptions(state,choice,(r.generic??0)+(r.physical??0)+(r.mental??0)+(r.energy??0),r)}case"divide":{let picked=[],cards=[];for(let id of ids){if(picked.length>=choice.prompt.amount)break;let cardId=id.slice(0,id.lastIndexOf("#"));if(!cards.includes(cardId)){if(choice.prompt.maxTargets!==void 0&&cards.length>=choice.prompt.maxTargets)continue;cards.push(cardId)}picked.push(id)}return picked}case"declareWildTypes":{let{wilds,pool,requirement,only}=choice.prompt,resolved={generic:requirement.generic??0,physical:requirement.physical??0,mental:requirement.mental??0,energy:requirement.energy??0,...requirement.wild===void 0?{}:{wild:requirement.wild}},declared=wildDeclarations(wilds).find(d=>wildDeclarationFault(pool,d,resolved,only)===null);return declared?declared.map((type,index)=>`${index}:${type}`):fewest}case"discardDownToHandSize":case"discardOverAllyLimit":case"discardOverPlayerSideSchemeLimit":case"discardRestricted":return fewest;default:return ids.slice(0,Math.min(Math.max(choice.minSelections,1),choice.maxSelections))}}function spendUpTo(state,choice,range){let picks=[],sum=0;for(let option of choice.options){let value=option.optionId.startsWith("ability:")?1:resourceValue(state,option.optionId.slice(5));value>0&&sum+value<=range.max&&(picks.push(option.optionId),sum+=value)}return sum>=range.min?picks:[]}function payFromOptions(state,choice,cost,typed){if(cost<=0)return[];let value=optionId=>optionId.startsWith("ability:")?1:resourceValue(state,optionId.slice(5)),matchesType=optionId=>{if(!typed||optionId.startsWith("ability:"))return optionId.startsWith("ability:");let c=card(state,optionId.slice(5));if(!c)return!1;let pool=printedResources(c);return pool.wild>0||["physical","mental","energy"].some(t=>(typed[t]??0)>0&&pool[t]>0)},ordered=choice.options.map(o=>o.optionId).sort((a,b)=>Number(matchesType(b))-Number(matchesType(a))),picks=[],sum=0;for(let optionId of ordered){if(sum>=cost)break;picks.push(optionId),sum+=value(optionId)}return sum>=cost?picks:[]}import{isDeepStrictEqual}from"node:util";var SMOKE_BASE_DECK="core-spider-man-justice",SMOKE_SCENARIOS=CORE_SCENARIOS.map(s=>String(s.id)),errorText=error=>error instanceof Error?error.message:String(error);function smokeSchedule(pack,options={}){let games=options.games??3,scenario=options.scenario??"rhino",maxCommands=options.maxCommands??4e3;if(!Number.isInteger(games)||games<1)throw new Error("games must be a whole number of at least 1");if(!SMOKE_SCENARIOS.includes(scenario))throw new Error(`unknown scenario "${scenario}" (one of ${SMOKE_SCENARIOS.join(", ")})`);let notes=[],plans=(pack.decks??[]).map(deck=>({name:String(deck.id),deck,scenario}));plans.length===0&&pack.cards.some(card2=>card2.type==="hero_identity")&¬es.push("the pack has a hero but no deck in decks/: add its precon so mc-pack test can play it");let ownScenarios=packScenarioRecords([pack]);for(let record of ownScenarios)plans.push({name:SMOKE_BASE_DECK,scenario:String(record.id)}),plans.push({name:SMOKE_BASE_DECK,scenario:String(record.id),difficulty:"expert"});let baseRecord=CORE_SCENARIOS.find(candidate=>String(candidate.id)===scenario);for(let set of baseRecord?packModularSetChoices(baseRecord,[pack]):[])plans.push({name:SMOKE_BASE_DECK,scenario,modularSet:String(set.id),modularSetIds:[String(set.id)]});return plans.length===0&&(notes.push(`the pack has no hero deck, scenario or modular set of its own, so a base precon (${SMOKE_BASE_DECK}) played ${scenario} with the pack's cards in the pool`),plans.push({name:SMOKE_BASE_DECK,scenario})),{scenario,games,maxCommands,plans,campaigns:packCampaignRecords([pack]),notes}}var packCardsIn=(events,prefix)=>[...new Set(events.flatMap(e=>(e.type==="cardPlayed"||e.type==="encounterCardRevealed")&&String(e.cardId).startsWith(prefix)?[String(e.cardId)]:[]))];function playSmokeGame(pack,deps,plan,seed,maxCommands=4e3){let base={deck:plan.name,scenario:plan.scenario,...plan.modularSet?{modularSet:plan.modularSet}:{},...plan.difficulty?{difficulty:plan.difficulty}:{},seed};try{let seat=plan.deck?{identityCardId:plan.deck.identityCardId,...plan.deck.aspects?{aspects:plan.deck.aspects}:{},deck:plan.deck.cards.flatMap(({cardId,quantity})=>Array.from({length:quantity},()=>cardId))}:{starterDeckId:SMOKE_BASE_DECK},config=scenarioWithPacks(plan.scenario,{players:[seat],seed,difficulty:plan.difficulty??"standard",...plan.modularSetIds?{modularSetIds:plan.modularSetIds}:{}},[pack]),created=createGame(config,deps);if(!created.ok)throw new Error(`setup failed: ${created.error.message}`);let run=playToOutcome(created.state,deps,{maxCommands}),state=run.session.state,replayed=replay(run.session.log,deps),error;return run.outcome===null?error=`stuck: no outcome after ${run.commands} commands (round ${run.rounds})`:state.pendingChoice!==null?error="a prompt was still open when the game ended":replayed.ok?isDeepStrictEqual(replayed.state,state)||(error="the game's log replays to a different state"):error=`the game's log does not replay: ${replayed.error.message}`,{...base,rounds:run.rounds,commands:run.commands,ok:error===void 0,...run.outcome?{outcome:`${run.outcome.result} (${run.outcome.reason})`}:{},...error!==void 0?{error}:{},packCardsPlayed:replayed.ok?packCardsIn(replayed.events,`x.${pack.manifest.id}.`):[]}}catch(caught){return{...base,ok:!1,rounds:0,commands:0,error:errorText(caught),packCardsPlayed:[]}}}function smokeTestCampaign(pack,campaign,deps,options={}){let seeds=options.games??3,games=[],notes=[`campaign ${campaign.id}: ${CAMPAIGN_DRIVER_LIMITS}`],lostAt=[];for(let seed=1;seed<=seeds;seed++){let run=playCampaign(pack,campaign,seed,deps,options.maxCommands??4e3);lostAt.push(run.lostAt),notes.push(...run.notes);for(let game of run.games)games.push(game),options.onGame?.(game)}let first=lostAt[0];if(options.failOnAlwaysLost&&first!==null&&first!==void 0&&lostAt.every(node=>node===first)){let failed={deck:SMOKE_BASE_DECK,scenario:campaign.record.scenarioIds[campaign.definition.graph.nodes.findIndex(n=>n.id===first)]??"",campaign:campaign.id,node:first,seed:0,ok:!1,rounds:0,commands:0,error:`every seed lost at node "${first}": the greedy driver never won it, so the later nodes were reached only with staged wins`,packCardsPlayed:[]};games.push(failed),options.onGame?.(failed)}return{games,notes}}function smokeTestPack(pack,options={}){let schedule=smokeSchedule(pack,options),notes=[...schedule.notes],deps=gameDepsWithPack(PLAYABLE_DEPS,pack),results=[],record=game=>{results.push(game),options.onGame?.(game)};for(let plan of schedule.plans)for(let seed=1;seed<=schedule.games;seed++)record(playSmokeGame(pack,deps,plan,seed,schedule.maxCommands));for(let campaign of schedule.campaigns){let run=smokeTestCampaign(pack,campaign,deps,{...options,games:schedule.games});notes.push(...run.notes),results.push(...run.games)}return results.length>0&&results.every(game=>game.packCardsPlayed.length===0)&¬es.push("no game played or revealed one of the pack's own cards; try more games (--games)"),{ok:results.every(g=>g.ok),scenario:schedule.scenario,games:results,notes}}var CAMPAIGN_DRIVER_LIMITS="the greedy driver wins or loses on its own, so a Defeat block runs only if a game is lost (and a node that is always won never runs it); optional between-games choices are declined; every other choice takes its first options; and an instruction behind a `when` gate or mode that is false in these runs is not exercised";function settleCampaign(step){let answers=[];for(let guard=0;guard<64;guard++){let result=step(answers);if(result.kind==="done")return result.value;let{instructionId,slot,seatNumber,optional,options,count}=result.choice;answers.push({instructionId,slot,seatNumber,picked:optional?[]:options.slice(0,count)})}throw new Error("the campaign runner kept asking questions")}var hasWrittenField=log=>Object.keys(log.shared).length>0||log.seats.some(seat=>Object.keys(seat.fields).length>0);function playCampaign(pack,campaign,seed,deps,maxCommands){let definition=campaign.definition,games=[],notes=[],lostAt=null,budget=definition.graph.nodes.length*3+2,failure=(node,scenario2,error)=>({deck:SMOKE_BASE_DECK,scenario:scenario2,campaign:campaign.id,node,seed,ok:!1,rounds:0,commands:0,error,packCardsPlayed:[]}),starter=CORE_STARTER_DECKS.find(deck=>String(deck.id)===SMOKE_BASE_DECK);if(!starter)throw new Error(`no starter deck "${SMOKE_BASE_DECK}"`);let prefix=`x.${pack.manifest.id}.`,campaignDeps=campaignDepsWithPacks(PLAYABLE_CARDS,[pack]),nodeId="(start)",scenario="(campaign)";try{let log=createCampaignLog(definition,{id:`smoke-${campaign.id}-${seed}`,seats:[{seatNumber:1,identityCardId:starter.identityCardId,deck:{identityCardId:starter.identityCardId,aspects:starter.aspects,cards:starter.cards}}],modes:{campaign:{campaignId:definition.campaignId}},poolVersion:"smoke",seed});for(let turn=0;turn<budget&&log.status==="active";turn++){let before=log,composed=settleCampaign(answers=>resolveBetweenGames(definition,before,campaignDeps,before.modes,answers)),start=startGameFromLog(definition,composed);nodeId=start.nodeId,scenario=String(start.scenarioId);let created=createGame(campaignGameWithPacks(start,[pack]),deps);if(!created.ok)throw new Error(`setup failed: ${created.error.message}`);let run=playToOutcome(created.state,deps,{maxCommands}),state=run.session.state,replayed=replay(run.session.log,deps),error;run.outcome===null?error=`stuck: no outcome after ${run.commands} commands (round ${run.rounds})`:state.pendingChoice!==null?error="a prompt was still open when the game ended":replayed.ok?isDeepStrictEqual(replayed.state,state)||(error="the game's log replays to a different state"):error=`the game's log does not replay: ${replayed.error.message}`;let events=replayed.ok?replayed.events:[],played=[...new Set(events.flatMap(e=>(e.type==="cardPlayed"||e.type==="encounterCardRevealed")&&String(e.cardId).startsWith(prefix)?[String(e.cardId)]:[]))];if(games.push({deck:SMOKE_BASE_DECK,scenario,campaign:campaign.id,node:nodeId,seed,ok:error===void 0,...run.outcome?{outcome:`${run.outcome.result} (${run.outcome.reason})`}:{},...error!==void 0?{error}:{},rounds:run.rounds,commands:run.commands,packCardsPlayed:played}),error!==void 0)return{games,notes,lostAt};let result=campaignResultOf(definition,composed,state,events,deps);if(log=settleCampaign(answers=>applyCampaignResult(definition,composed,result,{at:1},campaignDeps,answers)),result.outcome==="lost"&&(lostAt??=nodeId),result.outcome==="lost"&&log.status==="active"){let lost=log,again=settleCampaign(answers=>resolveBetweenGames(definition,lost,campaignDeps,lost.modes,answers)),staged={...state,outcome:{result:"win",reason:"villainDefeated"},campaignWrites:{logWrites:[],removedFromCampaign:[]}},stagedResult=campaignResultOf(definition,again,staged,events,deps);log=settleCampaign(answers=>applyCampaignResult(definition,again,stagedResult,{at:1},campaignDeps,answers)),notes.push(`campaign ${campaign.id} seed ${seed}: lost at "${nodeId}", then advanced with a staged win`)}}log.status==="active"?games.push(failure(nodeId,scenario,`the campaign was still open after ${budget} games`)):definition.logFields.length>0&&!hasWrittenField(log)&&games.push(failure(nodeId,scenario,"the campaign ended with none of its log fields written"))}catch(caught){games.push(failure(nodeId,scenario,errorText(caught)))}return{games,notes,lostAt}}export{playToOutcome,SMOKE_BASE_DECK,SMOKE_SCENARIOS,smokeTestPack};
|
package/dist/mc-pack.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{src_exports}from"./chunks/chunk-3YMCANI3.js";import{formatImportReport,importMarvelCdbPack}from"./chunks/chunk-DX44O32N.js";import{PackBuildError,assemblePack,buildPack,loadPackSource}from"./chunks/chunk-WFEXO5DU.js";import{publishIssues,readPackInput,splitIssues,validatePack}from"./chunks/chunk-3SR23UJ7.js";import{SMOKE_BASE_DECK,SMOKE_SCENARIOS,smokeTestPack}from"./chunks/chunk-
|
|
2
|
+
import{src_exports}from"./chunks/chunk-3YMCANI3.js";import{formatImportReport,importMarvelCdbPack}from"./chunks/chunk-DX44O32N.js";import{PackBuildError,assemblePack,buildPack,loadPackSource}from"./chunks/chunk-WFEXO5DU.js";import{publishIssues,readPackInput,splitIssues,validatePack}from"./chunks/chunk-3SR23UJ7.js";import{SMOKE_BASE_DECK,SMOKE_SCENARIOS,smokeTestPack}from"./chunks/chunk-7NRC6TLV.js";import"./chunks/chunk-S3JH4WL4.js";import"./chunks/chunk-ACT4TJXC.js";import{existsSync as existsSync2}from"node:fs";import{join as join2,resolve as resolve2}from"node:path";import{createJiti}from"jiti";function sdkModuleNames(){let published="@champions-digital-game/mod-sdk";return published&&published!=="@mc/mod-sdk"?["@mc/mod-sdk",published]:["@mc/mod-sdk"]}function packModuleImporter(){let virtualModules=Object.fromEntries(sdkModuleNames().map(name=>[name,src_exports]));return path=>createJiti(path,{virtualModules,fsCache:!1,moduleCache:!1,interopDefault:!1}).import(path)}import{spawnSync}from"node:child_process";import{existsSync,mkdtempSync,readFileSync,readdirSync,rmSync,statSync,writeFileSync}from"node:fs";import{createRequire}from"node:module";import{tmpdir}from"node:os";import{dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import{fileURLToPath}from"node:url";var TypecheckUnavailableError=class extends Error{};function nearestPackage(from){for(let dir=from;;dir=dirname(dir)){let file=join(dir,"package.json");if(existsSync(file))return{dir,json:JSON.parse(readFileSync(file,"utf8"))};if(dirname(dir)===dir)return}}var HERE=dirname(fileURLToPath(import.meta.url));function sdkTypesEntry(){let pkg=nearestPackage(HERE),types=pkg?.json.types;if(!pkg||typeof types!="string")throw new TypecheckUnavailableError("cannot find the SDK's own type entry");let entry=join(pkg.dir,types);if(!existsSync(entry))throw new TypecheckUnavailableError(`the SDK's type entry ${entry} is missing`);return entry}function findTsc(packDir2){for(let from of[join(HERE,"package.json"),join(packDir2,"package.json")])try{let manifest=createRequire(from).resolve("typescript/package.json"),bin=JSON.parse(readFileSync(manifest,"utf8")).bin?.tsc;if(bin)return join(dirname(manifest),bin)}catch{}throw new TypecheckUnavailableError("TypeScript is not installed, so the pack's abilities cannot be type-checked: install the SDK's dependencies (npm ci), add typescript to the pack's devDependencies, or pass --skip-typecheck")}var hasTypeScript=dir=>readdirSync(dir).some(name=>{let full=join(dir,name);return statSync(full).isDirectory()?name!=="node_modules"&&hasTypeScript(full):/\.[cm]?ts$/.test(name)}),DIAGNOSTIC=/^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/,GLOBAL_ERROR=/^error (TS\d+): (.*)$/;function typecheckPack(packDir2,options={}){let root=resolve(packDir2),abilitiesDir=join(root,"abilities");if(!existsSync(abilitiesDir)||!hasTypeScript(abilitiesDir))return[];let tsc=options.tsc??findTsc(root),sdkTypes=options.sdkTypes??sdkTypesEntry(),slash=path=>path.split(sep).join("/"),work=mkdtempSync(join(tmpdir(),"mc-pack-typecheck-"));try{let config={compilerOptions:{target:"es2022",module:"preserve",moduleResolution:"bundler",lib:["es2023","dom"],strict:!0,noEmit:!0,allowImportingTsExtensions:!0,skipLibCheck:!0,types:[],paths:Object.fromEntries(sdkModuleNames().map(name=>[name,[slash(sdkTypes)]]))},include:[`${slash(abilitiesDir)}/**/*.ts`,`${slash(abilitiesDir)}/**/*.mts`,`${slash(abilitiesDir)}/**/*.cts`]},project=join(work,"tsconfig.json");writeFileSync(project,JSON.stringify(config,null,2));let run=spawnSync(process.execPath,[tsc,"-p",project,"--pretty","false"],{cwd:root,encoding:"utf8",maxBuffer:64*1024*1024});if(run.error)throw new TypecheckUnavailableError(`tsc failed to run: ${run.error.message}`);let lines=`${run.stdout??""}${run.stderr??""}`.split(/\r?\n/),issues=[],globals=[],open=-1;for(let line of lines){let diagnostic=DIAGNOSTIC.exec(line);if(diagnostic){let[,file,row,col,code,message]=diagnostic,rel=relative(root,resolve(root,file));open=!rel.startsWith("..")&&!isAbsolute(rel)&&!rel.split(sep).includes("node_modules")?issues.push({path:`${slash(rel)}:${row}:${col}`,message:`${code}: ${message}`})-1:-1;continue}let global=GLOBAL_ERROR.exec(line);if(global)globals.push(`${global[1]}: ${global[2]}`),open=-1;else if(open>=0&&/^\s+\S/.test(line)){let issue=issues[open];issues[open]={...issue,message:`${issue.message} ${line.trim()}`}}}if(globals.length>0)throw new TypecheckUnavailableError(`tsc could not check the pack: ${globals.join("; ")}`);if(run.status!==0&&!lines.some(line=>DIAGNOSTIC.test(line))){let head=lines.filter(Boolean).slice(0,5).join(" ");throw new TypecheckUnavailableError(`tsc exited ${run.status??run.signal}: ${head||"no output"}`)}return issues}finally{rmSync(work,{recursive:!0,force:!0})}}var EXIT_OK=0,EXIT_PACK_PROBLEM=1,EXIT_USAGE=2,consoleIo={out:line=>process.stdout.write(`${line}
|
|
3
3
|
`),err:line=>process.stderr.write(`${line}
|
|
4
4
|
`)},USAGE=`mc-pack: build, check and test Marvel Champions Digital content packs
|
|
5
5
|
|
|
@@ -25,4 +25,4 @@ validate, build and test run the pack's own code: they import its abilities/inde
|
|
|
25
25
|
user's access to files, the network and the environment. Run them only on a pack you trust, or in a sandbox (a CI
|
|
26
26
|
job with no secrets).
|
|
27
27
|
|
|
28
|
-
Exit codes: 0 success, 1 the pack has a problem, 2 usage error.`,UsageError=class extends Error{},VALUE_FLAGS=new Set(["out","games","scenario","max-commands","id","app"]),BOOLEAN_FLAGS=new Set(["allow-unscripted","publish","skip-typecheck","help","version"]);function parseArgs(argv){let positional=[],flags=new Map;for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="-h")flags.set("help",!0);else if(arg==="-v")flags.set("version",!0);else if(arg.startsWith("--")){let eq=arg.indexOf("="),name=eq<0?arg.slice(2):arg.slice(2,eq);if(BOOLEAN_FLAGS.has(name)){if(eq>=0)throw new UsageError(`--${name} takes no value`);flags.set(name,!0)}else if(VALUE_FLAGS.has(name)){let value2=eq>=0?arg.slice(eq+1):argv[++i];if(value2===void 0||value2==="")throw new UsageError(`--${name} needs a value`);flags.set(name,value2)}else throw new UsageError(`unknown option --${name}`)}else positional.push(arg)}return{positional,flags}}var value=(parsed,name)=>{let v=parsed.flags.get(name);return typeof v=="string"?v:void 0};function positiveInt(parsed,name){let raw=value(parsed,name);if(raw===void 0)return;let n=Number(raw);if(!Number.isInteger(n)||n<1)throw new UsageError(`--${name} must be a whole number of at least 1`);return n}function packDir(parsed,command){let[dir,...extra]=parsed.positional;if(dir===void 0)throw new UsageError(`${command} needs a folder`);if(extra.length>0)throw new UsageError(`${command} takes one folder, got ${parsed.positional.length}`);let full=resolve2(dir);if(!existsSync2(full))throw new UsageError(`${dir}: no such folder`);return full}function allowOnly(parsed,command,allowed){for(let name of parsed.flags.keys())if(!allowed.includes(name))throw new UsageError(`${command} does not take --${name}`)}var errorText=error=>error instanceof Error?error.message:String(error);async function loadBuilt(dir){let pack=assemblePack(await loadPackSource(dir,{importModule:packModuleImporter()}));return readPackInput(pack.manifest,pack.files)}function formatIssues(issues){let{defects,unscripted}=splitIssues(issues),lines=[];if(defects.length>0){lines.push(`${defects.length} problem${defects.length===1?"":"s"}:`);for(let issue of defects)lines.push(` ${issue.path}: ${issue.message}`)}if(unscripted.length>0){lines.push(`${unscripted.length} unscripted abilit${unscripted.length===1?"y":"ies"} (write them in abilities/):`);for(let issue of unscripted)lines.push(` ${issue.path}: ${issue.message}`)}return lines}async function validateCommand(parsed,io){allowOnly(parsed,"validate",["allow-unscripted","publish","skip-typecheck"]);let dir=packDir(parsed,"validate"),typeIssues=parsed.flags.has("skip-typecheck")?[]:typecheckPack(dir),pack;try{pack=await loadBuilt(dir)}catch(error){if(typeIssues.length===0)throw error;io.err(`mc-pack validate: ${errorText(error)}`);for(let line of formatIssues(typeIssues))io.err(line);return EXIT_PACK_PROBLEM}let publish=parsed.flags.has("publish"),draft=existsSync2(join2(dir,"DRAFT"));publish&&draft&&io.out(`${pack.manifest.id}: a DRAFT, never published; the publish check is skipped`);let issues=[...typeIssues,...validatePack(pack),...publish&&!draft?publishIssues(pack.manifest):[]],{defects,unscripted}=splitIssues(issues),name=`${pack.manifest.id}@${pack.manifest.version}`;if(issues.length===0)return io.out(`${name}: valid (${pack.cards.length} cards, ${Object.keys(pack.abilities).length} abilities)`),EXIT_OK;let lines=formatIssues(issues);if(defects.length===0&&parsed.flags.has("allow-unscripted")){io.out(`${name}: valid, ${unscripted.length} abilit${unscripted.length===1?"y":"ies"} to script`);for(let line of lines)io.out(line);return EXIT_OK}io.err(`${name}: invalid`);for(let line of lines)io.err(line);return EXIT_PACK_PROBLEM}async function buildCommand(parsed,io){allowOnly(parsed,"build",["out"]);let dir=packDir(parsed,"build"),out=value(parsed,"out");if(out===void 0)throw new UsageError("build needs --out <dir>");try{let result=await buildPack(dir,resolve2(out),{importModule:packModuleImporter()}),{manifest}=result;return io.out(`${manifest.id}@${manifest.version}: built ${result.zipPath}`),io.out(` ${result.zipBytes} bytes, sha256 ${result.zipSha256}`),io.out(` ${manifest.files.length} files, ${manifest.totalBytes} bytes unzipped`),io.out(` requires app ${manifest.requires.app}; DSL features: ${manifest.requires.dslFeatures.join(", ")||"none"}`),EXIT_OK}catch(error){if(!(error instanceof PackBuildError))throw error;io.err("build failed: the pack is invalid");for(let line of formatIssues(error.issues))io.err(line);return EXIT_PACK_PROBLEM}}var describeGame=game=>{let where=game.deck===SMOKE_BASE_DECK?` at ${game.campaign?`${game.campaign}/${game.node} (${game.scenario})`:game.scenario}${game.modularSet?` with ${game.modularSet}`:""}${game.difficulty?`, ${game.difficulty}`:""}`:"",head=` ${game.deck}${where} seed ${game.seed}: `;if(!game.ok)return`${head}FAILED: ${game.error??"unknown error"}`;let played=game.packCardsPlayed.length>0?`; pack cards played or revealed: ${game.packCardsPlayed.join(", ")}`:"";return`${head}${game.outcome??"ended"} in round ${game.rounds} (${game.commands} commands)${played}`};async function testCommand(parsed,io){allowOnly(parsed,"test",["games","scenario","max-commands"]);let dir=packDir(parsed,"test"),scenario=value(parsed,"scenario")??"rhino";if(!SMOKE_SCENARIOS.includes(scenario))throw new UsageError(`--scenario must be one of ${SMOKE_SCENARIOS.join(", ")}`);let games=positiveInt(parsed,"games")??3,maxCommands=positiveInt(parsed,"max-commands"),pack=await loadBuilt(dir),issues=validatePack(pack);if(issues.length>0){io.err(`${pack.manifest.id}: not tested, the pack is invalid (run mc-pack validate)`);for(let line of formatIssues(issues))io.err(line);return EXIT_PACK_PROBLEM}io.out(`${pack.manifest.id}@${pack.manifest.version}: ${games} game(s) per deck, scenario and modular set (Core scenario: ${scenario})`);let result=smokeTestPack(pack,{games,scenario,...maxCommands!==void 0?{maxCommands}:{},onGame:game=>(game.ok?io.out:io.err)(describeGame(game))});for(let note of result.notes)io.out(`note: ${note}`);let failed=result.games.filter(g=>!g.ok).length;return failed>0?(io.err(`${failed} of ${result.games.length} game(s) failed`),EXIT_PACK_PROBLEM):(io.out(`all ${result.games.length} game(s) passed`),EXIT_OK)}async function importCommand(parsed,io){allowOnly(parsed,"import-marvelcdb",["out","id","app"]);let src=packDir(parsed,"import-marvelcdb"),out=value(parsed,"out"),packId=value(parsed,"id"),app=value(parsed,"app"),report=await importMarvelCdbPack(src,{...out!==void 0?{outDir:resolve2(out)}:{},...packId!==void 0?{packId}:{},...app!==void 0?{app}:{}}),text=formatImportReport(report);if(!report.normalized||report.validationIssues.length>0)return io.err(text),EXIT_PACK_PROBLEM;if(io.out(text),report.unscriptedIssues.length>0){io.out(`${report.unscriptedIssues.length} abilities to script, listed in abilities/index.ts:`);for(let issue of report.unscriptedIssues)io.out(` ${issue.path}: ${issue.message}`)}return io.out(report.outDir?`written to ${report.outDir}`:"dry run: nothing written (pass --out <dir>)"),EXIT_OK}var COMMANDS={validate:validateCommand,build:buildCommand,test:testCommand,"import-marvelcdb":importCommand};async function runCli(argv,io=consoleIo){let[command,...rest]=argv;try{if(command===void 0||command==="--help"||command==="-h"||command==="help")return io.out(USAGE),command===void 0?EXIT_USAGE:EXIT_OK;if(command==="--version"||command==="-v")return io.out("0.
|
|
28
|
+
Exit codes: 0 success, 1 the pack has a problem, 2 usage error.`,UsageError=class extends Error{},VALUE_FLAGS=new Set(["out","games","scenario","max-commands","id","app"]),BOOLEAN_FLAGS=new Set(["allow-unscripted","publish","skip-typecheck","help","version"]);function parseArgs(argv){let positional=[],flags=new Map;for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="-h")flags.set("help",!0);else if(arg==="-v")flags.set("version",!0);else if(arg.startsWith("--")){let eq=arg.indexOf("="),name=eq<0?arg.slice(2):arg.slice(2,eq);if(BOOLEAN_FLAGS.has(name)){if(eq>=0)throw new UsageError(`--${name} takes no value`);flags.set(name,!0)}else if(VALUE_FLAGS.has(name)){let value2=eq>=0?arg.slice(eq+1):argv[++i];if(value2===void 0||value2==="")throw new UsageError(`--${name} needs a value`);flags.set(name,value2)}else throw new UsageError(`unknown option --${name}`)}else positional.push(arg)}return{positional,flags}}var value=(parsed,name)=>{let v=parsed.flags.get(name);return typeof v=="string"?v:void 0};function positiveInt(parsed,name){let raw=value(parsed,name);if(raw===void 0)return;let n=Number(raw);if(!Number.isInteger(n)||n<1)throw new UsageError(`--${name} must be a whole number of at least 1`);return n}function packDir(parsed,command){let[dir,...extra]=parsed.positional;if(dir===void 0)throw new UsageError(`${command} needs a folder`);if(extra.length>0)throw new UsageError(`${command} takes one folder, got ${parsed.positional.length}`);let full=resolve2(dir);if(!existsSync2(full))throw new UsageError(`${dir}: no such folder`);return full}function allowOnly(parsed,command,allowed){for(let name of parsed.flags.keys())if(!allowed.includes(name))throw new UsageError(`${command} does not take --${name}`)}var errorText=error=>error instanceof Error?error.message:String(error);async function loadBuilt(dir){let pack=assemblePack(await loadPackSource(dir,{importModule:packModuleImporter()}));return readPackInput(pack.manifest,pack.files)}function formatIssues(issues){let{defects,unscripted}=splitIssues(issues),lines=[];if(defects.length>0){lines.push(`${defects.length} problem${defects.length===1?"":"s"}:`);for(let issue of defects)lines.push(` ${issue.path}: ${issue.message}`)}if(unscripted.length>0){lines.push(`${unscripted.length} unscripted abilit${unscripted.length===1?"y":"ies"} (write them in abilities/):`);for(let issue of unscripted)lines.push(` ${issue.path}: ${issue.message}`)}return lines}async function validateCommand(parsed,io){allowOnly(parsed,"validate",["allow-unscripted","publish","skip-typecheck"]);let dir=packDir(parsed,"validate"),typeIssues=parsed.flags.has("skip-typecheck")?[]:typecheckPack(dir),pack;try{pack=await loadBuilt(dir)}catch(error){if(typeIssues.length===0)throw error;io.err(`mc-pack validate: ${errorText(error)}`);for(let line of formatIssues(typeIssues))io.err(line);return EXIT_PACK_PROBLEM}let publish=parsed.flags.has("publish"),draft=existsSync2(join2(dir,"DRAFT"));publish&&draft&&io.out(`${pack.manifest.id}: a DRAFT, never published; the publish check is skipped`);let issues=[...typeIssues,...validatePack(pack),...publish&&!draft?publishIssues(pack.manifest):[]],{defects,unscripted}=splitIssues(issues),name=`${pack.manifest.id}@${pack.manifest.version}`;if(issues.length===0)return io.out(`${name}: valid (${pack.cards.length} cards, ${Object.keys(pack.abilities).length} abilities)`),EXIT_OK;let lines=formatIssues(issues);if(defects.length===0&&parsed.flags.has("allow-unscripted")){io.out(`${name}: valid, ${unscripted.length} abilit${unscripted.length===1?"y":"ies"} to script`);for(let line of lines)io.out(line);return EXIT_OK}io.err(`${name}: invalid`);for(let line of lines)io.err(line);return EXIT_PACK_PROBLEM}async function buildCommand(parsed,io){allowOnly(parsed,"build",["out"]);let dir=packDir(parsed,"build"),out=value(parsed,"out");if(out===void 0)throw new UsageError("build needs --out <dir>");try{let result=await buildPack(dir,resolve2(out),{importModule:packModuleImporter()}),{manifest}=result;return io.out(`${manifest.id}@${manifest.version}: built ${result.zipPath}`),io.out(` ${result.zipBytes} bytes, sha256 ${result.zipSha256}`),io.out(` ${manifest.files.length} files, ${manifest.totalBytes} bytes unzipped`),io.out(` requires app ${manifest.requires.app}; DSL features: ${manifest.requires.dslFeatures.join(", ")||"none"}`),EXIT_OK}catch(error){if(!(error instanceof PackBuildError))throw error;io.err("build failed: the pack is invalid");for(let line of formatIssues(error.issues))io.err(line);return EXIT_PACK_PROBLEM}}var describeGame=game=>{let where=game.deck===SMOKE_BASE_DECK?` at ${game.campaign?`${game.campaign}/${game.node} (${game.scenario})`:game.scenario}${game.modularSet?` with ${game.modularSet}`:""}${game.difficulty?`, ${game.difficulty}`:""}`:"",head=` ${game.deck}${where} seed ${game.seed}: `;if(!game.ok)return`${head}FAILED: ${game.error??"unknown error"}`;let played=game.packCardsPlayed.length>0?`; pack cards played or revealed: ${game.packCardsPlayed.join(", ")}`:"";return`${head}${game.outcome??"ended"} in round ${game.rounds} (${game.commands} commands)${played}`};async function testCommand(parsed,io){allowOnly(parsed,"test",["games","scenario","max-commands"]);let dir=packDir(parsed,"test"),scenario=value(parsed,"scenario")??"rhino";if(!SMOKE_SCENARIOS.includes(scenario))throw new UsageError(`--scenario must be one of ${SMOKE_SCENARIOS.join(", ")}`);let games=positiveInt(parsed,"games")??3,maxCommands=positiveInt(parsed,"max-commands"),pack=await loadBuilt(dir),issues=validatePack(pack);if(issues.length>0){io.err(`${pack.manifest.id}: not tested, the pack is invalid (run mc-pack validate)`);for(let line of formatIssues(issues))io.err(line);return EXIT_PACK_PROBLEM}io.out(`${pack.manifest.id}@${pack.manifest.version}: ${games} game(s) per deck, scenario and modular set (Core scenario: ${scenario})`);let result=smokeTestPack(pack,{games,scenario,...maxCommands!==void 0?{maxCommands}:{},onGame:game=>(game.ok?io.out:io.err)(describeGame(game))});for(let note of result.notes)io.out(`note: ${note}`);let failed=result.games.filter(g=>!g.ok).length;return failed>0?(io.err(`${failed} of ${result.games.length} game(s) failed`),EXIT_PACK_PROBLEM):(io.out(`all ${result.games.length} game(s) passed`),EXIT_OK)}async function importCommand(parsed,io){allowOnly(parsed,"import-marvelcdb",["out","id","app"]);let src=packDir(parsed,"import-marvelcdb"),out=value(parsed,"out"),packId=value(parsed,"id"),app=value(parsed,"app"),report=await importMarvelCdbPack(src,{...out!==void 0?{outDir:resolve2(out)}:{},...packId!==void 0?{packId}:{},...app!==void 0?{app}:{}}),text=formatImportReport(report);if(!report.normalized||report.validationIssues.length>0)return io.err(text),EXIT_PACK_PROBLEM;if(io.out(text),report.unscriptedIssues.length>0){io.out(`${report.unscriptedIssues.length} abilities to script, listed in abilities/index.ts:`);for(let issue of report.unscriptedIssues)io.out(` ${issue.path}: ${issue.message}`)}return io.out(report.outDir?`written to ${report.outDir}`:"dry run: nothing written (pass --out <dir>)"),EXIT_OK}var COMMANDS={validate:validateCommand,build:buildCommand,test:testCommand,"import-marvelcdb":importCommand};async function runCli(argv,io=consoleIo){let[command,...rest]=argv;try{if(command===void 0||command==="--help"||command==="-h"||command==="help")return io.out(USAGE),command===void 0?EXIT_USAGE:EXIT_OK;if(command==="--version"||command==="-v")return io.out("0.54.0"),EXIT_OK;let run=COMMANDS[command];if(!run)throw new UsageError(`unknown command "${command}"`);let parsed=parseArgs(rest);return parsed.flags.has("help")?(io.out(USAGE),EXIT_OK):await run(parsed,io)}catch(error){return error instanceof UsageError?(io.err(`mc-pack: ${error.message}`),io.err("run mc-pack --help for usage"),EXIT_USAGE):(io.err(`mc-pack ${command}: ${errorText(error)}`),EXIT_PACK_PROBLEM)}}process.exitCode=await runCli(process.argv.slice(2));
|
package/dist/testing.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SMOKE_BASE_DECK,SMOKE_SCENARIOS,playToOutcome,smokeTestPack}from"./chunks/chunk-
|
|
1
|
+
import{SMOKE_BASE_DECK,SMOKE_SCENARIOS,playToOutcome,smokeTestPack}from"./chunks/chunk-7NRC6TLV.js";import"./chunks/chunk-S3JH4WL4.js";import"./chunks/chunk-ACT4TJXC.js";export{SMOKE_BASE_DECK,SMOKE_SCENARIOS,playToOutcome,smokeTestPack};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@champions-digital-game/mod-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.54.0",
|
|
4
4
|
"description": "The mod SDK for Marvel Champions Digital content packs: the pack schema, the ability DSL, and the mc-pack validate, build, test and import-marvelcdb tools.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"card-game",
|
|
@@ -3,7 +3,7 @@ export declare const CONTENT_VERSION = "0.0.0";
|
|
|
3
3
|
* Schema version for the card data shape itself (independent of how many
|
|
4
4
|
* cards/cycles have been ingested). Bump when a breaking shape change lands.
|
|
5
5
|
*/
|
|
6
|
-
export declare const SCHEMA_VERSION = "0.
|
|
6
|
+
export declare const SCHEMA_VERSION = "0.54.0";
|
|
7
7
|
export * from "./schema/index.js";
|
|
8
8
|
export * from "./data/index.js";
|
|
9
9
|
export * from "./import/index.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare const ENGINE_VERSION = "0.
|
|
1
|
+
export declare const ENGINE_VERSION = "0.54.0";
|
|
2
2
|
export type { PlayerId, InstanceId, ChoiceId, EncounterDeckId, FrameId, GroupId, TeamId } from "./ids.js";
|
|
3
3
|
export { playerId, instanceId, choiceId, encounterDeckId, frameId, groupId, teamId } from "./ids.js";
|
|
4
4
|
export type { GroupRef, PodNeutralArea, PodNeutralSetup, PodSetup, PodState, SharedEvent, SharedPodState, SharedResult, SharedThreatCause, } from "./pod.js";
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type StarterDeck } from "../../content/src/index.js";
|
|
1
2
|
import { type EngineDeps } from "../../engine/src/index.js";
|
|
2
3
|
import type { PackCampaign } from "./campaigns.js";
|
|
3
4
|
import type { PackInput } from "./validate.js";
|
|
@@ -50,6 +51,49 @@ export interface SmokeResult {
|
|
|
50
51
|
/** Not failures: what the run could not cover (a hero with no deck, no pack card played). */
|
|
51
52
|
readonly notes: readonly string[];
|
|
52
53
|
}
|
|
54
|
+
/** One kind of smoke game: who sits, at which scenario, with which modular pick. Each is played once per seed. */
|
|
55
|
+
export interface SmokePlan {
|
|
56
|
+
/** The deck seated: a pack precon's id, or the base precon's. */
|
|
57
|
+
readonly name: string;
|
|
58
|
+
/** The pack precon seated; absent seats `SMOKE_BASE_DECK`. */
|
|
59
|
+
readonly deck?: StarterDeck;
|
|
60
|
+
readonly scenario: string;
|
|
61
|
+
/** The pack's modular set this plan is about. */
|
|
62
|
+
readonly modularSet?: string;
|
|
63
|
+
readonly difficulty?: "expert";
|
|
64
|
+
/** The modular sets to pick; absent is the scenario's recommendation. */
|
|
65
|
+
readonly modularSetIds?: readonly string[];
|
|
66
|
+
}
|
|
67
|
+
/** What `smokeTestPack` plays for a pack: its game plans and its campaigns, each once per seed `1..games`. */
|
|
68
|
+
export interface SmokeSchedule {
|
|
69
|
+
readonly scenario: string;
|
|
70
|
+
readonly games: number;
|
|
71
|
+
readonly maxCommands: number;
|
|
72
|
+
readonly plans: readonly SmokePlan[];
|
|
73
|
+
readonly campaigns: readonly PackCampaign[];
|
|
74
|
+
/** Not failures: what the plans could not cover (a hero with no deck). */
|
|
75
|
+
readonly notes: readonly string[];
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Plans a pack's smoke run without playing it, so a caller (a test file) can play each game on its own: the pack's hero
|
|
79
|
+
* precons at the Core scenario, each of its scenarios standard and expert, each of its modular sets at the Core
|
|
80
|
+
* scenario, and each of its campaigns. Throws on bad options.
|
|
81
|
+
*/
|
|
82
|
+
export declare function smokeSchedule(pack: PackInput, options?: SmokeOptions): SmokeSchedule;
|
|
83
|
+
/**
|
|
84
|
+
* Plays one smoke game of `plan` at `seed` to an outcome and replays its log. `deps` is
|
|
85
|
+
* `gameDepsWithPack(PLAYABLE_DEPS, pack)`, made once by the caller for all of the pack's games. Never throws for a
|
|
86
|
+
* broken pack: the game says what failed.
|
|
87
|
+
*/
|
|
88
|
+
export declare function playSmokeGame(pack: PackInput, deps: EngineDeps, plan: SmokePlan, seed: number, maxCommands?: number): SmokeGame;
|
|
89
|
+
/**
|
|
90
|
+
* Plays a pack campaign once per seed `1..games` through `playCampaign`. With `failOnAlwaysLost`, adds a failed game
|
|
91
|
+
* when every seed lost at the same node.
|
|
92
|
+
*/
|
|
93
|
+
export declare function smokeTestCampaign(pack: PackInput, campaign: PackCampaign, deps: EngineDeps, options?: Pick<SmokeOptions, "games" | "maxCommands" | "failOnAlwaysLost" | "onGame">): {
|
|
94
|
+
readonly games: readonly SmokeGame[];
|
|
95
|
+
readonly notes: readonly string[];
|
|
96
|
+
};
|
|
53
97
|
/** Plays `options.games` headless games per deck the pack can field. Never throws for a broken pack. */
|
|
54
98
|
export declare function smokeTestPack(pack: PackInput, options?: SmokeOptions): SmokeResult;
|
|
55
99
|
/**
|