@archivist-gg/dnd5e 0.3.28 → 0.3.29

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.
@@ -0,0 +1 @@
1
+ import{normalizeRollScope}from"./chunk-FOLHTMSC.js";import{toProfSlug}from"./chunk-VTQ4RWEG.js";import{memberSpellTargets}from"./chunk-J27N3KUE.js";import{heldPicks}from"./chunk-E4E6YEN6.js";import{warnOnce}from"./chunk-DZITM5AG.js";import{bareEntitySlug}from"./chunk-63YJPWTM.js";import{normalizeAbility}from"./chunk-EVT7MGAC.js";function emptyFeatureEffectTotals(){return{initiative_bonus:0,initiative_terms:[],initiative_amount_terms:[],skill_bonus_terms:[],save_bonus_terms:[],half_proficiency_terms:[],hp_per_level_bonus:0,hp_per_level_terms:[],speed_walk_bonus:0,speed_walk_terms:[],speed_terms:[],ignore_armor_strength:[],speed_walk_set:0,attunement_set:0,ability_bonus:{},ability_bonus_terms:[],senses:{darkvision:0,blindsight:0,tremorsense:0,truesight:0},ac_terms:[],resistances:[],immunities:[],vulnerabilities:[],condition_immunities:[],proficiencies:{skills:[],skillExpertise:[],tools:[],languages:[],saves:[],armor:[],weapons:[]},weaponAbilities:[],rollModifiers:[],saveOutcomes:[],critRange:20,conditionalCrits:[],extraAttack:0,scopedExtraAttacks:[],attackNotes:[],damageBonuses:[],spellDamageBonuses:[],damageRollOptions:[]}}function pushUnique(list,value){const key=value.trim().toLowerCase();if(!key)return;if(!list.some(v=>v.trim().toLowerCase()===key))list.push(value.trim())}function pushDefenseGrant(list,value,source,condition,item){var _a;const key=value.trim().toLowerCase();if(!key)return;const existing=list.find(g=>g.value.trim().toLowerCase()===key);if(existing){if(!existing.sources.includes(source))existing.sources.push(source);if(!existing.condition&&condition)existing.condition=condition;if(item)mergeDefenseItems((_a=existing.items)!=null?_a:existing.items=[],[item]);return}list.push({value:value.trim(),sources:[source],...condition?{condition}:{},...item?{items:[item]}:{}})}function mergeDefenseItems(into,from){for(const it of from)if(!into.some(x=>x.index===it.index))into.push({...it})}function ownerItem(owner,label){return(owner==null?void 0:owner.kind)==="item"?{index:owner.index,name:label}:void 0}var NAMED_COLUMN=/^column\(\s*'([^']+)'\s*\)$/;function foldsNow(rf,activeBuffs){if(rf.feature.activatable!==true)return true;const id=rf.feature.id;return!!id&&activeBuffs.has(id)}function assembleEffectFeatures(resolved){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j;const activeBuffs=new Set((_b=(_a=resolved.state)==null?void 0:_a.active_buffs)!=null?_b:[]);const featureIds=new Set(((_c=resolved.features)!=null?_c:[]).map(f=>f.feature.id).filter(id=>!!id));const aliases=[];for(const pool of(_d=resolved.pools)!=null?_d:[]){for(const entry of[...(_e=pool.selected)!=null?_e:[],...(_f=pool.grants)!=null?_f:[]]){if(activeBuffs.has(entry.slug))continue;const bare=bareEntitySlug(entry.slug);for(const stored of activeBuffs){if(featureIds.has(stored))continue;if(bareEntitySlug(stored)===bare){aliases.push(entry.slug);break}}}}for(const a of aliases)activeBuffs.add(a);const buffFeatures=[];const pushBoon=(item,pool)=>{var _a2,_b2,_c2,_d2,_e2,_f2,_g2,_h2,_i2,_j2,_k;const e=item.entity;if(!e||item.itemBound===true||((_b2=(_a2=e.effects)==null?void 0:_a2.length)!=null?_b2:0)===0)return;const block=(_f2=(_e2=(_d2=(_c2=resolved.classes)==null?void 0:_c2[pool.classIndex])==null?void 0:_d2.choices)==null?void 0:_e2[pool.anchorLevel])!=null?_f2:{};const spellTargets=memberSpellTargets(e,id=>{var _a3;return block[`${pool.id}:${(_a3=item.key)!=null?_a3:item.slug}:${id}`]});buffFeatures.push({feature:{id:item.slug,name:e.name,activatable:(_g2=e.activatable)!=null?_g2:false,effects:e.effects},source:{kind:"class",slug:(_k=(_j2=(_i2=(_h2=resolved.classes)==null?void 0:_h2[pool.classIndex])==null?void 0:_i2.entity)==null?void 0:_j2.slug)!=null?_k:pool.id,level:pool.anchorLevel},...spellTargets?{spellTargets}:{},poolMember:true})};for(const pool of(_g=resolved.pools)!=null?_g:[]){for(const sel of heldPicks(pool))pushBoon(sel,pool);for(const g of(_h=pool.grants)!=null?_h:[])pushBoon(g,pool)}return{features:[...(_i=resolved.features)!=null?_i:[],...buffFeatures,...(_j=resolved.itemFeatures)!=null?_j:[]],activeBuffs}}function foldsOnSelf(eff){if(eff.subject===void 0||eff.subject==="self")return true;warnOnce(eff.subject,`archivist: unrecognised effect subject "${eff.subject}" (only "self" folds)`);return false}function selfEffectsOf(f){var _a;return((_a=f.effects)!=null?_a:[]).filter(foldsOnSelf)}function computeFeatureEffects(features,opts){var _a,_b,_c;const out=emptyFeatureEffectTotals();for(const rf of features){if(!foldsNow(rf,(_a=opts==null?void 0:opts.activeBuffs)!=null?_a:new Set))continue;const level=(_b=opts==null?void 0:opts.levelFor)==null?void 0:_b.call(opts,rf.source);for(const eff of selfEffectsOf(rf.feature)){const effect=columnScaledRider(eff,rf,level,opts==null?void 0:opts.tableDiceFor,opts==null?void 0:opts.tableCellFor);if(effect)applyEffect(out,effect,(_c=rf.feature.name)!=null?_c:"Feature",level,rf.source,rf.spellTargets,rf)}}return out}function classifyProficiencyEffect(eff){if(eff.kind!=="proficiency")return null;const raw=eff.value;const expertise=eff.expertise===true;switch(eff.proficiency_type){case"skill":return{bucket:"skills",value:toProfSlug(raw),raw,expertise};case"tool":return{bucket:"tools",value:toProfSlug(raw),raw,expertise};case"language":return{bucket:"languages",value:toProfSlug(raw),raw,expertise};case"armor":return{bucket:"armor",value:raw.toLowerCase(),raw,expertise};case"weapon":return{bucket:"weapons",value:raw.toLowerCase(),raw,expertise};default:{const ab=normalizeAbility(raw);return ab?{bucket:"saves",value:ab,raw,expertise}:null}}}function collectProficiencyEffectGrants(features,activeBuffs){const out={skills:[],tools:[],languages:[],saves:[],armor:[],weapons:[]};for(const rf of features){if(!foldsNow(rf,activeBuffs))continue;for(const eff of selfEffectsOf(rf.feature)){const c=classifyProficiencyEffect(eff);if(!c)continue;out[c.bucket].push({value:c.value,raw:c.raw,sourceKind:rf.source.kind,sourceSlug:rf.source.slug,...c.expertise?{expertise:true}:{}})}}return out}function scaled(base,key,scalesAt,level){if(level===void 0||!(scalesAt==null?void 0:scalesAt.length))return base;let best=base;let bestLevel=-1;for(const step of scalesAt){if(step.level>level||step.level<=bestLevel)continue;const v=step[key];if(typeof v!=="number")continue;best=v;bestLevel=step.level}return best}function columnScaledRider(eff,rf,level,tableDiceFor,tableCellFor){var _a;if(eff.kind!=="damage-bonus")return eff;const named=NAMED_COLUMN.exec(eff.amount.trim());if(named){const cell=(_a=tableCellFor==null?void 0:tableCellFor(rf.source,named[1]))!=null?_a:null;return cell?{...eff,amount:cell}:null}if(level===void 0||!tableDiceFor)return eff;const src=rf.source;const column=rf.feature.name;if(src.kind!=="class"&&src.kind!=="subclass"||!column)return eff;const atGain=tableDiceFor(src,column,src.level);if(!atGain||atGain.toLowerCase()!==eff.amount.trim().toLowerCase())return eff;const now=tableDiceFor(src,column,level);return now?{...eff,amount:now}:eff}function riderScope(appliesTo){if(appliesTo===void 0||appliesTo==="all"||appliesTo==="spell")return void 0;return Array.isArray(appliesTo)?[...appliesTo]:[appliesTo]}function extraAttackSourceOf(rf,label,level,owner,scope){const source=owner!=null?owner:rf==null?void 0:rf.source;if(!source)return void 0;return{name:label,source,...level!==void 0?{level}:{},...(rf==null?void 0:rf.poolMember)?{poolMember:true}:{},...(rf==null?void 0:rf.feature.activatable)===true?{switched:true}:{},...scope?{scope}:{}}}function applyEffect(out,eff,label,level,owner,targets,rf){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q;switch(eff.kind){case"initiative-bonus":if(typeof eff.value==="number"){out.initiative_bonus+=eff.value;out.initiative_terms.push({label,value:eff.value})}else if(typeof eff.amount==="string"){out.initiative_amount_terms.push({label,amount:eff.amount,...owner?{owner}:{}})}break;case"skill-bonus":out.skill_bonus_terms.push({skills:eff.skills.map(toProfSlug),ability:eff.ability,minimum:(_a=eff.minimum)!=null?_a:0,label});break;case"save-bonus":out.save_bonus_terms.push({saves:[...(_b=eff.saves)!=null?_b:[]],ability:eff.ability,minimum:(_c=eff.minimum)!=null?_c:0,...eff.inactive_while?{inactiveWhile:eff.inactive_while}:{},label});break;case"half-proficiency":out.half_proficiency_terms.push({skills:((_d=eff.skills)!=null?_d:[]).map(toProfSlug),round:(_e=eff.round)!=null?_e:"down",label});break;case"hp-per-level-bonus":out.hp_per_level_bonus+=eff.value;out.hp_per_level_terms.push({label,value:eff.value});break;case"speed-bonus":{const gate=eff.inactive_while===void 0?void 0:[].concat(eff.inactive_while);const qualifiers={...eff.condition?{condition:eff.condition}:{},...gate?{inactiveWhile:gate}:{}};if(eff.equal_to==="walk"){out.speed_terms.push({mode:eff.mode,label,value:0,set:false,equalsWalk:true,...qualifiers});break}const value=scaled((_f=eff.value)!=null?_f:0,"value",eff.scales_at,level);out.speed_terms.push({mode:eff.mode,label,value,set:eff.set===true,...qualifiers});if(eff.mode==="walk"&&!gate){if(eff.set)out.speed_walk_set=Math.max(out.speed_walk_set,value);else{out.speed_walk_bonus+=value;out.speed_walk_terms.push({label,value})}}break}case"speed-rule":if(eff.flag==="ignore-armor-strength")out.ignore_armor_strength.push(label);break;case"attunement-limit":{out.attunement_set=Math.max(out.attunement_set,scaled(eff.value,"value",eff.scales_at,level));break}case"sense":out.senses[eff.type]=Math.max(out.senses[eff.type],eff.range);break;case"resistance":pushDefenseGrant(out.resistances,eff.damage_type,label,eff.condition,ownerItem(owner,label));break;case"immunity":pushDefenseGrant(out.immunities,eff.damage_type,label,eff.condition,ownerItem(owner,label));break;case"vulnerability":pushDefenseGrant(out.vulnerabilities,eff.damage_type,label,eff.condition,ownerItem(owner,label));break;case"immune-condition":if(!eff.while)pushDefenseGrant(out.condition_immunities,eff.condition,label,void 0,ownerItem(owner,label));else if((owner==null?void 0:owner.kind)==="item")pushDefenseGrant(out.condition_immunities,eff.condition,label,eff.while,ownerItem(owner,label));break;case"proficiency":{const c=classifyProficiencyEffect(eff);if(!c)break;if(c.bucket==="saves"){pushUnique(out.proficiencies.saves,c.value)}else{pushUnique(out.proficiencies[c.bucket],c.value)}if(c.expertise&&c.bucket==="skills")pushUnique(out.proficiencies.skillExpertise,c.value);break}case"ac-bonus":out.ac_terms.push({value:eff.value,requires_armor:eff.requires_armor===true,label,condition:eff.condition});break;case"weapon-ability":{if(eff.ability!=="spellcasting"){const w=eff.weapons;if(w==="pact-weapon"){out.weaponAbilities.push({ability:eff.ability,pactWeapon:true});break}const weaponSlugs=!w||w==="chosen"?void 0:Array.isArray(w)?w.map(bareEntitySlug):[bareEntitySlug(w)];out.weaponAbilities.push({ability:eff.ability,weaponSlugs})}break}case"roll-modifier":{const rolls=eff.roll==="any"?["ability-check","saving-throw","attack"]:[eff.roll];const scopes=(_g=normalizeRollScope(eff.scope,rolls[0]))!=null?_g:[eff.scope];for(const roll of rolls)for(const scope of scopes)out.rollModifiers.push({mode:eff.mode,roll,scope,condition:eff.condition,label});break}case"save-outcome":out.saveOutcomes.push({ability:eff.ability==="any"?void 0:eff.ability,on_success:eff.on_success,on_failure:eff.on_failure,appliesTo:(_h=eff.applies_to)!=null?_h:void 0,condition:eff.condition,label});break;case"crit-range":if(((_i=eff.applies_to)!=null?_i:"weapon")==="spell")break;if((_j=eff.condition)==null?void 0:_j.trim())out.conditionalCrits.push({minRoll:eff.min_roll,condition:eff.condition.trim(),source:label});else out.critRange=Math.min(out.critRange,eff.min_roll);break;case"extra-attack":{const count=scaled(eff.count,"count",eff.scales_at,level);const scope=riderScope(eff.applies_to);const source=extraAttackSourceOf(rf,label,level,owner,scope);if(scope)out.scopedExtraAttacks.push({count,scope,...source?{source}:{}});else if(count>out.extraAttack){out.extraAttack=count;if(source)out.extraAttackSource=source}}break;case"reroll-damage":{const qualifiers=[eff.once_per_die?"once/die":"",(_l=(_k=eff.condition)==null?void 0:_k.trim())!=null?_l:""].filter(q=>q!=="");out.attackNotes.push(`Reroll ${eff.max_reroll}s${qualifiers.length?` (${qualifiers.join(", ")})`:""}`)}break;case"attack-rule":if(eff.flag==="no-ranged-in-melee-disadvantage")out.attackNotes.push("No disadvantage firing in melee");break;case"damage-roll-option":{const scope=eff.applies_to===void 0?void 0:[].concat(eff.applies_to);out.damageRollOptions.push({mode:eff.mode,...eff.value!==void 0?{value:eff.value}:{},...eff.two_handed?{twoHanded:true}:{},...eff.once_per_turn?{oncePerTurn:true}:{},...((_m=eff.condition)==null?void 0:_m.trim())?{condition:eff.condition.trim()}:{},source:label,...scope?{scope}:{}});break}case"damage-bonus":if(((_n=eff.applies_to)!=null?_n:"weapon")!=="spell"){const scope=riderScope(eff.applies_to);out.damageBonuses.push({amount:eff.amount,damage_type:eff.damage_type,source:label,...eff.condition?{condition:eff.condition}:{},...scope?{scope}:{},...owner?{owner}:{}})}if(eff.applies_to==="spell"||eff.applies_to==="all"){const spellScope=(_o=eff.spell_scope)!=null?_o:eff.applies_to==="all"?{}:void 0;out.spellDamageBonuses.push({amount:eff.amount,damage_type:eff.damage_type,source:label,...eff.condition?{condition:eff.condition}:{},...owner?{owner}:{},...targets?{targets}:{},...spellScope?{scope:spellScope}:{}})}break;case"ability-score-increase":if(eff.abilities==="chosen")break;for(const ab of eff.abilities){out.ability_bonus[ab]=((_p=out.ability_bonus[ab])!=null?_p:0)+eff.amount;((_q=out.ability_bonus_terms)!=null?_q:out.ability_bonus_terms=[]).push({ability:ab,source:label,amount:eff.amount})}break;default:break}}export{emptyFeatureEffectTotals,pushDefenseGrant,mergeDefenseItems,foldsNow,assembleEffectFeatures,foldsOnSelf,selfEffectsOf,computeFeatureEffects,classifyProficiencyEffect,collectProficiencyEffectGrants};
@@ -0,0 +1 @@
1
+ import{isConsumedOnUse,itemSpellUse,resolveEntryEntity}from"./chunk-E4E6YEN6.js";import{isReadOnceItem}from"./chunk-DVUXUIPV.js";import{requiresAttunement}from"./chunk-YGH7S5ZF.js";import{resolveEntityForEntry}from"./chunk-4IAMSRHD.js";import{featureEffectSchema}from"./chunk-EON7T2SN.js";var linkSlug=item=>{var _a,_b;return(_b=(_a=/^\[\[(.+?)(\|.*)?\]\]$/.exec(item.trim()))==null?void 0:_a[1])!=null?_b:null};function itemBenefitsActive(entry,entity,registry,view){var _a;if(!entry.equipped)return false;if(requiresAttunement(entity)&&entry.attuned!==true)return false;if(isConsumedOnUse(entry,registry,view))return false;const slug=entity==null?void 0:entity.slug;if(isReadOnceItem(typeof slug==="string"&&slug?slug:(_a=linkSlug(entry.item))!=null?_a:entry.item))return false;return true}function itemSpellCastable(entry,registry,view){const use=itemSpellUse(entry,registry,view);if(!use||!registry)return false;if(use.kind==="consume")return true;const entity=view?view.entity:resolveEntityForEntry(entry.item,registry).entity;return itemBenefitsActive(entry,entity,registry,view)}function itemLabel(entry,entity){var _a,_b,_c,_d;return(_d=(_a=entry.overrides)==null?void 0:_a.name)!=null?_d:String((_c=(_b=entity==null?void 0:entity.name)!=null?_b:linkSlug(entry.item))!=null?_c:entry.item)}var ITEM_ROW_KINDS=new Set(["damage-bonus","crit-range","reroll-damage","extra-attack","weapon-ability","attack-rule"]);var GATE_VERB="(?:wear|wearing|hold|holding|wield|wielding)";var GATE_SUBJECT="(?:you |you're |you are )?";var ITEM_NAME="([a-z][a-z'-]*(?: [a-z][a-z'-]*){0,2})";var GATE_OBJECT=`(?:it|them|(?:this|these|the) ${ITEM_NAME})`;var GATE_PHRASES=[new RegExp(`^while ${GATE_SUBJECT}${GATE_VERB}(?: or ${GATE_VERB})? ${GATE_OBJECT}$`),new RegExp(`^while ${GATE_SUBJECT}attuned to ${GATE_OBJECT}$`),/^while (?:(?:it is|it's|they are) )?(?:worn|held|wielded)$/,new RegExp(`^while (?:this|the) ${ITEM_NAME} orbits your head$`)];var NOT_AN_ITEM_NAME=new Set(["and","or","with","without","in","on","at","of","to","from","while","when","if","but","against","within","near","until","during","for","is","are","you","your"]);function restatesItemGate(text){const t=(text!=null?text:"").replace(/’/g,"'").trim().toLowerCase().replace(/\s+/g," ").replace(/[.,;:]+$/,"");for(const re of GATE_PHRASES){const m=re.exec(t);if(!m)continue;if(m[1]!==void 0&&m[1].split(" ").some(w=>NOT_AN_ITEM_NAME.has(w)))continue;return true}return false}function withoutGateRestatement(e){if(e.kind==="apply-condition"||e.kind==="immune-condition")return e;if(!("condition"in e)||!restatesItemGate(e.condition))return e;const copy={...e};delete copy.condition;return copy}function readItemEffects(entity){const raw=entity==null?void 0:entity.effects;const effects=[];const invalid=[];if(!Array.isArray(raw))return{effects,invalid};for(const e of raw){const parsed=featureEffectSchema.safeParse(e);if(parsed.success)effects.push(withoutGateRestatement(parsed.data));else invalid.push(typeof(e==null?void 0:e.kind)==="string"?String(e.kind):"unknown")}return{effects,invalid}}function itemRowEffects(entity){return readItemEffects(entity).effects.filter(e=>ITEM_ROW_KINDS.has(e.kind))}function buildItemFeatures(equipment,registry,infusions,warnings){const out=[];if(typeof registry.getBySlug!=="function")return out;equipment.forEach((entry,index)=>{var _a,_b;if(!entry.equipped)return;const{entity,entityType}=resolveEntryEntity(entry,index,registry,infusions);if(!entity||entityType!=="item")return;if(!itemBenefitsActive(entry,entity,registry,infusions==null?void 0:infusions.views.get(index)))return;const{effects,invalid}=readItemEffects(entity);const name=itemLabel(entry,entity);if(invalid.length){warnings.push(`${name}: the sheet cannot read ${invalid.length===1?"this effect":"these effects"} (${invalid.join(", ")}); ignored.`)}const own=effects.filter(e=>!ITEM_ROW_KINDS.has(e.kind));if(own.length===0)return;const slug=String((_b=(_a=entity.slug)!=null?_a:linkSlug(entry.item))!=null?_b:entry.item);out.push({feature:{id:`item:${index}:${slug}`,name,activatable:false,effects:own},source:{kind:"item",slug,index}})});return out}export{itemBenefitsActive,itemSpellCastable,itemLabel,ITEM_ROW_KINDS,restatesItemGate,readItemEffects,itemRowEffects,buildItemFeatures};
@@ -1 +1 @@
1
- import{equipmentCategoryKey,isCategoryGrant}from"./chunk-2EOGK6R6.js";import{withSubspeciesParent}from"./chunk-4AJYEWFQ.js";import{TOOL_CATEGORIES,backgroundToolPicks,categoryWords,classToolPicks,expandToolPool,toolCategoriesOf}from"./chunk-RQZCGXUZ.js";import{replacementChoiceId,replacementDescription,replacementOwner,replacementPick}from"./chunk-CLZRWPWT.js";import{assembleEffectFeatures,classifyProficiencyEffect,collectProficiencyEffectGrants,foldsNow,selfEffectsOf}from"./chunk-4FTTUZXM.js";import{ALL_LANGUAGES,ALL_SKILL_SLUGS,ALL_TOOLS}from"./chunk-4JEF3CET.js";import{humanizeProficiency,proficiencyLabel,toProfSlug}from"./chunk-VTQ4RWEG.js";import{buildItemFeatures}from"./chunk-MMDUUEFA.js";import{classPactWeaponPick,featOfSite,featPickSites,isTargetChoice,memberChoices,pactWeaponPick,poolMemberSites,poolMemberSitesOf,raceFeatSites}from"./chunk-J27N3KUE.js";import{collectAdditionalSpells}from"./chunk-RR26E7LH.js";import{resolveFeatureResources,resolveResourceIndex}from"./chunk-2OVDSMPY.js";import{attributeUnclassedSpell,effectiveSpellcastingAbility,normalizeKnownSpell,resolveSpellcasting}from"./chunk-PFQPP77Q.js";import{convertibleLegacyAsi,flattenAsiOrFeat,resolveLegacyAsiFeat}from"./chunk-QVWT67WA.js";import{bindFeatureConsumers,buildInfusionContext,resolveAllPools,resolveOptionRows,storedSpellNumbers,strandedPicks,withoutStrandedSites}from"./chunk-E4E6YEN6.js";import{countColumnsFor,readTableColumn}from"./chunk-CSTAQQGX.js";import{recognizeDecision}from"./chunk-3LWOVRLA.js";import{isItemEntity,resolveEntityForEntry}from"./chunk-4IAMSRHD.js";import{FEATURE_TYPE_FOR_CATEGORY,featCategoryOf,featProgressionCategory}from"./chunk-3QQOATV3.js";import{warnOnce}from"./chunk-DZITM5AG.js";import{resolveBaseItem}from"./chunk-PZ4L2EEG.js";import{bucketOf}from"./chunk-QMEKQTUT.js";import{isValidMaxFormula}from"./chunk-EAARMPCW.js";import{bareEntitySlug,wikilinkTailSlug}from"./chunk-63YJPWTM.js";import{mirrorSpellShapes}from"./chunk-4KVVAENP.js";import{ABILITY_KEYS,ALL_SKILLS}from"./chunk-EVT7MGAC.js";import{withResolvedActionCost}from"./chunk-S5UCI27C.js";var UNKNOWN_SOURCE="Unknown";var UNKNOWN_GRANT_SOURCE=UNKNOWN_SOURCE;function grantSourceName(resolved,kind,slug){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r;switch(kind){case"class":return(_d=(_c=(_b=(_a=resolved.classes)==null?void 0:_a.find(c=>{var _a2;return((_a2=c.entity)==null?void 0:_a2.slug)===slug}))==null?void 0:_b.entity)==null?void 0:_c.name)!=null?_d:UNKNOWN_SOURCE;case"subclass":return(_h=(_g=(_f=(_e=resolved.classes)==null?void 0:_e.find(c=>{var _a2;return((_a2=c.subclass)==null?void 0:_a2.slug)===slug}))==null?void 0:_f.subclass)==null?void 0:_g.name)!=null?_h:UNKNOWN_SOURCE;case"race":return(_j=(_i=resolved.race)==null?void 0:_i.name)!=null?_j:UNKNOWN_SOURCE;case"background":return(_l=(_k=resolved.background)==null?void 0:_k.name)!=null?_l:UNKNOWN_SOURCE;case"feat":return(_o=(_n=(_m=resolved.feats)==null?void 0:_m.find(f=>f.slug===slug))==null?void 0:_n.name)!=null?_o:UNKNOWN_SOURCE;case"item":return(_r=(_q=(_p=resolved.itemFeatures)==null?void 0:_p.find(f=>f.source.slug===slug))==null?void 0:_q.feature.name)!=null?_r:UNKNOWN_SOURCE;default:return UNKNOWN_SOURCE}}function collectProficiencyGrants(resolved){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x;const classArmor=[];const classWeaponFixed=[];const classWeaponCategories=[];const classToolFixed=[];for(const c of resolved.classes){const prof=(_a=c.entity)==null?void 0:_a.proficiencies;if(!prof)continue;const source=(_c=(_b=c.entity)==null?void 0:_b.name)!=null?_c:UNKNOWN_SOURCE;for(const a of(_d=prof.armor)!=null?_d:[])classArmor.push({value:a,source});for(const w of(_f=(_e=prof.weapons)==null?void 0:_e.fixed)!=null?_f:[])classWeaponFixed.push({value:w,source});for(const w of(_h=(_g=prof.weapons)==null?void 0:_g.categories)!=null?_h:[])classWeaponCategories.push({value:w,source});for(const t of(_j=(_i=prof.tools)==null?void 0:_i.fixed)!=null?_j:[])classToolFixed.push({value:t,source});for(const t of classToolPicks(c.entity).grants)classToolFixed.push({value:t,source})}const raceSource=(_l=(_k=resolved.race)==null?void 0:_k.name)!=null?_l:UNKNOWN_SOURCE;const raceLangFixed=((_o=(_n=(_m=resolved.race)==null?void 0:_m.languages)==null?void 0:_n.fixed)!=null?_o:[]).map(l=>({value:l,source:raceSource}));const bgToolFixed=[];const bgLangFixed=[];const bg=resolved.background;if(bg){const source=(_p=bg.name)!=null?_p:UNKNOWN_SOURCE;for(const entry of(_q=bg.tool_proficiencies)!=null?_q:[]){if(entry.kind==="fixed"){for(const t of entry.items)bgToolFixed.push({value:t,source})}}for(const t of backgroundToolPicks(bg).grants)bgToolFixed.push({value:t,source});for(const entry of(_r=bg.language_proficiencies)!=null?_r:[]){if(entry.kind==="fixed"){for(const l of entry.languages)bgLangFixed.push({value:l,source})}}}const featArmor=[];const featWeapons=[];const featTools=[];const featLanguages=[];for(const f of(_s=resolved.feats)!=null?_s:[]){const featView=f;const grants=featView.proficiencies;if(!grants)continue;const source=(_t=f.name)!=null?_t:UNKNOWN_SOURCE;for(const a of(_u=grants.armor)!=null?_u:[])featArmor.push({value:a,source});for(const w of(_v=grants.weapons)!=null?_v:[])featWeapons.push({value:w,source});for(const t of(_w=grants.tools)!=null?_w:[])featTools.push({value:t,source});for(const l of(_x=grants.languages)!=null?_x:[])featLanguages.push({value:l,source})}const{features:effectFeatures,activeBuffs}=assembleEffectFeatures(resolved);const fx=collectProficiencyEffectGrants(effectFeatures,activeBuffs);const nameFor=(kind,slug)=>grantSourceName(resolved,kind,slug);const toGrants=(list,useRaw)=>list.map(g=>({value:useRaw?g.raw:g.value,source:nameFor(g.sourceKind,g.sourceSlug),...g.expertise?{expertise:true}:{}}));const effectArmor=toGrants(fx.armor,true);const effectWeapons=toGrants(fx.weapons,true);const effectTools=toGrants(fx.tools,false);const effectLanguages=toGrants(fx.languages,false);return{classArmor,classWeaponFixed,classWeaponCategories,classToolFixed,raceLangFixed,bgToolFixed,bgLangFixed,featArmor,featWeapons,featTools,featLanguages,effectArmor,effectWeapons,effectTools,effectLanguages}}function inventoryOptions(resolved,registry,entityType){var _a,_b,_c,_d;const out=[];const seen=new Set;const find=ref=>{var _a2,_b2;const withSlug=registry;if(typeof withSlug.getBySlug==="function")return resolveBaseItem(ref,withSlug);const bare=ref.replace(/^\[\[/,"").replace(/\]\]$/,"").split("|")[0].trim();return(_b2=(_a2=registry.getByTypeAndSlug(entityType,bare))!=null?_a2:registry.getByTypeAndSlug("item",bare))!=null?_b2:null};for(const entry of(_b=(_a=resolved.definition)==null?void 0:_a.equipment)!=null?_b:[]){if(typeof entry.item!=="string")continue;const e=find(entry.item);if(!e||seen.has(e.slug))continue;const value=e.slug;const base=e.entityType===entityType?e:typeof e.data.base_item==="string"?find(e.data.base_item):null;if(!base||base.entityType!==entityType)continue;seen.add(value);const name=(_d=(_c=entry.overrides)==null?void 0:_c.name)!=null?_d:e.name;out.push({value,label:name,entity:e})}return out}var warnedDegradedEquipment=new Set;var warnedAmbiguousBare=new Set;var foldedTypeMemo=new Map;function foldedType(s){let v=foldedTypeMemo.get(s);if(v===void 0){v=categoryWords(s).join(" ");foldedTypeMemo.set(s,v)}return v}function matchesFilter(e,where,ownerBare){var _a,_b,_c,_d,_e,_f;const d=e.data;if(where.feature_type&&d.feature_type!==where.feature_type)return false;if(where.category&&featCategoryOf((_a=d.category)!=null?_a:"")!==featCategoryOf(where.category))return false;if(where.list&&!((_b=d.classes)!=null?_b:[]).includes(where.list))return false;if(where.level!==void 0&&((_c=d.level)!=null?_c:0)!==where.level)return false;if(where.edition&&d.edition!==where.edition)return false;if(where.ritual&&d.ritual!==true)return false;if(where.weapon_category){const cat=((_d=d.category)!=null?_d:"").toLowerCase();if(!cat.startsWith(`${where.weapon_category}-`)&&cat!==where.weapon_category)return false}if(where.armor_category){if(((_e=d.category)!=null?_e:"").toLowerCase()!==where.armor_category)return false}if(where.item_type){const t=foldedType(typeof d.type==="string"?d.type:"");if(!t||!where.item_type.some(x=>foldedType(x)===t))return false}if(where.mundane){const r=typeof d.rarity==="string"?d.rarity.trim().toLowerCase():"";if(r&&r!=="none"&&r!=="mundane")return false}if(where.parent_class==="self"){if(!d.parent_class||wikilinkTailSlug(d.parent_class)!==ownerBare)return false}if(where.available_to==="self"){const list=(_f=d.available_to)!=null?_f:[];if(!list.some(l=>wikilinkTailSlug(l)===ownerBare))return false}return true}var __matchesFilterForTest=matchesFilter;function parseEquipmentCategory(category){const tools=toolCategoriesOf(category);if(tools)return{kind:"tool",tools};const words=categoryWords(category).filter(w=>w!=="any");const has=w=>words.includes(w);const only=allowed=>words.every(w=>allowed.includes(w));if(words.length===1&&has("shield"))return{kind:"shield"};if(has("armor")&&only(["armor","light","medium","heavy"])&&words.length<=2){const armor=["light","medium","heavy"].find(k=>has(k));return{kind:"armor",armor}}if(has("weapon")&&only(["weapon","simple","martial","melee","ranged"])){const klass=["simple","martial"].filter(k=>has(k));const range=["melee","ranged"].filter(k=>has(k));if(klass.length===1&&range.length<=1&&words.length===2+range.length){return{kind:"weapon",weapon:klass[0],range:range[0]}}}return void 0}function categoryToEntitySelect(category,id){const spec=parseEquipmentCategory(category);const pick={kind:"select-entity",id,count:1};switch(spec==null?void 0:spec.kind){case"shield":return{...pick,label:"Choose a shield",entity_type:"armor",where:{armor_category:"shield"}};case"armor":return spec.armor?{...pick,label:`Choose ${spec.armor} armor`,entity_type:"armor",where:{armor_category:spec.armor}}:{...pick,label:"Choose armor",entity_type:"armor"};case"weapon":return{...pick,label:`Choose a ${spec.weapon}${spec.range?` ${spec.range}`:""} weapon`,entity_type:"weapon",where:{weapon_category:spec.weapon}};case"tool":return{...pick,label:`Choose ${spec.tools.map(t=>TOOL_CATEGORIES[t].label).join(" or ")}`,entity_type:"item",where:{item_type:spec.tools.map(t=>TOOL_CATEGORIES[t].itemType),mundane:true}};default:warnOnce(`equipment-category:${category}`,`Archivist: starting-equipment category "${category}" is not a known item category; its pick offers no options.`);return{...pick,label:`Choose a ${category.replace(/[-_]+/g," ")}`,entity_type:"item",from:[]}}}var __categoryToEntitySelectForTest=categoryToEntitySelect;function equipmentDecisions(entries,ownerSlug){const out=[];let degraded=false;(entries!=null?entries:[]).forEach((eq,i)=>{var _a;if((eq==null?void 0:eq.kind)!=="choice")return;const options=(_a=eq.options)!=null?_a:[];out.push({kind:"select-inline",id:`equipment-${i}`,label:"Starting Equipment",count:1,options:options.map((opt,j)=>{var _a2;const label=typeof opt==="string"?opt:(_a2=opt==null?void 0:opt.label)!=null?_a2:"";const wellFormed=!!opt&&typeof opt==="object"&&Array.isArray(opt.grants);if(!wellFormed)degraded=true;const grants=wellFormed?opt.grants:[];return{value:`option-${j}`,label,choices:grants.flatMap((g,k)=>isCategoryGrant(g)?[categoryToEntitySelect(g.category,equipmentCategoryKey(i,j,k))]:[])}})})});if(degraded&&!warnedDegradedEquipment.has(ownerSlug)){warnedDegradedEquipment.add(ownerSlug);console.warn(`[archivist] Starting equipment for "${ownerSlug}" is in an outdated/unstructured format; its nested picks and seeding are skipped. Re-sync the compendium (delete _compendium.md and reload) to fix.`)}return out}function authoredProficiencyPool(choice){if(!choice.from)return void 0;return choice.domain==="tool"?expandToolPool(choice.from):choice.from}function enumerateOptions(choice,ctx,ownerBare){var _a,_b;switch(choice.kind){case"select-inline":return choice.options.map(o=>({value:o.value,label:o.label,description:o.description}));case"select-entity":{if(choice.from){let byBare;const bareIndex=()=>{var _a2,_b2,_c,_d;if(byBare)return byBare;const built=new Map;const pool=ctx.registry.search("",choice.entity_type,Number.POSITIVE_INFINITY).slice().sort((a,b)=>a.name.localeCompare(b.name)||a.slug.localeCompare(b.slug));const seed=e=>{const bare=bareEntitySlug(e.slug);if(built.has(bare)){if(!warnedAmbiguousBare.has(bare)){warnedAmbiguousBare.add(bare);console.warn(`Archivist: bare slug "${bare}" matches multiple ${choice.entity_type} entities; using "${built.get(bare).slug}"`)}return}built.set(bare,e)};for(const e of pool)if((_b2=(_a2=ctx.isEntityVisible)==null?void 0:_a2.call(ctx,e))!=null?_b2:true)seed(e);for(const e of pool)if(!((_d=(_c=ctx.isEntityVisible)==null?void 0:_c.call(ctx,e))!=null?_d:true))seed(e);byBare=built;return built};return choice.from.map(slug=>{var _a2;const e=(_a2=ctx.registry.getByTypeAndSlug(choice.entity_type,slug))!=null?_a2:bareIndex().get(slug);return e?{value:e.slug,label:e.name,entity:e}:{value:slug,label:slug,missing:true}})}const all=ctx.registry.search("",choice.entity_type,Number.POSITIVE_INFINITY);const filtered=choice.where?all.filter(e=>matchesFilter(e,choice.where,ownerBare)):all;return filtered.map(e=>({value:e.slug,label:e.name,entity:e}))}case"select-proficiency":{const pool=(_a=authoredProficiencyPool(choice))!=null?_a:choice.domain==="skill"?[...ALL_SKILL_SLUGS]:choice.domain==="language"?[...ALL_LANGUAGES]:choice.domain==="tool"?[...ALL_TOOLS]:[];return pool.map(v=>({value:v,label:humanizeProficiency(v)}))}case"ability-points":{const pool=(_b=choice.pool)!=null?_b:["str","dex","con","int","wis","cha"];return pool.map(a=>({value:a,label:a.toUpperCase()}))}}}function selectionCount(choice,selected){if(selected===void 0)return 0;if(choice.kind==="ability-points"){if(typeof selected!=="object"||Array.isArray(selected))return 0;return Object.values(selected).reduce((s,v)=>s+(typeof v==="number"?v:0),0)}if(Array.isArray(selected))return selected.length;return typeof selected==="string"&&selected.length>0?1:0}function requiredCount(choice){var _a;if(choice.kind==="ability-points")return choice.points;if(choice.kind==="select-proficiency")return choice.count;return(_a=choice.count)!=null?_a:1}function capAtCount(choice,value){const folds=choice.kind==="select-proficiency"||choice.kind==="select-entity"&&choice.entity_type==="weapon"&&choice.id!=="weapon-mastery"&&!isTargetChoice(choice);if(!folds||!Array.isArray(value))return value;const n=requiredCount(choice);return value.length>n?value.slice(0,n):value}function statusOf(choice,selected,satisfied){const n=selectionCount(choice,selected);const need=requiredCount(choice);if(satisfied)return"resolved";if(n===0)return"unresolved";return n>=need?"resolved":"partial"}var matchPool=(v,pool)=>pool.find(p=>toProfSlug(p)===toProfSlug(v));var canonicalizeSelection=(value,pool)=>{var _a;if(typeof value==="string")return(_a=matchPool(value,pool))!=null?_a:value;if(Array.isArray(value))return value.map(v=>{var _a2;return(_a2=matchPool(v,pool))!=null?_a2:v});return value};function resolveEntityRef(ctx,entityType,value){if(typeof value!=="string"||value.length===0)return void 0;const raw=value.replace(/^\[\[/,"").replace(/\]\]$/,"");const direct=ctx.registry.getByTypeAndSlug(entityType,raw);if(direct)return direct;for(const e of ctx.registry.search("",entityType,Number.POSITIVE_INFINITY)){if(e.slug===raw||bareEntitySlug(e.slug)===raw)return e}return void 0}function buildItem(inputChoice,source,level,featureName,readValue,ctx,ownerBare,effective,opts){var _a,_b,_c,_d,_e;const choice=flattenAsiOrFeat(inputChoice);const keyPrefix=(_a=opts==null?void 0:opts.keyPrefix)!=null?_a:"";const expandFeatChildren=(_b=opts==null?void 0:opts.expandFeatChildren)!=null?_b:true;const key=keyPrefix+choice.id;const raw=capAtCount(choice,readValue(key));const preExclusionOptions=choice.kind==="select-entity"&&((_c=choice.where)==null?void 0:_c.inventory)===true?effective.inventory(choice.entity_type):enumerateOptions(choice,ctx,ownerBare);let options=preExclusionOptions;const mine=new Set((Array.isArray(raw)?raw:raw===void 0?[]:[raw]).map(v=>toProfSlug(String(v))));if(choice.kind==="select-proficiency"&&choice.domain==="skill"&&choice.from_proficient){options=options.filter(o=>effective.skill.has(toProfSlug(o.value))||mine.has(toProfSlug(o.value)))}const postInclusionOptions=options;const excludes=choice.kind==="select-proficiency"&&(choice.domain==="language"||choice.domain==="tool"||choice.domain==="skill"&&choice.expertise===true);if(excludes&&choice.kind==="select-proficiency"){const known=choice.domain==="skill"?effective.skillExpertise:effective[choice.domain];options=options.filter(o=>!known.has(toProfSlug(o.value))||mine.has(toProfSlug(o.value)))}const satisfied=excludes&&postInclusionOptions.length>0&&options.length===0;const selected=choice.kind==="select-proficiency"?canonicalizeSelection(raw,options.map(o=>o.value)):raw;const item={key,source,level,featureName,choice,description:opts==null?void 0:opts.description,options,selected,status:statusOf(choice,selected,satisfied),satisfied};if(choice.kind==="select-inline"&&typeof selected==="string"){const branch=choice.options.find(o=>o.value===selected);if((_d=branch==null?void 0:branch.choices)==null?void 0:_d.length){item.children=branch.choices.map(c=>buildItem(c,source,level,featureName,readValue,ctx,ownerBare,effective,{keyPrefix,expandFeatChildren}));if(item.status==="resolved"&&item.children.some(c=>c.status!=="resolved")){item.status="partial"}}}if(choice.kind==="select-entity"&&choice.entity_type==="feat"&&expandFeatChildren&&typeof selected==="string"){const entity=resolveEntityRef(ctx,"feat",selected);const rawChoices=(_e=entity==null?void 0:entity.data)==null?void 0:_e.choices;const featChoices=Array.isArray(rawChoices)?rawChoices:[];if(featChoices.length){const childPrefix=`${keyPrefix}feat:`;item.children=featChoices.map(c=>buildItem(c,source,level,featureName,readValue,ctx,ownerBare,effective,{keyPrefix:childPrefix,expandFeatChildren:false}));if(item.status==="resolved"&&item.children.some(c=>c.status!=="resolved")){item.status="partial"}}}return item}function buildSubclassItem(choice,source,level,featureName,c,ctx,ownerBare,description){const selected=c.subclass?c.subclass.slug:void 0;return{key:"subclass",source,level,featureName,description,choice,options:enumerateOptions(choice,ctx,ownerBare),selected,status:selected?"resolved":"unresolved",satisfied:false}}function visitProficiencyChoices(resolved,visit){var _a,_b,_c,_d,_e,_f;const walk=(choices,read,owner,kind)=>{for(const ch of choices!=null?choices:[]){visit(ch,read(ch.id),owner,kind);if(ch.kind==="select-inline"){const sel=read(ch.id);const branch=typeof sel==="string"?ch.options.find(o=>o.value===sel):void 0;if(branch==null?void 0:branch.choices)walk(branch.choices,read,owner,kind)}}};const oc=(_a=resolved.definition.origin_choices)!=null?_a:{};const originRead=ns=>id=>oc[`${ns}:${id}`];const stripRef=ref=>ref.replace(/^\[\[/,"").replace(/\]\]$/,"");const featBySlug=new Map(((_b=resolved.feats)!=null?_b:[]).map(f=>[f.slug,f]));const memberSites=poolMemberSitesOf(resolved);const featSites=featPickSites(resolved.classes,memberSites,ci=>{var _a2,_b2,_c2,_d2;return(_d2=(_c2=(_b2=(_a2=resolved.classes)==null?void 0:_a2[ci])==null?void 0:_b2.entity)==null?void 0:_c2.slug)!=null?_d2:null});resolved.classes.forEach((c,i)=>{var _a2,_b2,_c2,_d2,_e2,_f2,_g,_h;if(!c.entity)return;const entity=c.entity;const readAt=lvl=>id=>{var _a3;return(_a3=c.choices[lvl])==null?void 0:_a3[id]};const className=entity.name;if(i===0&&((_b2=(_a2=entity.skill_choices)==null?void 0:_a2.from)==null?void 0:_b2.length)){visit({kind:"select-proficiency",id:"skills",count:entity.skill_choices.count,domain:"skill",from:entity.skill_choices.from},readAt(1)("skills"),className,"class")}if(i===0)walk(entity.choices,readAt(1),className,"class");if(i===0)walk(classToolPicks(entity).decisions,readAt(1),className,"class");for(const rf of resolved.features){if(rf.source.kind!=="class"&&rf.source.kind!=="subclass")continue;const belongs=rf.source.kind==="class"?rf.source.slug===entity.slug:c.subclass!=null&&rf.source.slug===c.subclass.slug;if(!belongs)continue;const featureOwner=rf.source.kind==="subclass"?(_d2=(_c2=c.subclass)==null?void 0:_c2.name)!=null?_d2:className:className;for(const copy of(_e2=rf.foldedFrom)!=null?_e2:[])walk(copy.choices,readAt(copy.level),featureOwner,"class");walk(rf.feature.choices,readAt(rf.source.level),featureOwner,"class")}for(const site of featSites){if(site.classIndex!==i)continue;const feat=(_g=featBySlug.get(stripRef(site.slug)))!=null?_g:featOfSite(site,(_f2=resolved.feats)!=null?_f2:[]);if(!feat)continue;walk(feat.choices,site.read,feat.name,"feat")}for(const site of memberSites)if(site.classIndex===i)walk(site.choices,site.read,(_h=site.member.name)!=null?_h:className,"class")});if(resolved.race){const raceName=resolved.race.name;walk(resolved.race.choices,originRead("race"),raceName,"race");for(const t of(_c=resolved.race.traits)!=null?_c:[])walk(t.choices,originRead("race"),raceName,"race")}if(resolved.background){const bgName=resolved.background.name;walk(resolved.background.choices,originRead("background"),bgName,"background");walk(backgroundToolPicks(resolved.background).decisions,originRead("background"),bgName,"background");if(resolved.background.feature){const feature=resolved.background.feature;walk(feature.choices,originRead("background"),bgName,"background")}}for(const r of(_d=resolved.proficiencyReplacements)!=null?_d:[]){walk([r.choice],originRead(r.carrier.kind),replacementOwner(r),r.carrier.kind)}if(resolved.originFeatSlug){const of=featBySlug.get(resolved.originFeatSlug);if(of)walk(of.choices,id=>oc[`background:feat:${id}`],of.name,"feat")}for(const site of raceFeatSites(resolved.race,oc)){const rf=(_f=featBySlug.get(stripRef(site.slug)))!=null?_f:((_e=resolved.feats)!=null?_e:[]).find(f=>bareEntitySlug(f.slug)===bareEntitySlug(site.slug));if(rf)walk(rf.choices,site.read,rf.name,"feat")}}var filterToPool=(vals,pool)=>pool?vals.map(v=>matchPool(v,pool)).filter(v=>!!v):vals;function collectChosenProficiencies(resolved){const out={skills:[],expertise:[],languages:[],tools:[],weapons:[],saves:[]};forEachChosenProficiency(resolved,(bucket,value)=>{const list=out[bucket];if(!list.includes(value))list.push(value)});return out}function forEachChosenProficiency(resolved,on){const isAbility=v=>ABILITY_KEYS.includes(v);visitProficiencyChoices(resolved,(choice,stored,owner,ownerKind)=>{const selected=capAtCount(choice,stored);const vals=Array.isArray(selected)?selected:typeof selected==="string"?[selected]:[];if(choice.kind==="select-entity"&&choice.entity_type==="weapon"){if(choice.id==="weapon-mastery"||isTargetChoice(choice))return;for(const v of vals){const bare=bareEntitySlug(String(v));if(bare)on("weapons",bare,owner,ownerKind)}return}if(choice.kind!=="select-proficiency")return;const valid=filterToPool(vals,authoredProficiencyPool(choice));if(choice.domain==="save"){for(const v of valid)if(isAbility(v))on("saves",v,owner,ownerKind);return}const bucket=choice.domain==="skill"?choice.expertise?"expertise":"skills":choice.domain==="language"?"languages":choice.domain==="tool"?"tools":null;if(bucket)for(const v of valid)on(bucket,v,owner,ownerKind)})}function collectRuleProficiencySources(resolved){var _a,_b,_c,_d;const out={skills:{},expertise:{},saves:{}};const add=(rec,key,source)=>{var _a2;const list=(_a2=rec[key])!=null?_a2:rec[key]=[];if(!list.includes(source))list.push(source)};const firstClass=(_b=(_a=resolved.classes)==null?void 0:_a[0])==null?void 0:_b.entity;if(firstClass)for(const ab of(_c=firstClass.saving_throws)!=null?_c:[])add(out.saves,ab,firstClass.name);const bg=resolved.background;const replaced=new Set(pickedReplacements(resolved).map(({r})=>`${r.carrier.kind}:${r.domain}:${r.value}`));if(bg)for(const sk of(_d=bg.skill_proficiencies)!=null?_d:[]){if(!replaced.has(`background:skill:${toProfSlug(sk)}`))add(out.skills,sk,bg.name)}forEachChosenProficiency(resolved,(bucket,value,owner)=>{if(bucket==="skills"||bucket==="expertise"||bucket==="saves")add(out[bucket],value,owner)});const{features,activeBuffs}=assembleEffectFeatures(resolved);for(const rf of features){if(!foldsNow(rf,activeBuffs))continue;for(const eff of selfEffectsOf(rf.feature)){const c=classifyProficiencyEffect(eff);if(!c||c.bucket!=="skills"&&c.bucket!=="saves")continue;if(c.bucket==="skills"&&!c.expertise&&replaced.has(`${rf.source.kind}:skill:${toProfSlug(c.value)}`))continue;const named=grantSourceName(resolved,rf.source.kind,rf.source.slug);const source=named===UNKNOWN_GRANT_SOURCE?rf.feature.name:named;if(c.bucket==="saves")add(out.saves,c.value,source);else add(c.expertise?out.expertise:out.skills,c.value,source)}}return out}function pickedReplacements(resolved){var _a,_b;const oc=(_a=resolved.definition)==null?void 0:_a.origin_choices;const out=[];for(const r of(_b=resolved.proficiencyReplacements)!=null?_b:[]){const pick=replacementPick(r,oc);if(pick)out.push({r,pick})}return out}var STEP_RANK={race:0,class:1,background:2,other:3};var stepOf=k=>k==="race"?"race":k==="background"?"background":k==="class"||k==="subclass"?"class":"other";function collectProficiencyReplacements(resolved){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l;const base={...resolved,proficiencyReplacements:void 0};const bg=base.background;const race=base.race;if(!bg&&!race)return[];const grants={skill:new Map,tool:new Map};const note=(domain,raw,g)=>{var _a2;if(typeof raw!=="string"||!raw.trim())return;const v=toProfSlug(raw);const list=(_a2=grants[domain].get(v))!=null?_a2:[];if(!list.some(x=>x.step===g.step&&x.name===g.name&&x.fixed===g.fixed))list.push(g);grants[domain].set(v,list)};const strings=v=>Array.isArray(v)?v:[];const{features,activeBuffs}=assembleEffectFeatures(base);const fx=collectProficiencyEffectGrants(features,activeBuffs);const effectName=g=>grantSourceName(base,g.sourceKind,g.sourceSlug);for(const g of fx.skills)if(!g.expertise)note("skill",g.value,{name:effectName(g),step:stepOf(g.sourceKind),fixed:true});for(const g of fx.tools)note("tool",g.value,{name:effectName(g),step:stepOf(g.sourceKind),fixed:true});if(bg){for(const sk of strings(bg.skill_proficiencies))note("skill",sk,{name:bg.name,step:"background",fixed:true});for(const e of strings(bg.tool_proficiencies)){if(e&&typeof e==="object"&&e.kind==="fixed"){for(const t of strings(e.items))note("tool",t,{name:bg.name,step:"background",fixed:true})}}for(const t of backgroundToolPicks(bg).grants)note("tool",t,{name:bg.name,step:"background",fixed:true})}const carried=[...grants.skill.values(),...grants.tool.values()].some(list=>list.some(g=>g.fixed&&(g.step==="race"||g.step==="background")));if(!carried)return[];for(const c of(_a=base.classes)!=null?_a:[]){const e=c.entity;if(!e)continue;const tools=(_b=e.proficiencies)==null?void 0:_b.tools;for(const t of[...strings(tools==null?void 0:tools.fixed),...classToolPicks(e).grants])note("tool",t,{name:e.name,step:"class",fixed:true})}for(const f of(_c=base.feats)!=null?_c:[]){const tools=(_d=f.proficiencies)==null?void 0:_d.tools;for(const t of strings(tools))note("tool",t,{name:f.name,step:"other",fixed:true})}forEachChosenProficiency(base,(bucket,value,owner,kind)=>{if(bucket==="skills")note("skill",value,{name:owner,step:stepOf(kind),fixed:false});else if(bucket==="tools")note("tool",value,{name:owner,step:stepOf(kind),fixed:false})});const held={skill:new Set([...(_g=(_f=(_e=base.definition)==null?void 0:_e.skills)==null?void 0:_f.proficient)!=null?_g:[],...(_j=(_i=(_h=base.definition)==null?void 0:_h.skills)==null?void 0:_i.expertise)!=null?_j:[],...fx.skills.map(g=>g.value),...grants.skill.keys(),...collectChosenProficiencies(base).expertise].map(toProfSlug)),tool:new Set};let toolsHeld=false;const heldTools=()=>{if(!toolsHeld){toolsHeld=true;for(const e of computeEffectiveProficiencies(base).tools)held.tool.add(toProfSlug(e.value))}return held.tool};const candidates=[];const skillOrder=v=>{const i=ALL_SKILL_SLUGS.indexOf(v);return i<0?999:i};for(const domain of["skill","tool"]){const entries=[...grants[domain].entries()];if(domain==="skill")entries.sort(([a],[b])=>skillOrder(a)-skillOrder(b));for(const[value,list]of entries){const sources=[];for(const g of[...list].sort((a,b)=>STEP_RANK[a.step]-STEP_RANK[b.step])){if(!sources.some(x=>x.step===g.step&&x.name===g.name))sources.push(g)}const names=keep=>[...new Set(sources.filter(keep).map(g=>g.name))];const label=domain==="skill"?(_k=ALL_SKILLS.find(d=>toProfSlug(d)===value))!=null?_k:humanizeProficiency(value):humanizeProficiency(value);const id=replacementChoiceId(domain,value);const bgCarries=!!bg&&list.some(g=>g.step==="background"&&g.fixed)&&names(g=>g.step!=="background").length>0;if(bg&&bgCarries){candidates.push({domain,value,label,id,carrier:{kind:"background",slug:bg.slug,name:bg.name},others:names(g=>g.step!=="background")})}const raceOthers=names(g=>g.step!=="race"&&!(bgCarries&&g.step==="background"));if(race&&list.some(g=>g.step==="race"&&g.fixed)&&raceOthers.length>0){candidates.push({domain,value,label,id,carrier:{kind:"race",slug:race.slug,name:race.name},others:raceOthers})}}}const oc=(_l=base.definition)==null?void 0:_l.origin_choices;const picks=candidates.map(c=>replacementPick({carrier:c.carrier,choice:{id:c.id}},oc));return candidates.map((c,i)=>{const vocab=c.domain==="skill"?ALL_SKILL_SLUGS:ALL_TOOLS;const taken=new Set(picks.filter((p,j)=>j!==i&&p&&candidates[j].domain===c.domain));const own=picks[i];const have=c.domain==="skill"?held.skill:heldTools();const from=vocab.filter(v=>v===own||!have.has(v)&&!taken.has(v));const{id,...rest}=c;return{...rest,choice:{kind:"select-proficiency",id,label:`Already proficient in ${c.label}: pick a replacement`,count:1,domain:c.domain,from}}})}function proficiencyEntryFor(raw,vocab,origin,sources,expertise){const hit=matchPool(raw,vocab);const value=hit?toProfSlug(hit):raw;const label=hit?humanizeProficiency(value):origin==="custom"?raw:proficiencyLabel(raw);return{value,label,sources,origin,...expertise?{expertise:true}:{}}}function computeEffectiveProficiencies(resolved){const c=composeLanguageToolProficiencies(resolved);return{languages:c.languages.kept,tools:c.tools.kept}}function computeSuppressedProficiencies(resolved){const c=composeLanguageToolProficiencies(resolved);return{languages:c.languages.suppressed,tools:c.tools.suppressed}}function composeLanguageToolProficiencies(resolved){const grants=collectProficiencyGrants(resolved);const chosen=collectChosenProficiencies(resolved);const build=domain=>{var _a,_b,_c,_d,_e,_f,_g,_h;const vocab=domain==="languages"?ALL_LANGUAGES:ALL_TOOLS;const ov=(_b=(_a=resolved.definition)==null?void 0:_a.overrides)==null?void 0:_b[domain];const adds=(_c=ov==null?void 0:ov.add)!=null?_c:[];const removes=(_d=ov==null?void 0:ov.remove)!=null?_d:[];const byValue=new Map;const push=(raw,origin,source,expertise)=>{const probe=proficiencyEntryFor(raw,vocab,origin,source?[source]:[],expertise);const existing=byValue.get(probe.value);if(!existing){byValue.set(probe.value,probe);return}if(source&&!existing.sources.includes(source))existing.sources.push(source);if(expertise)existing.expertise=true;const rank={grant:0,pick:1,manual:2,custom:3};if(rank[origin]<rank[existing.origin])existing.origin=origin};const grantBuckets=domain==="languages"?[grants.raceLangFixed,grants.bgLangFixed,grants.featLanguages,grants.effectLanguages]:[grants.classToolFixed,grants.bgToolFixed,grants.featTools,grants.effectTools];const replacedTools=domain==="tools"?pickedReplacements(resolved).filter(({r})=>r.domain==="tool"):[];for(const b of grantBuckets)for(const g of b){if(replacedTools.some(({r})=>r.carrier.name===g.source&&r.value===toProfSlug(g.value)))continue;push(g.value,"grant",g.source,g.expertise)}for(const{r,pick}of replacedTools)push(pick,"pick",replacementOwner(r));for(const v of domain==="languages"?chosen.languages:chosen.tools)push(v,"pick");for(const v of adds)push(v,matchPool(v,vocab)?"manual":"custom");const triSuppressed=new Set;if(domain==="tools"){const tri=(_h=(_g=(_f=(_e=resolved.definition)==null?void 0:_e.overrides)==null?void 0:_f.tools)==null?void 0:_g.proficiency)!=null?_h:{};for(const[tool,state]of Object.entries(tri)){const key=toProfSlug(tool);if(state==="none"){triSuppressed.add(key);continue}let entry=[...byValue.values()].find(e=>toProfSlug(e.value)===key);if(!entry){push(tool,matchPool(tool,vocab)?"manual":"custom");entry=[...byValue.values()].find(e=>toProfSlug(e.value)===key)}if(!entry)continue;if(state==="expertise")entry.expertise=true;else delete entry.expertise}}const suppressed=new Set([...removes.map(r=>toProfSlug(r)),...triSuppressed]);const byLabel=(a,b)=>a.label<b.label?-1:a.label>b.label?1:0;const kept=[...byValue.values()].filter(e=>!suppressed.has(toProfSlug(e.value))).sort(byLabel);return{kept,suppressed:[...byValue.values()].filter(e=>suppressed.has(toProfSlug(e.value))).sort(byLabel)}};return{languages:build("languages"),tools:build("tools")}}function collectChosenAbilityPoints(resolved){var _a,_b,_c;const oc=(_a=resolved.definition.origin_choices)!=null?_a:{};const out={race:{},background:{}};const fold=(ns,choices)=>{var _a2;for(const ch of choices!=null?choices:[]){if(ch.kind!=="ability-points")continue;const raw=oc[`${ns}:${ch.id}`];if(!raw||typeof raw!=="object"||Array.isArray(raw))continue;let left=ch.points;for(const ab of ABILITY_KEYS){if(ch.pool&&!ch.pool.includes(ab))continue;const v=raw[ab];if(typeof v!=="number"||v<=0||left<=0)continue;const take=Math.min(v,ch.max_per,left);out[ns][ab]=((_a2=out[ns][ab])!=null?_a2:0)+take;left-=take}}};const race=resolved.race;if(race){fold("race",race.choices);for(const t of(_b=race.traits)!=null?_b:[])fold("race",t.choices)}const bg=resolved.background;if(bg){fold("background",bg.choices);fold("background",(_c=bg.feature)==null?void 0:_c.choices)}return out}function buildDecisionLedger(resolved,ctx){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n;const eff=computeEffectiveProficiencies(resolved);const chosen=collectChosenProficiencies(resolved);const{features,activeBuffs}=assembleEffectFeatures(resolved);const effectGrants=collectProficiencyEffectGrants(features,activeBuffs);const effective={language:new Set(eff.languages.map(e=>toProfSlug(e.value))),tool:new Set(eff.tools.map(e=>toProfSlug(e.value))),skill:new Set([...(_c=(_b=(_a=resolved.definition)==null?void 0:_a.skills)==null?void 0:_b.proficient)!=null?_c:[],...(_e=(_d=resolved.background)==null?void 0:_d.skill_proficiencies)!=null?_e:[],...chosen.skills,...effectGrants.skills.map(g=>g.value)].map(toProfSlug)),skillExpertise:new Set([...(_h=(_g=(_f=resolved.definition)==null?void 0:_f.skills)==null?void 0:_g.expertise)!=null?_h:[],...chosen.expertise,...effectGrants.skills.filter(g=>g.expertise).map(g=>g.value)].map(toProfSlug)),inventory:entityType=>inventoryOptions(resolved,ctx.registry,entityType)};const classes=[];resolved.classes.forEach((c,classIndex)=>{var _a2,_b2,_c2,_d2,_e2,_f2,_g2,_h2,_i2,_j2,_k2,_l2,_m2,_n2,_o;if(!c.entity)return;const entity=c.entity;const ownerBare=bareEntitySlug(entity.slug);const byLevel=new Map;const push=(lvl,item)=>{var _a3;const arr=(_a3=byLevel.get(lvl))!=null?_a3:[];arr.push(item);byLevel.set(lvl,arr)};const readAt=lvl=>id=>{var _a3;return(_a3=c.choices[lvl])==null?void 0:_a3[id]};let legacyAsiFeat;const legacyAsiReader=(choice,lvl)=>{const alloc=convertibleLegacyAsi(c.choices[lvl]);if(!alloc)return null;const flat=flattenAsiOrFeat(choice);if(flat.kind!=="select-entity"||flat.entity_type!=="feat"||flat.from||flat.where)return null;if(legacyAsiFeat===void 0)legacyAsiFeat=resolveLegacyAsiFeat(ctx.registry,entity);const asi=legacyAsiFeat;if(!asi)return null;const raw=readAt(lvl);const childKey=`feat:${asi.childId}`;return id=>id==="feat"?asi.slug:id===childKey?alloc:raw(id)};const featProgressions=[...(_a2=entity.feat_progression)!=null?_a2:[],...(_c2=(_b2=c.subclass)==null?void 0:_b2.feat_progression)!=null?_c2:[]];const suppressedFeatureTypes=new Set;for(const decl of[...(_d2=entity.selection_pools)!=null?_d2:[],...(_f2=(_e2=c.subclass)==null?void 0:_e2.selection_pools)!=null?_f2:[]]){const rp=resolved.pools.find(p=>p.classIndex===classIndex&&p.id===decl.id);if(rp&&rp.count>=1)suppressedFeatureTypes.add(decl.source.where.feature_type)}for(const entry of featProgressions){const category=featProgressionCategory(entry.category);const ft=category?FEATURE_TYPE_FOR_CATEGORY[category]:void 0;if(ft)suppressedFeatureTypes.add(ft)}if(classIndex===0&&((_h2=(_g2=entity.skill_choices)==null?void 0:_g2.from)==null?void 0:_h2.length)){const skillChoice={kind:"select-proficiency",id:"skills",label:"Skill Proficiencies",count:entity.skill_choices.count,domain:"skill",from:entity.skill_choices.from};push(1,buildItem(skillChoice,{kind:"class",slug:entity.slug,level:1},1,"Proficiencies",readAt(1),ctx,ownerBare,effective))}if(classIndex===0){for(const ch of[...(_i2=entity.choices)!=null?_i2:[],...classToolPicks(entity).decisions]){push(1,buildItem(ch,{kind:"class",slug:entity.slug,level:1},1,"Proficiencies",readAt(1),ctx,ownerBare,effective))}}if(classIndex===0){for(const ch of equipmentDecisions(entity.starting_equipment,entity.slug)){push(1,buildItem(ch,{kind:"class",slug:entity.slug,level:1},1,"Starting Equipment",readAt(1),ctx,ownerBare,effective))}}let sawAuthoredSubclass=false;const staged=[];const authoredRank=(kind,level,feature)=>{var _a3,_b3,_c3;const at=(_c3=(_b3=(_a3=kind==="class"?entity:c.subclass)==null?void 0:_a3.features_by_level)==null?void 0:_b3[level])!=null?_c3:[];const index=at.findIndex(f=>feature.id?f.id===feature.id:f.name===feature.name);return(kind==="class"?0:1)*1e6+(index<0?999999:index)};for(const rf of resolved.features){const src=rf.source;if(src.kind!=="class"&&src.kind!=="subclass")continue;const belongs=src.kind==="class"?src.slug===entity.slug:c.subclass!=null&&src.slug===c.subclass.slug;if(!belongs)continue;const lvl=src.level;const stage=(atLvl,item)=>{staged.push({level:atLvl,item,rank:authoredRank(src.kind,atLvl,rf.feature),seq:staged.length})};const emitChoices=(list,atLvl,name,description)=>{var _a3,_b3;for(const ch of list){if(ch.kind==="select-entity"&&ch.entity_type==="subclass"){sawAuthoredSubclass=true;stage(atLvl,buildSubclassItem(ch,src,atLvl,name,c,ctx,ownerBare,description));continue}let emitted=ch;if(ch.kind==="select-entity"){const columns=countColumnsFor(ch.id);const fromTable=columns?readTableColumn(entity.table,c.level,columns):null;if(fromTable!=null)emitted={...ch,count:Math.max((_a3=ch.count)!=null?_a3:1,fromTable)}}stage(atLvl,buildItem(emitted,src,atLvl,name,(_b3=legacyAsiReader(emitted,atLvl))!=null?_b3:readAt(atLvl),ctx,ownerBare,effective,{description}))}};const informationalItem=(atLvl,name,description)=>{var _a3,_b3;return{key:(_a3=rf.feature.id)!=null?_a3:name,source:src,level:atLvl,featureName:name,description,choice:{kind:"select-inline",id:(_b3=rf.feature.id)!=null?_b3:name,options:[{value:"_",label:"_"}]},options:[],selected:void 0,status:"informational",satisfied:false}};const emitCopy=copy=>{let list=copy.choices;if(!(list==null?void 0:list.length)){const recognized=recognizeDecision({id:rf.feature.id,name:copy.name,description:copy.description});if(recognized==="informational"){stage(copy.level,informationalItem(copy.level,copy.name,copy.prose));return}list=recognized!=null?recognized:void 0;if(list==null?void 0:list.length){list=list.filter(ch=>{var _a3;if(ch.kind!=="select-entity")return true;const ft=(_a3=ch.where)==null?void 0:_a3.feature_type;return!(ft!==void 0&&suppressedFeatureTypes.has(ft))})}}if(!(list==null?void 0:list.length)){if(copy.prose)stage(copy.level,informationalItem(copy.level,copy.name,copy.prose));return}emitChoices(list,copy.level,copy.name,copy.description)};for(const copy of(_j2=rf.foldedFrom)!=null?_j2:[])emitCopy({...copy,prose:copy.description});emitCopy({level:lvl,name:rf.feature.name,description:rf.feature.description,prose:rf.feature.description||(((_k2=rf.feature.entries)==null?void 0:_k2.length)?rf.feature.entries.join("\n\n"):void 0),choices:rf.feature.choices})}staged.sort((a,b)=>a.rank-b.rank||a.seq-b.seq);for(const s of staged)push(s.level,s.item);const subclassLevel=(_l2=entity.subclass_level)!=null?_l2:null;if(subclassLevel!=null&&subclassLevel<=c.level&&!sawAuthoredSubclass){const featureName=(_m2=entity.subclass_feature_name)!=null?_m2:"Subclass";const synthChoice={kind:"select-entity",id:"subclass",label:featureName,count:1,entity_type:"subclass",where:{parent_class:"self"}};push(subclassLevel,buildSubclassItem(synthChoice,{kind:"class",slug:entity.slug,level:subclassLevel},subclassLevel,featureName,c,ctx,ownerBare))}for(const pool of resolved.pools){if(pool.classIndex!==classIndex||pool.count<1)continue;const stranded=strandedPicks(pool);const strandedSlugs=new Set(stranded.map(e=>e.slug));const synth={kind:"select-entity",id:pool.id,label:pool.label,count:pool.count,entity_type:"optional-feature",from:[...pool.available.map(e=>e.slug),...stranded.map(e=>e.slug)]};const item=buildItem(synth,{kind:"class",slug:entity.slug,level:pool.anchorLevel},pool.anchorLevel,pool.label,()=>pool.selected.map(e=>e.key),ctx,ownerBare,effective);item.pool={id:pool.id,anchorLevel:pool.anchorLevel};const repeatables=pool.available.filter(e=>e.entity.repeatable===true);if(repeatables.length>0){item.repeatable=repeatables.map(e=>{var _a3,_b3;return{noteSlug:e.slug,itemChoice:(_a3=e.entity.item_choice)!=null?_a3:"learn",rows:resolveOptionRows(e.entity,ctx.registry,{edition:resolved.definition.edition,isEntityVisible:(_b3=ctx.isEntityVisible)==null?void 0:_b3.bind(ctx)})}})}for(const o of item.options)if(strandedSlugs.has(o.value))o.stranded=true;const memberChildren=[];for(const entry of pool.selected){for(const ch of memberChoices(entry.entity)){const child=buildItem(ch,{kind:"class",slug:entity.slug,level:pool.anchorLevel},pool.anchorLevel,entry.entity.name,readAt(pool.anchorLevel),ctx,ownerBare,effective,{keyPrefix:`${pool.id}:${entry.key}:`});child.parentLabel=entry.entity.name;memberChildren.push(child)}}if(memberChildren.length){item.children=memberChildren;if(item.status==="resolved"&&memberChildren.some(c2=>c2.status!=="resolved"))item.status="partial"}push(pool.anchorLevel,item)}for(const entry of featProgressions){const category=featProgressionCategory(entry.category);if(!category){warnOnce(`feat-progression-category:${entity.slug}:${entry.name}`,`Archivist: feat_progression "${entry.name}" on "${entity.slug}" carries no category this engine maps (${((_n2=entry.category)!=null?_n2:[]).join(", ")}); no decision is offered`);continue}const progression=entry.progression;if(Array.isArray(progression))continue;for(const key of Object.keys(progression)){const lvl=Number.parseInt(key,10);if(!Number.isInteger(lvl)||String(lvl)!==key)continue;if(lvl>c.level)continue;if(((_o=byLevel.get(lvl))!=null?_o:[]).some(i=>i.key==="feat")){warnOnce(`feat-progression-collision:${entity.slug}:${lvl}`,`Archivist: "${entry.name}" on "${entity.slug}" would add a second feat pick at level ${lvl}, where one already exists; skipping`);continue}const progressionChoice={kind:"select-entity",id:"feat",label:entry.name,count:1,entity_type:"feat",where:{category}};push(lvl,buildItem(progressionChoice,{kind:"class",slug:entity.slug,level:lvl},lvl,entry.name,readAt(lvl),ctx,ownerBare,effective))}}const levels=[...byLevel.entries()].sort(([a],[b])=>a-b).map(([level,items])=>({level,items}));classes.push({classIndex,levels})});const origin=[];const oc=(_i=resolved.definition.origin_choices)!=null?_i:{};const originRead=ns=>id=>oc[`${ns}:${id}`];const pushOrigin=(choices,ns,source,featureName,ownerBare,description)=>{for(const ch of choices!=null?choices:[]){origin.push(buildItem(ch,source,0,featureName,originRead(ns),ctx,ownerBare,effective,{description}))}};const pushReplacements=(kind,bare)=>{var _a2;for(const r of(_a2=resolved.proficiencyReplacements)!=null?_a2:[]){if(r.carrier.kind!==kind)continue;origin.push(buildItem(r.choice,{kind,slug:r.carrier.slug},0,r.carrier.name,originRead(kind),ctx,bare,effective,{description:replacementDescription(r)}))}};if(resolved.race){const bare=bareEntitySlug(resolved.race.slug);pushReplacements("race",bare);pushOrigin(resolved.race.choices,"race",{kind:"race",slug:resolved.race.slug},(_j=resolved.race.name)!=null?_j:"Race",bare);for(const t of(_k=resolved.race.traits)!=null?_k:[]){pushOrigin(t.choices,"race",{kind:"race",slug:resolved.race.slug},t.name,bare,t.description)}}if(resolved.background){const bare=bareEntitySlug(resolved.background.slug);pushReplacements("background",bare);pushOrigin([...(_l=resolved.background.choices)!=null?_l:[],...backgroundToolPicks(resolved.background).decisions],"background",{kind:"background",slug:resolved.background.slug},(_m=resolved.background.name)!=null?_m:"Background",bare);if(resolved.background.feature){pushOrigin(resolved.background.feature.choices,"background",{kind:"background",slug:resolved.background.slug},resolved.background.feature.name,bare,resolved.background.feature.description)}if(resolved.background.origin_feat){const originFeat=resolveOriginFeat(ctx.registry,resolved.background.origin_feat,resolved.background.slug);if(originFeat){const featSource={kind:"feat",slug:originFeat.feat.slug};const featBare=bareEntitySlug(originFeat.feat.slug);for(const ch of(_n=originFeat.feat.choices)!=null?_n:[]){origin.push(buildItem(ch,featSource,0,originFeat.display,originRead("background"),ctx,featBare,effective,{keyPrefix:"feat:"}))}}}for(const ch of equipmentDecisions(resolved.background.equipment,resolved.background.slug)){origin.push(buildItem(ch,{kind:"background",slug:resolved.background.slug},0,"Starting Equipment",originRead("background"),ctx,bare,effective))}}return{classes,origin}}var SLUG_RE=/^\[\[(.+?)\]\]$/;function stripSlug(ref){if(!ref)return null;const m=ref.match(SLUG_RE);return m?m[1]:ref}function resolveOriginFeat(entities,originFeatRef,ownerSlug){var _a,_b,_c;if(!originFeatRef)return null;const slug=wikilinkTailSlug(originFeatRef);const inner=originFeatRef.replace(/^\[\[/,"").replace(/\]\]$/,"").trim();const rawTail=(_b=(_a=inner.split("/").pop())==null?void 0:_a.trim())!=null?_b:"";const base=rawTail.replace(/\s*\([^()]*\)\s*$/,"").trim();const baseSlug=base&&base!==rawTail?wikilinkTailSlug(`[[${base}]]`):null;const baseInner=baseSlug?inner.slice(0,inner.length-rawTail.length)+base:null;const prefix=(ownerSlug==null?void 0:ownerSlug.includes("_"))?ownerSlug.slice(0,ownerSlug.indexOf("_")):null;const feats=bucketOf(entities,"feat");const byPath=p=>feats.find(f=>f.filePath===`${p}.md`||f.filePath.endsWith(`/${p}.md`));const sameCompendiumTail=s=>prefix?feats.find(f=>f.slug.startsWith(`${prefix}_feat_`)&&f.slug.endsWith(`_${s}`)):void 0;const anyTail=s=>feats.find(f=>f.slug.endsWith(`_${s}`));const tiers=[()=>{var _a2;return(_a2=feats.find(f=>f.slug===inner))!=null?_a2:feats.find(f=>f.slug===slug)},()=>byPath(inner),()=>baseInner?byPath(baseInner):void 0,()=>sameCompendiumTail(slug),()=>baseSlug?sameCompendiumTail(baseSlug):void 0,()=>anyTail(slug),()=>baseSlug?anyTail(baseSlug):void 0];let reg;let hitTier=0;for(let i=0;i<tiers.length&&!reg;i++){reg=tiers[i]();hitTier=i+1}if(!reg)return null;const variantName=baseSlug&&(hitTier===3||hitTier===5||hitTier===7)?rawTail:void 0;const data=reg.data;const feat=data.slug==null?{...data,slug:reg.slug}:data;return{feat,display:(_c=variantName!=null?variantName:feat.name)!=null?_c:slug}}var PCResolver=class{constructor(entities){this.entities=entities}get registry(){return this.entities}resolve(character){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j;const warnings=[];const lookup=(rawRef,type)=>{const slug=stripSlug(rawRef);if(!slug)return null;const reg=this.entities.getByTypeAndSlug(type,slug);if(!reg){warnings.push(`Slug [[${slug}]] not found in compendium as ${type}.`);return null}const data=reg.data;return data.slug==null?{...data,slug:reg.slug}:data};const race=withSubspeciesParent(lookup(character.race,"race"),this.entities);const background=lookup(character.background,"background");const classes=character.class.map(c=>({entity:lookup(c.name,"class"),level:c.level,subclass:lookup(c.subclass,"subclass"),choices:c.choices}));const memberSites=withoutStrandedSites(poolMemberSites(classes,this.entities),classes,this.entities,character.edition);const classSlugOf=i=>{var _a2,_b2,_c2,_d2,_e2;return(_e2=(_b2=(_a2=classes[i])==null?void 0:_a2.entity)==null?void 0:_b2.slug)!=null?_e2:stripSlug((_d2=(_c2=character.class[i])==null?void 0:_c2.name)!=null?_d2:null)};const featSites=featPickSites(character.class,memberSites,classSlugOf);const feats=[];const featVia=new Map;for(const site of featSites){const f=lookup(`[[${site.slug}]]`,"feat");if(!f)continue;if(!feats.some(x=>x.slug===f.slug))feats.push(f);if(site.via&&!featVia.has(f.slug))featVia.set(f.slug,site.via)}const originFeat=(background==null?void 0:background.origin_feat)?resolveOriginFeat(this.entities,background.origin_feat,background.slug):null;const originFeatSlug=originFeat==null?void 0:originFeat.feat.slug;if(originFeat&&!feats.some(f=>f.slug===originFeat.feat.slug)){feats.push(originFeat.feat)}if(originFeat&&background&&!featVia.has(originFeat.feat.slug)){featVia.set(originFeat.feat.slug,{kind:"background",slug:background.slug})}const raceFeats=[];for(const site of raceFeatSites(race,character.origin_choices)){const f=lookup(`[[${site.slug}]]`,"feat");if(!f)continue;raceFeats.push({feat:f,read:site.read});if(!feats.some(x=>x.slug===f.slug))feats.push(f);if(!featVia.has(f.slug))featVia.set(f.slug,site.via)}const totalLevel=classes.reduce((sum,c)=>sum+c.level,0);const features=collectResolvedFeatures(race,classes,background,feats,featVia);const extraFeatures=collectChosenGrantedFeatures(character,classes,this.entities,race,background,memberSites);features.push(...extraFeatures);const originChoices=(_a=character.origin_choices)!=null?_a:{};const featChoiceSites=[];for(const site of featSites){const f=lookup(`[[${site.slug}]]`,"feat");if(f)featChoiceSites.push({feat:f,via:site.via,read:site.read})}if(originFeat&&background){featChoiceSites.push({feat:originFeat.feat,via:{kind:"background",slug:background.slug},read:id=>originChoices[`background:feat:${id}`]})}for(const rf of raceFeats)featChoiceSites.push({feat:rf.feat,via:race?{kind:"race",slug:race.slug}:null,read:rf.read});features.push(...collectFeatChoiceGrants(featChoiceSites,this.entities));features.push(...collectAdditionalFeatures(character,this.entities,warnings));const casters=[];classes.forEach((c,i)=>{const profile=c.entity?resolveSpellcasting(c):null;const classSlug=profile?stripSlug(character.class[i].name):null;if(profile&&classSlug!=null)casters.push({classSlug,spellList:profile.spellList})});const spells=[];for(const raw of(_b=character.spells.known)!=null?_b:[]){const n=normalizeKnownSpell(raw);const reg=this.entities.getByTypeAndSlug("spell",n.slug);if(!reg){warnings.push(`Spell [[${n.slug}]] not found in compendium.`);continue}const entity=mirrorSpellShapes(reg.data);const isCantrip=((_c=entity.level)!=null?_c:0)===0;const classSlug=(_d=n.classSlug)!=null?_d:attributeUnclassedSpell(entity.classes,casters,this.entities);const prep=isCantrip||n.alwaysPrepared?true:(_e=n.preparedFlag)!=null?_e:false;spells.push({entity,slug:n.slug,classSlug,source:n.source,prepared:prep,alwaysPrepared:n.alwaysPrepared,persisted:true})}const oc=(_f=character.origin_choices)!=null?_f:{};if(originFeat){const read=childId=>oc[`background:feat:${childId}`];spells.push(...collectFeatGrantedSpells(originFeat.feat,read,this.entities,warnings))}for(const rf of raceFeats)spells.push(...collectFeatGrantedSpells(rf.feat,rf.read,this.entities,warnings));for(const site of featSites){const reg=this.entities.getByTypeAndSlug("feat",site.slug);if(!reg)continue;const feat=reg.data;spells.push(...collectFeatGrantedSpells(feat,site.read,this.entities,warnings))}for(const site of memberSites){const classSlug=stripSlug((_h=(_g=character.class[site.classIndex])==null?void 0:_g.name)!=null?_h:null);for(const ch of site.choices){if(ch.kind!=="select-entity"||ch.entity_type!=="spell"||isTargetChoice(ch))continue;const v=site.read(ch.id);for(const ref of Array.isArray(v)?v:typeof v==="string"?[v]:[]){const slug=typeof ref==="string"?stripSlug(ref):null;if(!slug)continue;const reg=this.entities.getByTypeAndSlug("spell",slug);if(!reg){warnings.push(`Spell [[${slug}]] not found in compendium.`);continue}const entity=mirrorSpellShapes(reg.data);spells.push({entity,slug,classSlug,source:"class",prepared:true,alwaysPrepared:true})}}}const ownSpellcastingAbility=(_i=classes.map(c=>{if(!c.entity)return null;const p=resolveSpellcasting(c);return p?effectiveSpellcastingAbility(c.entity.slug,p.ability,character.overrides):null}).find(a=>a!=null))!=null?_i:null;spells.push(...collectItemGrantedSpells(character,ownSpellcastingAbility,this.entities,warnings));const chosenMasteries=collectChosenWeaponMasteries(character);if(chosenMasteries.full.length>0){const target=features.find(rf=>{var _a2;return rf.feature.id==="weapon-mastery"||((_a2=rf.feature.choices)==null?void 0:_a2.some(ch=>ch.kind==="select-entity"&&ch.id==="weapon-mastery"&&ch.entity_type==="weapon"))});if(target){const names=chosenMasteries.full.map(fullSlug=>{var _a2,_b2;return(_b2=(_a2=this.entities.getByTypeAndSlug("weapon",fullSlug))==null?void 0:_a2.name)!=null?_b2:fullSlug});const entry={label:"Mastered weapons",description:names.join(", ")};target.chosenInline=target.chosenInline?[...target.chosenInline,entry]:[entry]}}const featureResources=resolveFeatureResources(features);const resolvedCharacter={definition:character,race,classes,background,feats,...originFeatSlug?{originFeatSlug}:{},totalLevel,features,spells:[],pools:[],resources:featureResources,weaponMasteries:chosenMasteries.bare,...(()=>{var _a2;const p=(_a2=pactWeaponPick(memberSites))!=null?_a2:classPactWeaponPick(character,classes);return p?{pactWeapon:p}:{}})(),state:character.state};resolvedCharacter.pools=resolveAllPools(resolvedCharacter,this.entities,featureResources);spells.push(...collectAdditionalSpells({race,feats,classes,totalLevel,ownAbility:ownSpellcastingAbility,alreadyCollected:spells,entities:this.entities,warnings,raceChoice:id=>oc[`race:${id}`],pools:resolvedCharacter.pools}));resolvedCharacter.spells=dedupeResolvedSpells(spells);resolvedCharacter.resources=resolveResourceIndex(resolvedCharacter);resolvedCharacter.features=bindFeatureConsumers(resolvedCharacter.features,resolvedCharacter.resources,classes);const infusions=buildInfusionContext(character,resolvedCharacter,this.entities);if(infusions)resolvedCharacter.infusions=infusions;const itemFeatures=buildItemFeatures((_j=character.equipment)!=null?_j:[],this.entities,infusions,warnings);if(itemFeatures.length)resolvedCharacter.itemFeatures=itemFeatures;try{resolvedCharacter.proficiencyReplacements=collectProficiencyReplacements(resolvedCharacter)}catch(e){resolvedCharacter.proficiencyReplacements=[];warnings.push(`Duplicate proficiency check skipped: ${e instanceof Error?e.message:String(e)}`)}return{character:resolvedCharacter,warnings}}};function collectChosenWeaponMasteries(character){var _a,_b;const full=new Set;for(const cls of(_a=character.class)!=null?_a:[]){for(const lvl of Object.values((_b=cls.choices)!=null?_b:{})){const pick=lvl["weapon-mastery"];if(Array.isArray(pick)){for(const s of pick)if(typeof s==="string")full.add(s)}}}return{full:[...full],bare:[...new Set([...full].map(bareEntitySlug))]}}function collectFeatPicks(character){const picks=new Map;for(const site of featPickSites(character.class,[],()=>null)){if(!picks.has(site.slug))picks.set(site.slug,{slug:site.slug,classIndex:site.classIndex,level:site.level})}return[...picks.values()]}function collectFeatGrantedSpells(feat,read,entities,warnings){var _a;const ability=readChosenSpellAbility(read);const slugs=[];collectSpellPickSlugs(feat.choices,read,slugs);const out=[];for(const rawSlug of slugs){const slug=(_a=stripSlug(rawSlug))!=null?_a:rawSlug;const reg=entities.getByTypeAndSlug("spell",slug);if(!reg){warnings.push(`Feat spell [[${slug}]] not found in compendium.`);continue}const entity=mirrorSpellShapes(reg.data);out.push({entity,slug,classSlug:null,source:"feat",prepared:true,alwaysPrepared:true,ability})}return out}function collectItemGrantedSpells(character,ownAbility,entities,warnings){var _a;const out=[];((_a=character.equipment)!=null?_a:[]).forEach((entry,entryIndex)=>{var _a2,_b,_c,_d,_e,_f;const spellRef=(_a2=entry.overrides)==null?void 0:_a2.spell;if(!spellRef)return;const{entity:itemEntity}=resolveEntityForEntry(entry.item,entities);const scrollLevel=isItemEntity(itemEntity)?itemEntity.scroll_level:void 0;if(scrollLevel==null)return;const slug=(_b=stripSlug(spellRef))!=null?_b:spellRef;const reg=entities.getByTypeAndSlug("spell",slug);if(!reg){warnings.push(`Scroll spell [[${slug}]] not found in compendium.`);return}const entity=mirrorSpellShapes(reg.data);const ability=(_f=(_d=(_c=entry.overrides)==null?void 0:_c.spell_ability)!=null?_d:ownAbility)!=null?_f:(_e=character.overrides)==null?void 0:_e.spellcasting_ability;const itemCasting=storedSpellNumbers(itemEntity);out.push({entity,slug,classSlug:null,source:"item",prepared:true,alwaysPrepared:true,ability,entryIndex,...itemCasting?{itemCasting}:{}})});return out}function dedupeResolvedSpells(spells){const byKey=new Map;for(const s of spells){const key=s.source==="item"?`${s.slug}#${s.entryIndex}`:s.atWill?`${s.slug}#atwill`:s.slug;const existing=byKey.get(key);if(!existing){byKey.set(key,s);continue}if(existing.source==="feat"&&s.source!=="feat"){byKey.set(key,{...s,alwaysPrepared:s.alwaysPrepared||existing.alwaysPrepared,prepared:s.prepared||existing.alwaysPrepared,...existing.persisted||s.persisted?{persisted:true}:{}})}else if(s.alwaysPrepared&&!existing.alwaysPrepared){byKey.set(key,{...existing,alwaysPrepared:true,prepared:true})}}return[...byKey.values()]}function readChosenSpellAbility(read){const pick=read("spellcasting-ability");return typeof pick==="string"&&ABILITY_KEYS.includes(pick)?pick:null}function collectSpellPickSlugs(choices,read,out){for(const ch of choices!=null?choices:[]){if(ch.kind==="select-entity"&&ch.entity_type==="spell"){const sel=read(ch.id);const picks=Array.isArray(sel)?sel:typeof sel==="string"?[sel]:[];for(const p of picks)if(typeof p==="string"&&p.length>0)out.push(p)}else if(ch.kind==="select-inline"){const sel=read(ch.id);const branch=typeof sel==="string"?ch.options.find(o=>o.value===sel):void 0;if(branch==null?void 0:branch.choices)collectSpellPickSlugs(branch.choices,read,out)}}}function collectChosenGrantedFeatures(character,classes,registry,race=null,background=null,memberSites=[]){var _a,_b,_c,_d;const out=[];for(const site of memberSites){const classSlug=(_b=(_a=classes[site.classIndex])==null?void 0:_a.entity)==null?void 0:_b.slug;if(!classSlug)continue;const at={};const grants=site.choices.filter(ch=>!isTargetChoice(ch));for(const ch of grants)at[ch.id]=site.read(ch.id);walkChoiceGrants(grants,at,(granted,suppress)=>{out.push({feature:granted,source:{kind:"class",slug:classSlug,level:site.level},...suppress?{renderSuppressed:true}:{}})},registry)}classes.forEach((c,i)=>{var _a2,_b2,_c2,_d2;if(!c.entity)return;const entity=c.entity;const entry=character.class[i];if(!entry)return;for(const[lvlStr,atLevel]of Object.entries(entry.choices)){const lvl=Number(lvlStr);if(!Number.isFinite(lvl)||lvl>entry.level)continue;const features=(_b2=((_a2=entity.features_by_level)!=null?_a2:{})[lvl])!=null?_b2:[];const subFeatures=c.subclass?(_d2=((_c2=c.subclass.features_by_level)!=null?_c2:{})[lvl])!=null?_d2:[]:[];for(const feature of[...features,...subFeatures]){walkChoiceGrants(feature.choices,atLevel,(granted,suppress)=>{out.push({feature:granted,source:{kind:"class",slug:entity.slug,level:lvl},...suppress?{renderSuppressed:true}:{}})},registry)}}});const oc=(_c=character.origin_choices)!=null?_c:{};const originAt=ns=>{const at={};for(const[key,val]of Object.entries(oc)){if(key.startsWith(`${ns}:`))at[key.slice(ns.length+1)]=val}return at};if(race){const atRace=originAt("race");const emitRace=(granted,suppress)=>{out.push({feature:granted,source:{kind:"race",slug:race.slug},...suppress?{renderSuppressed:true}:{}})};walkChoiceGrants(race.choices,atRace,emitRace,registry);for(const trait of(_d=race.traits)!=null?_d:[]){walkChoiceGrants(trait.choices,atRace,emitRace,registry)}}if(background){const atBg=originAt("background");const emitBg=(granted,suppress)=>{out.push({feature:granted,source:{kind:"background",slug:background.slug},...suppress?{renderSuppressed:true}:{}})};walkChoiceGrants(background.choices,atBg,emitBg,registry);if(background.feature){walkChoiceGrants(background.feature.choices,atBg,emitBg,registry)}}return out}function choiceIdsOf(choices,out=[]){for(const ch of choices!=null?choices:[]){out.push(ch.id);if(ch.kind==="select-inline")for(const o of ch.options)choiceIdsOf(o.choices,out)}return out}function collectFeatChoiceGrants(sites,registry){var _a;const out=[];for(const site of sites){const choices=(_a=site.feat.choices)!=null?_a:[];if(!choices.length)continue;const at={};for(const id of choiceIdsOf(choices))at[id]=site.read(id);const source={kind:"feat",slug:site.feat.slug,...site.via?{via:site.via}:{}};walkChoiceGrants(choices,at,granted=>{var _a2;out.push({feature:{...granted,name:(_a2=site.feat.name)!=null?_a2:granted.name},source,renderSuppressed:true})},registry,{inlineOnly:true})}return out}function collectAdditionalFeatures(character,entities,warnings){var _a,_b,_c,_d,_e,_f,_g,_h;const out=[];for(const entry of(_a=character.additional_features)!=null?_a:[]){const slug=(_b=stripSlug(entry))!=null?_b:entry;const reg=entities.getByTypeAndSlug("optional-feature",slug);if(!reg){warnings.push(`Granted feature [[${slug}]] not found in compendium as optional-feature.`);continue}const d=reg.data;const feature={id:(_c=d.slug)!=null?_c:slug,name:(_d=d.name)!=null?_d:slug,description:d.description,...((_e=d.effects)==null?void 0:_e.length)?{effects:d.effects}:{},...d.action_cost?{action:d.action_cost}:{},...d.passive!==void 0?{passive:d.passive}:{},...d.activatable!==void 0?{activatable:d.activatable}:{},...d.duration?{duration:d.duration}:{},...d.consumes?{consumes:d.consumes}:{}};const uses=d.uses;if(uses){const maxFormula=String(uses.max);if(isValidMaxFormula(maxFormula)){feature.resources=[{id:(_f=d.slug)!=null?_f:slug,name:(_g=d.name)!=null?_g:slug,max_formula:maxFormula,reset:uses.recharge,...((_h=uses.recovery)==null?void 0:_h.length)?{recovery:uses.recovery}:{},...d.rendering_hint?{rendering_hint:d.rendering_hint}:{},...d.surface?{surface:d.surface}:{}}]}else{warnings.push(`Granted feature "${slug}" has a prose uses.max (${JSON.stringify(uses.max)}); no tracker.`)}}out.push({feature,source:{kind:"campaign",slug}})}return out}function walkChoiceGrants(choices,atLevel,emit,registry,opts={}){var _a,_b,_c,_d,_e;for(const ch of choices!=null?choices:[]){const sel=atLevel[ch.id];if(!opts.inlineOnly&&ch.kind==="select-entity"&&ch.entity_type==="optional-feature"){const slugs=Array.isArray(sel)?sel:typeof sel==="string"?[sel]:[];for(const slug of slugs){const reg=registry.getByTypeAndSlug("optional-feature",(_a=stripSlug(String(slug)))!=null?_a:String(slug));if(!reg)continue;const d=reg.data;emit({id:(_b=d.slug)!=null?_b:String(slug),name:(_c=d.name)!=null?_c:String(slug),description:d.description,effects:d.effects,...d.action_cost?{action:d.action_cost}:{}})}}if(ch.kind==="select-inline"){const picks=Array.isArray(sel)?sel.filter(v=>typeof v==="string"):typeof sel==="string"?[sel]:[];for(const value of picks){const branch=ch.options.find(o=>o.value===value);if((_d=branch==null?void 0:branch.effects)==null?void 0:_d.length){const wc=(_e=branch.choices)==null?void 0:_e.find(c=>c.kind==="select-entity"&&c.entity_type==="weapon");const picked=wc?atLevel==null?void 0:atLevel[wc.id]:void 0;const effects=branch.effects.map(e=>e.kind==="weapon-ability"&&e.weapons==="chosen"&&typeof picked==="string"?{...e,weapons:[bareEntitySlug(picked)]}:e);emit({id:`${ch.id}-${branch.value}`,name:branch.label,description:branch.description,effects},true)}if(branch==null?void 0:branch.choices)walkChoiceGrants(branch.choices,atLevel,emit,registry,opts)}}}}function resolveChosenInline(feature,atLevel){var _a;if(!atLevel)return void 0;const picks=[];for(const ch of(_a=feature.choices)!=null?_a:[]){if(ch.kind!=="select-inline")continue;const sel=atLevel[ch.id];if(typeof sel!=="string")continue;const opt=ch.options.find(o=>o.value===sel);if(!opt)continue;picks.push({label:opt.label,description:opt.description})}return picks.length?picks:void 0}function isAsiSlotFeature(feature){var _a,_b,_c,_d;return feature.id==="ability-score-improvement"&&!((_a=feature.effects)!=null?_a:[]).some(e=>!(e.kind==="ability-score-increase"&&e.abilities==="chosen"))&&!((_b=feature.resources)==null?void 0:_b.length)&&!feature.action&&!((_c=feature.sub_features)==null?void 0:_c.length)&&!((_d=feature.attacks)==null?void 0:_d.length)}function foldRepeated(list){const byId=new Map;for(const rf of list){const id=rf.feature.id;if(!id||rf.buildOnly)continue;const arr=byId.get(id);if(arr)arr.push(rf);else byId.set(id,[rf])}const out=[];for(const rf of list){if(!rf.feature.id||rf.buildOnly){out.push(rf);continue}const arr=byId.get(rf.feature.id);if(!arr||arr.length===1){out.push(rf);continue}const sorted=[...arr].sort((a,b)=>a.source.level-b.source.level);const top=sorted[sorted.length-1];if(rf!==top)continue;const effects=sorted.flatMap(c=>{var _a;return(_a=c.feature.effects)!=null?_a:[]});const seen=new Set;const resources=sorted.flatMap(c=>{var _a;return((_a=c.feature.resources)!=null?_a:[]).filter(r=>!seen.has(r.id)&&seen.add(r.id))});const chosenInline=sorted.flatMap(c=>c.chosenInline?[c.chosenInline]:[]);const cardProse=f=>{var _a,_b;return(_b=f.description)!=null?_b:((_a=f.entries)==null?void 0:_a.length)?f.entries.join("\n\n"):void 0};const foldedFrom=sorted.slice(0,-1).map(c=>{var _a;return{level:c.source.level,name:c.feature.name,...cardProse(c.feature)?{description:cardProse(c.feature)}:{},...((_a=c.feature.choices)==null?void 0:_a.length)?{choices:c.feature.choices}:{}}});out.push({...top,feature:{...top.feature,...effects.length?{effects}:{},...resources.length?{resources}:{}},...chosenInline.length?{chosenInline:chosenInline.flat()}:{},...foldedFrom.length?{foldedFrom}:{}})}return out}function collectResolvedFeatures(race,classes,background,feats,featVia=new Map){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o;const out=[];for(const c of classes){if(!c.entity)continue;const slug=c.entity.slug;const byLevel=(_a=c.entity.features_by_level)!=null?_a:{};const classFeatures=[];const subclassFeatures=[];for(const[lvlStr,feats0]of Object.entries(byLevel)){const lvl=parseInt(lvlStr,10);if(Number.isNaN(lvl)||lvl>c.level)continue;for(const feat of feats0){const chosenInline=resolveChosenInline(feat,(_b=c.choices)==null?void 0:_b[lvl]);const feature=withResolvedActionCost(feat);classFeatures.push({feature,source:{kind:"class",slug,level:lvl},...chosenInline?{chosenInline}:{},...isAsiSlotFeature(feature)?{buildOnly:true}:{}})}}if(c.subclass){const sSlug=c.subclass.slug;const sByLevel=(_c=c.subclass.features_by_level)!=null?_c:{};for(const[lvlStr,feats0]of Object.entries(sByLevel)){const lvl=parseInt(lvlStr,10);if(Number.isNaN(lvl)||lvl>c.level)continue;for(const feat of feats0){const chosenInline=resolveChosenInline(feat,(_d=c.choices)==null?void 0:_d[lvl]);const feature=withResolvedActionCost(feat);subclassFeatures.push({feature,source:{kind:"subclass",slug:sSlug,level:lvl},...chosenInline?{chosenInline}:{},...isAsiSlotFeature(feature)?{buildOnly:true}:{}})}}}const foldedClass=foldRepeated(classFeatures);const foldedSubclass=foldRepeated(subclassFeatures);out.push(...foldedClass);if((_e=c.entity.resources)==null?void 0:_e.length){out.push({feature:{name:c.entity.name,resources:c.entity.resources},source:{kind:"class",slug,level:1}})}out.push(...foldedSubclass);if((_g=(_f=c.subclass)==null?void 0:_f.resources)==null?void 0:_g.length){out.push({feature:{name:c.subclass.name,resources:c.subclass.resources},source:{kind:"subclass",slug:c.subclass.slug,level:1}})}}if(race){const traits=(_h=race.traits)!=null?_h:[];for(const feat of traits){out.push({feature:withResolvedActionCost(feat),source:{kind:"race",slug:race.slug}})}}if(background){const bgFeature=background.feature;if(bgFeature){out.push({feature:withResolvedActionCost(bgFeature),source:{kind:"background",slug:background.slug}})}}for(const feat of feats){const via=featVia.get(feat.slug);const featSource={kind:"feat",slug:feat.slug,...via?{via}:{}};const bundled=(_i=feat.features)!=null?_i:[];const entityEffects=(_j=feat.effects)!=null?_j:[];if(bundled.length>0){bundled.forEach((f,i)=>{var _a2,_b2;const feature=i===0?{...f,action:(_a2=f.action)!=null?_a2:feat.action_cost,...entityEffects.length>0?{effects:[...(_b2=f.effects)!=null?_b2:[],...entityEffects]}:{}}:f;out.push({feature,source:featSource})})}else{const name=(_k=feat.name)!=null?_k:feat.slug;const foldedDesc=[feat.description,...(_l=feat.benefits)!=null?_l:[]].filter(Boolean).join("\n\n")||void 0;const buildOnly=((_m=feat.choices)!=null?_m:[]).some(c=>c.kind==="ability-points"&&c.points>=2)&&!((_n=feat.effects)==null?void 0:_n.length)&&!((_o=feat.resources)==null?void 0:_o.length)&&bundled.length===0;out.push({feature:{name,...foldedDesc?{description:foldedDesc}:{},...feat.resources?{resources:feat.resources}:{},...feat.action_cost?{action:feat.action_cost}:{},...entityEffects.length>0?{effects:entityEffects}:{}},source:featSource,...buildOnly?{buildOnly:true}:{}})}}return out}export{stripSlug,resolveOriginFeat,PCResolver,collectChosenWeaponMasteries,collectFeatPicks,collectFeatGrantedSpells,collectItemGrantedSpells,dedupeResolvedSpells,collectChosenGrantedFeatures,collectFeatChoiceGrants,collectAdditionalFeatures,collectResolvedFeatures,collectProficiencyGrants,__matchesFilterForTest,__categoryToEntitySelectForTest,collectChosenProficiencies,collectRuleProficiencySources,collectProficiencyReplacements,computeEffectiveProficiencies,computeSuppressedProficiencies,collectChosenAbilityPoints,buildDecisionLedger};
1
+ import{equipmentCategoryKey,isCategoryGrant}from"./chunk-2EOGK6R6.js";import{withSubspeciesParent}from"./chunk-4AJYEWFQ.js";import{TOOL_CATEGORIES,backgroundToolPicks,categoryWords,classToolPicks,expandToolPool,toolCategoriesOf}from"./chunk-RQZCGXUZ.js";import{replacementChoiceId,replacementDescription,replacementOwner,replacementPick}from"./chunk-CLZRWPWT.js";import{assembleEffectFeatures,classifyProficiencyEffect,collectProficiencyEffectGrants,foldsNow,selfEffectsOf}from"./chunk-B2JSF2LL.js";import{ALL_LANGUAGES,ALL_SKILL_SLUGS,ALL_TOOLS}from"./chunk-4JEF3CET.js";import{humanizeProficiency,proficiencyLabel,toProfSlug}from"./chunk-VTQ4RWEG.js";import{buildItemFeatures}from"./chunk-DXJ5NKKB.js";import{classPactWeaponPick,featOfSite,featPickSites,isTargetChoice,memberChoices,pactWeaponPick,poolMemberSites,poolMemberSitesOf,raceFeatSites}from"./chunk-J27N3KUE.js";import{collectAdditionalSpells}from"./chunk-RR26E7LH.js";import{resolveFeatureResources,resolveResourceIndex}from"./chunk-2OVDSMPY.js";import{attributeUnclassedSpell,effectiveSpellcastingAbility,normalizeKnownSpell,resolveSpellcasting}from"./chunk-PFQPP77Q.js";import{convertibleLegacyAsi,flattenAsiOrFeat,resolveLegacyAsiFeat}from"./chunk-QVWT67WA.js";import{bindFeatureConsumers,buildInfusionContext,resolveAllPools,resolveOptionRows,storedSpellNumbers,strandedPicks,withoutStrandedSites}from"./chunk-E4E6YEN6.js";import{countColumnsFor,readTableColumn}from"./chunk-CSTAQQGX.js";import{recognizeDecision}from"./chunk-3LWOVRLA.js";import{isItemEntity,resolveEntityForEntry}from"./chunk-4IAMSRHD.js";import{FEATURE_TYPE_FOR_CATEGORY,featCategoryOf,featProgressionCategory}from"./chunk-3QQOATV3.js";import{warnOnce}from"./chunk-DZITM5AG.js";import{resolveBaseItem}from"./chunk-PZ4L2EEG.js";import{bucketOf}from"./chunk-QMEKQTUT.js";import{isValidMaxFormula}from"./chunk-EAARMPCW.js";import{bareEntitySlug,wikilinkTailSlug}from"./chunk-63YJPWTM.js";import{mirrorSpellShapes}from"./chunk-4KVVAENP.js";import{ABILITY_KEYS,ALL_SKILLS}from"./chunk-EVT7MGAC.js";import{withResolvedActionCost}from"./chunk-S5UCI27C.js";var UNKNOWN_SOURCE="Unknown";var UNKNOWN_GRANT_SOURCE=UNKNOWN_SOURCE;function grantSourceName(resolved,kind,slug){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r;switch(kind){case"class":return(_d=(_c=(_b=(_a=resolved.classes)==null?void 0:_a.find(c=>{var _a2;return((_a2=c.entity)==null?void 0:_a2.slug)===slug}))==null?void 0:_b.entity)==null?void 0:_c.name)!=null?_d:UNKNOWN_SOURCE;case"subclass":return(_h=(_g=(_f=(_e=resolved.classes)==null?void 0:_e.find(c=>{var _a2;return((_a2=c.subclass)==null?void 0:_a2.slug)===slug}))==null?void 0:_f.subclass)==null?void 0:_g.name)!=null?_h:UNKNOWN_SOURCE;case"race":return(_j=(_i=resolved.race)==null?void 0:_i.name)!=null?_j:UNKNOWN_SOURCE;case"background":return(_l=(_k=resolved.background)==null?void 0:_k.name)!=null?_l:UNKNOWN_SOURCE;case"feat":return(_o=(_n=(_m=resolved.feats)==null?void 0:_m.find(f=>f.slug===slug))==null?void 0:_n.name)!=null?_o:UNKNOWN_SOURCE;case"item":return(_r=(_q=(_p=resolved.itemFeatures)==null?void 0:_p.find(f=>f.source.slug===slug))==null?void 0:_q.feature.name)!=null?_r:UNKNOWN_SOURCE;default:return UNKNOWN_SOURCE}}function collectProficiencyGrants(resolved){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x;const classArmor=[];const classWeaponFixed=[];const classWeaponCategories=[];const classToolFixed=[];for(const c of resolved.classes){const prof=(_a=c.entity)==null?void 0:_a.proficiencies;if(!prof)continue;const source=(_c=(_b=c.entity)==null?void 0:_b.name)!=null?_c:UNKNOWN_SOURCE;for(const a of(_d=prof.armor)!=null?_d:[])classArmor.push({value:a,source});for(const w of(_f=(_e=prof.weapons)==null?void 0:_e.fixed)!=null?_f:[])classWeaponFixed.push({value:w,source});for(const w of(_h=(_g=prof.weapons)==null?void 0:_g.categories)!=null?_h:[])classWeaponCategories.push({value:w,source});for(const t of(_j=(_i=prof.tools)==null?void 0:_i.fixed)!=null?_j:[])classToolFixed.push({value:t,source});for(const t of classToolPicks(c.entity).grants)classToolFixed.push({value:t,source})}const raceSource=(_l=(_k=resolved.race)==null?void 0:_k.name)!=null?_l:UNKNOWN_SOURCE;const raceLangFixed=((_o=(_n=(_m=resolved.race)==null?void 0:_m.languages)==null?void 0:_n.fixed)!=null?_o:[]).map(l=>({value:l,source:raceSource}));const bgToolFixed=[];const bgLangFixed=[];const bg=resolved.background;if(bg){const source=(_p=bg.name)!=null?_p:UNKNOWN_SOURCE;for(const entry of(_q=bg.tool_proficiencies)!=null?_q:[]){if(entry.kind==="fixed"){for(const t of entry.items)bgToolFixed.push({value:t,source})}}for(const t of backgroundToolPicks(bg).grants)bgToolFixed.push({value:t,source});for(const entry of(_r=bg.language_proficiencies)!=null?_r:[]){if(entry.kind==="fixed"){for(const l of entry.languages)bgLangFixed.push({value:l,source})}}}const featArmor=[];const featWeapons=[];const featTools=[];const featLanguages=[];for(const f of(_s=resolved.feats)!=null?_s:[]){const featView=f;const grants=featView.proficiencies;if(!grants)continue;const source=(_t=f.name)!=null?_t:UNKNOWN_SOURCE;for(const a of(_u=grants.armor)!=null?_u:[])featArmor.push({value:a,source});for(const w of(_v=grants.weapons)!=null?_v:[])featWeapons.push({value:w,source});for(const t of(_w=grants.tools)!=null?_w:[])featTools.push({value:t,source});for(const l of(_x=grants.languages)!=null?_x:[])featLanguages.push({value:l,source})}const{features:effectFeatures,activeBuffs}=assembleEffectFeatures(resolved);const fx=collectProficiencyEffectGrants(effectFeatures,activeBuffs);const nameFor=(kind,slug)=>grantSourceName(resolved,kind,slug);const toGrants=(list,useRaw)=>list.map(g=>({value:useRaw?g.raw:g.value,source:nameFor(g.sourceKind,g.sourceSlug),...g.expertise?{expertise:true}:{}}));const effectArmor=toGrants(fx.armor,true);const effectWeapons=toGrants(fx.weapons,true);const effectTools=toGrants(fx.tools,false);const effectLanguages=toGrants(fx.languages,false);return{classArmor,classWeaponFixed,classWeaponCategories,classToolFixed,raceLangFixed,bgToolFixed,bgLangFixed,featArmor,featWeapons,featTools,featLanguages,effectArmor,effectWeapons,effectTools,effectLanguages}}function inventoryOptions(resolved,registry,entityType){var _a,_b,_c,_d;const out=[];const seen=new Set;const find=ref=>{var _a2,_b2;const withSlug=registry;if(typeof withSlug.getBySlug==="function")return resolveBaseItem(ref,withSlug);const bare=ref.replace(/^\[\[/,"").replace(/\]\]$/,"").split("|")[0].trim();return(_b2=(_a2=registry.getByTypeAndSlug(entityType,bare))!=null?_a2:registry.getByTypeAndSlug("item",bare))!=null?_b2:null};for(const entry of(_b=(_a=resolved.definition)==null?void 0:_a.equipment)!=null?_b:[]){if(typeof entry.item!=="string")continue;const e=find(entry.item);if(!e||seen.has(e.slug))continue;const value=e.slug;const base=e.entityType===entityType?e:typeof e.data.base_item==="string"?find(e.data.base_item):null;if(!base||base.entityType!==entityType)continue;seen.add(value);const name=(_d=(_c=entry.overrides)==null?void 0:_c.name)!=null?_d:e.name;out.push({value,label:name,entity:e})}return out}var warnedDegradedEquipment=new Set;var warnedAmbiguousBare=new Set;var foldedTypeMemo=new Map;function foldedType(s){let v=foldedTypeMemo.get(s);if(v===void 0){v=categoryWords(s).join(" ");foldedTypeMemo.set(s,v)}return v}function matchesFilter(e,where,ownerBare){var _a,_b,_c,_d,_e,_f;const d=e.data;if(where.feature_type&&d.feature_type!==where.feature_type)return false;if(where.category&&featCategoryOf((_a=d.category)!=null?_a:"")!==featCategoryOf(where.category))return false;if(where.list&&!((_b=d.classes)!=null?_b:[]).includes(where.list))return false;if(where.level!==void 0&&((_c=d.level)!=null?_c:0)!==where.level)return false;if(where.edition&&d.edition!==where.edition)return false;if(where.ritual&&d.ritual!==true)return false;if(where.weapon_category){const cat=((_d=d.category)!=null?_d:"").toLowerCase();if(!cat.startsWith(`${where.weapon_category}-`)&&cat!==where.weapon_category)return false}if(where.armor_category){if(((_e=d.category)!=null?_e:"").toLowerCase()!==where.armor_category)return false}if(where.item_type){const t=foldedType(typeof d.type==="string"?d.type:"");if(!t||!where.item_type.some(x=>foldedType(x)===t))return false}if(where.mundane){const r=typeof d.rarity==="string"?d.rarity.trim().toLowerCase():"";if(r&&r!=="none"&&r!=="mundane")return false}if(where.parent_class==="self"){if(!d.parent_class||wikilinkTailSlug(d.parent_class)!==ownerBare)return false}if(where.available_to==="self"){const list=(_f=d.available_to)!=null?_f:[];if(!list.some(l=>wikilinkTailSlug(l)===ownerBare))return false}return true}var __matchesFilterForTest=matchesFilter;function parseEquipmentCategory(category){const tools=toolCategoriesOf(category);if(tools)return{kind:"tool",tools};const words=categoryWords(category).filter(w=>w!=="any");const has=w=>words.includes(w);const only=allowed=>words.every(w=>allowed.includes(w));if(words.length===1&&has("shield"))return{kind:"shield"};if(has("armor")&&only(["armor","light","medium","heavy"])&&words.length<=2){const armor=["light","medium","heavy"].find(k=>has(k));return{kind:"armor",armor}}if(has("weapon")&&only(["weapon","simple","martial","melee","ranged"])){const klass=["simple","martial"].filter(k=>has(k));const range=["melee","ranged"].filter(k=>has(k));if(klass.length===1&&range.length<=1&&words.length===2+range.length){return{kind:"weapon",weapon:klass[0],range:range[0]}}}return void 0}function categoryToEntitySelect(category,id){const spec=parseEquipmentCategory(category);const pick={kind:"select-entity",id,count:1};switch(spec==null?void 0:spec.kind){case"shield":return{...pick,label:"Choose a shield",entity_type:"armor",where:{armor_category:"shield"}};case"armor":return spec.armor?{...pick,label:`Choose ${spec.armor} armor`,entity_type:"armor",where:{armor_category:spec.armor}}:{...pick,label:"Choose armor",entity_type:"armor"};case"weapon":return{...pick,label:`Choose a ${spec.weapon}${spec.range?` ${spec.range}`:""} weapon`,entity_type:"weapon",where:{weapon_category:spec.weapon}};case"tool":return{...pick,label:`Choose ${spec.tools.map(t=>TOOL_CATEGORIES[t].label).join(" or ")}`,entity_type:"item",where:{item_type:spec.tools.map(t=>TOOL_CATEGORIES[t].itemType),mundane:true}};default:warnOnce(`equipment-category:${category}`,`Archivist: starting-equipment category "${category}" is not a known item category; its pick offers no options.`);return{...pick,label:`Choose a ${category.replace(/[-_]+/g," ")}`,entity_type:"item",from:[]}}}var __categoryToEntitySelectForTest=categoryToEntitySelect;function equipmentDecisions(entries,ownerSlug){const out=[];let degraded=false;(entries!=null?entries:[]).forEach((eq,i)=>{var _a;if((eq==null?void 0:eq.kind)!=="choice")return;const options=(_a=eq.options)!=null?_a:[];out.push({kind:"select-inline",id:`equipment-${i}`,label:"Starting Equipment",count:1,options:options.map((opt,j)=>{var _a2;const label=typeof opt==="string"?opt:(_a2=opt==null?void 0:opt.label)!=null?_a2:"";const wellFormed=!!opt&&typeof opt==="object"&&Array.isArray(opt.grants);if(!wellFormed)degraded=true;const grants=wellFormed?opt.grants:[];return{value:`option-${j}`,label,choices:grants.flatMap((g,k)=>isCategoryGrant(g)?[categoryToEntitySelect(g.category,equipmentCategoryKey(i,j,k))]:[])}})})});if(degraded&&!warnedDegradedEquipment.has(ownerSlug)){warnedDegradedEquipment.add(ownerSlug);console.warn(`[archivist] Starting equipment for "${ownerSlug}" is in an outdated/unstructured format; its nested picks and seeding are skipped. Re-sync the compendium (delete _compendium.md and reload) to fix.`)}return out}function authoredProficiencyPool(choice){if(!choice.from)return void 0;return choice.domain==="tool"?expandToolPool(choice.from):choice.from}function enumerateOptions(choice,ctx,ownerBare){var _a,_b;switch(choice.kind){case"select-inline":return choice.options.map(o=>({value:o.value,label:o.label,description:o.description}));case"select-entity":{if(choice.from){let byBare;const bareIndex=()=>{var _a2,_b2,_c,_d;if(byBare)return byBare;const built=new Map;const pool=ctx.registry.search("",choice.entity_type,Number.POSITIVE_INFINITY).slice().sort((a,b)=>a.name.localeCompare(b.name)||a.slug.localeCompare(b.slug));const seed=e=>{const bare=bareEntitySlug(e.slug);if(built.has(bare)){if(!warnedAmbiguousBare.has(bare)){warnedAmbiguousBare.add(bare);console.warn(`Archivist: bare slug "${bare}" matches multiple ${choice.entity_type} entities; using "${built.get(bare).slug}"`)}return}built.set(bare,e)};for(const e of pool)if((_b2=(_a2=ctx.isEntityVisible)==null?void 0:_a2.call(ctx,e))!=null?_b2:true)seed(e);for(const e of pool)if(!((_d=(_c=ctx.isEntityVisible)==null?void 0:_c.call(ctx,e))!=null?_d:true))seed(e);byBare=built;return built};return choice.from.map(slug=>{var _a2;const e=(_a2=ctx.registry.getByTypeAndSlug(choice.entity_type,slug))!=null?_a2:bareIndex().get(slug);return e?{value:e.slug,label:e.name,entity:e}:{value:slug,label:slug,missing:true}})}const all=ctx.registry.search("",choice.entity_type,Number.POSITIVE_INFINITY);const filtered=choice.where?all.filter(e=>matchesFilter(e,choice.where,ownerBare)):all;return filtered.map(e=>({value:e.slug,label:e.name,entity:e}))}case"select-proficiency":{const pool=(_a=authoredProficiencyPool(choice))!=null?_a:choice.domain==="skill"?[...ALL_SKILL_SLUGS]:choice.domain==="language"?[...ALL_LANGUAGES]:choice.domain==="tool"?[...ALL_TOOLS]:[];return pool.map(v=>({value:v,label:humanizeProficiency(v)}))}case"ability-points":{const pool=(_b=choice.pool)!=null?_b:["str","dex","con","int","wis","cha"];return pool.map(a=>({value:a,label:a.toUpperCase()}))}}}function selectionCount(choice,selected){if(selected===void 0)return 0;if(choice.kind==="ability-points"){if(typeof selected!=="object"||Array.isArray(selected))return 0;return Object.values(selected).reduce((s,v)=>s+(typeof v==="number"?v:0),0)}if(Array.isArray(selected))return selected.length;return typeof selected==="string"&&selected.length>0?1:0}function requiredCount(choice){var _a;if(choice.kind==="ability-points")return choice.points;if(choice.kind==="select-proficiency")return choice.count;return(_a=choice.count)!=null?_a:1}function capAtCount(choice,value){const folds=choice.kind==="select-proficiency"||choice.kind==="select-entity"&&choice.entity_type==="weapon"&&choice.id!=="weapon-mastery"&&!isTargetChoice(choice);if(!folds||!Array.isArray(value))return value;const n=requiredCount(choice);return value.length>n?value.slice(0,n):value}function statusOf(choice,selected,satisfied){const n=selectionCount(choice,selected);const need=requiredCount(choice);if(satisfied)return"resolved";if(n===0)return"unresolved";return n>=need?"resolved":"partial"}var matchPool=(v,pool)=>pool.find(p=>toProfSlug(p)===toProfSlug(v));var canonicalizeSelection=(value,pool)=>{var _a;if(typeof value==="string")return(_a=matchPool(value,pool))!=null?_a:value;if(Array.isArray(value))return value.map(v=>{var _a2;return(_a2=matchPool(v,pool))!=null?_a2:v});return value};function resolveEntityRef(ctx,entityType,value){if(typeof value!=="string"||value.length===0)return void 0;const raw=value.replace(/^\[\[/,"").replace(/\]\]$/,"");const direct=ctx.registry.getByTypeAndSlug(entityType,raw);if(direct)return direct;for(const e of ctx.registry.search("",entityType,Number.POSITIVE_INFINITY)){if(e.slug===raw||bareEntitySlug(e.slug)===raw)return e}return void 0}function buildItem(inputChoice,source,level,featureName,readValue,ctx,ownerBare,effective,opts){var _a,_b,_c,_d,_e;const choice=flattenAsiOrFeat(inputChoice);const keyPrefix=(_a=opts==null?void 0:opts.keyPrefix)!=null?_a:"";const expandFeatChildren=(_b=opts==null?void 0:opts.expandFeatChildren)!=null?_b:true;const key=keyPrefix+choice.id;const raw=capAtCount(choice,readValue(key));const preExclusionOptions=choice.kind==="select-entity"&&((_c=choice.where)==null?void 0:_c.inventory)===true?effective.inventory(choice.entity_type):enumerateOptions(choice,ctx,ownerBare);let options=preExclusionOptions;const mine=new Set((Array.isArray(raw)?raw:raw===void 0?[]:[raw]).map(v=>toProfSlug(String(v))));if(choice.kind==="select-proficiency"&&choice.domain==="skill"&&choice.from_proficient){options=options.filter(o=>effective.skill.has(toProfSlug(o.value))||mine.has(toProfSlug(o.value)))}const postInclusionOptions=options;const excludes=choice.kind==="select-proficiency"&&(choice.domain==="language"||choice.domain==="tool"||choice.domain==="skill"&&choice.expertise===true);if(excludes&&choice.kind==="select-proficiency"){const known=choice.domain==="skill"?effective.skillExpertise:effective[choice.domain];options=options.filter(o=>!known.has(toProfSlug(o.value))||mine.has(toProfSlug(o.value)))}const satisfied=excludes&&postInclusionOptions.length>0&&options.length===0;const selected=choice.kind==="select-proficiency"?canonicalizeSelection(raw,options.map(o=>o.value)):raw;const item={key,source,level,featureName,choice,description:opts==null?void 0:opts.description,options,selected,status:statusOf(choice,selected,satisfied),satisfied};if(choice.kind==="select-inline"&&typeof selected==="string"){const branch=choice.options.find(o=>o.value===selected);if((_d=branch==null?void 0:branch.choices)==null?void 0:_d.length){item.children=branch.choices.map(c=>buildItem(c,source,level,featureName,readValue,ctx,ownerBare,effective,{keyPrefix,expandFeatChildren}));if(item.status==="resolved"&&item.children.some(c=>c.status!=="resolved")){item.status="partial"}}}if(choice.kind==="select-entity"&&choice.entity_type==="feat"&&expandFeatChildren&&typeof selected==="string"){const entity=resolveEntityRef(ctx,"feat",selected);const rawChoices=(_e=entity==null?void 0:entity.data)==null?void 0:_e.choices;const featChoices=Array.isArray(rawChoices)?rawChoices:[];if(featChoices.length){const childPrefix=`${keyPrefix}feat:`;item.children=featChoices.map(c=>buildItem(c,source,level,featureName,readValue,ctx,ownerBare,effective,{keyPrefix:childPrefix,expandFeatChildren:false}));if(item.status==="resolved"&&item.children.some(c=>c.status!=="resolved")){item.status="partial"}}}return item}function buildSubclassItem(choice,source,level,featureName,c,ctx,ownerBare,description){const selected=c.subclass?c.subclass.slug:void 0;return{key:"subclass",source,level,featureName,description,choice,options:enumerateOptions(choice,ctx,ownerBare),selected,status:selected?"resolved":"unresolved",satisfied:false}}function visitProficiencyChoices(resolved,visit){var _a,_b,_c,_d,_e,_f;const walk=(choices,read,owner,kind)=>{for(const ch of choices!=null?choices:[]){visit(ch,read(ch.id),owner,kind);if(ch.kind==="select-inline"){const sel=read(ch.id);const branch=typeof sel==="string"?ch.options.find(o=>o.value===sel):void 0;if(branch==null?void 0:branch.choices)walk(branch.choices,read,owner,kind)}}};const oc=(_a=resolved.definition.origin_choices)!=null?_a:{};const originRead=ns=>id=>oc[`${ns}:${id}`];const stripRef=ref=>ref.replace(/^\[\[/,"").replace(/\]\]$/,"");const featBySlug=new Map(((_b=resolved.feats)!=null?_b:[]).map(f=>[f.slug,f]));const memberSites=poolMemberSitesOf(resolved);const featSites=featPickSites(resolved.classes,memberSites,ci=>{var _a2,_b2,_c2,_d2;return(_d2=(_c2=(_b2=(_a2=resolved.classes)==null?void 0:_a2[ci])==null?void 0:_b2.entity)==null?void 0:_c2.slug)!=null?_d2:null});resolved.classes.forEach((c,i)=>{var _a2,_b2,_c2,_d2,_e2,_f2,_g,_h;if(!c.entity)return;const entity=c.entity;const readAt=lvl=>id=>{var _a3;return(_a3=c.choices[lvl])==null?void 0:_a3[id]};const className=entity.name;if(i===0&&((_b2=(_a2=entity.skill_choices)==null?void 0:_a2.from)==null?void 0:_b2.length)){visit({kind:"select-proficiency",id:"skills",count:entity.skill_choices.count,domain:"skill",from:entity.skill_choices.from},readAt(1)("skills"),className,"class")}if(i===0)walk(entity.choices,readAt(1),className,"class");if(i===0)walk(classToolPicks(entity).decisions,readAt(1),className,"class");for(const rf of resolved.features){if(rf.source.kind!=="class"&&rf.source.kind!=="subclass")continue;const belongs=rf.source.kind==="class"?rf.source.slug===entity.slug:c.subclass!=null&&rf.source.slug===c.subclass.slug;if(!belongs)continue;const featureOwner=rf.source.kind==="subclass"?(_d2=(_c2=c.subclass)==null?void 0:_c2.name)!=null?_d2:className:className;for(const copy of(_e2=rf.foldedFrom)!=null?_e2:[])walk(copy.choices,readAt(copy.level),featureOwner,"class");walk(rf.feature.choices,readAt(rf.source.level),featureOwner,"class")}for(const site of featSites){if(site.classIndex!==i)continue;const feat=(_g=featBySlug.get(stripRef(site.slug)))!=null?_g:featOfSite(site,(_f2=resolved.feats)!=null?_f2:[]);if(!feat)continue;walk(feat.choices,site.read,feat.name,"feat")}for(const site of memberSites)if(site.classIndex===i)walk(site.choices,site.read,(_h=site.member.name)!=null?_h:className,"class")});if(resolved.race){const raceName=resolved.race.name;walk(resolved.race.choices,originRead("race"),raceName,"race");for(const t of(_c=resolved.race.traits)!=null?_c:[])walk(t.choices,originRead("race"),raceName,"race")}if(resolved.background){const bgName=resolved.background.name;walk(resolved.background.choices,originRead("background"),bgName,"background");walk(backgroundToolPicks(resolved.background).decisions,originRead("background"),bgName,"background");if(resolved.background.feature){const feature=resolved.background.feature;walk(feature.choices,originRead("background"),bgName,"background")}}for(const r of(_d=resolved.proficiencyReplacements)!=null?_d:[]){walk([r.choice],originRead(r.carrier.kind),replacementOwner(r),r.carrier.kind)}if(resolved.originFeatSlug){const of=featBySlug.get(resolved.originFeatSlug);if(of)walk(of.choices,id=>oc[`background:feat:${id}`],of.name,"feat")}for(const site of raceFeatSites(resolved.race,oc)){const rf=(_f=featBySlug.get(stripRef(site.slug)))!=null?_f:((_e=resolved.feats)!=null?_e:[]).find(f=>bareEntitySlug(f.slug)===bareEntitySlug(site.slug));if(rf)walk(rf.choices,site.read,rf.name,"feat")}}var filterToPool=(vals,pool)=>pool?vals.map(v=>matchPool(v,pool)).filter(v=>!!v):vals;function collectChosenProficiencies(resolved){const out={skills:[],expertise:[],languages:[],tools:[],weapons:[],saves:[]};forEachChosenProficiency(resolved,(bucket,value)=>{const list=out[bucket];if(!list.includes(value))list.push(value)});return out}function forEachChosenProficiency(resolved,on){const isAbility=v=>ABILITY_KEYS.includes(v);visitProficiencyChoices(resolved,(choice,stored,owner,ownerKind)=>{const selected=capAtCount(choice,stored);const vals=Array.isArray(selected)?selected:typeof selected==="string"?[selected]:[];if(choice.kind==="select-entity"&&choice.entity_type==="weapon"){if(choice.id==="weapon-mastery"||isTargetChoice(choice))return;for(const v of vals){const bare=bareEntitySlug(String(v));if(bare)on("weapons",bare,owner,ownerKind)}return}if(choice.kind!=="select-proficiency")return;const valid=filterToPool(vals,authoredProficiencyPool(choice));if(choice.domain==="save"){for(const v of valid)if(isAbility(v))on("saves",v,owner,ownerKind);return}const bucket=choice.domain==="skill"?choice.expertise?"expertise":"skills":choice.domain==="language"?"languages":choice.domain==="tool"?"tools":null;if(bucket)for(const v of valid)on(bucket,v,owner,ownerKind)})}function collectRuleProficiencySources(resolved){var _a,_b,_c,_d;const out={skills:{},expertise:{},saves:{}};const add=(rec,key,source)=>{var _a2;const list=(_a2=rec[key])!=null?_a2:rec[key]=[];if(!list.includes(source))list.push(source)};const firstClass=(_b=(_a=resolved.classes)==null?void 0:_a[0])==null?void 0:_b.entity;if(firstClass)for(const ab of(_c=firstClass.saving_throws)!=null?_c:[])add(out.saves,ab,firstClass.name);const bg=resolved.background;const replaced=new Set(pickedReplacements(resolved).map(({r})=>`${r.carrier.kind}:${r.domain}:${r.value}`));if(bg)for(const sk of(_d=bg.skill_proficiencies)!=null?_d:[]){if(!replaced.has(`background:skill:${toProfSlug(sk)}`))add(out.skills,sk,bg.name)}forEachChosenProficiency(resolved,(bucket,value,owner)=>{if(bucket==="skills"||bucket==="expertise"||bucket==="saves")add(out[bucket],value,owner)});const{features,activeBuffs}=assembleEffectFeatures(resolved);for(const rf of features){if(!foldsNow(rf,activeBuffs))continue;for(const eff of selfEffectsOf(rf.feature)){const c=classifyProficiencyEffect(eff);if(!c||c.bucket!=="skills"&&c.bucket!=="saves")continue;if(c.bucket==="skills"&&!c.expertise&&replaced.has(`${rf.source.kind}:skill:${toProfSlug(c.value)}`))continue;const named=grantSourceName(resolved,rf.source.kind,rf.source.slug);const source=named===UNKNOWN_GRANT_SOURCE?rf.feature.name:named;if(c.bucket==="saves")add(out.saves,c.value,source);else add(c.expertise?out.expertise:out.skills,c.value,source)}}return out}function pickedReplacements(resolved){var _a,_b;const oc=(_a=resolved.definition)==null?void 0:_a.origin_choices;const out=[];for(const r of(_b=resolved.proficiencyReplacements)!=null?_b:[]){const pick=replacementPick(r,oc);if(pick)out.push({r,pick})}return out}var STEP_RANK={race:0,class:1,background:2,other:3};var stepOf=k=>k==="race"?"race":k==="background"?"background":k==="class"||k==="subclass"?"class":"other";function collectProficiencyReplacements(resolved){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l;const base={...resolved,proficiencyReplacements:void 0};const bg=base.background;const race=base.race;if(!bg&&!race)return[];const grants={skill:new Map,tool:new Map};const note=(domain,raw,g)=>{var _a2;if(typeof raw!=="string"||!raw.trim())return;const v=toProfSlug(raw);const list=(_a2=grants[domain].get(v))!=null?_a2:[];if(!list.some(x=>x.step===g.step&&x.name===g.name&&x.fixed===g.fixed))list.push(g);grants[domain].set(v,list)};const strings=v=>Array.isArray(v)?v:[];const{features,activeBuffs}=assembleEffectFeatures(base);const fx=collectProficiencyEffectGrants(features,activeBuffs);const effectName=g=>grantSourceName(base,g.sourceKind,g.sourceSlug);for(const g of fx.skills)if(!g.expertise)note("skill",g.value,{name:effectName(g),step:stepOf(g.sourceKind),fixed:true});for(const g of fx.tools)note("tool",g.value,{name:effectName(g),step:stepOf(g.sourceKind),fixed:true});if(bg){for(const sk of strings(bg.skill_proficiencies))note("skill",sk,{name:bg.name,step:"background",fixed:true});for(const e of strings(bg.tool_proficiencies)){if(e&&typeof e==="object"&&e.kind==="fixed"){for(const t of strings(e.items))note("tool",t,{name:bg.name,step:"background",fixed:true})}}for(const t of backgroundToolPicks(bg).grants)note("tool",t,{name:bg.name,step:"background",fixed:true})}const carried=[...grants.skill.values(),...grants.tool.values()].some(list=>list.some(g=>g.fixed&&(g.step==="race"||g.step==="background")));if(!carried)return[];for(const c of(_a=base.classes)!=null?_a:[]){const e=c.entity;if(!e)continue;const tools=(_b=e.proficiencies)==null?void 0:_b.tools;for(const t of[...strings(tools==null?void 0:tools.fixed),...classToolPicks(e).grants])note("tool",t,{name:e.name,step:"class",fixed:true})}for(const f of(_c=base.feats)!=null?_c:[]){const tools=(_d=f.proficiencies)==null?void 0:_d.tools;for(const t of strings(tools))note("tool",t,{name:f.name,step:"other",fixed:true})}forEachChosenProficiency(base,(bucket,value,owner,kind)=>{if(bucket==="skills")note("skill",value,{name:owner,step:stepOf(kind),fixed:false});else if(bucket==="tools")note("tool",value,{name:owner,step:stepOf(kind),fixed:false})});const held={skill:new Set([...(_g=(_f=(_e=base.definition)==null?void 0:_e.skills)==null?void 0:_f.proficient)!=null?_g:[],...(_j=(_i=(_h=base.definition)==null?void 0:_h.skills)==null?void 0:_i.expertise)!=null?_j:[],...fx.skills.map(g=>g.value),...grants.skill.keys(),...collectChosenProficiencies(base).expertise].map(toProfSlug)),tool:new Set};let toolsHeld=false;const heldTools=()=>{if(!toolsHeld){toolsHeld=true;for(const e of computeEffectiveProficiencies(base).tools)held.tool.add(toProfSlug(e.value))}return held.tool};const candidates=[];const skillOrder=v=>{const i=ALL_SKILL_SLUGS.indexOf(v);return i<0?999:i};for(const domain of["skill","tool"]){const entries=[...grants[domain].entries()];if(domain==="skill")entries.sort(([a],[b])=>skillOrder(a)-skillOrder(b));for(const[value,list]of entries){const sources=[];for(const g of[...list].sort((a,b)=>STEP_RANK[a.step]-STEP_RANK[b.step])){if(!sources.some(x=>x.step===g.step&&x.name===g.name))sources.push(g)}const names=keep=>[...new Set(sources.filter(keep).map(g=>g.name))];const label=domain==="skill"?(_k=ALL_SKILLS.find(d=>toProfSlug(d)===value))!=null?_k:humanizeProficiency(value):humanizeProficiency(value);const id=replacementChoiceId(domain,value);const bgCarries=!!bg&&list.some(g=>g.step==="background"&&g.fixed)&&names(g=>g.step!=="background").length>0;if(bg&&bgCarries){candidates.push({domain,value,label,id,carrier:{kind:"background",slug:bg.slug,name:bg.name},others:names(g=>g.step!=="background")})}const raceOthers=names(g=>g.step!=="race"&&!(bgCarries&&g.step==="background"));if(race&&list.some(g=>g.step==="race"&&g.fixed)&&raceOthers.length>0){candidates.push({domain,value,label,id,carrier:{kind:"race",slug:race.slug,name:race.name},others:raceOthers})}}}const oc=(_l=base.definition)==null?void 0:_l.origin_choices;const picks=candidates.map(c=>replacementPick({carrier:c.carrier,choice:{id:c.id}},oc));return candidates.map((c,i)=>{const vocab=c.domain==="skill"?ALL_SKILL_SLUGS:ALL_TOOLS;const taken=new Set(picks.filter((p,j)=>j!==i&&p&&candidates[j].domain===c.domain));const own=picks[i];const have=c.domain==="skill"?held.skill:heldTools();const from=vocab.filter(v=>v===own||!have.has(v)&&!taken.has(v));const{id,...rest}=c;return{...rest,choice:{kind:"select-proficiency",id,label:`Already proficient in ${c.label}: pick a replacement`,count:1,domain:c.domain,from}}})}function proficiencyEntryFor(raw,vocab,origin,sources,expertise){const hit=matchPool(raw,vocab);const value=hit?toProfSlug(hit):raw;const label=hit?humanizeProficiency(value):origin==="custom"?raw:proficiencyLabel(raw);return{value,label,sources,origin,...expertise?{expertise:true}:{}}}function computeEffectiveProficiencies(resolved){const c=composeLanguageToolProficiencies(resolved);return{languages:c.languages.kept,tools:c.tools.kept}}function computeSuppressedProficiencies(resolved){const c=composeLanguageToolProficiencies(resolved);return{languages:c.languages.suppressed,tools:c.tools.suppressed}}function composeLanguageToolProficiencies(resolved){const grants=collectProficiencyGrants(resolved);const chosen=collectChosenProficiencies(resolved);const build=domain=>{var _a,_b,_c,_d,_e,_f,_g,_h;const vocab=domain==="languages"?ALL_LANGUAGES:ALL_TOOLS;const ov=(_b=(_a=resolved.definition)==null?void 0:_a.overrides)==null?void 0:_b[domain];const adds=(_c=ov==null?void 0:ov.add)!=null?_c:[];const removes=(_d=ov==null?void 0:ov.remove)!=null?_d:[];const byValue=new Map;const push=(raw,origin,source,expertise)=>{const probe=proficiencyEntryFor(raw,vocab,origin,source?[source]:[],expertise);const existing=byValue.get(probe.value);if(!existing){byValue.set(probe.value,probe);return}if(source&&!existing.sources.includes(source))existing.sources.push(source);if(expertise)existing.expertise=true;const rank={grant:0,pick:1,manual:2,custom:3};if(rank[origin]<rank[existing.origin])existing.origin=origin};const grantBuckets=domain==="languages"?[grants.raceLangFixed,grants.bgLangFixed,grants.featLanguages,grants.effectLanguages]:[grants.classToolFixed,grants.bgToolFixed,grants.featTools,grants.effectTools];const replacedTools=domain==="tools"?pickedReplacements(resolved).filter(({r})=>r.domain==="tool"):[];for(const b of grantBuckets)for(const g of b){if(replacedTools.some(({r})=>r.carrier.name===g.source&&r.value===toProfSlug(g.value)))continue;push(g.value,"grant",g.source,g.expertise)}for(const{r,pick}of replacedTools)push(pick,"pick",replacementOwner(r));for(const v of domain==="languages"?chosen.languages:chosen.tools)push(v,"pick");for(const v of adds)push(v,matchPool(v,vocab)?"manual":"custom");const triSuppressed=new Set;if(domain==="tools"){const tri=(_h=(_g=(_f=(_e=resolved.definition)==null?void 0:_e.overrides)==null?void 0:_f.tools)==null?void 0:_g.proficiency)!=null?_h:{};for(const[tool,state]of Object.entries(tri)){const key=toProfSlug(tool);if(state==="none"){triSuppressed.add(key);continue}let entry=[...byValue.values()].find(e=>toProfSlug(e.value)===key);if(!entry){push(tool,matchPool(tool,vocab)?"manual":"custom");entry=[...byValue.values()].find(e=>toProfSlug(e.value)===key)}if(!entry)continue;if(state==="expertise")entry.expertise=true;else delete entry.expertise}}const suppressed=new Set([...removes.map(r=>toProfSlug(r)),...triSuppressed]);const byLabel=(a,b)=>a.label<b.label?-1:a.label>b.label?1:0;const kept=[...byValue.values()].filter(e=>!suppressed.has(toProfSlug(e.value))).sort(byLabel);return{kept,suppressed:[...byValue.values()].filter(e=>suppressed.has(toProfSlug(e.value))).sort(byLabel)}};return{languages:build("languages"),tools:build("tools")}}function collectChosenAbilityPoints(resolved){var _a,_b,_c;const oc=(_a=resolved.definition.origin_choices)!=null?_a:{};const out={race:{},background:{}};const fold=(ns,choices)=>{var _a2;for(const ch of choices!=null?choices:[]){if(ch.kind!=="ability-points")continue;const raw=oc[`${ns}:${ch.id}`];if(!raw||typeof raw!=="object"||Array.isArray(raw))continue;let left=ch.points;for(const ab of ABILITY_KEYS){if(ch.pool&&!ch.pool.includes(ab))continue;const v=raw[ab];if(typeof v!=="number"||v<=0||left<=0)continue;const take=Math.min(v,ch.max_per,left);out[ns][ab]=((_a2=out[ns][ab])!=null?_a2:0)+take;left-=take}}};const race=resolved.race;if(race){fold("race",race.choices);for(const t of(_b=race.traits)!=null?_b:[])fold("race",t.choices)}const bg=resolved.background;if(bg){fold("background",bg.choices);fold("background",(_c=bg.feature)==null?void 0:_c.choices)}return out}function buildDecisionLedger(resolved,ctx){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n;const eff=computeEffectiveProficiencies(resolved);const chosen=collectChosenProficiencies(resolved);const{features,activeBuffs}=assembleEffectFeatures(resolved);const effectGrants=collectProficiencyEffectGrants(features,activeBuffs);const effective={language:new Set(eff.languages.map(e=>toProfSlug(e.value))),tool:new Set(eff.tools.map(e=>toProfSlug(e.value))),skill:new Set([...(_c=(_b=(_a=resolved.definition)==null?void 0:_a.skills)==null?void 0:_b.proficient)!=null?_c:[],...(_e=(_d=resolved.background)==null?void 0:_d.skill_proficiencies)!=null?_e:[],...chosen.skills,...effectGrants.skills.map(g=>g.value)].map(toProfSlug)),skillExpertise:new Set([...(_h=(_g=(_f=resolved.definition)==null?void 0:_f.skills)==null?void 0:_g.expertise)!=null?_h:[],...chosen.expertise,...effectGrants.skills.filter(g=>g.expertise).map(g=>g.value)].map(toProfSlug)),inventory:entityType=>inventoryOptions(resolved,ctx.registry,entityType)};const classes=[];resolved.classes.forEach((c,classIndex)=>{var _a2,_b2,_c2,_d2,_e2,_f2,_g2,_h2,_i2,_j2,_k2,_l2,_m2,_n2,_o;if(!c.entity)return;const entity=c.entity;const ownerBare=bareEntitySlug(entity.slug);const byLevel=new Map;const push=(lvl,item)=>{var _a3;const arr=(_a3=byLevel.get(lvl))!=null?_a3:[];arr.push(item);byLevel.set(lvl,arr)};const readAt=lvl=>id=>{var _a3;return(_a3=c.choices[lvl])==null?void 0:_a3[id]};let legacyAsiFeat;const legacyAsiReader=(choice,lvl)=>{const alloc=convertibleLegacyAsi(c.choices[lvl]);if(!alloc)return null;const flat=flattenAsiOrFeat(choice);if(flat.kind!=="select-entity"||flat.entity_type!=="feat"||flat.from||flat.where)return null;if(legacyAsiFeat===void 0)legacyAsiFeat=resolveLegacyAsiFeat(ctx.registry,entity);const asi=legacyAsiFeat;if(!asi)return null;const raw=readAt(lvl);const childKey=`feat:${asi.childId}`;return id=>id==="feat"?asi.slug:id===childKey?alloc:raw(id)};const featProgressions=[...(_a2=entity.feat_progression)!=null?_a2:[],...(_c2=(_b2=c.subclass)==null?void 0:_b2.feat_progression)!=null?_c2:[]];const suppressedFeatureTypes=new Set;for(const decl of[...(_d2=entity.selection_pools)!=null?_d2:[],...(_f2=(_e2=c.subclass)==null?void 0:_e2.selection_pools)!=null?_f2:[]]){const rp=resolved.pools.find(p=>p.classIndex===classIndex&&p.id===decl.id);if(rp&&rp.count>=1)suppressedFeatureTypes.add(decl.source.where.feature_type)}for(const entry of featProgressions){const category=featProgressionCategory(entry.category);const ft=category?FEATURE_TYPE_FOR_CATEGORY[category]:void 0;if(ft)suppressedFeatureTypes.add(ft)}if(classIndex===0&&((_h2=(_g2=entity.skill_choices)==null?void 0:_g2.from)==null?void 0:_h2.length)){const skillChoice={kind:"select-proficiency",id:"skills",label:"Skill Proficiencies",count:entity.skill_choices.count,domain:"skill",from:entity.skill_choices.from};push(1,buildItem(skillChoice,{kind:"class",slug:entity.slug,level:1},1,"Proficiencies",readAt(1),ctx,ownerBare,effective))}if(classIndex===0){for(const ch of[...(_i2=entity.choices)!=null?_i2:[],...classToolPicks(entity).decisions]){push(1,buildItem(ch,{kind:"class",slug:entity.slug,level:1},1,"Proficiencies",readAt(1),ctx,ownerBare,effective))}}if(classIndex===0){for(const ch of equipmentDecisions(entity.starting_equipment,entity.slug)){push(1,buildItem(ch,{kind:"class",slug:entity.slug,level:1},1,"Starting Equipment",readAt(1),ctx,ownerBare,effective))}}let sawAuthoredSubclass=false;const staged=[];const authoredRank=(kind,level,feature)=>{var _a3,_b3,_c3;const at=(_c3=(_b3=(_a3=kind==="class"?entity:c.subclass)==null?void 0:_a3.features_by_level)==null?void 0:_b3[level])!=null?_c3:[];const index=at.findIndex(f=>feature.id?f.id===feature.id:f.name===feature.name);return(kind==="class"?0:1)*1e6+(index<0?999999:index)};for(const rf of resolved.features){const src=rf.source;if(src.kind!=="class"&&src.kind!=="subclass")continue;const belongs=src.kind==="class"?src.slug===entity.slug:c.subclass!=null&&src.slug===c.subclass.slug;if(!belongs)continue;const lvl=src.level;const stage=(atLvl,item)=>{staged.push({level:atLvl,item,rank:authoredRank(src.kind,atLvl,rf.feature),seq:staged.length})};const emitChoices=(list,atLvl,name,description)=>{var _a3,_b3;for(const ch of list){if(ch.kind==="select-entity"&&ch.entity_type==="subclass"){sawAuthoredSubclass=true;stage(atLvl,buildSubclassItem(ch,src,atLvl,name,c,ctx,ownerBare,description));continue}let emitted=ch;if(ch.kind==="select-entity"){const columns=countColumnsFor(ch.id);const fromTable=columns?readTableColumn(entity.table,c.level,columns):null;if(fromTable!=null)emitted={...ch,count:Math.max((_a3=ch.count)!=null?_a3:1,fromTable)}}stage(atLvl,buildItem(emitted,src,atLvl,name,(_b3=legacyAsiReader(emitted,atLvl))!=null?_b3:readAt(atLvl),ctx,ownerBare,effective,{description}))}};const informationalItem=(atLvl,name,description)=>{var _a3,_b3;return{key:(_a3=rf.feature.id)!=null?_a3:name,source:src,level:atLvl,featureName:name,description,choice:{kind:"select-inline",id:(_b3=rf.feature.id)!=null?_b3:name,options:[{value:"_",label:"_"}]},options:[],selected:void 0,status:"informational",satisfied:false}};const emitCopy=copy=>{let list=copy.choices;if(!(list==null?void 0:list.length)){const recognized=recognizeDecision({id:rf.feature.id,name:copy.name,description:copy.description});if(recognized==="informational"){stage(copy.level,informationalItem(copy.level,copy.name,copy.prose));return}list=recognized!=null?recognized:void 0;if(list==null?void 0:list.length){list=list.filter(ch=>{var _a3;if(ch.kind!=="select-entity")return true;const ft=(_a3=ch.where)==null?void 0:_a3.feature_type;return!(ft!==void 0&&suppressedFeatureTypes.has(ft))})}}if(!(list==null?void 0:list.length)){if(copy.prose)stage(copy.level,informationalItem(copy.level,copy.name,copy.prose));return}emitChoices(list,copy.level,copy.name,copy.description)};for(const copy of(_j2=rf.foldedFrom)!=null?_j2:[])emitCopy({...copy,prose:copy.description});emitCopy({level:lvl,name:rf.feature.name,description:rf.feature.description,prose:rf.feature.description||(((_k2=rf.feature.entries)==null?void 0:_k2.length)?rf.feature.entries.join("\n\n"):void 0),choices:rf.feature.choices})}staged.sort((a,b)=>a.rank-b.rank||a.seq-b.seq);for(const s of staged)push(s.level,s.item);const subclassLevel=(_l2=entity.subclass_level)!=null?_l2:null;if(subclassLevel!=null&&subclassLevel<=c.level&&!sawAuthoredSubclass){const featureName=(_m2=entity.subclass_feature_name)!=null?_m2:"Subclass";const synthChoice={kind:"select-entity",id:"subclass",label:featureName,count:1,entity_type:"subclass",where:{parent_class:"self"}};push(subclassLevel,buildSubclassItem(synthChoice,{kind:"class",slug:entity.slug,level:subclassLevel},subclassLevel,featureName,c,ctx,ownerBare))}for(const pool of resolved.pools){if(pool.classIndex!==classIndex||pool.count<1)continue;const stranded=strandedPicks(pool);const strandedSlugs=new Set(stranded.map(e=>e.slug));const synth={kind:"select-entity",id:pool.id,label:pool.label,count:pool.count,entity_type:"optional-feature",from:[...pool.available.map(e=>e.slug),...stranded.map(e=>e.slug)]};const item=buildItem(synth,{kind:"class",slug:entity.slug,level:pool.anchorLevel},pool.anchorLevel,pool.label,()=>pool.selected.map(e=>e.key),ctx,ownerBare,effective);item.pool={id:pool.id,anchorLevel:pool.anchorLevel};const repeatables=pool.available.filter(e=>e.entity.repeatable===true);if(repeatables.length>0){item.repeatable=repeatables.map(e=>{var _a3,_b3;return{noteSlug:e.slug,itemChoice:(_a3=e.entity.item_choice)!=null?_a3:"learn",rows:resolveOptionRows(e.entity,ctx.registry,{edition:resolved.definition.edition,isEntityVisible:(_b3=ctx.isEntityVisible)==null?void 0:_b3.bind(ctx)})}})}for(const o of item.options)if(strandedSlugs.has(o.value))o.stranded=true;const memberChildren=[];for(const entry of pool.selected){for(const ch of memberChoices(entry.entity)){const child=buildItem(ch,{kind:"class",slug:entity.slug,level:pool.anchorLevel},pool.anchorLevel,entry.entity.name,readAt(pool.anchorLevel),ctx,ownerBare,effective,{keyPrefix:`${pool.id}:${entry.key}:`});child.parentLabel=entry.entity.name;memberChildren.push(child)}}if(memberChildren.length){item.children=memberChildren;if(item.status==="resolved"&&memberChildren.some(c2=>c2.status!=="resolved"))item.status="partial"}push(pool.anchorLevel,item)}for(const entry of featProgressions){const category=featProgressionCategory(entry.category);if(!category){warnOnce(`feat-progression-category:${entity.slug}:${entry.name}`,`Archivist: feat_progression "${entry.name}" on "${entity.slug}" carries no category this engine maps (${((_n2=entry.category)!=null?_n2:[]).join(", ")}); no decision is offered`);continue}const progression=entry.progression;if(Array.isArray(progression))continue;for(const key of Object.keys(progression)){const lvl=Number.parseInt(key,10);if(!Number.isInteger(lvl)||String(lvl)!==key)continue;if(lvl>c.level)continue;if(((_o=byLevel.get(lvl))!=null?_o:[]).some(i=>i.key==="feat")){warnOnce(`feat-progression-collision:${entity.slug}:${lvl}`,`Archivist: "${entry.name}" on "${entity.slug}" would add a second feat pick at level ${lvl}, where one already exists; skipping`);continue}const progressionChoice={kind:"select-entity",id:"feat",label:entry.name,count:1,entity_type:"feat",where:{category}};push(lvl,buildItem(progressionChoice,{kind:"class",slug:entity.slug,level:lvl},lvl,entry.name,readAt(lvl),ctx,ownerBare,effective))}}const levels=[...byLevel.entries()].sort(([a],[b])=>a-b).map(([level,items])=>({level,items}));classes.push({classIndex,levels})});const origin=[];const oc=(_i=resolved.definition.origin_choices)!=null?_i:{};const originRead=ns=>id=>oc[`${ns}:${id}`];const pushOrigin=(choices,ns,source,featureName,ownerBare,description)=>{for(const ch of choices!=null?choices:[]){origin.push(buildItem(ch,source,0,featureName,originRead(ns),ctx,ownerBare,effective,{description}))}};const pushReplacements=(kind,bare)=>{var _a2;for(const r of(_a2=resolved.proficiencyReplacements)!=null?_a2:[]){if(r.carrier.kind!==kind)continue;origin.push(buildItem(r.choice,{kind,slug:r.carrier.slug},0,r.carrier.name,originRead(kind),ctx,bare,effective,{description:replacementDescription(r)}))}};if(resolved.race){const bare=bareEntitySlug(resolved.race.slug);pushReplacements("race",bare);pushOrigin(resolved.race.choices,"race",{kind:"race",slug:resolved.race.slug},(_j=resolved.race.name)!=null?_j:"Race",bare);for(const t of(_k=resolved.race.traits)!=null?_k:[]){pushOrigin(t.choices,"race",{kind:"race",slug:resolved.race.slug},t.name,bare,t.description)}}if(resolved.background){const bare=bareEntitySlug(resolved.background.slug);pushReplacements("background",bare);pushOrigin([...(_l=resolved.background.choices)!=null?_l:[],...backgroundToolPicks(resolved.background).decisions],"background",{kind:"background",slug:resolved.background.slug},(_m=resolved.background.name)!=null?_m:"Background",bare);if(resolved.background.feature){pushOrigin(resolved.background.feature.choices,"background",{kind:"background",slug:resolved.background.slug},resolved.background.feature.name,bare,resolved.background.feature.description)}if(resolved.background.origin_feat){const originFeat=resolveOriginFeat(ctx.registry,resolved.background.origin_feat,resolved.background.slug);if(originFeat){const featSource={kind:"feat",slug:originFeat.feat.slug};const featBare=bareEntitySlug(originFeat.feat.slug);for(const ch of(_n=originFeat.feat.choices)!=null?_n:[]){origin.push(buildItem(ch,featSource,0,originFeat.display,originRead("background"),ctx,featBare,effective,{keyPrefix:"feat:"}))}}}for(const ch of equipmentDecisions(resolved.background.equipment,resolved.background.slug)){origin.push(buildItem(ch,{kind:"background",slug:resolved.background.slug},0,"Starting Equipment",originRead("background"),ctx,bare,effective))}}return{classes,origin}}var SLUG_RE=/^\[\[(.+?)\]\]$/;function stripSlug(ref){if(!ref)return null;const m=ref.match(SLUG_RE);return m?m[1]:ref}function resolveOriginFeat(entities,originFeatRef,ownerSlug){var _a,_b,_c;if(!originFeatRef)return null;const slug=wikilinkTailSlug(originFeatRef);const inner=originFeatRef.replace(/^\[\[/,"").replace(/\]\]$/,"").trim();const rawTail=(_b=(_a=inner.split("/").pop())==null?void 0:_a.trim())!=null?_b:"";const base=rawTail.replace(/\s*\([^()]*\)\s*$/,"").trim();const baseSlug=base&&base!==rawTail?wikilinkTailSlug(`[[${base}]]`):null;const baseInner=baseSlug?inner.slice(0,inner.length-rawTail.length)+base:null;const prefix=(ownerSlug==null?void 0:ownerSlug.includes("_"))?ownerSlug.slice(0,ownerSlug.indexOf("_")):null;const feats=bucketOf(entities,"feat");const byPath=p=>feats.find(f=>f.filePath===`${p}.md`||f.filePath.endsWith(`/${p}.md`));const sameCompendiumTail=s=>prefix?feats.find(f=>f.slug.startsWith(`${prefix}_feat_`)&&f.slug.endsWith(`_${s}`)):void 0;const anyTail=s=>feats.find(f=>f.slug.endsWith(`_${s}`));const tiers=[()=>{var _a2;return(_a2=feats.find(f=>f.slug===inner))!=null?_a2:feats.find(f=>f.slug===slug)},()=>byPath(inner),()=>baseInner?byPath(baseInner):void 0,()=>sameCompendiumTail(slug),()=>baseSlug?sameCompendiumTail(baseSlug):void 0,()=>anyTail(slug),()=>baseSlug?anyTail(baseSlug):void 0];let reg;let hitTier=0;for(let i=0;i<tiers.length&&!reg;i++){reg=tiers[i]();hitTier=i+1}if(!reg)return null;const variantName=baseSlug&&(hitTier===3||hitTier===5||hitTier===7)?rawTail:void 0;const data=reg.data;const feat=data.slug==null?{...data,slug:reg.slug}:data;return{feat,display:(_c=variantName!=null?variantName:feat.name)!=null?_c:slug}}var PCResolver=class{constructor(entities){this.entities=entities}get registry(){return this.entities}resolve(character){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j;const warnings=[];const lookup=(rawRef,type)=>{const slug=stripSlug(rawRef);if(!slug)return null;const reg=this.entities.getByTypeAndSlug(type,slug);if(!reg){warnings.push(`Slug [[${slug}]] not found in compendium as ${type}.`);return null}const data=reg.data;return data.slug==null?{...data,slug:reg.slug}:data};const race=withSubspeciesParent(lookup(character.race,"race"),this.entities);const background=lookup(character.background,"background");const classes=character.class.map(c=>({entity:lookup(c.name,"class"),level:c.level,subclass:lookup(c.subclass,"subclass"),choices:c.choices}));const memberSites=withoutStrandedSites(poolMemberSites(classes,this.entities),classes,this.entities,character.edition);const classSlugOf=i=>{var _a2,_b2,_c2,_d2,_e2;return(_e2=(_b2=(_a2=classes[i])==null?void 0:_a2.entity)==null?void 0:_b2.slug)!=null?_e2:stripSlug((_d2=(_c2=character.class[i])==null?void 0:_c2.name)!=null?_d2:null)};const featSites=featPickSites(character.class,memberSites,classSlugOf);const feats=[];const featVia=new Map;for(const site of featSites){const f=lookup(`[[${site.slug}]]`,"feat");if(!f)continue;if(!feats.some(x=>x.slug===f.slug))feats.push(f);if(site.via&&!featVia.has(f.slug))featVia.set(f.slug,site.via)}const originFeat=(background==null?void 0:background.origin_feat)?resolveOriginFeat(this.entities,background.origin_feat,background.slug):null;const originFeatSlug=originFeat==null?void 0:originFeat.feat.slug;if(originFeat&&!feats.some(f=>f.slug===originFeat.feat.slug)){feats.push(originFeat.feat)}if(originFeat&&background&&!featVia.has(originFeat.feat.slug)){featVia.set(originFeat.feat.slug,{kind:"background",slug:background.slug})}const raceFeats=[];for(const site of raceFeatSites(race,character.origin_choices)){const f=lookup(`[[${site.slug}]]`,"feat");if(!f)continue;raceFeats.push({feat:f,read:site.read});if(!feats.some(x=>x.slug===f.slug))feats.push(f);if(!featVia.has(f.slug))featVia.set(f.slug,site.via)}const totalLevel=classes.reduce((sum,c)=>sum+c.level,0);const features=collectResolvedFeatures(race,classes,background,feats,featVia);const extraFeatures=collectChosenGrantedFeatures(character,classes,this.entities,race,background,memberSites);features.push(...extraFeatures);const originChoices=(_a=character.origin_choices)!=null?_a:{};const featChoiceSites=[];for(const site of featSites){const f=lookup(`[[${site.slug}]]`,"feat");if(f)featChoiceSites.push({feat:f,via:site.via,read:site.read})}if(originFeat&&background){featChoiceSites.push({feat:originFeat.feat,via:{kind:"background",slug:background.slug},read:id=>originChoices[`background:feat:${id}`]})}for(const rf of raceFeats)featChoiceSites.push({feat:rf.feat,via:race?{kind:"race",slug:race.slug}:null,read:rf.read});features.push(...collectFeatChoiceGrants(featChoiceSites,this.entities));features.push(...collectAdditionalFeatures(character,this.entities,warnings));const casters=[];classes.forEach((c,i)=>{const profile=c.entity?resolveSpellcasting(c):null;const classSlug=profile?stripSlug(character.class[i].name):null;if(profile&&classSlug!=null)casters.push({classSlug,spellList:profile.spellList})});const spells=[];for(const raw of(_b=character.spells.known)!=null?_b:[]){const n=normalizeKnownSpell(raw);const reg=this.entities.getByTypeAndSlug("spell",n.slug);if(!reg){warnings.push(`Spell [[${n.slug}]] not found in compendium.`);continue}const entity=mirrorSpellShapes(reg.data);const isCantrip=((_c=entity.level)!=null?_c:0)===0;const classSlug=(_d=n.classSlug)!=null?_d:attributeUnclassedSpell(entity.classes,casters,this.entities);const prep=isCantrip||n.alwaysPrepared?true:(_e=n.preparedFlag)!=null?_e:false;spells.push({entity,slug:n.slug,classSlug,source:n.source,prepared:prep,alwaysPrepared:n.alwaysPrepared,persisted:true})}const oc=(_f=character.origin_choices)!=null?_f:{};if(originFeat){const read=childId=>oc[`background:feat:${childId}`];spells.push(...collectFeatGrantedSpells(originFeat.feat,read,this.entities,warnings))}for(const rf of raceFeats)spells.push(...collectFeatGrantedSpells(rf.feat,rf.read,this.entities,warnings));for(const site of featSites){const reg=this.entities.getByTypeAndSlug("feat",site.slug);if(!reg)continue;const feat=reg.data;spells.push(...collectFeatGrantedSpells(feat,site.read,this.entities,warnings))}for(const site of memberSites){const classSlug=stripSlug((_h=(_g=character.class[site.classIndex])==null?void 0:_g.name)!=null?_h:null);for(const ch of site.choices){if(ch.kind!=="select-entity"||ch.entity_type!=="spell"||isTargetChoice(ch))continue;const v=site.read(ch.id);for(const ref of Array.isArray(v)?v:typeof v==="string"?[v]:[]){const slug=typeof ref==="string"?stripSlug(ref):null;if(!slug)continue;const reg=this.entities.getByTypeAndSlug("spell",slug);if(!reg){warnings.push(`Spell [[${slug}]] not found in compendium.`);continue}const entity=mirrorSpellShapes(reg.data);spells.push({entity,slug,classSlug,source:"class",prepared:true,alwaysPrepared:true})}}}const ownSpellcastingAbility=(_i=classes.map(c=>{if(!c.entity)return null;const p=resolveSpellcasting(c);return p?effectiveSpellcastingAbility(c.entity.slug,p.ability,character.overrides):null}).find(a=>a!=null))!=null?_i:null;spells.push(...collectItemGrantedSpells(character,ownSpellcastingAbility,this.entities,warnings));const chosenMasteries=collectChosenWeaponMasteries(character);if(chosenMasteries.full.length>0){const target=features.find(rf=>{var _a2;return rf.feature.id==="weapon-mastery"||((_a2=rf.feature.choices)==null?void 0:_a2.some(ch=>ch.kind==="select-entity"&&ch.id==="weapon-mastery"&&ch.entity_type==="weapon"))});if(target){const names=chosenMasteries.full.map(fullSlug=>{var _a2,_b2;return(_b2=(_a2=this.entities.getByTypeAndSlug("weapon",fullSlug))==null?void 0:_a2.name)!=null?_b2:fullSlug});const entry={label:"Mastered weapons",description:names.join(", ")};target.chosenInline=target.chosenInline?[...target.chosenInline,entry]:[entry]}}const featureResources=resolveFeatureResources(features);const resolvedCharacter={definition:character,race,classes,background,feats,...originFeatSlug?{originFeatSlug}:{},totalLevel,features,spells:[],pools:[],resources:featureResources,weaponMasteries:chosenMasteries.bare,...(()=>{var _a2;const p=(_a2=pactWeaponPick(memberSites))!=null?_a2:classPactWeaponPick(character,classes);return p?{pactWeapon:p}:{}})(),state:character.state};resolvedCharacter.pools=resolveAllPools(resolvedCharacter,this.entities,featureResources);spells.push(...collectAdditionalSpells({race,feats,classes,totalLevel,ownAbility:ownSpellcastingAbility,alreadyCollected:spells,entities:this.entities,warnings,raceChoice:id=>oc[`race:${id}`],pools:resolvedCharacter.pools}));resolvedCharacter.spells=dedupeResolvedSpells(spells);resolvedCharacter.resources=resolveResourceIndex(resolvedCharacter);resolvedCharacter.features=bindFeatureConsumers(resolvedCharacter.features,resolvedCharacter.resources,classes);const infusions=buildInfusionContext(character,resolvedCharacter,this.entities);if(infusions)resolvedCharacter.infusions=infusions;const itemFeatures=buildItemFeatures((_j=character.equipment)!=null?_j:[],this.entities,infusions,warnings);if(itemFeatures.length)resolvedCharacter.itemFeatures=itemFeatures;try{resolvedCharacter.proficiencyReplacements=collectProficiencyReplacements(resolvedCharacter)}catch(e){resolvedCharacter.proficiencyReplacements=[];warnings.push(`Duplicate proficiency check skipped: ${e instanceof Error?e.message:String(e)}`)}return{character:resolvedCharacter,warnings}}};function collectChosenWeaponMasteries(character){var _a,_b;const full=new Set;for(const cls of(_a=character.class)!=null?_a:[]){for(const lvl of Object.values((_b=cls.choices)!=null?_b:{})){const pick=lvl["weapon-mastery"];if(Array.isArray(pick)){for(const s of pick)if(typeof s==="string")full.add(s)}}}return{full:[...full],bare:[...new Set([...full].map(bareEntitySlug))]}}function collectFeatPicks(character){const picks=new Map;for(const site of featPickSites(character.class,[],()=>null)){if(!picks.has(site.slug))picks.set(site.slug,{slug:site.slug,classIndex:site.classIndex,level:site.level})}return[...picks.values()]}function collectFeatGrantedSpells(feat,read,entities,warnings){var _a;const ability=readChosenSpellAbility(read);const slugs=[];collectSpellPickSlugs(feat.choices,read,slugs);const out=[];for(const rawSlug of slugs){const slug=(_a=stripSlug(rawSlug))!=null?_a:rawSlug;const reg=entities.getByTypeAndSlug("spell",slug);if(!reg){warnings.push(`Feat spell [[${slug}]] not found in compendium.`);continue}const entity=mirrorSpellShapes(reg.data);out.push({entity,slug,classSlug:null,source:"feat",prepared:true,alwaysPrepared:true,ability})}return out}function collectItemGrantedSpells(character,ownAbility,entities,warnings){var _a;const out=[];((_a=character.equipment)!=null?_a:[]).forEach((entry,entryIndex)=>{var _a2,_b,_c,_d,_e,_f;const spellRef=(_a2=entry.overrides)==null?void 0:_a2.spell;if(!spellRef)return;const{entity:itemEntity}=resolveEntityForEntry(entry.item,entities);const scrollLevel=isItemEntity(itemEntity)?itemEntity.scroll_level:void 0;if(scrollLevel==null)return;const slug=(_b=stripSlug(spellRef))!=null?_b:spellRef;const reg=entities.getByTypeAndSlug("spell",slug);if(!reg){warnings.push(`Scroll spell [[${slug}]] not found in compendium.`);return}const entity=mirrorSpellShapes(reg.data);const ability=(_f=(_d=(_c=entry.overrides)==null?void 0:_c.spell_ability)!=null?_d:ownAbility)!=null?_f:(_e=character.overrides)==null?void 0:_e.spellcasting_ability;const itemCasting=storedSpellNumbers(itemEntity);out.push({entity,slug,classSlug:null,source:"item",prepared:true,alwaysPrepared:true,ability,entryIndex,...itemCasting?{itemCasting}:{}})});return out}function dedupeResolvedSpells(spells){const byKey=new Map;for(const s of spells){const key=s.source==="item"?`${s.slug}#${s.entryIndex}`:s.atWill?`${s.slug}#atwill`:s.slug;const existing=byKey.get(key);if(!existing){byKey.set(key,s);continue}if(existing.source==="feat"&&s.source!=="feat"){byKey.set(key,{...s,alwaysPrepared:s.alwaysPrepared||existing.alwaysPrepared,prepared:s.prepared||existing.alwaysPrepared,...existing.persisted||s.persisted?{persisted:true}:{}})}else if(s.alwaysPrepared&&!existing.alwaysPrepared){byKey.set(key,{...existing,alwaysPrepared:true,prepared:true})}}return[...byKey.values()]}function readChosenSpellAbility(read){const pick=read("spellcasting-ability");return typeof pick==="string"&&ABILITY_KEYS.includes(pick)?pick:null}function collectSpellPickSlugs(choices,read,out){for(const ch of choices!=null?choices:[]){if(ch.kind==="select-entity"&&ch.entity_type==="spell"){const sel=read(ch.id);const picks=Array.isArray(sel)?sel:typeof sel==="string"?[sel]:[];for(const p of picks)if(typeof p==="string"&&p.length>0)out.push(p)}else if(ch.kind==="select-inline"){const sel=read(ch.id);const branch=typeof sel==="string"?ch.options.find(o=>o.value===sel):void 0;if(branch==null?void 0:branch.choices)collectSpellPickSlugs(branch.choices,read,out)}}}function collectChosenGrantedFeatures(character,classes,registry,race=null,background=null,memberSites=[]){var _a,_b,_c,_d;const out=[];for(const site of memberSites){const classSlug=(_b=(_a=classes[site.classIndex])==null?void 0:_a.entity)==null?void 0:_b.slug;if(!classSlug)continue;const at={};const grants=site.choices.filter(ch=>!isTargetChoice(ch));for(const ch of grants)at[ch.id]=site.read(ch.id);walkChoiceGrants(grants,at,(granted,suppress)=>{out.push({feature:granted,source:{kind:"class",slug:classSlug,level:site.level},...suppress?{renderSuppressed:true}:{}})},registry)}classes.forEach((c,i)=>{var _a2,_b2,_c2,_d2;if(!c.entity)return;const entity=c.entity;const entry=character.class[i];if(!entry)return;for(const[lvlStr,atLevel]of Object.entries(entry.choices)){const lvl=Number(lvlStr);if(!Number.isFinite(lvl)||lvl>entry.level)continue;const features=(_b2=((_a2=entity.features_by_level)!=null?_a2:{})[lvl])!=null?_b2:[];const subFeatures=c.subclass?(_d2=((_c2=c.subclass.features_by_level)!=null?_c2:{})[lvl])!=null?_d2:[]:[];for(const feature of[...features,...subFeatures]){walkChoiceGrants(feature.choices,atLevel,(granted,suppress)=>{out.push({feature:granted,source:{kind:"class",slug:entity.slug,level:lvl},...suppress?{renderSuppressed:true}:{}})},registry)}}});const oc=(_c=character.origin_choices)!=null?_c:{};const originAt=ns=>{const at={};for(const[key,val]of Object.entries(oc)){if(key.startsWith(`${ns}:`))at[key.slice(ns.length+1)]=val}return at};if(race){const atRace=originAt("race");const emitRace=(granted,suppress)=>{out.push({feature:granted,source:{kind:"race",slug:race.slug},...suppress?{renderSuppressed:true}:{}})};walkChoiceGrants(race.choices,atRace,emitRace,registry);for(const trait of(_d=race.traits)!=null?_d:[]){walkChoiceGrants(trait.choices,atRace,emitRace,registry)}}if(background){const atBg=originAt("background");const emitBg=(granted,suppress)=>{out.push({feature:granted,source:{kind:"background",slug:background.slug},...suppress?{renderSuppressed:true}:{}})};walkChoiceGrants(background.choices,atBg,emitBg,registry);if(background.feature){walkChoiceGrants(background.feature.choices,atBg,emitBg,registry)}}return out}function choiceIdsOf(choices,out=[]){for(const ch of choices!=null?choices:[]){out.push(ch.id);if(ch.kind==="select-inline")for(const o of ch.options)choiceIdsOf(o.choices,out)}return out}function collectFeatChoiceGrants(sites,registry){var _a;const out=[];for(const site of sites){const choices=(_a=site.feat.choices)!=null?_a:[];if(!choices.length)continue;const at={};for(const id of choiceIdsOf(choices))at[id]=site.read(id);const source={kind:"feat",slug:site.feat.slug,...site.via?{via:site.via}:{}};walkChoiceGrants(choices,at,granted=>{var _a2;out.push({feature:{...granted,name:(_a2=site.feat.name)!=null?_a2:granted.name},source,renderSuppressed:true})},registry,{inlineOnly:true})}return out}function collectAdditionalFeatures(character,entities,warnings){var _a,_b,_c,_d,_e,_f,_g,_h;const out=[];for(const entry of(_a=character.additional_features)!=null?_a:[]){const slug=(_b=stripSlug(entry))!=null?_b:entry;const reg=entities.getByTypeAndSlug("optional-feature",slug);if(!reg){warnings.push(`Granted feature [[${slug}]] not found in compendium as optional-feature.`);continue}const d=reg.data;const feature={id:(_c=d.slug)!=null?_c:slug,name:(_d=d.name)!=null?_d:slug,description:d.description,...((_e=d.effects)==null?void 0:_e.length)?{effects:d.effects}:{},...d.action_cost?{action:d.action_cost}:{},...d.passive!==void 0?{passive:d.passive}:{},...d.activatable!==void 0?{activatable:d.activatable}:{},...d.duration?{duration:d.duration}:{},...d.consumes?{consumes:d.consumes}:{}};const uses=d.uses;if(uses){const maxFormula=String(uses.max);if(isValidMaxFormula(maxFormula)){feature.resources=[{id:(_f=d.slug)!=null?_f:slug,name:(_g=d.name)!=null?_g:slug,max_formula:maxFormula,reset:uses.recharge,...((_h=uses.recovery)==null?void 0:_h.length)?{recovery:uses.recovery}:{},...d.rendering_hint?{rendering_hint:d.rendering_hint}:{},...d.surface?{surface:d.surface}:{}}]}else{warnings.push(`Granted feature "${slug}" has a prose uses.max (${JSON.stringify(uses.max)}); no tracker.`)}}out.push({feature,source:{kind:"campaign",slug}})}return out}function walkChoiceGrants(choices,atLevel,emit,registry,opts={}){var _a,_b,_c,_d,_e;for(const ch of choices!=null?choices:[]){const sel=atLevel[ch.id];if(!opts.inlineOnly&&ch.kind==="select-entity"&&ch.entity_type==="optional-feature"){const slugs=Array.isArray(sel)?sel:typeof sel==="string"?[sel]:[];for(const slug of slugs){const reg=registry.getByTypeAndSlug("optional-feature",(_a=stripSlug(String(slug)))!=null?_a:String(slug));if(!reg)continue;const d=reg.data;emit({id:(_b=d.slug)!=null?_b:String(slug),name:(_c=d.name)!=null?_c:String(slug),description:d.description,effects:d.effects,...d.action_cost?{action:d.action_cost}:{}})}}if(ch.kind==="select-inline"){const picks=Array.isArray(sel)?sel.filter(v=>typeof v==="string"):typeof sel==="string"?[sel]:[];for(const value of picks){const branch=ch.options.find(o=>o.value===value);if((_d=branch==null?void 0:branch.effects)==null?void 0:_d.length){const wc=(_e=branch.choices)==null?void 0:_e.find(c=>c.kind==="select-entity"&&c.entity_type==="weapon");const picked=wc?atLevel==null?void 0:atLevel[wc.id]:void 0;const effects=branch.effects.map(e=>e.kind==="weapon-ability"&&e.weapons==="chosen"&&typeof picked==="string"?{...e,weapons:[bareEntitySlug(picked)]}:e);emit({id:`${ch.id}-${branch.value}`,name:branch.label,description:branch.description,effects},true)}if(branch==null?void 0:branch.choices)walkChoiceGrants(branch.choices,atLevel,emit,registry,opts)}}}}function resolveChosenInline(feature,atLevel){var _a;if(!atLevel)return void 0;const picks=[];for(const ch of(_a=feature.choices)!=null?_a:[]){if(ch.kind!=="select-inline")continue;const sel=atLevel[ch.id];if(typeof sel!=="string")continue;const opt=ch.options.find(o=>o.value===sel);if(!opt)continue;picks.push({label:opt.label,description:opt.description})}return picks.length?picks:void 0}function isAsiSlotFeature(feature){var _a,_b,_c,_d;return feature.id==="ability-score-improvement"&&!((_a=feature.effects)!=null?_a:[]).some(e=>!(e.kind==="ability-score-increase"&&e.abilities==="chosen"))&&!((_b=feature.resources)==null?void 0:_b.length)&&!feature.action&&!((_c=feature.sub_features)==null?void 0:_c.length)&&!((_d=feature.attacks)==null?void 0:_d.length)}function foldRepeated(list){const byId=new Map;for(const rf of list){const id=rf.feature.id;if(!id||rf.buildOnly)continue;const arr=byId.get(id);if(arr)arr.push(rf);else byId.set(id,[rf])}const out=[];for(const rf of list){if(!rf.feature.id||rf.buildOnly){out.push(rf);continue}const arr=byId.get(rf.feature.id);if(!arr||arr.length===1){out.push(rf);continue}const sorted=[...arr].sort((a,b)=>a.source.level-b.source.level);const top=sorted[sorted.length-1];if(rf!==top)continue;const effects=sorted.flatMap(c=>{var _a;return(_a=c.feature.effects)!=null?_a:[]});const seen=new Set;const resources=sorted.flatMap(c=>{var _a;return((_a=c.feature.resources)!=null?_a:[]).filter(r=>!seen.has(r.id)&&seen.add(r.id))});const chosenInline=sorted.flatMap(c=>c.chosenInline?[c.chosenInline]:[]);const cardProse=f=>{var _a,_b;return(_b=f.description)!=null?_b:((_a=f.entries)==null?void 0:_a.length)?f.entries.join("\n\n"):void 0};const foldedFrom=sorted.slice(0,-1).map(c=>{var _a;return{level:c.source.level,name:c.feature.name,...cardProse(c.feature)?{description:cardProse(c.feature)}:{},...((_a=c.feature.choices)==null?void 0:_a.length)?{choices:c.feature.choices}:{}}});out.push({...top,feature:{...top.feature,...effects.length?{effects}:{},...resources.length?{resources}:{}},...chosenInline.length?{chosenInline:chosenInline.flat()}:{},...foldedFrom.length?{foldedFrom}:{}})}return out}function collectResolvedFeatures(race,classes,background,feats,featVia=new Map){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o;const out=[];for(const c of classes){if(!c.entity)continue;const slug=c.entity.slug;const byLevel=(_a=c.entity.features_by_level)!=null?_a:{};const classFeatures=[];const subclassFeatures=[];for(const[lvlStr,feats0]of Object.entries(byLevel)){const lvl=parseInt(lvlStr,10);if(Number.isNaN(lvl)||lvl>c.level)continue;for(const feat of feats0){const chosenInline=resolveChosenInline(feat,(_b=c.choices)==null?void 0:_b[lvl]);const feature=withResolvedActionCost(feat);classFeatures.push({feature,source:{kind:"class",slug,level:lvl},...chosenInline?{chosenInline}:{},...isAsiSlotFeature(feature)?{buildOnly:true}:{}})}}if(c.subclass){const sSlug=c.subclass.slug;const sByLevel=(_c=c.subclass.features_by_level)!=null?_c:{};for(const[lvlStr,feats0]of Object.entries(sByLevel)){const lvl=parseInt(lvlStr,10);if(Number.isNaN(lvl)||lvl>c.level)continue;for(const feat of feats0){const chosenInline=resolveChosenInline(feat,(_d=c.choices)==null?void 0:_d[lvl]);const feature=withResolvedActionCost(feat);subclassFeatures.push({feature,source:{kind:"subclass",slug:sSlug,level:lvl},...chosenInline?{chosenInline}:{},...isAsiSlotFeature(feature)?{buildOnly:true}:{}})}}}const foldedClass=foldRepeated(classFeatures);const foldedSubclass=foldRepeated(subclassFeatures);out.push(...foldedClass);if((_e=c.entity.resources)==null?void 0:_e.length){out.push({feature:{name:c.entity.name,resources:c.entity.resources},source:{kind:"class",slug,level:1}})}out.push(...foldedSubclass);if((_g=(_f=c.subclass)==null?void 0:_f.resources)==null?void 0:_g.length){out.push({feature:{name:c.subclass.name,resources:c.subclass.resources},source:{kind:"subclass",slug:c.subclass.slug,level:1}})}}if(race){const traits=(_h=race.traits)!=null?_h:[];for(const feat of traits){out.push({feature:withResolvedActionCost(feat),source:{kind:"race",slug:race.slug}})}}if(background){const bgFeature=background.feature;if(bgFeature){out.push({feature:withResolvedActionCost(bgFeature),source:{kind:"background",slug:background.slug}})}}for(const feat of feats){const via=featVia.get(feat.slug);const featSource={kind:"feat",slug:feat.slug,...via?{via}:{}};const bundled=(_i=feat.features)!=null?_i:[];const entityEffects=(_j=feat.effects)!=null?_j:[];if(bundled.length>0){bundled.forEach((f,i)=>{var _a2,_b2;const feature=i===0?{...f,action:(_a2=f.action)!=null?_a2:feat.action_cost,...entityEffects.length>0?{effects:[...(_b2=f.effects)!=null?_b2:[],...entityEffects]}:{}}:f;out.push({feature,source:featSource})})}else{const name=(_k=feat.name)!=null?_k:feat.slug;const foldedDesc=[feat.description,...(_l=feat.benefits)!=null?_l:[]].filter(Boolean).join("\n\n")||void 0;const buildOnly=((_m=feat.choices)!=null?_m:[]).some(c=>c.kind==="ability-points"&&c.points>=2)&&!((_n=feat.effects)==null?void 0:_n.length)&&!((_o=feat.resources)==null?void 0:_o.length)&&bundled.length===0;out.push({feature:{name,...foldedDesc?{description:foldedDesc}:{},...feat.resources?{resources:feat.resources}:{},...feat.action_cost?{action:feat.action_cost}:{},...entityEffects.length>0?{effects:entityEffects}:{}},source:featSource,...buildOnly?{buildOnly:true}:{}})}}return out}export{stripSlug,resolveOriginFeat,PCResolver,collectChosenWeaponMasteries,collectFeatPicks,collectFeatGrantedSpells,collectItemGrantedSpells,dedupeResolvedSpells,collectChosenGrantedFeatures,collectFeatChoiceGrants,collectAdditionalFeatures,collectResolvedFeatures,collectProficiencyGrants,__matchesFilterForTest,__categoryToEntitySelectForTest,collectChosenProficiencies,collectRuleProficiencySources,collectProficiencyReplacements,computeEffectiveProficiencies,computeSuppressedProficiencies,collectChosenAbilityPoints,buildDecisionLedger};
@@ -1 +1 @@
1
- import{qualifiedGrantCovers}from"./chunk-T55DELVL.js";import{classifyWeaponRange}from"./chunk-SEOASDO4.js";import{resolveContainment}from"./chunk-4E2GIWJE.js";import{foldsNow,pushDefenseGrant}from"./chunk-4FTTUZXM.js";import{normKey}from"./chunk-VTQ4RWEG.js";import{itemBenefitsActive,itemLabel,itemRowEffects}from"./chunk-MMDUUEFA.js";import{WEAPON_DEFAULT_ACTION_COST,resolveEntryEntity}from"./chunk-E4E6YEN6.js";import{isActivatedSpeedItem}from"./chunk-DVUXUIPV.js";import{readNumericBonus}from"./chunk-NEMX7QGG.js";import{defaultSlotForType,effectiveArmor,effectiveWeapon,isItemEntity,isShieldArmor,isTwoHandedWeapon,slotAcTerms}from"./chunk-4IAMSRHD.js";import{resolveBaseItem}from"./chunk-PZ4L2EEG.js";import{bareEntitySlug}from"./chunk-63YJPWTM.js";var MASTERY={cleave:{label:"Cleave",description:"If you hit a creature with a melee attack roll using this weapon, you can make an attack roll with the weapon against a second creature within 5 feet of the first that is also within your reach. On a hit, the second creature takes the weapon's damage, but don't add your ability modifier to that damage unless it is negative. You can make this extra attack only once per turn.",gist:"hit a 2nd creature in reach"},graze:{label:"Graze",description:"If your attack roll with this weapon misses a creature, you can deal damage to that creature equal to the ability modifier you used to make the attack roll. This damage is the same type dealt by the weapon, and the damage can be increased only by increasing the ability modifier.",gist:"on miss: ability-mod damage"},nick:{label:"Nick",description:"When you make the extra attack of the Light property, you can make it as part of the Attack action instead of as a Bonus Action. You can make this extra attack only once per turn.",gist:"extra Light attack (no Bonus Action)"},push:{label:"Push",description:"If you hit a creature with this weapon, you can push the creature up to 10 feet straight away from yourself if it is Large or smaller.",gist:"on hit: pushed 10 ft."},sap:{label:"Sap",description:"If you hit a creature with this weapon, that creature has Disadvantage on its next attack roll before the start of your next turn.",gist:"on hit: target Disadvantage"},slow:{label:"Slow",description:"If you hit a creature with this weapon and deal damage, you can reduce its Speed by 10 feet until the start of your next turn. If the creature is hit more than once by weapons that have this property, the Speed reduction doesn't exceed 10 feet.",gist:"on hit: -10 ft. Speed"},topple:{label:"Topple",description:"If you hit a creature with this weapon, you can force the creature to make a Constitution saving throw (DC 8 plus the ability modifier used to make the attack roll and your Proficiency Bonus). On a failed save, the creature has the Prone condition.",gist:"on fail: Prone"},vex:{label:"Vex",description:"If you hit a creature with this weapon and deal damage, you have Advantage on your next attack roll against that creature before the end of your next turn.",gist:"on hit: you gain Advantage next"}};function masteryGist(slug){var _a;return(_a=MASTERY[slug])==null?void 0:_a.gist}function masteryDerived(slug,abilityMod,proficiencyBonus){if(slug==="topple")return{label:"Save DC",value:8+proficiencyBonus+abilityMod};if(slug==="graze")return{label:"On miss",value:abilityMod};return void 0}var ABILITY_KEYS=["str","dex","con","int","wis","cha"];function isAbilityKey(k){return ABILITY_KEYS.includes(k)}function emptyAppliedBonuses(){return{ability_bonuses:{},ability_statics:{},ability_terms:[],ability_static_terms:[],save_bonus:0,save_terms:[],speed_bonuses:{walk:0,fly:null,swim:0,climb:0},speed_walk_set:0,speed_walk_set_terms:[],speed_terms:[],spell_attack:0,spell_save_dc:0,defenses:{resistances:[],immunities:[],vulnerabilities:[],condition_immunities:[]},informational:[],senses:{darkvision:0,blindsight:0,tremorsense:0,truesight:0}}}function unwrapSlug(item){const m=item.match(/^\[\[(.+)\]\]$/);return m?m[1]:null}function unwrapClassSlug(maybeWiki){if(!maybeWiki)return"";const m=/^\[\[([^\]]+)\]\]$/.exec(maybeWiki);return(m?m[1]:maybeWiki).toLowerCase()}function buildConditionContext(resolved,equippedSlots,registry){var _a,_b;return{derived:{equippedSlots},classList:(_a=resolved.definition.class)!=null?_a:[],race:resolved.definition.race,subclasses:((_b=resolved.definition.class)!=null?_b:[]).map(c=>c.subclass).filter(s=>typeof s==="string"&&s.length>0).map(unwrapClassSlug),registry}}function pushApply(outcome,field,source,pool,onApply){if(!outcome)return;if(outcome.kind==="applied")onApply(outcome.value);else if(outcome.kind==="informational"){pool.push({field,source,value:outcome.value,conditions:outcome.conditions})}}function isOtherSpeedMode(mode){return mode==="fly"||mode==="swim"||mode==="climb"||mode==="burrow"}function computeAppliedBonuses(resolved,_profs,registry,warnings){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u;const out=emptyAppliedBonuses();const equipment=(_a=resolved.definition.equipment)!=null?_a:[];const ctx=buildConditionContext(resolved,{},registry);for(let index=0;index<equipment.length;index++){const entry=equipment[index];const{entity,entityType}=resolveEntryEntity(entry,index,registry,resolved.infusions);if(!entity){const slug=unwrapSlug(entry.item);if(slug&&entry.equipped&&!((_b=resolved.infusions)==null?void 0:_b.views.has(index)))warnings.push(`Equipped item [[${slug}]] not found in compendium.`);continue}if(!itemBenefitsActive(entry,entity,registry,(_c=resolved.infusions)==null?void 0:_c.views.get(index)))continue;if(entityType!=="item")continue;const item=entity;const label=itemLabel(entry,item);const grant=(bucket,values)=>{for(const v of values!=null?values:[])if(typeof v==="string")pushDefenseGrant(out.defenses[bucket],v,label,void 0,{index,name:label})};grant("resistances",item.resist);grant("immunities",item.immune);grant("vulnerabilities",item.vulnerable);grant("condition_immunities",item.condition_immune);grant("resistances",(_d=entry.overrides)==null?void 0:_d.resist);grant("immunities",(_e=entry.overrides)==null?void 0:_e.immune);grant("vulnerabilities",(_f=entry.overrides)==null?void 0:_f.vulnerable);grant("condition_immunities",(_g=entry.overrides)==null?void 0:_g.condition_immune);const gs=(_h=item.grants)==null?void 0:_h.senses;if(gs){if(typeof gs.darkvision==="number")out.senses.darkvision=Math.max(out.senses.darkvision,gs.darkvision);if(typeof gs.blindsight==="number")out.senses.blindsight=Math.max(out.senses.blindsight,gs.blindsight);if(typeof gs.tremorsense==="number")out.senses.tremorsense=Math.max(out.senses.tremorsense,gs.tremorsense);if(typeof gs.truesight==="number")out.senses.truesight=Math.max(out.senses.truesight,gs.truesight)}const floor=(_j=(_i=item.modify_speed)==null?void 0:_i.static)==null?void 0:_j.walk;if(typeof floor==="number"&&floor>0){out.speed_walk_set=Math.max(out.speed_walk_set,floor);out.speed_walk_set_terms.push({source:label,amount:floor})}const activatedSpeed=isActivatedSpeedItem(String((_k=item.slug)!=null?_k:"")||((_l=unwrapSlug(entry.item))!=null?_l:entry.item),item);const itemSpeed=(mode,kind,amount)=>{if(!activatedSpeed&&isOtherSpeedMode(mode))out.speed_terms.push({mode,kind,source:label,amount})};for(const[mode,n]of Object.entries((_n=(_m=item.modify_speed)==null?void 0:_m.static)!=null?_n:{}))if(typeof n==="number"&&n>0)itemSpeed(mode,"grant",n);for(const[mode,to]of Object.entries((_p=(_o=item.modify_speed)==null?void 0:_o.equal)!=null?_p:{}))if(to==="walk")itemSpeed(mode,"walk",0);const b=item.bonuses;if(!b)continue;const saveSource=(_r=(_q=entry.overrides)==null?void 0:_q.name)!=null?_r:item.name;pushApply(readNumericBonus(b.saving_throws,ctx),"saving_throws",saveSource,out.informational,v=>{out.save_bonus+=v;out.save_terms.push({source:saveSource,amount:v})});pushApply(readNumericBonus(b.spell_attack,ctx),"spell_attack",item.name,out.informational,v=>{out.spell_attack+=v});pushApply(readNumericBonus(b.spell_save_dc,ctx),"spell_save_dc",item.name,out.informational,v=>{out.spell_save_dc+=v});if((_s=b.ability_scores)==null?void 0:_s.bonus){for(const[k,v]of Object.entries(b.ability_scores.bonus)){if(!isAbilityKey(k))continue;pushApply(readNumericBonus(v,ctx),`ability_scores.bonus.${k}`,item.name,out.informational,val=>{var _a2,_b2;out.ability_bonuses[k]=((_a2=out.ability_bonuses[k])!=null?_a2:0)+val;((_b2=out.ability_terms)!=null?_b2:out.ability_terms=[]).push({ability:k,source:saveSource,amount:val})})}}if((_t=b.ability_scores)==null?void 0:_t.static){for(const[k,n]of Object.entries(b.ability_scores.static)){if(!isAbilityKey(k)||typeof n!=="number")continue;((_u=out.ability_static_terms)!=null?_u:out.ability_static_terms=[]).push({ability:k,source:saveSource,value:n});const prev=out.ability_statics[k];if(prev===void 0){out.ability_statics[k]=n}else{if(n!==prev){warnings.push(`Multiple static ${k.toUpperCase()} bonuses on equipped+attuned items; using highest (${Math.max(prev,n)}).`)}out.ability_statics[k]=Math.max(prev,n)}}}if(b.speed){pushApply(readNumericBonus(b.speed.walk,ctx),"speed.walk",item.name,out.informational,v=>{out.speed_bonuses.walk+=v;out.speed_terms.push({mode:"walk",kind:"bonus",source:label,amount:v})});if(b.speed.fly==="walk"){out.speed_bonuses.fly="walk";itemSpeed("fly","walk",0)}else{pushApply(readNumericBonus(b.speed.fly,ctx),"speed.fly",item.name,out.informational,v=>{const cur=out.speed_bonuses.fly;out.speed_bonuses.fly=(typeof cur==="number"?cur:0)+v;itemSpeed("fly","grant",v)})}pushApply(readNumericBonus(b.speed.swim,ctx),"speed.swim",item.name,out.informational,v=>{out.speed_bonuses.swim+=v;itemSpeed("swim","grant",v)});pushApply(readNumericBonus(b.speed.climb,ctx),"speed.climb",item.name,out.informational,v=>{out.speed_bonuses.climb+=v;itemSpeed("climb","grant",v)})}}return out}function assignSlots(resolved,registry,warnings){var _a;const slots={};const eq=(_a=resolved.definition.equipment)!=null?_a:[];for(let i=0;i<eq.length;i++){const entry=eq[i];if(!entry.equipped||!entry.slot)continue;const{entity,entityType}=resolveEntryEntity(entry,i,registry,resolved.infusions);if(slots[entry.slot])continue;const placed={index:i,entity,entityType,entry};slots[entry.slot]=placed}for(let i=0;i<eq.length;i++){const entry=eq[i];if(!entry.equipped||entry.slot)continue;const{entity,entityType}=resolveEntryEntity(entry,i,registry,resolved.infusions);if(!entity||!entityType)continue;const defaultSlot=defaultSlotForType(entityType,entity,registry);if(!defaultSlot){if(isItemEntity(entity)&&typeof entity.base_item==="string"&&entity.base_item.length>0){warnings.push(`Magic item "${entity.name}" base_item ${entity.base_item} did not resolve to a base weapon or armor; not slotted (AC/attack not applied).`)}continue}const placed={index:i,entity,entityType,entry};if(defaultSlot==="mainhand"){if(!slots.mainhand)slots.mainhand=placed;else if(!slots.offhand)slots.offhand=placed}else if(!slots[defaultSlot]){slots[defaultSlot]=placed}}return slots}function pickShield(equippedSlots,equipment,registry,infusions){const slotted=equippedSlots.shield;const slottedArmor=effectiveArmor(slotted==null?void 0:slotted.entity,registry);if(slotted&&slottedArmor&&isShieldArmor(slottedArmor)){return{index:slotted.index,shield:slottedArmor,entity:slotted.entity,entry:slotted.entry}}for(let i=0;i<equipment.length;i++){const entry=equipment[i];if(!entry.equipped)continue;const{entity}=resolveEntryEntity(entry,i,registry,infusions);const armor=effectiveArmor(entity,registry);if(armor&&isShieldArmor(armor))return{index:i,shield:armor,entity,entry}}return null}function twoHandedShieldWarnings(equipment,registry,warnings,infusions){const equipped=equipment.flatMap((entry,i)=>{if(!entry.equipped)return[];const{entity}=resolveEntryEntity(entry,i,registry,infusions);return[{entry,entity}]});const isShield=e=>{const armor=effectiveArmor(e.entity,registry);return!!armor&&isShieldArmor(armor)};for(const e of equipped){if(!e.entity||!isTwoHandedWeapon(e.entity,registry))continue;if(!equipped.some(other=>other!==e&&isShield(other)))continue;warnings.push(`${e.entity.name} is two-handed and a Shield is also equipped.`)}}function computeAC(equippedSlots,resolved,mods,registry,warnings){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j;const breakdown=[];const armorSlot=equippedSlots.armor;const armorEntity=(_a=armorSlot==null?void 0:armorSlot.entity)!=null?_a:null;const armor=effectiveArmor(armorEntity,registry);if(isItemEntity(armorEntity)&&typeof armorEntity.base_item==="string"&&!armor){warnings.push(`Magic armor "${armorEntity.name}" base_item ${armorEntity.base_item} did not resolve to a base armor; AC not applied.`)}const acCtx=buildConditionContext(resolved,equippedSlots,registry);const skip=new Set;const slotBonus=slot=>{var _a2,_b2;const view=slot?(_a2=resolved.infusions)==null?void 0:_a2.views.get(slot.index):void 0;if(!slot||!(view==null?void 0:view.entity)||!isItemEntity(view.entity)||!itemBenefitsActive(slot.entry,view.entity,registry,view))return 0;const out=readNumericBonus((_b2=view.entity.bonuses)==null?void 0:_b2.ac,acCtx);if((out==null?void 0:out.kind)!=="applied")return 0;skip.add(slot.index);return out.value};const armorTerms=slotAcTerms(armor,armorSlot==null?void 0:armorSlot.entry);let ac=10;if(armor&&armorTerms.armor!==null){const armorBase=armorTerms.armor+slotBonus(armorSlot);ac=armorBase;breakdown.push({source:(_b=armorEntity==null?void 0:armorEntity.name)!=null?_b:armor.name,amount:armorBase,kind:"armor"});if(armor.ac.add_dex){const dexCap=(_c=armor.ac.dex_max)!=null?_c:Number.POSITIVE_INFINITY;const dexAdd=Math.min(mods.dex,dexCap);ac+=dexAdd;const capped=mods.dex>dexCap;breakdown.push({source:`DEX modifier${capped?" (capped)":""}`,amount:dexAdd,kind:"dex"})}}else{ac=10+mods.dex;breakdown.push({source:"Base",amount:10,kind:"unarmored"});breakdown.push({source:"DEX modifier",amount:mods.dex,kind:"dex"})}const acBonus=armorTerms.override;if(acBonus!==0){ac+=acBonus;breakdown.push({source:`${(_d=armorEntity==null?void 0:armorEntity.name)!=null?_d:"Armor"} (override)`,amount:acBonus,kind:"override"})}const picked=pickShield(equippedSlots,(_e=resolved.definition.equipment)!=null?_e:[],registry,resolved.infusions);if(picked){const{shield,entity:shieldEntity}=picked;const shieldTerms=slotAcTerms(shield,picked.entry);const n=shieldTerms.armor+slotBonus(picked);ac+=n;breakdown.push({source:(_f=shieldEntity==null?void 0:shieldEntity.name)!=null?_f:shield.name,amount:n,kind:"shield"});const shieldAcBonus=shieldTerms.override;if(shieldAcBonus!==0){ac+=shieldAcBonus;breakdown.push({source:`${(_g=shieldEntity==null?void 0:shieldEntity.name)!=null?_g:shield.name} (override)`,amount:shieldAcBonus,kind:"shield"})}}const acInformational=[];const acEquipment=(_h=resolved.definition.equipment)!=null?_h:[];for(let index=0;index<acEquipment.length;index++){if(skip.has(index))continue;const entry=acEquipment[index];const{entity,entityType}=resolveEntryEntity(entry,index,registry,resolved.infusions);if(!entity||entityType!=="item")continue;if(!itemBenefitsActive(entry,entity,registry,(_i=resolved.infusions)==null?void 0:_i.views.get(index)))continue;const item=entity;const out=readNumericBonus((_j=item.bonuses)==null?void 0:_j.ac,acCtx);if(!out)continue;if(out.kind==="applied"){ac+=out.value;breakdown.push({source:item.name,amount:out.value,kind:"item"})}else if(out.kind==="informational"){acInformational.push({field:"ac",source:item.name,value:out.value,conditions:out.conditions})}}return{ac,breakdown,informational:acInformational}}function hasProperty(weapon,prop){return weapon.properties.some(p=>p===prop)}function attackAbility(weapon,mods,weaponAbilities){const modes=classifyWeaponRange(weapon);const finesse=hasProperty(weapon,"finesse");if(modes.melee){const scoped=weaponAbilities.find(o2=>{var _a;return(_a=o2.weaponSlugs)==null?void 0:_a.includes(bareEntitySlug(weapon.slug))});const glob=weaponAbilities.find(o2=>!o2.weaponSlugs);const o=scoped!=null?scoped:glob;if(o)return o.ability;if(finesse)return mods.dex>=mods.str?"dex":"str";return"str"}return finesse&&mods.str>mods.dex?"str":"dex"}function pactScopedAbilities(overrides,pactPicked,isPact){if(!overrides.some(o=>o.pactWeapon))return overrides;return overrides.flatMap(o=>{if(!o.pactWeapon)return[o];return!pactPicked||isPact?[{ability:o.ability}]:[]})}function pactWeaponIndexes(resolved,registry){var _a;const pick=resolved.pactWeapon;if(!pick)return null;const out=new Set;const bare=bareEntitySlug(pick);((_a=resolved.definition.equipment)!=null?_a:[]).forEach((entry,i)=>{var _a2;if(typeof entry.item!=="string")return;const slugs=[unwrapSlug(entry.item),registry?(_a2=resolveBaseItem(entry.item,registry))==null?void 0:_a2.slug:void 0];if(slugs.some(s=>!!s&&(s===pick||bareEntitySlug(s)===bare)))out.add(i)});return out.size?out:null}function isWeaponSlugProficient(weapon,weaponSlug,profs){const wp=profs.weapons;if(wp.specific.some(e=>e===weaponSlug||normKey(e)===normKey(weapon.name)))return true;if(wp.specific.some(e=>qualifiedGrantCovers(e,weapon)))return true;const cat=weapon.category;if(typeof cat==="string"){if(/^simple\b/.test(cat)&&wp.categories.includes("simple"))return true;if(/^martial\b/.test(cat)&&wp.categories.includes("martial"))return true;if(wp.categories.includes(cat))return true}return false}function magicBonusesForWeaponEntry(entry,registry,ctx,index,infusions){var _a,_b,_c,_d;const{entity}=resolveEntryEntity(entry,index,registry,infusions);const ovr=(_a=entry.overrides)!=null?_a:{};const entryAttack=typeof ovr.bonus==="number"?ovr.bonus:0;const entryDamage=typeof ovr.damage_bonus==="number"?ovr.damage_bonus:0;const extra=typeof ovr.extra_damage==="string"?ovr.extra_damage:void 0;let itemAttack=0;let itemDamage=0;let sourceName;let itemName;let damageTypeOverride;let propertiesOverride;const informational=[];let itemRiders=[];let critRange;const conditionalCrits=[];if(entity&&isItemEntity(entity)){sourceName=entity.name;itemName=entity.name;damageTypeOverride=typeof entity.damage_type==="string"&&entity.damage_type.length>0?entity.damage_type:void 0;propertiesOverride=Array.isArray(entity.properties)&&entity.properties.length>0?entity.properties:void 0}if(entity&&isItemEntity(entity)&&itemBenefitsActive(entry,entity,registry,infusions==null?void 0:infusions.views.get(index))){const b=entity.bonuses;const atkOut=readNumericBonus(b==null?void 0:b.weapon_attack,ctx);const dmgOut=readNumericBonus(b==null?void 0:b.weapon_damage,ctx);if((atkOut==null?void 0:atkOut.kind)==="applied")itemAttack=atkOut.value;else if((atkOut==null?void 0:atkOut.kind)==="informational")informational.push({field:"weapon_attack",source:entity.name,value:atkOut.value,conditions:atkOut.conditions});if((dmgOut==null?void 0:dmgOut.kind)==="applied")itemDamage=dmgOut.value;else if((dmgOut==null?void 0:dmgOut.kind)==="informational")informational.push({field:"weapon_damage",source:entity.name,value:dmgOut.value,conditions:dmgOut.conditions});itemRiders=Array.isArray(entity.damage_riders)?entity.damage_riders.filter(r=>{var _a2;return((_a2=r.applies_to)!=null?_a2:"weapon")!=="spell"}).map(r=>({amount:r.amount,damage_type:r.damage_type,source:entity.name,...r.condition?{condition:r.condition}:{}})):[];for(const eff of itemRowEffects(entity)){if(eff.kind==="damage-bonus"&&((_b=eff.applies_to)!=null?_b:"weapon")!=="spell"){itemRiders.push({amount:eff.amount,damage_type:eff.damage_type,source:entity.name,...eff.condition?{condition:eff.condition}:{}})}else if(eff.kind==="crit-range"&&((_c=eff.applies_to)!=null?_c:"weapon")!=="spell"){if((_d=eff.condition)==null?void 0:_d.trim())conditionalCrits.push({minRoll:eff.min_roll,condition:eff.condition.trim(),source:entity.name});else critRange=Math.min(critRange!=null?critRange:20,eff.min_roll)}}}return{...critRange!==void 0&&critRange<20?{critRange}:{},...conditionalCrits.length?{conditionalCrits}:{},atk:itemAttack+entryAttack,dmg:itemDamage+entryDamage,extra,sourceName,itemName,damageTypeOverride,propertiesOverride,informational,riders:itemRiders}}function buildAttackRow(args){var _a,_b,_c,_d;const{id,name,weapon,baseDice,ability,mods,proficient,proficiencyBonus,magic,weaponMasteries}=args;const abilityMod=mods[ability];const pb=proficient?proficiencyBonus:0;const toHit=abilityMod+pb+magic.atk;const dmgFlat=abilityMod+magic.dmg;const formatDice=dice=>`${dice}${dmgFlat>=0?"+":""}${dmgFlat}`.replace(/\+0$/,"");const damageDice=formatDice(baseDice);const magicSource=magic.sourceName?`${magic.sourceName} bonus`:"Magic weapon";const toHitBreakdown=[{source:`${ability.toUpperCase()} modifier`,amount:abilityMod,kind:"ability"},{source:"Proficiency bonus",amount:proficient?proficiencyBonus:0,kind:"ability"},{source:magicSource,amount:magic.atk,kind:"item"}];const damageBreakdown=[{source:"Base damage",amount:0,kind:"ability"},{source:`${ability.toUpperCase()} modifier`,amount:abilityMod,kind:"ability"},{source:magicSource,amount:magic.dmg,kind:"item"}];const modes=classifyWeaponRange(weapon);const fmtRanged=r=>r.long>r.normal?`${r.normal}/${r.long} ft.`:`${r.normal} ft.`;const range=modes.melee?`${modes.melee.reach} ft.`:modes.ranged?fmtRanged(modes.ranged):void 0;const thrownRange=modes.melee&&modes.ranged?fmtRanged(modes.ranged):void 0;const stringProps=weapon.properties.filter(p=>typeof p==="string");const finalProps=(_a=magic.propertiesOverride)!=null?_a:stringProps;const row={id,name,...range!==void 0?{range}:{},...thrownRange!==void 0?{thrownRange}:{},toHit,damageDice,damageType:(_b=magic.damageTypeOverride)!=null?_b:weapon.damage.type,...(()=>{const riders=[...magic.riders,...magic.extra?[{amount:magic.extra}]:[]];return riders.length?{damageRiders:riders}:{}})(),weaponCategory:modes.melee?"melee":"ranged",properties:finalProps,proficient,breakdown:{toHit:toHitBreakdown,damage:damageBreakdown},informational:args.magic.informational.length>0?args.magic.informational:void 0,slotKey:args.slotKey,subLabel:formatWeaponSubLabel(weapon,finalProps,modes),actionCost:args.actionCost,versatile:args.versatileDice?{damageDice:formatDice(args.versatileDice)}:void 0,...magic.critRange!==void 0?{critRange:magic.critRange}:{},...((_c=magic.conditionalCrits)==null?void 0:_c.length)?{conditionalCrits:magic.conditionalCrits}:{}};const mSlug=(_d=weapon.mastery)==null?void 0:_d[0];if(mSlug&&proficient&&weaponMasteries.includes(bareEntitySlug(weapon.slug))){const g=MASTERY[mSlug];if(g){const derived=masteryDerived(mSlug,mods[ability],proficiencyBonus);row.mastery={slug:mSlug,label:g.label,description:g.description,gist:masteryGist(mSlug),...derived?{derived}:{}}}}return row}function buildUnarmedRow(mods,proficiencyBonus,spec){var _a;const strike=unarmedStrikeNumbers(mods,proficiencyBonus,["str",...(_a=spec==null?void 0:spec.abilities)!=null?_a:[]],spec==null?void 0:spec.dice);return{id:"unarmed-strike",name:"Unarmed Strike",unarmed:true,range:"5 ft.",...strike,damageType:"bludgeoning",properties:[],proficient:true,subLabel:"Unarmed",actionCost:"action"}}function unarmedStrikeNumbers(mods,proficiencyBonus,candidates,dice){var _a;let ability=(_a=candidates[0])!=null?_a:"str";for(const ab of candidates)if(mods[ab]>=mods[ability])ability=ab;const abilityMod=mods[ability];const flat=`${abilityMod>=0?"+":""}${abilityMod}`.replace(/^\+0$/,"");const label=`${ability.toUpperCase()} modifier`;return{toHit:abilityMod+proficiencyBonus,damageDice:dice?`${dice}${flat}`:String(Math.max(0,1+abilityMod)),breakdown:{toHit:[{source:label,amount:abilityMod,kind:"ability"},{source:"Proficiency bonus",amount:proficiencyBonus,kind:"ability"}],damage:[{source:"Base damage",amount:dice?0:1,kind:"ability"},{source:label,amount:abilityMod,kind:"ability"}]}}}function buildFeatureAttackRows(resolved,mods,profs,proficiencyBonus,weaponAbilities=[],opts={}){var _a,_b,_c,_d;const rows=[];const abilities=weaponAbilities.filter(o=>!o.pactWeapon);const active=new Set((_a=opts.activeBuffs)!=null?_a:[]);for(const rf of(_b=resolved.features)!=null?_b:[]){if(rf.renderSuppressed||rf.buildOnly||!foldsNow(rf,active))continue;const featureId=(_c=rf.feature.id)!=null?_c:rf.feature.name;((_d=rf.feature.attacks)!=null?_d:[]).forEach((a,n)=>{var _a2,_b2,_c2,_d2,_e,_f,_g,_h;const id=`feature-attack:${rf.source.kind}:${rf.source.slug}:${featureId}:${n}`;if(!a.weapon_category&&a.unarmed===true){const natural=buildNaturalWeaponRow(a,id,mods,proficiencyBonus,(_a2=opts.unarmedAbilities)!=null?_a2:[]);if(natural)rows.push({...natural,grantedBy:rf.feature.name});return}if(!a.weapon_category||a.type!=="melee"&&a.type!=="ranged"||typeof a.damage!=="string"||!a.damage.trim())return;const long=(_d2=(_b2=a.range)==null?void 0:_b2.long)!=null?_d2:(_c2=a.range)==null?void 0:_c2.normal;const weapon={name:a.name,slug:`feature-attack_${featureId}_${n}`,category:`${a.weapon_category}-${a.type}`,damage:{dice:a.damage.trim(),type:(_e=a.damage_type)!=null?_e:""},properties:((_f=a.properties)!=null?_f:[]).map(p=>p.trim().toLowerCase()),...((_g=a.range)==null?void 0:_g.normal)!==void 0&&long!==void 0?{range:{normal:a.range.normal,long}}:{},...a.mastery?{mastery:[a.mastery.trim().toLowerCase()]}:{}};const proficient=isWeaponSlugProficient(weapon,weapon.slug,profs);const row=buildAttackRow({id,name:a.name,weapon,baseDice:weapon.damage.dice,ability:attackAbility(weapon,mods,abilities),mods,proficient,proficiencyBonus,magic:{atk:0,dmg:0,informational:[],riders:[]},actionCost:(_h=a.action)!=null?_h:WEAPON_DEFAULT_ACTION_COST,weaponMasteries:a.mastery?[bareEntitySlug(weapon.slug)]:[]});row.grantedBy=rf.feature.name;rows.push(row)})}return rows}function buildNaturalWeaponRow(a,id,mods,proficiencyBonus,unarmedAbilities){var _a,_b,_c,_d;const dice=typeof a.damage==="string"?a.damage.trim():"";if(a.type!=="melee"||!dice)return null;const own=a.ability===void 0?["str"]:Array.isArray(a.ability)?[...a.ability]:[a.ability];return{id,name:a.name,naturalWeapon:true,range:`${(_b=(_a=a.range)==null?void 0:_a.reach)!=null?_b:5} ft.`,...unarmedStrikeNumbers(mods,proficiencyBonus,[...own,...unarmedAbilities],dice),damageType:((_c=a.damage_type)==null?void 0:_c.trim())||"bludgeoning",properties:[],proficient:true,subLabel:"Unarmed",actionCost:(_d=a.action)!=null?_d:"action"}}function humanizeWeaponToken(s){return s.replace(/[-_]/g," ").replace(/(^|[\s(])\w/g,c=>c.toUpperCase())}function formatWeaponSubLabel(weapon,properties,modes){const parts=[];if(weapon.category){const cat=modes.melee&&/ranged/.test(weapon.category)?weapon.category.replace("ranged","melee"):weapon.category;parts.push(humanizeWeaponToken(cat))}if(properties.length>0)parts.push(properties.map(humanizeWeaponToken).join(", "));return parts.join(" \xB7 ")}function computeAttacks(equippedSlots,equipment,mods,profs,registry,warnings,proficiencyBonus,ctx,weaponMasteries,weaponAbilities=[],infusions,pactIndexes=null){var _a,_b;const rows=[];const rowFor=(index,entry,weapon,slotKey,versatileDice)=>{var _a2,_b2,_c,_d,_e;const slugFromEntry=(_a2=unwrapSlug(entry.item))!=null?_a2:weapon.slug;const proficient=isWeaponSlugProficient(weapon,slugFromEntry,profs)||isWeaponSlugProficient(weapon,weapon.slug,profs);if(!proficient){warnings.push(`Character not proficient with ${weapon.name}; proficiency bonus excluded.`)}const isPact=(pactIndexes==null?void 0:pactIndexes.has(index))===true;const ability=attackAbility(weapon,mods,pactScopedAbilities(weaponAbilities,pactIndexes!==null,isPact));const magic=magicBonusesForWeaponEntry(entry,registry,ctx,index,infusions);const ovr=(_b2=entry.overrides)!=null?_b2:{};const row=buildAttackRow({id:`${index}:standard`,name:(_d=(_c=ovr.name)!=null?_c:magic.itemName)!=null?_d:weapon.name,weapon,baseDice:weapon.damage.dice,ability,mods,proficient,proficiencyBonus,magic,slotKey,actionCost:(_e=ovr.action)!=null?_e:WEAPON_DEFAULT_ACTION_COST,versatileDice,weaponMasteries});if(isPact)row.pactWeapon=true;return row};const handedSlots=[{key:"mainhand",placed:equippedSlots.mainhand},{key:"offhand",placed:equippedSlots.offhand}];for(const{key,placed}of handedSlots){if(!placed)continue;const{entity,entry}=placed;if(!entity)continue;const weapon=effectiveWeapon(entity,registry);if(!weapon){if(isItemEntity(entity)&&typeof entity.base_item==="string"&&!resolveBaseItem(entity.base_item,registry)){warnings.push(`Magic weapon ${entity.name} references missing base_item ${entity.base_item}.`)}continue}const versatileDice=key==="mainhand"&&hasProperty(weapon,"versatile")&&typeof weapon.damage.versatile_dice==="string"&&!equippedSlots.offhand?weapon.damage.versatile_dice:void 0;rows.push(rowFor(placed.index,entry,weapon,key,versatileDice))}const handIndex=new Set([(_a=equippedSlots.mainhand)==null?void 0:_a.index,(_b=equippedSlots.offhand)==null?void 0:_b.index]);equipment.forEach((entry,index)=>{if(!entry.equipped||handIndex.has(index))return;const{entity}=resolveEntryEntity(entry,index,registry,infusions);const weapon=effectiveWeapon(entity,registry);if(!weapon)return;rows.push(rowFor(index,entry,weapon))});return rows}function coerceWeight(raw){if(typeof raw==="number"&&Number.isFinite(raw)&&raw>=0)return raw;if(typeof raw==="string"){const n=Number.parseFloat(raw);if(Number.isFinite(n)&&n>=0)return n}return 0}function computeCarriedWeight(resolved,registry){var _a;const equipment=(_a=resolved.definition.equipment)!=null?_a:[];const view=resolveContainment(equipment,registry);const weightlessContainer=equipment.map(entry=>{var _a2,_b,_c;const data=(_a2=resolveBaseItem(entry.item,registry))==null?void 0:_a2.data;return((_c=(_b=data==null?void 0:data.container)==null?void 0:_b.capacity)==null?void 0:_c.weightless)===true});const exempt=i=>{for(let p=view.parentOf[i];p!==null;p=view.parentOf[p])if(weightlessContainer[p])return true;return false};let total=0;equipment.forEach((entry,i)=>{if(exempt(i))return;const found=resolveBaseItem(entry.item,registry);if(!found)return;const entity=found.data;const w=coerceWeight(entity.weight);if(w===0)return;const qty=typeof entry.qty==="number"&&entry.qty>=0?entry.qty:1;total+=w*qty});return total}function computeSlotsAndAttacks(resolved,mods,profs,registry,warnings,proficiencyBonus,weaponAbilities=[],weaponMasteries=[],attunementFloor=0){var _a,_b,_c,_d,_e;const equippedSlots=assignSlots(resolved,registry,warnings);twoHandedShieldWarnings((_a=resolved.definition.equipment)!=null?_a:[],registry,warnings,resolved.infusions);const overrides=(_b=resolved.definition.overrides)!=null?_b:{};const acOut=computeAC(equippedSlots,resolved,mods,registry,warnings);const ctx=buildConditionContext(resolved,equippedSlots,registry);const attacks=computeAttacks(equippedSlots,(_c=resolved.definition.equipment)!=null?_c:[],mods,profs,registry,warnings,proficiencyBonus,ctx,weaponMasteries,weaponAbilities,resolved.infusions,pactWeaponIndexes(resolved,registry));return{ac:acOut.ac,acBreakdown:acOut.breakdown,acInformational:acOut.informational,attacks,equippedSlots,carriedWeight:computeCarriedWeight(resolved,registry),attunementUsed:((_d=resolved.definition.equipment)!=null?_d:[]).filter(e=>e.attuned).length,attunementLimit:(_e=overrides.attunement_limit)!=null?_e:Math.max(3,attunementFloor)}}export{emptyAppliedBonuses,computeAppliedBonuses,pactWeaponIndexes,isWeaponSlugProficient,buildUnarmedRow,buildFeatureAttackRows,computeSlotsAndAttacks};
1
+ import{qualifiedGrantCovers}from"./chunk-T55DELVL.js";import{classifyWeaponRange}from"./chunk-SEOASDO4.js";import{resolveContainment}from"./chunk-4E2GIWJE.js";import{foldsNow,pushDefenseGrant}from"./chunk-B2JSF2LL.js";import{normKey}from"./chunk-VTQ4RWEG.js";import{itemBenefitsActive,itemLabel,itemRowEffects}from"./chunk-DXJ5NKKB.js";import{WEAPON_DEFAULT_ACTION_COST,resolveEntryEntity}from"./chunk-E4E6YEN6.js";import{isActivatedSpeedItem}from"./chunk-DVUXUIPV.js";import{readNumericBonus}from"./chunk-NEMX7QGG.js";import{defaultSlotForType,effectiveArmor,effectiveWeapon,isItemEntity,isShieldArmor,isTwoHandedWeapon,slotAcTerms}from"./chunk-4IAMSRHD.js";import{resolveBaseItem}from"./chunk-PZ4L2EEG.js";import{bareEntitySlug}from"./chunk-63YJPWTM.js";var MASTERY={cleave:{label:"Cleave",description:"If you hit a creature with a melee attack roll using this weapon, you can make an attack roll with the weapon against a second creature within 5 feet of the first that is also within your reach. On a hit, the second creature takes the weapon's damage, but don't add your ability modifier to that damage unless it is negative. You can make this extra attack only once per turn.",gist:"hit a 2nd creature in reach"},graze:{label:"Graze",description:"If your attack roll with this weapon misses a creature, you can deal damage to that creature equal to the ability modifier you used to make the attack roll. This damage is the same type dealt by the weapon, and the damage can be increased only by increasing the ability modifier.",gist:"on miss: ability-mod damage"},nick:{label:"Nick",description:"When you make the extra attack of the Light property, you can make it as part of the Attack action instead of as a Bonus Action. You can make this extra attack only once per turn.",gist:"extra Light attack (no Bonus Action)"},push:{label:"Push",description:"If you hit a creature with this weapon, you can push the creature up to 10 feet straight away from yourself if it is Large or smaller.",gist:"on hit: pushed 10 ft."},sap:{label:"Sap",description:"If you hit a creature with this weapon, that creature has Disadvantage on its next attack roll before the start of your next turn.",gist:"on hit: target Disadvantage"},slow:{label:"Slow",description:"If you hit a creature with this weapon and deal damage, you can reduce its Speed by 10 feet until the start of your next turn. If the creature is hit more than once by weapons that have this property, the Speed reduction doesn't exceed 10 feet.",gist:"on hit: -10 ft. Speed"},topple:{label:"Topple",description:"If you hit a creature with this weapon, you can force the creature to make a Constitution saving throw (DC 8 plus the ability modifier used to make the attack roll and your Proficiency Bonus). On a failed save, the creature has the Prone condition.",gist:"on fail: Prone"},vex:{label:"Vex",description:"If you hit a creature with this weapon and deal damage, you have Advantage on your next attack roll against that creature before the end of your next turn.",gist:"on hit: you gain Advantage next"}};function masteryGist(slug){var _a;return(_a=MASTERY[slug])==null?void 0:_a.gist}function masteryDerived(slug,abilityMod,proficiencyBonus){if(slug==="topple")return{label:"Save DC",value:8+proficiencyBonus+abilityMod};if(slug==="graze")return{label:"On miss",value:abilityMod};return void 0}var ABILITY_KEYS=["str","dex","con","int","wis","cha"];function isAbilityKey(k){return ABILITY_KEYS.includes(k)}function emptyAppliedBonuses(){return{ability_bonuses:{},ability_statics:{},ability_terms:[],ability_static_terms:[],save_bonus:0,save_terms:[],speed_bonuses:{walk:0,fly:null,swim:0,climb:0},speed_walk_set:0,speed_walk_set_terms:[],speed_terms:[],spell_attack:0,spell_save_dc:0,defenses:{resistances:[],immunities:[],vulnerabilities:[],condition_immunities:[]},informational:[],senses:{darkvision:0,blindsight:0,tremorsense:0,truesight:0}}}function unwrapSlug(item){const m=item.match(/^\[\[(.+)\]\]$/);return m?m[1]:null}function unwrapClassSlug(maybeWiki){if(!maybeWiki)return"";const m=/^\[\[([^\]]+)\]\]$/.exec(maybeWiki);return(m?m[1]:maybeWiki).toLowerCase()}function buildConditionContext(resolved,equippedSlots,registry){var _a,_b;return{derived:{equippedSlots},classList:(_a=resolved.definition.class)!=null?_a:[],race:resolved.definition.race,subclasses:((_b=resolved.definition.class)!=null?_b:[]).map(c=>c.subclass).filter(s=>typeof s==="string"&&s.length>0).map(unwrapClassSlug),registry}}function pushApply(outcome,field,source,pool,onApply){if(!outcome)return;if(outcome.kind==="applied")onApply(outcome.value);else if(outcome.kind==="informational"){pool.push({field,source,value:outcome.value,conditions:outcome.conditions})}}function isOtherSpeedMode(mode){return mode==="fly"||mode==="swim"||mode==="climb"||mode==="burrow"}function computeAppliedBonuses(resolved,_profs,registry,warnings){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u;const out=emptyAppliedBonuses();const equipment=(_a=resolved.definition.equipment)!=null?_a:[];const ctx=buildConditionContext(resolved,{},registry);for(let index=0;index<equipment.length;index++){const entry=equipment[index];const{entity,entityType}=resolveEntryEntity(entry,index,registry,resolved.infusions);if(!entity){const slug=unwrapSlug(entry.item);if(slug&&entry.equipped&&!((_b=resolved.infusions)==null?void 0:_b.views.has(index)))warnings.push(`Equipped item [[${slug}]] not found in compendium.`);continue}if(!itemBenefitsActive(entry,entity,registry,(_c=resolved.infusions)==null?void 0:_c.views.get(index)))continue;if(entityType!=="item")continue;const item=entity;const label=itemLabel(entry,item);const grant=(bucket,values)=>{for(const v of values!=null?values:[])if(typeof v==="string")pushDefenseGrant(out.defenses[bucket],v,label,void 0,{index,name:label})};grant("resistances",item.resist);grant("immunities",item.immune);grant("vulnerabilities",item.vulnerable);grant("condition_immunities",item.condition_immune);grant("resistances",(_d=entry.overrides)==null?void 0:_d.resist);grant("immunities",(_e=entry.overrides)==null?void 0:_e.immune);grant("vulnerabilities",(_f=entry.overrides)==null?void 0:_f.vulnerable);grant("condition_immunities",(_g=entry.overrides)==null?void 0:_g.condition_immune);const gs=(_h=item.grants)==null?void 0:_h.senses;if(gs){if(typeof gs.darkvision==="number")out.senses.darkvision=Math.max(out.senses.darkvision,gs.darkvision);if(typeof gs.blindsight==="number")out.senses.blindsight=Math.max(out.senses.blindsight,gs.blindsight);if(typeof gs.tremorsense==="number")out.senses.tremorsense=Math.max(out.senses.tremorsense,gs.tremorsense);if(typeof gs.truesight==="number")out.senses.truesight=Math.max(out.senses.truesight,gs.truesight)}const floor=(_j=(_i=item.modify_speed)==null?void 0:_i.static)==null?void 0:_j.walk;if(typeof floor==="number"&&floor>0){out.speed_walk_set=Math.max(out.speed_walk_set,floor);out.speed_walk_set_terms.push({source:label,amount:floor})}const activatedSpeed=isActivatedSpeedItem(String((_k=item.slug)!=null?_k:"")||((_l=unwrapSlug(entry.item))!=null?_l:entry.item),item);const itemSpeed=(mode,kind,amount)=>{if(!activatedSpeed&&isOtherSpeedMode(mode))out.speed_terms.push({mode,kind,source:label,amount})};for(const[mode,n]of Object.entries((_n=(_m=item.modify_speed)==null?void 0:_m.static)!=null?_n:{}))if(typeof n==="number"&&n>0)itemSpeed(mode,"grant",n);for(const[mode,to]of Object.entries((_p=(_o=item.modify_speed)==null?void 0:_o.equal)!=null?_p:{}))if(to==="walk")itemSpeed(mode,"walk",0);const b=item.bonuses;if(!b)continue;const saveSource=(_r=(_q=entry.overrides)==null?void 0:_q.name)!=null?_r:item.name;pushApply(readNumericBonus(b.saving_throws,ctx),"saving_throws",saveSource,out.informational,v=>{out.save_bonus+=v;out.save_terms.push({source:saveSource,amount:v})});pushApply(readNumericBonus(b.spell_attack,ctx),"spell_attack",item.name,out.informational,v=>{out.spell_attack+=v});pushApply(readNumericBonus(b.spell_save_dc,ctx),"spell_save_dc",item.name,out.informational,v=>{out.spell_save_dc+=v});if((_s=b.ability_scores)==null?void 0:_s.bonus){for(const[k,v]of Object.entries(b.ability_scores.bonus)){if(!isAbilityKey(k))continue;pushApply(readNumericBonus(v,ctx),`ability_scores.bonus.${k}`,item.name,out.informational,val=>{var _a2,_b2;out.ability_bonuses[k]=((_a2=out.ability_bonuses[k])!=null?_a2:0)+val;((_b2=out.ability_terms)!=null?_b2:out.ability_terms=[]).push({ability:k,source:saveSource,amount:val})})}}if((_t=b.ability_scores)==null?void 0:_t.static){for(const[k,n]of Object.entries(b.ability_scores.static)){if(!isAbilityKey(k)||typeof n!=="number")continue;((_u=out.ability_static_terms)!=null?_u:out.ability_static_terms=[]).push({ability:k,source:saveSource,value:n});const prev=out.ability_statics[k];if(prev===void 0){out.ability_statics[k]=n}else{if(n!==prev){warnings.push(`Multiple static ${k.toUpperCase()} bonuses on equipped+attuned items; using highest (${Math.max(prev,n)}).`)}out.ability_statics[k]=Math.max(prev,n)}}}if(b.speed){pushApply(readNumericBonus(b.speed.walk,ctx),"speed.walk",item.name,out.informational,v=>{out.speed_bonuses.walk+=v;out.speed_terms.push({mode:"walk",kind:"bonus",source:label,amount:v})});if(b.speed.fly==="walk"){out.speed_bonuses.fly="walk";itemSpeed("fly","walk",0)}else{pushApply(readNumericBonus(b.speed.fly,ctx),"speed.fly",item.name,out.informational,v=>{const cur=out.speed_bonuses.fly;out.speed_bonuses.fly=(typeof cur==="number"?cur:0)+v;itemSpeed("fly","grant",v)})}pushApply(readNumericBonus(b.speed.swim,ctx),"speed.swim",item.name,out.informational,v=>{out.speed_bonuses.swim+=v;itemSpeed("swim","grant",v)});pushApply(readNumericBonus(b.speed.climb,ctx),"speed.climb",item.name,out.informational,v=>{out.speed_bonuses.climb+=v;itemSpeed("climb","grant",v)})}}return out}function assignSlots(resolved,registry,warnings){var _a;const slots={};const eq=(_a=resolved.definition.equipment)!=null?_a:[];for(let i=0;i<eq.length;i++){const entry=eq[i];if(!entry.equipped||!entry.slot)continue;const{entity,entityType}=resolveEntryEntity(entry,i,registry,resolved.infusions);if(slots[entry.slot])continue;const placed={index:i,entity,entityType,entry};slots[entry.slot]=placed}for(let i=0;i<eq.length;i++){const entry=eq[i];if(!entry.equipped||entry.slot)continue;const{entity,entityType}=resolveEntryEntity(entry,i,registry,resolved.infusions);if(!entity||!entityType)continue;const defaultSlot=defaultSlotForType(entityType,entity,registry);if(!defaultSlot){if(isItemEntity(entity)&&typeof entity.base_item==="string"&&entity.base_item.length>0){warnings.push(`Magic item "${entity.name}" base_item ${entity.base_item} did not resolve to a base weapon or armor; not slotted (AC/attack not applied).`)}continue}const placed={index:i,entity,entityType,entry};if(defaultSlot==="mainhand"){if(!slots.mainhand)slots.mainhand=placed;else if(!slots.offhand)slots.offhand=placed}else if(!slots[defaultSlot]){slots[defaultSlot]=placed}}return slots}function pickShield(equippedSlots,equipment,registry,infusions){const slotted=equippedSlots.shield;const slottedArmor=effectiveArmor(slotted==null?void 0:slotted.entity,registry);if(slotted&&slottedArmor&&isShieldArmor(slottedArmor)){return{index:slotted.index,shield:slottedArmor,entity:slotted.entity,entry:slotted.entry}}for(let i=0;i<equipment.length;i++){const entry=equipment[i];if(!entry.equipped)continue;const{entity}=resolveEntryEntity(entry,i,registry,infusions);const armor=effectiveArmor(entity,registry);if(armor&&isShieldArmor(armor))return{index:i,shield:armor,entity,entry}}return null}function twoHandedShieldWarnings(equipment,registry,warnings,infusions){const equipped=equipment.flatMap((entry,i)=>{if(!entry.equipped)return[];const{entity}=resolveEntryEntity(entry,i,registry,infusions);return[{entry,entity}]});const isShield=e=>{const armor=effectiveArmor(e.entity,registry);return!!armor&&isShieldArmor(armor)};for(const e of equipped){if(!e.entity||!isTwoHandedWeapon(e.entity,registry))continue;if(!equipped.some(other=>other!==e&&isShield(other)))continue;warnings.push(`${e.entity.name} is two-handed and a Shield is also equipped.`)}}function computeAC(equippedSlots,resolved,mods,registry,warnings){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j;const breakdown=[];const armorSlot=equippedSlots.armor;const armorEntity=(_a=armorSlot==null?void 0:armorSlot.entity)!=null?_a:null;const armor=effectiveArmor(armorEntity,registry);if(isItemEntity(armorEntity)&&typeof armorEntity.base_item==="string"&&!armor){warnings.push(`Magic armor "${armorEntity.name}" base_item ${armorEntity.base_item} did not resolve to a base armor; AC not applied.`)}const acCtx=buildConditionContext(resolved,equippedSlots,registry);const skip=new Set;const slotBonus=slot=>{var _a2,_b2;const view=slot?(_a2=resolved.infusions)==null?void 0:_a2.views.get(slot.index):void 0;if(!slot||!(view==null?void 0:view.entity)||!isItemEntity(view.entity)||!itemBenefitsActive(slot.entry,view.entity,registry,view))return 0;const out=readNumericBonus((_b2=view.entity.bonuses)==null?void 0:_b2.ac,acCtx);if((out==null?void 0:out.kind)!=="applied")return 0;skip.add(slot.index);return out.value};const armorTerms=slotAcTerms(armor,armorSlot==null?void 0:armorSlot.entry);let ac=10;if(armor&&armorTerms.armor!==null){const armorBase=armorTerms.armor+slotBonus(armorSlot);ac=armorBase;breakdown.push({source:(_b=armorEntity==null?void 0:armorEntity.name)!=null?_b:armor.name,amount:armorBase,kind:"armor"});if(armor.ac.add_dex){const dexCap=(_c=armor.ac.dex_max)!=null?_c:Number.POSITIVE_INFINITY;const dexAdd=Math.min(mods.dex,dexCap);ac+=dexAdd;const capped=mods.dex>dexCap;breakdown.push({source:`DEX modifier${capped?" (capped)":""}`,amount:dexAdd,kind:"dex"})}}else{ac=10+mods.dex;breakdown.push({source:"Base",amount:10,kind:"unarmored"});breakdown.push({source:"DEX modifier",amount:mods.dex,kind:"dex"})}const acBonus=armorTerms.override;if(acBonus!==0){ac+=acBonus;breakdown.push({source:`${(_d=armorEntity==null?void 0:armorEntity.name)!=null?_d:"Armor"} (override)`,amount:acBonus,kind:"override"})}const picked=pickShield(equippedSlots,(_e=resolved.definition.equipment)!=null?_e:[],registry,resolved.infusions);if(picked){const{shield,entity:shieldEntity}=picked;const shieldTerms=slotAcTerms(shield,picked.entry);const n=shieldTerms.armor+slotBonus(picked);ac+=n;breakdown.push({source:(_f=shieldEntity==null?void 0:shieldEntity.name)!=null?_f:shield.name,amount:n,kind:"shield"});const shieldAcBonus=shieldTerms.override;if(shieldAcBonus!==0){ac+=shieldAcBonus;breakdown.push({source:`${(_g=shieldEntity==null?void 0:shieldEntity.name)!=null?_g:shield.name} (override)`,amount:shieldAcBonus,kind:"shield"})}}const acInformational=[];const acEquipment=(_h=resolved.definition.equipment)!=null?_h:[];for(let index=0;index<acEquipment.length;index++){if(skip.has(index))continue;const entry=acEquipment[index];const{entity,entityType}=resolveEntryEntity(entry,index,registry,resolved.infusions);if(!entity||entityType!=="item")continue;if(!itemBenefitsActive(entry,entity,registry,(_i=resolved.infusions)==null?void 0:_i.views.get(index)))continue;const item=entity;const out=readNumericBonus((_j=item.bonuses)==null?void 0:_j.ac,acCtx);if(!out)continue;if(out.kind==="applied"){ac+=out.value;breakdown.push({source:item.name,amount:out.value,kind:"item"})}else if(out.kind==="informational"){acInformational.push({field:"ac",source:item.name,value:out.value,conditions:out.conditions})}}return{ac,breakdown,informational:acInformational}}function hasProperty(weapon,prop){return weapon.properties.some(p=>p===prop)}function attackAbility(weapon,mods,weaponAbilities){const modes=classifyWeaponRange(weapon);const finesse=hasProperty(weapon,"finesse");if(modes.melee){const scoped=weaponAbilities.find(o2=>{var _a;return(_a=o2.weaponSlugs)==null?void 0:_a.includes(bareEntitySlug(weapon.slug))});const glob=weaponAbilities.find(o2=>!o2.weaponSlugs);const o=scoped!=null?scoped:glob;if(o)return o.ability;if(finesse)return mods.dex>=mods.str?"dex":"str";return"str"}return finesse&&mods.str>mods.dex?"str":"dex"}function pactScopedAbilities(overrides,pactPicked,isPact){if(!overrides.some(o=>o.pactWeapon))return overrides;return overrides.flatMap(o=>{if(!o.pactWeapon)return[o];return!pactPicked||isPact?[{ability:o.ability}]:[]})}function pactWeaponIndexes(resolved,registry){var _a;const pick=resolved.pactWeapon;if(!pick)return null;const out=new Set;const bare=bareEntitySlug(pick);((_a=resolved.definition.equipment)!=null?_a:[]).forEach((entry,i)=>{var _a2;if(typeof entry.item!=="string")return;const slugs=[unwrapSlug(entry.item),registry?(_a2=resolveBaseItem(entry.item,registry))==null?void 0:_a2.slug:void 0];if(slugs.some(s=>!!s&&(s===pick||bareEntitySlug(s)===bare)))out.add(i)});return out.size?out:null}function isWeaponSlugProficient(weapon,weaponSlug,profs){const wp=profs.weapons;if(wp.specific.some(e=>e===weaponSlug||normKey(e)===normKey(weapon.name)))return true;if(wp.specific.some(e=>qualifiedGrantCovers(e,weapon)))return true;const cat=weapon.category;if(typeof cat==="string"){if(/^simple\b/.test(cat)&&wp.categories.includes("simple"))return true;if(/^martial\b/.test(cat)&&wp.categories.includes("martial"))return true;if(wp.categories.includes(cat))return true}return false}function magicBonusesForWeaponEntry(entry,registry,ctx,index,infusions){var _a,_b,_c,_d;const{entity}=resolveEntryEntity(entry,index,registry,infusions);const ovr=(_a=entry.overrides)!=null?_a:{};const entryAttack=typeof ovr.bonus==="number"?ovr.bonus:0;const entryDamage=typeof ovr.damage_bonus==="number"?ovr.damage_bonus:0;const extra=typeof ovr.extra_damage==="string"?ovr.extra_damage:void 0;let itemAttack=0;let itemDamage=0;let sourceName;let itemName;let damageTypeOverride;let propertiesOverride;const informational=[];let itemRiders=[];let critRange;const conditionalCrits=[];if(entity&&isItemEntity(entity)){sourceName=entity.name;itemName=entity.name;damageTypeOverride=typeof entity.damage_type==="string"&&entity.damage_type.length>0?entity.damage_type:void 0;propertiesOverride=Array.isArray(entity.properties)&&entity.properties.length>0?entity.properties:void 0}if(entity&&isItemEntity(entity)&&itemBenefitsActive(entry,entity,registry,infusions==null?void 0:infusions.views.get(index))){const b=entity.bonuses;const atkOut=readNumericBonus(b==null?void 0:b.weapon_attack,ctx);const dmgOut=readNumericBonus(b==null?void 0:b.weapon_damage,ctx);if((atkOut==null?void 0:atkOut.kind)==="applied")itemAttack=atkOut.value;else if((atkOut==null?void 0:atkOut.kind)==="informational")informational.push({field:"weapon_attack",source:entity.name,value:atkOut.value,conditions:atkOut.conditions});if((dmgOut==null?void 0:dmgOut.kind)==="applied")itemDamage=dmgOut.value;else if((dmgOut==null?void 0:dmgOut.kind)==="informational")informational.push({field:"weapon_damage",source:entity.name,value:dmgOut.value,conditions:dmgOut.conditions});itemRiders=Array.isArray(entity.damage_riders)?entity.damage_riders.filter(r=>{var _a2;return((_a2=r.applies_to)!=null?_a2:"weapon")!=="spell"}).map(r=>({amount:r.amount,damage_type:r.damage_type,source:entity.name,...r.condition?{condition:r.condition}:{}})):[];for(const eff of itemRowEffects(entity)){if(eff.kind==="damage-bonus"&&((_b=eff.applies_to)!=null?_b:"weapon")!=="spell"){itemRiders.push({amount:eff.amount,damage_type:eff.damage_type,source:entity.name,...eff.condition?{condition:eff.condition}:{}})}else if(eff.kind==="crit-range"&&((_c=eff.applies_to)!=null?_c:"weapon")!=="spell"){if((_d=eff.condition)==null?void 0:_d.trim())conditionalCrits.push({minRoll:eff.min_roll,condition:eff.condition.trim(),source:entity.name});else critRange=Math.min(critRange!=null?critRange:20,eff.min_roll)}}}return{...critRange!==void 0&&critRange<20?{critRange}:{},...conditionalCrits.length?{conditionalCrits}:{},atk:itemAttack+entryAttack,dmg:itemDamage+entryDamage,extra,sourceName,itemName,damageTypeOverride,propertiesOverride,informational,riders:itemRiders}}function buildAttackRow(args){var _a,_b,_c,_d;const{id,name,weapon,baseDice,ability,mods,proficient,proficiencyBonus,magic,weaponMasteries}=args;const abilityMod=mods[ability];const pb=proficient?proficiencyBonus:0;const toHit=abilityMod+pb+magic.atk;const dmgFlat=abilityMod+magic.dmg;const formatDice=dice=>`${dice}${dmgFlat>=0?"+":""}${dmgFlat}`.replace(/\+0$/,"");const damageDice=formatDice(baseDice);const magicSource=magic.sourceName?`${magic.sourceName} bonus`:"Magic weapon";const toHitBreakdown=[{source:`${ability.toUpperCase()} modifier`,amount:abilityMod,kind:"ability"},{source:"Proficiency bonus",amount:proficient?proficiencyBonus:0,kind:"ability"},{source:magicSource,amount:magic.atk,kind:"item"}];const damageBreakdown=[{source:"Base damage",amount:0,kind:"ability"},{source:`${ability.toUpperCase()} modifier`,amount:abilityMod,kind:"ability"},{source:magicSource,amount:magic.dmg,kind:"item"}];const modes=classifyWeaponRange(weapon);const fmtRanged=r=>r.long>r.normal?`${r.normal}/${r.long} ft.`:`${r.normal} ft.`;const range=modes.melee?`${modes.melee.reach} ft.`:modes.ranged?fmtRanged(modes.ranged):void 0;const thrownRange=modes.melee&&modes.ranged?fmtRanged(modes.ranged):void 0;const stringProps=weapon.properties.filter(p=>typeof p==="string");const finalProps=(_a=magic.propertiesOverride)!=null?_a:stringProps;const row={id,name,...range!==void 0?{range}:{},...thrownRange!==void 0?{thrownRange}:{},toHit,damageDice,damageType:(_b=magic.damageTypeOverride)!=null?_b:weapon.damage.type,...(()=>{const riders=[...magic.riders,...magic.extra?[{amount:magic.extra}]:[]];return riders.length?{damageRiders:riders}:{}})(),weaponCategory:modes.melee?"melee":"ranged",properties:finalProps,proficient,breakdown:{toHit:toHitBreakdown,damage:damageBreakdown},informational:args.magic.informational.length>0?args.magic.informational:void 0,slotKey:args.slotKey,subLabel:formatWeaponSubLabel(weapon,finalProps,modes),actionCost:args.actionCost,versatile:args.versatileDice?{damageDice:formatDice(args.versatileDice)}:void 0,...magic.critRange!==void 0?{critRange:magic.critRange}:{},...((_c=magic.conditionalCrits)==null?void 0:_c.length)?{conditionalCrits:magic.conditionalCrits}:{}};const mSlug=(_d=weapon.mastery)==null?void 0:_d[0];if(mSlug&&proficient&&weaponMasteries.includes(bareEntitySlug(weapon.slug))){const g=MASTERY[mSlug];if(g){const derived=masteryDerived(mSlug,mods[ability],proficiencyBonus);row.mastery={slug:mSlug,label:g.label,description:g.description,gist:masteryGist(mSlug),...derived?{derived}:{}}}}return row}function buildUnarmedRow(mods,proficiencyBonus,spec){var _a;const strike=unarmedStrikeNumbers(mods,proficiencyBonus,["str",...(_a=spec==null?void 0:spec.abilities)!=null?_a:[]],spec==null?void 0:spec.dice);return{id:"unarmed-strike",name:"Unarmed Strike",unarmed:true,range:"5 ft.",...strike,damageType:"bludgeoning",properties:[],proficient:true,subLabel:"Unarmed",actionCost:"action"}}function unarmedStrikeNumbers(mods,proficiencyBonus,candidates,dice){var _a;let ability=(_a=candidates[0])!=null?_a:"str";for(const ab of candidates)if(mods[ab]>=mods[ability])ability=ab;const abilityMod=mods[ability];const flat=`${abilityMod>=0?"+":""}${abilityMod}`.replace(/^\+0$/,"");const label=`${ability.toUpperCase()} modifier`;return{toHit:abilityMod+proficiencyBonus,damageDice:dice?`${dice}${flat}`:String(Math.max(0,1+abilityMod)),breakdown:{toHit:[{source:label,amount:abilityMod,kind:"ability"},{source:"Proficiency bonus",amount:proficiencyBonus,kind:"ability"}],damage:[{source:"Base damage",amount:dice?0:1,kind:"ability"},{source:label,amount:abilityMod,kind:"ability"}]}}}function buildFeatureAttackRows(resolved,mods,profs,proficiencyBonus,weaponAbilities=[],opts={}){var _a,_b,_c,_d;const rows=[];const abilities=weaponAbilities.filter(o=>!o.pactWeapon);const active=new Set((_a=opts.activeBuffs)!=null?_a:[]);for(const rf of(_b=resolved.features)!=null?_b:[]){if(rf.renderSuppressed||rf.buildOnly||!foldsNow(rf,active))continue;const featureId=(_c=rf.feature.id)!=null?_c:rf.feature.name;((_d=rf.feature.attacks)!=null?_d:[]).forEach((a,n)=>{var _a2,_b2,_c2,_d2,_e,_f,_g,_h;const id=`feature-attack:${rf.source.kind}:${rf.source.slug}:${featureId}:${n}`;if(!a.weapon_category&&a.unarmed===true){const natural=buildNaturalWeaponRow(a,id,mods,proficiencyBonus,(_a2=opts.unarmedAbilities)!=null?_a2:[]);if(natural)rows.push({...natural,grantedBy:rf.feature.name});return}if(!a.weapon_category||a.type!=="melee"&&a.type!=="ranged"||typeof a.damage!=="string"||!a.damage.trim())return;const long=(_d2=(_b2=a.range)==null?void 0:_b2.long)!=null?_d2:(_c2=a.range)==null?void 0:_c2.normal;const weapon={name:a.name,slug:`feature-attack_${featureId}_${n}`,category:`${a.weapon_category}-${a.type}`,damage:{dice:a.damage.trim(),type:(_e=a.damage_type)!=null?_e:""},properties:((_f=a.properties)!=null?_f:[]).map(p=>p.trim().toLowerCase()),...((_g=a.range)==null?void 0:_g.normal)!==void 0&&long!==void 0?{range:{normal:a.range.normal,long}}:{},...a.mastery?{mastery:[a.mastery.trim().toLowerCase()]}:{}};const proficient=isWeaponSlugProficient(weapon,weapon.slug,profs);const row=buildAttackRow({id,name:a.name,weapon,baseDice:weapon.damage.dice,ability:attackAbility(weapon,mods,abilities),mods,proficient,proficiencyBonus,magic:{atk:0,dmg:0,informational:[],riders:[]},actionCost:(_h=a.action)!=null?_h:WEAPON_DEFAULT_ACTION_COST,weaponMasteries:a.mastery?[bareEntitySlug(weapon.slug)]:[]});row.grantedBy=rf.feature.name;rows.push(row)})}return rows}function buildNaturalWeaponRow(a,id,mods,proficiencyBonus,unarmedAbilities){var _a,_b,_c,_d;const dice=typeof a.damage==="string"?a.damage.trim():"";if(a.type!=="melee"||!dice)return null;const own=a.ability===void 0?["str"]:Array.isArray(a.ability)?[...a.ability]:[a.ability];return{id,name:a.name,naturalWeapon:true,range:`${(_b=(_a=a.range)==null?void 0:_a.reach)!=null?_b:5} ft.`,...unarmedStrikeNumbers(mods,proficiencyBonus,[...own,...unarmedAbilities],dice),damageType:((_c=a.damage_type)==null?void 0:_c.trim())||"bludgeoning",properties:[],proficient:true,subLabel:"Unarmed",actionCost:(_d=a.action)!=null?_d:"action"}}function humanizeWeaponToken(s){return s.replace(/[-_]/g," ").replace(/(^|[\s(])\w/g,c=>c.toUpperCase())}function formatWeaponSubLabel(weapon,properties,modes){const parts=[];if(weapon.category){const cat=modes.melee&&/ranged/.test(weapon.category)?weapon.category.replace("ranged","melee"):weapon.category;parts.push(humanizeWeaponToken(cat))}if(properties.length>0)parts.push(properties.map(humanizeWeaponToken).join(", "));return parts.join(" \xB7 ")}function computeAttacks(equippedSlots,equipment,mods,profs,registry,warnings,proficiencyBonus,ctx,weaponMasteries,weaponAbilities=[],infusions,pactIndexes=null){var _a,_b;const rows=[];const rowFor=(index,entry,weapon,slotKey,versatileDice)=>{var _a2,_b2,_c,_d,_e;const slugFromEntry=(_a2=unwrapSlug(entry.item))!=null?_a2:weapon.slug;const proficient=isWeaponSlugProficient(weapon,slugFromEntry,profs)||isWeaponSlugProficient(weapon,weapon.slug,profs);if(!proficient){warnings.push(`Character not proficient with ${weapon.name}; proficiency bonus excluded.`)}const isPact=(pactIndexes==null?void 0:pactIndexes.has(index))===true;const ability=attackAbility(weapon,mods,pactScopedAbilities(weaponAbilities,pactIndexes!==null,isPact));const magic=magicBonusesForWeaponEntry(entry,registry,ctx,index,infusions);const ovr=(_b2=entry.overrides)!=null?_b2:{};const row=buildAttackRow({id:`${index}:standard`,name:(_d=(_c=ovr.name)!=null?_c:magic.itemName)!=null?_d:weapon.name,weapon,baseDice:weapon.damage.dice,ability,mods,proficient,proficiencyBonus,magic,slotKey,actionCost:(_e=ovr.action)!=null?_e:WEAPON_DEFAULT_ACTION_COST,versatileDice,weaponMasteries});if(isPact)row.pactWeapon=true;return row};const handedSlots=[{key:"mainhand",placed:equippedSlots.mainhand},{key:"offhand",placed:equippedSlots.offhand}];for(const{key,placed}of handedSlots){if(!placed)continue;const{entity,entry}=placed;if(!entity)continue;const weapon=effectiveWeapon(entity,registry);if(!weapon){if(isItemEntity(entity)&&typeof entity.base_item==="string"&&!resolveBaseItem(entity.base_item,registry)){warnings.push(`Magic weapon ${entity.name} references missing base_item ${entity.base_item}.`)}continue}const versatileDice=key==="mainhand"&&hasProperty(weapon,"versatile")&&typeof weapon.damage.versatile_dice==="string"&&!equippedSlots.offhand?weapon.damage.versatile_dice:void 0;rows.push(rowFor(placed.index,entry,weapon,key,versatileDice))}const handIndex=new Set([(_a=equippedSlots.mainhand)==null?void 0:_a.index,(_b=equippedSlots.offhand)==null?void 0:_b.index]);equipment.forEach((entry,index)=>{if(!entry.equipped||handIndex.has(index))return;const{entity}=resolveEntryEntity(entry,index,registry,infusions);const weapon=effectiveWeapon(entity,registry);if(!weapon)return;rows.push(rowFor(index,entry,weapon))});return rows}function coerceWeight(raw){if(typeof raw==="number"&&Number.isFinite(raw)&&raw>=0)return raw;if(typeof raw==="string"){const n=Number.parseFloat(raw);if(Number.isFinite(n)&&n>=0)return n}return 0}function computeCarriedWeight(resolved,registry){var _a;const equipment=(_a=resolved.definition.equipment)!=null?_a:[];const view=resolveContainment(equipment,registry);const weightlessContainer=equipment.map(entry=>{var _a2,_b,_c;const data=(_a2=resolveBaseItem(entry.item,registry))==null?void 0:_a2.data;return((_c=(_b=data==null?void 0:data.container)==null?void 0:_b.capacity)==null?void 0:_c.weightless)===true});const exempt=i=>{for(let p=view.parentOf[i];p!==null;p=view.parentOf[p])if(weightlessContainer[p])return true;return false};let total=0;equipment.forEach((entry,i)=>{if(exempt(i))return;const found=resolveBaseItem(entry.item,registry);if(!found)return;const entity=found.data;const w=coerceWeight(entity.weight);if(w===0)return;const qty=typeof entry.qty==="number"&&entry.qty>=0?entry.qty:1;total+=w*qty});return total}function computeSlotsAndAttacks(resolved,mods,profs,registry,warnings,proficiencyBonus,weaponAbilities=[],weaponMasteries=[],attunementFloor=0){var _a,_b,_c,_d,_e;const equippedSlots=assignSlots(resolved,registry,warnings);twoHandedShieldWarnings((_a=resolved.definition.equipment)!=null?_a:[],registry,warnings,resolved.infusions);const overrides=(_b=resolved.definition.overrides)!=null?_b:{};const acOut=computeAC(equippedSlots,resolved,mods,registry,warnings);const ctx=buildConditionContext(resolved,equippedSlots,registry);const attacks=computeAttacks(equippedSlots,(_c=resolved.definition.equipment)!=null?_c:[],mods,profs,registry,warnings,proficiencyBonus,ctx,weaponMasteries,weaponAbilities,resolved.infusions,pactWeaponIndexes(resolved,registry));return{ac:acOut.ac,acBreakdown:acOut.breakdown,acInformational:acOut.informational,attacks,equippedSlots,carriedWeight:computeCarriedWeight(resolved,registry),attunementUsed:((_d=resolved.definition.equipment)!=null?_d:[]).filter(e=>e.attuned).length,attunementLimit:(_e=overrides.attunement_limit)!=null?_e:Math.max(3,attunementFloor)}}export{emptyAppliedBonuses,computeAppliedBonuses,pactWeaponIndexes,isWeaponSlugProficient,buildUnarmedRow,buildFeatureAttackRows,computeSlotsAndAttacks};
@@ -1 +1 @@
1
- import{__categoryToEntitySelectForTest,__matchesFilterForTest,buildDecisionLedger,collectChosenAbilityPoints,collectChosenProficiencies,collectProficiencyReplacements,collectRuleProficiencySources,computeEffectiveProficiencies,computeSuppressedProficiencies}from"../chunk-2GZM7FCD.js";import"../chunk-2EOGK6R6.js";import"../chunk-4AJYEWFQ.js";import"../chunk-RQZCGXUZ.js";import"../chunk-CLZRWPWT.js";import"../chunk-4FTTUZXM.js";import"../chunk-FOLHTMSC.js";import"../chunk-4JEF3CET.js";import"../chunk-VTQ4RWEG.js";import"../chunk-MMDUUEFA.js";import"../chunk-J27N3KUE.js";import"../chunk-RR26E7LH.js";import"../chunk-UBUKCRZ3.js";import"../chunk-2OVDSMPY.js";import"../chunk-PFQPP77Q.js";import"../chunk-QVWT67WA.js";import"../chunk-E4E6YEN6.js";import"../chunk-CMIEZQL4.js";import"../chunk-O776WL7O.js";import"../chunk-CSTAQQGX.js";import"../chunk-3LWOVRLA.js";import"../chunk-DVUXUIPV.js";import"../chunk-YGH7S5ZF.js";import"../chunk-4IAMSRHD.js";import"../chunk-3QQOATV3.js";import"../chunk-DZITM5AG.js";import"../chunk-PZ4L2EEG.js";import"../chunk-QMEKQTUT.js";import"../chunk-EAARMPCW.js";import"../chunk-CAPYNIGK.js";import{wikilinkTailSlug}from"../chunk-63YJPWTM.js";import"../chunk-4KVVAENP.js";import"../chunk-7EL3GWWJ.js";import"../chunk-BREHZNTL.js";import"../chunk-7FPQJDFD.js";import"../chunk-EVT7MGAC.js";import"../chunk-S5UCI27C.js";import"../chunk-EON7T2SN.js";import"../chunk-I26FHSI6.js";export{__categoryToEntitySelectForTest,__matchesFilterForTest,buildDecisionLedger,collectChosenAbilityPoints,collectChosenProficiencies,collectProficiencyReplacements,collectRuleProficiencySources,computeEffectiveProficiencies,computeSuppressedProficiencies,wikilinkTailSlug};
1
+ import{__categoryToEntitySelectForTest,__matchesFilterForTest,buildDecisionLedger,collectChosenAbilityPoints,collectChosenProficiencies,collectProficiencyReplacements,collectRuleProficiencySources,computeEffectiveProficiencies,computeSuppressedProficiencies}from"../chunk-JSI2G6LE.js";import"../chunk-2EOGK6R6.js";import"../chunk-4AJYEWFQ.js";import"../chunk-RQZCGXUZ.js";import"../chunk-CLZRWPWT.js";import"../chunk-B2JSF2LL.js";import"../chunk-FOLHTMSC.js";import"../chunk-4JEF3CET.js";import"../chunk-VTQ4RWEG.js";import"../chunk-DXJ5NKKB.js";import"../chunk-J27N3KUE.js";import"../chunk-RR26E7LH.js";import"../chunk-UBUKCRZ3.js";import"../chunk-2OVDSMPY.js";import"../chunk-PFQPP77Q.js";import"../chunk-QVWT67WA.js";import"../chunk-E4E6YEN6.js";import"../chunk-CMIEZQL4.js";import"../chunk-O776WL7O.js";import"../chunk-CSTAQQGX.js";import"../chunk-3LWOVRLA.js";import"../chunk-DVUXUIPV.js";import"../chunk-YGH7S5ZF.js";import"../chunk-4IAMSRHD.js";import"../chunk-3QQOATV3.js";import"../chunk-DZITM5AG.js";import"../chunk-PZ4L2EEG.js";import"../chunk-QMEKQTUT.js";import"../chunk-EAARMPCW.js";import"../chunk-CAPYNIGK.js";import{wikilinkTailSlug}from"../chunk-63YJPWTM.js";import"../chunk-4KVVAENP.js";import"../chunk-7EL3GWWJ.js";import"../chunk-BREHZNTL.js";import"../chunk-7FPQJDFD.js";import"../chunk-EVT7MGAC.js";import"../chunk-S5UCI27C.js";import"../chunk-EON7T2SN.js";import"../chunk-I26FHSI6.js";export{__categoryToEntitySelectForTest,__matchesFilterForTest,buildDecisionLedger,collectChosenAbilityPoints,collectChosenProficiencies,collectProficiencyReplacements,collectRuleProficiencySources,computeEffectiveProficiencies,computeSuppressedProficiencies,wikilinkTailSlug};
@@ -1 +1 @@
1
- import{buildFeatureAttackRows,buildUnarmedRow,computeAppliedBonuses,computeSlotsAndAttacks,emptyAppliedBonuses,isWeaponSlugProficient,pactWeaponIndexes}from"../chunk-KZFTTAFN.js";import"../chunk-T55DELVL.js";import"../chunk-SEOASDO4.js";import"../chunk-4E2GIWJE.js";import"../chunk-4FTTUZXM.js";import"../chunk-FOLHTMSC.js";import"../chunk-4JEF3CET.js";import"../chunk-VTQ4RWEG.js";import"../chunk-MMDUUEFA.js";import"../chunk-J27N3KUE.js";import"../chunk-E4E6YEN6.js";import"../chunk-CMIEZQL4.js";import"../chunk-O776WL7O.js";import"../chunk-CSTAQQGX.js";import"../chunk-DVUXUIPV.js";import"../chunk-YGH7S5ZF.js";import"../chunk-NEMX7QGG.js";import"../chunk-56JK6VCL.js";import"../chunk-4IAMSRHD.js";import"../chunk-3QQOATV3.js";import"../chunk-DZITM5AG.js";import"../chunk-PZ4L2EEG.js";import"../chunk-QMEKQTUT.js";import"../chunk-63YJPWTM.js";import"../chunk-BREHZNTL.js";import"../chunk-7FPQJDFD.js";import"../chunk-EVT7MGAC.js";import"../chunk-EON7T2SN.js";export{buildFeatureAttackRows,buildUnarmedRow,computeAppliedBonuses,computeSlotsAndAttacks,emptyAppliedBonuses,isWeaponSlugProficient,pactWeaponIndexes};
1
+ import{buildFeatureAttackRows,buildUnarmedRow,computeAppliedBonuses,computeSlotsAndAttacks,emptyAppliedBonuses,isWeaponSlugProficient,pactWeaponIndexes}from"../chunk-YWKC2LJY.js";import"../chunk-T55DELVL.js";import"../chunk-SEOASDO4.js";import"../chunk-4E2GIWJE.js";import"../chunk-B2JSF2LL.js";import"../chunk-FOLHTMSC.js";import"../chunk-4JEF3CET.js";import"../chunk-VTQ4RWEG.js";import"../chunk-DXJ5NKKB.js";import"../chunk-J27N3KUE.js";import"../chunk-E4E6YEN6.js";import"../chunk-CMIEZQL4.js";import"../chunk-O776WL7O.js";import"../chunk-CSTAQQGX.js";import"../chunk-DVUXUIPV.js";import"../chunk-YGH7S5ZF.js";import"../chunk-NEMX7QGG.js";import"../chunk-56JK6VCL.js";import"../chunk-4IAMSRHD.js";import"../chunk-3QQOATV3.js";import"../chunk-DZITM5AG.js";import"../chunk-PZ4L2EEG.js";import"../chunk-QMEKQTUT.js";import"../chunk-63YJPWTM.js";import"../chunk-BREHZNTL.js";import"../chunk-7FPQJDFD.js";import"../chunk-EVT7MGAC.js";import"../chunk-EON7T2SN.js";export{buildFeatureAttackRows,buildUnarmedRow,computeAppliedBonuses,computeSlotsAndAttacks,emptyAppliedBonuses,isWeaponSlugProficient,pactWeaponIndexes};
@@ -1,6 +1,6 @@
1
1
  import type { FeatureEffect, SenseType, SpeedGateWord, WeaponScope } from "@archivist-gg/dnd5e/types/feature-effect";
2
2
  import type { Ability } from "@archivist-gg/dnd5e";
3
- import type { ConditionalCrit, DamageRider, DamageRollOption, DefenseGrant, DefenseItemSource, FeatureSource, SpeedMode, ResolvedCharacter, ResolvedFeature, RollModifierEntry, SaveOutcomeEntry, SpellDamageRider } from "./pc.types.js";
3
+ import type { ConditionalCrit, DamageRider, DamageRollOption, DefenseGrant, DefenseItemSource, ExtraAttackSource, FeatureSource, SpeedMode, ResolvedCharacter, ResolvedFeature, RollModifierEntry, SaveOutcomeEntry, SpellDamageRider } from "./pc.types.js";
4
4
  export interface WeaponAbilityOverride {
5
5
  ability: Ability;
6
6
  weaponSlugs?: string[];
@@ -90,9 +90,11 @@ export interface FeatureEffectTotals {
90
90
  critRange: number;
91
91
  conditionalCrits: ConditionalCrit[];
92
92
  extraAttack: number;
93
+ extraAttackSource?: ExtraAttackSource;
93
94
  scopedExtraAttacks: Array<{
94
95
  count: number;
95
96
  scope: WeaponScope[];
97
+ source?: ExtraAttackSource;
96
98
  }>;
97
99
  attackNotes: string[];
98
100
  damageBonuses: DamageRider[];
@@ -1 +1 @@
1
- import{assembleEffectFeatures,classifyProficiencyEffect,collectProficiencyEffectGrants,computeFeatureEffects,emptyFeatureEffectTotals,foldsNow,foldsOnSelf,mergeDefenseItems,pushDefenseGrant,selfEffectsOf}from"../chunk-4FTTUZXM.js";import"../chunk-FOLHTMSC.js";import"../chunk-4JEF3CET.js";import"../chunk-VTQ4RWEG.js";import"../chunk-J27N3KUE.js";import"../chunk-E4E6YEN6.js";import"../chunk-CMIEZQL4.js";import"../chunk-O776WL7O.js";import"../chunk-CSTAQQGX.js";import"../chunk-DVUXUIPV.js";import"../chunk-YGH7S5ZF.js";import"../chunk-4IAMSRHD.js";import"../chunk-3QQOATV3.js";import"../chunk-DZITM5AG.js";import"../chunk-PZ4L2EEG.js";import"../chunk-QMEKQTUT.js";import"../chunk-63YJPWTM.js";import"../chunk-BREHZNTL.js";import"../chunk-7FPQJDFD.js";import"../chunk-EVT7MGAC.js";export{assembleEffectFeatures,classifyProficiencyEffect,collectProficiencyEffectGrants,computeFeatureEffects,emptyFeatureEffectTotals,foldsNow,foldsOnSelf,mergeDefenseItems,pushDefenseGrant,selfEffectsOf};
1
+ import{assembleEffectFeatures,classifyProficiencyEffect,collectProficiencyEffectGrants,computeFeatureEffects,emptyFeatureEffectTotals,foldsNow,foldsOnSelf,mergeDefenseItems,pushDefenseGrant,selfEffectsOf}from"../chunk-B2JSF2LL.js";import"../chunk-FOLHTMSC.js";import"../chunk-4JEF3CET.js";import"../chunk-VTQ4RWEG.js";import"../chunk-J27N3KUE.js";import"../chunk-E4E6YEN6.js";import"../chunk-CMIEZQL4.js";import"../chunk-O776WL7O.js";import"../chunk-CSTAQQGX.js";import"../chunk-DVUXUIPV.js";import"../chunk-YGH7S5ZF.js";import"../chunk-4IAMSRHD.js";import"../chunk-3QQOATV3.js";import"../chunk-DZITM5AG.js";import"../chunk-PZ4L2EEG.js";import"../chunk-QMEKQTUT.js";import"../chunk-63YJPWTM.js";import"../chunk-BREHZNTL.js";import"../chunk-7FPQJDFD.js";import"../chunk-EVT7MGAC.js";export{assembleEffectFeatures,classifyProficiencyEffect,collectProficiencyEffectGrants,computeFeatureEffects,emptyFeatureEffectTotals,foldsNow,foldsOnSelf,mergeDefenseItems,pushDefenseGrant,selfEffectsOf};
@@ -11,6 +11,7 @@ export declare function itemLabel(entry: EquipmentEntry, entity: {
11
11
  name?: unknown;
12
12
  } | null): string;
13
13
  export declare const ITEM_ROW_KINDS: ReadonlySet<FeatureEffect["kind"]>;
14
+ export declare function restatesItemGate(text: string | undefined): boolean;
14
15
  export declare function readItemEffects(entity: unknown): {
15
16
  effects: FeatureEffect[];
16
17
  invalid: string[];
@@ -1 +1 @@
1
- import{ITEM_ROW_KINDS,buildItemFeatures,itemBenefitsActive,itemLabel,itemRowEffects,itemSpellCastable,readItemEffects}from"../chunk-MMDUUEFA.js";import"../chunk-E4E6YEN6.js";import"../chunk-CMIEZQL4.js";import"../chunk-O776WL7O.js";import"../chunk-CSTAQQGX.js";import"../chunk-DVUXUIPV.js";import"../chunk-YGH7S5ZF.js";import"../chunk-4IAMSRHD.js";import"../chunk-DZITM5AG.js";import"../chunk-PZ4L2EEG.js";import"../chunk-QMEKQTUT.js";import"../chunk-63YJPWTM.js";import"../chunk-BREHZNTL.js";import"../chunk-7FPQJDFD.js";import"../chunk-EVT7MGAC.js";import"../chunk-EON7T2SN.js";export{ITEM_ROW_KINDS,buildItemFeatures,itemBenefitsActive,itemLabel,itemRowEffects,itemSpellCastable,readItemEffects};
1
+ import{ITEM_ROW_KINDS,buildItemFeatures,itemBenefitsActive,itemLabel,itemRowEffects,itemSpellCastable,readItemEffects,restatesItemGate}from"../chunk-DXJ5NKKB.js";import"../chunk-E4E6YEN6.js";import"../chunk-CMIEZQL4.js";import"../chunk-O776WL7O.js";import"../chunk-CSTAQQGX.js";import"../chunk-DVUXUIPV.js";import"../chunk-YGH7S5ZF.js";import"../chunk-4IAMSRHD.js";import"../chunk-DZITM5AG.js";import"../chunk-PZ4L2EEG.js";import"../chunk-QMEKQTUT.js";import"../chunk-63YJPWTM.js";import"../chunk-BREHZNTL.js";import"../chunk-7FPQJDFD.js";import"../chunk-EVT7MGAC.js";import"../chunk-EON7T2SN.js";export{ITEM_ROW_KINDS,buildItemFeatures,itemBenefitsActive,itemLabel,itemRowEffects,itemSpellCastable,readItemEffects,restatesItemGate};
@@ -1 +1 @@
1
- import{qualifiedGrantCovers}from"../chunk-T55DELVL.js";import"../chunk-SEOASDO4.js";import{collectChosenProficiencies,collectProficiencyGrants,computeEffectiveProficiencies,computeSuppressedProficiencies}from"../chunk-2GZM7FCD.js";import"../chunk-2EOGK6R6.js";import"../chunk-4AJYEWFQ.js";import"../chunk-RQZCGXUZ.js";import"../chunk-CLZRWPWT.js";import"../chunk-4FTTUZXM.js";import"../chunk-FOLHTMSC.js";import"../chunk-4JEF3CET.js";import{normKey,proficiencyKey,proficiencyLabel,toProfSlug,weaponProfKey}from"../chunk-VTQ4RWEG.js";import"../chunk-MMDUUEFA.js";import"../chunk-J27N3KUE.js";import"../chunk-RR26E7LH.js";import"../chunk-UBUKCRZ3.js";import"../chunk-2OVDSMPY.js";import"../chunk-PFQPP77Q.js";import"../chunk-QVWT67WA.js";import"../chunk-E4E6YEN6.js";import"../chunk-CMIEZQL4.js";import"../chunk-O776WL7O.js";import"../chunk-CSTAQQGX.js";import"../chunk-3LWOVRLA.js";import"../chunk-DVUXUIPV.js";import"../chunk-YGH7S5ZF.js";import"../chunk-4IAMSRHD.js";import"../chunk-3QQOATV3.js";import"../chunk-DZITM5AG.js";import"../chunk-PZ4L2EEG.js";import"../chunk-QMEKQTUT.js";import"../chunk-EAARMPCW.js";import"../chunk-CAPYNIGK.js";import"../chunk-63YJPWTM.js";import"../chunk-4KVVAENP.js";import"../chunk-7EL3GWWJ.js";import"../chunk-BREHZNTL.js";import"../chunk-7FPQJDFD.js";import"../chunk-EVT7MGAC.js";import"../chunk-S5UCI27C.js";import"../chunk-EON7T2SN.js";import"../chunk-I26FHSI6.js";function collectProficiencySources(resolved){const g=collectProficiencyGrants(resolved);const chosen=collectChosenProficiencies(resolved);return{...g,chosenLanguages:chosen.languages,chosenTools:chosen.tools,chosenWeapons:chosen.weapons}}function aggregateProficiencies(resolved){const{armor,weapons}=composeArmorWeapons(resolved);const effective=computeEffectiveProficiencies(resolved);return{armor:armor.kept,weapons:weapons.kept,tools:effective.tools,languages:effective.languages}}function proficiencyOverview(resolved,kind){if(kind==="armor"||kind==="weapons"){const c=composeArmorWeapons(resolved)[kind];return{effective:c.kept,removed:c.suppressed}}return{effective:computeEffectiveProficiencies(resolved)[kind],removed:computeSuppressedProficiencies(resolved)[kind]}}function weaponCoveredBy(effective,weapon){const cat=typeof weapon.category==="string"?weapon.category:"";const base=cat.split("-")[0];return effective.find(e=>{const key=weaponProfKey(e.value);if((key==="simple"||key==="martial")&&key===base)return true;if(cat&&key===normKey(cat))return true;return qualifiedGrantCovers(e.value,weapon)})}function composeArmorWeapons(resolved){const src=collectProficiencySources(resolved);return{armor:applyKindOverrides(resolved,"armor",composeGrantEntries([src.classArmor,src.featArmor,src.effectArmor])),weapons:applyKindOverrides(resolved,"weapons",composeGrantEntries([src.classWeaponFixed,src.classWeaponCategories,src.featWeapons,src.effectWeapons],src.chosenWeapons))}}function applyKindOverrides(resolved,kind,entries){var _a,_b,_c,_d;const ov=(_b=(_a=resolved.definition)==null?void 0:_a.overrides)==null?void 0:_b[kind];const key=v=>proficiencyKey(kind,v);const all=[...entries];for(const v of(_c=ov==null?void 0:ov.add)!=null?_c:[]){if(!all.some(e=>key(e.value)===key(v)))all.push({value:v,label:prettyName(v),sources:[],origin:"manual"})}const removes=new Set(((_d=ov==null?void 0:ov.remove)!=null?_d:[]).map(key));const byLabel=(a,b)=>a.label<b.label?-1:a.label>b.label?1:0;return{kept:all.filter(e=>!removes.has(key(e.value))).sort(byLabel),suppressed:all.filter(e=>removes.has(key(e.value))).sort(byLabel)}}function composeGrantEntries(buckets,picks=[]){const byKey=new Map;for(const bucket of buckets){for(const g of bucket){const key=toProfSlug(g.value);const existing=byKey.get(key);if(!existing){byKey.set(key,{value:g.value,label:prettyName(g.value),sources:[g.source],origin:"grant"});continue}if(!existing.sources.includes(g.source))existing.sources.push(g.source)}}for(const v of picks){const k=toProfSlug(v);if(!byKey.has(k))byKey.set(k,{value:v,label:prettyName(v),sources:[],origin:"pick"})}return[...byKey.values()].sort((a,b)=>a.label<b.label?-1:a.label>b.label?1:0)}function prettyName(slug){return proficiencyLabel(slug)}export{aggregateProficiencies,collectProficiencySources,proficiencyOverview,weaponCoveredBy};
1
+ import{qualifiedGrantCovers}from"../chunk-T55DELVL.js";import"../chunk-SEOASDO4.js";import{collectChosenProficiencies,collectProficiencyGrants,computeEffectiveProficiencies,computeSuppressedProficiencies}from"../chunk-JSI2G6LE.js";import"../chunk-2EOGK6R6.js";import"../chunk-4AJYEWFQ.js";import"../chunk-RQZCGXUZ.js";import"../chunk-CLZRWPWT.js";import"../chunk-B2JSF2LL.js";import"../chunk-FOLHTMSC.js";import"../chunk-4JEF3CET.js";import{normKey,proficiencyKey,proficiencyLabel,toProfSlug,weaponProfKey}from"../chunk-VTQ4RWEG.js";import"../chunk-DXJ5NKKB.js";import"../chunk-J27N3KUE.js";import"../chunk-RR26E7LH.js";import"../chunk-UBUKCRZ3.js";import"../chunk-2OVDSMPY.js";import"../chunk-PFQPP77Q.js";import"../chunk-QVWT67WA.js";import"../chunk-E4E6YEN6.js";import"../chunk-CMIEZQL4.js";import"../chunk-O776WL7O.js";import"../chunk-CSTAQQGX.js";import"../chunk-3LWOVRLA.js";import"../chunk-DVUXUIPV.js";import"../chunk-YGH7S5ZF.js";import"../chunk-4IAMSRHD.js";import"../chunk-3QQOATV3.js";import"../chunk-DZITM5AG.js";import"../chunk-PZ4L2EEG.js";import"../chunk-QMEKQTUT.js";import"../chunk-EAARMPCW.js";import"../chunk-CAPYNIGK.js";import"../chunk-63YJPWTM.js";import"../chunk-4KVVAENP.js";import"../chunk-7EL3GWWJ.js";import"../chunk-BREHZNTL.js";import"../chunk-7FPQJDFD.js";import"../chunk-EVT7MGAC.js";import"../chunk-S5UCI27C.js";import"../chunk-EON7T2SN.js";import"../chunk-I26FHSI6.js";function collectProficiencySources(resolved){const g=collectProficiencyGrants(resolved);const chosen=collectChosenProficiencies(resolved);return{...g,chosenLanguages:chosen.languages,chosenTools:chosen.tools,chosenWeapons:chosen.weapons}}function aggregateProficiencies(resolved){const{armor,weapons}=composeArmorWeapons(resolved);const effective=computeEffectiveProficiencies(resolved);return{armor:armor.kept,weapons:weapons.kept,tools:effective.tools,languages:effective.languages}}function proficiencyOverview(resolved,kind){if(kind==="armor"||kind==="weapons"){const c=composeArmorWeapons(resolved)[kind];return{effective:c.kept,removed:c.suppressed}}return{effective:computeEffectiveProficiencies(resolved)[kind],removed:computeSuppressedProficiencies(resolved)[kind]}}function weaponCoveredBy(effective,weapon){const cat=typeof weapon.category==="string"?weapon.category:"";const base=cat.split("-")[0];return effective.find(e=>{const key=weaponProfKey(e.value);if((key==="simple"||key==="martial")&&key===base)return true;if(cat&&key===normKey(cat))return true;return qualifiedGrantCovers(e.value,weapon)})}function composeArmorWeapons(resolved){const src=collectProficiencySources(resolved);return{armor:applyKindOverrides(resolved,"armor",composeGrantEntries([src.classArmor,src.featArmor,src.effectArmor])),weapons:applyKindOverrides(resolved,"weapons",composeGrantEntries([src.classWeaponFixed,src.classWeaponCategories,src.featWeapons,src.effectWeapons],src.chosenWeapons))}}function applyKindOverrides(resolved,kind,entries){var _a,_b,_c,_d;const ov=(_b=(_a=resolved.definition)==null?void 0:_a.overrides)==null?void 0:_b[kind];const key=v=>proficiencyKey(kind,v);const all=[...entries];for(const v of(_c=ov==null?void 0:ov.add)!=null?_c:[]){if(!all.some(e=>key(e.value)===key(v)))all.push({value:v,label:prettyName(v),sources:[],origin:"manual"})}const removes=new Set(((_d=ov==null?void 0:ov.remove)!=null?_d:[]).map(key));const byLabel=(a,b)=>a.label<b.label?-1:a.label>b.label?1:0;return{kept:all.filter(e=>!removes.has(key(e.value))).sort(byLabel),suppressed:all.filter(e=>removes.has(key(e.value))).sort(byLabel)}}function composeGrantEntries(buckets,picks=[]){const byKey=new Map;for(const bucket of buckets){for(const g of bucket){const key=toProfSlug(g.value);const existing=byKey.get(key);if(!existing){byKey.set(key,{value:g.value,label:prettyName(g.value),sources:[g.source],origin:"grant"});continue}if(!existing.sources.includes(g.source))existing.sources.push(g.source)}}for(const v of picks){const k=toProfSlug(v);if(!byKey.has(k))byKey.set(k,{value:v,label:prettyName(v),sources:[],origin:"pick"})}return[...byKey.values()].sort((a,b)=>a.label<b.label?-1:a.label>b.label?1:0)}function prettyName(slug){return proficiencyLabel(slug)}export{aggregateProficiencies,collectProficiencySources,proficiencyOverview,weaponCoveredBy};
@@ -1 +1 @@
1
- import{speciesIncreaseRule}from"../chunk-6IPWTOLU.js";import{buildFeatureAttackRows,buildUnarmedRow,computeAppliedBonuses,computeSlotsAndAttacks,emptyAppliedBonuses,pactWeaponIndexes}from"../chunk-KZFTTAFN.js";import"../chunk-T55DELVL.js";import"../chunk-SEOASDO4.js";import{amountBindingsFor,ownerClassSlug}from"../chunk-53SHSS4M.js";import"../chunk-PZ3ZZ5H5.js";import{computeConditionEffects,speedConditionNames}from"../chunk-VA3ZWV7C.js";import"../chunk-4E2GIWJE.js";import{collectChosenAbilityPoints,collectChosenProficiencies}from"../chunk-2GZM7FCD.js";import"../chunk-2EOGK6R6.js";import"../chunk-4AJYEWFQ.js";import"../chunk-RQZCGXUZ.js";import"../chunk-CLZRWPWT.js";import{assembleEffectFeatures,computeFeatureEffects,foldsNow,mergeDefenseItems,selfEffectsOf}from"../chunk-4FTTUZXM.js";import"../chunk-FOLHTMSC.js";import"../chunk-4JEF3CET.js";import{proficiencyKey}from"../chunk-VTQ4RWEG.js";import{itemLabel}from"../chunk-MMDUUEFA.js";import{featPickSites,poolMemberSitesOf,spellsReached}from"../chunk-J27N3KUE.js";import"../chunk-RR26E7LH.js";import"../chunk-UBUKCRZ3.js";import{resourceLevelFor}from"../chunk-2OVDSMPY.js";import{computeSpellLimits,deriveSpellSlots,effectiveSpellcastingAbility,resolveSpellcasting}from"../chunk-PFQPP77Q.js";import{legacyAsiBranch}from"../chunk-QVWT67WA.js";import{toDefenseSlug}from"../chunk-LR6UMA5V.js";import"../chunk-E4E6YEN6.js";import"../chunk-CMIEZQL4.js";import"../chunk-O776WL7O.js";import{diceColumnAt,tableCellAt,unarmedDieColumnFor}from"../chunk-CSTAQQGX.js";import"../chunk-3LWOVRLA.js";import"../chunk-DVUXUIPV.js";import"../chunk-YGH7S5ZF.js";import"../chunk-NEMX7QGG.js";import"../chunk-56JK6VCL.js";import{effectiveArmor,isShieldArmor}from"../chunk-4IAMSRHD.js";import"../chunk-3QQOATV3.js";import"../chunk-DZITM5AG.js";import"../chunk-PZ4L2EEG.js";import"../chunk-QMEKQTUT.js";import{resolveAmountText}from"../chunk-VIP3FH2O.js";import"../chunk-EAARMPCW.js";import"../chunk-CAPYNIGK.js";import{bareEntitySlug,slugify}from"../chunk-63YJPWTM.js";import"../chunk-4KVVAENP.js";import"../chunk-7EL3GWWJ.js";import"../chunk-BREHZNTL.js";import{abilityModifier,attackBonus,isCanonicalDamageType,isChosenDamageType,proficiencyFromLevel,saveDC,savingThrow,skillBonus}from"../chunk-7FPQJDFD.js";import{ABILITY_KEYS,ALL_SKILLS,SKILL_ABILITY}from"../chunk-EVT7MGAC.js";import"../chunk-S5UCI27C.js";import"../chunk-EON7T2SN.js";import"../chunk-I26FHSI6.js";var lower=s=>(s!=null?s:"").trim().toLowerCase();function namedSpellSlug(ref){var _a;const inner=ref.replace(/^\[\[/,"").replace(/\]\]$/,"").split("|")[0];return slugify((_a=inner.split("/").pop())!=null?_a:inner)}function dealsDamage(spell){var _a,_b;return((_b=(_a=spell.damage)==null?void 0:_a.types)!=null?_b:[]).some(t=>t.trim()!=="")}function spellsInScope(scope,spells,pickedTypes){var _a,_b;if(!scope)return[];const picked=scope.damage_type_pick!==void 0?pickedTypes(scope.damage_type_pick).map(lower):null;const types=(_a=scope.damage_types)==null?void 0:_a.map(lower);const named=(_b=scope.spells)==null?void 0:_b.map(namedSpellSlug);const hit=spells.filter(({slug,entity:e})=>{var _a2,_b2,_c,_d,_e;if(!dealsDamage(e))return false;const own=((_b2=(_a2=e.damage)==null?void 0:_a2.types)!=null?_b2:[]).map(lower);if(scope.list!==void 0&&!((_c=e.classes)!=null?_c:[]).map(lower).includes(lower(scope.list)))return false;if(scope.level!==void 0&&((_d=e.level)!=null?_d:0)!==scope.level)return false;if(scope.school!==void 0&&lower(e.school)!==lower(scope.school))return false;if(types&&!own.some(t=>types.includes(t)))return false;if(picked&&!own.some(t=>picked.includes(t)))return false;if(named&&!named.includes(bareEntitySlug(slug))&&!named.includes(slugify((_e=e.name)!=null?_e:"")))return false;return true});return[...new Set(hit.map(s=>s.slug))]}function pickedDamageTypes(resolved,choiceId){var _a,_b,_c,_d,_e,_f;const out=new Set;for(const c of(_a=resolved.classes)!=null?_a:[]){for(const owner of[c.entity,c.subclass]){for(const[lvl,feats]of Object.entries((_b=owner==null?void 0:owner.features_by_level)!=null?_b:{})){for(const feat of feats!=null?feats:[]){for(const ch of(_c=feat.choices)!=null?_c:[]){if(ch.kind!=="select-inline"||ch.id!==choiceId)continue;const sel=((_e=(_d=c.choices)==null?void 0:_d[Number(lvl)])!=null?_e:{})[ch.id];if(typeof sel!=="string")continue;const opt=ch.options.find(o=>o.value===sel);for(const word of`${sel} ${(_f=opt==null?void 0:opt.label)!=null?_f:""}`.split(/[^A-Za-z]+/)){if(word&&isCanonicalDamageType(word))out.add(word.toLowerCase())}}}}}}return[...out]}var OTHER_MODES=["fly","swim","climb","burrow"];function wornArmor(slots,registry){const body=slots==null?void 0:slots.armor;const armor=body&&registry?effectiveArmor(body.entity,registry):null;const isBody=armor!==null&&!isShieldArmor(armor);const score=isBody?strengthRequirementOf(armor):void 0;return{heavy:isBody&&armor.category==="heavy",armor:isBody,shield:(slots==null?void 0:slots.shield)!==void 0,strength:body&&isBody&&typeof score==="number"&&score>0?{label:itemLabel(body.entry,body.entity),score}:null}}function strengthRequirementOf(armor){var _a;return(_a=armor.strength_requirement)!=null?_a:armor.strength_required}function speedTermActive(t,worn){var _a;const holds=w=>w==="heavy-armor"?worn.heavy:w==="armor"?worn.armor:worn.shield;return!((_a=t.inactiveWhile)!=null?_a:[]).some(holds)}function armorStrengthPenalty(worn,str,ignoredBy){if(!worn.strength||str>=worn.strength.score||ignoredBy.length>0)return null;return{source:`${worn.strength.label} (Strength ${str} < ${worn.strength.score})`,amount:-ARMOR_STRENGTH_PENALTY}}var ARMOR_STRENGTH_PENALTY=10;function speedAfterConditions(pre,ce){if(ce.speed_floor_zero)return 0;return Math.max(0,Math.floor(pre*ce.speed_multiplier-ce.speed_reduction_ft))}var term=(source,amount,condition)=>({source,amount,...condition?{condition}:{}});function walkTerms(i,species){var _a,_b,_c;const terms=[term(species,i.walk.race)];for(const f of i.resolved.feats){const bonus=f.speed_bonus;if(typeof bonus==="number"&&bonus!==0)terms.push(term((_a=f.name)!=null?_a:"Feat",bonus))}for(const t of i.applied.speed_terms)if(t.mode==="walk"&&t.kind==="bonus")terms.push(term(t.source,t.amount));for(const t of i.features.speed_terms)if(t.mode==="walk"&&!t.set)terms.push(term(t.label,t.value,t.condition));if(i.armorPenalty)terms.push(i.armorPenalty.term);if(i.walk.base>i.walk.additive){const itemWins=i.applied.speed_walk_set===i.walk.base&&i.applied.speed_walk_set>i.features.speed_walk_set;const source=itemWins?(_b=i.applied.speed_walk_set_terms.find(t=>t.amount===i.walk.base))==null?void 0:_b.source:(_c=i.features.speed_terms.find(t=>t.mode==="walk"&&t.set&&t.value===i.walk.base))==null?void 0:_c.label;terms.push(term(source!=null?source:"Minimum speed",i.walk.base-i.walk.additive))}if(i.walk.final!==i.walk.base)terms.push(term(conditionLabel(i),i.walk.final-i.walk.base));return terms}var conditionLabel=i=>i.conditionNames.join(", ")||"Conditions";function otherLine(i,mode,species){var _a,_b,_c,_d,_e;const grants=[];const own=(_b=(_a=i.resolved.race)==null?void 0:_a.speed)==null?void 0:_b[mode];if(typeof own==="number"&&own>0)grants.push(term(species,own));for(const t of i.features.speed_terms)if(t.mode===mode&&t.set&&t.value>0)grants.push(term(t.label,t.value,t.condition));for(const t of i.applied.speed_terms)if(t.mode===mode&&t.kind==="grant"&&t.amount>0)grants.push(term(t.source,t.amount));for(const t of i.applied.speed_terms)if(t.mode===mode&&t.kind==="walk")grants.push({...term(t.source,i.walk.base),equalsWalk:true});for(const t of i.features.speed_terms)if(t.mode===mode&&t.equalsWalk)grants.push({...term(t.label,i.walk.base,t.condition),equalsWalk:true});if(grants.length===0)return null;const penalty=((_c=i.armorPenalty)==null?void 0:_c.everyMode)?-i.armorPenalty.term.amount:0;const after=g=>g.equalsWalk?g.amount:g.amount-Math.min(penalty,g.amount);const best=grants.reduce((a,b)=>after(b)>after(a)?b:a);if(best.amount<=0)return null;const{equalsWalk,...bestTerm}=best;const bonuses=i.features.speed_terms.filter(t=>t.mode===mode&&!t.set&&!t.equalsWalk&&t.value!==0).map(t=>term(t.label,t.value,t.condition));const terms=[bestTerm,...bonuses];if(i.armorPenalty&&penalty>0&&!equalsWalk){const cut=Math.min(penalty,terms.reduce((s,t)=>s+t.amount,0));if(cut>0)terms.push({...i.armorPenalty.term,amount:-cut})}const pre=terms.reduce((s,t)=>s+t.amount,0);const value=speedAfterConditions(pre,i.conditions);if(value!==pre)terms.push(term(conditionLabel(i),value-pre));return{mode,value,...equalsWalk&&bonuses.length===0?{equalsWalk:true}:{},...mode==="fly"&&((_e=(_d=i.resolved.race)==null?void 0:_d.speed)==null?void 0:_e.hover)===true&&typeof own==="number"&&own>0?{hover:true}:{},terms}}function buildSpeedLines(i){var _a,_b;const species=(_b=(_a=i.resolved.race)==null?void 0:_a.name)!=null?_b:"Base speed";const lines=[{mode:"walk",value:i.walk.final,terms:walkTerms(i,species)}];for(const mode of OTHER_MODES){const line=otherLine(i,mode,species);if(line)lines.push(line)}return lines}var WEAPON_CATEGORY_WORDS=new Set(["simple","martial","simple-melee","simple-ranged","martial-melee","martial-ranged","natural"]);function phbAverageForDie(hitDieStr){const n=parseDieSize(hitDieStr);if(n==null)return 4;return Math.floor(n/2)+1}function parseDieSize(die){if(die==null)return null;if(typeof die==="number")return die;const m=die.match(/^d?(\d+)$/i);return m?parseInt(m[1],10):null}function skillSlugFromDisplay(display){return display.toLowerCase().replace(/\s+/g,"-")}function skillSlugToAbilityLookup(slug){return slug.replace(/-/g," ")}function flattenRaceAsi(race){var _a;const out={};if(!(race==null?void 0:race.ability_score_increases))return out;for(const asi of race.ability_score_increases){if("ability"in asi){out[asi.ability]=((_a=out[asi.ability])!=null?_a:0)+asi.amount}}return out}function subraceAsi(resolved){var _a,_b,_c,_d,_e;const subSlug=(_b=(_a=resolved.definition.subrace)==null?void 0:_a.replace(/\[\[|\]\]/g,""))!=null?_b:null;if(!subSlug)return[];const subraces=(_d=(_c=resolved.race)==null?void 0:_c.subraces)!=null?_d:[];const sub=subraces.find(s=>s.slug===subSlug);return(_e=sub==null?void 0:sub.ability_score_increases)!=null?_e:[]}function collectClassAsiBranch(resolved){var _a;const out={};for(const c of resolved.classes){for(const choice of Object.values(c.choices)){const alloc=legacyAsiBranch(choice);if(!alloc)continue;for(const ab of ABILITY_KEYS){const v=alloc[ab];if(typeof v==="number")out[ab]=((_a=out[ab])!=null?_a:0)+v}}}return out}function abilityBonusBreakdown(resolved,featureEffects){var _a,_b,_c,_d,_e,_f,_g;const species=speciesIncreaseTotals(resolved);const suppressed=speciesIncreaseRule(resolved).suppressed;const origin=collectChosenAbilityPoints(resolved);const classAsi=collectClassAsiBranch(resolved);const featPoints=collectClassFeatAbilityPoints(resolved);const out={};for(const ab of ABILITY_KEYS){let feat=(_a=featPoints[ab])!=null?_a:0;for(const f of resolved.feats){const bonus=(_b=f.ability_bonuses)==null?void 0:_b[ab];if(typeof bonus==="number")feat+=bonus;feat+=(_c=fixedFeatAbilityIncrease(f)[ab])!=null?_c:0}const sp=(_d=species[ab])!=null?_d:0;out[ab]={species:suppressed?0:sp,speciesNotUsed:suppressed?sp:0,background:(_e=origin.background[ab])!=null?_e:0,class:((_f=classAsi[ab])!=null?_f:0)+((_g=featureEffects==null?void 0:featureEffects.ability_bonus[ab])!=null?_g:0),feat}}return out}function speciesIncreaseTotals(resolved){var _a,_b;const out={...flattenRaceAsi(resolved.race)};for(const asi of subraceAsi(resolved)){if(asi.ability&&typeof asi.amount==="number")out[asi.ability]=((_a=out[asi.ability])!=null?_a:0)+asi.amount}const picked=collectChosenAbilityPoints(resolved).race;for(const ab of ABILITY_KEYS){const v=picked[ab];if(typeof v==="number")out[ab]=((_b=out[ab])!=null?_b:0)+v}return out}function fixedFeatAbilityIncrease(f){var _a;const g=f.grants_asi;if(!g||typeof g.amount!=="number"||g.amount<=0||!Array.isArray(g.pool)||g.pool.length!==1)return{};if(((_a=f.choices)!=null?_a:[]).some(c=>c.kind==="ability-points"))return{};const ab=g.pool[0];return ABILITY_KEYS.includes(ab)?{[ab]:g.amount}:{}}function hitDiceAverageSum(classes){var _a;let total=0;let firstLevelCounted=false;for(const c of classes){const die=parseDieSize((_a=c.entity)==null?void 0:_a.hit_die);if(!c.entity||die==null||c.level<1)continue;for(let lvl=1;lvl<=c.level;lvl++){if(!firstLevelCounted){total+=die;firstLevelCounted=true}else{total+=Math.floor(die/2)+1}}}return total}function hpLevelCount(classes){var _a;let count=0;for(const c of classes){const die=parseDieSize((_a=c.entity)==null?void 0:_a.hit_die);if(!c.entity||die==null||c.level<1)continue;count+=c.level}return count}function multiclassMaxHP(classes,conMod){return Math.max(1,hitDiceAverageSum(classes)+conMod*hpLevelCount(classes))}function resolveDamageRider(rider,rowDamageType,bindings){const{owner,scope:_scope,...rest}=rider;const out={...rest,amount:resolveAmountText(rider.amount,bindings(owner))};if(rider.damage_type!==void 0&&!isChosenDamageType(rider.damage_type)){const resolved=isCanonicalDamageType(rider.damage_type)?rider.damage_type:rowDamageType;if(resolved)out.damage_type=resolved;else delete out.damage_type}return out}function riderReachesRow(rider,row,opts){return scopeReachesRow(rider.scope,row,opts)}function scopeReachesRow(scope,row,opts){if(!(scope==null?void 0:scope.length))return true;const unarmedStrike=row.unarmed===true||row.naturalWeapon===true;return scope.some(word=>{switch(word){case"weapon":return!unarmedStrike;case"pact-weapon":return(opts==null?void 0:opts.pactPicked)===true?row.pactWeapon===true:!unarmedStrike;case"unarmed":return unarmedStrike;case"melee":case"ranged":return row.weaponCategory===word;case"finesse":case"thrown":case"heavy":return row.properties.includes(word)}})}function unarmoredAC(resolved,mods,warnings){return unarmoredACBreakdown(resolved,mods,warnings).total}function unarmoredACBreakdown(resolved,mods,warnings,shieldBonus=0){var _a,_b,_c,_d,_e,_f;const baseTerms=[{source:"Unarmored",amount:10,kind:"unarmored"},{source:"DEX modifier",amount:mods.dex,kind:"dex"}];const{activeBuffs}=assembleEffectFeatures(resolved);const candidates=[{total:10+mods.dex,terms:baseTerms,shieldAllowed:true}];for(const rf of[...resolved.features,...(_a=resolved.itemFeatures)!=null?_a:[]]){if(!foldsNow(rf,activeBuffs))continue;for(const eff of selfEffectsOf(rf.feature)){if(eff.kind!=="unarmored-ac")continue;const base=(_b=eff.base)!=null?_b:10;const terms=[{source:"Unarmored",amount:base,kind:"unarmored"}];let total=base;for(const ab of eff.abilities){terms.push(ab==="dex"?{source:"DEX modifier",amount:mods.dex,kind:"dex"}:{source:`${ab.toUpperCase()} modifier (${(_c=rf.feature.name)!=null?_c:"Unarmored"})`,amount:mods[ab],kind:"ability"});total+=mods[ab]}candidates.push({total,terms,shieldAllowed:eff.allow_shield===true})}}if(candidates.length>1){const applied=c=>c.total+(c.shieldAllowed?shieldBonus:0);let best=candidates[0];for(const c of candidates)if(applied(c)>applied(best))best=c;return best}for(const rf of resolved.features){const feat=rf.feature;if((_d=feat.unarmored_defense)==null?void 0:_d.ability){const ab=feat.unarmored_defense.ability;const amt=(_e=mods[ab])!=null?_e:0;const terms=[...baseTerms,{source:`${ab.toUpperCase()} modifier (Unarmored Defense)`,amount:amt,kind:"ability"}];return{total:10+mods.dex+amt,terms,shieldAllowed:true}}}for(const rf of resolved.features){const name=((_f=rf.feature.name)!=null?_f:"").toLowerCase();if(!/unarmored\s*defense/.test(name))continue;if(rf.source.kind==="class"&&rf.source.slug.includes("monk")){const terms=[...baseTerms,{source:"WIS modifier (Unarmored Defense)",amount:mods.wis,kind:"ability"}];return{total:10+mods.dex+mods.wis,terms,shieldAllowed:true}}if(rf.source.kind==="class"&&rf.source.slug.includes("barbarian")){const terms=[...baseTerms,{source:"CON modifier (Unarmored Defense)",amount:mods.con,kind:"ability"}];return{total:10+mods.dex+mods.con,terms,shieldAllowed:true}}}return{total:10+mods.dex,terms:baseTerms,shieldAllowed:true}}function resolveUnarmedStrike(resolved){var _a,_b,_c;const dice=[];const abilities=new Set;const classOf=rf=>rf.source.kind==="class"?resolved.classes.find(c=>{var _a2;return((_a2=c.entity)==null?void 0:_a2.slug)===rf.source.slug}):void 0;const readDie=(rf,d)=>{var _a2,_b2;if(typeof d==="string")return d;if(!d)return void 0;const cls=classOf(rf);return cls?(_b2=diceColumnAt((_a2=cls.entity)==null?void 0:_a2.table,cls.level,d.column))!=null?_b2:void 0:void 0};for(const rf of resolved.features){const authored=selfEffectsOf(rf.feature).filter(e=>e.kind==="unarmed-strike");for(const e of authored){const d2=readDie(rf,e.dice);if(d2)dice.push(d2);for(const ab of(_a=e.abilities)!=null?_a:[])abilities.add(ab)}if(authored.length||rf.source.kind!=="class")continue;const slug=((_c=(_b=rf.feature.id)!=null?_b:rf.feature.name)!=null?_c:"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"");const column=unarmedDieColumnFor(slug);if(!column)continue;const d=readDie(rf,{column});if(!d)continue;dice.push(d);abilities.add("dex")}const avg=d=>{const m=/^(\d+)d(\d+)$/i.exec(d);return m?Number(m[1])*(Number(m[2])+1)/2:1};const best=dice.sort((a,b)=>avg(b)-avg(a))[0];return{...best?{dice:best}:{},...abilities.size?{abilities:[...abilities]}:{}}}function initiativeBonus(dexMod,feats,edition){var _a,_b,_c;let bonus=dexMod;for(const f of feats){const featEdition=(_a=f.edition)!=null?_a:edition;const hasData=((_b=f.effects)!=null?_b:[]).some(e=>e.kind==="initiative-bonus");if(bareEntitySlug((_c=f.slug)!=null?_c:"")==="alert"&&featEdition==="2014"&&!hasData)bonus+=5;const initBonus=f.initiative_bonus;if(typeof initBonus==="number")bonus+=initBonus}return bonus}function speedFromRace(resolved){var _a,_b,_c;const base=(_c=(_b=(_a=resolved.race)==null?void 0:_a.speed)==null?void 0:_b.walk)!=null?_c:30;let extra=0;for(const f of resolved.feats){const bonus=f.speed_bonus;if(typeof bonus==="number")extra+=bonus}return base+extra}function collectClassFeatAbilityPoints(resolved){var _a;const out={};for(const t of classFeatAbilityPointTerms(resolved))out[t.ability]=((_a=out[t.ability])!=null?_a:0)+t.amount;return out}function classFeatAbilityPointTerms(resolved){var _a;const out=[];const stripRef=ref=>ref.replace(/^\[\[/,"").replace(/\]\]$/,"");const featBySlug=new Map;for(const f of resolved.feats)featBySlug.set(f.slug,f);const sites=featPickSites(resolved.classes,poolMemberSitesOf(resolved),ci=>{var _a2,_b,_c,_d;return(_d=(_c=(_b=(_a2=resolved.classes)==null?void 0:_a2[ci])==null?void 0:_b.entity)==null?void 0:_c.slug)!=null?_d:null});for(const site of sites){{const feat=featBySlug.get(stripRef(site.slug));if(!feat)continue;for(const ch of(_a=feat.choices)!=null?_a:[]){if(ch.kind!=="ability-points")continue;const raw=site.read(ch.id);if(!raw||typeof raw!=="object"||Array.isArray(raw))continue;let left=ch.points;for(const ab of ABILITY_KEYS){if(ch.pool&&!ch.pool.includes(ab))continue;const v=raw[ab];if(typeof v!=="number"||v<=0||left<=0)continue;const take=Math.min(v,ch.max_per,left);out.push({feat,ability:ab,amount:take});left-=take}}}}return out}function computeAbilityScores(resolved,overrides){var _a,_b,_c,_d,_e,_f;const out={...resolved.definition.abilities};if(!speciesIncreaseRule(resolved).suppressed){const species=speciesIncreaseTotals(resolved);for(const ab of ABILITY_KEYS){const b=species[ab];if(typeof b==="number")out[ab]=((_a=out[ab])!=null?_a:0)+b}}const originPoints=collectChosenAbilityPoints(resolved);for(const ab of ABILITY_KEYS){const v=originPoints.background[ab];if(typeof v==="number")out[ab]=((_b=out[ab])!=null?_b:0)+v}const classAsi=collectClassAsiBranch(resolved);for(const ab of ABILITY_KEYS){const v=classAsi[ab];if(typeof v==="number")out[ab]=((_c=out[ab])!=null?_c:0)+v}const featPoints=collectClassFeatAbilityPoints(resolved);for(const ab of ABILITY_KEYS){const v=featPoints[ab];if(typeof v==="number")out[ab]=((_d=out[ab])!=null?_d:0)+v}for(const f of resolved.feats){const bonuses=f.ability_bonuses;if(bonuses){for(const ab of ABILITY_KEYS){const v=bonuses[ab];if(typeof v==="number")out[ab]=((_e=out[ab])!=null?_e:0)+v}}for(const[ab,v]of Object.entries(fixedFeatAbilityIncrease(f)))out[ab]=((_f=out[ab])!=null?_f:0)+v}if(overrides.scores){for(const ab of ABILITY_KEYS){const v=overrides.scores[ab];if(typeof v==="number")out[ab]=v}}for(const ab of ABILITY_KEYS){if(typeof out[ab]!=="number")out[ab]=10}return out}function abilityScoreBreakdowns(resolved,overrides,applied,featureEffects,scores){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n;const suppressed=speciesIncreaseRule(resolved).suppressed;const species=speciesIncreaseTotals(resolved);const origin=collectChosenAbilityPoints(resolved);const classAsi=collectClassAsiBranch(resolved);const featTerms=classFeatAbilityPointTerms(resolved);const out={};for(const ab of ABILITY_KEYS){const base=(_a=resolved.definition.abilities)==null?void 0:_a[ab];const terms=[{source:"Base score",amount:typeof base==="number"?base:10}];const add=(source,amount,notUsed=false)=>{if(!amount)return;const prior=terms.find((t,i)=>i>0&&t.source===source&&t.notUsed===true===notUsed);if(prior)prior.amount+=amount;else terms.push(notUsed?{source,amount,notUsed:true}:{source,amount})};add((_c=(_b=resolved.race)==null?void 0:_b.name)!=null?_c:"Species",(_d=species[ab])!=null?_d:0,suppressed);add((_f=(_e=resolved.background)==null?void 0:_e.name)!=null?_f:"Background",(_g=origin.background[ab])!=null?_g:0);add("Ability Score Improvement",(_h=classAsi[ab])!=null?_h:0);for(const t of featTerms)if(t.ability===ab)add(t.feat.name,t.amount);for(const f of resolved.feats){const bonus=(_i=f.ability_bonuses)==null?void 0:_i[ab];if(typeof bonus==="number")add(f.name,bonus);add(f.name,(_j=fixedFeatAbilityIncrease(f)[ab])!=null?_j:0)}for(const t of(_k=applied.ability_terms)!=null?_k:[])if(t.ability===ab)add(t.source,t.amount);for(const t of(_l=featureEffects.ability_bonus_terms)!=null?_l:[])if(t.ability===ab)add(t.source,t.amount);const sum=terms.reduce((n,t)=>n+(t.notUsed?0:t.amount),0);const b={total:scores[ab],terms};let best;for(const t of(_m=applied.ability_static_terms)!=null?_m:[])if(t.ability===ab&&(!best||t.value>best.value))best={source:t.source,value:t.value};if(best&&best.value>sum)b.set=best;const o=(_n=overrides.scores)==null?void 0:_n[ab];if(typeof o==="number")b.override=o;out[ab]=b}return out}function normalizeArmorProf(input){var _a,_b;if(!input)return{categories:[],specific:[]};if(Array.isArray(input))return{categories:input,specific:[]};return{categories:(_a=input.categories)!=null?_a:[],specific:(_b=input.specific)!=null?_b:[]}}function normalizeWeaponToolProf(input){var _a,_b,_c;if(!input)return{categories:[],specific:[]};if(Array.isArray(input))return{categories:[],specific:input};return{categories:(_a=input.categories)!=null?_a:[],specific:((_b=input.fixed)!=null?_b:[]).concat((_c=input.specific)!=null?_c:[])}}function mergeInto(target,source){for(const c of source.categories)if(!target.categories.includes(c))target.categories.push(c);for(const s of source.specific)if(!target.specific.includes(s))target.specific.push(s)}function applyArmorWeaponOverrides(profs,overrides){var _a,_b;for(const kind of["armor","weapons"]){const ov=overrides==null?void 0:overrides[kind];if(!ov)continue;const set=profs[kind];const key=v=>proficiencyKey(kind,v);const removes=new Set(((_a=ov.remove)!=null?_a:[]).map(key));for(const v of(_b=ov.add)!=null?_b:[]){const k=key(v);if(removes.has(k))continue;const category=kind==="armor"||k==="simple"||k==="martial";const target=category?set.categories:set.specific;if(!target.some(e=>key(e)===k))target.push(category?k:v)}set.categories=set.categories.filter(e=>!removes.has(key(e)));set.specific=set.specific.filter(e=>!removes.has(key(e)))}}var ORIGIN_RANK={manual:0,equipment:1,grant:2};function composeDefenseEntries(manual,equipment,grants){const byValue=new Map;for(const raw of manual){const value=toDefenseSlug(raw);if(!value||byValue.has(value))continue;byValue.set(value,{value,label:raw.trim(),origin:"manual"})}const consider=(list,origin)=>{var _a,_b,_c,_d;for(const g of list){const value=toDefenseSlug(g.value);if(!value)continue;const existing=byValue.get(value);if(!existing){byValue.set(value,{value,label:g.value.trim(),origin,sources:[...g.sources],...g.condition?{condition:g.condition}:{},...((_a=g.items)==null?void 0:_a.length)?{items:g.items.map(it=>({...it}))}:{}});continue}if(ORIGIN_RANK[origin]>ORIGIN_RANK[existing.origin])existing.origin=origin;const sources=(_b=existing.sources)!=null?_b:existing.sources=[];for(const src of g.sources)if(!sources.includes(src))sources.push(src);if(!existing.condition&&g.condition)existing.condition=g.condition;if((_c=g.items)==null?void 0:_c.length)mergeDefenseItems((_d=existing.items)!=null?_d:existing.items=[],g.items)}};consider(equipment,"equipment");consider(grants,"grant");return[...byValue.values()]}function suppress(resolved,bucket,entries){var _a,_b,_c,_d,_e;const suppressed=new Set(((_e=(_d=(_c=(_b=(_a=resolved.definition)==null?void 0:_a.overrides)==null?void 0:_b.defenses)==null?void 0:_c[bucket])==null?void 0:_d.remove)!=null?_e:[]).map(toDefenseSlug));return entries.filter(e=>!suppressed.has(e.value))}function computeProficiencies(resolved){var _a,_b,_c,_d,_e,_f,_g;const armor={categories:[],specific:[]};const weapons={categories:[],specific:[]};const tools={categories:[],specific:[]};const languages=new Set;for(const c of resolved.classes){const p=(_a=c.entity)==null?void 0:_a.proficiencies;if(!p)continue;mergeInto(armor,normalizeArmorProf(p.armor));mergeInto(weapons,normalizeWeaponToolProf(p.weapons));mergeInto(tools,normalizeWeaponToolProf(p.tools));(_b=p.languages)==null?void 0:_b.forEach(l=>languages.add(l))}const racePr=(_c=resolved.race)==null?void 0:_c.proficiencies;if(racePr){mergeInto(armor,normalizeArmorProf(racePr.armor));mergeInto(weapons,normalizeWeaponToolProf(racePr.weapons));mergeInto(tools,normalizeWeaponToolProf(racePr.tools));(_d=racePr.languages)==null?void 0:_d.forEach(l=>languages.add(l))}const bgPr=(_e=resolved.background)==null?void 0:_e.proficiencies;if(bgPr){mergeInto(armor,normalizeArmorProf(bgPr.armor));mergeInto(weapons,normalizeWeaponToolProf(bgPr.weapons));mergeInto(tools,normalizeWeaponToolProf(bgPr.tools));(_f=bgPr.languages)==null?void 0:_f.forEach(l=>languages.add(l))}for(const f of resolved.feats){const grants=f.grants_proficiency;if(!grants)continue;mergeInto(armor,normalizeArmorProf(grants.armor));mergeInto(weapons,normalizeWeaponToolProf(grants.weapons));mergeInto(tools,normalizeWeaponToolProf(grants.tools));(_g=grants.languages)==null?void 0:_g.forEach(l=>languages.add(l))}return{armor,weapons,tools,languages:Array.from(languages).sort(),saves:[]}}var HAND_SET_HALF_SOURCE="Set by you";function recalc(resolved,registry){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x,_y,_z,_A,_B,_C,_D,_E,_F,_G,_H,_I,_J,_K,_L,_M,_N,_O,_P,_Q,_R,_S,_T,_U,_V,_W,_X,_Y,_Z,__,_$,_aa,_ba;const warnings=[];const overrides=(_a=resolved.definition.overrides)!=null?_a:{};const chosenProfs=collectChosenProficiencies(resolved);const{features:effectFeatures,activeBuffs}=assembleEffectFeatures(resolved);const tableDiceFor=(src,column,level)=>{var _a2;const cls=src.kind==="class"?resolved.classes.find(c=>{var _a3;return((_a3=c.entity)==null?void 0:_a3.slug)===src.slug}):src.kind==="subclass"?resolved.classes.find(c=>{var _a3;return((_a3=c.subclass)==null?void 0:_a3.slug)===src.slug}):void 0;return cls?diceColumnAt((_a2=cls.entity)==null?void 0:_a2.table,level,column):null};const tableCellFor=(src,column)=>{var _a2;const slug=ownerClassSlug(src,resolved);const cls=slug?resolved.classes.find(c=>{var _a3;return((_a3=c.entity)==null?void 0:_a3.slug)===slug}):void 0;return cls?tableCellAt((_a2=cls.entity)==null?void 0:_a2.table,cls.level,column):null};const featureEffects=computeFeatureEffects(effectFeatures,{activeBuffs,levelFor:src=>resourceLevelFor(src,resolved),tableDiceFor,tableCellFor});const profsForApply=computeProficiencies(resolved);for(const t of chosenProfs.tools){if(!profsForApply.tools.specific.includes(t))profsForApply.tools.specific.push(t)}for(const l of chosenProfs.languages){if(!profsForApply.languages.includes(l))profsForApply.languages.push(l)}for(const w of chosenProfs.weapons){if(!profsForApply.weapons.specific.includes(w))profsForApply.weapons.specific.push(w)}for(const t of featureEffects.proficiencies.tools){if(!profsForApply.tools.specific.includes(t))profsForApply.tools.specific.push(t)}for(const l of featureEffects.proficiencies.languages){if(!profsForApply.languages.includes(l))profsForApply.languages.push(l)}for(const a of featureEffects.proficiencies.armor){if(!profsForApply.armor.categories.includes(a))profsForApply.armor.categories.push(a)}for(const w of featureEffects.proficiencies.weapons){if(!profsForApply.weapons.categories.includes(w))profsForApply.weapons.categories.push(w);if(!WEAPON_CATEGORY_WORDS.has(w)&&!profsForApply.weapons.specific.includes(w)){profsForApply.weapons.specific.push(w)}}profsForApply.languages.sort();applyArmorWeaponOverrides(profsForApply,(_b=resolved.definition)==null?void 0:_b.overrides);const applied=registry?computeAppliedBonuses(resolved,profsForApply,registry,warnings):emptyAppliedBonuses();const savesInformational=applied.informational.filter(i=>i.field==="saving_throws");const spellcastingInformational=applied.informational.filter(i=>i.field==="spell_attack"||i.field==="spell_save_dc");const speedInformational=applied.informational.filter(i=>i.field.startsWith("speed."));const baseScores=computeAbilityScores(resolved,overrides);const scores={...baseScores};for(const ab of ABILITY_KEYS){const bonus=applied.ability_bonuses[ab];scores[ab]+=(typeof bonus==="number"?bonus:0)+((_c=featureEffects.ability_bonus[ab])!=null?_c:0)}for(const ab of ABILITY_KEYS){const stat=applied.ability_statics[ab];if(typeof stat==="number"&&stat>scores[ab])scores[ab]=stat}if(overrides.scores){for(const ab of ABILITY_KEYS){const o=overrides.scores[ab];if(typeof o==="number")scores[ab]=o}}const mods={str:abilityModifier(scores.str),dex:abilityModifier(scores.dex),con:abilityModifier(scores.con),int:abilityModifier(scores.int),wis:abilityModifier(scores.wis),cha:abilityModifier(scores.cha)};const totalLevel=resolved.classes.reduce((s,c)=>s+c.level,0);const proficiencyBonus=proficiencyFromLevel(totalLevel||1);const conditionEffects=computeConditionEffects(resolved.state,resolved.definition.edition,scores);const firstClass=(_e=(_d=resolved.classes[0])==null?void 0:_d.entity)!=null?_e:null;const saveProfs=new Set((_f=firstClass==null?void 0:firstClass.saving_throws)!=null?_f:[]);for(const ab of featureEffects.proficiencies.saves)saveProfs.add(ab);for(const ab of chosenProfs.saves)saveProfs.add(ab);const saves={};const saveBreakdowns={};const activeSaveBonusTerms=featureEffects.save_bonus_terms.filter(t=>{var _a2;return t.inactiveWhile==="incapacitated"?!conditionEffects.actions_disabled:t.inactiveWhile==="unconscious"?!((_a2=resolved.state.conditions)!=null?_a2:[]).includes("unconscious"):true});for(const ab of ABILITY_KEYS){const override=(_g=overrides.saves)==null?void 0:_g[ab];const prof=(_h=override==null?void 0:override.proficient)!=null?_h:saveProfs.has(ab);const featureTerms=[];for(const t of activeSaveBonusTerms){if(t.saves.length>0&&!t.saves.includes(ab))continue;const amount=Math.max(t.minimum,mods[t.ability]);const prior=featureTerms.find(x=>x.source===t.label);if(prior===void 0)featureTerms.push({source:t.label,amount});else if(amount>prior.amount)prior.amount=amount}const derivedBonus=savingThrow(scores[ab],prof,proficiencyBonus)+applied.save_bonus+featureTerms.reduce((sum,t)=>sum+t.amount,0)+conditionEffects.d20_test_penalty;const bonus=(_i=override==null?void 0:override.bonus)!=null?_i:derivedBonus;saves[ab]={bonus,proficient:prof};saveBreakdowns[ab]=[{source:ab.toUpperCase(),amount:mods[ab]},...prof?[{source:"Proficiency",amount:proficiencyBonus}]:[],...applied.save_terms.map(t=>({...t})),...featureTerms,...conditionEffects.d20_test_penalty?[{source:`Exhaustion ${conditionEffects.exhaustion_level}`,amount:conditionEffects.d20_test_penalty}]:[]]}const profSet=new Set([...resolved.definition.skills.proficient,...(_k=(_j=resolved.background)==null?void 0:_j.skill_proficiencies)!=null?_k:[],...chosenProfs.skills,...featureEffects.proficiencies.skills]);const expSet=new Set([...resolved.definition.skills.expertise,...chosenProfs.expertise,...featureEffects.proficiencies.skillExpertise]);const skills={};const skillBreakdowns={};for(const skill of ALL_SKILLS){const skillKey=skillSlugFromDisplay(skill);const ab=SKILL_ABILITY[skillSlugToAbilityLookup(skillKey)];const override=(_l=overrides.skills)==null?void 0:_l[skillKey];const tri=(_m=override==null?void 0:override.proficiency)!=null?_m:expSet.has(skillKey)?"expertise":profSet.has(skillKey)?"proficient":"none";const skillTerms=featureEffects.skill_bonus_terms.filter(t=>t.skills.includes(skillKey)).map(t=>({source:t.label,amount:Math.max(t.minimum,mods[t.ability])}));const halfProfTerms=tri!=="none"?[]:[...featureEffects.half_proficiency_terms.filter(t=>t.skills.length===0||t.skills.includes(skillKey)).map(t=>({source:t.label,amount:t.round==="up"?Math.ceil(proficiencyBonus/2):Math.floor(proficiencyBonus/2)})),...((_n=resolved.definition.skills.half)==null?void 0:_n.includes(skillKey))?[{source:HAND_SET_HALF_SOURCE,amount:Math.floor(proficiencyBonus/2)}]:[]];const halfProfBest=halfProfTerms.length?halfProfTerms.reduce((best,t)=>t.amount>best.amount?t:best):null;const bonus=(_p=override==null?void 0:override.bonus)!=null?_p:skillBonus(scores[ab],tri,proficiencyBonus)+skillTerms.reduce((sum,t)=>sum+t.amount,0)+((_o=halfProfBest==null?void 0:halfProfBest.amount)!=null?_o:0)+conditionEffects.d20_test_penalty;skillBreakdowns[skillKey]=[{source:ab.toUpperCase(),amount:mods[ab]},...tri!=="none"?[{source:tri==="expertise"?"Expertise":"Proficiency",amount:proficiencyBonus*(tri==="expertise"?2:1)}]:[],...skillTerms,...halfProfBest?[halfProfBest]:[],...conditionEffects.d20_test_penalty?[{source:"Conditions",amount:conditionEffects.d20_test_penalty}]:[]];skills[skillKey]={bonus,proficiency:tri,ability:ab,...halfProfBest?{halfProficiency:{source:halfProfBest.source,amount:halfProfBest.amount}}:{}}}const passives={perception:(_r=(_q=overrides.passives)==null?void 0:_q.perception)!=null?_r:10+skills.perception.bonus,investigation:(_t=(_s=overrides.passives)==null?void 0:_s.investigation)!=null?_t:10+skills.investigation.bonus,insight:(_v=(_u=overrides.passives)==null?void 0:_u.insight)!=null?_v:10+skills.insight.bonus};const hpRolled=(_x=(_w=overrides.hp)==null?void 0:_w.rolled)!=null?_x:null;const hpModifier=(_z=(_y=overrides.hp)==null?void 0:_y.modifier)!=null?_z:null;const averageDiceSum=hitDiceAverageSum(resolved.classes);const conLevels=hpLevelCount(resolved.classes);const diceSum=hpRolled!=null?hpRolled:averageDiceSum;const diceConRaw=diceSum+mods.con*conLevels;const diceConClamped=Math.max(1,diceConRaw);const hpMaxDerived=diceConClamped+featureEffects.hp_per_level_bonus*totalLevel+(hpModifier!=null?hpModifier:0);const hpMaxAfterConditions=Math.max(0,Math.floor(hpMaxDerived*conditionEffects.hp_max_multiplier));const hpMax=(_B=(_A=overrides.hp)==null?void 0:_A.max)!=null?_B:hpMaxAfterConditions;const hpBreakdown={diceSum,diceSource:hpRolled!=null?"rolled":"average",averageDiceSum,conMod:mods.con,conLevels,clampApplied:diceConClamped!==diceConRaw,perLevelTerms:featureEffects.hp_per_level_terms.map(t=>({label:t.label,perLevel:t.value,levels:totalLevel,total:t.value*totalLevel})),modifier:hpModifier,exhaustionMultiplier:conditionEffects.hp_max_multiplier,exhaustionLevel:conditionEffects.exhaustion_level,derivedMax:hpMaxAfterConditions,override:(_D=(_C=overrides.hp)==null?void 0:_C.max)!=null?_D:null,final:hpMax};const featureAcTermsFor=hasArmor=>featureEffects.ac_terms.filter(t=>!t.requires_armor||hasArmor).map(t=>({source:t.label,amount:t.value,kind:"feature",condition:t.condition}));const sumTerms=terms=>terms.reduce((s,t)=>s+t.amount,0);const weaponAbilities=[...featureEffects.weaponAbilities];const wantsSpellcasting=resolved.features.some(rf=>selfEffectsOf(rf.feature).some(e=>e.kind==="weapon-ability"&&e.ability==="spellcasting"));if(wantsSpellcasting){let primaryCasterAbility=null;for(const c of resolved.classes){if(!c.entity)continue;const profile=resolveSpellcasting(c);if(profile){primaryCasterAbility=effectiveSpellcastingAbility(c.entity.slug,profile.ability,overrides);break}}if(primaryCasterAbility)weaponAbilities.unshift({ability:primaryCasterAbility})}let derivedEquipment=null;let acDerived;let acBreakdownDerived=[];let acInformationalDerived=[];if(registry){derivedEquipment=computeSlotsAndAttacks(resolved,mods,profsForApply,registry,warnings,proficiencyBonus,weaponAbilities,(_E=resolved.weaponMasteries)!=null?_E:[],featureEffects.attunement_set);if(derivedEquipment.equippedSlots.armor){const featTerms=featureAcTermsFor(true);acDerived=derivedEquipment.ac+sumTerms(featTerms);acBreakdownDerived=[...derivedEquipment.acBreakdown,...featTerms];acInformationalDerived=derivedEquipment.acInformational}else{const shieldBonus=derivedEquipment.acBreakdown.filter(b=>b.kind==="shield").reduce((sum,b)=>sum+b.amount,0);const{total:unarmored,terms:unarmoredTerms,shieldAllowed}=unarmoredACBreakdown(resolved,mods,warnings,shieldBonus);const additive=derivedEquipment.acBreakdown.filter(b=>b.kind==="item"||b.kind==="override"||b.kind==="shield"&&shieldAllowed);const featTerms=featureAcTermsFor(false);const additiveSum=additive.reduce((sum,b)=>sum+b.amount,0);acDerived=unarmored+additiveSum+sumTerms(featTerms);acBreakdownDerived=[...unarmoredTerms,...additive,...featTerms];acInformationalDerived=derivedEquipment.acInformational}}else{const{total,terms}=unarmoredACBreakdown(resolved,mods,warnings);const featTerms=featureAcTermsFor(false);acDerived=total+sumTerms(featTerms);acBreakdownDerived=[...terms,...featTerms]}const ac=(_F=overrides.ac)!=null?_F:acDerived;const worn=wornArmor(derivedEquipment==null?void 0:derivedEquipment.equippedSlots,registry);const featureSpeedTerms=featureEffects.speed_terms.filter(t=>speedTermActive(t,worn));const gatedWalk=featureSpeedTerms.filter(t=>t.mode==="walk"&&t.inactiveWhile!==void 0);const featureWalkBonus=featureEffects.speed_walk_bonus+gatedWalk.filter(t=>!t.set).reduce((sum,t)=>sum+t.value,0);const featureWalkFloor=Math.max(featureEffects.speed_walk_set,...gatedWalk.filter(t=>t.set).map(t=>t.value));const armorPenalty=armorStrengthPenalty(worn,scores.str,featureEffects.ignore_armor_strength);const additiveSpeed=speedFromRace(resolved)+applied.speed_bonuses.walk+featureWalkBonus+((_G=armorPenalty==null?void 0:armorPenalty.amount)!=null?_G:0);const baseSpeed=Math.max(featureWalkFloor,applied.speed_walk_set,additiveSpeed);const adjustedSpeed=baseSpeed*conditionEffects.speed_multiplier-conditionEffects.speed_reduction_ft;const conditionSpeed=conditionEffects.speed_floor_zero?0:Math.max(0,Math.floor(adjustedSpeed));const speed=(_H=overrides.speed)!=null?_H:conditionSpeed;const raceSpeed=(_K=(_J=(_I=resolved.race)==null?void 0:_I.speed)==null?void 0:_J.walk)!=null?_K:30;const speeds=buildSpeedLines({resolved,applied,features:{speed_terms:featureSpeedTerms,speed_walk_set:featureWalkFloor},conditions:conditionEffects,conditionNames:speedConditionNames(resolved.state,resolved.definition.edition),walk:{race:raceSpeed,additive:additiveSpeed,base:baseSpeed,final:conditionSpeed},armorPenalty:armorPenalty?{term:armorPenalty,everyMode:resolved.definition.edition==="2024"}:null});const speedBreakdown=speeds[0].terms;if(!resolved.race)warnings.push("No race resolved; speed defaulted to 30.");const initiativeAmountTerms=featureEffects.initiative_amount_terms.flatMap(term2=>{const text=resolveAmountText(term2.amount,amountBindingsFor(term2.owner,resolved,{proficiencyBonus,mods,spellcastingClasses:[]}));const n=Number(text);if(!Number.isInteger(n)){warnings.push(`${term2.label}: initiative amount "${term2.amount}" is not a number; nothing added.`);return[]}return[{source:term2.label,amount:n}]});const init=(_L=overrides.initiative)!=null?_L:initiativeBonus(mods.dex,resolved.feats,resolved.definition.edition)+featureEffects.initiative_bonus+initiativeAmountTerms.reduce((s,t)=>s+t.amount,0);const initiativeBreakdown=[{source:"DEX",amount:mods.dex},...initiativeBonus(mods.dex,resolved.feats,resolved.definition.edition)!==mods.dex?[{source:"Feats",amount:initiativeBonus(mods.dex,resolved.feats,resolved.definition.edition)-mods.dex}]:[],...featureEffects.initiative_terms.map(term2=>({source:term2.label,amount:term2.value})),...initiativeAmountTerms];const senses={darkvision:Math.max((_O=(_N=(_M=resolved.race)==null?void 0:_M.vision)==null?void 0:_N.darkvision)!=null?_O:0,featureEffects.senses.darkvision,applied.senses.darkvision),blindsight:Math.max(featureEffects.senses.blindsight,applied.senses.blindsight),tremorsense:Math.max(featureEffects.senses.tremorsense,applied.senses.tremorsense),truesight:Math.max(featureEffects.senses.truesight,applied.senses.truesight)};const spellcastingClasses=[];const slotInputs=[];const limitInputs=[];for(const c of resolved.classes){if(!c.entity)continue;const profile=resolveSpellcasting(c);if(!profile)continue;const ab=effectiveSpellcastingAbility(c.entity.slug,profile.ability,overrides);const dc=saveDC(scores[ab],proficiencyBonus)+applied.spell_save_dc;const atk=attackBonus(scores[ab],proficiencyBonus)+applied.spell_attack;spellcastingClasses.push({classSlug:c.entity.slug,className:c.entity.name,ability:ab,defaultAbility:profile.ability,saveDC:dc,attackBonus:atk,casterType:profile.casterType,preparation:profile.preparation,spellList:profile.spellList});slotInputs.push({casterType:profile.casterType,level:c.level});limitInputs.push({classSlug:c.entity.slug,level:c.level,profile,abilityScore:scores[ab]})}const spellcasting=spellcastingClasses.length>0?{ability:spellcastingClasses[0].ability,saveDC:spellcastingClasses[0].saveDC,attackBonus:spellcastingClasses[0].attackBonus}:null;const abilitySpellcasting={};for(const s of resolved.spells){const ab=s.ability;if(!ab||abilitySpellcasting[ab])continue;abilitySpellcasting[ab]={saveDC:saveDC(scores[ab],proficiencyBonus)+applied.spell_save_dc,attackBonus:attackBonus(scores[ab],proficiencyBonus)+applied.spell_attack}}const derivedSlots=deriveSpellSlots(slotInputs);const spellLimits=computeSpellLimits(limitInputs);const defenses={resistances:suppress(resolved,"resistances",composeDefenseEntries((_Q=(_P=resolved.definition.defenses)==null?void 0:_P.resistances)!=null?_Q:[],applied.defenses.resistances,featureEffects.resistances)),immunities:suppress(resolved,"immunities",composeDefenseEntries((_S=(_R=resolved.definition.defenses)==null?void 0:_R.immunities)!=null?_S:[],applied.defenses.immunities,featureEffects.immunities)),vulnerabilities:suppress(resolved,"vulnerabilities",composeDefenseEntries((_U=(_T=resolved.definition.defenses)==null?void 0:_T.vulnerabilities)!=null?_U:[],applied.defenses.vulnerabilities,featureEffects.vulnerabilities)),condition_immunities:suppress(resolved,"condition_immunities",composeDefenseEntries((_W=(_V=resolved.definition.defenses)==null?void 0:_V.condition_immunities)!=null?_W:[],applied.defenses.condition_immunities,featureEffects.condition_immunities))};const unarmedSpec=resolveUnarmedStrike(resolved);const attackRows=[...(_X=derivedEquipment==null?void 0:derivedEquipment.attacks)!=null?_X:[],...buildFeatureAttackRows(resolved,mods,profsForApply,proficiencyBonus,weaponAbilities,{unarmedAbilities:unarmedSpec.abilities,activeBuffs}),buildUnarmedRow(mods,proficiencyBonus,unarmedSpec)];const scopeOpts={pactPicked:pactWeaponIndexes(resolved,registry)!==null};const riderBindings=owner=>amountBindingsFor(owner,resolved,{proficiencyBonus,mods,spellcastingClasses});const ownSpells=(_Y=resolved.spells)!=null?_Y:[];const spellDamageRiders=featureEffects.spellDamageBonuses.flatMap(r=>{const reached=new Set([...spellsReached(r.targets,ownSpells),...spellsInScope(r.scope,ownSpells,id=>pickedDamageTypes(resolved,id))]);const spells=[...new Set(ownSpells.map(s=>s.slug))].filter(slug=>reached.has(slug));if(!spells.length)return[];const{owner,targets:_targets,scope,damage_type,...rest}=r;return[{...rest,amount:resolveAmountText(r.amount,riderBindings(owner)),...damage_type&&isCanonicalDamageType(damage_type)?{damage_type}:{},...(scope==null?void 0:scope.once)?{once:true}:{},spells}]});const scopedExtra=featureEffects.scopedExtraAttacks;const rowAttacks=attackRows.map(a=>scopedExtra.length?1+Math.max(featureEffects.extraAttack,...scopedExtra.filter(x=>scopeReachesRow(x.scope,a,scopeOpts)).map(x=>x.count)):void 0);return{totalLevel,proficiencyBonus,scores,mods,saves,proficiencies:profsForApply,skills,statBreakdowns:{skills:skillBreakdowns,saves:saveBreakdowns,speed:speedBreakdown,initiative:initiativeBreakdown,abilities:abilityScoreBreakdowns(resolved,overrides,applied,featureEffects,scores)},passives,senses,hp:{max:hpMax,current:resolved.state.hp.current,temp:resolved.state.hp.temp},hpBreakdown,ac,speed,speeds,initiative:init,spellcasting,spellcastingClasses,abilitySpellcasting,derivedSpellSlots:derivedSlots.standard,pactMagic:derivedSlots.pact,spellLimits,warnings,defenses,acBreakdown:acBreakdownDerived,acInformational:acInformationalDerived,savesInformational,spellcastingInformational,speedInformational,attacksPerAction:Math.max(1+featureEffects.extraAttack,...rowAttacks.filter(n=>n!==void 0)),attacks:attackRows.map((a,i)=>{var _a2,_b2,_c2;const critRange=Math.min((_a2=a.critRange)!=null?_a2:20,featureEffects.critRange);const conditionalCrits=[...(_b2=a.conditionalCrits)!=null?_b2:[],...featureEffects.conditionalCrits].filter(c=>c.minRoll<critRange);const riders=[...(_c2=a.damageRiders)!=null?_c2:[],...featureEffects.damageBonuses.filter(r=>riderReachesRow(r,a,scopeOpts))].map(r=>resolveDamageRider(r,a.damageType,riderBindings));const rollOptions=featureEffects.damageRollOptions.filter(o=>scopeReachesRow(o.scope,a,scopeOpts)).map(({scope:_scope,...o})=>o);const{critRange:_ownCrit,conditionalCrits:_ownConditional,...row}=a;return{...row,toHit:a.toHit+conditionEffects.d20_test_penalty,...critRange<20?{critRange}:{},...conditionalCrits.length?{conditionalCrits}:{},...featureEffects.attackNotes.length?{attackNotes:featureEffects.attackNotes}:{},...riders.length?{damageRiders:riders}:{},...rollOptions.length?{damageRollOptions:rollOptions}:{},...rowAttacks[i]!==void 0?{attacksPerAction:rowAttacks[i]}:{}}}),...spellDamageRiders.length?{spellDamageRiders}:{},equippedSlots:(_Z=derivedEquipment==null?void 0:derivedEquipment.equippedSlots)!=null?_Z:{},carriedWeight:(__=derivedEquipment==null?void 0:derivedEquipment.carriedWeight)!=null?__:0,attunementUsed:(_$=derivedEquipment==null?void 0:derivedEquipment.attunementUsed)!=null?_$:0,attunementLimit:(_ba=derivedEquipment==null?void 0:derivedEquipment.attunementLimit)!=null?_ba:(_aa=overrides.attunement_limit)!=null?_aa:Math.max(3,featureEffects.attunement_set),conditionEffects,rollModifiers:featureEffects.rollModifiers,saveOutcomes:featureEffects.saveOutcomes}}export{HAND_SET_HALF_SOURCE,abilityBonusBreakdown,abilityScoreBreakdowns,collectClassAsiBranch,collectClassFeatAbilityPoints,computeAbilityScores,computeProficiencies,fixedFeatAbilityIncrease,flattenRaceAsi,hitDiceAverageSum,hpLevelCount,initiativeBonus,multiclassMaxHP,parseDieSize,phbAverageForDie,recalc,resolveUnarmedStrike,riderReachesRow,scopeReachesRow,speedFromRace,unarmoredAC,unarmoredACBreakdown};
1
+ import{speciesIncreaseRule}from"../chunk-6IPWTOLU.js";import{buildFeatureAttackRows,buildUnarmedRow,computeAppliedBonuses,computeSlotsAndAttacks,emptyAppliedBonuses,pactWeaponIndexes}from"../chunk-YWKC2LJY.js";import"../chunk-T55DELVL.js";import"../chunk-SEOASDO4.js";import{amountBindingsFor,ownerClassSlug}from"../chunk-53SHSS4M.js";import"../chunk-PZ3ZZ5H5.js";import{computeConditionEffects,speedConditionNames}from"../chunk-VA3ZWV7C.js";import"../chunk-4E2GIWJE.js";import{collectChosenAbilityPoints,collectChosenProficiencies}from"../chunk-JSI2G6LE.js";import"../chunk-2EOGK6R6.js";import"../chunk-4AJYEWFQ.js";import"../chunk-RQZCGXUZ.js";import"../chunk-CLZRWPWT.js";import{assembleEffectFeatures,computeFeatureEffects,foldsNow,mergeDefenseItems,selfEffectsOf}from"../chunk-B2JSF2LL.js";import"../chunk-FOLHTMSC.js";import"../chunk-4JEF3CET.js";import{proficiencyKey}from"../chunk-VTQ4RWEG.js";import{itemLabel}from"../chunk-DXJ5NKKB.js";import{featPickSites,poolMemberSitesOf,spellsReached}from"../chunk-J27N3KUE.js";import"../chunk-RR26E7LH.js";import"../chunk-UBUKCRZ3.js";import{resourceLevelFor}from"../chunk-2OVDSMPY.js";import{computeSpellLimits,deriveSpellSlots,effectiveSpellcastingAbility,resolveSpellcasting}from"../chunk-PFQPP77Q.js";import{legacyAsiBranch}from"../chunk-QVWT67WA.js";import{toDefenseSlug}from"../chunk-LR6UMA5V.js";import"../chunk-E4E6YEN6.js";import"../chunk-CMIEZQL4.js";import"../chunk-O776WL7O.js";import{diceColumnAt,tableCellAt,unarmedDieColumnFor}from"../chunk-CSTAQQGX.js";import"../chunk-3LWOVRLA.js";import"../chunk-DVUXUIPV.js";import"../chunk-YGH7S5ZF.js";import"../chunk-NEMX7QGG.js";import"../chunk-56JK6VCL.js";import{effectiveArmor,isShieldArmor}from"../chunk-4IAMSRHD.js";import"../chunk-3QQOATV3.js";import"../chunk-DZITM5AG.js";import"../chunk-PZ4L2EEG.js";import"../chunk-QMEKQTUT.js";import{resolveAmountText}from"../chunk-VIP3FH2O.js";import"../chunk-EAARMPCW.js";import"../chunk-CAPYNIGK.js";import{bareEntitySlug,slugify}from"../chunk-63YJPWTM.js";import"../chunk-4KVVAENP.js";import"../chunk-7EL3GWWJ.js";import"../chunk-BREHZNTL.js";import{abilityModifier,attackBonus,isCanonicalDamageType,isChosenDamageType,proficiencyFromLevel,saveDC,savingThrow,skillBonus}from"../chunk-7FPQJDFD.js";import{ABILITY_KEYS,ALL_SKILLS,SKILL_ABILITY}from"../chunk-EVT7MGAC.js";import"../chunk-S5UCI27C.js";import"../chunk-EON7T2SN.js";import"../chunk-I26FHSI6.js";var lower=s=>(s!=null?s:"").trim().toLowerCase();function namedSpellSlug(ref){var _a;const inner=ref.replace(/^\[\[/,"").replace(/\]\]$/,"").split("|")[0];return slugify((_a=inner.split("/").pop())!=null?_a:inner)}function dealsDamage(spell){var _a,_b;return((_b=(_a=spell.damage)==null?void 0:_a.types)!=null?_b:[]).some(t=>t.trim()!=="")}function spellsInScope(scope,spells,pickedTypes){var _a,_b;if(!scope)return[];const picked=scope.damage_type_pick!==void 0?pickedTypes(scope.damage_type_pick).map(lower):null;const types=(_a=scope.damage_types)==null?void 0:_a.map(lower);const named=(_b=scope.spells)==null?void 0:_b.map(namedSpellSlug);const hit=spells.filter(({slug,entity:e})=>{var _a2,_b2,_c,_d,_e;if(!dealsDamage(e))return false;const own=((_b2=(_a2=e.damage)==null?void 0:_a2.types)!=null?_b2:[]).map(lower);if(scope.list!==void 0&&!((_c=e.classes)!=null?_c:[]).map(lower).includes(lower(scope.list)))return false;if(scope.level!==void 0&&((_d=e.level)!=null?_d:0)!==scope.level)return false;if(scope.school!==void 0&&lower(e.school)!==lower(scope.school))return false;if(types&&!own.some(t=>types.includes(t)))return false;if(picked&&!own.some(t=>picked.includes(t)))return false;if(named&&!named.includes(bareEntitySlug(slug))&&!named.includes(slugify((_e=e.name)!=null?_e:"")))return false;return true});return[...new Set(hit.map(s=>s.slug))]}function pickedDamageTypes(resolved,choiceId){var _a,_b,_c,_d,_e,_f;const out=new Set;for(const c of(_a=resolved.classes)!=null?_a:[]){for(const owner of[c.entity,c.subclass]){for(const[lvl,feats]of Object.entries((_b=owner==null?void 0:owner.features_by_level)!=null?_b:{})){for(const feat of feats!=null?feats:[]){for(const ch of(_c=feat.choices)!=null?_c:[]){if(ch.kind!=="select-inline"||ch.id!==choiceId)continue;const sel=((_e=(_d=c.choices)==null?void 0:_d[Number(lvl)])!=null?_e:{})[ch.id];if(typeof sel!=="string")continue;const opt=ch.options.find(o=>o.value===sel);for(const word of`${sel} ${(_f=opt==null?void 0:opt.label)!=null?_f:""}`.split(/[^A-Za-z]+/)){if(word&&isCanonicalDamageType(word))out.add(word.toLowerCase())}}}}}}return[...out]}var OTHER_MODES=["fly","swim","climb","burrow"];function wornArmor(slots,registry){const body=slots==null?void 0:slots.armor;const armor=body&&registry?effectiveArmor(body.entity,registry):null;const isBody=armor!==null&&!isShieldArmor(armor);const score=isBody?strengthRequirementOf(armor):void 0;return{heavy:isBody&&armor.category==="heavy",armor:isBody,shield:(slots==null?void 0:slots.shield)!==void 0,strength:body&&isBody&&typeof score==="number"&&score>0?{label:itemLabel(body.entry,body.entity),score}:null}}function strengthRequirementOf(armor){var _a;return(_a=armor.strength_requirement)!=null?_a:armor.strength_required}function speedTermActive(t,worn){var _a;const holds=w=>w==="heavy-armor"?worn.heavy:w==="armor"?worn.armor:worn.shield;return!((_a=t.inactiveWhile)!=null?_a:[]).some(holds)}function armorStrengthPenalty(worn,str,ignoredBy){if(!worn.strength||str>=worn.strength.score||ignoredBy.length>0)return null;return{source:`${worn.strength.label} (Strength ${str} < ${worn.strength.score})`,amount:-ARMOR_STRENGTH_PENALTY}}var ARMOR_STRENGTH_PENALTY=10;function speedAfterConditions(pre,ce){if(ce.speed_floor_zero)return 0;return Math.max(0,Math.floor(pre*ce.speed_multiplier-ce.speed_reduction_ft))}var term=(source,amount,condition)=>({source,amount,...condition?{condition}:{}});function walkTerms(i,species){var _a,_b,_c;const terms=[term(species,i.walk.race)];for(const f of i.resolved.feats){const bonus=f.speed_bonus;if(typeof bonus==="number"&&bonus!==0)terms.push(term((_a=f.name)!=null?_a:"Feat",bonus))}for(const t of i.applied.speed_terms)if(t.mode==="walk"&&t.kind==="bonus")terms.push(term(t.source,t.amount));for(const t of i.features.speed_terms)if(t.mode==="walk"&&!t.set)terms.push(term(t.label,t.value,t.condition));if(i.armorPenalty)terms.push(i.armorPenalty.term);if(i.walk.base>i.walk.additive){const itemWins=i.applied.speed_walk_set===i.walk.base&&i.applied.speed_walk_set>i.features.speed_walk_set;const source=itemWins?(_b=i.applied.speed_walk_set_terms.find(t=>t.amount===i.walk.base))==null?void 0:_b.source:(_c=i.features.speed_terms.find(t=>t.mode==="walk"&&t.set&&t.value===i.walk.base))==null?void 0:_c.label;terms.push(term(source!=null?source:"Minimum speed",i.walk.base-i.walk.additive))}if(i.walk.final!==i.walk.base)terms.push(term(conditionLabel(i),i.walk.final-i.walk.base));return terms}var conditionLabel=i=>i.conditionNames.join(", ")||"Conditions";function otherLine(i,mode,species){var _a,_b,_c,_d,_e;const grants=[];const own=(_b=(_a=i.resolved.race)==null?void 0:_a.speed)==null?void 0:_b[mode];if(typeof own==="number"&&own>0)grants.push(term(species,own));for(const t of i.features.speed_terms)if(t.mode===mode&&t.set&&t.value>0)grants.push(term(t.label,t.value,t.condition));for(const t of i.applied.speed_terms)if(t.mode===mode&&t.kind==="grant"&&t.amount>0)grants.push(term(t.source,t.amount));for(const t of i.applied.speed_terms)if(t.mode===mode&&t.kind==="walk")grants.push({...term(t.source,i.walk.base),equalsWalk:true});for(const t of i.features.speed_terms)if(t.mode===mode&&t.equalsWalk)grants.push({...term(t.label,i.walk.base,t.condition),equalsWalk:true});if(grants.length===0)return null;const penalty=((_c=i.armorPenalty)==null?void 0:_c.everyMode)?-i.armorPenalty.term.amount:0;const after=g=>g.equalsWalk?g.amount:g.amount-Math.min(penalty,g.amount);const best=grants.reduce((a,b)=>after(b)>after(a)?b:a);if(best.amount<=0)return null;const{equalsWalk,...bestTerm}=best;const bonuses=i.features.speed_terms.filter(t=>t.mode===mode&&!t.set&&!t.equalsWalk&&t.value!==0).map(t=>term(t.label,t.value,t.condition));const terms=[bestTerm,...bonuses];if(i.armorPenalty&&penalty>0&&!equalsWalk){const cut=Math.min(penalty,terms.reduce((s,t)=>s+t.amount,0));if(cut>0)terms.push({...i.armorPenalty.term,amount:-cut})}const pre=terms.reduce((s,t)=>s+t.amount,0);const value=speedAfterConditions(pre,i.conditions);if(value!==pre)terms.push(term(conditionLabel(i),value-pre));return{mode,value,...equalsWalk&&bonuses.length===0?{equalsWalk:true}:{},...mode==="fly"&&((_e=(_d=i.resolved.race)==null?void 0:_d.speed)==null?void 0:_e.hover)===true&&typeof own==="number"&&own>0?{hover:true}:{},terms}}function buildSpeedLines(i){var _a,_b;const species=(_b=(_a=i.resolved.race)==null?void 0:_a.name)!=null?_b:"Base speed";const lines=[{mode:"walk",value:i.walk.final,terms:walkTerms(i,species)}];for(const mode of OTHER_MODES){const line=otherLine(i,mode,species);if(line)lines.push(line)}return lines}var WEAPON_CATEGORY_WORDS=new Set(["simple","martial","simple-melee","simple-ranged","martial-melee","martial-ranged","natural"]);function phbAverageForDie(hitDieStr){const n=parseDieSize(hitDieStr);if(n==null)return 4;return Math.floor(n/2)+1}function parseDieSize(die){if(die==null)return null;if(typeof die==="number")return die;const m=die.match(/^d?(\d+)$/i);return m?parseInt(m[1],10):null}function skillSlugFromDisplay(display){return display.toLowerCase().replace(/\s+/g,"-")}function skillSlugToAbilityLookup(slug){return slug.replace(/-/g," ")}function flattenRaceAsi(race){var _a;const out={};if(!(race==null?void 0:race.ability_score_increases))return out;for(const asi of race.ability_score_increases){if("ability"in asi){out[asi.ability]=((_a=out[asi.ability])!=null?_a:0)+asi.amount}}return out}function subraceAsi(resolved){var _a,_b,_c,_d,_e;const subSlug=(_b=(_a=resolved.definition.subrace)==null?void 0:_a.replace(/\[\[|\]\]/g,""))!=null?_b:null;if(!subSlug)return[];const subraces=(_d=(_c=resolved.race)==null?void 0:_c.subraces)!=null?_d:[];const sub=subraces.find(s=>s.slug===subSlug);return(_e=sub==null?void 0:sub.ability_score_increases)!=null?_e:[]}function collectClassAsiBranch(resolved){var _a;const out={};for(const c of resolved.classes){for(const choice of Object.values(c.choices)){const alloc=legacyAsiBranch(choice);if(!alloc)continue;for(const ab of ABILITY_KEYS){const v=alloc[ab];if(typeof v==="number")out[ab]=((_a=out[ab])!=null?_a:0)+v}}}return out}function abilityBonusBreakdown(resolved,featureEffects){var _a,_b,_c,_d,_e,_f,_g;const species=speciesIncreaseTotals(resolved);const suppressed=speciesIncreaseRule(resolved).suppressed;const origin=collectChosenAbilityPoints(resolved);const classAsi=collectClassAsiBranch(resolved);const featPoints=collectClassFeatAbilityPoints(resolved);const out={};for(const ab of ABILITY_KEYS){let feat=(_a=featPoints[ab])!=null?_a:0;for(const f of resolved.feats){const bonus=(_b=f.ability_bonuses)==null?void 0:_b[ab];if(typeof bonus==="number")feat+=bonus;feat+=(_c=fixedFeatAbilityIncrease(f)[ab])!=null?_c:0}const sp=(_d=species[ab])!=null?_d:0;out[ab]={species:suppressed?0:sp,speciesNotUsed:suppressed?sp:0,background:(_e=origin.background[ab])!=null?_e:0,class:((_f=classAsi[ab])!=null?_f:0)+((_g=featureEffects==null?void 0:featureEffects.ability_bonus[ab])!=null?_g:0),feat}}return out}function speciesIncreaseTotals(resolved){var _a,_b;const out={...flattenRaceAsi(resolved.race)};for(const asi of subraceAsi(resolved)){if(asi.ability&&typeof asi.amount==="number")out[asi.ability]=((_a=out[asi.ability])!=null?_a:0)+asi.amount}const picked=collectChosenAbilityPoints(resolved).race;for(const ab of ABILITY_KEYS){const v=picked[ab];if(typeof v==="number")out[ab]=((_b=out[ab])!=null?_b:0)+v}return out}function fixedFeatAbilityIncrease(f){var _a;const g=f.grants_asi;if(!g||typeof g.amount!=="number"||g.amount<=0||!Array.isArray(g.pool)||g.pool.length!==1)return{};if(((_a=f.choices)!=null?_a:[]).some(c=>c.kind==="ability-points"))return{};const ab=g.pool[0];return ABILITY_KEYS.includes(ab)?{[ab]:g.amount}:{}}function hitDiceAverageSum(classes){var _a;let total=0;let firstLevelCounted=false;for(const c of classes){const die=parseDieSize((_a=c.entity)==null?void 0:_a.hit_die);if(!c.entity||die==null||c.level<1)continue;for(let lvl=1;lvl<=c.level;lvl++){if(!firstLevelCounted){total+=die;firstLevelCounted=true}else{total+=Math.floor(die/2)+1}}}return total}function hpLevelCount(classes){var _a;let count=0;for(const c of classes){const die=parseDieSize((_a=c.entity)==null?void 0:_a.hit_die);if(!c.entity||die==null||c.level<1)continue;count+=c.level}return count}function multiclassMaxHP(classes,conMod){return Math.max(1,hitDiceAverageSum(classes)+conMod*hpLevelCount(classes))}function resolveDamageRider(rider,rowDamageType,bindings){const{owner,scope:_scope,...rest}=rider;const out={...rest,amount:resolveAmountText(rider.amount,bindings(owner))};if(rider.damage_type!==void 0&&!isChosenDamageType(rider.damage_type)){const resolved=isCanonicalDamageType(rider.damage_type)?rider.damage_type:rowDamageType;if(resolved)out.damage_type=resolved;else delete out.damage_type}return out}function riderReachesRow(rider,row,opts){return scopeReachesRow(rider.scope,row,opts)}function scopeReachesRow(scope,row,opts){if(!(scope==null?void 0:scope.length))return true;const unarmedStrike=row.unarmed===true||row.naturalWeapon===true;return scope.some(word=>{switch(word){case"weapon":return!unarmedStrike;case"pact-weapon":return(opts==null?void 0:opts.pactPicked)===true?row.pactWeapon===true:!unarmedStrike;case"unarmed":return unarmedStrike;case"melee":case"ranged":return row.weaponCategory===word;case"finesse":case"thrown":case"heavy":return row.properties.includes(word)}})}function unarmoredAC(resolved,mods,warnings){return unarmoredACBreakdown(resolved,mods,warnings).total}function unarmoredACBreakdown(resolved,mods,warnings,shieldBonus=0){var _a,_b,_c,_d,_e,_f;const baseTerms=[{source:"Unarmored",amount:10,kind:"unarmored"},{source:"DEX modifier",amount:mods.dex,kind:"dex"}];const{activeBuffs}=assembleEffectFeatures(resolved);const candidates=[{total:10+mods.dex,terms:baseTerms,shieldAllowed:true}];for(const rf of[...resolved.features,...(_a=resolved.itemFeatures)!=null?_a:[]]){if(!foldsNow(rf,activeBuffs))continue;for(const eff of selfEffectsOf(rf.feature)){if(eff.kind!=="unarmored-ac")continue;const base=(_b=eff.base)!=null?_b:10;const terms=[{source:"Unarmored",amount:base,kind:"unarmored"}];let total=base;for(const ab of eff.abilities){terms.push(ab==="dex"?{source:"DEX modifier",amount:mods.dex,kind:"dex"}:{source:`${ab.toUpperCase()} modifier (${(_c=rf.feature.name)!=null?_c:"Unarmored"})`,amount:mods[ab],kind:"ability"});total+=mods[ab]}candidates.push({total,terms,shieldAllowed:eff.allow_shield===true})}}if(candidates.length>1){const applied=c=>c.total+(c.shieldAllowed?shieldBonus:0);let best=candidates[0];for(const c of candidates)if(applied(c)>applied(best))best=c;return best}for(const rf of resolved.features){const feat=rf.feature;if((_d=feat.unarmored_defense)==null?void 0:_d.ability){const ab=feat.unarmored_defense.ability;const amt=(_e=mods[ab])!=null?_e:0;const terms=[...baseTerms,{source:`${ab.toUpperCase()} modifier (Unarmored Defense)`,amount:amt,kind:"ability"}];return{total:10+mods.dex+amt,terms,shieldAllowed:true}}}for(const rf of resolved.features){const name=((_f=rf.feature.name)!=null?_f:"").toLowerCase();if(!/unarmored\s*defense/.test(name))continue;if(rf.source.kind==="class"&&rf.source.slug.includes("monk")){const terms=[...baseTerms,{source:"WIS modifier (Unarmored Defense)",amount:mods.wis,kind:"ability"}];return{total:10+mods.dex+mods.wis,terms,shieldAllowed:true}}if(rf.source.kind==="class"&&rf.source.slug.includes("barbarian")){const terms=[...baseTerms,{source:"CON modifier (Unarmored Defense)",amount:mods.con,kind:"ability"}];return{total:10+mods.dex+mods.con,terms,shieldAllowed:true}}}return{total:10+mods.dex,terms:baseTerms,shieldAllowed:true}}function resolveUnarmedStrike(resolved){var _a,_b,_c;const dice=[];const abilities=new Set;const classOf=rf=>rf.source.kind==="class"?resolved.classes.find(c=>{var _a2;return((_a2=c.entity)==null?void 0:_a2.slug)===rf.source.slug}):void 0;const readDie=(rf,d)=>{var _a2,_b2;if(typeof d==="string")return d;if(!d)return void 0;const cls=classOf(rf);return cls?(_b2=diceColumnAt((_a2=cls.entity)==null?void 0:_a2.table,cls.level,d.column))!=null?_b2:void 0:void 0};for(const rf of resolved.features){const authored=selfEffectsOf(rf.feature).filter(e=>e.kind==="unarmed-strike");for(const e of authored){const d2=readDie(rf,e.dice);if(d2)dice.push(d2);for(const ab of(_a=e.abilities)!=null?_a:[])abilities.add(ab)}if(authored.length||rf.source.kind!=="class")continue;const slug=((_c=(_b=rf.feature.id)!=null?_b:rf.feature.name)!=null?_c:"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"");const column=unarmedDieColumnFor(slug);if(!column)continue;const d=readDie(rf,{column});if(!d)continue;dice.push(d);abilities.add("dex")}const avg=d=>{const m=/^(\d+)d(\d+)$/i.exec(d);return m?Number(m[1])*(Number(m[2])+1)/2:1};const best=dice.sort((a,b)=>avg(b)-avg(a))[0];return{...best?{dice:best}:{},...abilities.size?{abilities:[...abilities]}:{}}}function initiativeBonus(dexMod,feats,edition){var _a,_b,_c;let bonus=dexMod;for(const f of feats){const featEdition=(_a=f.edition)!=null?_a:edition;const hasData=((_b=f.effects)!=null?_b:[]).some(e=>e.kind==="initiative-bonus");if(bareEntitySlug((_c=f.slug)!=null?_c:"")==="alert"&&featEdition==="2014"&&!hasData)bonus+=5;const initBonus=f.initiative_bonus;if(typeof initBonus==="number")bonus+=initBonus}return bonus}function speedFromRace(resolved){var _a,_b,_c;const base=(_c=(_b=(_a=resolved.race)==null?void 0:_a.speed)==null?void 0:_b.walk)!=null?_c:30;let extra=0;for(const f of resolved.feats){const bonus=f.speed_bonus;if(typeof bonus==="number")extra+=bonus}return base+extra}function collectClassFeatAbilityPoints(resolved){var _a;const out={};for(const t of classFeatAbilityPointTerms(resolved))out[t.ability]=((_a=out[t.ability])!=null?_a:0)+t.amount;return out}function classFeatAbilityPointTerms(resolved){var _a;const out=[];const stripRef=ref=>ref.replace(/^\[\[/,"").replace(/\]\]$/,"");const featBySlug=new Map;for(const f of resolved.feats)featBySlug.set(f.slug,f);const sites=featPickSites(resolved.classes,poolMemberSitesOf(resolved),ci=>{var _a2,_b,_c,_d;return(_d=(_c=(_b=(_a2=resolved.classes)==null?void 0:_a2[ci])==null?void 0:_b.entity)==null?void 0:_c.slug)!=null?_d:null});for(const site of sites){{const feat=featBySlug.get(stripRef(site.slug));if(!feat)continue;for(const ch of(_a=feat.choices)!=null?_a:[]){if(ch.kind!=="ability-points")continue;const raw=site.read(ch.id);if(!raw||typeof raw!=="object"||Array.isArray(raw))continue;let left=ch.points;for(const ab of ABILITY_KEYS){if(ch.pool&&!ch.pool.includes(ab))continue;const v=raw[ab];if(typeof v!=="number"||v<=0||left<=0)continue;const take=Math.min(v,ch.max_per,left);out.push({feat,ability:ab,amount:take});left-=take}}}}return out}function computeAbilityScores(resolved,overrides){var _a,_b,_c,_d,_e,_f;const out={...resolved.definition.abilities};if(!speciesIncreaseRule(resolved).suppressed){const species=speciesIncreaseTotals(resolved);for(const ab of ABILITY_KEYS){const b=species[ab];if(typeof b==="number")out[ab]=((_a=out[ab])!=null?_a:0)+b}}const originPoints=collectChosenAbilityPoints(resolved);for(const ab of ABILITY_KEYS){const v=originPoints.background[ab];if(typeof v==="number")out[ab]=((_b=out[ab])!=null?_b:0)+v}const classAsi=collectClassAsiBranch(resolved);for(const ab of ABILITY_KEYS){const v=classAsi[ab];if(typeof v==="number")out[ab]=((_c=out[ab])!=null?_c:0)+v}const featPoints=collectClassFeatAbilityPoints(resolved);for(const ab of ABILITY_KEYS){const v=featPoints[ab];if(typeof v==="number")out[ab]=((_d=out[ab])!=null?_d:0)+v}for(const f of resolved.feats){const bonuses=f.ability_bonuses;if(bonuses){for(const ab of ABILITY_KEYS){const v=bonuses[ab];if(typeof v==="number")out[ab]=((_e=out[ab])!=null?_e:0)+v}}for(const[ab,v]of Object.entries(fixedFeatAbilityIncrease(f)))out[ab]=((_f=out[ab])!=null?_f:0)+v}if(overrides.scores){for(const ab of ABILITY_KEYS){const v=overrides.scores[ab];if(typeof v==="number")out[ab]=v}}for(const ab of ABILITY_KEYS){if(typeof out[ab]!=="number")out[ab]=10}return out}function abilityScoreBreakdowns(resolved,overrides,applied,featureEffects,scores){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n;const suppressed=speciesIncreaseRule(resolved).suppressed;const species=speciesIncreaseTotals(resolved);const origin=collectChosenAbilityPoints(resolved);const classAsi=collectClassAsiBranch(resolved);const featTerms=classFeatAbilityPointTerms(resolved);const out={};for(const ab of ABILITY_KEYS){const base=(_a=resolved.definition.abilities)==null?void 0:_a[ab];const terms=[{source:"Base score",amount:typeof base==="number"?base:10}];const add=(source,amount,notUsed=false)=>{if(!amount)return;const prior=terms.find((t,i)=>i>0&&t.source===source&&t.notUsed===true===notUsed);if(prior)prior.amount+=amount;else terms.push(notUsed?{source,amount,notUsed:true}:{source,amount})};add((_c=(_b=resolved.race)==null?void 0:_b.name)!=null?_c:"Species",(_d=species[ab])!=null?_d:0,suppressed);add((_f=(_e=resolved.background)==null?void 0:_e.name)!=null?_f:"Background",(_g=origin.background[ab])!=null?_g:0);add("Ability Score Improvement",(_h=classAsi[ab])!=null?_h:0);for(const t of featTerms)if(t.ability===ab)add(t.feat.name,t.amount);for(const f of resolved.feats){const bonus=(_i=f.ability_bonuses)==null?void 0:_i[ab];if(typeof bonus==="number")add(f.name,bonus);add(f.name,(_j=fixedFeatAbilityIncrease(f)[ab])!=null?_j:0)}for(const t of(_k=applied.ability_terms)!=null?_k:[])if(t.ability===ab)add(t.source,t.amount);for(const t of(_l=featureEffects.ability_bonus_terms)!=null?_l:[])if(t.ability===ab)add(t.source,t.amount);const sum=terms.reduce((n,t)=>n+(t.notUsed?0:t.amount),0);const b={total:scores[ab],terms};let best;for(const t of(_m=applied.ability_static_terms)!=null?_m:[])if(t.ability===ab&&(!best||t.value>best.value))best={source:t.source,value:t.value};if(best&&best.value>sum)b.set=best;const o=(_n=overrides.scores)==null?void 0:_n[ab];if(typeof o==="number")b.override=o;out[ab]=b}return out}function normalizeArmorProf(input){var _a,_b;if(!input)return{categories:[],specific:[]};if(Array.isArray(input))return{categories:input,specific:[]};return{categories:(_a=input.categories)!=null?_a:[],specific:(_b=input.specific)!=null?_b:[]}}function normalizeWeaponToolProf(input){var _a,_b,_c;if(!input)return{categories:[],specific:[]};if(Array.isArray(input))return{categories:[],specific:input};return{categories:(_a=input.categories)!=null?_a:[],specific:((_b=input.fixed)!=null?_b:[]).concat((_c=input.specific)!=null?_c:[])}}function mergeInto(target,source){for(const c of source.categories)if(!target.categories.includes(c))target.categories.push(c);for(const s of source.specific)if(!target.specific.includes(s))target.specific.push(s)}function applyArmorWeaponOverrides(profs,overrides){var _a,_b;for(const kind of["armor","weapons"]){const ov=overrides==null?void 0:overrides[kind];if(!ov)continue;const set=profs[kind];const key=v=>proficiencyKey(kind,v);const removes=new Set(((_a=ov.remove)!=null?_a:[]).map(key));for(const v of(_b=ov.add)!=null?_b:[]){const k=key(v);if(removes.has(k))continue;const category=kind==="armor"||k==="simple"||k==="martial";const target=category?set.categories:set.specific;if(!target.some(e=>key(e)===k))target.push(category?k:v)}set.categories=set.categories.filter(e=>!removes.has(key(e)));set.specific=set.specific.filter(e=>!removes.has(key(e)))}}var ORIGIN_RANK={manual:0,equipment:1,grant:2};function composeDefenseEntries(manual,equipment,grants){const byValue=new Map;for(const raw of manual){const value=toDefenseSlug(raw);if(!value||byValue.has(value))continue;byValue.set(value,{value,label:raw.trim(),origin:"manual"})}const consider=(list,origin)=>{var _a,_b,_c,_d;for(const g of list){const value=toDefenseSlug(g.value);if(!value)continue;const existing=byValue.get(value);if(!existing){byValue.set(value,{value,label:g.value.trim(),origin,sources:[...g.sources],...g.condition?{condition:g.condition}:{},...((_a=g.items)==null?void 0:_a.length)?{items:g.items.map(it=>({...it}))}:{}});continue}if(ORIGIN_RANK[origin]>ORIGIN_RANK[existing.origin])existing.origin=origin;const sources=(_b=existing.sources)!=null?_b:existing.sources=[];for(const src of g.sources)if(!sources.includes(src))sources.push(src);if(!existing.condition&&g.condition)existing.condition=g.condition;if((_c=g.items)==null?void 0:_c.length)mergeDefenseItems((_d=existing.items)!=null?_d:existing.items=[],g.items)}};consider(equipment,"equipment");consider(grants,"grant");return[...byValue.values()]}function suppress(resolved,bucket,entries){var _a,_b,_c,_d,_e;const suppressed=new Set(((_e=(_d=(_c=(_b=(_a=resolved.definition)==null?void 0:_a.overrides)==null?void 0:_b.defenses)==null?void 0:_c[bucket])==null?void 0:_d.remove)!=null?_e:[]).map(toDefenseSlug));return entries.filter(e=>!suppressed.has(e.value))}function computeProficiencies(resolved){var _a,_b,_c,_d,_e,_f,_g;const armor={categories:[],specific:[]};const weapons={categories:[],specific:[]};const tools={categories:[],specific:[]};const languages=new Set;for(const c of resolved.classes){const p=(_a=c.entity)==null?void 0:_a.proficiencies;if(!p)continue;mergeInto(armor,normalizeArmorProf(p.armor));mergeInto(weapons,normalizeWeaponToolProf(p.weapons));mergeInto(tools,normalizeWeaponToolProf(p.tools));(_b=p.languages)==null?void 0:_b.forEach(l=>languages.add(l))}const racePr=(_c=resolved.race)==null?void 0:_c.proficiencies;if(racePr){mergeInto(armor,normalizeArmorProf(racePr.armor));mergeInto(weapons,normalizeWeaponToolProf(racePr.weapons));mergeInto(tools,normalizeWeaponToolProf(racePr.tools));(_d=racePr.languages)==null?void 0:_d.forEach(l=>languages.add(l))}const bgPr=(_e=resolved.background)==null?void 0:_e.proficiencies;if(bgPr){mergeInto(armor,normalizeArmorProf(bgPr.armor));mergeInto(weapons,normalizeWeaponToolProf(bgPr.weapons));mergeInto(tools,normalizeWeaponToolProf(bgPr.tools));(_f=bgPr.languages)==null?void 0:_f.forEach(l=>languages.add(l))}for(const f of resolved.feats){const grants=f.grants_proficiency;if(!grants)continue;mergeInto(armor,normalizeArmorProf(grants.armor));mergeInto(weapons,normalizeWeaponToolProf(grants.weapons));mergeInto(tools,normalizeWeaponToolProf(grants.tools));(_g=grants.languages)==null?void 0:_g.forEach(l=>languages.add(l))}return{armor,weapons,tools,languages:Array.from(languages).sort(),saves:[]}}var HAND_SET_HALF_SOURCE="Set by you";function recalc(resolved,registry){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x,_y,_z,_A,_B,_C,_D,_E,_F,_G,_H,_I,_J,_K,_L,_M,_N,_O,_P,_Q,_R,_S,_T,_U,_V,_W,_X,_Y,_Z,__,_$,_aa,_ba;const warnings=[];const overrides=(_a=resolved.definition.overrides)!=null?_a:{};const chosenProfs=collectChosenProficiencies(resolved);const{features:effectFeatures,activeBuffs}=assembleEffectFeatures(resolved);const tableDiceFor=(src,column,level)=>{var _a2;const cls=src.kind==="class"?resolved.classes.find(c=>{var _a3;return((_a3=c.entity)==null?void 0:_a3.slug)===src.slug}):src.kind==="subclass"?resolved.classes.find(c=>{var _a3;return((_a3=c.subclass)==null?void 0:_a3.slug)===src.slug}):void 0;return cls?diceColumnAt((_a2=cls.entity)==null?void 0:_a2.table,level,column):null};const tableCellFor=(src,column)=>{var _a2;const slug=ownerClassSlug(src,resolved);const cls=slug?resolved.classes.find(c=>{var _a3;return((_a3=c.entity)==null?void 0:_a3.slug)===slug}):void 0;return cls?tableCellAt((_a2=cls.entity)==null?void 0:_a2.table,cls.level,column):null};const featureEffects=computeFeatureEffects(effectFeatures,{activeBuffs,levelFor:src=>resourceLevelFor(src,resolved),tableDiceFor,tableCellFor});const profsForApply=computeProficiencies(resolved);for(const t of chosenProfs.tools){if(!profsForApply.tools.specific.includes(t))profsForApply.tools.specific.push(t)}for(const l of chosenProfs.languages){if(!profsForApply.languages.includes(l))profsForApply.languages.push(l)}for(const w of chosenProfs.weapons){if(!profsForApply.weapons.specific.includes(w))profsForApply.weapons.specific.push(w)}for(const t of featureEffects.proficiencies.tools){if(!profsForApply.tools.specific.includes(t))profsForApply.tools.specific.push(t)}for(const l of featureEffects.proficiencies.languages){if(!profsForApply.languages.includes(l))profsForApply.languages.push(l)}for(const a of featureEffects.proficiencies.armor){if(!profsForApply.armor.categories.includes(a))profsForApply.armor.categories.push(a)}for(const w of featureEffects.proficiencies.weapons){if(!profsForApply.weapons.categories.includes(w))profsForApply.weapons.categories.push(w);if(!WEAPON_CATEGORY_WORDS.has(w)&&!profsForApply.weapons.specific.includes(w)){profsForApply.weapons.specific.push(w)}}profsForApply.languages.sort();applyArmorWeaponOverrides(profsForApply,(_b=resolved.definition)==null?void 0:_b.overrides);const applied=registry?computeAppliedBonuses(resolved,profsForApply,registry,warnings):emptyAppliedBonuses();const savesInformational=applied.informational.filter(i=>i.field==="saving_throws");const spellcastingInformational=applied.informational.filter(i=>i.field==="spell_attack"||i.field==="spell_save_dc");const speedInformational=applied.informational.filter(i=>i.field.startsWith("speed."));const baseScores=computeAbilityScores(resolved,overrides);const scores={...baseScores};for(const ab of ABILITY_KEYS){const bonus=applied.ability_bonuses[ab];scores[ab]+=(typeof bonus==="number"?bonus:0)+((_c=featureEffects.ability_bonus[ab])!=null?_c:0)}for(const ab of ABILITY_KEYS){const stat=applied.ability_statics[ab];if(typeof stat==="number"&&stat>scores[ab])scores[ab]=stat}if(overrides.scores){for(const ab of ABILITY_KEYS){const o=overrides.scores[ab];if(typeof o==="number")scores[ab]=o}}const mods={str:abilityModifier(scores.str),dex:abilityModifier(scores.dex),con:abilityModifier(scores.con),int:abilityModifier(scores.int),wis:abilityModifier(scores.wis),cha:abilityModifier(scores.cha)};const totalLevel=resolved.classes.reduce((s,c)=>s+c.level,0);const proficiencyBonus=proficiencyFromLevel(totalLevel||1);const conditionEffects=computeConditionEffects(resolved.state,resolved.definition.edition,scores);const firstClass=(_e=(_d=resolved.classes[0])==null?void 0:_d.entity)!=null?_e:null;const saveProfs=new Set((_f=firstClass==null?void 0:firstClass.saving_throws)!=null?_f:[]);for(const ab of featureEffects.proficiencies.saves)saveProfs.add(ab);for(const ab of chosenProfs.saves)saveProfs.add(ab);const saves={};const saveBreakdowns={};const activeSaveBonusTerms=featureEffects.save_bonus_terms.filter(t=>{var _a2;return t.inactiveWhile==="incapacitated"?!conditionEffects.actions_disabled:t.inactiveWhile==="unconscious"?!((_a2=resolved.state.conditions)!=null?_a2:[]).includes("unconscious"):true});for(const ab of ABILITY_KEYS){const override=(_g=overrides.saves)==null?void 0:_g[ab];const prof=(_h=override==null?void 0:override.proficient)!=null?_h:saveProfs.has(ab);const featureTerms=[];for(const t of activeSaveBonusTerms){if(t.saves.length>0&&!t.saves.includes(ab))continue;const amount=Math.max(t.minimum,mods[t.ability]);const prior=featureTerms.find(x=>x.source===t.label);if(prior===void 0)featureTerms.push({source:t.label,amount});else if(amount>prior.amount)prior.amount=amount}const derivedBonus=savingThrow(scores[ab],prof,proficiencyBonus)+applied.save_bonus+featureTerms.reduce((sum,t)=>sum+t.amount,0)+conditionEffects.d20_test_penalty;const bonus=(_i=override==null?void 0:override.bonus)!=null?_i:derivedBonus;saves[ab]={bonus,proficient:prof};saveBreakdowns[ab]=[{source:ab.toUpperCase(),amount:mods[ab]},...prof?[{source:"Proficiency",amount:proficiencyBonus}]:[],...applied.save_terms.map(t=>({...t})),...featureTerms,...conditionEffects.d20_test_penalty?[{source:`Exhaustion ${conditionEffects.exhaustion_level}`,amount:conditionEffects.d20_test_penalty}]:[]]}const profSet=new Set([...resolved.definition.skills.proficient,...(_k=(_j=resolved.background)==null?void 0:_j.skill_proficiencies)!=null?_k:[],...chosenProfs.skills,...featureEffects.proficiencies.skills]);const expSet=new Set([...resolved.definition.skills.expertise,...chosenProfs.expertise,...featureEffects.proficiencies.skillExpertise]);const skills={};const skillBreakdowns={};for(const skill of ALL_SKILLS){const skillKey=skillSlugFromDisplay(skill);const ab=SKILL_ABILITY[skillSlugToAbilityLookup(skillKey)];const override=(_l=overrides.skills)==null?void 0:_l[skillKey];const tri=(_m=override==null?void 0:override.proficiency)!=null?_m:expSet.has(skillKey)?"expertise":profSet.has(skillKey)?"proficient":"none";const skillTerms=featureEffects.skill_bonus_terms.filter(t=>t.skills.includes(skillKey)).map(t=>({source:t.label,amount:Math.max(t.minimum,mods[t.ability])}));const halfProfTerms=tri!=="none"?[]:[...featureEffects.half_proficiency_terms.filter(t=>t.skills.length===0||t.skills.includes(skillKey)).map(t=>({source:t.label,amount:t.round==="up"?Math.ceil(proficiencyBonus/2):Math.floor(proficiencyBonus/2)})),...((_n=resolved.definition.skills.half)==null?void 0:_n.includes(skillKey))?[{source:HAND_SET_HALF_SOURCE,amount:Math.floor(proficiencyBonus/2)}]:[]];const halfProfBest=halfProfTerms.length?halfProfTerms.reduce((best,t)=>t.amount>best.amount?t:best):null;const bonus=(_p=override==null?void 0:override.bonus)!=null?_p:skillBonus(scores[ab],tri,proficiencyBonus)+skillTerms.reduce((sum,t)=>sum+t.amount,0)+((_o=halfProfBest==null?void 0:halfProfBest.amount)!=null?_o:0)+conditionEffects.d20_test_penalty;skillBreakdowns[skillKey]=[{source:ab.toUpperCase(),amount:mods[ab]},...tri!=="none"?[{source:tri==="expertise"?"Expertise":"Proficiency",amount:proficiencyBonus*(tri==="expertise"?2:1)}]:[],...skillTerms,...halfProfBest?[halfProfBest]:[],...conditionEffects.d20_test_penalty?[{source:"Conditions",amount:conditionEffects.d20_test_penalty}]:[]];skills[skillKey]={bonus,proficiency:tri,ability:ab,...halfProfBest?{halfProficiency:{source:halfProfBest.source,amount:halfProfBest.amount}}:{}}}const passives={perception:(_r=(_q=overrides.passives)==null?void 0:_q.perception)!=null?_r:10+skills.perception.bonus,investigation:(_t=(_s=overrides.passives)==null?void 0:_s.investigation)!=null?_t:10+skills.investigation.bonus,insight:(_v=(_u=overrides.passives)==null?void 0:_u.insight)!=null?_v:10+skills.insight.bonus};const hpRolled=(_x=(_w=overrides.hp)==null?void 0:_w.rolled)!=null?_x:null;const hpModifier=(_z=(_y=overrides.hp)==null?void 0:_y.modifier)!=null?_z:null;const averageDiceSum=hitDiceAverageSum(resolved.classes);const conLevels=hpLevelCount(resolved.classes);const diceSum=hpRolled!=null?hpRolled:averageDiceSum;const diceConRaw=diceSum+mods.con*conLevels;const diceConClamped=Math.max(1,diceConRaw);const hpMaxDerived=diceConClamped+featureEffects.hp_per_level_bonus*totalLevel+(hpModifier!=null?hpModifier:0);const hpMaxAfterConditions=Math.max(0,Math.floor(hpMaxDerived*conditionEffects.hp_max_multiplier));const hpMax=(_B=(_A=overrides.hp)==null?void 0:_A.max)!=null?_B:hpMaxAfterConditions;const hpBreakdown={diceSum,diceSource:hpRolled!=null?"rolled":"average",averageDiceSum,conMod:mods.con,conLevels,clampApplied:diceConClamped!==diceConRaw,perLevelTerms:featureEffects.hp_per_level_terms.map(t=>({label:t.label,perLevel:t.value,levels:totalLevel,total:t.value*totalLevel})),modifier:hpModifier,exhaustionMultiplier:conditionEffects.hp_max_multiplier,exhaustionLevel:conditionEffects.exhaustion_level,derivedMax:hpMaxAfterConditions,override:(_D=(_C=overrides.hp)==null?void 0:_C.max)!=null?_D:null,final:hpMax};const featureAcTermsFor=hasArmor=>featureEffects.ac_terms.filter(t=>!t.requires_armor||hasArmor).map(t=>({source:t.label,amount:t.value,kind:"feature",condition:t.condition}));const sumTerms=terms=>terms.reduce((s,t)=>s+t.amount,0);const weaponAbilities=[...featureEffects.weaponAbilities];const wantsSpellcasting=resolved.features.some(rf=>selfEffectsOf(rf.feature).some(e=>e.kind==="weapon-ability"&&e.ability==="spellcasting"));if(wantsSpellcasting){let primaryCasterAbility=null;for(const c of resolved.classes){if(!c.entity)continue;const profile=resolveSpellcasting(c);if(profile){primaryCasterAbility=effectiveSpellcastingAbility(c.entity.slug,profile.ability,overrides);break}}if(primaryCasterAbility)weaponAbilities.unshift({ability:primaryCasterAbility})}let derivedEquipment=null;let acDerived;let acBreakdownDerived=[];let acInformationalDerived=[];if(registry){derivedEquipment=computeSlotsAndAttacks(resolved,mods,profsForApply,registry,warnings,proficiencyBonus,weaponAbilities,(_E=resolved.weaponMasteries)!=null?_E:[],featureEffects.attunement_set);if(derivedEquipment.equippedSlots.armor){const featTerms=featureAcTermsFor(true);acDerived=derivedEquipment.ac+sumTerms(featTerms);acBreakdownDerived=[...derivedEquipment.acBreakdown,...featTerms];acInformationalDerived=derivedEquipment.acInformational}else{const shieldBonus=derivedEquipment.acBreakdown.filter(b=>b.kind==="shield").reduce((sum,b)=>sum+b.amount,0);const{total:unarmored,terms:unarmoredTerms,shieldAllowed}=unarmoredACBreakdown(resolved,mods,warnings,shieldBonus);const additive=derivedEquipment.acBreakdown.filter(b=>b.kind==="item"||b.kind==="override"||b.kind==="shield"&&shieldAllowed);const featTerms=featureAcTermsFor(false);const additiveSum=additive.reduce((sum,b)=>sum+b.amount,0);acDerived=unarmored+additiveSum+sumTerms(featTerms);acBreakdownDerived=[...unarmoredTerms,...additive,...featTerms];acInformationalDerived=derivedEquipment.acInformational}}else{const{total,terms}=unarmoredACBreakdown(resolved,mods,warnings);const featTerms=featureAcTermsFor(false);acDerived=total+sumTerms(featTerms);acBreakdownDerived=[...terms,...featTerms]}const ac=(_F=overrides.ac)!=null?_F:acDerived;const worn=wornArmor(derivedEquipment==null?void 0:derivedEquipment.equippedSlots,registry);const featureSpeedTerms=featureEffects.speed_terms.filter(t=>speedTermActive(t,worn));const gatedWalk=featureSpeedTerms.filter(t=>t.mode==="walk"&&t.inactiveWhile!==void 0);const featureWalkBonus=featureEffects.speed_walk_bonus+gatedWalk.filter(t=>!t.set).reduce((sum,t)=>sum+t.value,0);const featureWalkFloor=Math.max(featureEffects.speed_walk_set,...gatedWalk.filter(t=>t.set).map(t=>t.value));const armorPenalty=armorStrengthPenalty(worn,scores.str,featureEffects.ignore_armor_strength);const additiveSpeed=speedFromRace(resolved)+applied.speed_bonuses.walk+featureWalkBonus+((_G=armorPenalty==null?void 0:armorPenalty.amount)!=null?_G:0);const baseSpeed=Math.max(featureWalkFloor,applied.speed_walk_set,additiveSpeed);const adjustedSpeed=baseSpeed*conditionEffects.speed_multiplier-conditionEffects.speed_reduction_ft;const conditionSpeed=conditionEffects.speed_floor_zero?0:Math.max(0,Math.floor(adjustedSpeed));const speed=(_H=overrides.speed)!=null?_H:conditionSpeed;const raceSpeed=(_K=(_J=(_I=resolved.race)==null?void 0:_I.speed)==null?void 0:_J.walk)!=null?_K:30;const speeds=buildSpeedLines({resolved,applied,features:{speed_terms:featureSpeedTerms,speed_walk_set:featureWalkFloor},conditions:conditionEffects,conditionNames:speedConditionNames(resolved.state,resolved.definition.edition),walk:{race:raceSpeed,additive:additiveSpeed,base:baseSpeed,final:conditionSpeed},armorPenalty:armorPenalty?{term:armorPenalty,everyMode:resolved.definition.edition==="2024"}:null});const speedBreakdown=speeds[0].terms;if(!resolved.race)warnings.push("No race resolved; speed defaulted to 30.");const initiativeAmountTerms=featureEffects.initiative_amount_terms.flatMap(term2=>{const text=resolveAmountText(term2.amount,amountBindingsFor(term2.owner,resolved,{proficiencyBonus,mods,spellcastingClasses:[]}));const n=Number(text);if(!Number.isInteger(n)){warnings.push(`${term2.label}: initiative amount "${term2.amount}" is not a number; nothing added.`);return[]}return[{source:term2.label,amount:n}]});const init=(_L=overrides.initiative)!=null?_L:initiativeBonus(mods.dex,resolved.feats,resolved.definition.edition)+featureEffects.initiative_bonus+initiativeAmountTerms.reduce((s,t)=>s+t.amount,0);const initiativeBreakdown=[{source:"DEX",amount:mods.dex},...initiativeBonus(mods.dex,resolved.feats,resolved.definition.edition)!==mods.dex?[{source:"Feats",amount:initiativeBonus(mods.dex,resolved.feats,resolved.definition.edition)-mods.dex}]:[],...featureEffects.initiative_terms.map(term2=>({source:term2.label,amount:term2.value})),...initiativeAmountTerms];const senses={darkvision:Math.max((_O=(_N=(_M=resolved.race)==null?void 0:_M.vision)==null?void 0:_N.darkvision)!=null?_O:0,featureEffects.senses.darkvision,applied.senses.darkvision),blindsight:Math.max(featureEffects.senses.blindsight,applied.senses.blindsight),tremorsense:Math.max(featureEffects.senses.tremorsense,applied.senses.tremorsense),truesight:Math.max(featureEffects.senses.truesight,applied.senses.truesight)};const spellcastingClasses=[];const slotInputs=[];const limitInputs=[];for(const c of resolved.classes){if(!c.entity)continue;const profile=resolveSpellcasting(c);if(!profile)continue;const ab=effectiveSpellcastingAbility(c.entity.slug,profile.ability,overrides);const dc=saveDC(scores[ab],proficiencyBonus)+applied.spell_save_dc;const atk=attackBonus(scores[ab],proficiencyBonus)+applied.spell_attack;spellcastingClasses.push({classSlug:c.entity.slug,className:c.entity.name,ability:ab,defaultAbility:profile.ability,saveDC:dc,attackBonus:atk,casterType:profile.casterType,preparation:profile.preparation,spellList:profile.spellList});slotInputs.push({casterType:profile.casterType,level:c.level});limitInputs.push({classSlug:c.entity.slug,level:c.level,profile,abilityScore:scores[ab]})}const spellcasting=spellcastingClasses.length>0?{ability:spellcastingClasses[0].ability,saveDC:spellcastingClasses[0].saveDC,attackBonus:spellcastingClasses[0].attackBonus}:null;const abilitySpellcasting={};for(const s of resolved.spells){const ab=s.ability;if(!ab||abilitySpellcasting[ab])continue;abilitySpellcasting[ab]={saveDC:saveDC(scores[ab],proficiencyBonus)+applied.spell_save_dc,attackBonus:attackBonus(scores[ab],proficiencyBonus)+applied.spell_attack}}const derivedSlots=deriveSpellSlots(slotInputs);const spellLimits=computeSpellLimits(limitInputs);const defenses={resistances:suppress(resolved,"resistances",composeDefenseEntries((_Q=(_P=resolved.definition.defenses)==null?void 0:_P.resistances)!=null?_Q:[],applied.defenses.resistances,featureEffects.resistances)),immunities:suppress(resolved,"immunities",composeDefenseEntries((_S=(_R=resolved.definition.defenses)==null?void 0:_R.immunities)!=null?_S:[],applied.defenses.immunities,featureEffects.immunities)),vulnerabilities:suppress(resolved,"vulnerabilities",composeDefenseEntries((_U=(_T=resolved.definition.defenses)==null?void 0:_T.vulnerabilities)!=null?_U:[],applied.defenses.vulnerabilities,featureEffects.vulnerabilities)),condition_immunities:suppress(resolved,"condition_immunities",composeDefenseEntries((_W=(_V=resolved.definition.defenses)==null?void 0:_V.condition_immunities)!=null?_W:[],applied.defenses.condition_immunities,featureEffects.condition_immunities))};const unarmedSpec=resolveUnarmedStrike(resolved);const attackRows=[...(_X=derivedEquipment==null?void 0:derivedEquipment.attacks)!=null?_X:[],...buildFeatureAttackRows(resolved,mods,profsForApply,proficiencyBonus,weaponAbilities,{unarmedAbilities:unarmedSpec.abilities,activeBuffs}),buildUnarmedRow(mods,proficiencyBonus,unarmedSpec)];const scopeOpts={pactPicked:pactWeaponIndexes(resolved,registry)!==null};const riderBindings=owner=>amountBindingsFor(owner,resolved,{proficiencyBonus,mods,spellcastingClasses});const ownSpells=(_Y=resolved.spells)!=null?_Y:[];const spellDamageRiders=featureEffects.spellDamageBonuses.flatMap(r=>{const reached=new Set([...spellsReached(r.targets,ownSpells),...spellsInScope(r.scope,ownSpells,id=>pickedDamageTypes(resolved,id))]);const spells=[...new Set(ownSpells.map(s=>s.slug))].filter(slug=>reached.has(slug));if(!spells.length)return[];const{owner,targets:_targets,scope,damage_type,...rest}=r;return[{...rest,amount:resolveAmountText(r.amount,riderBindings(owner)),...damage_type&&isCanonicalDamageType(damage_type)?{damage_type}:{},...(scope==null?void 0:scope.once)?{once:true}:{},spells}]});const scopedExtra=featureEffects.scopedExtraAttacks;const rowExtra=attackRows.map(a=>{if(!scopedExtra.length)return void 0;let best={count:featureEffects.extraAttack,source:featureEffects.extraAttackSource};for(const x of scopedExtra)if(x.count>best.count&&scopeReachesRow(x.scope,a,scopeOpts))best={count:x.count,source:x.source};return{count:1+best.count,...best.count>0&&best.source?{source:best.source}:{}}});const rowAttacks=rowExtra.map(r=>r==null?void 0:r.count);return{totalLevel,proficiencyBonus,scores,mods,saves,proficiencies:profsForApply,skills,statBreakdowns:{skills:skillBreakdowns,saves:saveBreakdowns,speed:speedBreakdown,initiative:initiativeBreakdown,abilities:abilityScoreBreakdowns(resolved,overrides,applied,featureEffects,scores)},passives,senses,hp:{max:hpMax,current:resolved.state.hp.current,temp:resolved.state.hp.temp},hpBreakdown,ac,speed,speeds,initiative:init,spellcasting,spellcastingClasses,abilitySpellcasting,derivedSpellSlots:derivedSlots.standard,pactMagic:derivedSlots.pact,spellLimits,warnings,defenses,acBreakdown:acBreakdownDerived,acInformational:acInformationalDerived,savesInformational,spellcastingInformational,speedInformational,attacksPerAction:Math.max(1+featureEffects.extraAttack,...rowAttacks.filter(n=>n!==void 0)),...featureEffects.extraAttackSource?{extraAttackSource:featureEffects.extraAttackSource}:{},attacks:attackRows.map((a,i)=>{var _a2,_b2,_c2,_d2,_e2;const critRange=Math.min((_a2=a.critRange)!=null?_a2:20,featureEffects.critRange);const conditionalCrits=[...(_b2=a.conditionalCrits)!=null?_b2:[],...featureEffects.conditionalCrits].filter(c=>c.minRoll<critRange);const riders=[...(_c2=a.damageRiders)!=null?_c2:[],...featureEffects.damageBonuses.filter(r=>riderReachesRow(r,a,scopeOpts))].map(r=>resolveDamageRider(r,a.damageType,riderBindings));const rollOptions=featureEffects.damageRollOptions.filter(o=>scopeReachesRow(o.scope,a,scopeOpts)).map(({scope:_scope,...o})=>o);const{critRange:_ownCrit,conditionalCrits:_ownConditional,...row}=a;return{...row,toHit:a.toHit+conditionEffects.d20_test_penalty,...critRange<20?{critRange}:{},...conditionalCrits.length?{conditionalCrits}:{},...featureEffects.attackNotes.length?{attackNotes:featureEffects.attackNotes}:{},...riders.length?{damageRiders:riders}:{},...rollOptions.length?{damageRollOptions:rollOptions}:{},...rowAttacks[i]!==void 0?{attacksPerAction:rowAttacks[i]}:{},...((_d2=rowExtra[i])==null?void 0:_d2.source)?{extraAttackSource:(_e2=rowExtra[i])==null?void 0:_e2.source}:{}}}),...spellDamageRiders.length?{spellDamageRiders}:{},equippedSlots:(_Z=derivedEquipment==null?void 0:derivedEquipment.equippedSlots)!=null?_Z:{},carriedWeight:(__=derivedEquipment==null?void 0:derivedEquipment.carriedWeight)!=null?__:0,attunementUsed:(_$=derivedEquipment==null?void 0:derivedEquipment.attunementUsed)!=null?_$:0,attunementLimit:(_ba=derivedEquipment==null?void 0:derivedEquipment.attunementLimit)!=null?_ba:(_aa=overrides.attunement_limit)!=null?_aa:Math.max(3,featureEffects.attunement_set),conditionEffects,rollModifiers:featureEffects.rollModifiers,saveOutcomes:featureEffects.saveOutcomes}}export{HAND_SET_HALF_SOURCE,abilityBonusBreakdown,abilityScoreBreakdowns,collectClassAsiBranch,collectClassFeatAbilityPoints,computeAbilityScores,computeProficiencies,fixedFeatAbilityIncrease,flattenRaceAsi,hitDiceAverageSum,hpLevelCount,initiativeBonus,multiclassMaxHP,parseDieSize,phbAverageForDie,recalc,resolveUnarmedStrike,riderReachesRow,scopeReachesRow,speedFromRace,unarmoredAC,unarmoredACBreakdown};
@@ -1 +1 @@
1
- import{PCResolver,collectAdditionalFeatures,collectChosenGrantedFeatures,collectChosenWeaponMasteries,collectFeatChoiceGrants,collectFeatGrantedSpells,collectFeatPicks,collectItemGrantedSpells,collectResolvedFeatures,dedupeResolvedSpells,resolveOriginFeat,stripSlug}from"../chunk-2GZM7FCD.js";import"../chunk-2EOGK6R6.js";import"../chunk-4AJYEWFQ.js";import"../chunk-RQZCGXUZ.js";import"../chunk-CLZRWPWT.js";import"../chunk-4FTTUZXM.js";import"../chunk-FOLHTMSC.js";import"../chunk-4JEF3CET.js";import"../chunk-VTQ4RWEG.js";import"../chunk-MMDUUEFA.js";import"../chunk-J27N3KUE.js";import"../chunk-RR26E7LH.js";import"../chunk-UBUKCRZ3.js";import"../chunk-2OVDSMPY.js";import"../chunk-PFQPP77Q.js";import"../chunk-QVWT67WA.js";import"../chunk-E4E6YEN6.js";import"../chunk-CMIEZQL4.js";import"../chunk-O776WL7O.js";import"../chunk-CSTAQQGX.js";import"../chunk-3LWOVRLA.js";import"../chunk-DVUXUIPV.js";import"../chunk-YGH7S5ZF.js";import"../chunk-4IAMSRHD.js";import"../chunk-3QQOATV3.js";import"../chunk-DZITM5AG.js";import"../chunk-PZ4L2EEG.js";import"../chunk-QMEKQTUT.js";import"../chunk-EAARMPCW.js";import"../chunk-CAPYNIGK.js";import"../chunk-63YJPWTM.js";import"../chunk-4KVVAENP.js";import"../chunk-7EL3GWWJ.js";import"../chunk-BREHZNTL.js";import"../chunk-7FPQJDFD.js";import"../chunk-EVT7MGAC.js";import"../chunk-S5UCI27C.js";import"../chunk-EON7T2SN.js";import"../chunk-I26FHSI6.js";export{PCResolver,collectAdditionalFeatures,collectChosenGrantedFeatures,collectChosenWeaponMasteries,collectFeatChoiceGrants,collectFeatGrantedSpells,collectFeatPicks,collectItemGrantedSpells,collectResolvedFeatures,dedupeResolvedSpells,resolveOriginFeat,stripSlug};
1
+ import{PCResolver,collectAdditionalFeatures,collectChosenGrantedFeatures,collectChosenWeaponMasteries,collectFeatChoiceGrants,collectFeatGrantedSpells,collectFeatPicks,collectItemGrantedSpells,collectResolvedFeatures,dedupeResolvedSpells,resolveOriginFeat,stripSlug}from"../chunk-JSI2G6LE.js";import"../chunk-2EOGK6R6.js";import"../chunk-4AJYEWFQ.js";import"../chunk-RQZCGXUZ.js";import"../chunk-CLZRWPWT.js";import"../chunk-B2JSF2LL.js";import"../chunk-FOLHTMSC.js";import"../chunk-4JEF3CET.js";import"../chunk-VTQ4RWEG.js";import"../chunk-DXJ5NKKB.js";import"../chunk-J27N3KUE.js";import"../chunk-RR26E7LH.js";import"../chunk-UBUKCRZ3.js";import"../chunk-2OVDSMPY.js";import"../chunk-PFQPP77Q.js";import"../chunk-QVWT67WA.js";import"../chunk-E4E6YEN6.js";import"../chunk-CMIEZQL4.js";import"../chunk-O776WL7O.js";import"../chunk-CSTAQQGX.js";import"../chunk-3LWOVRLA.js";import"../chunk-DVUXUIPV.js";import"../chunk-YGH7S5ZF.js";import"../chunk-4IAMSRHD.js";import"../chunk-3QQOATV3.js";import"../chunk-DZITM5AG.js";import"../chunk-PZ4L2EEG.js";import"../chunk-QMEKQTUT.js";import"../chunk-EAARMPCW.js";import"../chunk-CAPYNIGK.js";import"../chunk-63YJPWTM.js";import"../chunk-4KVVAENP.js";import"../chunk-7EL3GWWJ.js";import"../chunk-BREHZNTL.js";import"../chunk-7FPQJDFD.js";import"../chunk-EVT7MGAC.js";import"../chunk-S5UCI27C.js";import"../chunk-EON7T2SN.js";import"../chunk-I26FHSI6.js";export{PCResolver,collectAdditionalFeatures,collectChosenGrantedFeatures,collectChosenWeaponMasteries,collectFeatChoiceGrants,collectFeatGrantedSpells,collectFeatPicks,collectItemGrantedSpells,collectResolvedFeatures,dedupeResolvedSpells,resolveOriginFeat,stripSlug};
@@ -343,6 +343,15 @@ export interface ResolvedFeature {
343
343
  description?: string;
344
344
  choices?: Choice[];
345
345
  }[];
346
+ poolMember?: true;
347
+ }
348
+ export interface ExtraAttackSource {
349
+ name: string;
350
+ source: FeatureSource;
351
+ level?: number;
352
+ poolMember?: true;
353
+ switched?: true;
354
+ scope?: WeaponScope[];
346
355
  }
347
356
  export interface ResolvedSpell {
348
357
  entity: Spell;
@@ -509,6 +518,7 @@ export interface AttackRow {
509
518
  damageRiders?: DamageRider[];
510
519
  weaponCategory?: "melee" | "ranged";
511
520
  attacksPerAction?: number;
521
+ extraAttackSource?: ExtraAttackSource;
512
522
  properties: string[];
513
523
  proficient: boolean;
514
524
  breakdown: {
@@ -729,6 +739,7 @@ export interface DerivedStats {
729
739
  spellcastingInformational: import("@archivist-gg/dnd5e/item/item.conditions.types").InformationalBonus[];
730
740
  speedInformational: import("@archivist-gg/dnd5e/item/item.conditions.types").InformationalBonus[];
731
741
  attacksPerAction: number;
742
+ extraAttackSource?: ExtraAttackSource;
732
743
  attacks: AttackRow[];
733
744
  spellDamageRiders?: SpellDamageRider[];
734
745
  equippedSlots: EquippedSlots;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@archivist-gg/dnd5e",
3
- "version": "0.3.28",
3
+ "version": "0.3.29",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -1 +0,0 @@
1
- import{normalizeRollScope}from"./chunk-FOLHTMSC.js";import{toProfSlug}from"./chunk-VTQ4RWEG.js";import{memberSpellTargets}from"./chunk-J27N3KUE.js";import{heldPicks}from"./chunk-E4E6YEN6.js";import{warnOnce}from"./chunk-DZITM5AG.js";import{bareEntitySlug}from"./chunk-63YJPWTM.js";import{normalizeAbility}from"./chunk-EVT7MGAC.js";function emptyFeatureEffectTotals(){return{initiative_bonus:0,initiative_terms:[],initiative_amount_terms:[],skill_bonus_terms:[],save_bonus_terms:[],half_proficiency_terms:[],hp_per_level_bonus:0,hp_per_level_terms:[],speed_walk_bonus:0,speed_walk_terms:[],speed_terms:[],ignore_armor_strength:[],speed_walk_set:0,attunement_set:0,ability_bonus:{},ability_bonus_terms:[],senses:{darkvision:0,blindsight:0,tremorsense:0,truesight:0},ac_terms:[],resistances:[],immunities:[],vulnerabilities:[],condition_immunities:[],proficiencies:{skills:[],skillExpertise:[],tools:[],languages:[],saves:[],armor:[],weapons:[]},weaponAbilities:[],rollModifiers:[],saveOutcomes:[],critRange:20,conditionalCrits:[],extraAttack:0,scopedExtraAttacks:[],attackNotes:[],damageBonuses:[],spellDamageBonuses:[],damageRollOptions:[]}}function pushUnique(list,value){const key=value.trim().toLowerCase();if(!key)return;if(!list.some(v=>v.trim().toLowerCase()===key))list.push(value.trim())}function pushDefenseGrant(list,value,source,condition,item){var _a;const key=value.trim().toLowerCase();if(!key)return;const existing=list.find(g=>g.value.trim().toLowerCase()===key);if(existing){if(!existing.sources.includes(source))existing.sources.push(source);if(!existing.condition&&condition)existing.condition=condition;if(item)mergeDefenseItems((_a=existing.items)!=null?_a:existing.items=[],[item]);return}list.push({value:value.trim(),sources:[source],...condition?{condition}:{},...item?{items:[item]}:{}})}function mergeDefenseItems(into,from){for(const it of from)if(!into.some(x=>x.index===it.index))into.push({...it})}function ownerItem(owner,label){return(owner==null?void 0:owner.kind)==="item"?{index:owner.index,name:label}:void 0}var NAMED_COLUMN=/^column\(\s*'([^']+)'\s*\)$/;function foldsNow(rf,activeBuffs){if(rf.feature.activatable!==true)return true;const id=rf.feature.id;return!!id&&activeBuffs.has(id)}function assembleEffectFeatures(resolved){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j;const activeBuffs=new Set((_b=(_a=resolved.state)==null?void 0:_a.active_buffs)!=null?_b:[]);const featureIds=new Set(((_c=resolved.features)!=null?_c:[]).map(f=>f.feature.id).filter(id=>!!id));const aliases=[];for(const pool of(_d=resolved.pools)!=null?_d:[]){for(const entry of[...(_e=pool.selected)!=null?_e:[],...(_f=pool.grants)!=null?_f:[]]){if(activeBuffs.has(entry.slug))continue;const bare=bareEntitySlug(entry.slug);for(const stored of activeBuffs){if(featureIds.has(stored))continue;if(bareEntitySlug(stored)===bare){aliases.push(entry.slug);break}}}}for(const a of aliases)activeBuffs.add(a);const buffFeatures=[];const pushBoon=(item,pool)=>{var _a2,_b2,_c2,_d2,_e2,_f2,_g2,_h2,_i2,_j2,_k;const e=item.entity;if(!e||item.itemBound===true||((_b2=(_a2=e.effects)==null?void 0:_a2.length)!=null?_b2:0)===0)return;const block=(_f2=(_e2=(_d2=(_c2=resolved.classes)==null?void 0:_c2[pool.classIndex])==null?void 0:_d2.choices)==null?void 0:_e2[pool.anchorLevel])!=null?_f2:{};const spellTargets=memberSpellTargets(e,id=>{var _a3;return block[`${pool.id}:${(_a3=item.key)!=null?_a3:item.slug}:${id}`]});buffFeatures.push({feature:{id:item.slug,name:e.name,activatable:(_g2=e.activatable)!=null?_g2:false,effects:e.effects},source:{kind:"class",slug:(_k=(_j2=(_i2=(_h2=resolved.classes)==null?void 0:_h2[pool.classIndex])==null?void 0:_i2.entity)==null?void 0:_j2.slug)!=null?_k:pool.id,level:pool.anchorLevel},...spellTargets?{spellTargets}:{}})};for(const pool of(_g=resolved.pools)!=null?_g:[]){for(const sel of heldPicks(pool))pushBoon(sel,pool);for(const g of(_h=pool.grants)!=null?_h:[])pushBoon(g,pool)}return{features:[...(_i=resolved.features)!=null?_i:[],...buffFeatures,...(_j=resolved.itemFeatures)!=null?_j:[]],activeBuffs}}function foldsOnSelf(eff){if(eff.subject===void 0||eff.subject==="self")return true;warnOnce(eff.subject,`archivist: unrecognised effect subject "${eff.subject}" (only "self" folds)`);return false}function selfEffectsOf(f){var _a;return((_a=f.effects)!=null?_a:[]).filter(foldsOnSelf)}function computeFeatureEffects(features,opts){var _a,_b,_c;const out=emptyFeatureEffectTotals();for(const rf of features){if(!foldsNow(rf,(_a=opts==null?void 0:opts.activeBuffs)!=null?_a:new Set))continue;const level=(_b=opts==null?void 0:opts.levelFor)==null?void 0:_b.call(opts,rf.source);for(const eff of selfEffectsOf(rf.feature)){const effect=columnScaledRider(eff,rf,level,opts==null?void 0:opts.tableDiceFor,opts==null?void 0:opts.tableCellFor);if(effect)applyEffect(out,effect,(_c=rf.feature.name)!=null?_c:"Feature",level,rf.source,rf.spellTargets)}}return out}function classifyProficiencyEffect(eff){if(eff.kind!=="proficiency")return null;const raw=eff.value;const expertise=eff.expertise===true;switch(eff.proficiency_type){case"skill":return{bucket:"skills",value:toProfSlug(raw),raw,expertise};case"tool":return{bucket:"tools",value:toProfSlug(raw),raw,expertise};case"language":return{bucket:"languages",value:toProfSlug(raw),raw,expertise};case"armor":return{bucket:"armor",value:raw.toLowerCase(),raw,expertise};case"weapon":return{bucket:"weapons",value:raw.toLowerCase(),raw,expertise};default:{const ab=normalizeAbility(raw);return ab?{bucket:"saves",value:ab,raw,expertise}:null}}}function collectProficiencyEffectGrants(features,activeBuffs){const out={skills:[],tools:[],languages:[],saves:[],armor:[],weapons:[]};for(const rf of features){if(!foldsNow(rf,activeBuffs))continue;for(const eff of selfEffectsOf(rf.feature)){const c=classifyProficiencyEffect(eff);if(!c)continue;out[c.bucket].push({value:c.value,raw:c.raw,sourceKind:rf.source.kind,sourceSlug:rf.source.slug,...c.expertise?{expertise:true}:{}})}}return out}function scaled(base,key,scalesAt,level){if(level===void 0||!(scalesAt==null?void 0:scalesAt.length))return base;let best=base;let bestLevel=-1;for(const step of scalesAt){if(step.level>level||step.level<=bestLevel)continue;const v=step[key];if(typeof v!=="number")continue;best=v;bestLevel=step.level}return best}function columnScaledRider(eff,rf,level,tableDiceFor,tableCellFor){var _a;if(eff.kind!=="damage-bonus")return eff;const named=NAMED_COLUMN.exec(eff.amount.trim());if(named){const cell=(_a=tableCellFor==null?void 0:tableCellFor(rf.source,named[1]))!=null?_a:null;return cell?{...eff,amount:cell}:null}if(level===void 0||!tableDiceFor)return eff;const src=rf.source;const column=rf.feature.name;if(src.kind!=="class"&&src.kind!=="subclass"||!column)return eff;const atGain=tableDiceFor(src,column,src.level);if(!atGain||atGain.toLowerCase()!==eff.amount.trim().toLowerCase())return eff;const now=tableDiceFor(src,column,level);return now?{...eff,amount:now}:eff}function riderScope(appliesTo){if(appliesTo===void 0||appliesTo==="all"||appliesTo==="spell")return void 0;return Array.isArray(appliesTo)?[...appliesTo]:[appliesTo]}function applyEffect(out,eff,label,level,owner,targets){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q;switch(eff.kind){case"initiative-bonus":if(typeof eff.value==="number"){out.initiative_bonus+=eff.value;out.initiative_terms.push({label,value:eff.value})}else if(typeof eff.amount==="string"){out.initiative_amount_terms.push({label,amount:eff.amount,...owner?{owner}:{}})}break;case"skill-bonus":out.skill_bonus_terms.push({skills:eff.skills.map(toProfSlug),ability:eff.ability,minimum:(_a=eff.minimum)!=null?_a:0,label});break;case"save-bonus":out.save_bonus_terms.push({saves:[...(_b=eff.saves)!=null?_b:[]],ability:eff.ability,minimum:(_c=eff.minimum)!=null?_c:0,...eff.inactive_while?{inactiveWhile:eff.inactive_while}:{},label});break;case"half-proficiency":out.half_proficiency_terms.push({skills:((_d=eff.skills)!=null?_d:[]).map(toProfSlug),round:(_e=eff.round)!=null?_e:"down",label});break;case"hp-per-level-bonus":out.hp_per_level_bonus+=eff.value;out.hp_per_level_terms.push({label,value:eff.value});break;case"speed-bonus":{const gate=eff.inactive_while===void 0?void 0:[].concat(eff.inactive_while);const qualifiers={...eff.condition?{condition:eff.condition}:{},...gate?{inactiveWhile:gate}:{}};if(eff.equal_to==="walk"){out.speed_terms.push({mode:eff.mode,label,value:0,set:false,equalsWalk:true,...qualifiers});break}const value=scaled((_f=eff.value)!=null?_f:0,"value",eff.scales_at,level);out.speed_terms.push({mode:eff.mode,label,value,set:eff.set===true,...qualifiers});if(eff.mode==="walk"&&!gate){if(eff.set)out.speed_walk_set=Math.max(out.speed_walk_set,value);else{out.speed_walk_bonus+=value;out.speed_walk_terms.push({label,value})}}break}case"speed-rule":if(eff.flag==="ignore-armor-strength")out.ignore_armor_strength.push(label);break;case"attunement-limit":{out.attunement_set=Math.max(out.attunement_set,scaled(eff.value,"value",eff.scales_at,level));break}case"sense":out.senses[eff.type]=Math.max(out.senses[eff.type],eff.range);break;case"resistance":pushDefenseGrant(out.resistances,eff.damage_type,label,eff.condition,ownerItem(owner,label));break;case"immunity":pushDefenseGrant(out.immunities,eff.damage_type,label,eff.condition,ownerItem(owner,label));break;case"vulnerability":pushDefenseGrant(out.vulnerabilities,eff.damage_type,label,eff.condition,ownerItem(owner,label));break;case"immune-condition":if(!eff.while)pushDefenseGrant(out.condition_immunities,eff.condition,label,void 0,ownerItem(owner,label));else if((owner==null?void 0:owner.kind)==="item")pushDefenseGrant(out.condition_immunities,eff.condition,label,eff.while,ownerItem(owner,label));break;case"proficiency":{const c=classifyProficiencyEffect(eff);if(!c)break;if(c.bucket==="saves"){pushUnique(out.proficiencies.saves,c.value)}else{pushUnique(out.proficiencies[c.bucket],c.value)}if(c.expertise&&c.bucket==="skills")pushUnique(out.proficiencies.skillExpertise,c.value);break}case"ac-bonus":out.ac_terms.push({value:eff.value,requires_armor:eff.requires_armor===true,label,condition:eff.condition});break;case"weapon-ability":{if(eff.ability!=="spellcasting"){const w=eff.weapons;if(w==="pact-weapon"){out.weaponAbilities.push({ability:eff.ability,pactWeapon:true});break}const weaponSlugs=!w||w==="chosen"?void 0:Array.isArray(w)?w.map(bareEntitySlug):[bareEntitySlug(w)];out.weaponAbilities.push({ability:eff.ability,weaponSlugs})}break}case"roll-modifier":{const rolls=eff.roll==="any"?["ability-check","saving-throw","attack"]:[eff.roll];const scopes=(_g=normalizeRollScope(eff.scope,rolls[0]))!=null?_g:[eff.scope];for(const roll of rolls)for(const scope of scopes)out.rollModifiers.push({mode:eff.mode,roll,scope,condition:eff.condition,label});break}case"save-outcome":out.saveOutcomes.push({ability:eff.ability==="any"?void 0:eff.ability,on_success:eff.on_success,on_failure:eff.on_failure,appliesTo:(_h=eff.applies_to)!=null?_h:void 0,condition:eff.condition,label});break;case"crit-range":if(((_i=eff.applies_to)!=null?_i:"weapon")==="spell")break;if((_j=eff.condition)==null?void 0:_j.trim())out.conditionalCrits.push({minRoll:eff.min_roll,condition:eff.condition.trim(),source:label});else out.critRange=Math.min(out.critRange,eff.min_roll);break;case"extra-attack":{const count=scaled(eff.count,"count",eff.scales_at,level);const scope=riderScope(eff.applies_to);if(scope)out.scopedExtraAttacks.push({count,scope});else out.extraAttack=Math.max(out.extraAttack,count)}break;case"reroll-damage":{const qualifiers=[eff.once_per_die?"once/die":"",(_l=(_k=eff.condition)==null?void 0:_k.trim())!=null?_l:""].filter(q=>q!=="");out.attackNotes.push(`Reroll ${eff.max_reroll}s${qualifiers.length?` (${qualifiers.join(", ")})`:""}`)}break;case"attack-rule":if(eff.flag==="no-ranged-in-melee-disadvantage")out.attackNotes.push("No disadvantage firing in melee");break;case"damage-roll-option":{const scope=eff.applies_to===void 0?void 0:[].concat(eff.applies_to);out.damageRollOptions.push({mode:eff.mode,...eff.value!==void 0?{value:eff.value}:{},...eff.two_handed?{twoHanded:true}:{},...eff.once_per_turn?{oncePerTurn:true}:{},...((_m=eff.condition)==null?void 0:_m.trim())?{condition:eff.condition.trim()}:{},source:label,...scope?{scope}:{}});break}case"damage-bonus":if(((_n=eff.applies_to)!=null?_n:"weapon")!=="spell"){const scope=riderScope(eff.applies_to);out.damageBonuses.push({amount:eff.amount,damage_type:eff.damage_type,source:label,...eff.condition?{condition:eff.condition}:{},...scope?{scope}:{},...owner?{owner}:{}})}if(eff.applies_to==="spell"||eff.applies_to==="all"){const spellScope=(_o=eff.spell_scope)!=null?_o:eff.applies_to==="all"?{}:void 0;out.spellDamageBonuses.push({amount:eff.amount,damage_type:eff.damage_type,source:label,...eff.condition?{condition:eff.condition}:{},...owner?{owner}:{},...targets?{targets}:{},...spellScope?{scope:spellScope}:{}})}break;case"ability-score-increase":if(eff.abilities==="chosen")break;for(const ab of eff.abilities){out.ability_bonus[ab]=((_p=out.ability_bonus[ab])!=null?_p:0)+eff.amount;((_q=out.ability_bonus_terms)!=null?_q:out.ability_bonus_terms=[]).push({ability:ab,source:label,amount:eff.amount})}break;default:break}}export{emptyFeatureEffectTotals,pushDefenseGrant,mergeDefenseItems,foldsNow,assembleEffectFeatures,foldsOnSelf,selfEffectsOf,computeFeatureEffects,classifyProficiencyEffect,collectProficiencyEffectGrants};
@@ -1 +0,0 @@
1
- import{isConsumedOnUse,itemSpellUse,resolveEntryEntity}from"./chunk-E4E6YEN6.js";import{isReadOnceItem}from"./chunk-DVUXUIPV.js";import{requiresAttunement}from"./chunk-YGH7S5ZF.js";import{resolveEntityForEntry}from"./chunk-4IAMSRHD.js";import{featureEffectSchema}from"./chunk-EON7T2SN.js";var linkSlug=item=>{var _a,_b;return(_b=(_a=/^\[\[(.+?)(\|.*)?\]\]$/.exec(item.trim()))==null?void 0:_a[1])!=null?_b:null};function itemBenefitsActive(entry,entity,registry,view){var _a;if(!entry.equipped)return false;if(requiresAttunement(entity)&&entry.attuned!==true)return false;if(isConsumedOnUse(entry,registry,view))return false;const slug=entity==null?void 0:entity.slug;if(isReadOnceItem(typeof slug==="string"&&slug?slug:(_a=linkSlug(entry.item))!=null?_a:entry.item))return false;return true}function itemSpellCastable(entry,registry,view){const use=itemSpellUse(entry,registry,view);if(!use||!registry)return false;if(use.kind==="consume")return true;const entity=view?view.entity:resolveEntityForEntry(entry.item,registry).entity;return itemBenefitsActive(entry,entity,registry,view)}function itemLabel(entry,entity){var _a,_b,_c,_d;return(_d=(_a=entry.overrides)==null?void 0:_a.name)!=null?_d:String((_c=(_b=entity==null?void 0:entity.name)!=null?_b:linkSlug(entry.item))!=null?_c:entry.item)}var ITEM_ROW_KINDS=new Set(["damage-bonus","crit-range","reroll-damage","extra-attack","weapon-ability","attack-rule"]);function readItemEffects(entity){const raw=entity==null?void 0:entity.effects;const effects=[];const invalid=[];if(!Array.isArray(raw))return{effects,invalid};for(const e of raw){const parsed=featureEffectSchema.safeParse(e);if(parsed.success)effects.push(parsed.data);else invalid.push(typeof(e==null?void 0:e.kind)==="string"?String(e.kind):"unknown")}return{effects,invalid}}function itemRowEffects(entity){return readItemEffects(entity).effects.filter(e=>ITEM_ROW_KINDS.has(e.kind))}function buildItemFeatures(equipment,registry,infusions,warnings){const out=[];if(typeof registry.getBySlug!=="function")return out;equipment.forEach((entry,index)=>{var _a,_b;if(!entry.equipped)return;const{entity,entityType}=resolveEntryEntity(entry,index,registry,infusions);if(!entity||entityType!=="item")return;if(!itemBenefitsActive(entry,entity,registry,infusions==null?void 0:infusions.views.get(index)))return;const{effects,invalid}=readItemEffects(entity);const name=itemLabel(entry,entity);if(invalid.length){warnings.push(`${name}: the sheet cannot read ${invalid.length===1?"this effect":"these effects"} (${invalid.join(", ")}); ignored.`)}const own=effects.filter(e=>!ITEM_ROW_KINDS.has(e.kind));if(own.length===0)return;const slug=String((_b=(_a=entity.slug)!=null?_a:linkSlug(entry.item))!=null?_b:entry.item);out.push({feature:{id:`item:${index}:${slug}`,name,activatable:false,effects:own},source:{kind:"item",slug,index}})});return out}export{itemBenefitsActive,itemSpellCastable,itemLabel,ITEM_ROW_KINDS,readItemEffects,itemRowEffects,buildItemFeatures};