@champions-digital-game/mod-sdk 0.51.0 → 0.53.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.
Files changed (36) hide show
  1. package/README.md +8 -4
  2. package/dist/build.js +1 -1
  3. package/dist/chunks/{chunk-TUJLFNR7.js → chunk-3SR23UJ7.js} +1 -1
  4. package/dist/chunks/chunk-3YMCANI3.js +1 -0
  5. package/dist/chunks/{chunk-EKR67REN.js → chunk-ACT4TJXC.js} +6 -6
  6. package/dist/chunks/{chunk-Y6B5ZZGK.js → chunk-D5S6EHFQ.js} +1 -1
  7. package/dist/chunks/{chunk-JR3ALXBR.js → chunk-DX44O32N.js} +1 -1
  8. package/dist/chunks/{chunk-S3DCO2A6.js → chunk-S3JH4WL4.js} +1 -1
  9. package/dist/chunks/{chunk-GK7LCLI7.js → chunk-WFEXO5DU.js} +1 -1
  10. package/dist/import.js +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/mc-pack.js +7 -5
  13. package/dist/testing.js +1 -1
  14. package/package.json +3 -2
  15. package/types/cards/src/dsl/abilities.d.ts +60 -9
  16. package/types/cards/src/dsl/effects.d.ts +14 -0
  17. package/types/cards/src/wave11/luke_cage/leadership.d.ts +2 -1
  18. package/types/content/src/index.d.ts +1 -1
  19. package/types/content/src/schema/sets.d.ts +6 -0
  20. package/types/engine/src/choices.d.ts +8 -0
  21. package/types/engine/src/effects.d.ts +39 -2
  22. package/types/engine/src/events.d.ts +4 -2
  23. package/types/engine/src/index.d.ts +2 -1
  24. package/types/engine/src/legal.d.ts +2 -0
  25. package/types/engine/src/query.d.ts +9 -2
  26. package/types/engine/src/resolve/discarded-card.d.ts +84 -0
  27. package/types/engine/src/resolve/hand-discard.d.ts +20 -0
  28. package/types/engine/src/resolve/target-validity.d.ts +14 -1
  29. package/types/engine/src/resolve/triggers.d.ts +1 -1
  30. package/types/engine/src/search-findable.d.ts +41 -0
  31. package/types/engine/src/select.d.ts +5 -0
  32. package/types/engine/src/spec.d.ts +7 -0
  33. package/types/engine/src/state.d.ts +16 -0
  34. package/types/engine/src/trigger-events.d.ts +45 -5
  35. package/types/mod-sdk/src/typecheck.d.ts +23 -0
  36. package/dist/chunks/chunk-6F73M3HY.js +0 -1
@@ -1 +1 @@
1
- import{campaignDepsWithPacks,campaignGameWithPacks,gameDepsWithPack,packCampaignRecords,packModularSetChoices,packScenarioRecords,scenarioWithPacks}from"./chunk-S3DCO2A6.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-EKR67REN.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")&&notes.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&&notes.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 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")&&notes.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&&notes.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,4 +1,4 @@
1
- import{assemblePack}from"./chunk-GK7LCLI7.js";import{abilityRefsOf,readPackInput,splitIssues,validatePack}from"./chunk-TUJLFNR7.js";import{PACK_KINDS,isLanguageTag,isPackId,packCardImagePath}from"./chunk-EKR67REN.js";import{copyFileSync,existsSync,mkdirSync,readFileSync,readdirSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname,join}from"node:path";var isObj=value=>typeof value=="object"&&value!==null&&!Array.isArray(value),str=value=>typeof value=="string"&&value!==""?value:void 0,normalizer;function registerMarvelCdbNormalizer(normalize){normalizer=normalize}async function loadNormalizer(){if(normalizer)return normalizer;let module=await import(new URL("../../content/scripts/marvelcdb/normalize.ts",import.meta.url).href);if(typeof module.normalizePack!="function")throw new Error("the content package's normalizePack is missing");return normalizer=module.normalizePack}var kebab=text=>text.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),KIND_ALIASES=Object.fromEntries(PACK_KINDS.flatMap(kind=>[[kind,kind],[`${kind}_pack`,kind]]));function dataFileOf(srcDir,modId){let named=join(srcDir,`${modId}.json`);if(existsSync(named))return named;let others=readdirSync(srcDir).filter(name=>name.endsWith(".json")&&name!=="mod.json");if(others.length!==1)throw new Error(`${srcDir}: expected ${modId}.json (or one .json besides mod.json)`);return join(srcDir,others[0])}var tailOf=code=>{let match=/^(.*\d)([a-z])$/.exec(code);return match?{key:match[1],letter:match[2]}:{key:code,letter:""}};function planCodes(records,packId){let order=[],visit=record2=>{let code=str(record2.code);if(code===void 0)throw new Error("a card record has no code");order.push(code),isObj(record2.linked_card)&&visit(record2.linked_card)};records.forEach(visit);let numbers=new Map,out=new Map;for(let code of order){if(out.has(code))throw new Error(`card code ${code} appears twice`);let{key,letter}=tailOf(code);numbers.has(key)||numbers.set(key,numbers.size+1);let n=numbers.get(key);out.set(code,`x.${packId}.${String(n).padStart(numbers.size>99?3:2,"0")}${letter}`)}return out}function planSets(records,packId){let all=records.flatMap(r=>isObj(r.linked_card)?[r,r.linked_card]:[r]),heroSet=all.map(r=>r.type_code==="hero"?str(r.card_set_code):void 0).find(Boolean),out=new Map;for(let record2 of all){let set=str(record2.card_set_code);if(!(set===void 0||out.has(set)))if(set===heroSet)out.set(set,packId);else{let rest=heroSet!==void 0&&set.startsWith(`${heroSet}_`)?set.slice(heroSet.length+1):set;out.set(set,`${packId}-${kebab(rest)}`)}}let finals=[...out.values()];if(new Set(finals).size!==finals.length)throw new Error("two source sets map to the same encounter set id");return out}var escapeRegExp=text=>text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function makeRewriter(map){let keys=[...map.keys()].sort((a,b)=>b.length-a.length).map(escapeRegExp),pattern=new RegExp(`(?<![A-Za-z0-9_])(?:${keys.join("|")})(?![A-Za-z0-9_])`,"g"),walk=node=>typeof node=="string"?node.replace(pattern,hit=>map.get(hit)??hit):Array.isArray(node)?node.map(walk):isObj(node)?Object.fromEntries(Object.entries(node).filter(([key])=>key!=="images"&&key!=="image").map(([key,child])=>[key,walk(child)])):node;return walk}var collectorOf=finalCode=>(/\.(\d+[a-z]?)$/.exec(finalCode)?.[1]??finalCode).replace(/^0+(?=\d)/,"").toUpperCase();function toSourceCodes(curation,finalToSource){let source=code=>finalToSource.get(code)??code,pattern=new RegExp(`^(${[...finalToSource.keys()].map(escapeRegExp).join("|")})(?=\\.|$)`),fixKeys=record2=>isObj(record2)?Object.fromEntries(Object.entries(record2).map(([key,value])=>[key.replace(pattern,m=>source(m)),value])):record2,fixCode=list=>Array.isArray(list)?list.map(e=>isObj(e)&&typeof e.code=="string"?{...e,code:source(e.code)}:e):list,out={...curation};for(let key of["corrections","errata","ignoredRecords"])key in out&&(out[key]=fixCode(out[key]));for(let key of["cardNotes","scriptingNotes"])key in out&&(out[key]=fixKeys(out[key]));return out}function markFlipSides(records,notes,codes){let IDENTITY_TYPES=new Set(["hero","alter_ego","villain","main_scheme"]);return records.map(record2=>{let back=record2.linked_card,type=record2.type_code;if(!isObj(back)||back.hidden!==void 0||IDENTITY_TYPES.has(type)||IDENTITY_TYPES.has(back.type_code))return record2;let code=str(back.code)??"?";return notes.push(`marked ${codes.get(code)??code} as the hidden flip side of ${str(record2.name)??"?"}, as the API does`),{...record2,linked_card:{...back,hidden:!0}}})}function dashCostCorrections(records,finalOf,skip){let found=[];for(let record2 of records){let code=str(record2.code);if(code===void 0||skip.has(code))continue;let noCost=record2.cost===void 0||record2.cost===null;if(record2.permanent!==!0||!noCost||record2.cost_per_hero===!0||record2.type_code!=="upgrade"&&record2.type_code!=="support")continue;let what=`${String(record2.name)}: a permanent ${String(record2.type_code)} with no cost in the source reads as a printed dash cost (cannot be played, enters play through its own text)`;found.push({correction:{code,reason:what,evidence:"pack importer: permanent card, no cost in the MarvelCDB-shaped record; check the card image",specialCost:"dash"},auto:{code,finalCode:finalOf(code),what}})}return found}var APPENDED=new Set(["corrections","errata","scenarios","starterDecks","separateDecks","ignoredRecords"]);function mergeCuration(base,extra){let out={...base};for(let[key,value]of Object.entries(extra)){let current=out[key];APPENDED.has(key)&&Array.isArray(current)&&Array.isArray(value)?out[key]=[...current,...value]:isObj(current)&&isObj(value)?out[key]={...current,...value}:out[key]=value}return out}function semverOf(text){let match=/^\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?![\d.])/.exec(text);return match?`${match[1]}.${match[2]??"0"}.${match[3]??"0"}`:void 0}function readMod(srcDir){let mod=JSON.parse(readFileSync(join(srcDir,"mod.json"),"utf8"));if(!isObj(mod)||!str(mod.id)||!str(mod.name)||!str(mod.kind)||!str(mod.author))throw new Error(`${join(srcDir,"mod.json")}: needs id, name, kind and author`);return mod}var subDirs=dir=>existsSync(dir)?readdirSync(dir,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name):[];function mapPictures(srcDir,codes){let copies=[],missing=[],unmatched=[],languages=subDirs(join(srcDir,"images")).sort();for(let lang of languages){let dir=join(srcDir,"images",lang),present=new Set(readdirSync(dir));for(let[source,final]of codes)present.delete(`${source}.webp`)?copies.push({from:join(dir,`${source}.webp`),to:packCardImagePath(lang,final)}):missing.push(`${lang}/${source}`);unmatched.push(...[...present].sort().map(name=>`images/${lang}/${name}`))}let altArt={};for(let lang of subDirs(join(srcDir,"alt-art")).sort()){let dir=join(srcDir,"alt-art",lang);for(let name of readdirSync(dir).sort()){let match=/^(.+)\.webp$/.exec(name);if(!match){unmatched.push(`alt-art/${lang}/${name}`);continue}let stem=match[1],own=codes.get(stem.replace(/-alt$/,"")),code=own!==void 0&&stem.endsWith("-alt")?own:stem,to=`alt-art/${lang}/${code}.webp`;(altArt[lang]??={})[code]=to,copies.push({from:join(dir,name),to})}}return{copies,languages,missing,unmatched,altArt}}var bytesOf=path=>new Uint8Array(readFileSync(path));function creditsMarkdown(mod,packId,languages,base){let translators=Object.entries(mod.languages??{}).filter(([lang,who])=>lang!=="base"&&who!=="author");return["# Credits","",`${mod.name} (\`${packId}\`) is a fan-made pack by ${mod.author}.`,"",`- Card design and art direction: ${mod.author}.`,...mod.template?[`- Card template: ${mod.template}.`]:[],...translators.map(([lang,who])=>`- Translation and layout (${lang}): ${who}.`),`- Pictures: ${languages.join(", ")} (base language ${base}).`,...mod.version?[`- Source version: ${mod.version}.`]:[],"","The card data was converted from MarvelCDB-shaped records with the mod SDK's `importMarvelCdbPack`.","Character art is Marvel comics art, as used by each author.","","Marvel Champions: The Card Game is the property of Fantasy Flight Games and Marvel.",""].join(`
1
+ import{assemblePack}from"./chunk-WFEXO5DU.js";import{abilityRefsOf,readPackInput,splitIssues,validatePack}from"./chunk-3SR23UJ7.js";import{PACK_KINDS,isLanguageTag,isPackId,packCardImagePath}from"./chunk-ACT4TJXC.js";import{copyFileSync,existsSync,mkdirSync,readFileSync,readdirSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname,join}from"node:path";var isObj=value=>typeof value=="object"&&value!==null&&!Array.isArray(value),str=value=>typeof value=="string"&&value!==""?value:void 0,normalizer;function registerMarvelCdbNormalizer(normalize){normalizer=normalize}async function loadNormalizer(){if(normalizer)return normalizer;let module=await import(new URL("../../content/scripts/marvelcdb/normalize.ts",import.meta.url).href);if(typeof module.normalizePack!="function")throw new Error("the content package's normalizePack is missing");return normalizer=module.normalizePack}var kebab=text=>text.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),KIND_ALIASES=Object.fromEntries(PACK_KINDS.flatMap(kind=>[[kind,kind],[`${kind}_pack`,kind]]));function dataFileOf(srcDir,modId){let named=join(srcDir,`${modId}.json`);if(existsSync(named))return named;let others=readdirSync(srcDir).filter(name=>name.endsWith(".json")&&name!=="mod.json");if(others.length!==1)throw new Error(`${srcDir}: expected ${modId}.json (or one .json besides mod.json)`);return join(srcDir,others[0])}var tailOf=code=>{let match=/^(.*\d)([a-z])$/.exec(code);return match?{key:match[1],letter:match[2]}:{key:code,letter:""}};function planCodes(records,packId){let order=[],visit=record2=>{let code=str(record2.code);if(code===void 0)throw new Error("a card record has no code");order.push(code),isObj(record2.linked_card)&&visit(record2.linked_card)};records.forEach(visit);let numbers=new Map,out=new Map;for(let code of order){if(out.has(code))throw new Error(`card code ${code} appears twice`);let{key,letter}=tailOf(code);numbers.has(key)||numbers.set(key,numbers.size+1);let n=numbers.get(key);out.set(code,`x.${packId}.${String(n).padStart(numbers.size>99?3:2,"0")}${letter}`)}return out}function planSets(records,packId){let all=records.flatMap(r=>isObj(r.linked_card)?[r,r.linked_card]:[r]),heroSet=all.map(r=>r.type_code==="hero"?str(r.card_set_code):void 0).find(Boolean),out=new Map;for(let record2 of all){let set=str(record2.card_set_code);if(!(set===void 0||out.has(set)))if(set===heroSet)out.set(set,packId);else{let rest=heroSet!==void 0&&set.startsWith(`${heroSet}_`)?set.slice(heroSet.length+1):set;out.set(set,`${packId}-${kebab(rest)}`)}}let finals=[...out.values()];if(new Set(finals).size!==finals.length)throw new Error("two source sets map to the same encounter set id");return out}var escapeRegExp=text=>text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function makeRewriter(map){let keys=[...map.keys()].sort((a,b)=>b.length-a.length).map(escapeRegExp),pattern=new RegExp(`(?<![A-Za-z0-9_])(?:${keys.join("|")})(?![A-Za-z0-9_])`,"g"),walk=node=>typeof node=="string"?node.replace(pattern,hit=>map.get(hit)??hit):Array.isArray(node)?node.map(walk):isObj(node)?Object.fromEntries(Object.entries(node).filter(([key])=>key!=="images"&&key!=="image").map(([key,child])=>[key,walk(child)])):node;return walk}var collectorOf=finalCode=>(/\.(\d+[a-z]?)$/.exec(finalCode)?.[1]??finalCode).replace(/^0+(?=\d)/,"").toUpperCase();function toSourceCodes(curation,finalToSource){let source=code=>finalToSource.get(code)??code,pattern=new RegExp(`^(${[...finalToSource.keys()].map(escapeRegExp).join("|")})(?=\\.|$)`),fixKeys=record2=>isObj(record2)?Object.fromEntries(Object.entries(record2).map(([key,value])=>[key.replace(pattern,m=>source(m)),value])):record2,fixCode=list=>Array.isArray(list)?list.map(e=>isObj(e)&&typeof e.code=="string"?{...e,code:source(e.code)}:e):list,out={...curation};for(let key of["corrections","errata","ignoredRecords"])key in out&&(out[key]=fixCode(out[key]));for(let key of["cardNotes","scriptingNotes"])key in out&&(out[key]=fixKeys(out[key]));return out}function markFlipSides(records,notes,codes){let IDENTITY_TYPES=new Set(["hero","alter_ego","villain","main_scheme"]);return records.map(record2=>{let back=record2.linked_card,type=record2.type_code;if(!isObj(back)||back.hidden!==void 0||IDENTITY_TYPES.has(type)||IDENTITY_TYPES.has(back.type_code))return record2;let code=str(back.code)??"?";return notes.push(`marked ${codes.get(code)??code} as the hidden flip side of ${str(record2.name)??"?"}, as the API does`),{...record2,linked_card:{...back,hidden:!0}}})}function dashCostCorrections(records,finalOf,skip){let found=[];for(let record2 of records){let code=str(record2.code);if(code===void 0||skip.has(code))continue;let noCost=record2.cost===void 0||record2.cost===null;if(record2.permanent!==!0||!noCost||record2.cost_per_hero===!0||record2.type_code!=="upgrade"&&record2.type_code!=="support")continue;let what=`${String(record2.name)}: a permanent ${String(record2.type_code)} with no cost in the source reads as a printed dash cost (cannot be played, enters play through its own text)`;found.push({correction:{code,reason:what,evidence:"pack importer: permanent card, no cost in the MarvelCDB-shaped record; check the card image",specialCost:"dash"},auto:{code,finalCode:finalOf(code),what}})}return found}var APPENDED=new Set(["corrections","errata","scenarios","starterDecks","separateDecks","ignoredRecords"]);function mergeCuration(base,extra){let out={...base};for(let[key,value]of Object.entries(extra)){let current=out[key];APPENDED.has(key)&&Array.isArray(current)&&Array.isArray(value)?out[key]=[...current,...value]:isObj(current)&&isObj(value)?out[key]={...current,...value}:out[key]=value}return out}function semverOf(text){let match=/^\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?![\d.])/.exec(text);return match?`${match[1]}.${match[2]??"0"}.${match[3]??"0"}`:void 0}function readMod(srcDir){let mod=JSON.parse(readFileSync(join(srcDir,"mod.json"),"utf8"));if(!isObj(mod)||!str(mod.id)||!str(mod.name)||!str(mod.kind)||!str(mod.author))throw new Error(`${join(srcDir,"mod.json")}: needs id, name, kind and author`);return mod}var subDirs=dir=>existsSync(dir)?readdirSync(dir,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name):[];function mapPictures(srcDir,codes){let copies=[],missing=[],unmatched=[],languages=subDirs(join(srcDir,"images")).sort();for(let lang of languages){let dir=join(srcDir,"images",lang),present=new Set(readdirSync(dir));for(let[source,final]of codes)present.delete(`${source}.webp`)?copies.push({from:join(dir,`${source}.webp`),to:packCardImagePath(lang,final)}):missing.push(`${lang}/${source}`);unmatched.push(...[...present].sort().map(name=>`images/${lang}/${name}`))}let altArt={};for(let lang of subDirs(join(srcDir,"alt-art")).sort()){let dir=join(srcDir,"alt-art",lang);for(let name of readdirSync(dir).sort()){let match=/^(.+)\.webp$/.exec(name);if(!match){unmatched.push(`alt-art/${lang}/${name}`);continue}let stem=match[1],own=codes.get(stem.replace(/-alt$/,"")),code=own!==void 0&&stem.endsWith("-alt")?own:stem,to=`alt-art/${lang}/${code}.webp`;(altArt[lang]??={})[code]=to,copies.push({from:join(dir,name),to})}}return{copies,languages,missing,unmatched,altArt}}var bytesOf=path=>new Uint8Array(readFileSync(path));function creditsMarkdown(mod,packId,languages,base){let translators=Object.entries(mod.languages??{}).filter(([lang,who])=>lang!=="base"&&who!=="author");return["# Credits","",`${mod.name} (\`${packId}\`) is a fan-made pack by ${mod.author}.`,"",`- Card design and art direction: ${mod.author}.`,...mod.template?[`- Card template: ${mod.template}.`]:[],...translators.map(([lang,who])=>`- Translation and layout (${lang}): ${who}.`),`- Pictures: ${languages.join(", ")} (base language ${base}).`,...mod.version?[`- Source version: ${mod.version}.`]:[],"","The card data was converted from MarvelCDB-shaped records with the mod SDK's `importMarvelCdbPack`.","Character art is Marvel comics art, as used by each author.","","Marvel Champions: The Card Game is the property of Fantasy Flight Games and Marvel.",""].join(`
2
2
  `)}function permissionMarkdown(mod,granted){let p=mod.permission??{};return["# Permission","",granted?`${mod.author}, the author of ${mod.name}, gave permission for this pack to be distributed through the mod store.`:`**Permission is not recorded as granted for this pack (status: ${p.status??"none"}). Do not publish it.**`,"",`- Status: ${p.status??"not recorded"}`,`- Scope: ${p.scope??"not recorded"}`,`- Date: ${p.date??"not recorded"}`,"","Recorded in the pack's draft `mod.json`. The registry review asks for the evidence (a link or a quoted message).",""].join(`
3
3
  `)}function abilityFacesOf(card){let faces=[],walk=(node,title)=>{if(Array.isArray(node))return void node.forEach(n=>walk(n,title));if(!isObj(node))return;let ids=Array.isArray(node.abilities)?node.abilities.flatMap(a=>isObj(a)&&typeof a.id=="string"?[a.id]:[]):[],here=str(node.faceName)??str(node.name)??title;if(ids.length>0){let text=isObj(node.text)?str(node.text.printed)??"":"";faces.push({title:here,text,ids})}for(let[key,child]of Object.entries(node))key!=="abilities"&&key!=="text"&&walk(child,here)};return walk(card,card.name),faces}function abilitiesStub(cards,packName){let ids=[],blocks=[];for(let card of cards)for(let face of abilityFacesOf(card)){let fresh=face.ids.filter(id=>!ids.includes(id));if(fresh.length===0)continue;ids.push(...fresh);let text=face.text.split(`
4
4
  `).map(line=>` // ${line}`);blocks.push([` // ${String(card.id)} ${face.title} (${card.type})`,...text,...fresh.map(id=>` // ${id}`)].join(`
@@ -1 +1 @@
1
- import{customModularSetChoices,playableScenarioWithCustom}from"./chunk-EKR67REN.js";function gameDepsWithPack(base,pack){for(let id of Object.keys(pack.abilities))if(Object.hasOwn(base.abilities,id))throw new Error(`pack ability ${id} is already defined by the base game`);return{...base,abilities:{...base.abilities,...pack.abilities}}}function cardPoolWithPack(pool,pack){let known=new Set(pool.map(card=>card.id));for(let card of pack.cards)if(known.has(card.id))throw new Error(`pack card ${card.id} is already in the pool`);return[...pool,...pack.cards]}function gameDepsWithPacks(base,packs){return packs.reduce((deps,pack)=>gameDepsWithPack(deps,pack),base)}function packScenarioRecords(packs){return packs.flatMap(pack=>pack.scenarios??[])}function packEncounterSetRecords(packs){return packs.flatMap(pack=>pack.encounterSets??[])}function customContentOfPacks(packs){return{cards:packs.flatMap(pack=>pack.cards),encounterSets:packEncounterSetRecords(packs),scenarios:packScenarioRecords(packs)}}function packModularSetChoices(scenario,packs){return customModularSetChoices(scenario,customContentOfPacks(packs))}function scenarioWithPacks(scenarioId,options,packs){return playableScenarioWithCustom(scenarioId,options,customContentOfPacks(packs))}function packCampaignRecords(packs){return packs.flatMap(pack=>pack.campaigns??[])}function packCampaignDefinitionOf(packs,campaignId){return packCampaignRecords(packs).find(campaign=>campaign.id===campaignId)?.definition}function packCampaignDefinitions(packs){return Object.fromEntries(packCampaignRecords(packs).map(campaign=>[campaign.id,campaign.definition]))}function campaignDepsWithPacks(pool,packs){return{pool:cardPoolWithPacks(pool,packs)}}function cardPoolWithPacks(pool,packs){return packs.reduce((all,pack)=>cardPoolWithPack(all,pack),pool)}function campaignGameWithPacks(start,packs,options={}){if(start.scenarioId===null)throw new Error(`campaign node "${start.nodeId}" has no fixed scenario`);return{...scenarioWithPacks(start.scenarioId,{players:start.input.seats.map(seat=>({identityCardId:seat.identityCardId,deck:[...seat.deck],aspects:seat.aspects})),seed:start.input.seed,difficulty:options.difficulty??"standard",...options.modularSetIds?{modularSetIds:[...options.modularSetIds]}:{}},packs),campaign:start.input}}export{gameDepsWithPack,cardPoolWithPack,gameDepsWithPacks,packScenarioRecords,packEncounterSetRecords,customContentOfPacks,packModularSetChoices,scenarioWithPacks,packCampaignRecords,packCampaignDefinitionOf,packCampaignDefinitions,campaignDepsWithPacks,cardPoolWithPacks,campaignGameWithPacks};
1
+ import{customModularSetChoices,playableScenarioWithCustom}from"./chunk-ACT4TJXC.js";function gameDepsWithPack(base,pack){for(let id of Object.keys(pack.abilities))if(Object.hasOwn(base.abilities,id))throw new Error(`pack ability ${id} is already defined by the base game`);return{...base,abilities:{...base.abilities,...pack.abilities}}}function cardPoolWithPack(pool,pack){let known=new Set(pool.map(card=>card.id));for(let card of pack.cards)if(known.has(card.id))throw new Error(`pack card ${card.id} is already in the pool`);return[...pool,...pack.cards]}function gameDepsWithPacks(base,packs){return packs.reduce((deps,pack)=>gameDepsWithPack(deps,pack),base)}function packScenarioRecords(packs){return packs.flatMap(pack=>pack.scenarios??[])}function packEncounterSetRecords(packs){return packs.flatMap(pack=>pack.encounterSets??[])}function customContentOfPacks(packs){return{cards:packs.flatMap(pack=>pack.cards),encounterSets:packEncounterSetRecords(packs),scenarios:packScenarioRecords(packs)}}function packModularSetChoices(scenario,packs){return customModularSetChoices(scenario,customContentOfPacks(packs))}function scenarioWithPacks(scenarioId,options,packs){return playableScenarioWithCustom(scenarioId,options,customContentOfPacks(packs))}function packCampaignRecords(packs){return packs.flatMap(pack=>pack.campaigns??[])}function packCampaignDefinitionOf(packs,campaignId){return packCampaignRecords(packs).find(campaign=>campaign.id===campaignId)?.definition}function packCampaignDefinitions(packs){return Object.fromEntries(packCampaignRecords(packs).map(campaign=>[campaign.id,campaign.definition]))}function campaignDepsWithPacks(pool,packs){return{pool:cardPoolWithPacks(pool,packs)}}function cardPoolWithPacks(pool,packs){return packs.reduce((all,pack)=>cardPoolWithPack(all,pack),pool)}function campaignGameWithPacks(start,packs,options={}){if(start.scenarioId===null)throw new Error(`campaign node "${start.nodeId}" has no fixed scenario`);return{...scenarioWithPacks(start.scenarioId,{players:start.input.seats.map(seat=>({identityCardId:seat.identityCardId,deck:[...seat.deck],aspects:seat.aspects})),seed:start.input.seed,difficulty:options.difficulty??"standard",...options.modularSetIds?{modularSetIds:[...options.modularSetIds]}:{}},packs),campaign:start.input}}export{gameDepsWithPack,cardPoolWithPack,gameDepsWithPacks,packScenarioRecords,packEncounterSetRecords,customContentOfPacks,packModularSetChoices,scenarioWithPacks,packCampaignRecords,packCampaignDefinitionOf,packCampaignDefinitions,campaignDepsWithPacks,cardPoolWithPacks,campaignGameWithPacks};
@@ -1,4 +1,4 @@
1
- import{campaignDefinitionsOf,dslFeatures,readPackInput,sha256Hex,validatePack}from"./chunk-TUJLFNR7.js";import{PACK_PREVIEW_SCHEMA_VERSION,isSafePackPath,packCardImagePath,parsePackCardImagePath}from"./chunk-EKR67REN.js";import{mkdirSync,readFileSync,readdirSync,statSync,writeFileSync,existsSync}from"node:fs";import{dirname,join,relative,sep}from"node:path";import{pathToFileURL}from"node:url";import{createRequire}from"module";var require2=createRequire("/"),_a,Worker,isMarkedAsUntransferable;try{_a=require2("worker_threads"),Worker=_a.Worker,isMarkedAsUntransferable=_a.isMarkedAsUntransferable}catch{}var u8=Uint8Array,u16=Uint16Array,i32=Int32Array,fleb=new u8([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),fdeb=new u8([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),clim=new u8([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),freb=function(eb,start){for(var b=new u16(31),i2=0;i2<31;++i2)b[i2]=start+=1<<eb[i2-1];for(var r=new i32(b[30]),i2=1;i2<30;++i2)for(var j=b[i2];j<b[i2+1];++j)r[j]=j-b[i2]<<5|i2;return{b,r}},_a=freb(fleb,2),fl=_a.b,revfl=_a.r;fl[28]=258,revfl[258]=28;var _b=freb(fdeb,0),fd=_b.b,revfd=_b.r,rev=new u16(32768);for(i=0;i<32768;++i)x=(i&43690)>>1|(i&21845)<<1,x=(x&52428)>>2|(x&13107)<<2,x=(x&61680)>>4|(x&3855)<<4,rev[i]=((x&65280)>>8|(x&255)<<8)>>1;var x,i,hMap=(function(cd,mb,r){for(var s=cd.length,i2=0,l=new u16(mb);i2<s;++i2)cd[i2]&&++l[cd[i2]-1];var le=new u16(mb);for(i2=1;i2<mb;++i2)le[i2]=le[i2-1]+l[i2-1]<<1;var co;if(r){co=new u16(1<<mb);var rvb=15-mb;for(i2=0;i2<s;++i2)if(cd[i2])for(var sv=i2<<4|cd[i2],r_1=mb-cd[i2],v=le[cd[i2]-1]++<<r_1,m=v|(1<<r_1)-1;v<=m;++v)co[rev[v]>>rvb]=sv}else for(co=new u16(s),i2=0;i2<s;++i2)cd[i2]&&(co[i2]=rev[le[cd[i2]-1]++]>>15-cd[i2]);return co}),flt=new u8(288);for(i=0;i<144;++i)flt[i]=8;var i;for(i=144;i<256;++i)flt[i]=9;var i;for(i=256;i<280;++i)flt[i]=7;var i;for(i=280;i<288;++i)flt[i]=8;var i,fdt=new u8(32);for(i=0;i<32;++i)fdt[i]=5;var i,flm=hMap(flt,9,0);var fdm=hMap(fdt,5,0);var shft=function(p){return(p+7)/8|0},slc=function(v,s,e){return(s==null||s<0)&&(s=0),(e==null||e>v.length)&&(e=v.length),new u8(v.subarray(s,e))};var ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],err=function(ind,msg,nt){var e=new Error(msg||ec[ind]);if(e.code=ind,Error.captureStackTrace&&Error.captureStackTrace(e,err),!nt)throw e;return e};var wbits=function(d,p,v){v<<=p&7;var o=p/8|0;d[o]|=v,d[o+1]|=v>>8},wbits16=function(d,p,v){v<<=p&7;var o=p/8|0;d[o]|=v,d[o+1]|=v>>8,d[o+2]|=v>>16},hTree=function(d,mb){for(var t=[],i2=0;i2<d.length;++i2)d[i2]&&t.push({s:i2,f:d[i2]});var s=t.length,t2=t.slice();if(!s)return{t:et,l:0};if(s==1){var v=new u8(t[0].s+1);return v[t[0].s]=1,{t:v,l:1}}t.sort(function(a,b){return a.f-b.f}),t.push({s:-1,f:25001});var l=t[0],r=t[1],i0=0,i1=1,i22=2;for(t[0]={s:-1,f:l.f+r.f,l,r};i1!=s-1;)l=t[t[i0].f<t[i22].f?i0++:i22++],r=t[i0!=i1&&t[i0].f<t[i22].f?i0++:i22++],t[i1++]={s:-1,f:l.f+r.f,l,r};for(var maxSym=t2[0].s,i2=1;i2<s;++i2)t2[i2].s>maxSym&&(maxSym=t2[i2].s);var tr=new u16(maxSym+1),mbt=ln(t[i1-1],tr,0);if(mbt>mb){var i2=0,dt=0,lft=mbt-mb,cst=1<<lft;for(t2.sort(function(a,b){return tr[b.s]-tr[a.s]||a.f-b.f});i2<s;++i2){var i2_1=t2[i2].s;if(tr[i2_1]>mb)dt+=cst-(1<<mbt-tr[i2_1]),tr[i2_1]=mb;else break}for(dt>>=lft;dt>0;){var i2_2=t2[i2].s;tr[i2_2]<mb?dt-=1<<mb-tr[i2_2]++-1:++i2}for(;i2>=0&&dt;--i2){var i2_3=t2[i2].s;tr[i2_3]==mb&&(--tr[i2_3],++dt)}mbt=mb}return{t:new u8(tr),l:mbt}},ln=function(n,l,d){return n.s==-1?Math.max(ln(n.l,l,d+1),ln(n.r,l,d+1)):l[n.s]=d},lc=function(c){for(var s=c.length;s&&!c[--s];);for(var cl=new u16(++s),cli=0,cln=c[0],cls=1,w=function(v){cl[cli++]=v},i2=1;i2<=s;++i2)if(c[i2]==cln&&i2!=s)++cls;else{if(!cln&&cls>2){for(;cls>138;cls-=138)w(32754);cls>2&&(w(cls>10?cls-11<<5|28690:cls-3<<5|12305),cls=0)}else if(cls>3){for(w(cln),--cls;cls>6;cls-=6)w(8304);cls>2&&(w(cls-3<<5|8208),cls=0)}for(;cls--;)w(cln);cls=1,cln=c[i2]}return{c:cl.subarray(0,cli),n:s}},clen=function(cf,cl){for(var l=0,i2=0;i2<cl.length;++i2)l+=cf[i2]*cl[i2];return l},wfblk=function(out,pos,dat){var s=dat.length,o=shft(pos+2);out[o]=s&255,out[o+1]=s>>8,out[o+2]=out[o]^255,out[o+3]=out[o+1]^255;for(var i2=0;i2<s;++i2)out[o+i2+4]=dat[i2];return(o+4+s)*8},wblk=function(dat,out,final,syms,lf,df,eb,li,bs,bl,p){wbits(out,p++,final),++lf[256];for(var _a2=hTree(lf,15),dlt=_a2.t,mlb=_a2.l,_b2=hTree(df,15),ddt=_b2.t,mdb=_b2.l,_c=lc(dlt),lclt=_c.c,nlc=_c.n,_d=lc(ddt),lcdt=_d.c,ndc=_d.n,lcfreq=new u16(19),i2=0;i2<lclt.length;++i2)++lcfreq[lclt[i2]&31];for(var i2=0;i2<lcdt.length;++i2)++lcfreq[lcdt[i2]&31];for(var _e=hTree(lcfreq,7),lct=_e.t,mlcb=_e.l,nlcc=19;nlcc>4&&!lct[clim[nlcc-1]];--nlcc);var flen=bl+5<<3,ftlen=clen(lf,flt)+clen(df,fdt)+eb,dtlen=clen(lf,dlt)+clen(df,ddt)+eb+14+3*nlcc+clen(lcfreq,lct)+2*lcfreq[16]+3*lcfreq[17]+7*lcfreq[18];if(bs>=0&&flen<=ftlen&&flen<=dtlen)return wfblk(out,p,dat.subarray(bs,bs+bl));var lm,ll,dm,dl;if(wbits(out,p,1+(dtlen<ftlen)),p+=2,dtlen<ftlen){lm=hMap(dlt,mlb,0),ll=dlt,dm=hMap(ddt,mdb,0),dl=ddt;var llm=hMap(lct,mlcb,0);wbits(out,p,nlc-257),wbits(out,p+5,ndc-1),wbits(out,p+10,nlcc-4),p+=14;for(var i2=0;i2<nlcc;++i2)wbits(out,p+3*i2,lct[clim[i2]]);p+=3*nlcc;for(var lcts=[lclt,lcdt],it=0;it<2;++it)for(var clct=lcts[it],i2=0;i2<clct.length;++i2){var len=clct[i2]&31;wbits(out,p,llm[len]),p+=lct[len],len>15&&(wbits(out,p,clct[i2]>>5&127),p+=clct[i2]>>12)}}else lm=flm,ll=flt,dm=fdm,dl=fdt;for(var i2=0;i2<li;++i2){var sym=syms[i2];if(sym>255){var len=sym>>18&31;wbits16(out,p,lm[len+257]),p+=ll[len+257],len>7&&(wbits(out,p,sym>>23&31),p+=fleb[len]);var dst=sym&31;wbits16(out,p,dm[dst]),p+=dl[dst],dst>3&&(wbits16(out,p,sym>>5&8191),p+=fdeb[dst])}else wbits16(out,p,lm[sym]),p+=ll[sym]}return wbits16(out,p,lm[256]),p+ll[256]},deo=new i32([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),et=new u8(0),dflt=function(dat,lvl,plvl,pre,post,st){var s=st.z||dat.length,o=new u8(pre+s+5*(1+Math.ceil(s/7e3))+post),w=o.subarray(pre,o.length-post),lst=st.l,pos=(st.r||0)&7;if(lvl){pos&&(w[0]=st.r>>3);for(var opt=deo[lvl-1],n=opt>>13,c=opt&8191,msk_1=(1<<plvl)-1,prev=st.p||new u16(32768),head=st.h||new u16(msk_1+1),bs1_1=Math.ceil(plvl/3),bs2_1=2*bs1_1,hsh=function(i3){return(dat[i3]^dat[i3+1]<<bs1_1^dat[i3+2]<<bs2_1)&msk_1},syms=new i32(25e3),lf=new u16(288),df=new u16(32),lc_1=0,eb=0,i2=st.i||0,li=0,wi=st.w||0,bs=0;i2+2<s;++i2){var hv=hsh(i2),imod=i2&32767,pimod=head[hv];if(prev[imod]=pimod,head[hv]=imod,wi<=i2){var rem=s-i2;if((lc_1>7e3||li>24576)&&(rem>423||!lst)){pos=wblk(dat,w,0,syms,lf,df,eb,li,bs,i2-bs,pos),li=lc_1=eb=0,bs=i2;for(var j=0;j<286;++j)lf[j]=0;for(var j=0;j<30;++j)df[j]=0}var l=2,d=0,ch_1=c,dif=imod-pimod&32767;if(rem>2&&hv==hsh(i2-dif))for(var maxn=Math.min(n,rem)-1,maxd=Math.min(32767,i2),ml=Math.min(258,rem);dif<=maxd&&--ch_1&&imod!=pimod;){if(dat[i2+l]==dat[i2+l-dif]){for(var nl=0;nl<ml&&dat[i2+nl]==dat[i2+nl-dif];++nl);if(nl>l){if(l=nl,d=dif,nl>maxn)break;for(var mmd=Math.min(dif,nl-2),md=0,j=0;j<mmd;++j){var ti=i2-dif+j&32767,pti=prev[ti],cd=ti-pti&32767;cd>md&&(md=cd,pimod=ti)}}}imod=pimod,pimod=prev[imod],dif+=imod-pimod&32767}if(d){syms[li++]=268435456|revfl[l]<<18|revfd[d];var lin=revfl[l]&31,din=revfd[d]&31;eb+=fleb[lin]+fdeb[din],++lf[257+lin],++df[din],wi=i2+l,++lc_1}else syms[li++]=dat[i2],++lf[dat[i2]]}}for(i2=Math.max(i2,wi);i2<s;++i2)syms[li++]=dat[i2],++lf[dat[i2]];pos=wblk(dat,w,lst,syms,lf,df,eb,li,bs,i2-bs,pos),lst||(st.r=pos&7|w[pos/8|0]<<3,pos-=7,st.h=head,st.p=prev,st.i=i2,st.w=wi)}else{for(var i2=st.w||0;i2<s+lst;i2+=65535){var e=i2+65535;e>=s&&(w[pos/8|0]=lst,e=s),pos=wfblk(w,pos+1,dat.subarray(i2,e))}st.i=s}return slc(o,0,pre+shft(pos)+post)},crct=(function(){for(var t=new Int32Array(256),i2=0;i2<256;++i2){for(var c=i2,k=9;--k;)c=(c&1&&-306674912)^c>>>1;t[i2]=c}return t})(),crc=function(){var c=-1;return{p:function(d){for(var cr=c,i2=0;i2<d.length;++i2)cr=crct[cr&255^d[i2]]^cr>>>8;c=cr},d:function(){return~c}}};var dopt=function(dat,opt,pre,post,st){if(!st&&(st={l:1},opt.dictionary)){var dict=opt.dictionary.subarray(-32768),newDat=new u8(dict.length+dat.length);newDat.set(dict),newDat.set(dat,dict.length),dat=newDat,st.w=dict.length}return dflt(dat,opt.level==null?6:opt.level,opt.mem==null?st.l?Math.ceil(Math.max(8,Math.min(13,Math.log(dat.length)))*1.5):20:12+opt.mem,pre,post,st)},mrg=function(a,b){var o={};for(var k in a)o[k]=a[k];for(var k in b)o[k]=b[k];return o};var wbytes=function(d,b,v){for(;v;++b)d[b]=v,v>>>=8};var Deflate=(function(){function Deflate2(opts,cb){if(typeof opts=="function"&&(cb=opts,opts={}),this.ondata=cb,this.o=opts||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new u8(98304),this.o.dictionary){var dict=this.o.dictionary.subarray(-32768);this.b.set(dict,32768-dict.length),this.s.i=32768-dict.length}}return Deflate2.prototype.p=function(c,f){this.ondata(dopt(c,this.o,0,0,this.s),f)},Deflate2.prototype.push=function(chunk,final){this.ondata||err(5),this.s.l&&err(4);var endLen=chunk.length+this.s.z;if(endLen>this.b.length){if(endLen>2*this.b.length-32768){var newBuf=new u8(endLen&-32768);newBuf.set(this.b.subarray(0,this.s.z)),this.b=newBuf}var split=this.b.length-this.s.z;this.b.set(chunk.subarray(0,split),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(chunk.subarray(split),32768),this.s.z=chunk.length-split+32768,this.s.i=32766,this.s.w=32768}else this.b.set(chunk,this.s.z),this.s.z+=chunk.length;this.s.l=final&1,(this.s.z>this.s.w+8191||final)&&(this.p(this.b,final||!1),this.s.w=this.s.i,this.s.i-=2),final&&(this.s=this.o={},this.b=et)},Deflate2.prototype.flush=function(sync){if(this.ondata||err(5),this.s.l&&err(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2,sync){var c=new u8(6);c[0]=this.s.r>>3;var ep=wfblk(c,this.s.r,et);this.s.r=0,this.ondata(c.subarray(0,ep>>3),!1)}},Deflate2})();var te=typeof TextEncoder<"u"&&new TextEncoder,td=typeof TextDecoder<"u"&&new TextDecoder,tds=0;try{td.decode(et,{stream:!0}),tds=1}catch{}function strToU8(str,latin1){if(latin1){for(var ar_1=new u8(str.length),i2=0;i2<str.length;++i2)ar_1[i2]=str.charCodeAt(i2);return ar_1}if(te)return te.encode(str);for(var l=str.length,ar=new u8(str.length+(str.length>>1)),ai=0,w=function(v){ar[ai++]=v},i2=0;i2<l;++i2){if(ai+5>ar.length){var n=new u8(ai+8+(l-i2<<1));n.set(ar),ar=n}var c=str.charCodeAt(i2);c<128||latin1?w(c):c<2048?(w(192|c>>6),w(128|c&63)):c>55295&&c<57344?(c=65536+(c&1047552)|str.charCodeAt(++i2)&1023,w(240|c>>18),w(128|c>>12&63),w(128|c>>6&63),w(128|c&63)):(w(224|c>>12),w(128|c>>6&63),w(128|c&63))}return slc(ar,0,ai)}var dbf=function(l){return l==1?3:l<6?2:l==9?1:0};var exfl=function(ex){var le=0;if(ex)for(var k in ex){var l=ex[k].length;l>65535&&err(9),le+=l+4}return le},wzh=function(d,b,f,fn,u,c,ce,co){var fl2=fn.length,ex=f.extra,col=co&&co.length,exl=exfl(ex);wbytes(d,b,ce!=null?33639248:67324752),b+=4,ce!=null&&(d[b++]=20,d[b++]=f.os),d[b]=20,b+=2,d[b++]=f.flag<<1|(c<0&&8),d[b++]=u&&8,d[b++]=f.compression&255,d[b++]=f.compression>>8;var dt=new Date(f.mtime==null?Date.now():f.mtime),y=dt.getFullYear()-1980;if((y<0||y>119)&&err(10),wbytes(d,b,y<<25|dt.getMonth()+1<<21|dt.getDate()<<16|dt.getHours()<<11|dt.getMinutes()<<5|dt.getSeconds()>>1),b+=4,c!=-1&&(wbytes(d,b,f.crc),wbytes(d,b+4,c<0?-c-2:c),wbytes(d,b+8,f.size)),wbytes(d,b+12,fl2),wbytes(d,b+14,exl),b+=16,ce!=null&&(wbytes(d,b,col),wbytes(d,b+6,f.attrs),wbytes(d,b+10,ce),b+=14),d.set(fn,b),b+=fl2,exl)for(var k in ex){var exf=ex[k],l=exf.length;wbytes(d,b,+k),wbytes(d,b+2,l),d.set(exf,b+4),b+=4+l}return col&&(d.set(co,b),b+=col),b},wzf=function(o,b,c,d,e){wbytes(o,b,101010256),wbytes(o,b+8,c),wbytes(o,b+10,c),wbytes(o,b+12,d),wbytes(o,b+16,e)},ZipPassThrough=(function(){function ZipPassThrough2(filename){this.filename=filename,this.c=crc(),this.size=0,this.compression=0}return ZipPassThrough2.prototype.process=function(chunk,final){this.ondata(null,chunk,final)},ZipPassThrough2.prototype.push=function(chunk,final){this.ondata||err(5),this.c.p(chunk),this.size+=chunk.length,final&&(this.crc=this.c.d()),this.process(chunk,final||!1)},ZipPassThrough2})();var ZipDeflate=(function(){function ZipDeflate2(filename,opts){var _this=this;opts||(opts={}),ZipPassThrough.call(this,filename),this.d=new Deflate(opts,function(dat,final){_this.ondata(null,dat,final)}),this.compression=8,this.flag=dbf(opts.level)}return ZipDeflate2.prototype.process=function(chunk,final){try{this.d.push(chunk,final)}catch(e){this.ondata(e,null,final)}},ZipDeflate2.prototype.push=function(chunk,final){ZipPassThrough.prototype.push.call(this,chunk,final)},ZipDeflate2})();var Zip=(function(){function Zip2(cb){this.ondata=cb,this.u=[],this.d=1}return Zip2.prototype.add=function(file){var _this=this;if(this.ondata||err(5),this.d&2)this.ondata(err(4+(this.d&1)*8,0,1),null,!1);else{var f=strToU8(file.filename),fl_1=f.length,com=file.comment,o=com&&strToU8(com),u=fl_1!=file.filename.length||o&&com.length!=o.length,hl_1=fl_1+exfl(file.extra)+30;fl_1>65535&&this.ondata(err(11,0,1),null,!1);var header=new u8(hl_1);wzh(header,0,file,f,u,-1);var chks_1=[header],pAll_1=function(){for(var _i=0,chks_2=chks_1;_i<chks_2.length;_i++){var chk=chks_2[_i];_this.ondata(null,chk,!1)}chks_1=[]},tr_1=this.d;this.d=0;var ind_1=this.u.length,uf_1=mrg(file,{f,u,o,t:function(){file.terminate&&file.terminate()},r:function(){if(pAll_1(),tr_1){var nxt=_this.u[ind_1+1];nxt?nxt.r():_this.d=1}tr_1=1}}),cl_1=0;file.ondata=function(err2,dat,final){if(err2)_this.ondata(err2,dat,final),_this.terminate();else if(cl_1+=dat.length,chks_1.push(dat),final){var dd=new u8(16);wbytes(dd,0,134695760),wbytes(dd,4,file.crc),wbytes(dd,8,cl_1),wbytes(dd,12,file.size),chks_1.push(dd),uf_1.c=cl_1,uf_1.b=hl_1+cl_1+16,uf_1.crc=file.crc,uf_1.size=file.size,tr_1&&uf_1.r(),tr_1=1}else tr_1&&pAll_1()},this.u.push(uf_1)}},Zip2.prototype.end=function(){var _this=this;if(this.d&2){this.ondata(err(4+(this.d&1)*8,0,1),null,!0);return}this.d?this.e():this.u.push({r:function(){_this.d&1&&(_this.u.splice(-1,1),_this.e())},t:function(){}}),this.d=3},Zip2.prototype.e=function(){for(var bt=0,l=0,tl=0,_i=0,_a2=this.u;_i<_a2.length;_i++){var f=_a2[_i];tl+=46+f.f.length+exfl(f.extra)+(f.o?f.o.length:0)}for(var out=new u8(tl+22),_b2=0,_c=this.u;_b2<_c.length;_b2++){var f=_c[_b2];wzh(out,bt,f,f.f,f.u,-f.c-2,l,f.o),bt+=46+f.f.length+exfl(f.extra)+(f.o?f.o.length:0),l+=f.b}wzf(out,bt,this.u.length,tl,l),this.ondata(null,out,!0),this.d=2},Zip2.prototype.terminate=function(){for(var _i=0,_a2=this.u;_i<_a2.length;_i++){var f=_a2[_i];f.t()}this.d=2},Zip2})();function firstCampaignScenarioId(campaigns){let id=campaigns?.[0]?.definition?.graph?.nodes?.[0]?.scenario?.scenarioId;return typeof id=="string"?id:void 0}function featuredCardId(pack){let own=new Set(pack.cards.map(card=>card.id)),villainOf=scenarios=>{for(let scenario of scenarios){let id=scenario.villainCardId;if(typeof id=="string"&&own.has(id))return id}},firstOfType=type=>pack.cards.find(card=>card.type===type)?.id;if(pack.manifest.kind==="hero")return firstOfType("hero_identity");if(pack.manifest.kind==="house-rule"){let base=pack.manifest.languages?.base;return[...pack.files.keys()].sort().map(path=>parsePackCardImagePath(path)).find(picture=>picture!==void 0&&picture.lang===base)?.code}if(pack.manifest.kind==="campaign"){let scenarioId=firstCampaignScenarioId(pack.campaigns),scenario=(pack.scenarios??[]).find(one=>one.id===scenarioId),fromCampaign=scenario?villainOf([scenario]):void 0;if(fromCampaign)return fromCampaign}return villainOf(pack.scenarios??[])??firstOfType("villain")??firstOfType("main_scheme")??firstOfType("hero_identity")}function featuredImages(pack,cardId,images){let base=pack.manifest.languages?.base;if(!base)return[];if(pack.manifest.kind==="house-rule")return[packCardImagePath(base,cardId)].filter(path=>images.has(path));let type=pack.cards.find(card=>card.id===cardId)?.type,codes=[cardId];return type==="hero_identity"&&cardId.endsWith("a")&&codes.push(`${cardId.slice(0,-1)}b`),codes.map(code=>packCardImagePath(base,code)).filter(path=>images.has(path))}function buildPreview(pack,manifest=pack.manifest){let images=[...pack.files.keys()].filter(path=>parsePackCardImagePath(path)!==void 0).sort(),imageSet=new Set(images),cardId=featuredCardId(pack),featuredPaths=cardId?featuredImages(pack,cardId,imageSet):[],cover=typeof manifest.cover=="string"&&pack.files.has(manifest.cover)?manifest.cover:void 0;return{preview:{schema:PACK_PREVIEW_SCHEMA_VERSION,packId:manifest.id,version:manifest.version,...manifest.description?{description:manifest.description}:{},...cardId?{featured:{cardId,images:featuredPaths}}:{},...cover?{cover}:{},images,...manifest.languages?{languages:manifest.languages}:{},cards:pack.cards,...(manifest.achievements?.length??0)>0?{achievements:manifest.achievements}:{},decks:[...pack.decks??[]].map(deck=>({id:deck.id,name:deck.name,identityCardId:deck.identityCardId,cards:deck.cards.map(entry=>({cardId:entry.cardId,quantity:entry.quantity}))}))},thumbFrom:cover??featuredPaths[0]}}var PackBuildError=class extends Error{constructor(issues){super(`pack is invalid:
1
+ import{campaignDefinitionsOf,dslFeatures,readPackInput,sha256Hex,validatePack}from"./chunk-3SR23UJ7.js";import{PACK_PREVIEW_SCHEMA_VERSION,isSafePackPath,packCardImagePath,parsePackCardImagePath}from"./chunk-ACT4TJXC.js";import{mkdirSync,readFileSync,readdirSync,statSync,writeFileSync,existsSync}from"node:fs";import{dirname,join,relative,sep}from"node:path";import{pathToFileURL}from"node:url";import{createRequire}from"module";var require2=createRequire("/"),_a,Worker,isMarkedAsUntransferable;try{_a=require2("worker_threads"),Worker=_a.Worker,isMarkedAsUntransferable=_a.isMarkedAsUntransferable}catch{}var u8=Uint8Array,u16=Uint16Array,i32=Int32Array,fleb=new u8([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),fdeb=new u8([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),clim=new u8([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),freb=function(eb,start){for(var b=new u16(31),i2=0;i2<31;++i2)b[i2]=start+=1<<eb[i2-1];for(var r=new i32(b[30]),i2=1;i2<30;++i2)for(var j=b[i2];j<b[i2+1];++j)r[j]=j-b[i2]<<5|i2;return{b,r}},_a=freb(fleb,2),fl=_a.b,revfl=_a.r;fl[28]=258,revfl[258]=28;var _b=freb(fdeb,0),fd=_b.b,revfd=_b.r,rev=new u16(32768);for(i=0;i<32768;++i)x=(i&43690)>>1|(i&21845)<<1,x=(x&52428)>>2|(x&13107)<<2,x=(x&61680)>>4|(x&3855)<<4,rev[i]=((x&65280)>>8|(x&255)<<8)>>1;var x,i,hMap=(function(cd,mb,r){for(var s=cd.length,i2=0,l=new u16(mb);i2<s;++i2)cd[i2]&&++l[cd[i2]-1];var le=new u16(mb);for(i2=1;i2<mb;++i2)le[i2]=le[i2-1]+l[i2-1]<<1;var co;if(r){co=new u16(1<<mb);var rvb=15-mb;for(i2=0;i2<s;++i2)if(cd[i2])for(var sv=i2<<4|cd[i2],r_1=mb-cd[i2],v=le[cd[i2]-1]++<<r_1,m=v|(1<<r_1)-1;v<=m;++v)co[rev[v]>>rvb]=sv}else for(co=new u16(s),i2=0;i2<s;++i2)cd[i2]&&(co[i2]=rev[le[cd[i2]-1]++]>>15-cd[i2]);return co}),flt=new u8(288);for(i=0;i<144;++i)flt[i]=8;var i;for(i=144;i<256;++i)flt[i]=9;var i;for(i=256;i<280;++i)flt[i]=7;var i;for(i=280;i<288;++i)flt[i]=8;var i,fdt=new u8(32);for(i=0;i<32;++i)fdt[i]=5;var i,flm=hMap(flt,9,0);var fdm=hMap(fdt,5,0);var shft=function(p){return(p+7)/8|0},slc=function(v,s,e){return(s==null||s<0)&&(s=0),(e==null||e>v.length)&&(e=v.length),new u8(v.subarray(s,e))};var ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],err=function(ind,msg,nt){var e=new Error(msg||ec[ind]);if(e.code=ind,Error.captureStackTrace&&Error.captureStackTrace(e,err),!nt)throw e;return e};var wbits=function(d,p,v){v<<=p&7;var o=p/8|0;d[o]|=v,d[o+1]|=v>>8},wbits16=function(d,p,v){v<<=p&7;var o=p/8|0;d[o]|=v,d[o+1]|=v>>8,d[o+2]|=v>>16},hTree=function(d,mb){for(var t=[],i2=0;i2<d.length;++i2)d[i2]&&t.push({s:i2,f:d[i2]});var s=t.length,t2=t.slice();if(!s)return{t:et,l:0};if(s==1){var v=new u8(t[0].s+1);return v[t[0].s]=1,{t:v,l:1}}t.sort(function(a,b){return a.f-b.f}),t.push({s:-1,f:25001});var l=t[0],r=t[1],i0=0,i1=1,i22=2;for(t[0]={s:-1,f:l.f+r.f,l,r};i1!=s-1;)l=t[t[i0].f<t[i22].f?i0++:i22++],r=t[i0!=i1&&t[i0].f<t[i22].f?i0++:i22++],t[i1++]={s:-1,f:l.f+r.f,l,r};for(var maxSym=t2[0].s,i2=1;i2<s;++i2)t2[i2].s>maxSym&&(maxSym=t2[i2].s);var tr=new u16(maxSym+1),mbt=ln(t[i1-1],tr,0);if(mbt>mb){var i2=0,dt=0,lft=mbt-mb,cst=1<<lft;for(t2.sort(function(a,b){return tr[b.s]-tr[a.s]||a.f-b.f});i2<s;++i2){var i2_1=t2[i2].s;if(tr[i2_1]>mb)dt+=cst-(1<<mbt-tr[i2_1]),tr[i2_1]=mb;else break}for(dt>>=lft;dt>0;){var i2_2=t2[i2].s;tr[i2_2]<mb?dt-=1<<mb-tr[i2_2]++-1:++i2}for(;i2>=0&&dt;--i2){var i2_3=t2[i2].s;tr[i2_3]==mb&&(--tr[i2_3],++dt)}mbt=mb}return{t:new u8(tr),l:mbt}},ln=function(n,l,d){return n.s==-1?Math.max(ln(n.l,l,d+1),ln(n.r,l,d+1)):l[n.s]=d},lc=function(c){for(var s=c.length;s&&!c[--s];);for(var cl=new u16(++s),cli=0,cln=c[0],cls=1,w=function(v){cl[cli++]=v},i2=1;i2<=s;++i2)if(c[i2]==cln&&i2!=s)++cls;else{if(!cln&&cls>2){for(;cls>138;cls-=138)w(32754);cls>2&&(w(cls>10?cls-11<<5|28690:cls-3<<5|12305),cls=0)}else if(cls>3){for(w(cln),--cls;cls>6;cls-=6)w(8304);cls>2&&(w(cls-3<<5|8208),cls=0)}for(;cls--;)w(cln);cls=1,cln=c[i2]}return{c:cl.subarray(0,cli),n:s}},clen=function(cf,cl){for(var l=0,i2=0;i2<cl.length;++i2)l+=cf[i2]*cl[i2];return l},wfblk=function(out,pos,dat){var s=dat.length,o=shft(pos+2);out[o]=s&255,out[o+1]=s>>8,out[o+2]=out[o]^255,out[o+3]=out[o+1]^255;for(var i2=0;i2<s;++i2)out[o+i2+4]=dat[i2];return(o+4+s)*8},wblk=function(dat,out,final,syms,lf,df,eb,li,bs,bl,p){wbits(out,p++,final),++lf[256];for(var _a2=hTree(lf,15),dlt=_a2.t,mlb=_a2.l,_b2=hTree(df,15),ddt=_b2.t,mdb=_b2.l,_c=lc(dlt),lclt=_c.c,nlc=_c.n,_d=lc(ddt),lcdt=_d.c,ndc=_d.n,lcfreq=new u16(19),i2=0;i2<lclt.length;++i2)++lcfreq[lclt[i2]&31];for(var i2=0;i2<lcdt.length;++i2)++lcfreq[lcdt[i2]&31];for(var _e=hTree(lcfreq,7),lct=_e.t,mlcb=_e.l,nlcc=19;nlcc>4&&!lct[clim[nlcc-1]];--nlcc);var flen=bl+5<<3,ftlen=clen(lf,flt)+clen(df,fdt)+eb,dtlen=clen(lf,dlt)+clen(df,ddt)+eb+14+3*nlcc+clen(lcfreq,lct)+2*lcfreq[16]+3*lcfreq[17]+7*lcfreq[18];if(bs>=0&&flen<=ftlen&&flen<=dtlen)return wfblk(out,p,dat.subarray(bs,bs+bl));var lm,ll,dm,dl;if(wbits(out,p,1+(dtlen<ftlen)),p+=2,dtlen<ftlen){lm=hMap(dlt,mlb,0),ll=dlt,dm=hMap(ddt,mdb,0),dl=ddt;var llm=hMap(lct,mlcb,0);wbits(out,p,nlc-257),wbits(out,p+5,ndc-1),wbits(out,p+10,nlcc-4),p+=14;for(var i2=0;i2<nlcc;++i2)wbits(out,p+3*i2,lct[clim[i2]]);p+=3*nlcc;for(var lcts=[lclt,lcdt],it=0;it<2;++it)for(var clct=lcts[it],i2=0;i2<clct.length;++i2){var len=clct[i2]&31;wbits(out,p,llm[len]),p+=lct[len],len>15&&(wbits(out,p,clct[i2]>>5&127),p+=clct[i2]>>12)}}else lm=flm,ll=flt,dm=fdm,dl=fdt;for(var i2=0;i2<li;++i2){var sym=syms[i2];if(sym>255){var len=sym>>18&31;wbits16(out,p,lm[len+257]),p+=ll[len+257],len>7&&(wbits(out,p,sym>>23&31),p+=fleb[len]);var dst=sym&31;wbits16(out,p,dm[dst]),p+=dl[dst],dst>3&&(wbits16(out,p,sym>>5&8191),p+=fdeb[dst])}else wbits16(out,p,lm[sym]),p+=ll[sym]}return wbits16(out,p,lm[256]),p+ll[256]},deo=new i32([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),et=new u8(0),dflt=function(dat,lvl,plvl,pre,post,st){var s=st.z||dat.length,o=new u8(pre+s+5*(1+Math.ceil(s/7e3))+post),w=o.subarray(pre,o.length-post),lst=st.l,pos=(st.r||0)&7;if(lvl){pos&&(w[0]=st.r>>3);for(var opt=deo[lvl-1],n=opt>>13,c=opt&8191,msk_1=(1<<plvl)-1,prev=st.p||new u16(32768),head=st.h||new u16(msk_1+1),bs1_1=Math.ceil(plvl/3),bs2_1=2*bs1_1,hsh=function(i3){return(dat[i3]^dat[i3+1]<<bs1_1^dat[i3+2]<<bs2_1)&msk_1},syms=new i32(25e3),lf=new u16(288),df=new u16(32),lc_1=0,eb=0,i2=st.i||0,li=0,wi=st.w||0,bs=0;i2+2<s;++i2){var hv=hsh(i2),imod=i2&32767,pimod=head[hv];if(prev[imod]=pimod,head[hv]=imod,wi<=i2){var rem=s-i2;if((lc_1>7e3||li>24576)&&(rem>423||!lst)){pos=wblk(dat,w,0,syms,lf,df,eb,li,bs,i2-bs,pos),li=lc_1=eb=0,bs=i2;for(var j=0;j<286;++j)lf[j]=0;for(var j=0;j<30;++j)df[j]=0}var l=2,d=0,ch_1=c,dif=imod-pimod&32767;if(rem>2&&hv==hsh(i2-dif))for(var maxn=Math.min(n,rem)-1,maxd=Math.min(32767,i2),ml=Math.min(258,rem);dif<=maxd&&--ch_1&&imod!=pimod;){if(dat[i2+l]==dat[i2+l-dif]){for(var nl=0;nl<ml&&dat[i2+nl]==dat[i2+nl-dif];++nl);if(nl>l){if(l=nl,d=dif,nl>maxn)break;for(var mmd=Math.min(dif,nl-2),md=0,j=0;j<mmd;++j){var ti=i2-dif+j&32767,pti=prev[ti],cd=ti-pti&32767;cd>md&&(md=cd,pimod=ti)}}}imod=pimod,pimod=prev[imod],dif+=imod-pimod&32767}if(d){syms[li++]=268435456|revfl[l]<<18|revfd[d];var lin=revfl[l]&31,din=revfd[d]&31;eb+=fleb[lin]+fdeb[din],++lf[257+lin],++df[din],wi=i2+l,++lc_1}else syms[li++]=dat[i2],++lf[dat[i2]]}}for(i2=Math.max(i2,wi);i2<s;++i2)syms[li++]=dat[i2],++lf[dat[i2]];pos=wblk(dat,w,lst,syms,lf,df,eb,li,bs,i2-bs,pos),lst||(st.r=pos&7|w[pos/8|0]<<3,pos-=7,st.h=head,st.p=prev,st.i=i2,st.w=wi)}else{for(var i2=st.w||0;i2<s+lst;i2+=65535){var e=i2+65535;e>=s&&(w[pos/8|0]=lst,e=s),pos=wfblk(w,pos+1,dat.subarray(i2,e))}st.i=s}return slc(o,0,pre+shft(pos)+post)},crct=(function(){for(var t=new Int32Array(256),i2=0;i2<256;++i2){for(var c=i2,k=9;--k;)c=(c&1&&-306674912)^c>>>1;t[i2]=c}return t})(),crc=function(){var c=-1;return{p:function(d){for(var cr=c,i2=0;i2<d.length;++i2)cr=crct[cr&255^d[i2]]^cr>>>8;c=cr},d:function(){return~c}}};var dopt=function(dat,opt,pre,post,st){if(!st&&(st={l:1},opt.dictionary)){var dict=opt.dictionary.subarray(-32768),newDat=new u8(dict.length+dat.length);newDat.set(dict),newDat.set(dat,dict.length),dat=newDat,st.w=dict.length}return dflt(dat,opt.level==null?6:opt.level,opt.mem==null?st.l?Math.ceil(Math.max(8,Math.min(13,Math.log(dat.length)))*1.5):20:12+opt.mem,pre,post,st)},mrg=function(a,b){var o={};for(var k in a)o[k]=a[k];for(var k in b)o[k]=b[k];return o};var wbytes=function(d,b,v){for(;v;++b)d[b]=v,v>>>=8};var Deflate=(function(){function Deflate2(opts,cb){if(typeof opts=="function"&&(cb=opts,opts={}),this.ondata=cb,this.o=opts||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new u8(98304),this.o.dictionary){var dict=this.o.dictionary.subarray(-32768);this.b.set(dict,32768-dict.length),this.s.i=32768-dict.length}}return Deflate2.prototype.p=function(c,f){this.ondata(dopt(c,this.o,0,0,this.s),f)},Deflate2.prototype.push=function(chunk,final){this.ondata||err(5),this.s.l&&err(4);var endLen=chunk.length+this.s.z;if(endLen>this.b.length){if(endLen>2*this.b.length-32768){var newBuf=new u8(endLen&-32768);newBuf.set(this.b.subarray(0,this.s.z)),this.b=newBuf}var split=this.b.length-this.s.z;this.b.set(chunk.subarray(0,split),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(chunk.subarray(split),32768),this.s.z=chunk.length-split+32768,this.s.i=32766,this.s.w=32768}else this.b.set(chunk,this.s.z),this.s.z+=chunk.length;this.s.l=final&1,(this.s.z>this.s.w+8191||final)&&(this.p(this.b,final||!1),this.s.w=this.s.i,this.s.i-=2),final&&(this.s=this.o={},this.b=et)},Deflate2.prototype.flush=function(sync){if(this.ondata||err(5),this.s.l&&err(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2,sync){var c=new u8(6);c[0]=this.s.r>>3;var ep=wfblk(c,this.s.r,et);this.s.r=0,this.ondata(c.subarray(0,ep>>3),!1)}},Deflate2})();var te=typeof TextEncoder<"u"&&new TextEncoder,td=typeof TextDecoder<"u"&&new TextDecoder,tds=0;try{td.decode(et,{stream:!0}),tds=1}catch{}function strToU8(str,latin1){if(latin1){for(var ar_1=new u8(str.length),i2=0;i2<str.length;++i2)ar_1[i2]=str.charCodeAt(i2);return ar_1}if(te)return te.encode(str);for(var l=str.length,ar=new u8(str.length+(str.length>>1)),ai=0,w=function(v){ar[ai++]=v},i2=0;i2<l;++i2){if(ai+5>ar.length){var n=new u8(ai+8+(l-i2<<1));n.set(ar),ar=n}var c=str.charCodeAt(i2);c<128||latin1?w(c):c<2048?(w(192|c>>6),w(128|c&63)):c>55295&&c<57344?(c=65536+(c&1047552)|str.charCodeAt(++i2)&1023,w(240|c>>18),w(128|c>>12&63),w(128|c>>6&63),w(128|c&63)):(w(224|c>>12),w(128|c>>6&63),w(128|c&63))}return slc(ar,0,ai)}var dbf=function(l){return l==1?3:l<6?2:l==9?1:0};var exfl=function(ex){var le=0;if(ex)for(var k in ex){var l=ex[k].length;l>65535&&err(9),le+=l+4}return le},wzh=function(d,b,f,fn,u,c,ce,co){var fl2=fn.length,ex=f.extra,col=co&&co.length,exl=exfl(ex);wbytes(d,b,ce!=null?33639248:67324752),b+=4,ce!=null&&(d[b++]=20,d[b++]=f.os),d[b]=20,b+=2,d[b++]=f.flag<<1|(c<0&&8),d[b++]=u&&8,d[b++]=f.compression&255,d[b++]=f.compression>>8;var dt=new Date(f.mtime==null?Date.now():f.mtime),y=dt.getFullYear()-1980;if((y<0||y>119)&&err(10),wbytes(d,b,y<<25|dt.getMonth()+1<<21|dt.getDate()<<16|dt.getHours()<<11|dt.getMinutes()<<5|dt.getSeconds()>>1),b+=4,c!=-1&&(wbytes(d,b,f.crc),wbytes(d,b+4,c<0?-c-2:c),wbytes(d,b+8,f.size)),wbytes(d,b+12,fl2),wbytes(d,b+14,exl),b+=16,ce!=null&&(wbytes(d,b,col),wbytes(d,b+6,f.attrs),wbytes(d,b+10,ce),b+=14),d.set(fn,b),b+=fl2,exl)for(var k in ex){var exf=ex[k],l=exf.length;wbytes(d,b,+k),wbytes(d,b+2,l),d.set(exf,b+4),b+=4+l}return col&&(d.set(co,b),b+=col),b},wzf=function(o,b,c,d,e){wbytes(o,b,101010256),wbytes(o,b+8,c),wbytes(o,b+10,c),wbytes(o,b+12,d),wbytes(o,b+16,e)},ZipPassThrough=(function(){function ZipPassThrough2(filename){this.filename=filename,this.c=crc(),this.size=0,this.compression=0}return ZipPassThrough2.prototype.process=function(chunk,final){this.ondata(null,chunk,final)},ZipPassThrough2.prototype.push=function(chunk,final){this.ondata||err(5),this.c.p(chunk),this.size+=chunk.length,final&&(this.crc=this.c.d()),this.process(chunk,final||!1)},ZipPassThrough2})();var ZipDeflate=(function(){function ZipDeflate2(filename,opts){var _this=this;opts||(opts={}),ZipPassThrough.call(this,filename),this.d=new Deflate(opts,function(dat,final){_this.ondata(null,dat,final)}),this.compression=8,this.flag=dbf(opts.level)}return ZipDeflate2.prototype.process=function(chunk,final){try{this.d.push(chunk,final)}catch(e){this.ondata(e,null,final)}},ZipDeflate2.prototype.push=function(chunk,final){ZipPassThrough.prototype.push.call(this,chunk,final)},ZipDeflate2})();var Zip=(function(){function Zip2(cb){this.ondata=cb,this.u=[],this.d=1}return Zip2.prototype.add=function(file){var _this=this;if(this.ondata||err(5),this.d&2)this.ondata(err(4+(this.d&1)*8,0,1),null,!1);else{var f=strToU8(file.filename),fl_1=f.length,com=file.comment,o=com&&strToU8(com),u=fl_1!=file.filename.length||o&&com.length!=o.length,hl_1=fl_1+exfl(file.extra)+30;fl_1>65535&&this.ondata(err(11,0,1),null,!1);var header=new u8(hl_1);wzh(header,0,file,f,u,-1);var chks_1=[header],pAll_1=function(){for(var _i=0,chks_2=chks_1;_i<chks_2.length;_i++){var chk=chks_2[_i];_this.ondata(null,chk,!1)}chks_1=[]},tr_1=this.d;this.d=0;var ind_1=this.u.length,uf_1=mrg(file,{f,u,o,t:function(){file.terminate&&file.terminate()},r:function(){if(pAll_1(),tr_1){var nxt=_this.u[ind_1+1];nxt?nxt.r():_this.d=1}tr_1=1}}),cl_1=0;file.ondata=function(err2,dat,final){if(err2)_this.ondata(err2,dat,final),_this.terminate();else if(cl_1+=dat.length,chks_1.push(dat),final){var dd=new u8(16);wbytes(dd,0,134695760),wbytes(dd,4,file.crc),wbytes(dd,8,cl_1),wbytes(dd,12,file.size),chks_1.push(dd),uf_1.c=cl_1,uf_1.b=hl_1+cl_1+16,uf_1.crc=file.crc,uf_1.size=file.size,tr_1&&uf_1.r(),tr_1=1}else tr_1&&pAll_1()},this.u.push(uf_1)}},Zip2.prototype.end=function(){var _this=this;if(this.d&2){this.ondata(err(4+(this.d&1)*8,0,1),null,!0);return}this.d?this.e():this.u.push({r:function(){_this.d&1&&(_this.u.splice(-1,1),_this.e())},t:function(){}}),this.d=3},Zip2.prototype.e=function(){for(var bt=0,l=0,tl=0,_i=0,_a2=this.u;_i<_a2.length;_i++){var f=_a2[_i];tl+=46+f.f.length+exfl(f.extra)+(f.o?f.o.length:0)}for(var out=new u8(tl+22),_b2=0,_c=this.u;_b2<_c.length;_b2++){var f=_c[_b2];wzh(out,bt,f,f.f,f.u,-f.c-2,l,f.o),bt+=46+f.f.length+exfl(f.extra)+(f.o?f.o.length:0),l+=f.b}wzf(out,bt,this.u.length,tl,l),this.ondata(null,out,!0),this.d=2},Zip2.prototype.terminate=function(){for(var _i=0,_a2=this.u;_i<_a2.length;_i++){var f=_a2[_i];f.t()}this.d=2},Zip2})();function firstCampaignScenarioId(campaigns){let id=campaigns?.[0]?.definition?.graph?.nodes?.[0]?.scenario?.scenarioId;return typeof id=="string"?id:void 0}function featuredCardId(pack){let own=new Set(pack.cards.map(card=>card.id)),villainOf=scenarios=>{for(let scenario of scenarios){let id=scenario.villainCardId;if(typeof id=="string"&&own.has(id))return id}},firstOfType=type=>pack.cards.find(card=>card.type===type)?.id;if(pack.manifest.kind==="hero")return firstOfType("hero_identity");if(pack.manifest.kind==="house-rule"){let base=pack.manifest.languages?.base;return[...pack.files.keys()].sort().map(path=>parsePackCardImagePath(path)).find(picture=>picture!==void 0&&picture.lang===base)?.code}if(pack.manifest.kind==="campaign"){let scenarioId=firstCampaignScenarioId(pack.campaigns),scenario=(pack.scenarios??[]).find(one=>one.id===scenarioId),fromCampaign=scenario?villainOf([scenario]):void 0;if(fromCampaign)return fromCampaign}return villainOf(pack.scenarios??[])??firstOfType("villain")??firstOfType("main_scheme")??firstOfType("hero_identity")}function featuredImages(pack,cardId,images){let base=pack.manifest.languages?.base;if(!base)return[];if(pack.manifest.kind==="house-rule")return[packCardImagePath(base,cardId)].filter(path=>images.has(path));let type=pack.cards.find(card=>card.id===cardId)?.type,codes=[cardId];return type==="hero_identity"&&cardId.endsWith("a")&&codes.push(`${cardId.slice(0,-1)}b`),codes.map(code=>packCardImagePath(base,code)).filter(path=>images.has(path))}function buildPreview(pack,manifest=pack.manifest){let images=[...pack.files.keys()].filter(path=>parsePackCardImagePath(path)!==void 0).sort(),imageSet=new Set(images),cardId=featuredCardId(pack),featuredPaths=cardId?featuredImages(pack,cardId,imageSet):[],cover=typeof manifest.cover=="string"&&pack.files.has(manifest.cover)?manifest.cover:void 0;return{preview:{schema:PACK_PREVIEW_SCHEMA_VERSION,packId:manifest.id,version:manifest.version,...manifest.description?{description:manifest.description}:{},...cardId?{featured:{cardId,images:featuredPaths}}:{},...cover?{cover}:{},images,...manifest.languages?{languages:manifest.languages}:{},cards:pack.cards,...(manifest.achievements?.length??0)>0?{achievements:manifest.achievements}:{},decks:[...pack.decks??[]].map(deck=>({id:deck.id,name:deck.name,identityCardId:deck.identityCardId,cards:deck.cards.map(entry=>({cardId:entry.cardId,quantity:entry.quantity}))}))},thumbFrom:cover??featuredPaths[0]}}var PackBuildError=class extends Error{constructor(issues){super(`pack is invalid:
2
2
  ${issues.map(i2=>`${i2.path}: ${i2.message}`).join(`
3
3
  `)}`);this.issues=issues;this.name="PackBuildError"}issues},encoder=new TextEncoder,json=value=>encoder.encode(`${JSON.stringify(value,null,2)}
4
4
  `);function readJsonFiles(dir){return existsSync(dir)?readdirSync(dir).filter(name=>name.endsWith(".json")).sort().map(name=>JSON.parse(readFileSync(join(dir,name),"utf8"))):[]}function walkFiles(dir){if(!existsSync(dir))return[];let out=[];for(let name of readdirSync(dir).sort()){let full=join(dir,name);statSync(full).isDirectory()?out.push(...walkFiles(full)):out.push(full)}return out}var nativeImport=path=>import(pathToFileURL(path).href);async function loadPackSource(srcDir,options={}){let author=JSON.parse(readFileSync(join(srcDir,"pack.json"),"utf8")),cards=readJsonFiles(join(srcDir,"cards")),decks=readJsonFiles(join(srcDir,"decks")),scenarios=readJsonFiles(join(srcDir,"scenarios")),encounterSets=readJsonFiles(join(srcDir,"encounter-sets")),campaigns=readJsonFiles(join(srcDir,"campaigns")),abilities={},abilitiesEntry=join(srcDir,"abilities","index.ts");if(existsSync(abilitiesEntry)){let module=await(options.importModule??nativeImport)(abilitiesEntry);if(!module.default)throw new Error("abilities/index.ts must export a default ability registry");abilities=module.default}let assets=new Map;for(let root of["art","alt-art"])for(let full of walkFiles(join(srcDir,root)))assets.set(relative(srcDir,full).split(sep).join("/"),new Uint8Array(readFileSync(full)));for(let full of walkFiles(join(srcDir,"cards"))){let path=relative(srcDir,full).split(sep).join("/");path.includes("/",6)&&assets.set(path,new Uint8Array(readFileSync(full)))}for(let name of["CREDITS.md","PERMISSION.md"]){let full=join(srcDir,name);existsSync(full)&&assets.set(name,new Uint8Array(readFileSync(full)))}let cover=author.cover;if(typeof cover=="string"&&isSafePackPath(cover)&&!assets.has(cover)){let full=join(srcDir,...cover.split("/"));existsSync(full)&&statSync(full).isFile()&&assets.set(cover,new Uint8Array(readFileSync(full)))}return{author,cards,abilities,decks,scenarios,encounterSets,campaigns,assets}}var byCode=(a,b)=>a.id<b.id?-1:a.id>b.id?1:0;function assemblePack(source){let files=new Map,cards=[...source.cards].sort(byCode),abilities=Object.fromEntries(Object.entries(source.abilities).sort(([a],[b])=>a<b?-1:1)),decks=[...source.decks].sort((a,b)=>a.id<b.id?-1:1);files.set("data/cards.json",json(cards)),Object.keys(abilities).length>0&&files.set("data/abilities.json",json(abilities)),decks.length>0&&files.set("data/decks.json",json(decks)),source.scenarios.length>0&&files.set("data/scenarios.json",json(source.scenarios));let encounterSets=[...source.encounterSets??[]].sort((a,b)=>a.id<b.id?-1:1);encounterSets.length>0&&files.set("data/encounter-sets.json",json(encounterSets));let campaigns=source.campaigns??[];campaigns.length>0&&files.set("data/campaigns.json",json(campaigns));for(let[path,bytes]of source.assets)files.set(path,bytes);let listed=[...files.entries()].sort(([a],[b])=>a<b?-1:1).map(([path,bytes])=>({path,bytes:bytes.length,sha256:sha256Hex(bytes)})),{author}=source;return{manifest:{schema:1,id:author.id,version:author.version,kind:author.kind,name:author.name,authors:author.authors,description:author.description,requires:{app:author.requires.app,dslFeatures:dslFeatures(abilities,campaignDefinitionsOf(campaigns)),packs:author.requires.packs??[]},contents:{cards:"data/cards.json",...files.has("data/abilities.json")?{abilities:"data/abilities.json"}:{},...files.has("data/scenarios.json")?{scenarios:"data/scenarios.json"}:{},...files.has("data/decks.json")?{decks:"data/decks.json"}:{},...files.has("data/encounter-sets.json")?{encounterSets:"data/encounter-sets.json"}:{},...files.has("data/campaigns.json")?{campaigns:"data/campaigns.json"}:{}},...author.pictures?{pictures:author.pictures}:{},...author.languages?{languages:author.languages}:{},...author.altArt?{altArt:author.altArt}:{},...author.houseRule?{houseRule:author.houseRule}:{},...author.permission?{permission:author.permission}:{},...author.templateCredit?{templateCredit:author.templateCredit}:{},...author.translators?{translators:author.translators}:{},...author.cover!==void 0?{cover:author.cover}:{},...author.achievements?{achievements:author.achievements}:{},...author.tags?{tags:author.tags}:{},...author.wave!==void 0?{wave:author.wave}:{},...author.unlock!==void 0?{unlock:author.unlock}:{},files:listed,totalBytes:listed.reduce((sum,file)=>sum+file.bytes,0),license:author.license},files,cards,abilities,decks,scenarios:source.scenarios,...encounterSets.length>0?{encounterSets}:{},...campaigns.length>0?{campaigns}:{}}}var ZIP_EPOCH=new Date(1980,0,1,12);function zipPack(manifest,files){let chunks=[],failure,zip=new Zip((error,chunk)=>{error?failure=error:chunks.push(chunk)}),entries=[["pack.json",json(manifest)],...[...files.keys()].sort().map(path=>[path,files.get(path)])];for(let[path,bytes]of entries){let entry=new ZipDeflate(path,{level:6});entry.mtime=ZIP_EPOCH,zip.add(entry),entry.push(bytes,!0)}if(zip.end(),failure)throw failure;let out=new Uint8Array(chunks.reduce((n,c)=>n+c.length,0)),at=0;for(let chunk of chunks)out.set(chunk,at),at+=chunk.length;return out}async function buildPack(srcDir,outDir,options={}){let{importModule,...validateOptions}=options,source=await loadPackSource(srcDir,importModule?{importModule}:{}),pack=assemblePack(source),issues=validatePack(readPackInput(pack.manifest,pack.files),validateOptions);if(issues.length>0)throw new PackBuildError(issues);let write=(path,bytes)=>{let full=join(outDir,...path.split("/"));mkdirSync(dirname(full),{recursive:!0}),writeFileSync(full,bytes)};for(let[path,bytes]of pack.files)write(path,bytes);write("pack.json",json(pack.manifest));let zip=zipPack(pack.manifest,pack.files),zipPath=join(outDir,`${pack.manifest.id}-${pack.manifest.version}.zip`);write(`${pack.manifest.id}-${pack.manifest.version}.zip`,zip);let{preview,thumbFrom}=buildPreview(pack);return write("preview.json",json(preview)),thumbFrom&&write("thumb.webp",pack.files.get(thumbFrom)),{manifest:pack.manifest,zipPath,zipBytes:zip.length,zipSha256:sha256Hex(zip)}}export{PackBuildError,loadPackSource,assemblePack,zipPack,buildPack};
package/dist/import.js CHANGED
@@ -1 +1 @@
1
- import{formatImportReport,importMarvelCdbPack,registerMarvelCdbNormalizer}from"./chunks/chunk-JR3ALXBR.js";import"./chunks/chunk-GK7LCLI7.js";import"./chunks/chunk-TUJLFNR7.js";import"./chunks/chunk-EKR67REN.js";export{formatImportReport,importMarvelCdbPack,registerMarvelCdbNormalizer};
1
+ import{formatImportReport,importMarvelCdbPack,registerMarvelCdbNormalizer}from"./chunks/chunk-DX44O32N.js";import"./chunks/chunk-WFEXO5DU.js";import"./chunks/chunk-3SR23UJ7.js";import"./chunks/chunk-ACT4TJXC.js";export{formatImportReport,importMarvelCdbPack,registerMarvelCdbNormalizer};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{builtinGameDeps,validateBuiltinPack}from"./chunks/chunk-6F73M3HY.js";import{PACK_ABILITY_ID,REQUIRED_PACK_FILES,SUPPORTED_DSL_FEATURES,campaignDefinitionsOf,checkPackCampaigns,definePackAbilities,dslFeatures,isPlainJson,isUnscriptedAbilityIssue,packCampaignsOf,publishIssues,readPackInput,sha256Hex,splitIssues,validatePack}from"./chunks/chunk-TUJLFNR7.js";import{campaignDepsWithPacks,campaignGameWithPacks,cardPoolWithPack,cardPoolWithPacks,customContentOfPacks,gameDepsWithPack,gameDepsWithPacks,packCampaignDefinitionOf,packCampaignDefinitions,packCampaignRecords,packEncounterSetRecords,packModularSetChoices,packScenarioRecords,scenarioWithPacks}from"./chunks/chunk-S3DCO2A6.js";import{ANY_ASPECT_CARD,ANY_NUMBER,ANY_RESOURCE,AOA_CAMPAIGN_DEFINITION,AOA_DEFEATED,AOA_MISSIONS,AOA_NOT_DEFEATED,AOA_OVERSEERS,AOA_PROTECT_THE_PROFESSOR,AOS_CAMPAIGN_DEFINITION,AS_DRONE,BUILTIN_PACKS,CAMPAIGNS,CAN_TAKE_THIS_ATTACK,COMMUNITY_DECK_AUTHORS,CORE_ABILITIES,CORE_BUILTIN_PACK,CORE_DEPS,CUSTOM_SCENARIO_FIELDS,ENCOUNTER_CARD,ENCOUNTER_CARD_CATEGORIES,ENCOUNTER_SIDE_SCHEME,ENGINE_ONLY_DSL_EXAMPLES,FRIENDLY_CHARACTER,GMW_BALANCED_FIELD,GMW_BALANCED_TOGGLES,GMW_CAMPAIGN_DEFINITION,INFINITES_GENE_POOL_THREAT_MAX,MOJO_CAMPAIGN_DEFINITION,MTS_CAMPAIGN_DEFINITION,NEXT_EVOL_CAMPAIGN_DEFINITION,NOT_READY_PACK_CODES,PAID_CARDS,PAID_IN_PLAY_CARDS,PLAYABLE_ABILITIES,PLAYABLE_DEPS,PLAYABLE_ENCOUNTER_SETS,PLAYABLE_SCENARIO_RECORDS,PLAYER_SIDE_SCHEME,RANDOM_VILLAIN,SHADOWLAND_CAMPAIGN_DEFINITION,SM_CAMPAIGN_DEFINITION,TEAM_UP_CARD,TRAIT,TRORS_CAMPAIGN_DEFINITION,UNSCRIPTED_ENCOUNTER_SET_IDS,VILLAIN_OR_VILLAINOUS,WAVE10_ABILITIES,WAVE10_BUILTIN_PACKS,WAVE10_CARDS,WAVE10_DEPS,WAVE10_GAME_ENCOUNTER_SETS,WAVE11_ABILITIES,WAVE11_BUILTIN_PACKS,WAVE11_CARDS,WAVE11_DEPS,WAVE11_GAME_ENCOUNTER_SETS,WAVE1_ABILITIES,WAVE1_BUILTIN_PACKS,WAVE1_DEPS,WAVE1_REPRINT_ABILITIES,WAVE2_ABILITIES,WAVE2_BUILTIN_PACKS,WAVE2_DEPS,WAVE2_REPRINT_ABILITIES,WAVE3_ABILITIES,WAVE3_BUILTIN_PACKS,WAVE3_CARDS,WAVE3_DEPS,WAVE3_REPRINT_ABILITIES,WAVE4_BUILTIN_PACKS,WAVE5_BUILTIN_PACKS,WAVE6_BUILTIN_PACKS,WAVE7_ABILITIES,WAVE7_BUILTIN_PACKS,WAVE7_CARDS,WAVE7_DEPS,WAVE8_ABILITIES,WAVE8_BUILTIN_PACKS,WAVE8_CARDS,WAVE8_DEPS,WAVE9_ABILITIES,WAVE9_BUILTIN_PACKS,WAVE9_CARDS,WAVE9_DEPS,YOUR_HERO,YOUR_IDENTITY,aDifferentCard,aScheme,abilitiesForCards,accelerationTokensOn,accusationWrongGuesses,accuse,accusedWrong,actingCharacter,action,activatesBeforeVillain,activatingEnemy,activationIs,activationOrderOf,addAccelerationToken,addCounters,addMainSchemeStageToVictoryDisplay,addToVictoryDisplay,addVillain,additionalAttackCost,additionalCostToPlay,additionalCostToReady,additionalPowerCost,additionalThwartCost,adjustBoostCount,advanceMainScheme,advanceToSetAsideVillain,after,afterNextCardPlayed,agile,allOf,allowUnlabeledAttack,alterEgoAction,alterEgoInterrupt,alterEgoResponse,amount,anAttackableEnemy,anEnemy,andThen,anyIn,anyNumberOfToughStatusCards,anyOf,anyOfCards,anyPlayerEliminated,applyAsBoostCard,applyRuleUntil,areaPlayersDefeated,assignDamage,atEndOfActivation,atEndOfAttack,atEndOfPhase,atEndOfRound,atEndOfThwart,atMost,attachCard,attachCost,attachInstruction,attack,attackAnEnemy,attackDamageDealt,attackExcessAsDealt,attackInProgress,attackInitiatedAgainst,attackPreventedAmount,attackPreventedTotal,attackResolvedLabeled,attackTarget,attackTotalAtk,attackUsedAtk,attackWasPrevented,attackableAsMinion,attackedBy,attackedPlayer,attackedThisPhase,attackingEnemy,attacksDealAdditionalDamage,attacksGainKeywords,attacksLoseKeywords,baseStatOf,baseStatsFromYourHero,basicPowerBy,basicPowerCost,basicPowerIs,basicPowerStatIs,basicThwartOnlyAgainst,basicThwartsIgnore,bindTargets,blankTextBoxForPlayers,blankTextBoxUntil,blanksTextBox,boost,boostAreaIconsOn,boostCardOf,boostCardsFromSet,boostIconsCount,boostIconsOn,buildScenarioDeck,buildWave11Scenario,builtinPackProblems,campaignDefinitionOf,campaignDefinitionProblems,campaignInstructionsOf,campaignLogAtLeast,campaignLogCardCounter,campaignLogCardRecorded,campaignLogCards,campaignLogHas,campaignLogIsSet,campaignLogValue,campaignModularPickProblem,canAttachTo,canAttachToCategory,canChangeForm,canEnterPlay,canFlip,canPayResources,canPlayFromHand,canRemoveThreatFrom,canSpendDifferentResources,canTakeStatus,canUseBasicPower,cancelBoostedActivation,cancelConsequentialDamage,cancelIt,cancelRevealedCard,cancelWhenRevealed,cannotActivate,cannotAttach,cannotBeAttachedUnlessInPlay,cannotBeCanceled,cannotBeDefeated,cannotBeHealed,cannotBeReadiedByPlayerCards,cannotChangeFormUntil,cannotChooseOption,cannotChooseToDiscard,cannotEnterPlay,cannotFlip,cannotHaveStatus,cannotLeavePlay,cannotMakeBasicAttacks,cannotReadyUntil,cannotRecover,cannotResolveTriggeredAbilities,cannotThwart,cardIdsIn,cards,cardsFrom,cardsOfComposedSets,centralMainScheme,changeAdditionalForm,changeForm,changeFormCost,changeToHeroFormNamed,changeToHeroFormWithTrait,changeToOtherHeroForm,changeVillainForm,characterDidThisPhase,checkModularPickCount,checkPlayableDifficultySets,choiceFoundNothing,chooseCardCost,chooseCardType,chooseCards,chooseEncounterCardType,chooseGroup,chooseMainSchemeStages,chooseNumber,chooseOne,chooseOneBy,chooseOptions,choosePlayer,chooseTarget,chooseTargetCost,chosen,chosenGroup,chosenModularSetIds,chosenPlayer,chosenVillain,civilWarGameModes,civilWarModularSets,civilWarSidesOffer,communityDeckUrl,communityDecks,competitiveOnly,competitiveOnlyTexts,completeMainScheme,confuse,consideredToHaveHitPoints,consideredToHaveResourceIcon,constant,controllerOf2 as controllerOf,coreScenario,costIf,costModifier,costsPayableByAnyPlayer,countAmong,countBoostIcons,countOf,countTowardStartingHand,counterLimit,countersAsResource,countersOn,countsAs,coveredByEngineRule,createGameArea,createScenarioArea,createScenarioPlayArea,customContentProblems,customModularPickProblem,customModularSetChoices,customScenarioProblems,damageAnEnemy,damageCardsCost,damageOn,damageSharedVillain,damageThisCardCost,damagedAtLeast,dealAsEncounterCard,dealDamage,dealDamageCost,dealDamageToChosenCost,dealEncounterCard,dealEncounterCardsCost,dealEncounterCardsToChosenPlayerCost,dealHiddenPiles,dealIndirectDamage,dealPoolOneAtATime,dealtEncounterCards,dealtEncounterCount,deckCountOf,deckDiscardIconsCount,declareDefender,defeat,defeatExcessDamage,defeatExcessThreat,defeatedWithExcessConsequentialDamage,defeatedWithExcessDamage,defeatingPlayer,defenderDefForAttack,defendingCharacter,defendsWithoutExhausting,defineAbilities,defineBuiltinPack,detach,difficultySetAlternativesFor,discard,discardAtRandom,discardBoostCard,discardCardsCost,discardChosenFromEncounterDeckCost,discardDeckUntil,discardEncounterCards,discardEncounterUntil,discardFacedownBoostCards,discardFromHand,discardFromHandCombinedCost,discardFromHandCost,discardRandomFromHandCost,discardStatusCost,discardStatusesTokensAndAttachments,discardThis,discardTopOfDeckCost,discardTopOfEncounterDeckCost,discardTuckedCost,discardUpToTopOfDeckCost,distinctAspectsOf,distinctTraitsOf,divide,doesNotExhaustToDefend,doubleDamageTaken,doubleNextCardSpent,doubleStat,doublesResourcesGeneratedForThisCard,doublesResourcesWhilePayingFor,draw,drawUpTo,droneFromDeck,duringPlayerPhase,duringTurnOf,duringVillainPhaseStepOne,each,eachGroupInPod,eachPlayer,eachPlayerCost,eachTimeUntil,eitherCost,encounterCard,encounterCards,encounterCardsOf,encounterIconsInPlay,encounterLookDiscardCost,encounterSetAside,encounterSetOf,endGame,enemyActivates,enemyAttack,enemyAttacksEnemy,enemyAttacksYouCost,enemyCanAttackAnother,enemyLeader,enemyScheme,enemyTeam,enemyTeamChooses,enemyToAttack,engage,engagedPlayerOf,engineOnlyDslProblems,entersPlayExhausted,eventAmount,eventDamageTaken,eventDamageTakenBy,eventDealt,eventKindIs,eventPlayer,eventResult,eventSource,eventSourceEnemy,eventTarget,eventTargetsTogether,exactlyDefeated,exactlyDefeatedByPower,excludedFromAllyLimit,excludedFromPlayerSideSchemeLimit,exhaust,exhaustCardsCost,exhaustEachCost,exhaustThis,exhaustYourHero,exists,expertSetReplaceable,extraBoostCardsForVillain,faceNamed,fieldsIn,finalStep,find,findCard,firstAttackThisTurn,firstPlayer,firstPlayerAction,firstPlayerPicksFromHand,firstRevealGainsSurge,firstThisRound,flatten,flipCard,flipCardsCost,flipThis,focusedMainScheme,forAnIdentityNotInThisGame,forEachCard,forEachPlayer,forEachPlayerInChosenOrder,forcedAction,forcedInterrupt,forcedResponse,formChangeCost,friendlyCharacterAttacks,fromAnyAspect,gainFromHiddenPile,gainKeywordUntil,gainTraitUntil,gainTraitsOfUntil,gainsAbility,gainsIcon,gainsKeyword,gainsKeywordX,gainsKeywordsOf,gainsTrait,gainsTraitsOf,gameAreasSplit,genePoolThreatOffer,generatesAmount,generatesPerCard,gets,giveBasicPowerBoostCard,giveBoostCard,giveBoostCardsCost,giveHeldBoostCard,giveStatus,giveStatusCost,giveTough,gmwBalancedHiddenFields,grantAdditionalMulligans,grantOwnedCards,grantedTo,grantingCard,grantsPreparation,groupPlayerCount,handCountOf,handSizeOf,hasAttachment,hasNamedResource,hasPrintedBoostAbility,hasStatus,hasTaggedAbility,hasTrait,heal,healCost,healYourIdentityCost,heroAction,heroInterrupt,heroNoCharacterIsTitledAs,heroResource,heroResponse,hiddenPileCount,highestStatAmong,hitPointsOf,holdMinion,horsemanSidesOffer,host,identifyMole,identityOf,ifElse,ifThen,ignoreAbilities,ignoreBoost,ignoreBoostAbilities,ignoreBoostForThisAttack,ignores,ignoresRetaliate,inAdditionalForm,inCampaign,inCampaignLogField,inCompetitiveMode,inDiscard,inEncounterSet,inForm,inGroup,inHand,inMode,inPlay,inPlayAreaOf,inScenarioPlayArea,inVictoryDisplay,increaseDamage,increaseDamageTaken,increaseNextCardCost,infinitesGenePoolThreatRecommendation,instead,interrupt,isAlterEgo,isAttached,isBaseEncounterSetId,isBaseScenarioId,isConfused,isHero,isModularChoice,isNotReadyCard,isScenarioSpecificSet,isStunned,joinGameArea,keepsExhausted,lastPlayedThisRound,leavingPlayLoses,limitPerPaidCard,logCardList,logCardRef,logFlag,logNumber,logOption,logText,lookAt,lookAtAndRearrange,lookAtTopOfScenarioDeckThenPlace,loseKeywordUntil,loseTraitUntil,losesIcon,losesKeyword,made,mainSchemeAdvancedBy,mainSchemeMarkedBy,mainSchemePicksOffer,mainSchemeStageGist,mainSchemeStageNumber,mainSchemeStagesOffer,mainSchemeStagesProblem,max,maxDamageTaken,maxOnePerTriggeringInstance,maxSustainedDamage,mayLookAtTopOfEncounterDeckUntil,mergeCosts,mergeRegistries,min,minDamageTaken,modifyAttack,modifyBasicPower,modifyCardEffect,modifyCardEffectsUntil,modifyConsequentialDamage,modifyStat,modifyStatOf,modifyThwart,modularPickCountProblem,modularPickCountRange,modularPickProblem,modularSetContents,mojoCheckedOffSets,mojoModularSetPicks,mostCommonHandTypeCount,moveActiveCounterToNextInRow,moveActiveCounterToNextVillain,moveBoostCards,moveCards,moveCardsInto,moveCounters,moveThreat,multiplyStat,named,namedByTeamUpOf,nextAfter,not,notCountedTowardHandSize,notMatching,notOfChosenCardType,obligation,ofChosenCardType,ofClassification,ofIdentitySetTitled,ofTeamUpSet,offersEasierStart,offersGenePoolThreat,on,onChosenMainScheme,oncePerPaidCard,oncePerPhase,oncePerPhasePerEventPlayer,oncePerRound,oncePerRoundPerPlayer,oneCopyOf,onlyCharacterRemovesThreat,onlySourceRemovesThreat,onlyThwartsRemoveThreat,opsOfKind,option,otherFaceOf,otherPlayers,outsideFact,overdefeated,overpaidWhenPlayed,ownScriptsOf,ownerOf,packScenarioOffer,paidCards,paidInPlayCards,paidType,paidTypeCount,paidUsingResourceFrom,paidWith,paidWithCard,paidWithOnly,paidWithResourceCard,pairCards,pairLimit,partOf,passEncounterCard,payPrintedCostOf,payingFor,perHero,placeCountersCost,placeDamage,placeOnTopOrBottom,placeOnTopOrBottomOfPlayerDeck,placeThreat,placeThreatOnSharedScheme,playFromDeckIgnoringCost,playFromDeckReducingCost,playFromDiscard,playFromHandIgnoringCost,playFromHandReducingCost,playFromSeparateDeck,playNote,playOnlyIf,playSetAside,playTuckedCard,playWithTopOfDeckFaceup,playWithTopOfEncounterDeckFaceup,playableAttachments,playableScenario,playableScenarioOffer,playableScenarioWithCustom,playableStarterDeckSetup,playableTopOfDeck,playableTucked,playedThisPhase,playedThisRound,playedThisTurn,playedVia,playerOrElse,playersCannotDiscard,playersWhere,preparation,preventAllDamageTo,preventConsequentialDamage,preventDamage,preventThreat,printedBoostAreaIconsOn,printedCostAtLeast,printedCostOf,printedForm,printedHpNumeralOf,printedHpOf,printedResourcesInHandAs,printedResourcesOf,printedStatOf,printsAbility,product,putIntoPlay,putIntoPlayAsHost,putIntoPlayFacedown,putIntoPlayFromSetAside,putLinkedAllyIntoPlay,putMainSchemeStageIntoPlay,query,raiseMoment,randomCivilWarScenario,reachableFromPod,reaching,readsAtkOf,readsPaymentTypesOf,ready,readyCardsCost,recordInCampaignLog,reduceCostOfCards,reduceCostToPlay,reduceDamage,reduceDamageTo,reduceNextCardCost,reducesAttackDamageTaken,refCount,refMatches,remainingHpCompare,remainingHpOf,removeAccelerationToken,removeAllCounters,removeAllCountersFrom,removeAnAccelerationToken,removeCounter,removeCountersAmong,removeCountersFrom,removeEachCounterFrom,removeFromCampaign,removeMainSchemeStage,removeMainSchemeStages,removeStatus,removeThreat,removeThreatCost,removeThreatFromAScheme,removeThreatFromChosenCost,removeThreatUpToCost,removeUpToCounters,removeVillain,removedFromGameCards,reorderCards,repeatTimes,repeatWhile,replaceAttachHost,replaceBoostCount,replaceLeaveDestination,replaceNextVillainPhaseWithPlayerPhase,replaceStatus,replaceTuckHost,reportFact,resetHitPoints,resolveAttackAgainst,resolveBoostAbilitiesOf,resolveForcedInterruptOf,resolveForcedResponseCost,resolveForcedResponseOf,resolveModes,resolveOneTagged,resolvePreparationsOf,resolveSetups,resolveSpecialCost,resolveSpecials,resolveSpecialsOf,resolveTagged,resolveWhenDefeatedOf,resolveWhenRevealedOf,resource,resourceTypesOf,resourcesGeneratedAsWild,resourcesPaidBy,response,restrictedLimit,retargetAttack,retargetPlayerAttack,returnEachToHandCost,returnToHandAfterResolving,returnToHandCost,revealCard,revealEncounterCard,revealFromSetAsideModularSet,revealHeldMinion,revealHiddenPile,revealInstead,revealMainSchemeStage,revealNextVillainStage,revealSetAside,revealTopOfScenarioDeck,revealTopOfSeparateDeck,revealedFromEncounterDeck,revealedPileCardCount,rotateEngagement,rule,sameClassificationAs,scaled,scenarioArea,scenarioAreaCount,scenarioDeck,scenarioGameSetIds,scenarioSideClause,scenarioWithVillain,schemeStartedByAttackBoost,schemeThreatOn,searchAndReveal,searchCollection,searchEncounterIntoPlayCost,seedHiddenPiles,selectCards,self,sentence,separateDeckCards,separateDeckCountOf,setActiveVillain,setAside,setAsideDestination,setAsideModularSetCount,setDefeatDestination,setRemainingHitPoints,setVar,setVillainAside,setVillainSide,setup,sharesTitleWith,sharesTraitWith,sharesTraitWithHeroOf,shuffleDeck,shuffleEncounterDeck,shuffleInSetAsideModularSet,shuffleIntoSeparateDeck,shuffleMainSchemeStageGroup,shuffleMainSchemeStages,shuffleSeparateDeck,shuffleTopOfSeparateDeckIntoEncounterDeck,sitOut,skipNextVillainPhase,skippedCommunityDecks,skirmishOffer,special,spend,spendChosen,spendDifferentResources,spendEqualTo,spendPrinted,spendResources,spendSameType,spendUpTo,spendX,spendXResources,spendableForAnyPlayer,spendableForPlayersWhere,spendableFromTucked,standardSetReplaceable,starIconsOn,starterDeckSetup,statCompare,statOf,stateCheck,stateCheckFromEntering,statusCount,statusLimit,staysInHand,stillCountedByDiscarder,stun,sum,superlative,superlativePlayer,surge,swapCards,swapIdentity,swapMainScheme,swapVillain,swapVillainByTrait,tagged,taggedAbilitiesOn,takeAnyDamageCost,takeControl,takeDamage,takeDamageCost,takeIndirectDamageCost,takeIntoHand,takesConsequentialDamage,takesDamageOnlyFrom,takesDamageOnlyFromAttacks,takesFirstTurn,teamUpCharacter,teamUpCharacters,textBoxCannotBeBlanked,thatAttackGainsKeywords,thatPlayer,theAccused,theAffectedCard,theMainScheme,theMole,theVillain,thisCardGenerates,thisGroup,threatAtLeast,threatOn,thwart,thwartAScheme,thwartInProgress,thwartTarget,titled,toScenarioDeck,topOfDeck,topOfDeckIsFaceup,topOfDeckMatches,topOfEncounterDeckIsFaceup,topOfEncounterDeckMatches,topOfEncounterDeckShowsIcons,topOfEncounterDeckShowsNoIcons,topOfYourDeckHas,totalPrintedCost,totalPrintedResources,totalStatOf,traitEncounterDeck,traitNumber,treatAsAlly,treatAsMinion,treatAttachedAllyAsMinion,treatAttachedHeroAsMinion,treatAttachedMinionAsAlly,treatAttachedVillainAsMinion,treatSelfAsAlly,tuckCards,tuckLimit,tuckedCount,tuckedUnder,tuckedUnderRef,turnFacedown,uncancellable,undefendedAttack,upgradesCannotBeRemoved,useActionAbility,useThwInsteadOfAtk,usingBasicPower,validateDefinition,valueAtLeast,valueAtMost,valueEquals,varAtLeast,varFor,varOf,victoryCondition,victoryDisplayCards,victoryDisplayCount,villainChoiceOf,villainChoiceOffer,villainOnSide,villainOptionOf,villainStageNumberOf,wave10Scenario,wave10StarterDeckSetup,wave11Scenario,wave11ScenarioRecord,wave11StarterDeckSetup,wave1ReprintPairs,wave1Scenario,wave1StarterDeckSetup,wave2ReprintPairs,wave2Scenario,wave2StarterDeckSetup,wave3ReprintPairs,wave3Scenario,wave3StarterDeckSetup,wave7Scenario,wave7StarterDeckSetup,wave8Scenario,wave8StarterDeckSetup,wave9Scenario,wave9StarterDeckSetup,when,whenCompleted,whenDefeated,whenRevealed,whenRevealedAlterEgo,whenRevealedHero,whenSpentGenerate,whileOnChosenMainScheme,whileTucked,withFewestCounters,withModularSetContents,withMostCounters,you,youAre,youAreNamed,youHaveTrait,yourIdentity,yourLeader,yourMainScheme,yourTeam,zone,zoneCountOf}from"./chunks/chunk-EKR67REN.js";export{ANY_ASPECT_CARD,ANY_NUMBER,ANY_RESOURCE,AOA_CAMPAIGN_DEFINITION,AOA_DEFEATED,AOA_MISSIONS,AOA_NOT_DEFEATED,AOA_OVERSEERS,AOA_PROTECT_THE_PROFESSOR,AOS_CAMPAIGN_DEFINITION,AS_DRONE,BUILTIN_PACKS,CAMPAIGNS,CAN_TAKE_THIS_ATTACK,COMMUNITY_DECK_AUTHORS,CORE_ABILITIES,CORE_BUILTIN_PACK,CORE_DEPS,CUSTOM_SCENARIO_FIELDS,ENCOUNTER_CARD,ENCOUNTER_CARD_CATEGORIES,ENCOUNTER_SIDE_SCHEME,ENGINE_ONLY_DSL_EXAMPLES,FRIENDLY_CHARACTER,GMW_BALANCED_FIELD,GMW_BALANCED_TOGGLES,GMW_CAMPAIGN_DEFINITION,INFINITES_GENE_POOL_THREAT_MAX,MOJO_CAMPAIGN_DEFINITION,MTS_CAMPAIGN_DEFINITION,NEXT_EVOL_CAMPAIGN_DEFINITION,NOT_READY_PACK_CODES,PACK_ABILITY_ID,PAID_CARDS,PAID_IN_PLAY_CARDS,PLAYABLE_ABILITIES,PLAYABLE_DEPS,PLAYABLE_ENCOUNTER_SETS,PLAYABLE_SCENARIO_RECORDS,PLAYER_SIDE_SCHEME,RANDOM_VILLAIN,REQUIRED_PACK_FILES,SHADOWLAND_CAMPAIGN_DEFINITION,SM_CAMPAIGN_DEFINITION,SUPPORTED_DSL_FEATURES,TEAM_UP_CARD,TRAIT,TRORS_CAMPAIGN_DEFINITION,UNSCRIPTED_ENCOUNTER_SET_IDS,VILLAIN_OR_VILLAINOUS,WAVE10_ABILITIES,WAVE10_BUILTIN_PACKS,WAVE10_CARDS,WAVE10_DEPS,WAVE10_GAME_ENCOUNTER_SETS,WAVE11_ABILITIES,WAVE11_BUILTIN_PACKS,WAVE11_CARDS,WAVE11_DEPS,WAVE11_GAME_ENCOUNTER_SETS,WAVE1_ABILITIES,WAVE1_BUILTIN_PACKS,WAVE1_DEPS,WAVE1_REPRINT_ABILITIES,WAVE2_ABILITIES,WAVE2_BUILTIN_PACKS,WAVE2_DEPS,WAVE2_REPRINT_ABILITIES,WAVE3_ABILITIES,WAVE3_BUILTIN_PACKS,WAVE3_CARDS,WAVE3_DEPS,WAVE3_REPRINT_ABILITIES,WAVE4_BUILTIN_PACKS,WAVE5_BUILTIN_PACKS,WAVE6_BUILTIN_PACKS,WAVE7_ABILITIES,WAVE7_BUILTIN_PACKS,WAVE7_CARDS,WAVE7_DEPS,WAVE8_ABILITIES,WAVE8_BUILTIN_PACKS,WAVE8_CARDS,WAVE8_DEPS,WAVE9_ABILITIES,WAVE9_BUILTIN_PACKS,WAVE9_CARDS,WAVE9_DEPS,YOUR_HERO,YOUR_IDENTITY,aDifferentCard,aScheme,abilitiesForCards,accelerationTokensOn,accusationWrongGuesses,accuse,accusedWrong,actingCharacter,action,activatesBeforeVillain,activatingEnemy,activationIs,activationOrderOf,addAccelerationToken,addCounters,addMainSchemeStageToVictoryDisplay,addToVictoryDisplay,addVillain,additionalAttackCost,additionalCostToPlay,additionalCostToReady,additionalPowerCost,additionalThwartCost,adjustBoostCount,advanceMainScheme,advanceToSetAsideVillain,after,afterNextCardPlayed,agile,allOf,allowUnlabeledAttack,alterEgoAction,alterEgoInterrupt,alterEgoResponse,amount,anAttackableEnemy,anEnemy,andThen,anyIn,anyNumberOfToughStatusCards,anyOf,anyOfCards,anyPlayerEliminated,applyAsBoostCard,applyRuleUntil,areaPlayersDefeated,assignDamage,atEndOfActivation,atEndOfAttack,atEndOfPhase,atEndOfRound,atEndOfThwart,atMost,attachCard,attachCost,attachInstruction,attack,attackAnEnemy,attackDamageDealt,attackExcessAsDealt,attackInProgress,attackInitiatedAgainst,attackPreventedAmount,attackPreventedTotal,attackResolvedLabeled,attackTarget,attackTotalAtk,attackUsedAtk,attackWasPrevented,attackableAsMinion,attackedBy,attackedPlayer,attackedThisPhase,attackingEnemy,attacksDealAdditionalDamage,attacksGainKeywords,attacksLoseKeywords,baseStatOf,baseStatsFromYourHero,basicPowerBy,basicPowerCost,basicPowerIs,basicPowerStatIs,basicThwartOnlyAgainst,basicThwartsIgnore,bindTargets,blankTextBoxForPlayers,blankTextBoxUntil,blanksTextBox,boost,boostAreaIconsOn,boostCardOf,boostCardsFromSet,boostIconsCount,boostIconsOn,buildScenarioDeck,buildWave11Scenario,builtinGameDeps,builtinPackProblems,campaignDefinitionOf,campaignDefinitionProblems,campaignDefinitionsOf,campaignDepsWithPacks,campaignGameWithPacks,campaignInstructionsOf,campaignLogAtLeast,campaignLogCardCounter,campaignLogCardRecorded,campaignLogCards,campaignLogHas,campaignLogIsSet,campaignLogValue,campaignModularPickProblem,canAttachTo,canAttachToCategory,canChangeForm,canEnterPlay,canFlip,canPayResources,canPlayFromHand,canRemoveThreatFrom,canSpendDifferentResources,canTakeStatus,canUseBasicPower,cancelBoostedActivation,cancelConsequentialDamage,cancelIt,cancelRevealedCard,cancelWhenRevealed,cannotActivate,cannotAttach,cannotBeAttachedUnlessInPlay,cannotBeCanceled,cannotBeDefeated,cannotBeHealed,cannotBeReadiedByPlayerCards,cannotChangeFormUntil,cannotChooseOption,cannotChooseToDiscard,cannotEnterPlay,cannotFlip,cannotHaveStatus,cannotLeavePlay,cannotMakeBasicAttacks,cannotReadyUntil,cannotRecover,cannotResolveTriggeredAbilities,cannotThwart,cardIdsIn,cardPoolWithPack,cardPoolWithPacks,cards,cardsFrom,cardsOfComposedSets,centralMainScheme,changeAdditionalForm,changeForm,changeFormCost,changeToHeroFormNamed,changeToHeroFormWithTrait,changeToOtherHeroForm,changeVillainForm,characterDidThisPhase,checkModularPickCount,checkPackCampaigns,checkPlayableDifficultySets,choiceFoundNothing,chooseCardCost,chooseCardType,chooseCards,chooseEncounterCardType,chooseGroup,chooseMainSchemeStages,chooseNumber,chooseOne,chooseOneBy,chooseOptions,choosePlayer,chooseTarget,chooseTargetCost,chosen,chosenGroup,chosenModularSetIds,chosenPlayer,chosenVillain,civilWarGameModes,civilWarModularSets,civilWarSidesOffer,communityDeckUrl,communityDecks,competitiveOnly,competitiveOnlyTexts,completeMainScheme,confuse,consideredToHaveHitPoints,consideredToHaveResourceIcon,constant,controllerOf,coreScenario,costIf,costModifier,costsPayableByAnyPlayer,countAmong,countBoostIcons,countOf,countTowardStartingHand,counterLimit,countersAsResource,countersOn,countsAs,coveredByEngineRule,createGameArea,createScenarioArea,createScenarioPlayArea,customContentOfPacks,customContentProblems,customModularPickProblem,customModularSetChoices,customScenarioProblems,damageAnEnemy,damageCardsCost,damageOn,damageSharedVillain,damageThisCardCost,damagedAtLeast,dealAsEncounterCard,dealDamage,dealDamageCost,dealDamageToChosenCost,dealEncounterCard,dealEncounterCardsCost,dealEncounterCardsToChosenPlayerCost,dealHiddenPiles,dealIndirectDamage,dealPoolOneAtATime,dealtEncounterCards,dealtEncounterCount,deckCountOf,deckDiscardIconsCount,declareDefender,defeat,defeatExcessDamage,defeatExcessThreat,defeatedWithExcessConsequentialDamage,defeatedWithExcessDamage,defeatingPlayer,defenderDefForAttack,defendingCharacter,defendsWithoutExhausting,defineAbilities,defineBuiltinPack,definePackAbilities,detach,difficultySetAlternativesFor,discard,discardAtRandom,discardBoostCard,discardCardsCost,discardChosenFromEncounterDeckCost,discardDeckUntil,discardEncounterCards,discardEncounterUntil,discardFacedownBoostCards,discardFromHand,discardFromHandCombinedCost,discardFromHandCost,discardRandomFromHandCost,discardStatusCost,discardStatusesTokensAndAttachments,discardThis,discardTopOfDeckCost,discardTopOfEncounterDeckCost,discardTuckedCost,discardUpToTopOfDeckCost,distinctAspectsOf,distinctTraitsOf,divide,doesNotExhaustToDefend,doubleDamageTaken,doubleNextCardSpent,doubleStat,doublesResourcesGeneratedForThisCard,doublesResourcesWhilePayingFor,draw,drawUpTo,droneFromDeck,dslFeatures,duringPlayerPhase,duringTurnOf,duringVillainPhaseStepOne,each,eachGroupInPod,eachPlayer,eachPlayerCost,eachTimeUntil,eitherCost,encounterCard,encounterCards,encounterCardsOf,encounterIconsInPlay,encounterLookDiscardCost,encounterSetAside,encounterSetOf,endGame,enemyActivates,enemyAttack,enemyAttacksEnemy,enemyAttacksYouCost,enemyCanAttackAnother,enemyLeader,enemyScheme,enemyTeam,enemyTeamChooses,enemyToAttack,engage,engagedPlayerOf,engineOnlyDslProblems,entersPlayExhausted,eventAmount,eventDamageTaken,eventDamageTakenBy,eventDealt,eventKindIs,eventPlayer,eventResult,eventSource,eventSourceEnemy,eventTarget,eventTargetsTogether,exactlyDefeated,exactlyDefeatedByPower,excludedFromAllyLimit,excludedFromPlayerSideSchemeLimit,exhaust,exhaustCardsCost,exhaustEachCost,exhaustThis,exhaustYourHero,exists,expertSetReplaceable,extraBoostCardsForVillain,faceNamed,fieldsIn,finalStep,find,findCard,firstAttackThisTurn,firstPlayer,firstPlayerAction,firstPlayerPicksFromHand,firstRevealGainsSurge,firstThisRound,flatten,flipCard,flipCardsCost,flipThis,focusedMainScheme,forAnIdentityNotInThisGame,forEachCard,forEachPlayer,forEachPlayerInChosenOrder,forcedAction,forcedInterrupt,forcedResponse,formChangeCost,friendlyCharacterAttacks,fromAnyAspect,gainFromHiddenPile,gainKeywordUntil,gainTraitUntil,gainTraitsOfUntil,gainsAbility,gainsIcon,gainsKeyword,gainsKeywordX,gainsKeywordsOf,gainsTrait,gainsTraitsOf,gameAreasSplit,gameDepsWithPack,gameDepsWithPacks,genePoolThreatOffer,generatesAmount,generatesPerCard,gets,giveBasicPowerBoostCard,giveBoostCard,giveBoostCardsCost,giveHeldBoostCard,giveStatus,giveStatusCost,giveTough,gmwBalancedHiddenFields,grantAdditionalMulligans,grantOwnedCards,grantedTo,grantingCard,grantsPreparation,groupPlayerCount,handCountOf,handSizeOf,hasAttachment,hasNamedResource,hasPrintedBoostAbility,hasStatus,hasTaggedAbility,hasTrait,heal,healCost,healYourIdentityCost,heroAction,heroInterrupt,heroNoCharacterIsTitledAs,heroResource,heroResponse,hiddenPileCount,highestStatAmong,hitPointsOf,holdMinion,horsemanSidesOffer,host,identifyMole,identityOf,ifElse,ifThen,ignoreAbilities,ignoreBoost,ignoreBoostAbilities,ignoreBoostForThisAttack,ignores,ignoresRetaliate,inAdditionalForm,inCampaign,inCampaignLogField,inCompetitiveMode,inDiscard,inEncounterSet,inForm,inGroup,inHand,inMode,inPlay,inPlayAreaOf,inScenarioPlayArea,inVictoryDisplay,increaseDamage,increaseDamageTaken,increaseNextCardCost,infinitesGenePoolThreatRecommendation,instead,interrupt,isAlterEgo,isAttached,isBaseEncounterSetId,isBaseScenarioId,isConfused,isHero,isModularChoice,isNotReadyCard,isPlainJson,isScenarioSpecificSet,isStunned,isUnscriptedAbilityIssue,joinGameArea,keepsExhausted,lastPlayedThisRound,leavingPlayLoses,limitPerPaidCard,logCardList,logCardRef,logFlag,logNumber,logOption,logText,lookAt,lookAtAndRearrange,lookAtTopOfScenarioDeckThenPlace,loseKeywordUntil,loseTraitUntil,losesIcon,losesKeyword,made,mainSchemeAdvancedBy,mainSchemeMarkedBy,mainSchemePicksOffer,mainSchemeStageGist,mainSchemeStageNumber,mainSchemeStagesOffer,mainSchemeStagesProblem,max,maxDamageTaken,maxOnePerTriggeringInstance,maxSustainedDamage,mayLookAtTopOfEncounterDeckUntil,mergeCosts,mergeRegistries,min,minDamageTaken,modifyAttack,modifyBasicPower,modifyCardEffect,modifyCardEffectsUntil,modifyConsequentialDamage,modifyStat,modifyStatOf,modifyThwart,modularPickCountProblem,modularPickCountRange,modularPickProblem,modularSetContents,mojoCheckedOffSets,mojoModularSetPicks,mostCommonHandTypeCount,moveActiveCounterToNextInRow,moveActiveCounterToNextVillain,moveBoostCards,moveCards,moveCardsInto,moveCounters,moveThreat,multiplyStat,named,namedByTeamUpOf,nextAfter,not,notCountedTowardHandSize,notMatching,notOfChosenCardType,obligation,ofChosenCardType,ofClassification,ofIdentitySetTitled,ofTeamUpSet,offersEasierStart,offersGenePoolThreat,on,onChosenMainScheme,oncePerPaidCard,oncePerPhase,oncePerPhasePerEventPlayer,oncePerRound,oncePerRoundPerPlayer,oneCopyOf,onlyCharacterRemovesThreat,onlySourceRemovesThreat,onlyThwartsRemoveThreat,opsOfKind,option,otherFaceOf,otherPlayers,outsideFact,overdefeated,overpaidWhenPlayed,ownScriptsOf,ownerOf,packCampaignDefinitionOf,packCampaignDefinitions,packCampaignRecords,packCampaignsOf,packEncounterSetRecords,packModularSetChoices,obligation as packObligation,packScenarioOffer,packScenarioRecords,paidCards,paidInPlayCards,paidType,paidTypeCount,paidUsingResourceFrom,paidWith,paidWithCard,paidWithOnly,paidWithResourceCard,pairCards,pairLimit,partOf,passEncounterCard,payPrintedCostOf,payingFor,perHero,placeCountersCost,placeDamage,placeOnTopOrBottom,placeOnTopOrBottomOfPlayerDeck,placeThreat,placeThreatOnSharedScheme,playFromDeckIgnoringCost,playFromDeckReducingCost,playFromDiscard,playFromHandIgnoringCost,playFromHandReducingCost,playFromSeparateDeck,playNote,playOnlyIf,playSetAside,playTuckedCard,playWithTopOfDeckFaceup,playWithTopOfEncounterDeckFaceup,playableAttachments,playableScenario,playableScenarioOffer,playableScenarioWithCustom,playableStarterDeckSetup,playableTopOfDeck,playableTucked,playedThisPhase,playedThisRound,playedThisTurn,playedVia,playerOrElse,playersCannotDiscard,playersWhere,preparation,preventAllDamageTo,preventConsequentialDamage,preventDamage,preventThreat,printedBoostAreaIconsOn,printedCostAtLeast,printedCostOf,printedForm,printedHpNumeralOf,printedHpOf,printedResourcesInHandAs,printedResourcesOf,printedStatOf,printsAbility,product,publishIssues,putIntoPlay,putIntoPlayAsHost,putIntoPlayFacedown,putIntoPlayFromSetAside,putLinkedAllyIntoPlay,putMainSchemeStageIntoPlay,query,raiseMoment,randomCivilWarScenario,reachableFromPod,reaching,readPackInput,readsAtkOf,readsPaymentTypesOf,ready,readyCardsCost,recordInCampaignLog,reduceCostOfCards,reduceCostToPlay,reduceDamage,reduceDamageTo,reduceNextCardCost,reducesAttackDamageTaken,refCount,refMatches,remainingHpCompare,remainingHpOf,removeAccelerationToken,removeAllCounters,removeAllCountersFrom,removeAnAccelerationToken,removeCounter,removeCountersAmong,removeCountersFrom,removeEachCounterFrom,removeFromCampaign,removeMainSchemeStage,removeMainSchemeStages,removeStatus,removeThreat,removeThreatCost,removeThreatFromAScheme,removeThreatFromChosenCost,removeThreatUpToCost,removeUpToCounters,removeVillain,removedFromGameCards,reorderCards,repeatTimes,repeatWhile,replaceAttachHost,replaceBoostCount,replaceLeaveDestination,replaceNextVillainPhaseWithPlayerPhase,replaceStatus,replaceTuckHost,reportFact,resetHitPoints,resolveAttackAgainst,resolveBoostAbilitiesOf,resolveForcedInterruptOf,resolveForcedResponseCost,resolveForcedResponseOf,resolveModes,resolveOneTagged,resolvePreparationsOf,resolveSetups,resolveSpecialCost,resolveSpecials,resolveSpecialsOf,resolveTagged,resolveWhenDefeatedOf,resolveWhenRevealedOf,resource,resourceTypesOf,resourcesGeneratedAsWild,resourcesPaidBy,response,restrictedLimit,retargetAttack,retargetPlayerAttack,returnEachToHandCost,returnToHandAfterResolving,returnToHandCost,revealCard,revealEncounterCard,revealFromSetAsideModularSet,revealHeldMinion,revealHiddenPile,revealInstead,revealMainSchemeStage,revealNextVillainStage,revealSetAside,revealTopOfScenarioDeck,revealTopOfSeparateDeck,revealedFromEncounterDeck,revealedPileCardCount,rotateEngagement,rule,sameClassificationAs,scaled,scenarioArea,scenarioAreaCount,scenarioDeck,scenarioGameSetIds,scenarioSideClause,scenarioWithPacks,scenarioWithVillain,schemeStartedByAttackBoost,schemeThreatOn,searchAndReveal,searchCollection,searchEncounterIntoPlayCost,seedHiddenPiles,selectCards,self,sentence,separateDeckCards,separateDeckCountOf,setActiveVillain,setAside,setAsideDestination,setAsideModularSetCount,setDefeatDestination,setRemainingHitPoints,setVar,setVillainAside,setVillainSide,setup,sha256Hex,sharesTitleWith,sharesTraitWith,sharesTraitWithHeroOf,shuffleDeck,shuffleEncounterDeck,shuffleInSetAsideModularSet,shuffleIntoSeparateDeck,shuffleMainSchemeStageGroup,shuffleMainSchemeStages,shuffleSeparateDeck,shuffleTopOfSeparateDeckIntoEncounterDeck,sitOut,skipNextVillainPhase,skippedCommunityDecks,skirmishOffer,special,spend,spendChosen,spendDifferentResources,spendEqualTo,spendPrinted,spendResources,spendSameType,spendUpTo,spendX,spendXResources,spendableForAnyPlayer,spendableForPlayersWhere,spendableFromTucked,splitIssues,standardSetReplaceable,starIconsOn,starterDeckSetup,statCompare,statOf,stateCheck,stateCheckFromEntering,statusCount,statusLimit,staysInHand,stillCountedByDiscarder,stun,sum,superlative,superlativePlayer,surge,swapCards,swapIdentity,swapMainScheme,swapVillain,swapVillainByTrait,tagged,taggedAbilitiesOn,takeAnyDamageCost,takeControl,takeDamage,takeDamageCost,takeIndirectDamageCost,takeIntoHand,takesConsequentialDamage,takesDamageOnlyFrom,takesDamageOnlyFromAttacks,takesFirstTurn,teamUpCharacter,teamUpCharacters,textBoxCannotBeBlanked,thatAttackGainsKeywords,thatPlayer,theAccused,theAffectedCard,theMainScheme,theMole,theVillain,thisCardGenerates,thisGroup,threatAtLeast,threatOn,thwart,thwartAScheme,thwartInProgress,thwartTarget,titled,toScenarioDeck,topOfDeck,topOfDeckIsFaceup,topOfDeckMatches,topOfEncounterDeckIsFaceup,topOfEncounterDeckMatches,topOfEncounterDeckShowsIcons,topOfEncounterDeckShowsNoIcons,topOfYourDeckHas,totalPrintedCost,totalPrintedResources,totalStatOf,traitEncounterDeck,traitNumber,treatAsAlly,treatAsMinion,treatAttachedAllyAsMinion,treatAttachedHeroAsMinion,treatAttachedMinionAsAlly,treatAttachedVillainAsMinion,treatSelfAsAlly,tuckCards,tuckLimit,tuckedCount,tuckedUnder,tuckedUnderRef,turnFacedown,uncancellable,undefendedAttack,upgradesCannotBeRemoved,useActionAbility,useThwInsteadOfAtk,usingBasicPower,validateBuiltinPack,validateDefinition,validatePack,valueAtLeast,valueAtMost,valueEquals,varAtLeast,varFor,varOf,victoryCondition,victoryDisplayCards,victoryDisplayCount,villainChoiceOf,villainChoiceOffer,villainOnSide,villainOptionOf,villainStageNumberOf,wave10Scenario,wave10StarterDeckSetup,wave11Scenario,wave11ScenarioRecord,wave11StarterDeckSetup,wave1ReprintPairs,wave1Scenario,wave1StarterDeckSetup,wave2ReprintPairs,wave2Scenario,wave2StarterDeckSetup,wave3ReprintPairs,wave3Scenario,wave3StarterDeckSetup,wave7Scenario,wave7StarterDeckSetup,wave8Scenario,wave8StarterDeckSetup,wave9Scenario,wave9StarterDeckSetup,when,whenCompleted,whenDefeated,whenRevealed,whenRevealedAlterEgo,whenRevealedHero,whenSpentGenerate,whileOnChosenMainScheme,whileTucked,withFewestCounters,withModularSetContents,withMostCounters,you,youAre,youAreNamed,youHaveTrait,yourIdentity,yourLeader,yourMainScheme,yourTeam,zone,zoneCountOf};
1
+ import{builtinGameDeps,validateBuiltinPack}from"./chunks/chunk-3YMCANI3.js";import{PACK_ABILITY_ID,REQUIRED_PACK_FILES,SUPPORTED_DSL_FEATURES,campaignDefinitionsOf,checkPackCampaigns,definePackAbilities,dslFeatures,isPlainJson,isUnscriptedAbilityIssue,packCampaignsOf,publishIssues,readPackInput,sha256Hex,splitIssues,validatePack}from"./chunks/chunk-3SR23UJ7.js";import{campaignDepsWithPacks,campaignGameWithPacks,cardPoolWithPack,cardPoolWithPacks,customContentOfPacks,gameDepsWithPack,gameDepsWithPacks,packCampaignDefinitionOf,packCampaignDefinitions,packCampaignRecords,packEncounterSetRecords,packModularSetChoices,packScenarioRecords,scenarioWithPacks}from"./chunks/chunk-S3JH4WL4.js";import{ANY_ASPECT_CARD,ANY_NUMBER,ANY_RESOURCE,AOA_CAMPAIGN_DEFINITION,AOA_DEFEATED,AOA_MISSIONS,AOA_NOT_DEFEATED,AOA_OVERSEERS,AOA_PROTECT_THE_PROFESSOR,AOS_CAMPAIGN_DEFINITION,AS_DRONE,BUILTIN_PACKS,CAMPAIGNS,CAN_TAKE_THIS_ATTACK,COMMUNITY_DECK_AUTHORS,CORE_ABILITIES,CORE_BUILTIN_PACK,CORE_DEPS,CUSTOM_SCENARIO_FIELDS,ENCOUNTER_CARD,ENCOUNTER_CARD_CATEGORIES,ENCOUNTER_SIDE_SCHEME,ENGINE_ONLY_DSL_EXAMPLES,FRIENDLY_CHARACTER,GMW_BALANCED_FIELD,GMW_BALANCED_TOGGLES,GMW_CAMPAIGN_DEFINITION,INFINITES_GENE_POOL_THREAT_MAX,MOJO_CAMPAIGN_DEFINITION,MTS_CAMPAIGN_DEFINITION,NEXT_EVOL_CAMPAIGN_DEFINITION,NOT_READY_PACK_CODES,PAID_CARDS,PAID_IN_PLAY_CARDS,PLAYABLE_ABILITIES,PLAYABLE_DEPS,PLAYABLE_ENCOUNTER_SETS,PLAYABLE_SCENARIO_RECORDS,PLAYER_SIDE_SCHEME,RANDOM_VILLAIN,SHADOWLAND_CAMPAIGN_DEFINITION,SM_CAMPAIGN_DEFINITION,TEAM_UP_CARD,TRAIT,TRORS_CAMPAIGN_DEFINITION,UNSCRIPTED_ENCOUNTER_SET_IDS,VILLAIN_OR_VILLAINOUS,WAVE10_ABILITIES,WAVE10_BUILTIN_PACKS,WAVE10_CARDS,WAVE10_DEPS,WAVE10_GAME_ENCOUNTER_SETS,WAVE11_ABILITIES,WAVE11_BUILTIN_PACKS,WAVE11_CARDS,WAVE11_DEPS,WAVE11_GAME_ENCOUNTER_SETS,WAVE1_ABILITIES,WAVE1_BUILTIN_PACKS,WAVE1_DEPS,WAVE1_REPRINT_ABILITIES,WAVE2_ABILITIES,WAVE2_BUILTIN_PACKS,WAVE2_DEPS,WAVE2_REPRINT_ABILITIES,WAVE3_ABILITIES,WAVE3_BUILTIN_PACKS,WAVE3_CARDS,WAVE3_DEPS,WAVE3_REPRINT_ABILITIES,WAVE4_BUILTIN_PACKS,WAVE5_BUILTIN_PACKS,WAVE6_BUILTIN_PACKS,WAVE7_ABILITIES,WAVE7_BUILTIN_PACKS,WAVE7_CARDS,WAVE7_DEPS,WAVE8_ABILITIES,WAVE8_BUILTIN_PACKS,WAVE8_CARDS,WAVE8_DEPS,WAVE9_ABILITIES,WAVE9_BUILTIN_PACKS,WAVE9_CARDS,WAVE9_DEPS,YOUR_HERO,YOUR_IDENTITY,aDifferentCard,aScheme,abilitiesForCards,accelerationTokensOn,accusationWrongGuesses,accuse,accusedWrong,actingCharacter,action,activatesBeforeVillain,activatingEnemy,activationIs,activationOrderOf,addAccelerationToken,addCounters,addMainSchemeStageToVictoryDisplay,addToVictoryDisplay,addVillain,additionalAttackCost,additionalCostToPlay,additionalCostToReady,additionalPowerCost,additionalThwartCost,adjustBoostCount,advanceMainScheme,advanceToSetAsideVillain,after,afterNextCardPlayed,agile,allOf,allowUnlabeledAttack,alterEgoAction,alterEgoInterrupt,alterEgoResponse,amount,anAttackableEnemy,anEnemy,andThen,anyIn,anyNumberOfToughStatusCards,anyOf,anyOfCards,anyPlayerEliminated,applyAsBoostCard,applyRuleUntil,areaPlayersDefeated,assignDamage,atEndOfActivation,atEndOfAttack,atEndOfPhase,atEndOfRound,atEndOfThwart,atMost,attachCard,attachCost,attachInstruction,attack,attackAnEnemy,attackDamageDealt,attackExcessAsDealt,attackInProgress,attackInitiatedAgainst,attackPreventedAmount,attackPreventedTotal,attackResolvedLabeled,attackTarget,attackTotalAtk,attackUsedAtk,attackWasPrevented,attackableAsMinion,attackedBy,attackedPlayer,attackedThisPhase,attackingEnemy,attacksDealAdditionalDamage,attacksGainKeywords,attacksLoseKeywords,baseStatOf,baseStatsFromYourHero,basicPowerBy,basicPowerCost,basicPowerIs,basicPowerStatIs,basicThwartOnlyAgainst,basicThwartsIgnore,bindTargets,blankTextBoxForPlayers,blankTextBoxUntil,blanksTextBox,boost,boostAreaIconsOn,boostCardOf,boostCardsFromSet,boostIconsCount,boostIconsOn,buildScenarioDeck,buildWave11Scenario,builtinPackProblems,campaignDefinitionOf,campaignDefinitionProblems,campaignInstructionsOf,campaignLogAtLeast,campaignLogCardCounter,campaignLogCardRecorded,campaignLogCards,campaignLogHas,campaignLogIsSet,campaignLogValue,campaignModularPickProblem,canAttachTo,canAttachToCategory,canChangeForm,canEnterPlay,canFlip,canPayResources,canPlayFromHand,canRemoveThreatFrom,canSpendDifferentResources,canTakeStatus,canUseBasicPower,cancelBoostedActivation,cancelConsequentialDamage,cancelIt,cancelRevealedCard,cancelWhenRevealed,cannotActivate,cannotAttach,cannotBeAttachedUnlessInPlay,cannotBeCanceled,cannotBeDefeated,cannotBeHealed,cannotBeReadiedByPlayerCards,cannotChangeFormUntil,cannotChooseOption,cannotChooseToDiscard,cannotEnterPlay,cannotFlip,cannotHaveStatus,cannotLeavePlay,cannotMakeBasicAttacks,cannotReadyUntil,cannotRecover,cannotResolveTriggeredAbilities,cannotThwart,cardIdsIn,cards,cardsFrom,cardsOfComposedSets,centralMainScheme,changeAdditionalForm,changeForm,changeFormCost,changeToHeroFormNamed,changeToHeroFormWithTrait,changeToOtherHeroForm,changeVillainForm,characterDidThisPhase,checkModularPickCount,checkPlayableDifficultySets,choiceFoundNothing,chooseCardCost,chooseCardType,chooseCards,chooseEncounterCardType,chooseGroup,chooseMainSchemeStages,chooseNumber,chooseOne,chooseOneBy,chooseOptions,choosePlayer,choosePlayerWithEngaged,chooseTarget,chooseTargetCost,chosen,chosenGroup,chosenModularSetIds,chosenPlayer,chosenVillain,civilWarGameModes,civilWarModularSets,civilWarSidesOffer,communityDeckUrl,communityDecks,competitiveOnly,competitiveOnlyTexts,completeMainScheme,confuse,consideredToHaveHitPoints,consideredToHaveResourceIcon,constant,controllerOf2 as controllerOf,coreScenario,costIf,costModifier,costsPayableByAnyPlayer,countAmong,countBoostIcons,countOf,countTowardStartingHand,counterLimit,countersAsResource,countersOn,countsAs,coveredByEngineRule,createGameArea,createScenarioArea,createScenarioPlayArea,customContentProblems,customModularPickProblem,customModularSetChoices,customScenarioProblems,damageAnEnemy,damageCardsCost,damageOn,damageSharedVillain,damageThisCardCost,damagedAtLeast,dealAsEncounterCard,dealDamage,dealDamageCost,dealDamageToChosenCost,dealEncounterCard,dealEncounterCardsCost,dealEncounterCardsToChosenPlayerCost,dealHiddenPiles,dealIndirectDamage,dealPoolOneAtATime,dealtEncounterCards,dealtEncounterCount,deckCountOf,deckDiscardIconsCount,declareDefender,defeat,defeatExcessDamage,defeatExcessThreat,defeatedWithExcessConsequentialDamage,defeatedWithExcessDamage,defeatingPlayer,defenderDefForAttack,defendingCharacter,defendsWithoutExhausting,defineAbilities,defineBuiltinPack,detach,difficultySetAlternativesFor,discard,discardAtRandom,discardBoostCard,discardCardsCost,discardChosenFromEncounterDeckCost,discardDeckUntil,discardEncounterCards,discardEncounterUntil,discardFacedownBoostCards,discardFromHand,discardFromHandCombinedCost,discardFromHandCost,discardRandomFromHandCost,discardStatusCost,discardStatusesTokensAndAttachments,discardThis,discardTopOfDeckCost,discardTopOfEncounterDeckCost,discardTuckedCost,discardUpToTopOfDeckCost,distinctAspectsOf,distinctTraitsOf,divide,doesNotExhaustToDefend,doubleDamageTaken,doubleNextCardSpent,doubleStat,doublesResourcesGeneratedForThisCard,doublesResourcesWhilePayingFor,draw,drawUpTo,droneFromDeck,duringPlayerPhase,duringTurnOf,duringVillainPhaseStepOne,each,eachGroupInPod,eachPlayer,eachPlayerCost,eachTimeUntil,eitherCost,encounterCard,encounterCards,encounterCardsOf,encounterIconsInPlay,encounterLookDiscardCost,encounterSetAside,encounterSetOf,endGame,enemyActivates,enemyAttack,enemyAttacksEnemy,enemyAttacksYouCost,enemyCanAttackAnother,enemyLeader,enemyScheme,enemyTeam,enemyTeamChooses,enemyToAttack,engage,engagedPlayerOf,engineOnlyDslProblems,entersPlayExhausted,eventAmount,eventDamageTaken,eventDamageTakenBy,eventDealt,eventKindIs,eventPlayer,eventResult,eventSource,eventSourceEnemy,eventTarget,eventTargetsTogether,exactlyDefeated,exactlyDefeatedByPower,excludedFromAllyLimit,excludedFromPlayerSideSchemeLimit,exhaust,exhaustCardsCost,exhaustEachCost,exhaustThis,exhaustYourHero,exists,expertSetReplaceable,extraBoostCardsForVillain,faceNamed,fieldsIn,finalStep,find,findCard,firstAttackThisTurn,firstPlayer,firstPlayerAction,firstPlayerPicksFromHand,firstRevealGainsSurge,firstThisRound,flatten,flipCard,flipCardsCost,flipThis,focusedMainScheme,forAnIdentityNotInThisGame,forEachCard,forEachPlayer,forEachPlayerInChosenOrder,forcedAction,forcedInterrupt,forcedResponse,formChangeCost,friendlyCharacterAttacks,fromAnyAspect,gainFromHiddenPile,gainKeywordUntil,gainTraitUntil,gainTraitsOfUntil,gainsAbility,gainsIcon,gainsKeyword,gainsKeywordX,gainsKeywordsOf,gainsTrait,gainsTraitsOf,gameAreasSplit,genePoolThreatOffer,generatesAmount,generatesPerCard,gets,giveBasicPowerBoostCard,giveBoostCard,giveBoostCardsCost,giveHeldBoostCard,giveStatus,giveStatusCost,giveTough,gmwBalancedHiddenFields,grantAdditionalMulligans,grantOwnedCards,grantedTo,grantingCard,grantsPreparation,groupPlayerCount,handCountOf,handSizeOf,hasAttachment,hasNamedResource,hasPrintedBoostAbility,hasStatus,hasTaggedAbility,hasTrait,heal,healCost,healYourIdentityCost,heroAction,heroInterrupt,heroNoCharacterIsTitledAs,heroResource,heroResponse,hiddenPileCount,highestStatAmong,hitPointsOf,holdMinion,horsemanSidesOffer,host,identifyMole,identityOf,ifElse,ifThen,ignoreAbilities,ignoreBoost,ignoreBoostAbilities,ignoreBoostForThisAttack,ignores,ignoresRetaliate,inAdditionalForm,inCampaign,inCampaignLogField,inCompetitiveMode,inDiscard,inEncounterSet,inForm,inGroup,inHand,inMode,inPlay,inPlayAreaOf,inScenarioPlayArea,inVictoryDisplay,increaseDamage,increaseDamageTaken,increaseNextCardCost,infinitesGenePoolThreatRecommendation,instead,interrupt,isAlterEgo,isAttached,isBaseEncounterSetId,isBaseScenarioId,isConfused,isHero,isModularChoice,isNotReadyCard,isScenarioSpecificSet,isStunned,joinGameArea,keepsExhausted,lastPlayedThisRound,leavingPlayLoses,limitPerPaidCard,logCardList,logCardRef,logFlag,logNumber,logOption,logText,lookAt,lookAtAndRearrange,lookAtTopOfScenarioDeckThenPlace,loseKeywordUntil,loseTraitUntil,losesIcon,losesKeyword,made,mainSchemeAdvancedBy,mainSchemeMarkedBy,mainSchemePicksOffer,mainSchemeStageGist,mainSchemeStageNumber,mainSchemeStagesOffer,mainSchemeStagesProblem,max,maxDamageTaken,maxOnePerTriggeringInstance,maxSustainedDamage,mayLookAtTopOfEncounterDeckUntil,mergeCosts,mergeRegistries,min,minDamageTaken,modifyAttack,modifyBasicPower,modifyCardEffect,modifyCardEffectsUntil,modifyConsequentialDamage,modifyStat,modifyStatOf,modifyThwart,modularPickCountProblem,modularPickCountRange,modularPickProblem,modularSetContents,mojoCheckedOffSets,mojoModularSetPicks,mostCommonHandTypeCount,moveActiveCounterToNextInRow,moveActiveCounterToNextVillain,moveBoostCards,moveCards,moveCardsInto,moveCounters,moveThreat,multiplyStat,named,namedByTeamUpOf,nextAfter,not,notCountedTowardHandSize,notMatching,notOfChosenCardType,obligation,ofChosenCardType,ofClassification,ofIdentitySetTitled,ofTeamUpSet,offersEasierStart,offersGenePoolThreat,on,onChosenMainScheme,oncePerPaidCard,oncePerPhase,oncePerPhasePerEventPlayer,oncePerRound,oncePerRoundPerPlayer,oneCopyOf,onlyCharacterRemovesThreat,onlySourceRemovesThreat,onlyThwartsRemoveThreat,opsOfKind,option,otherFaceOf,otherPlayers,outsideFact,overdefeated,overpaidWhenPlayed,ownScriptsOf,ownerOf,packScenarioOffer,paidCards,paidInPlayCards,paidType,paidTypeCount,paidUsingResourceFrom,paidWith,paidWithCard,paidWithOnly,paidWithResourceCard,pairCards,pairLimit,partOf,passEncounterCard,payPrintedCostOf,payingFor,perHero,placeCountersCost,placeDamage,placeOnTopOrBottom,placeOnTopOrBottomOfPlayerDeck,placeThreat,placeThreatOnSharedScheme,playFromDeckIgnoringCost,playFromDeckReducingCost,playFromDiscard,playFromHandIgnoringCost,playFromHandReducingCost,playFromSeparateDeck,playNote,playOnlyIf,playSetAside,playTuckedCard,playWithTopOfDeckFaceup,playWithTopOfEncounterDeckFaceup,playableAttachments,playableScenario,playableScenarioOffer,playableScenarioWithCustom,playableStarterDeckSetup,playableTopOfDeck,playableTucked,playedThisPhase,playedThisRound,playedThisTurn,playedVia,playerOrElse,playersCannotDiscard,playersWhere,preparation,preventAllDamageTo,preventConsequentialDamage,preventDamage,preventThreat,printedBoostAreaIconsOn,printedCostAtLeast,printedCostOf,printedForm,printedHpNumeralOf,printedHpOf,printedResourcesInHandAs,printedResourcesOf,printedStatOf,printsAbility,product,putIntoPlay,putIntoPlayAsHost,putIntoPlayFacedown,putIntoPlayFromSetAside,putLinkedAllyIntoPlay,putMainSchemeStageIntoPlay,query,raiseMoment,randomCivilWarScenario,reachableFromPod,reaching,readsAtkOf,readsPaymentTypesOf,ready,readyCardsCost,recordInCampaignLog,reduceCostOfCards,reduceCostToPlay,reduceDamage,reduceDamageTo,reduceNextCardCost,reducesAttackDamageTaken,refCount,refMatches,remainingHpCompare,remainingHpOf,removeAccelerationToken,removeAllCounters,removeAllCountersFrom,removeAnAccelerationToken,removeCounter,removeCountersAmong,removeCountersFrom,removeEachCounterFrom,removeFromCampaign,removeMainSchemeStage,removeMainSchemeStages,removeStatus,removeThreat,removeThreatCost,removeThreatFromAScheme,removeThreatFromChosenCost,removeThreatUpToCost,removeUpToCounters,removeVillain,removedFromGameCards,reorderCards,repeatTimes,repeatWhile,replaceAttachHost,replaceBoostCount,replaceLeaveDestination,replaceNextVillainPhaseWithPlayerPhase,replaceStatus,replaceTuckHost,reportFact,resetHitPoints,resolveAttackAgainst,resolveBoostAbilitiesOf,resolveForcedInterruptOf,resolveForcedResponseCost,resolveForcedResponseOf,resolveModes,resolveOneTagged,resolvePreparationsOf,resolveSetups,resolveSpecialCost,resolveSpecials,resolveSpecialsOf,resolveTagged,resolveWhenDefeatedOf,resolveWhenRevealedOf,resource,resourceTypesOf,resourcesGeneratedAsWild,resourcesPaidBy,response,restrictedLimit,retargetAttack,retargetPlayerAttack,returnEachToHandCost,returnToHandAfterResolving,returnToHandCost,revealCard,revealEncounterCard,revealFromSetAsideModularSet,revealHeldMinion,revealHiddenPile,revealInstead,revealMainSchemeStage,revealNextVillainStage,revealSetAside,revealTopOfScenarioDeck,revealTopOfSeparateDeck,revealedFromEncounterDeck,revealedPileCardCount,rotateEngagement,rule,sameClassificationAs,scaled,scenarioArea,scenarioAreaCount,scenarioDeck,scenarioGameSetIds,scenarioSideClause,scenarioWithVillain,schemeStartedByAttackBoost,schemeThreatOn,searchAndReveal,searchCollection,searchEncounterIntoPlayCost,seedHiddenPiles,selectCards,self,sentence,separateDeckCards,separateDeckCountOf,setActiveVillain,setAside,setAsideDestination,setAsideModularSetCount,setDefeatDestination,setRemainingHitPoints,setVar,setVillainAside,setVillainSide,setup,sharesTitleWith,sharesTraitWith,sharesTraitWithHeroOf,shuffleDeck,shuffleEncounterDeck,shuffleInSetAsideModularSet,shuffleIntoSeparateDeck,shuffleMainSchemeStageGroup,shuffleMainSchemeStages,shuffleSeparateDeck,shuffleTopOfSeparateDeckIntoEncounterDeck,sitOut,skipNextVillainPhase,skippedCommunityDecks,skirmishOffer,special,spend,spendChosen,spendDifferentResources,spendEqualTo,spendPrinted,spendResources,spendSameType,spendUpTo,spendX,spendXResources,spendableForAnyPlayer,spendableForPlayersWhere,spendableFromTucked,standardSetReplaceable,starIconsOn,starterDeckSetup,statCompare,statOf,stateCheck,stateCheckFromEntering,statusCount,statusLimit,staysInHand,stillCountedByDiscarder,stun,sum,superlative,superlativePlayer,surge,swapCards,swapIdentity,swapMainScheme,swapVillain,swapVillainByTrait,tagged,taggedAbilitiesOn,takeAnyDamageCost,takeControl,takeDamage,takeDamageCost,takeIndirectDamageCost,takeIntoHand,takesConsequentialDamage,takesDamageOnlyFrom,takesDamageOnlyFromAttacks,takesFirstTurn,teamUpCharacter,teamUpCharacters,textBoxCannotBeBlanked,thatAttackGainsKeywords,thatPlayer,theAccused,theAffectedCard,theMainScheme,theMole,theVillain,thisCardGenerates,thisGroup,threatAtLeast,threatOn,thwart,thwartAScheme,thwartInProgress,thwartTarget,titled,toScenarioDeck,topOfDeck,topOfDeckIsFaceup,topOfDeckMatches,topOfEncounterDeckIsFaceup,topOfEncounterDeckMatches,topOfEncounterDeckShowsIcons,topOfEncounterDeckShowsNoIcons,topOfYourDeckHas,totalPrintedCost,totalPrintedResources,totalStatOf,traitEncounterDeck,traitNumber,treatAsAlly,treatAsMinion,treatAttachedAllyAsMinion,treatAttachedHeroAsMinion,treatAttachedMinionAsAlly,treatAttachedVillainAsMinion,treatSelfAsAlly,tuckCards,tuckLimit,tuckedCount,tuckedUnder,tuckedUnderRef,turnFacedown,uncancellable,undefendedAttack,upgradesCannotBeRemoved,useActionAbility,useThwInsteadOfAtk,usingBasicPower,validateDefinition,valueAtLeast,valueAtMost,valueEquals,varAtLeast,varFor,varOf,victoryCondition,victoryDisplayCards,victoryDisplayCount,villainChoiceOf,villainChoiceOffer,villainOnSide,villainOptionOf,villainStageNumberOf,wave10Scenario,wave10StarterDeckSetup,wave11Scenario,wave11ScenarioRecord,wave11StarterDeckSetup,wave1ReprintPairs,wave1Scenario,wave1StarterDeckSetup,wave2ReprintPairs,wave2Scenario,wave2StarterDeckSetup,wave3ReprintPairs,wave3Scenario,wave3StarterDeckSetup,wave7Scenario,wave7StarterDeckSetup,wave8Scenario,wave8StarterDeckSetup,wave9Scenario,wave9StarterDeckSetup,when,whenCompleted,whenDefeated,whenRevealed,whenRevealedAlterEgo,whenRevealedHero,whenSpentGenerate,whileOnChosenMainScheme,whileTucked,withFewestCounters,withModularSetContents,withMostCounters,you,youAre,youAreNamed,youHaveTrait,yourIdentity,yourLeader,yourMainScheme,yourTeam,zone,zoneCountOf}from"./chunks/chunk-ACT4TJXC.js";export{ANY_ASPECT_CARD,ANY_NUMBER,ANY_RESOURCE,AOA_CAMPAIGN_DEFINITION,AOA_DEFEATED,AOA_MISSIONS,AOA_NOT_DEFEATED,AOA_OVERSEERS,AOA_PROTECT_THE_PROFESSOR,AOS_CAMPAIGN_DEFINITION,AS_DRONE,BUILTIN_PACKS,CAMPAIGNS,CAN_TAKE_THIS_ATTACK,COMMUNITY_DECK_AUTHORS,CORE_ABILITIES,CORE_BUILTIN_PACK,CORE_DEPS,CUSTOM_SCENARIO_FIELDS,ENCOUNTER_CARD,ENCOUNTER_CARD_CATEGORIES,ENCOUNTER_SIDE_SCHEME,ENGINE_ONLY_DSL_EXAMPLES,FRIENDLY_CHARACTER,GMW_BALANCED_FIELD,GMW_BALANCED_TOGGLES,GMW_CAMPAIGN_DEFINITION,INFINITES_GENE_POOL_THREAT_MAX,MOJO_CAMPAIGN_DEFINITION,MTS_CAMPAIGN_DEFINITION,NEXT_EVOL_CAMPAIGN_DEFINITION,NOT_READY_PACK_CODES,PACK_ABILITY_ID,PAID_CARDS,PAID_IN_PLAY_CARDS,PLAYABLE_ABILITIES,PLAYABLE_DEPS,PLAYABLE_ENCOUNTER_SETS,PLAYABLE_SCENARIO_RECORDS,PLAYER_SIDE_SCHEME,RANDOM_VILLAIN,REQUIRED_PACK_FILES,SHADOWLAND_CAMPAIGN_DEFINITION,SM_CAMPAIGN_DEFINITION,SUPPORTED_DSL_FEATURES,TEAM_UP_CARD,TRAIT,TRORS_CAMPAIGN_DEFINITION,UNSCRIPTED_ENCOUNTER_SET_IDS,VILLAIN_OR_VILLAINOUS,WAVE10_ABILITIES,WAVE10_BUILTIN_PACKS,WAVE10_CARDS,WAVE10_DEPS,WAVE10_GAME_ENCOUNTER_SETS,WAVE11_ABILITIES,WAVE11_BUILTIN_PACKS,WAVE11_CARDS,WAVE11_DEPS,WAVE11_GAME_ENCOUNTER_SETS,WAVE1_ABILITIES,WAVE1_BUILTIN_PACKS,WAVE1_DEPS,WAVE1_REPRINT_ABILITIES,WAVE2_ABILITIES,WAVE2_BUILTIN_PACKS,WAVE2_DEPS,WAVE2_REPRINT_ABILITIES,WAVE3_ABILITIES,WAVE3_BUILTIN_PACKS,WAVE3_CARDS,WAVE3_DEPS,WAVE3_REPRINT_ABILITIES,WAVE4_BUILTIN_PACKS,WAVE5_BUILTIN_PACKS,WAVE6_BUILTIN_PACKS,WAVE7_ABILITIES,WAVE7_BUILTIN_PACKS,WAVE7_CARDS,WAVE7_DEPS,WAVE8_ABILITIES,WAVE8_BUILTIN_PACKS,WAVE8_CARDS,WAVE8_DEPS,WAVE9_ABILITIES,WAVE9_BUILTIN_PACKS,WAVE9_CARDS,WAVE9_DEPS,YOUR_HERO,YOUR_IDENTITY,aDifferentCard,aScheme,abilitiesForCards,accelerationTokensOn,accusationWrongGuesses,accuse,accusedWrong,actingCharacter,action,activatesBeforeVillain,activatingEnemy,activationIs,activationOrderOf,addAccelerationToken,addCounters,addMainSchemeStageToVictoryDisplay,addToVictoryDisplay,addVillain,additionalAttackCost,additionalCostToPlay,additionalCostToReady,additionalPowerCost,additionalThwartCost,adjustBoostCount,advanceMainScheme,advanceToSetAsideVillain,after,afterNextCardPlayed,agile,allOf,allowUnlabeledAttack,alterEgoAction,alterEgoInterrupt,alterEgoResponse,amount,anAttackableEnemy,anEnemy,andThen,anyIn,anyNumberOfToughStatusCards,anyOf,anyOfCards,anyPlayerEliminated,applyAsBoostCard,applyRuleUntil,areaPlayersDefeated,assignDamage,atEndOfActivation,atEndOfAttack,atEndOfPhase,atEndOfRound,atEndOfThwart,atMost,attachCard,attachCost,attachInstruction,attack,attackAnEnemy,attackDamageDealt,attackExcessAsDealt,attackInProgress,attackInitiatedAgainst,attackPreventedAmount,attackPreventedTotal,attackResolvedLabeled,attackTarget,attackTotalAtk,attackUsedAtk,attackWasPrevented,attackableAsMinion,attackedBy,attackedPlayer,attackedThisPhase,attackingEnemy,attacksDealAdditionalDamage,attacksGainKeywords,attacksLoseKeywords,baseStatOf,baseStatsFromYourHero,basicPowerBy,basicPowerCost,basicPowerIs,basicPowerStatIs,basicThwartOnlyAgainst,basicThwartsIgnore,bindTargets,blankTextBoxForPlayers,blankTextBoxUntil,blanksTextBox,boost,boostAreaIconsOn,boostCardOf,boostCardsFromSet,boostIconsCount,boostIconsOn,buildScenarioDeck,buildWave11Scenario,builtinGameDeps,builtinPackProblems,campaignDefinitionOf,campaignDefinitionProblems,campaignDefinitionsOf,campaignDepsWithPacks,campaignGameWithPacks,campaignInstructionsOf,campaignLogAtLeast,campaignLogCardCounter,campaignLogCardRecorded,campaignLogCards,campaignLogHas,campaignLogIsSet,campaignLogValue,campaignModularPickProblem,canAttachTo,canAttachToCategory,canChangeForm,canEnterPlay,canFlip,canPayResources,canPlayFromHand,canRemoveThreatFrom,canSpendDifferentResources,canTakeStatus,canUseBasicPower,cancelBoostedActivation,cancelConsequentialDamage,cancelIt,cancelRevealedCard,cancelWhenRevealed,cannotActivate,cannotAttach,cannotBeAttachedUnlessInPlay,cannotBeCanceled,cannotBeDefeated,cannotBeHealed,cannotBeReadiedByPlayerCards,cannotChangeFormUntil,cannotChooseOption,cannotChooseToDiscard,cannotEnterPlay,cannotFlip,cannotHaveStatus,cannotLeavePlay,cannotMakeBasicAttacks,cannotReadyUntil,cannotRecover,cannotResolveTriggeredAbilities,cannotThwart,cardIdsIn,cardPoolWithPack,cardPoolWithPacks,cards,cardsFrom,cardsOfComposedSets,centralMainScheme,changeAdditionalForm,changeForm,changeFormCost,changeToHeroFormNamed,changeToHeroFormWithTrait,changeToOtherHeroForm,changeVillainForm,characterDidThisPhase,checkModularPickCount,checkPackCampaigns,checkPlayableDifficultySets,choiceFoundNothing,chooseCardCost,chooseCardType,chooseCards,chooseEncounterCardType,chooseGroup,chooseMainSchemeStages,chooseNumber,chooseOne,chooseOneBy,chooseOptions,choosePlayer,choosePlayerWithEngaged,chooseTarget,chooseTargetCost,chosen,chosenGroup,chosenModularSetIds,chosenPlayer,chosenVillain,civilWarGameModes,civilWarModularSets,civilWarSidesOffer,communityDeckUrl,communityDecks,competitiveOnly,competitiveOnlyTexts,completeMainScheme,confuse,consideredToHaveHitPoints,consideredToHaveResourceIcon,constant,controllerOf,coreScenario,costIf,costModifier,costsPayableByAnyPlayer,countAmong,countBoostIcons,countOf,countTowardStartingHand,counterLimit,countersAsResource,countersOn,countsAs,coveredByEngineRule,createGameArea,createScenarioArea,createScenarioPlayArea,customContentOfPacks,customContentProblems,customModularPickProblem,customModularSetChoices,customScenarioProblems,damageAnEnemy,damageCardsCost,damageOn,damageSharedVillain,damageThisCardCost,damagedAtLeast,dealAsEncounterCard,dealDamage,dealDamageCost,dealDamageToChosenCost,dealEncounterCard,dealEncounterCardsCost,dealEncounterCardsToChosenPlayerCost,dealHiddenPiles,dealIndirectDamage,dealPoolOneAtATime,dealtEncounterCards,dealtEncounterCount,deckCountOf,deckDiscardIconsCount,declareDefender,defeat,defeatExcessDamage,defeatExcessThreat,defeatedWithExcessConsequentialDamage,defeatedWithExcessDamage,defeatingPlayer,defenderDefForAttack,defendingCharacter,defendsWithoutExhausting,defineAbilities,defineBuiltinPack,definePackAbilities,detach,difficultySetAlternativesFor,discard,discardAtRandom,discardBoostCard,discardCardsCost,discardChosenFromEncounterDeckCost,discardDeckUntil,discardEncounterCards,discardEncounterUntil,discardFacedownBoostCards,discardFromHand,discardFromHandCombinedCost,discardFromHandCost,discardRandomFromHandCost,discardStatusCost,discardStatusesTokensAndAttachments,discardThis,discardTopOfDeckCost,discardTopOfEncounterDeckCost,discardTuckedCost,discardUpToTopOfDeckCost,distinctAspectsOf,distinctTraitsOf,divide,doesNotExhaustToDefend,doubleDamageTaken,doubleNextCardSpent,doubleStat,doublesResourcesGeneratedForThisCard,doublesResourcesWhilePayingFor,draw,drawUpTo,droneFromDeck,dslFeatures,duringPlayerPhase,duringTurnOf,duringVillainPhaseStepOne,each,eachGroupInPod,eachPlayer,eachPlayerCost,eachTimeUntil,eitherCost,encounterCard,encounterCards,encounterCardsOf,encounterIconsInPlay,encounterLookDiscardCost,encounterSetAside,encounterSetOf,endGame,enemyActivates,enemyAttack,enemyAttacksEnemy,enemyAttacksYouCost,enemyCanAttackAnother,enemyLeader,enemyScheme,enemyTeam,enemyTeamChooses,enemyToAttack,engage,engagedPlayerOf,engineOnlyDslProblems,entersPlayExhausted,eventAmount,eventDamageTaken,eventDamageTakenBy,eventDealt,eventKindIs,eventPlayer,eventResult,eventSource,eventSourceEnemy,eventTarget,eventTargetsTogether,exactlyDefeated,exactlyDefeatedByPower,excludedFromAllyLimit,excludedFromPlayerSideSchemeLimit,exhaust,exhaustCardsCost,exhaustEachCost,exhaustThis,exhaustYourHero,exists,expertSetReplaceable,extraBoostCardsForVillain,faceNamed,fieldsIn,finalStep,find,findCard,firstAttackThisTurn,firstPlayer,firstPlayerAction,firstPlayerPicksFromHand,firstRevealGainsSurge,firstThisRound,flatten,flipCard,flipCardsCost,flipThis,focusedMainScheme,forAnIdentityNotInThisGame,forEachCard,forEachPlayer,forEachPlayerInChosenOrder,forcedAction,forcedInterrupt,forcedResponse,formChangeCost,friendlyCharacterAttacks,fromAnyAspect,gainFromHiddenPile,gainKeywordUntil,gainTraitUntil,gainTraitsOfUntil,gainsAbility,gainsIcon,gainsKeyword,gainsKeywordX,gainsKeywordsOf,gainsTrait,gainsTraitsOf,gameAreasSplit,gameDepsWithPack,gameDepsWithPacks,genePoolThreatOffer,generatesAmount,generatesPerCard,gets,giveBasicPowerBoostCard,giveBoostCard,giveBoostCardsCost,giveHeldBoostCard,giveStatus,giveStatusCost,giveTough,gmwBalancedHiddenFields,grantAdditionalMulligans,grantOwnedCards,grantedTo,grantingCard,grantsPreparation,groupPlayerCount,handCountOf,handSizeOf,hasAttachment,hasNamedResource,hasPrintedBoostAbility,hasStatus,hasTaggedAbility,hasTrait,heal,healCost,healYourIdentityCost,heroAction,heroInterrupt,heroNoCharacterIsTitledAs,heroResource,heroResponse,hiddenPileCount,highestStatAmong,hitPointsOf,holdMinion,horsemanSidesOffer,host,identifyMole,identityOf,ifElse,ifThen,ignoreAbilities,ignoreBoost,ignoreBoostAbilities,ignoreBoostForThisAttack,ignores,ignoresRetaliate,inAdditionalForm,inCampaign,inCampaignLogField,inCompetitiveMode,inDiscard,inEncounterSet,inForm,inGroup,inHand,inMode,inPlay,inPlayAreaOf,inScenarioPlayArea,inVictoryDisplay,increaseDamage,increaseDamageTaken,increaseNextCardCost,infinitesGenePoolThreatRecommendation,instead,interrupt,isAlterEgo,isAttached,isBaseEncounterSetId,isBaseScenarioId,isConfused,isHero,isModularChoice,isNotReadyCard,isPlainJson,isScenarioSpecificSet,isStunned,isUnscriptedAbilityIssue,joinGameArea,keepsExhausted,lastPlayedThisRound,leavingPlayLoses,limitPerPaidCard,logCardList,logCardRef,logFlag,logNumber,logOption,logText,lookAt,lookAtAndRearrange,lookAtTopOfScenarioDeckThenPlace,loseKeywordUntil,loseTraitUntil,losesIcon,losesKeyword,made,mainSchemeAdvancedBy,mainSchemeMarkedBy,mainSchemePicksOffer,mainSchemeStageGist,mainSchemeStageNumber,mainSchemeStagesOffer,mainSchemeStagesProblem,max,maxDamageTaken,maxOnePerTriggeringInstance,maxSustainedDamage,mayLookAtTopOfEncounterDeckUntil,mergeCosts,mergeRegistries,min,minDamageTaken,modifyAttack,modifyBasicPower,modifyCardEffect,modifyCardEffectsUntil,modifyConsequentialDamage,modifyStat,modifyStatOf,modifyThwart,modularPickCountProblem,modularPickCountRange,modularPickProblem,modularSetContents,mojoCheckedOffSets,mojoModularSetPicks,mostCommonHandTypeCount,moveActiveCounterToNextInRow,moveActiveCounterToNextVillain,moveBoostCards,moveCards,moveCardsInto,moveCounters,moveThreat,multiplyStat,named,namedByTeamUpOf,nextAfter,not,notCountedTowardHandSize,notMatching,notOfChosenCardType,obligation,ofChosenCardType,ofClassification,ofIdentitySetTitled,ofTeamUpSet,offersEasierStart,offersGenePoolThreat,on,onChosenMainScheme,oncePerPaidCard,oncePerPhase,oncePerPhasePerEventPlayer,oncePerRound,oncePerRoundPerPlayer,oneCopyOf,onlyCharacterRemovesThreat,onlySourceRemovesThreat,onlyThwartsRemoveThreat,opsOfKind,option,otherFaceOf,otherPlayers,outsideFact,overdefeated,overpaidWhenPlayed,ownScriptsOf,ownerOf,packCampaignDefinitionOf,packCampaignDefinitions,packCampaignRecords,packCampaignsOf,packEncounterSetRecords,packModularSetChoices,obligation as packObligation,packScenarioOffer,packScenarioRecords,paidCards,paidInPlayCards,paidType,paidTypeCount,paidUsingResourceFrom,paidWith,paidWithCard,paidWithOnly,paidWithResourceCard,pairCards,pairLimit,partOf,passEncounterCard,payPrintedCostOf,payingFor,perHero,placeCountersCost,placeDamage,placeOnTopOrBottom,placeOnTopOrBottomOfPlayerDeck,placeThreat,placeThreatOnSharedScheme,playFromDeckIgnoringCost,playFromDeckReducingCost,playFromDiscard,playFromHandIgnoringCost,playFromHandReducingCost,playFromSeparateDeck,playNote,playOnlyIf,playSetAside,playTuckedCard,playWithTopOfDeckFaceup,playWithTopOfEncounterDeckFaceup,playableAttachments,playableScenario,playableScenarioOffer,playableScenarioWithCustom,playableStarterDeckSetup,playableTopOfDeck,playableTucked,playedThisPhase,playedThisRound,playedThisTurn,playedVia,playerOrElse,playersCannotDiscard,playersWhere,preparation,preventAllDamageTo,preventConsequentialDamage,preventDamage,preventThreat,printedBoostAreaIconsOn,printedCostAtLeast,printedCostOf,printedForm,printedHpNumeralOf,printedHpOf,printedResourcesInHandAs,printedResourcesOf,printedStatOf,printsAbility,product,publishIssues,putIntoPlay,putIntoPlayAsHost,putIntoPlayFacedown,putIntoPlayFromSetAside,putLinkedAllyIntoPlay,putMainSchemeStageIntoPlay,query,raiseMoment,randomCivilWarScenario,reachableFromPod,reaching,readPackInput,readsAtkOf,readsPaymentTypesOf,ready,readyCardsCost,recordInCampaignLog,reduceCostOfCards,reduceCostToPlay,reduceDamage,reduceDamageTo,reduceNextCardCost,reducesAttackDamageTaken,refCount,refMatches,remainingHpCompare,remainingHpOf,removeAccelerationToken,removeAllCounters,removeAllCountersFrom,removeAnAccelerationToken,removeCounter,removeCountersAmong,removeCountersFrom,removeEachCounterFrom,removeFromCampaign,removeMainSchemeStage,removeMainSchemeStages,removeStatus,removeThreat,removeThreatCost,removeThreatFromAScheme,removeThreatFromChosenCost,removeThreatUpToCost,removeUpToCounters,removeVillain,removedFromGameCards,reorderCards,repeatTimes,repeatWhile,replaceAttachHost,replaceBoostCount,replaceLeaveDestination,replaceNextVillainPhaseWithPlayerPhase,replaceStatus,replaceTuckHost,reportFact,resetHitPoints,resolveAttackAgainst,resolveBoostAbilitiesOf,resolveForcedInterruptOf,resolveForcedResponseCost,resolveForcedResponseOf,resolveModes,resolveOneTagged,resolvePreparationsOf,resolveSetups,resolveSpecialCost,resolveSpecials,resolveSpecialsOf,resolveTagged,resolveWhenDefeatedOf,resolveWhenRevealedOf,resource,resourceTypesOf,resourcesGeneratedAsWild,resourcesPaidBy,response,restrictedLimit,retargetAttack,retargetPlayerAttack,returnEachToHandCost,returnToHandAfterResolving,returnToHandCost,revealCard,revealEncounterCard,revealFromSetAsideModularSet,revealHeldMinion,revealHiddenPile,revealInstead,revealMainSchemeStage,revealNextVillainStage,revealSetAside,revealTopOfScenarioDeck,revealTopOfSeparateDeck,revealedFromEncounterDeck,revealedPileCardCount,rotateEngagement,rule,sameClassificationAs,scaled,scenarioArea,scenarioAreaCount,scenarioDeck,scenarioGameSetIds,scenarioSideClause,scenarioWithPacks,scenarioWithVillain,schemeStartedByAttackBoost,schemeThreatOn,searchAndReveal,searchCollection,searchEncounterIntoPlayCost,seedHiddenPiles,selectCards,self,sentence,separateDeckCards,separateDeckCountOf,setActiveVillain,setAside,setAsideDestination,setAsideModularSetCount,setDefeatDestination,setRemainingHitPoints,setVar,setVillainAside,setVillainSide,setup,sha256Hex,sharesTitleWith,sharesTraitWith,sharesTraitWithHeroOf,shuffleDeck,shuffleEncounterDeck,shuffleInSetAsideModularSet,shuffleIntoSeparateDeck,shuffleMainSchemeStageGroup,shuffleMainSchemeStages,shuffleSeparateDeck,shuffleTopOfSeparateDeckIntoEncounterDeck,sitOut,skipNextVillainPhase,skippedCommunityDecks,skirmishOffer,special,spend,spendChosen,spendDifferentResources,spendEqualTo,spendPrinted,spendResources,spendSameType,spendUpTo,spendX,spendXResources,spendableForAnyPlayer,spendableForPlayersWhere,spendableFromTucked,splitIssues,standardSetReplaceable,starIconsOn,starterDeckSetup,statCompare,statOf,stateCheck,stateCheckFromEntering,statusCount,statusLimit,staysInHand,stillCountedByDiscarder,stun,sum,superlative,superlativePlayer,surge,swapCards,swapIdentity,swapMainScheme,swapVillain,swapVillainByTrait,tagged,taggedAbilitiesOn,takeAnyDamageCost,takeControl,takeDamage,takeDamageCost,takeIndirectDamageCost,takeIntoHand,takesConsequentialDamage,takesDamageOnlyFrom,takesDamageOnlyFromAttacks,takesFirstTurn,teamUpCharacter,teamUpCharacters,textBoxCannotBeBlanked,thatAttackGainsKeywords,thatPlayer,theAccused,theAffectedCard,theMainScheme,theMole,theVillain,thisCardGenerates,thisGroup,threatAtLeast,threatOn,thwart,thwartAScheme,thwartInProgress,thwartTarget,titled,toScenarioDeck,topOfDeck,topOfDeckIsFaceup,topOfDeckMatches,topOfEncounterDeckIsFaceup,topOfEncounterDeckMatches,topOfEncounterDeckShowsIcons,topOfEncounterDeckShowsNoIcons,topOfYourDeckHas,totalPrintedCost,totalPrintedResources,totalStatOf,traitEncounterDeck,traitNumber,treatAsAlly,treatAsMinion,treatAttachedAllyAsMinion,treatAttachedHeroAsMinion,treatAttachedMinionAsAlly,treatAttachedVillainAsMinion,treatSelfAsAlly,tuckCards,tuckLimit,tuckedCount,tuckedUnder,tuckedUnderRef,turnFacedown,uncancellable,undefendedAttack,upgradesCannotBeRemoved,useActionAbility,useThwInsteadOfAtk,usingBasicPower,validateBuiltinPack,validateDefinition,validatePack,valueAtLeast,valueAtMost,valueEquals,varAtLeast,varFor,varOf,victoryCondition,victoryDisplayCards,victoryDisplayCount,villainChoiceOf,villainChoiceOffer,villainOnSide,villainOptionOf,villainStageNumberOf,wave10Scenario,wave10StarterDeckSetup,wave11Scenario,wave11ScenarioRecord,wave11StarterDeckSetup,wave1ReprintPairs,wave1Scenario,wave1StarterDeckSetup,wave2ReprintPairs,wave2Scenario,wave2StarterDeckSetup,wave3ReprintPairs,wave3Scenario,wave3StarterDeckSetup,wave7Scenario,wave7StarterDeckSetup,wave8Scenario,wave8StarterDeckSetup,wave9Scenario,wave9StarterDeckSetup,when,whenCompleted,whenDefeated,whenRevealed,whenRevealedAlterEgo,whenRevealedHero,whenSpentGenerate,whileOnChosenMainScheme,whileTucked,withFewestCounters,withModularSetContents,withMostCounters,you,youAre,youAreNamed,youHaveTrait,yourIdentity,yourLeader,yourMainScheme,yourTeam,zone,zoneCountOf};
package/dist/mc-pack.js CHANGED
@@ -1,12 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{src_exports}from"./chunks/chunk-6F73M3HY.js";import{formatImportReport,importMarvelCdbPack}from"./chunks/chunk-JR3ALXBR.js";import{PackBuildError,assemblePack,buildPack,loadPackSource}from"./chunks/chunk-GK7LCLI7.js";import{publishIssues,readPackInput,splitIssues,validatePack}from"./chunks/chunk-TUJLFNR7.js";import{SMOKE_BASE_DECK,SMOKE_SCENARIOS,smokeTestPack}from"./chunks/chunk-Y6B5ZZGK.js";import"./chunks/chunk-S3DCO2A6.js";import"./chunks/chunk-EKR67REN.js";import{existsSync}from"node:fs";import{join,resolve}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)}var EXIT_OK=0,EXIT_PACK_PROBLEM=1,EXIT_USAGE=2,consoleIo={out:line=>process.stdout.write(`${line}
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-D5S6EHFQ.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
 
6
6
  Usage:
7
- mc-pack validate <dir> [--allow-unscripted] [--publish]
8
- Check the pack source in <dir>. --allow-unscripted passes a pack whose only problems are abilities
9
- that are not scripted yet (an imported pack being worked on); build and test never allow them.
7
+ mc-pack validate <dir> [--allow-unscripted] [--publish] [--skip-typecheck]
8
+ Check the pack source in <dir>, type-checking abilities/ with TypeScript first (a type error is a problem:
9
+ the game runs the code without checking it); --skip-typecheck leaves that out. --allow-unscripted passes a
10
+ pack whose only problems are abilities that are not scripted yet (an imported pack being worked on); build
11
+ and test never allow them.
10
12
  --publish also checks the pack may be published: pack.json's permission records the creator's grant
11
13
  (status "granted", by, date, evidence, scope, and languages covering every language it ships). A folder
12
14
  with a DRAFT file is never published, so --publish skips that check for it.
@@ -23,4 +25,4 @@ validate, build and test run the pack's own code: they import its abilities/inde
23
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
24
26
  job with no secrets).
25
27
 
26
- 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","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=resolve(dir);if(!existsSync(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"]);let dir=packDir(parsed,"validate"),pack=await loadBuilt(dir),publish=parsed.flags.has("publish"),draft=existsSync(join(dir,"DRAFT"));publish&&draft&&io.out(`${pack.manifest.id}: a DRAFT, never published; the publish check is skipped`);let issues=[...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,resolve(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:resolve(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.51.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));
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.53.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-Y6B5ZZGK.js";import"./chunks/chunk-S3DCO2A6.js";import"./chunks/chunk-EKR67REN.js";export{SMOKE_BASE_DECK,SMOKE_SCENARIOS,playToOutcome,smokeTestPack};
1
+ import{SMOKE_BASE_DECK,SMOKE_SCENARIOS,playToOutcome,smokeTestPack}from"./chunks/chunk-D5S6EHFQ.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.51.0",
3
+ "version": "0.53.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",
@@ -53,7 +53,8 @@
53
53
  "LICENSE"
54
54
  ],
55
55
  "dependencies": {
56
- "jiti": "^2.7.0"
56
+ "jiti": "^2.7.0",
57
+ "typescript": "^7.0.2"
57
58
  },
58
59
  "publishConfig": {
59
60
  "access": "public"