var __defProp=Object.defineProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __defProp2=Object.defineProperty,__defNormalProp=__name((obj,key,value)=>key in obj?__defProp2(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,"__defNormalProp"),__name2=__name((target,value)=>__defProp2(target,"name",{value,configurable:!0}),"__name"),__publicField=__name((obj,key,value)=>(__defNormalProp(obj,typeof key!="symbol"?key+"":key,value),value),"__publicField"),__accessCheck=__name((obj,member,msg)=>{if(!member.has(obj))throw TypeError("Cannot "+msg)},"__accessCheck"),__privateGet=__name((obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),"__privateGet"),__privateAdd=__name((obj,member,value)=>{if(member.has(obj))throw TypeError("Cannot add the same private member more than once");member instanceof WeakSet?member.add(obj):member.set(obj,value)},"__privateAdd"),__privateSet=__name((obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),"__privateSet"),__privateMethod=__name((obj,member,method)=>(__accessCheck(obj,member,"access private method"),method),"__privateMethod"),_renderFormula,renderFormula_fn,_slider,_noRefreshHook,_prepareDamageTypes,prepareDamageTypes_fn,_getInputElements,getInputElements_fn,_assertEntryIsDocument,assertEntryIsDocument_fn,_getRitualData,getRitualData_fn,_migrateDocuments,migrateDocuments_fn,_migrateItem,migrateItem_fn,_migrateActor,migrateActor_fn,_migrateWorldJournalEntry,migrateWorldJournalEntry_fn,_migrateWorldMacro,migrateWorldMacro_fn,_migrateWorldTable,migrateWorldTable_fn,_migrateSceneToken,migrateSceneToken_fn,_migrateUser,migrateUser_fn,_diehardPromise,_featSlugs,_featsPromise,_IMAGE_PATHS,_BASE_ARMORS,_MAGIC_ARMOR_TO_BASE,_BASE_WEAPONS,_imageOverrides,_sizeOverrides,_isTokenImageFlag,isTokenImageFlag_fn,_isTokenSizeFlag,isTokenSizeFlag_fn,_needsRuleElement,needsRuleElement_fn,_increasesByOne,_isClassFeature,isClassFeature_fn,_isTokenSizeRE,isTokenSizeRE_fn,_isActorSizeAELike,isActorSizeAELike_fn,_isBracketedValue,isBracketedValue_fn,_setAncestryVision,setAncestryVision_fn,_getDegreeAdjustment,getDegreeAdjustment_fn,_adjustDegreeOfSuccess,adjustDegreeOfSuccess_fn,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn,_calculateDegreeOfSuccess,calculateDegreeOfSuccess_fn,_isAdjustmentData,isAdjustmentData_fn,_weapon,_resolveOptions,resolveOptions_fn,_parseUuid2,parseUuid_fn,_processEffects,processEffects_fn,_createMovementType,createMovementType_fn,_originalValue,_title,_text,_check,_dc,_determineLabel,determineLabel_fn,_convertColors,convertColors_fn,_drawLabel,drawLabel_fn,_moveTime,_wheelListenerOptions,_onMouseMove,_onLeftClick,_onRightClick,_onMouseWheel,_filterTimeout,_updateIWR,updateIWR_fn,_sortableOnMoveData,_activateInventoryListeners,activateInventoryListeners_fn,_activateInventoryDragDrop,activateInventoryDragDrop_fn,_sortableOnMove,sortableOnMove_fn,_sortableOnEnd,sortableOnEnd_fn,_onClickDeleteItem,onClickDeleteItem_fn,_onClickBrowseEquipmentCompendia,onClickBrowseEquipmentCompendia_fn,_onClickCreateItem,onClickCreateItem_fn,_onClickSellAllTreasure,onClickSellAllTreasure_fn,_localize,localize_fn,_createTemplate,createTemplate_fn,_createCheck,createCheck_fn,_createSingleCheck,createSingleCheck_fn,_resolve,_getDamageIcon,getDamageIcon_fn,_getCategoryIcon,getCategoryIcon_fn,_getTypeLabel,getTypeLabel_fn,_getDiceLabel,getDiceLabel_fn,_finalizeDamage,finalizeDamage_fn,_excludeDamage,excludeDamage_fn,_getSelectors,getSelectors_fn,_strengthBasedDamage,strengthBasedDamage_fn,_strengthModToDamage,strengthModToDamage_fn,_item,_resolve2,_action,_canSetAbility,canSetAbility_fn,_onConfigureActor,onConfigureActor_fn,_onToggleSignatureSpell,onToggleSignatureSpell_fn,_onClickBrowseActions,onClickBrowseActions_fn,_onClickBrowseSpellCompendia,onClickBrowseSpellCompendia_fn,_createButtons,createButtons_fn,_calculateAncestryBoosts,calculateAncestryBoosts_fn,_calculateBackgroundBoosts,calculateBackgroundBoosts_fn,_calculateLeveledBoosts,calculateLeveledBoosts_fn,_getBoostFlawLabels,getBoostFlawLabels_fn,_updateRE,updateRE_fn,_prepareCraftingEntries,prepareCraftingEntries_fn,_onClickBrowseFeats,onClickBrowseFeats_fn,_onChangeAdjustStat,onChangeAdjustStat_fn,_onClickAdjustStat,onClickAdjustStat_fn,_onChangeAdjustItemStat,onChangeAdjustItemStat_fn,_onClickAdjustItemStat,onClickAdjustItemStat_fn,_onIncrementModifierValue,onIncrementModifierValue_fn,_onDecrementModifierValue,onDecrementModifierValue_fn,_onAddCustomModifier,onAddCustomModifier_fn,_onRemoveCustomModifier,onRemoveCustomModifier_fn,_getNearestFeatSlotId,getNearestFeatSlotId_fn,_sortFormulas,sortFormulas_fn,_isReachValue,isReachValue_fn,_getReach,getReach_fn,_isValid,isValid_fn,_constructWeapon,constructWeapon_fn,_setRollOptions,setRollOptions_fn,_prepareAC,prepareAC_fn,_prepareSenses,prepareSenses_fn,_prepareSize,prepareSize_fn,_prepareSpeeds,prepareSpeeds_fn,_prepareSkills,prepareSkills_fn,_prepareStrikes,prepareStrikes_fn,_prepareIWR,prepareIWR_fn,_suppressModifiers,suppressModifiers_fn,_filterModifier,filterModifier_fn,_suppressNotes,suppressNotes_fn,_setDefaultFlag,setDefaultFlag_fn,_choicesFromPath,choicesFromPath_fn,_choicesFromOwnedItems,choicesFromOwnedItems_fn,_choicesFromAttacks,choicesFromAttacks_fn,_getPreselection,getPreselection_fn,_setRollOption,setRollOption_fn,_validate,validate_fn,_getEffect,getEffect_fn,_isValidOverride,isValidOverride_fn,_resolvedBracketsIsValid,resolvedBracketsIsValid_fn,_details,_getOnDeleteActions,getOnDeleteActions_fn,_applyChoiceSelections,applyChoiceSelections_fn,_setGrantFlags,setGrantFlags_fn,_runGrantedItemPreCreates,runGrantedItemPreCreates_fn,_trackItem,trackItem_fn,_target,_resolve3,_cancelHandler,cancelHandler_fn,_checkRuleSource,checkRuleSource_fn,_createDeferredEffect,createDeferredEffect_fn,_isValid2,isValid_fn2,_resolveOption,resolveOption_fn,_isValid3,isValid_fn3,_isValid4,isValid_fn4,_srcIsValid,srcIsValid_fn,_refreshSettings,refreshSettings_fn,_registerModuleTags,registerModuleTags_fn,_getConfigRecord,getConfigRecord_fn,_updateConfigRecords,updateConfigRecords_fn,_isFlatModifier,isFlatModifier_fn,_toRuleElement,toRuleElement_fn,_rationsSourceId,_rationsPromise,_isOldRations,isOldRations_fn,_getRationRefs,getRationRefs_fn,_migrateClass,migrateClass_fn,_migrateFeature,migrateFeature_fn,_isClassFeature2,isClassFeature_fn2,_isClassFeature3,isClassFeature_fn3,_isHeritageFeature,isHeritageFeature_fn,_officialAncestries,_heritagesWithoutAncestryInName,_ancestrySlugs,_heritageFromFeat,heritageFromFeat_fn,_explorersClothingVariants,_pathPattern,_hasWellFormedFeatType,hasWellFormedFeatType_fn,_needsTrait,needsTrait_fn,_hasBrokenThreshold,hasBrokenThreshold_fn,_shadowPromise,_cascadePromise,_isEffectTargetRE,isEffectTargetRE_fn,_toChoiceSet,toChoiceSet_fn,_loadedSpells,_isChoiceSetWithSelection,isChoiceSetWithSelection_fn,_newRules,newRules_fn,_toSkip,_hasThrownTrait,hasThrownTrait_fn,_cleanText,cleanText_fn,_updateEffect,updateEffect_fn,_updateFeat,updateFeat_fn,_vivaciousRules,vivaciousRules_get,_auraOfLife,_enlightenedPresence,_eternalBlessing,_marshalsAura,_findDamageDiceRE,findDamageDiceRE_fn,_isClassFeature4,isClassFeature_fn4,_athleticStrategist,athleticStrategist_get,_deviseAStratagem,deviseAStratagem_get,_ruffianPredicate,ruffianPredicate_get,_sneakAttackPredicate,sneakAttackPredicate_get,_updateSpeed,updateSpeed_fn,_suppressNoCrowbar,suppressNoCrowbar_get,_convertToUUIDs,convertToUUIDs_fn,_getRules,getRules_fn,_preciseStrikeRules,preciseStrikeRules_get,_finishingPrecisionRules,finishingPrecisionRules_get,_otherClassDCs,_isClassFeature5,isClassFeature_fn5,_critSpec,critSpec_get,_hands,hands_get,_convertLegacyData,convertLegacyData_fn,_isOldRawPredicate,isOldRawPredicate_fn,_isArrayChoiceSet,isArrayChoiceSet_fn,_isObjectChoiceSet,isObjectChoiceSet_fn,_shapeFeats,_flatFootedToggle,flatFootedToggle_get,_isFlatFootedToggle,isFlatFootedToggle_fn,_convertToEntry,convertToEntry_fn,_modifyFlag,modifyFlag_fn,_oldIdsPattern,_colorDarkvision,colorDarkvision_get,_AREA_TYPES,_isAreaType,isAreaType_fn,_hasDetails,hasDetails_fn,_pattern,_damageTypeLabelPattern,_updateDamageFormula,updateDamageFormula_fn,_automatonEnhancements,automatonEnhancements_get,_conditionPattern,_pattern2,_updateDamageFormula2,updateDamageFormula_fn2,_getWR,getWR_fn,_oldENmappings,_parseExceptions,parseExceptions_fn,_normalizeType,normalizeType_fn,_updateWeaponMaterialData,updateWeaponMaterialData_fn,_updateChoiceSet,updateChoiceSet_fn,_bomberSetFlags,bomberSetFlags_get,_chirurgeonSetFlags,chirurgeonSetFlags_get,_mutagenistSetFlags,mutagenistSetFlags_get,_toxicologistSetFlags,toxicologistSetFlags_get,_needsRE,needsRE_fn,_splashPattern1,_splashPattern2,_damagePatternSingle,_damagePatternPair,_cleanFormula,cleanFormula_fn,_buildSplashFormula,buildSplashFormula_fn,_buildDamageFormula,buildDamageFormula_fn,_updateDamageFormula3,updateDamageFormula_fn3,_rename,rename_fn,_removeLinks,removeLinks_fn,_cloisteredClericSetFlags,cloisteredClericSetFlags_get,_warpriestSetFlags,warpriestSetFlags_get,_updateCategoryData,updateCategoryData_fn,_rename2,rename_fn2,_wrapPredicate,wrapPredicate_fn,_slugMap,_createBonusesAndPenalties,createBonusesAndPenalties_fn,_createShieldBonus,createShieldBonus_fn,_prepareAbilityScores,prepareAbilityScores_fn,_prepareFeats,prepareFeats_fn,_disableScale,disableScale_fn,_reestablishPrototype,reestablishPrototype_fn,_disableVisionInputs,disableVisionInputs_fn,_squares,_prepareDerivedPerception,prepareDerivedPerception_fn,_localize2,_initialize,initialize_fn,_handleTrickItem,handleTrickItem_fn,_hasRollOptionData,hasRollOptionData_fn,_createItemMacro,createItemMacro_fn,_createRollOptionToggleMacro,createRollOptionToggleMacro_fn,_appendBrowseButton,appendBrowseButton_fn,_appendBrowseButton2,appendBrowseButton_fn2,_handleDamageButtonClick,handleDamageButtonClick_fn,_handleRevertDamageClick,handleRevertDamageClick_fn,_handleShieldButtonClick,handleShieldButtonClick_fn,_dragPreview,dragPreview_get,_compileSearchIndex,compileSearchIndex_fn,_onToggleTarget,onToggleTarget_fn,_onDropCombatant,onDropCombatant_fn,_updateUI,updateUI_fn,_domParser,_localizeCoins,_setModuleArt,setModuleArt_fn,_getSources,getSources_fn,_createFilteredIndex,createFilteredIndex_fn,_loadSources,loadSources_fn,_getSourceFromDocument,getSourceFromDocument_fn,_resetInitializedTabs,resetInitializedTabs_fn,_renderResultList,renderResultList_fn,_activateResultListeners,activateResultListeners_fn,_takePhysicalItem,takePhysicalItem_fn,_buyPhysicalItem,buyPhysicalItem_fn,_getPhysicalItem,getPhysicalItem_fn,_resetFilters,resetFilters_fn,_clearScrollLimit,clearScrollLimit_fn,_getRemainingDurationLabel,getRemainingDurationLabel_fn,_getEnrichedDescriptions,getEnrichedDescriptions_fn,_lastCombatantToken,_ICON_THEME_DIRS,_activateListeners,activateListeners_fn,_updateStatusIcons,updateStatusIcons_fn,_showStatusLabel,showStatusLabel_fn,_setStatusValue,setStatusValue_fn,_toggleStatus,toggleStatus_fn,_createChatMessage,createChatMessage_fn,_action2,_cost,_description,_slug,_traits,_variants,_action3,_effect,_action4,_difficultyClass,_modifiers,_notes,_rollOptions,_statistic,_initialized,_sortConditions,sortConditions_fn,_removeExpired,removeExpired_fn,_getArtMap,getArtMap_fn,_isModuleArt,isModuleArt_fn,_prepareActions,prepareActions_fn,_prepareSaves,prepareSaves_fn,_distributeCoins,distributeCoins_fn,_lootNPCs,lootNPCs_fn,_onClickAddSkill,onClickAddSkill_fn,_onClickRemoveSkill,onClickRemoveSkill_fn,_onClickAddLoreSkill,onClickAddLoreSkill_fn,_onClickEditSkill,onClickEditSkill_fn,_isLoreSkill,isLoreSkill_fn,_isRegularSkill,isRegularSkill_fn,_findSkillName,findSkillName_fn,_findSkillItem,findSkillItem_fn,_identificationData,_padAttempts,padAttempts_fn,_prepareAbilities,prepareAbilities_fn,_prepareAlignment,prepareAlignment_fn,_prepareSkills2,prepareSkills_fn2,_prepareSaves2,prepareSaves_fn2,_prepareActions2,prepareActions_fn2,_rollAbility,rollAbility_fn,_onClickRollable,onClickRollable_fn,_onChangeSpellcastingEntry,onChangeSpellcastingEntry_fn,_isValidDrop,isValidDrop_fn,_formatSpellComponents,formatSpellComponents_fn,_prepareHeighteningLevels,prepareHeighteningLevels_fn,_prepareMembers,prepareMembers_fn,_prepareLanguages,prepareLanguages_fn,_getActorsThatUnderstand,getActorsThatUnderstand_fn;import{T as Tagify,D as Duration,I as Interval,a as DateTime,n as noUiSlider,b as nouisliderExports,u as uniq,s as sortBy$1,c as compact,S as Sortable,o as omit,d as difference,g as groupBy$1,E as EditorView,e as basicSetup,j as json,l as linter,k as keymap,i as indentWithTab,f as autocompletion,h as syntaxTree,m as jsonParseLinter,p as mapToObj,M as MiniSearch,q as pick$1}from"./vendor.mjs";const BabeleReady={listen(){Hooks.once("babele.ready",()=>{game.pf2e.ConditionManager.initialize(!0)})}},CanvasInit={listen:()=>{Hooks.on("canvasInit",async canvas2=>{SquareGrid.prototype.measureDistances=__name2(__name(function(segments,options={}){if(!options.gridSpaces)return BaseGrid.prototype.measureDistances.call(this,segments,options);let nDiagonal=0;const d=canvas2.dimensions;return segments.map(s=>{const r=s.ray,nx=Math.abs(Math.ceil(r.dx/d.size)),ny=Math.abs(Math.ceil(r.dy/d.size)),nd=Math.min(nx,ny),ns=Math.abs(ny-nx);nDiagonal+=nd;const nd10=Math.floor(nDiagonal/2)-Math.floor((nDiagonal-nd)/2);return(nd10*2+(nd-nd10)+ns)*canvas2.dimensions.distance})},"measureDistances"),"measureDistances")})}},CanvasReady={listen:()=>{Hooks.once("canvasReady",async()=>{var _a;await game.pf2e.ConditionManager.initialize();const tokenActors=((_a=canvas.scene)==null?void 0:_a.tokens.contents.flatMap(t=>t.actor??[]))??[];for(const actor of tokenActors)for(const effect of actor.itemTypes.effect.filter(e=>e.fromAura))game.pf2e.effectTracker.register(effect)}),Hooks.on("canvasReady",()=>{game.pf2e.effectPanel.render(!0),canvas.scene&&(game.ready&&canvas.scene.reset(),CONFIG.MeasuredTemplate.defaults.angle=canvas.scene.hasHexGrid?60:90);for(const token of canvas.tokens.placeables)(token.isVideo?new Promise(resolve=>{token.sourceElement.addEventListener("play",()=>setTimeout(resolve,50),{once:!0})}):Promise.resolve()).then(async()=>{const{visible}=token;await token.draw(),token.visible=visible})})}},CloseCombatTrackerConfig={listen:()=>{Hooks.on("closeCombatTrackerConfig",async(_app,$html)=>{const newIcon=String($html.find('input[name="deathIcon"]').val()).trim();newIcon&&newIcon!==game.settings.get("pf2e","deathIcon")&&await game.settings.set("pf2e","deathIcon",newIcon);const currentDeadAtZero=game.settings.get("pf2e","automation.actorsDeadAtZero"),newDeadAtZero=String($html.find('select[name="actorsDeadAtZero"]').val());currentDeadAtZero!==newDeadAtZero&&await game.settings.set("pf2e","automation.actorsDeadAtZero",newDeadAtZero)})}},CloseWorldClockSettings={listen:()=>{Hooks.on("closeWorldClockSettings",()=>{game.user.isGM&&game.socket.emit("system.pf2e",{request:"refreshSceneControls",data:{layer:"TokenLayer"}})})}},isDice3D=__name2(obj=>obj instanceof Object&&["addSystem","addDicePreset","addTexture","addColorset"].every(m=>m in obj),"isDice3D"),DiceSoNiceReady={listen:()=>{Hooks.once("diceSoNiceReady",dice3d=>{if(isDice3D(dice3d)){dice3d.addSystem({id:"basic",name:"Dicefinder Basic",colorset:"basic"});for(const faces of[4,6,8,10,12])dice3d.addDicePreset({type:`d${faces}`,labels:[...Array(faces)].map((_value,idx)=>String(idx+1)),system:"basic",colorset:"basic"});dice3d.addDicePreset({type:"d20",labels:["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","systems/pf2e/dice/basic/nat20.webp"],system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"dc",labels:["systems/pf2e/dice/basic/tail.webp","systems/pf2e/dice/basic/heads.webp"],system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"d2",labels:["systems/pf2e/dice/basic/tail_bump.webp","systems/pf2e/dice/basic/heads_bump.webp"],system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"d100",labels:[...Array(10)].map((_value,idx)=>String((idx+1)*10)),system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"df",labels:["-","","+"],system:"basic",colorset:"basic"}),dice3d.addTexture("PFred",{name:"Pathfinder Red",composite:"source-over",source:"systems/pf2e/dice/texture/texture.webp"}).then(()=>{dice3d.addColorset({name:"basic",description:"Dicefinder Basic",category:"Pathfinder 2e",texture:"PFred",material:"metal",foreground:"#f9b96e",outline:"none",edge:"#f9b96e",visibility:"hidden"})}),dice3d.addSystem({id:"campaign",name:"Dicefinder Campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"dc",labels:["systems/pf2e/dice/basic/tail.webp","systems/pf2e/dice/basic/heads.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d2",labels:["systems/pf2e/dice/basic/tail_bump.webp","systems/pf2e/dice/basic/heads_bump.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d4",labels:["systems/pf2e/dice/campaign/d4/d4-1.webp","systems/pf2e/dice/campaign/d4/d4-2.webp","systems/pf2e/dice/campaign/d4/d4-3.webp","systems/pf2e/dice/campaign/d4/d4-4.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d6",labels:["systems/pf2e/dice/campaign/d6/d6-1.webp","systems/pf2e/dice/campaign/d6/d6-2.webp","systems/pf2e/dice/campaign/d6/d6-3.webp","systems/pf2e/dice/campaign/d6/d6-4.webp","systems/pf2e/dice/campaign/d6/d6-5.webp","systems/pf2e/dice/campaign/d6/d6-6.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"df",labels:["systems/pf2e/dice/campaign/df/dfm.webp","systems/pf2e/dice/campaign/df/df.webp","systems/pf2e/dice/campaign/df/dfp.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d8",labels:["systems/pf2e/dice/campaign/d8/d8-1.webp","systems/pf2e/dice/campaign/d8/d8-2.webp","systems/pf2e/dice/campaign/d8/d8-3.webp","systems/pf2e/dice/campaign/d8/d8-4.webp","systems/pf2e/dice/campaign/d8/d8-5.webp","systems/pf2e/dice/campaign/d8/d8-6.webp","systems/pf2e/dice/campaign/d8/d8-7.webp","systems/pf2e/dice/campaign/d8/d8-P.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d10",labels:["systems/pf2e/dice/campaign/d10/d10-1.webp","systems/pf2e/dice/campaign/d10/d10-2.webp","systems/pf2e/dice/campaign/d10/d10-3.webp","systems/pf2e/dice/campaign/d10/d10-4.webp","systems/pf2e/dice/campaign/d10/d10-5.webp","systems/pf2e/dice/campaign/d10/d10-6.webp","systems/pf2e/dice/campaign/d10/d10-7.webp","systems/pf2e/dice/campaign/d10/d10-8.webp","systems/pf2e/dice/campaign/d10/d10-9.webp","systems/pf2e/dice/campaign/d10/d10-10.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d12",labels:["systems/pf2e/dice/campaign/d12/d12-1.webp","systems/pf2e/dice/campaign/d12/d12-2.webp","systems/pf2e/dice/campaign/d12/d12-3.webp","systems/pf2e/dice/campaign/d12/d12-4.webp","systems/pf2e/dice/campaign/d12/d12-5.webp","systems/pf2e/dice/campaign/d12/d12-6.webp","systems/pf2e/dice/campaign/d12/d12-7.webp","systems/pf2e/dice/campaign/d12/d12-8.webp","systems/pf2e/dice/campaign/d12/d12-9.webp","systems/pf2e/dice/campaign/d12/d12-10.webp","systems/pf2e/dice/campaign/d12/d12-11.webp","systems/pf2e/dice/campaign/d12/d12-12.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d100",labels:["systems/pf2e/dice/campaign/d100/d100-10.webp","systems/pf2e/dice/campaign/d100/d100-20.webp","systems/pf2e/dice/campaign/d100/d100-30.webp","systems/pf2e/dice/campaign/d100/d100-40.webp","systems/pf2e/dice/campaign/d100/d100-50.webp","systems/pf2e/dice/campaign/d100/d100-60.webp","systems/pf2e/dice/campaign/d100/d100-70.webp","systems/pf2e/dice/campaign/d100/d100-80.webp","systems/pf2e/dice/campaign/d100/d100-90.webp","systems/pf2e/dice/campaign/d100/d100-100.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d20",labels:["systems/pf2e/dice/campaign/d20/d20-1.webp","systems/pf2e/dice/campaign/d20/d20-2.webp","systems/pf2e/dice/campaign/d20/d20-3.webp","systems/pf2e/dice/campaign/d20/d20-4.webp","systems/pf2e/dice/campaign/d20/d20-5.webp","systems/pf2e/dice/campaign/d20/d20-6.webp","systems/pf2e/dice/campaign/d20/d20-7.webp","systems/pf2e/dice/campaign/d20/d20-8.webp","systems/pf2e/dice/campaign/d20/d20-9.webp","systems/pf2e/dice/campaign/d20/d20-10.webp","systems/pf2e/dice/campaign/d20/d20-11.webp","systems/pf2e/dice/campaign/d20/d20-12.webp","systems/pf2e/dice/campaign/d20/d20-13.webp","systems/pf2e/dice/campaign/d20/d20-14.webp","systems/pf2e/dice/campaign/d20/d20-15.webp","systems/pf2e/dice/campaign/d20/d20-16.webp","systems/pf2e/dice/campaign/d20/d20-17.webp","systems/pf2e/dice/campaign/d20/d20-18.webp","systems/pf2e/dice/campaign/d20/d20-19.webp","systems/pf2e/dice/campaign/d20/d20-20.webp"],system:"campaign",colorset:"campaign"}),dice3d.addTexture("stoneD4",{name:"Pathfinder Stone (D4)",composite:"source-over",source:"systems/pf2e/dice/texture/d4.webp"}).then(()=>{dice3d.addColorset({name:"campaign",description:"Dicefinder Campaign",category:"Pathfinder 2e",texture:"stoneD4",material:"stone",foreground:"#5c2f00",outline:"none",edge:"#f9b96e",visibility:"hidden"})}),dice3d.addSystem({id:"darkmode",name:"Dicefinder Dark Mode",colorset:"darkmode"});for(const faces of[4,6,8,10,12])dice3d.addDicePreset({type:`d${faces}`,labels:[...Array(faces)].map((_value,idx)=>String(idx+1)),system:"darkmode",colorset:"darkmode"});dice3d.addDicePreset({type:"d100",labels:[...Array(10)].map((_value,idx)=>String((idx+1)*10)),system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"df",labels:["-","","+"],system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"d20",labels:["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","systems/pf2e/dice/basic/nat20.webp"],system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"dc",labels:["systems/pf2e/dice/basic/tail.webp","systems/pf2e/dice/basic/heads.webp"],system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"d2",labels:["systems/pf2e/dice/basic/tail_bump.webp","systems/pf2e/dice/basic/heads_bump.webp"],system:"darkmode",colorset:"darkmode"}),dice3d.addTexture("darkModeBlack",{name:"Dark Mode Black",composite:"source-over",source:"systems/pf2e/dice/texture/transparent.webp"}).then(()=>{dice3d.addColorset({name:"darkmode",description:"Dicefinder Dark Mode",category:"Pathfinder 2e",texture:"darkModeBlack",material:"metal",foreground:"#f9b96e",outline:"none",edge:"#f9b96e",visibility:"hidden"})})}})}};function createHTMLElement(nodeName,{classes=[],dataset={},children=[]}={}){const element=document.createElement(nodeName);element.classList.add(...classes);for(const[key,value]of Object.entries(dataset))element.dataset[key]=String(value);for(const child of children){const childElement=child instanceof HTMLElement?child:new Text(child);element.appendChild(childElement)}return element}__name(createHTMLElement,"createHTMLElement"),__name2(createHTMLElement,"createHTMLElement");function htmlQuery(parent,selectors){return parent instanceof Element||parent instanceof Document?parent.querySelector(selectors):null}__name(htmlQuery,"htmlQuery"),__name2(htmlQuery,"htmlQuery");function htmlQueryAll(parent,selectors){return parent instanceof Element||parent instanceof Document?Array.from(parent.querySelectorAll(selectors)):[]}__name(htmlQueryAll,"htmlQueryAll"),__name2(htmlQueryAll,"htmlQueryAll");function htmlClosest(child,selectors){return child instanceof Element?child.closest(selectors):null}__name(htmlClosest,"htmlClosest"),__name2(htmlClosest,"htmlClosest");function groupBy(array,criterion){const result=new Map;for(const elem of array){const key=criterion(elem),group=result.get(key);group?group.push(elem):result.set(key,[elem])}return result}__name(groupBy,"groupBy"),__name2(groupBy,"groupBy");function sortBy(mapping){return(a,b)=>{const value1=mapping(a),value2=mapping(b);return value1(result[key]=mapping(value,key),result),{})}__name(mapValues,"mapValues"),__name2(mapValues,"mapValues");function isBlank(text){return text==null||text.trim()===""}__name(isBlank,"isBlank"),__name2(isBlank,"isBlank");function addSign(number){return number<0?`${number}`:`+${number}`}__name(addSign,"addSign"),__name2(addSign,"addSign");function sum(values){return values.reduce((a,b)=>a+b,0)}__name(sum,"sum"),__name2(sum,"sum");function zip(a,b,zipFunction){return a.length>b.length?b.map((elem,index)=>zipFunction(a[index],elem)):a.map((elem,index)=>zipFunction(elem,b[index]))}__name(zip,"zip"),__name2(zip,"zip");function applyNTimes(func,times,start){let result=start;for(let i=0;i(key in obj&&(result[key]=obj[key]),result),{})}__name(pick,"pick"),__name2(pick,"pick");let intlNumberFormat;function signedInteger(value,{emptyStringZero=!0}={}){return value===0&&emptyStringZero?"":(intlNumberFormat??(intlNumberFormat=new Intl.NumberFormat(game.i18n.lang,{maximumFractionDigits:0,signDisplay:"always"}))).format(value)}__name(signedInteger,"signedInteger"),__name2(signedInteger,"signedInteger");const wordCharacter=String.raw`[\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Join_Control}]`,nonWordCharacter=String.raw`[^\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Join_Control}]`,nonWordCharacterRE=new RegExp(nonWordCharacter,"gu"),wordBoundary=String.raw`(?:${wordCharacter})(?=${nonWordCharacter})|(?:${nonWordCharacter})(?=${wordCharacter})`,nonWordBoundary=String.raw`(?:${wordCharacter})(?=${wordCharacter})`,lowerCaseLetter=String.raw`\p{Lowercase_Letter}`,upperCaseLetter=String.raw`\p{Uppercase_Letter}`,lowerCaseThenUpperCaseRE=new RegExp(`(${lowerCaseLetter})(${upperCaseLetter}${nonWordBoundary})`,"gu"),nonWordCharacterHyphenOrSpaceRE=/[^-\p{White_Space}\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Join_Control}]/gu,upperOrWordBoundariedLowerRE=new RegExp(`${upperCaseLetter}|(?:${wordBoundary})${lowerCaseLetter}`,"gu");function sluggify(text,{camel=null}={}){if(typeof text!="string")return console.warn("Non-string argument passed to `sluggify`"),"";if(text==="-")return text;switch(camel){case null:return text.replace(lowerCaseThenUpperCaseRE,"$1-$2").toLowerCase().replace(/['’]/g,"").replace(nonWordCharacterRE," ").trim().replace(/[-\s]+/g,"-");case"bactrian":{const dromedary=sluggify(text,{camel:"dromedary"});return dromedary.charAt(0).toUpperCase()+dromedary.slice(1)}case"dromedary":return text.replace(nonWordCharacterHyphenOrSpaceRE,"").replace(/[-_]+/g," ").replace(upperOrWordBoundariedLowerRE,(part,index)=>index===0?part.toLowerCase():part.toUpperCase()).replace(/\s+/g,"");default:throw ErrorPF2e("I don't think that's a real camel.")}}__name(sluggify,"sluggify"),__name2(sluggify,"sluggify");function parseHTML(unparsed){const fragment=document.createElement("template");fragment.innerHTML=unparsed;const element=fragment.content.firstElementChild;if(!(element instanceof HTMLElement))throw ErrorPF2e("Unexpected error parsing HTML");return element}__name(parseHTML,"parseHTML"),__name2(parseHTML,"parseHTML");function getActionTypeLabel(type2,cost){switch(type2){case"action":return cost===1?"PF2E.Item.Action.Type.Single":"PF2E.Item.Action.Type.Activity";case"free":return"PF2E.Item.Action.Type.Free";case"reaction":return"PF2E.Item.Action.Type.Reaction";default:return null}}__name(getActionTypeLabel,"getActionTypeLabel"),__name2(getActionTypeLabel,"getActionTypeLabel");const actionImgMap={0:"systems/pf2e/icons/actions/FreeAction.webp",free:"systems/pf2e/icons/actions/FreeAction.webp",1:"systems/pf2e/icons/actions/OneAction.webp",2:"systems/pf2e/icons/actions/TwoActions.webp",3:"systems/pf2e/icons/actions/ThreeActions.webp","1 or 2":"systems/pf2e/icons/actions/OneTwoActions.webp","1 to 3":"systems/pf2e/icons/actions/OneThreeActions.webp","2 or 3":"systems/pf2e/icons/actions/TwoThreeActions.webp",reaction:"systems/pf2e/icons/actions/Reaction.webp",passive:"systems/pf2e/icons/actions/Passive.webp"};function getActionIcon(action2,fallback="systems/pf2e/icons/actions/Empty.webp"){if(action2===null)return actionImgMap.passive;const value=typeof action2!="object"?action2:action2.type==="action"?action2.value:action2.type,sanitized=String(value??"").toLowerCase().trim();return actionImgMap[sanitized]??fallback}__name(getActionIcon,"getActionIcon"),__name2(getActionIcon,"getActionIcon");const actionGlyphMap={0:"F",free:"F",1:"A",2:"D",3:"T","1 or 2":"A/D","1 to 3":"A - T","2 or 3":"D/T",reaction:"R"};function getActionGlyph(action2){if(!action2&&action2!==0)return"";const value=typeof action2!="object"?action2:action2.type==="action"?action2.value:action2.type,sanitized=String(value??"").toLowerCase().trim();return actionGlyphMap[sanitized]??""}__name(getActionGlyph,"getActionGlyph"),__name2(getActionGlyph,"getActionGlyph");function ErrorPF2e(message){return Error(`PF2e System | ${message}`)}__name(ErrorPF2e,"ErrorPF2e"),__name2(ErrorPF2e,"ErrorPF2e");function ordinal(value){const pluralRules=new Intl.PluralRules(game.i18n.lang,{type:"ordinal"}),suffix=game.i18n.localize(`PF2E.OrdinalSuffixes.${pluralRules.select(value)}`);return game.i18n.format("PF2E.OrdinalNumber",{value,suffix})}__name(ordinal,"ordinal"),__name2(ordinal,"ordinal");function localizeList(items,{conjunction="or"}={}){items=[...items].sort((a,b)=>a.localeCompare(b,game.i18n.lang));const parts=conjunction==="or"?"PF2E.ListPartsOr":"PF2E.ListPartsAnd";if(items.length===0)return"";if(items.length===1)return items[0];if(items.length===2)return game.i18n.format(`${parts}.two`,{first:items[0],second:items[1]});let result=game.i18n.format(`${parts}.start`,{first:items[0],second:"{second}"});for(let i=1;i<=items.length-2;i++)if(i===items.length-2){const end=game.i18n.format(`${parts}.end`,{first:items[i],second:items[items.length-1]});result=result.replace("{second}",end)}else{const newSegment=game.i18n.format(`${parts}.middle`,{first:items[i],second:"{second}"});result=result.replace("{second}",newSegment)}return result}__name(localizeList,"localizeList"),__name2(localizeList,"localizeList");function fontAwesomeIcon(glyph,{style="solid",fixedWidth=!1}={}){const styleClass=`fa-${style}`,glyphClass=glyph.startsWith("fa-")?glyph:`fa-${glyph}`,icon=document.createElement("i");return icon.classList.add(styleClass,glyphClass),fixedWidth&&icon.classList.add("fa-fw"),icon}__name(fontAwesomeIcon,"fontAwesomeIcon"),__name2(fontAwesomeIcon,"fontAwesomeIcon");function isObject(value){return typeof value=="object"&&value!==null}__name(isObject,"isObject"),__name2(isObject,"isObject");function sortLabeledRecord(record){return Object.entries(record).sort((a,b)=>a[1].label.localeCompare(b[1].label,game.i18n.lang)).reduce((copy,[key,value])=>mergeObject(copy,{[key]:value}),{})}__name(sortLabeledRecord,"sortLabeledRecord"),__name2(sortLabeledRecord,"sortLabeledRecord");function sortStringRecord(record){return Object.fromEntries(Object.entries(record).map(entry=>(entry[1]=game.i18n.localize(entry[1]),entry)).sort((a,b)=>a[1].localeCompare(b[1],game.i18n.lang)))}__name(sortStringRecord,"sortStringRecord"),__name2(sortStringRecord,"sortStringRecord");function sortObjByKey(value){return isObject(value)?Array.isArray(value)?value.map(sortObjByKey):Object.keys(value).sort().reduce((o,key)=>{const v=value[key];return o[key]=sortObjByKey(v),o},{}):value}__name(sortObjByKey,"sortObjByKey"),__name2(sortObjByKey,"sortObjByKey");function sortedStringify(obj){return JSON.stringify(sortObjByKey(obj))}__name(sortedStringify,"sortedStringify"),__name2(sortedStringify,"sortedStringify");function recursiveReplaceString(source,replace){const clone=isObject(source)?deepClone(source):source;if(typeof clone=="string")return replace(clone);if(isObject(clone))for(const[key,value]of Object.entries(clone))Array.isArray(value)?clone[key]=value.map(e=>typeof e=="string"||isObject(e)?recursiveReplaceString(e,replace):e):(typeof value=="string"||isObject(value))&&(clone[key]=recursiveReplaceString(value,replace));return clone}__name(recursiveReplaceString,"recursiveReplaceString"),__name2(recursiveReplaceString,"recursiveReplaceString");function localizer(prefix){return(...[suffix,formatArgs])=>formatArgs?game.i18n.format(`${prefix}.${suffix}`,formatArgs):game.i18n.localize(`${prefix}.${suffix}`)}__name(localizer,"localizer"),__name2(localizer,"localizer");function configFromLocalization(localization,prefix){return Object.entries(localization).reduce((map,[key,value])=>({...map,[key]:typeof value=="string"?`${prefix}.${key}`:configFromLocalization(value,`${prefix}.${key}`)}),{})}__name(configFromLocalization,"configFromLocalization"),__name2(configFromLocalization,"configFromLocalization");function isImageFilePath(path){return typeof path=="string"&&Object.keys(CONST.IMAGE_FILE_EXTENSIONS).some(e=>path.endsWith(`.${e}`))}__name(isImageFilePath,"isImageFilePath"),__name2(isImageFilePath,"isImageFilePath");function isVideoFilePath(path){return typeof path=="string"&&Object.keys(CONST.VIDEO_FILE_EXTENSIONS).some(e=>path.endsWith(`.${e}`))}__name(isVideoFilePath,"isVideoFilePath"),__name2(isVideoFilePath,"isVideoFilePath");function isImageOrVideoPath(path){return isImageFilePath(path)||isVideoFilePath(path)}__name(isImageOrVideoPath,"isImageOrVideoPath"),__name2(isImageOrVideoPath,"isImageOrVideoPath");function traitSlugToObject(trait,dictionary){const traitObject={name:trait,label:game.i18n.localize(dictionary[trait]??trait)};return objectHasKey(CONFIG.PF2E.traitsDescriptions,trait)&&(traitObject.description=CONFIG.PF2E.traitsDescriptions[trait]),traitObject}__name(traitSlugToObject,"traitSlugToObject"),__name2(traitSlugToObject,"traitSlugToObject");function transformWhitelist(whitelist){return Array.isArray(whitelist)?whitelist:Object.entries(whitelist).map(([key,locPath])=>({id:key,value:game.i18n.localize(typeof locPath=="string"?locPath:locPath.label)})).sort((a,b)=>a.value.localeCompare(b.value,game.i18n.lang))}__name(transformWhitelist,"transformWhitelist"),__name2(transformWhitelist,"transformWhitelist");function tagify$1(input,{whitelist,maxTags,enforceWhitelist=!0}={}){if(input?.hasAttribute("name")&&input.dataset.dtype!=="JSON")throw ErrorPF2e("Usable only on input elements with JSON data-dtype");if(!input)return null;const whitelistTransformed=whitelist?transformWhitelist(whitelist):[],maxItems=whitelist?Object.keys(whitelistTransformed).length:void 0,tagify2=new Tagify(input,{enforceWhitelist:!!whitelist&&enforceWhitelist,keepInvalidTags:!1,skipInvalid:!!whitelist,maxTags:maxTags??maxItems,dropdown:{enabled:0,maxItems,searchKeys:["id","value"]},whitelist:whitelistTransformed});return input.name&&(tagify2.DOM.scope.dataset.name=input.name),tagify2.DOM.input.blur(),tagify2}__name(tagify$1,"tagify$1"),__name2(tagify$1,"tagify$1");const _ArithmeticExpression=__name(class extends RollTerm{constructor(termData){super(termData),__publicField(this,"operator"),__publicField(this,"operands"),this.operator=termData.operator,this.operands=termData.operands.slice(0,2).map(datum=>datum instanceof RollTerm?datum:(CONFIG.Dice.termTypes[datum.class??""]??Object.values(CONFIG.Dice.terms).find(t=>t.name===datum.class)??Die).fromData(datum)),this.operator==="*"&&this.operands[0]instanceof NumericTerm&&tupleHasValue([2,3],this.operands[0].number)&&markAsCrit(this.operands[1],this.operands[0].number)}static fromData(data){return super.fromData({...data,class:"ArithmeticExpression"})}static totalOf(operator,left,right){if(!(left===void 0||right===void 0))switch(operator){case"+":return left+right;case"-":return left-right;case"*":return left*right;case"/":return left/right;case"%":return left%right}}get dice(){return this.operands.flatMap(o=>o instanceof DiceTerm?o:o instanceof Grouping||o instanceof _ArithmeticExpression||o instanceof IntermediateDie?o.dice:[])}get expression(){if(this.isDeterministic)return this.total.toString();const{operator,operands}=this;return`${operands[0].expression} ${operator} ${operands[1].expression}`}get formula(){const{operator,operands}=this;return`${operands[0].formula} ${operator} ${operands[1].formula}`}get total(){if(!this._evaluated&&!this.isDeterministic)return;const operands=[Number(this.operands[0].total),Number(this.operands[1].total)];return _ArithmeticExpression.totalOf(this.operator,...operands)}get critImmuneTotal(){if(!this._evaluated)return;const[left,right]=this.operands;if(left instanceof NumericTerm&&left.number===2&&this.operator==="*")return typeof right.total=="string"?Number(right.total):right.total;const undoubledLeft=(()=>left instanceof _ArithmeticExpression||left instanceof Grouping?Number(left.critImmuneTotal):Number(left.total))(),undoubledRight=right instanceof _ArithmeticExpression||right instanceof Grouping?Number(right.critImmuneTotal):Number(right.total);return _ArithmeticExpression.totalOf(this.operator,undoubledLeft,undoubledRight)}get isDeterministic(){return this.operands.every(o=>o.isDeterministic&&!(o instanceof MathTerm))}get minimumValue(){const left=DamageInstance.getValue(this.operands[0],"minimum"),right=DamageInstance.getValue(this.operands[1],"minimum");return _ArithmeticExpression.totalOf(this.operator,left,right)}get expectedValue(){const left=DamageInstance.getValue(this.operands[0]),right=DamageInstance.getValue(this.operands[1]);return _ArithmeticExpression.totalOf(this.operator,left,right)}get maximumValue(){const left=DamageInstance.getValue(this.operands[0],"maximum"),right=DamageInstance.getValue(this.operands[1],"maximum");return _ArithmeticExpression.totalOf(this.operator,left,right)}render(){const fragment=new DocumentFragment,{operator,operands}=this;if(operator==="*"&&operands[0]instanceof NumericTerm&&operands[1]instanceof NumericTerm)return fragment.append((operands[0].total*operands[1].total).toString()),fragment;const[left,right]=operands.map(o=>["precision","splash"].includes(o.flavor)?renderComponentDamage(o):isSystemDamageTerm(o)?o.render():o.expression);return fragment.append(left,` ${this.operator} `,right),fragment}async _evaluate(options={}){for(const operand of this.operands)operand._evaluated||await operand.evaluate({async:!0,...options});return this._evaluated=!0,this}toJSON(){return{...super.toJSON(),operands:[this.operands[0].toJSON(),this.operands[1].toJSON()]}}},"_ArithmeticExpression");let ArithmeticExpression=_ArithmeticExpression;__name2(ArithmeticExpression,"ArithmeticExpression"),__publicField(ArithmeticExpression,"SERIALIZE_ATTRIBUTES",["operator","operands"]);const _Grouping=__name(class extends RollTerm{constructor(termData){var __super=__name((...args)=>{super(...args),__publicField(this,"term")},"__super");const childTerm=(CONFIG.Dice.termTypes[termData.term.class??""]??Object.values(CONFIG.Dice.terms).find(t=>t.name===termData.term.class)??NumericTerm).fromData(termData.term);childTerm instanceof _Grouping?(__super(childTerm.toJSON()),this.term=childTerm.term):(__super(termData),this.term=childTerm),this._evaluated=termData.evaluated??this.term._evaluated??!0}static fromData(data){return super.fromData({...data,class:"Grouping"})}get dice(){if(this.term instanceof DiceTerm)return[this.term];if(isObject(this.term)&&"dice"in this.term){const{dice}=this.term;if(Array.isArray(dice)&&dice.every(d=>d instanceof DiceTerm))return dice}return[]}get expression(){return this.isDeterministic?this.total.toString():this.term instanceof DiceTerm?this.term.expression:`(${this.term.expression})`}get formula(){const termFormula=this.term.formula,flavor=this.flavor?`[${this.flavor}]`:"";return`(${termFormula})${flavor}`}get total(){return this._evaluated||this.isDeterministic?Number(this.term.total):void 0}get critImmuneTotal(){return this.term instanceof ArithmeticExpression||this.term instanceof _Grouping?this.term.critImmuneTotal:this.total}get isDeterministic(){return this.term.isDeterministic&&!(this.term instanceof MathTerm)}get minimumValue(){return DamageInstance.getValue(this.term,"minimum")}get expectedValue(){return DamageInstance.getValue(this.term)}get maximumValue(){return DamageInstance.getValue(this.term,"maximum")}async _evaluate(options={}){return this.term._evaluated||await this.term.evaluate({async:!0,...options}),this._evaluated=!0,this}toJSON(){return{...super.toJSON(),term:this.term.toJSON()}}render(){const expression=["precision","splash"].includes(this.flavor)?renderComponentDamage(this.term):isSystemDamageTerm(this.term)?this.term.render():this.expression,fragment=new DocumentFragment,nodes=this.term instanceof NumericTerm||this.term instanceof Die?[expression]:["(",expression,")"];return fragment.append(...nodes),fragment}},"_Grouping");let Grouping=_Grouping;__name2(Grouping,"Grouping"),__publicField(Grouping,"SERIALIZE_ATTRIBUTES",["term"]);class IntermediateDie extends RollTerm{constructor(data){super(data),__publicField(this,"number"),__publicField(this,"faces"),__publicField(this,"die",null);const setTerm=__name2(termData=>{const term=CONFIG.Dice.termTypes[termData.class??"NumericTerm"].fromData(termData);return term instanceof Grouping&&(term.isIntermediate=!0),term},"setTerm");this.die=data.die?Die.fromData({...data.die,class:"Die"}):null,this.number=setTerm(data.number),this.faces=setTerm(data.faces)}get expression(){var _a;return((_a=this.die)==null?void 0:_a.expression)??`${this.number.expression}d${this.faces.expression}`}get total(){var _a;return(_a=this.die)==null?void 0:_a.total}get dice(){return this.die?[this.die]:[]}get isDeterministic(){return this.number.isDeterministic&&this.faces.isDeterministic&&!(this.number instanceof MathTerm)&&!(this.faces instanceof MathTerm)}get minimumValue(){return this.isDeterministic?DamageInstance.getValue(new Die({number:this.number.total,faces:this.faces.total}),"minimum"):NaN}get expectedValue(){return this.isDeterministic?DamageInstance.getValue(new Die({number:this.number.total,faces:this.faces.total})):NaN}get maximumValue(){return this.isDeterministic?DamageInstance.getValue(new Die({number:this.number.total,faces:this.faces.total}),"maximum"):NaN}async _evaluate(){return await this.number.evaluate({async:!0}),this.number=NumericTerm.fromData({class:"NumericTerm",number:this.number.total}),await this.faces.evaluate({async:!0}),this.faces=NumericTerm.fromData({class:"NumericTerm",number:this.faces.total}),this.die=await new Die({number:this.number.total,faces:this.faces.total,options:this.options}).evaluate({async:!0}),this._evaluated=!0,this}toJSON(){var _a;return{...super.toJSON(),number:this.number.toJSON(),faces:this.faces.toJSON(),die:(_a=this.die)==null?void 0:_a.toJSON()}}}__name(IntermediateDie,"IntermediateDie"),__name2(IntermediateDie,"IntermediateDie"),__publicField(IntermediateDie,"SERIALIZE_ATTRIBUTES",["number","faces","die"]);class InstancePool extends PoolTerm{static fromRolls(rolls=[]){const allEvaluated=rolls.every(r=>r._evaluated),noneEvaluated=!rolls.some(r=>r._evaluated);if(!(allEvaluated||noneEvaluated))return super.fromRolls(rolls);const pool=new this({terms:rolls.map(r=>r._formula),modifiers:[],rolls,results:allEvaluated?rolls.map(r=>({result:r.total,active:!0})):[]});return pool._evaluated=allEvaluated,pool}}__name(InstancePool,"InstancePool"),__name2(InstancePool,"InstancePool");const PHYSICAL_DAMAGE_TYPES=["bludgeoning","piercing","slashing","bleed"],LIFE_ENERGY_DAMAGE_TYPES=["positive","negative"],ENERGY_DAMAGE_TYPES=["acid","cold","electricity","fire","sonic","force",...LIFE_ENERGY_DAMAGE_TYPES],ALIGNMENT_DAMAGE_TYPES=["chaotic","lawful","good","evil"],DAMAGE_CATEGORIES_UNIQUE=new Set(["persistent","precision","splash"]),MATERIAL_DAMAGE_EFFECTS=new Set(["adamantine","cold-iron","darkwood","mithral","orichalcum","silver","sisterstone-dusk","sisterstone-scarlet","warpglass"]);[...DAMAGE_CATEGORIES_UNIQUE,...MATERIAL_DAMAGE_EFFECTS];const DAMAGE_DIE_FACES_TUPLE=["d4","d6","d8","d10","d12"],DAMAGE_DIE_FACES=new Set(DAMAGE_DIE_FACES_TUPLE),DAMAGE_TYPES=new Set([...PHYSICAL_DAMAGE_TYPES,...ENERGY_DAMAGE_TYPES,...ALIGNMENT_DAMAGE_TYPES,"mental","poison","untyped"]),BASE_DAMAGE_TYPES_TO_CATEGORIES={bludgeoning:"physical",piercing:"physical",slashing:"physical",bleed:"physical",acid:"energy",cold:"energy",electricity:"energy",fire:"energy",sonic:"energy",positive:"energy",negative:"energy",force:"energy",chaotic:"alignment",evil:"alignment",good:"alignment",lawful:"alignment",mental:null,poison:null,untyped:null},DAMAGE_TYPE_ICONS={bleed:"droplet",acid:"vial",bludgeoning:"hammer",chaotic:"face-zany",cold:"snowflake",electricity:"bolt",evil:"face-angry-horns",fire:"fire",force:"sparkles",good:"face-smile-halo",lawful:"scale-balanced",mental:"brain",negative:"skull",piercing:"bow-arrow",poison:"spider",positive:"sun",slashing:"axe",sonic:"waveform-lines",untyped:null},PERSISTENT_DAMAGE_IMAGES={piercing:"systems/pf2e/icons/equipment/weapons/throwing-knife.webp",bludgeoning:"systems/pf2e/icons/equipment/weapons/bola.webp",slashing:"systems/pf2e/icons/equipment/weapons/scimitar.webp",fire:"icons/magic/fire/flame-burning-creature-skeleton.webp",acid:"icons/magic/acid/dissolve-arm-flesh.webp",cold:"icons/magic/water/ice-snowman.webp",electricity:"systems/pf2e/icons/spells/chain-lightning.webp",sonic:"systems/pf2e/icons/spells/cry-of-destruction.webp",force:"systems/pf2e/icons/spells/magic-missile.webp",mental:"systems/pf2e/icons/spells/modify-memory.webp",poison:"systems/pf2e/icons/spells/acidic-burst.webp",lawful:"systems/pf2e/icons/equipment/adventuring-gear/merchant-scale.webp",chaotic:"systems/pf2e/icons/spells/dinosaur-form.webp",good:"systems/pf2e/icons/damage/persistent/good.webp",evil:"icons/magic/unholy/strike-body-explode-disintegrate.webp",positive:"systems/pf2e/icons/spells/moment-of-renewal.webp",negative:"systems/pf2e/icons/spells/grim-tendrils.webp"},CRITICAL_INCLUSION={DOUBLE_ON_CRIT:null,CRITICAL_ONLY:!0,DONT_DOUBLE_ON_CRIT:!1};function nextDamageDieSize(next){const[faces,direction]="upgrade"in next?[next.upgrade,1]:[next.downgrade,-1];return DAMAGE_DIE_FACES_TUPLE[DAMAGE_DIE_FACES_TUPLE.indexOf(faces)+direction]??faces}__name(nextDamageDieSize,"nextDamageDieSize"),__name2(nextDamageDieSize,"nextDamageDieSize");const DamageCategorization={fromDamageType:damageType=>BASE_DAMAGE_TYPES_TO_CATEGORIES[damageType],allCategories:()=>new Set(Object.values(BASE_DAMAGE_TYPES_TO_CATEGORIES)),baseCategories:()=>new Set(Object.values(BASE_DAMAGE_TYPES_TO_CATEGORIES)),toDamageTypes:category=>{const types=Object.entries(BASE_DAMAGE_TYPES_TO_CATEGORIES).filter(([_key,value])=>value===category).map(([key])=>key);return new Set(types)}};function renderComponentDamage(term){if(!["precision","splash"].includes(term.flavor))throw ErrorPF2e("Unexpected error rendering damage roll");const span=document.createElement("span");span.className=term.flavor;const[title,faClass]=term.flavor==="precision"?[game.i18n.localize("PF2E.Damage.Precision"),"crosshairs"]:[game.i18n.localize("PF2E.TraitSplash"),"burst"];span.title=title;const icon=fontAwesomeIcon(faClass);return icon.classList.add("icon"),span.append(term.expression," ",icon),span}__name(renderComponentDamage,"renderComponentDamage"),__name2(renderComponentDamage,"renderComponentDamage");function isSystemDamageTerm(term){return term instanceof ArithmeticExpression||term instanceof Grouping}__name(isSystemDamageTerm,"isSystemDamageTerm"),__name2(isSystemDamageTerm,"isSystemDamageTerm");function deepFindTerms(term,{flavor}){const childTerms=term instanceof Grouping?[term.term]:term instanceof ArithmeticExpression?term.operands:[];return[term.flavor.split(",").includes(flavor)?[term]:[],childTerms.map(t=>deepFindTerms(t,{flavor})).flat()].flat()}__name(deepFindTerms,"deepFindTerms"),__name2(deepFindTerms,"deepFindTerms");function looksLikeDamageRoll(roll){const{dice}=roll;return dice.length===0||dice.some(d=>[4,6,8,10,12].includes(d.faces??20))&&!dice.some(d=>[2,20].includes(d.faces??20))}__name(looksLikeDamageRoll,"looksLikeDamageRoll"),__name2(looksLikeDamageRoll,"looksLikeDamageRoll");function damageDiceIcon(roll,{fixedWidth=!0}={}){var _a,_b;const firstTerm=roll instanceof DamageRoll&&((_a=roll.instances[0])==null?void 0:_a.head)instanceof IntermediateDie?(_b=roll.instances[0])==null?void 0:_b.head:null;if(firstTerm?.faces instanceof NumericTerm&&[4,8,6,10,12].includes(firstTerm.faces.number))return fontAwesomeIcon(`dice-d${firstTerm.faces.number}`,{fixedWidth});const firstDice=roll.dice.at(0),glyph=firstDice instanceof Die&&[4,8,6,10,12].includes(firstDice.faces)?`dice-d${firstDice.faces}`:firstDice?"dice-d20":"calculator";return fontAwesomeIcon(glyph,{fixedWidth})}__name(damageDiceIcon,"damageDiceIcon"),__name2(damageDiceIcon,"damageDiceIcon");function markAsCrit(term,multiplier){term.options.crit=multiplier,term instanceof ArithmeticExpression?(markAsCrit(term.operands[0],multiplier),markAsCrit(term.operands[1],multiplier)):term instanceof Grouping&&markAsCrit(term.term,multiplier)}__name(markAsCrit,"markAsCrit"),__name2(markAsCrit,"markAsCrit");class AbstractDamageRoll extends Roll{constructor(formula,data={},options={}){options.critRule=(()=>tupleHasValue(["double-damage","double-dice"],options.critRule)?options.critRule:game.settings.get("pf2e","critRule")==="doubledamage"?"double-damage":"double-dice")(),super(formula,data,options)}static replaceFormulaData(formula,data,options={}){return super.replaceFormulaData(formula.trim(),data,options).replace(new RegExp("(?{AbstractDamageRoll.parser=function(){function createNumericTerm(number,{flavor=null,truncate=!1}={}){number=truncate?Math.trunc(number):number;const formula=flavor?`${number}[${flavor}]`:number.toString(),obj={class:"NumericTerm",number,formula,evaluated:!1};return flavor&&(obj.options={flavor}),obj}__name(createNumericTerm,"createNumericTerm"),__name2(createNumericTerm,"createNumericTerm");function peg$subclass(child,parent){function C(){this.constructor=child}__name(C,"C"),__name2(C,"C"),C.prototype=parent.prototype,child.prototype=new C}__name(peg$subclass,"peg$subclass"),__name2(peg$subclass,"peg$subclass");function peg$SyntaxError(message,expected,found,location){var self=Error.call(this,message);return Object.setPrototypeOf&&Object.setPrototypeOf(self,peg$SyntaxError.prototype),self.expected=expected,self.found=found,self.location=location,self.name="SyntaxError",self}__name(peg$SyntaxError,"peg$SyntaxError"),__name2(peg$SyntaxError,"peg$SyntaxError"),peg$subclass(peg$SyntaxError,Error);function peg$padEnd(str,targetLength,padString){return padString=padString||" ",str.length>targetLength?str:(targetLength-=str.length,padString+=padString.repeat(targetLength),str+padString.slice(0,targetLength))}__name(peg$padEnd,"peg$padEnd"),__name2(peg$padEnd,"peg$padEnd"),peg$SyntaxError.prototype.format=function(sources){var str="Error: "+this.message;if(this.location){var src=null,k;for(k=0;k `+loc+` `+filler+` | `+offset_s.line+" | "+line+` `+filler+" | "+peg$padEnd("",s.column-1," ")+peg$padEnd("",hatLen,"^")}else str+=` at `+loc}return str},peg$SyntaxError.buildMessage=function(expected,found){var DESCRIBE_EXPECTATION_FNS={literal:function(expectation){return'"'+literalEscape(expectation.text)+'"'},class:function(expectation){var escapedParts=expectation.parts.map(function(part){return Array.isArray(part)?classEscape(part[0])+"-"+classEscape(part[1]):classEscape(part)});return"["+(expectation.inverted?"^":"")+escapedParts.join("")+"]"},any:function(){return"any character"},end:function(){return"end of input"},other:function(expectation){return expectation.description}};function hex(ch){return ch.charCodeAt(0).toString(16).toUpperCase()}__name(hex,"hex"),__name2(hex,"hex");function literalEscape(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(ch){return"\\x0"+hex(ch)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(ch){return"\\x"+hex(ch)})}__name(literalEscape,"literalEscape"),__name2(literalEscape,"literalEscape");function classEscape(s){return s.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(ch){return"\\x0"+hex(ch)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(ch){return"\\x"+hex(ch)})}__name(classEscape,"classEscape"),__name2(classEscape,"classEscape");function describeExpectation(expectation){return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation)}__name(describeExpectation,"describeExpectation"),__name2(describeExpectation,"describeExpectation");function describeExpected(expected2){var descriptions=expected2.map(describeExpectation),i,j;if(descriptions.sort(),descriptions.length>0){for(i=1,j=1;i{const operator=elements[1],operands=[result,elements.find(e=>typeof e=="number"||e instanceof Object&&e.class)].map(e=>typeof e=="number"?createNumericTerm(e,{truncate:!0}):e);return{class:"ArithmeticExpression",formula:text(),operator,operands,evaluated:!1}},head)},"peg$f0"),peg$f1=__name2(function(head,tail){return tail.reduce((result,elements)=>{const operator=elements[1],operands=[result,elements.find(e=>typeof e=="number"||e instanceof Object&&e.class)].map(e=>typeof e=="number"?createNumericTerm(e):e);return{class:"ArithmeticExpression",formula:text(),operator,operands,evaluated:!1}},head)},"peg$f1"),peg$f2=__name2(function(fn,head,tail){const terms=head!==null?[head,...tail].map(t=>typeof t=="number"?t.toString():t.formula):[];return{class:"MathTerm",formula:text(),fn,terms,evaluated:!1}},"peg$f2"),peg$f3=__name2(function(number,faces,modifiers,flavor){const obj=number instanceof Object||faces instanceof Object?{class:"IntermediateDie",formula:text(),number:typeof number=="number"?createNumericTerm(number):number,faces:typeof faces=="number"?createNumericTerm(faces):faces,evaluated:!1}:{class:"DiceTerm",formula:text(),number:number??1,faces,evaluated:!1};return modifiers&&(obj.modifiers=modifiers),flavor&&(obj.options={flavor}),obj},"peg$f3"),peg$f4=__name2(function(expression,flavor){const obj={class:"Grouping",formula:text(),term:typeof expression=="number"?createNumericTerm(expression):expression,evaluated:!1};return flavor&&(obj.options={flavor}),obj},"peg$f4"),peg$f5=__name2(function(head,tail,modifiers,flavor){var _a;const headTerm=typeof head=="number"?createNumericTerm(head):head,tailTerms=tail.map(t=>typeof t=="number"?createNumericTerm(t):t),terms=[headTerm.formula,...tailTerms.map(t=>t.formula)],firstRoll={class:"DamageInstance",formula:headTerm.formula,terms:[headTerm],evaluated:!1};(_a=headTerm.options)!=null&&_a.flavor&&(firstRoll.options={flavor:headTerm.options.flavor});const rolls=[firstRoll,...tailTerms.map(term=>{var _a2;const obj2={class:"DamageInstance",formula:term.formula,terms:[term],evaluated:!1};return(_a2=term.options)!=null&&_a2.flavor&&(obj2.options={flavor:term.options.flavor}),obj2})],obj={class:"InstancePool",formula:text(),terms,rolls,evaluated:!1};return flavor&&(obj.options={flavor}),modifiers&&(obj.modifiers=modifiers),obj},"peg$f5"),peg$f6=__name2(function(string){return string},"peg$f6"),peg$f7=__name2(function(){const numified=Number(text());return input===text()?createNumericTerm(numified):numified},"peg$f7"),peg$f8=__name2(function(number,flavor){return createNumericTerm(number,{flavor})},"peg$f8"),peg$f9=__name2(function(){return Array.from(text().matchAll(/([A-z]+)([^A-z\s()+\-*\/]+)?/g)).map(m=>m[0])},"peg$f9"),peg$currPos=0,peg$savedPos=0,peg$posDetailsCache=[{line:1,column:1}],peg$maxFailPos=0,peg$maxFailExpected=[],peg$silentFails=0,peg$result;if("startRule"in options){if(!(options.startRule in peg$startRuleFunctions))throw new Error(`Can't start parsing from rule "`+options.startRule+'".');peg$startRuleFunction=peg$startRuleFunctions[options.startRule]}function text(){return input.substring(peg$savedPos,peg$currPos)}__name(text,"text"),__name2(text,"text");function peg$literalExpectation(text2,ignoreCase){return{type:"literal",text:text2,ignoreCase}}__name(peg$literalExpectation,"peg$literalExpectation"),__name2(peg$literalExpectation,"peg$literalExpectation");function peg$classExpectation(parts,inverted,ignoreCase){return{type:"class",parts,inverted,ignoreCase}}__name(peg$classExpectation,"peg$classExpectation"),__name2(peg$classExpectation,"peg$classExpectation");function peg$endExpectation(){return{type:"end"}}__name(peg$endExpectation,"peg$endExpectation"),__name2(peg$endExpectation,"peg$endExpectation");function peg$otherExpectation(description){return{type:"other",description}}__name(peg$otherExpectation,"peg$otherExpectation"),__name2(peg$otherExpectation,"peg$otherExpectation");function peg$computePosDetails(pos){var details=peg$posDetailsCache[pos],p;if(details)return details;for(p=pos-1;!peg$posDetailsCache[p];)p--;for(details=peg$posDetailsCache[p],details={line:details.line,column:details.column};ppeg$maxFailPos&&(peg$maxFailPos=peg$currPos,peg$maxFailExpected=[]),peg$maxFailExpected.push(expected))}__name(peg$fail,"peg$fail"),__name2(peg$fail,"peg$fail");function peg$buildStructuredError(expected,found,location){return new peg$SyntaxError(peg$SyntaxError.buildMessage(expected,found),expected,found,location)}__name(peg$buildStructuredError,"peg$buildStructuredError"),__name2(peg$buildStructuredError,"peg$buildStructuredError");function peg$parseExpression(){var s0,s1,s2,s3,s4,s5,s6,s7;if(s0=peg$currPos,s1=peg$parsePool(),s1===peg$FAILED&&(s1=peg$parseTerm()),s1!==peg$FAILED){for(s2=[],s3=peg$currPos,s4=peg$parse_(),input.charCodeAt(peg$currPos)===43?(s5=peg$c0,peg$currPos++):(s5=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e0)),s5===peg$FAILED&&(input.charCodeAt(peg$currPos)===45?(s5=peg$c1,peg$currPos++):(s5=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e1))),s5!==peg$FAILED?(s6=peg$parse_(),s7=peg$parsePool(),s7===peg$FAILED&&(s7=peg$parseTerm()),s7!==peg$FAILED?(s4=[s4,s5,s6,s7],s3=s4):(peg$currPos=s3,s3=peg$FAILED)):(peg$currPos=s3,s3=peg$FAILED);s3!==peg$FAILED;)s2.push(s3),s3=peg$currPos,s4=peg$parse_(),input.charCodeAt(peg$currPos)===43?(s5=peg$c0,peg$currPos++):(s5=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e0)),s5===peg$FAILED&&(input.charCodeAt(peg$currPos)===45?(s5=peg$c1,peg$currPos++):(s5=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e1))),s5!==peg$FAILED?(s6=peg$parse_(),s7=peg$parsePool(),s7===peg$FAILED&&(s7=peg$parseTerm()),s7!==peg$FAILED?(s4=[s4,s5,s6,s7],s3=s4):(peg$currPos=s3,s3=peg$FAILED)):(peg$currPos=s3,s3=peg$FAILED);peg$savedPos=s0,s0=peg$f0(s1,s2)}else peg$currPos=s0,s0=peg$FAILED;return s0}__name(peg$parseExpression,"peg$parseExpression"),__name2(peg$parseExpression,"peg$parseExpression");function peg$parseTerm(){var s0,s1,s2,s3,s4,s5,s6,s7;if(s0=peg$currPos,s1=peg$parseTermOperand(),s1!==peg$FAILED){for(s2=[],s3=peg$currPos,s4=peg$parse_(),input.charCodeAt(peg$currPos)===42?(s5=peg$c2,peg$currPos++):(s5=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e2)),s5===peg$FAILED&&(input.charCodeAt(peg$currPos)===47?(s5=peg$c3,peg$currPos++):(s5=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e3))),s5!==peg$FAILED?(s6=peg$parse_(),s7=peg$parseTermOperand(),s7!==peg$FAILED?(s4=[s4,s5,s6,s7],s3=s4):(peg$currPos=s3,s3=peg$FAILED)):(peg$currPos=s3,s3=peg$FAILED);s3!==peg$FAILED;)s2.push(s3),s3=peg$currPos,s4=peg$parse_(),input.charCodeAt(peg$currPos)===42?(s5=peg$c2,peg$currPos++):(s5=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e2)),s5===peg$FAILED&&(input.charCodeAt(peg$currPos)===47?(s5=peg$c3,peg$currPos++):(s5=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e3))),s5!==peg$FAILED?(s6=peg$parse_(),s7=peg$parseTermOperand(),s7!==peg$FAILED?(s4=[s4,s5,s6,s7],s3=s4):(peg$currPos=s3,s3=peg$FAILED)):(peg$currPos=s3,s3=peg$FAILED);peg$savedPos=s0,s0=peg$f1(s1,s2)}else peg$currPos=s0,s0=peg$FAILED;return s0}__name(peg$parseTerm,"peg$parseTerm"),__name2(peg$parseTerm,"peg$parseTerm");function peg$parseTermOperand(){var s0;return s0=peg$parseDiceTerm(),s0===peg$FAILED&&(s0=peg$parseMathTerm(),s0===peg$FAILED&&(s0=peg$parseGrouping(),s0===peg$FAILED&&(s0=peg$parseFlavoredNumber(),s0===peg$FAILED&&(s0=peg$parseNumber())))),s0}__name(peg$parseTermOperand,"peg$parseTermOperand"),__name2(peg$parseTermOperand,"peg$parseTermOperand");function peg$parseMathTerm(){var s0,s1,s2,s4,s6,s7,s8,s9,s11;if(s0=peg$currPos,s1=peg$parseIdentifier(),s1!==peg$FAILED)if(input.charCodeAt(peg$currPos)===40?(s2=peg$c4,peg$currPos++):(s2=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e4)),s2!==peg$FAILED){for(peg$parse_(),s4=peg$parseExpression(),s4===peg$FAILED&&(s4=null),peg$parse_(),s6=[],s7=peg$currPos,s8=peg$parse_(),input.charCodeAt(peg$currPos)===44?(s9=peg$c5,peg$currPos++):(s9=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e5)),s9!==peg$FAILED?(peg$parse_(),s11=peg$parseExpression(),s11!==peg$FAILED?s7=s11:(peg$currPos=s7,s7=peg$FAILED)):(peg$currPos=s7,s7=peg$FAILED);s7!==peg$FAILED;)s6.push(s7),s7=peg$currPos,s8=peg$parse_(),input.charCodeAt(peg$currPos)===44?(s9=peg$c5,peg$currPos++):(s9=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e5)),s9!==peg$FAILED?(peg$parse_(),s11=peg$parseExpression(),s11!==peg$FAILED?s7=s11:(peg$currPos=s7,s7=peg$FAILED)):(peg$currPos=s7,s7=peg$FAILED);s7=peg$parse_(),input.charCodeAt(peg$currPos)===41?(s8=peg$c6,peg$currPos++):(s8=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e6)),s8!==peg$FAILED?(peg$savedPos=s0,s0=peg$f2(s1,s4,s6)):(peg$currPos=s0,s0=peg$FAILED)}else peg$currPos=s0,s0=peg$FAILED;else peg$currPos=s0,s0=peg$FAILED;return s0}__name(peg$parseMathTerm,"peg$parseMathTerm"),__name2(peg$parseMathTerm,"peg$parseMathTerm");function peg$parseDiceTerm(){var s0,s1,s2,s3,s4,s5;return s0=peg$currPos,s1=peg$parseGrouping(),s1===peg$FAILED&&(s1=peg$parseMathTerm(),s1===peg$FAILED&&(s1=peg$parseNumber())),s1===peg$FAILED&&(s1=null),peg$r0.test(input.charAt(peg$currPos))?(s2=input.charAt(peg$currPos),peg$currPos++):(s2=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e7)),s2!==peg$FAILED?(s3=peg$parseGrouping(),s3===peg$FAILED&&(s3=peg$parseMathTerm(),s3===peg$FAILED&&(s3=peg$parseNumber(),s3===peg$FAILED&&(s3=peg$parseIdentifier()))),s3!==peg$FAILED?(s4=peg$parseModifiers(),s4===peg$FAILED&&(s4=null),s5=peg$parseFlavor(),s5===peg$FAILED&&(s5=null),peg$savedPos=s0,s0=peg$f3(s1,s3,s4,s5)):(peg$currPos=s0,s0=peg$FAILED)):(peg$currPos=s0,s0=peg$FAILED),s0}__name(peg$parseDiceTerm,"peg$parseDiceTerm"),__name2(peg$parseDiceTerm,"peg$parseDiceTerm");function peg$parseGrouping(){var s0,s1,s3,s5,s6;return s0=peg$currPos,input.charCodeAt(peg$currPos)===40?(s1=peg$c4,peg$currPos++):(s1=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e4)),s1!==peg$FAILED?(peg$parse_(),s3=peg$parseExpression(),s3!==peg$FAILED?(peg$parse_(),input.charCodeAt(peg$currPos)===41?(s5=peg$c6,peg$currPos++):(s5=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e6)),s5!==peg$FAILED?(s6=peg$parseFlavor(),s6===peg$FAILED&&(s6=null),peg$savedPos=s0,s0=peg$f4(s3,s6)):(peg$currPos=s0,s0=peg$FAILED)):(peg$currPos=s0,s0=peg$FAILED)):(peg$currPos=s0,s0=peg$FAILED),s0}__name(peg$parseGrouping,"peg$parseGrouping"),__name2(peg$parseGrouping,"peg$parseGrouping");function peg$parsePool(){var s0,s1,s3,s4,s5,s6,s7,s8;if(s0=peg$currPos,input.charCodeAt(peg$currPos)===123?(s1=peg$c7,peg$currPos++):(s1=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e8)),s1!==peg$FAILED)if(peg$parse_(),s3=peg$parseExpression(),s3!==peg$FAILED){for(s4=[],s5=peg$currPos,input.charCodeAt(peg$currPos)===44?(s6=peg$c5,peg$currPos++):(s6=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e5)),s6!==peg$FAILED?(s7=peg$parse_(),s8=peg$parseExpression(),s8!==peg$FAILED?s5=s8:(peg$currPos=s5,s5=peg$FAILED)):(peg$currPos=s5,s5=peg$FAILED);s5!==peg$FAILED;)s4.push(s5),s5=peg$currPos,input.charCodeAt(peg$currPos)===44?(s6=peg$c5,peg$currPos++):(s6=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e5)),s6!==peg$FAILED?(s7=peg$parse_(),s8=peg$parseExpression(),s8!==peg$FAILED?s5=s8:(peg$currPos=s5,s5=peg$FAILED)):(peg$currPos=s5,s5=peg$FAILED);input.charCodeAt(peg$currPos)===125?(s5=peg$c8,peg$currPos++):(s5=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e9)),s5!==peg$FAILED?(s6=peg$parseModifiers(),s6===peg$FAILED&&(s6=null),s7=peg$parseFlavor(),s7===peg$FAILED&&(s7=null),peg$savedPos=s0,s0=peg$f5(s3,s4,s6,s7)):(peg$currPos=s0,s0=peg$FAILED)}else peg$currPos=s0,s0=peg$FAILED;else peg$currPos=s0,s0=peg$FAILED;return s0}__name(peg$parsePool,"peg$parsePool"),__name2(peg$parsePool,"peg$parsePool");function peg$parseFlavor(){var s0,s1,s2,s3;return s0=peg$currPos,input.charCodeAt(peg$currPos)===91?(s1=peg$c9,peg$currPos++):(s1=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e10)),s1!==peg$FAILED?(s2=peg$currPos,s3=peg$parseFlavorString(),s3!==peg$FAILED?s2=input.substring(s2,peg$currPos):s2=s3,s2!==peg$FAILED?(input.charCodeAt(peg$currPos)===93?(s3=peg$c10,peg$currPos++):(s3=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e11)),s3!==peg$FAILED?(peg$savedPos=s0,s0=peg$f6(s2)):(peg$currPos=s0,s0=peg$FAILED)):(peg$currPos=s0,s0=peg$FAILED)):(peg$currPos=s0,s0=peg$FAILED),s0}__name(peg$parseFlavor,"peg$parseFlavor"),__name2(peg$parseFlavor,"peg$parseFlavor");function peg$parseNumber(){var s0,s3,s4,s5,s6,s7;if(s0=peg$currPos,peg$parse_(),peg$r1.test(input.charAt(peg$currPos))?(input.charAt(peg$currPos),peg$currPos++):peg$silentFails===0&&peg$fail(peg$e12),s3=[],peg$r2.test(input.charAt(peg$currPos))?(s4=input.charAt(peg$currPos),peg$currPos++):(s4=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e13)),s4!==peg$FAILED)for(;s4!==peg$FAILED;)s3.push(s4),peg$r2.test(input.charAt(peg$currPos))?(s4=input.charAt(peg$currPos),peg$currPos++):(s4=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e13));else s3=peg$FAILED;if(s3!==peg$FAILED){if(s4=peg$currPos,input.charCodeAt(peg$currPos)===46?(s5=peg$c11,peg$currPos++):(s5=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e14)),s5!==peg$FAILED){if(s6=[],peg$r2.test(input.charAt(peg$currPos))?(s7=input.charAt(peg$currPos),peg$currPos++):(s7=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e13)),s7!==peg$FAILED)for(;s7!==peg$FAILED;)s6.push(s7),peg$r2.test(input.charAt(peg$currPos))?(s7=input.charAt(peg$currPos),peg$currPos++):(s7=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e13));else s6=peg$FAILED;s6!==peg$FAILED?(s5=[s5,s6],s4=s5):(peg$currPos=s4,s4=peg$FAILED)}else peg$currPos=s4,s4=peg$FAILED;s4===peg$FAILED&&(s4=null),peg$savedPos=s0,s0=peg$f7()}else peg$currPos=s0,s0=peg$FAILED;return s0}__name(peg$parseNumber,"peg$parseNumber"),__name2(peg$parseNumber,"peg$parseNumber");function peg$parseFlavoredNumber(){var s0,s1,s2;return s0=peg$currPos,s1=peg$parseNumber(),s1!==peg$FAILED?(s2=peg$parseFlavor(),s2!==peg$FAILED?(peg$savedPos=s0,s0=peg$f8(s1,s2)):(peg$currPos=s0,s0=peg$FAILED)):(peg$currPos=s0,s0=peg$FAILED),s0}__name(peg$parseFlavoredNumber,"peg$parseFlavoredNumber"),__name2(peg$parseFlavoredNumber,"peg$parseFlavoredNumber");function peg$parseIdentifier(){var s0,s1,s2,s3,s4;if(s0=peg$currPos,s1=peg$currPos,peg$r3.test(input.charAt(peg$currPos))?(s2=input.charAt(peg$currPos),peg$currPos++):(s2=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e15)),s2!==peg$FAILED){for(s3=[],peg$r4.test(input.charAt(peg$currPos))?(s4=input.charAt(peg$currPos),peg$currPos++):(s4=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e16));s4!==peg$FAILED;)s3.push(s4),peg$r4.test(input.charAt(peg$currPos))?(s4=input.charAt(peg$currPos),peg$currPos++):(s4=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e16));s2=[s2,s3],s1=s2}else peg$currPos=s1,s1=peg$FAILED;return s1!==peg$FAILED?s0=input.substring(s0,peg$currPos):s0=s1,s0}__name(peg$parseIdentifier,"peg$parseIdentifier"),__name2(peg$parseIdentifier,"peg$parseIdentifier");function peg$parseModifiers(){var s0,s1,s2;if(s0=peg$currPos,s1=[],peg$r5.test(input.charAt(peg$currPos))?(s2=input.charAt(peg$currPos),peg$currPos++):(s2=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e17)),s2!==peg$FAILED)for(;s2!==peg$FAILED;)s1.push(s2),peg$r5.test(input.charAt(peg$currPos))?(s2=input.charAt(peg$currPos),peg$currPos++):(s2=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e17));else s1=peg$FAILED;return s1!==peg$FAILED&&(peg$savedPos=s0,s1=peg$f9()),s0=s1,s0}__name(peg$parseModifiers,"peg$parseModifiers"),__name2(peg$parseModifiers,"peg$parseModifiers");function peg$parseFlavorString(){var s0,s1;if(peg$silentFails++,s0=[],peg$r6.test(input.charAt(peg$currPos))?(s1=input.charAt(peg$currPos),peg$currPos++):(s1=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e19)),s1!==peg$FAILED)for(;s1!==peg$FAILED;)s0.push(s1),peg$r6.test(input.charAt(peg$currPos))?(s1=input.charAt(peg$currPos),peg$currPos++):(s1=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e19));else s0=peg$FAILED;return peg$silentFails--,s0===peg$FAILED&&(s1=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e18)),s0}__name(peg$parseFlavorString,"peg$parseFlavorString"),__name2(peg$parseFlavorString,"peg$parseFlavorString");function peg$parse_(){var s0,s1;for(peg$silentFails++,s0=[],peg$r7.test(input.charAt(peg$currPos))?(s1=input.charAt(peg$currPos),peg$currPos++):(s1=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e21));s1!==peg$FAILED;)s0.push(s1),peg$r7.test(input.charAt(peg$currPos))?(s1=input.charAt(peg$currPos),peg$currPos++):(s1=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e21));return peg$silentFails--,s1=peg$FAILED,peg$silentFails===0&&peg$fail(peg$e20),s0}if(__name(peg$parse_,"peg$parse_"),__name2(peg$parse_,"peg$parse_"),peg$result=peg$startRuleFunction(),peg$result!==peg$FAILED&&peg$currPos===input.length)return peg$result;throw peg$result!==peg$FAILED&&peg$currPos{try{return this.parser.parse(replaced)}catch{return console.error(`Failed to parse damage formula "${formula}"`),null}})();if(poolData){if(!["PoolTerm","InstancePool"].includes(poolData.class??""))throw ErrorPF2e("A damage roll must consist of a single InstancePool")}else return[];return this.classifyDice(poolData),[InstancePool.fromData(poolData)]}static validate(formula){formula=formula.trim();const wrapped=this.replaceFormulaData(formula.startsWith("{")?formula:`{${formula}}`,{});try{const result=this.parser.parse(wrapped);return isObject(result)&&"class"in result&&["PoolTerm","InstancePool"].includes(String(result.class))}catch{return!1}}static classifyDice(data){var _a;const isDiceTerm=__name2(v=>isObject(v)&&v.class==="DiceTerm","isDiceTerm"),deepFindDice=__name2(value=>{const accumulated=[];if(isDiceTerm(value))accumulated.push(value);else if(value instanceof Object){const objects=Object.values(value).filter(v=>v instanceof Object);accumulated.push(...objects.flatMap(o=>deepFindDice(o)))}return accumulated},"deepFindDice"),diceTerms=deepFindDice(data);for(const term of diceTerms)if(typeof term.faces=="number"||term.faces instanceof Object)term.class="Die";else if(typeof term.faces=="string"){const termClassName=(_a=CONFIG.Dice.terms[term.faces])==null?void 0:_a.name;if(!termClassName)throw ErrorPF2e(`No matching DiceTerm class for "${term.faces}"`);term.class=termClassName}}get formula(){const{instances}=this,firstInstance=instances.at(0);if(firstInstance){if(instances.length===1&&firstInstance.head instanceof Grouping){const instanceFormula=firstInstance.formula;return instanceFormula.startsWith("(")?instanceFormula.slice(1).replace(/\)([^)]*)$/i,"$1"):instanceFormula}}else return super.formula;return instances.map(i=>i.formula).join(" + ")}get instances(){const pool=this.terms[0];return pool instanceof PoolTerm?pool.rolls.filter(r=>r instanceof DamageInstance):[]}get materials(){return[...new Set(this.instances.flatMap(i=>i.materials))]}get dice(){const{instances}=this;return instances.length>0?instances.flatMap(i=>i.dice):super.dice}get minimumValue(){return this.instances.reduce((sum2,i)=>sum2+i.minimumValue,0)}get expectedValue(){return this.instances.reduce((sum2,i)=>sum2+i.expectedValue,0)}get maximumValue(){return this.instances.reduce((sum2,i)=>sum2+i.maximumValue,0)}static fromData(data){for(const term of data.terms)this.classifyDice(term);return super.fromData(data)}_evaluateTotal(){const total=super._evaluateTotal();return this.instances.some(i=>!i.persistent)&&total<=0?(this.options.increasedFrom=total,Promise.resolve().then(()=>{this.alter(1,1-total)}),1):total}async getTooltip(){const instances=this.instances.filter(i=>i.dice.length>0&&(!i.persistent||i.options.evaluatePersistent)).map(i=>({type:i.type,typeLabel:i.typeLabel,iconClass:i.iconClass,dice:i.dice.map(d=>({...d.getTooltipData()}))}));return renderTemplate(this.constructor.TOOLTIP_TEMPLATE,{instances})}async render({flavor,template=this.constructor.CHAT_TEMPLATE,isPrivate=!1}={}){const{instances}=this;if(!instances.at(-1))return super.render({flavor,template,isPrivate});this._evaluated||await this.evaluate({async:!0});const chatData={formula:isPrivate?"???":(await Promise.all(instances.map(i=>i.render()))).join(" + "),user:game.user.id,tooltip:isPrivate||this.dice.length===0?"":await this.getTooltip(),instances:isPrivate?[]:instances,total:isPrivate?"?":Math.floor(this.total*100/100),increasedFrom:this.options.increasedFrom,splashOnly:!!this.options.splashOnly,allPersistent:this.instances.every(i=>i.persistent&&!i.options.evaluatePersistent),showTripleDamage:game.settings.get("pf2e","critFumbleButtons")};return renderTemplate(template,chatData)}alter(multiplier,addend,{multiplyNumeric=!0}={}){const{instances}=this;if(!this._evaluated||instances.length===0)return super.alter(multiplier,addend,{multiplyNumeric});if(multiplier===1&&addend===0)return this;const instanceClones=multiplier===1?this.instances.map(i=>DamageInstance.fromData(i.toJSON())):instances.map(instance=>{const{head}=instance,rightOperand=head instanceof ArithmeticExpression&&["+","-"].includes(head.operator)?{class:"Grouping",term:head.toJSON()}:head.toJSON(),multiplierTerm={class:"NumericTerm",number:multiplier},expression=ArithmeticExpression.fromData({operator:"*",operands:[deepClone(multiplierTerm),rightOperand]});return[2,3].includes(multiplier)&&(expression.options.crit=multiplier),DamageInstance.fromTerms([expression],deepClone(instance.options))});if(addend!==0){const firstInstance=instanceClones[0],term=firstInstance.head.toJSON(),options=term.options??{};delete term.options;const termClone={class:"Grouping",term,options},addendTerm={class:"NumericTerm",number:Math.abs(addend)},expression=ArithmeticExpression.fromData({operator:addend>0?"+":"-",operands:[termClone,addendTerm],evaluated:!0});instanceClones[0]=DamageInstance.fromTerms([expression],deepClone(firstInstance.options))}return _DamageRoll.fromTerms([InstancePool.fromRolls(instanceClones)])}},"_DamageRoll");let DamageRoll=_DamageRoll;__name2(DamageRoll,"DamageRoll"),__publicField(DamageRoll,"CHAT_TEMPLATE","systems/pf2e/templates/dice/damage-roll.hbs"),__publicField(DamageRoll,"TOOLTIP_TEMPLATE","systems/pf2e/templates/dice/damage-tooltip.hbs");const _DamageInstance=__name(class extends AbstractDamageRoll{constructor(formula,data={},options={}){var _a;super(formula.trim(),data,options),__privateAdd(this,_renderFormula),__publicField(this,"type"),__publicField(this,"persistent"),__publicField(this,"materials");const flavorIdentifiers=((_a=options.flavor)==null?void 0:_a.replace(/[^a-z,_-]/g,"").split(","))??[];this.type=flavorIdentifiers.find(t=>objectHasKey(CONFIG.PF2E.damageTypes,t))??"untyped",this.persistent=flavorIdentifiers.includes("persistent")||flavorIdentifiers.includes("bleed"),this.materials=flavorIdentifiers.filter(i=>objectHasKey(CONFIG.PF2E.materialDamageEffects,i))}static parse(formula,data){const replaced=this.replaceFormulaData(formula,data,{missing:"0"}),syntaxTree2=(()=>{try{return this.parser.parse(replaced)}catch{return console.error(`Failed to parse damage formula "${formula}"`),null}})();return syntaxTree2?(DamageRoll.classifyDice(syntaxTree2),[RollTerm.fromData(syntaxTree2)]):[]}static fromData(data){for(const term of data.terms)DamageRoll.classifyDice(term);return super.fromData(data)}static getValue(term,type2="expected"){if(term instanceof NumericTerm)return term.number;switch(type2){case"minimum":if(term instanceof Die)return term.number;if(term instanceof ArithmeticExpression||term instanceof Grouping||term instanceof IntermediateDie)return term.minimumValue;break;case"maximum":if(term instanceof Die)return term.number*term.faces;if(term instanceof ArithmeticExpression||term instanceof Grouping||term instanceof IntermediateDie)return term.maximumValue;break;default:{if(term instanceof Die)return term.number*((term.faces+1)/2);if(term instanceof ArithmeticExpression||term instanceof Grouping||term instanceof IntermediateDie)return term.expectedValue}}return 0}get formula(){const typeFlavor=game.i18n.localize(CONFIG.PF2E.damageRollFlavors[this.type]??this.type),damageType=this.persistent&&this.type!=="bleed"?game.i18n.format("PF2E.Damage.RollFlavor.persistent",{damageType:typeFlavor}):this.type!=="untyped"?typeFlavor:"";return[this.head.expression,damageType].join(" ").trim()}get total(){const maybeNumber=this.persistent&&!this.options.evaluatePersistent?0:super.total;return typeof maybeNumber=="number"?Math.floor(maybeNumber):maybeNumber}get minimumValue(){return _DamageInstance.getValue(this.head,"minimum")}get expectedValue(){return _DamageInstance.getValue(this.head)}get maximumValue(){return _DamageInstance.getValue(this.head,"maximum")}get formalDescription(){const typeCategory=DamageCategorization.fromDamageType(this.type);return new Set(["damage",`damage:type:${this.type}`,typeCategory?`damage:category:${typeCategory}`:[],this.persistent?"damage:category:persistent":[],this.materials.map(m=>`damage:material:${m}`)].flat())}get iconClass(){return DAMAGE_TYPE_ICONS[this.type]}_evaluateTotal(){return this.persistent&&!this.options.evaluatePersistent?0:super._evaluateTotal()}async render(){const span=document.createElement("span");if(span.classList.add("instance",this.type),span.title=this.typeLabel,span.append(__privateMethod(this,_renderFormula,renderFormula_fn).call(this)),this.persistent&&this.type!=="bleed"){const icon=fontAwesomeIcon("hourglass",{style:"duotone"});icon.classList.add("icon"),span.append(" ",icon)}const{iconClass}=this;if(iconClass){(!this.persistent||this.type==="bleed")&&span.append(" ");const icon=fontAwesomeIcon(iconClass);icon.classList.add("icon"),span.append(icon)}return span.outerHTML}get dice(){return this._dice.concat(this.terms.reduce((dice,t)=>t instanceof DiceTerm?[...dice,t]:t instanceof Grouping||t instanceof ArithmeticExpression||t instanceof IntermediateDie?[...dice,...t.dice]:[],this._dice).flat())}get head(){return this.terms[0]}get category(){return DamageCategorization.fromDamageType(this.type)}get typeLabel(){const damageType=game.i18n.localize(CONFIG.PF2E.damageTypes[this.type]);return this.persistent&&this.type!=="bleed"?game.i18n.format("PF2E.Damage.PersistentTooltip",{damageType}):damageType}get critImmuneTotal(){if(!this._evaluated)return;const{head}=this,undoubledTotal=head instanceof ArithmeticExpression||head instanceof Grouping?head.critImmuneTotal:this.total;if(this.options.critRule==="double-damage")return undoubledTotal;{const secondHalf=this.dice.filter(d=>/\bdoubled\b/.test(d.flavor)).flatMap(d=>d.results.slice(Math.ceil(d.results.length/2)));return undoubledTotal-secondHalf.reduce((sum2,r)=>sum2+r.result,0)}}componentTotal(component){if(!this._evaluated)throw ErrorPF2e("Component totals may only be accessed from an evaluated damage instance");return deepFindTerms(this.head,{flavor:component}).reduce((total,t)=>total+(Number(t.total)||0)*Number(t.options.crit||1),0)}async _evaluate(params){if(await super._evaluate(params),this.persistent&&!this.options.evaluatePersistent){const results=this.dice.flatMap(d=>d.results);for(const result of results)result.hidden=!0}return this}},"_DamageInstance");let DamageInstance=_DamageInstance;__name2(DamageInstance,"DamageInstance"),_renderFormula=new WeakSet,renderFormula_fn=__name2(function(){const head=this.head instanceof Grouping?this.head.term:this.head;return head instanceof ArithmeticExpression?head.render():["precision","splash"].includes(head.flavor)?renderComponentDamage(head):head.expression},"#renderFormula");const DropCanvasData={listen:()=>{Hooks.on("dropCanvasData",(_canvas,data)=>{const dropTarget=[...canvas.tokens.placeables].sort((a,b)=>b.document.sort-a.document.sort).find(token=>{var _a,_b;const maximumX=token.x+(((_a=token.hitArea)==null?void 0:_a.right)??0),maximumY=token.y+(((_b=token.hitArea)==null?void 0:_b.bottom)??0);return data.x>=token.x&&data.y>=token.y&&data.x<=maximumX&&data.y<=maximumY}),actor=dropTarget?.actor;if(actor&&data.type==="Item")return actor.sheet.emulateItemDrop(data),!1;if(actor&&data.type==="PersistentDamage"&&"formula"in data){const instances=new DamageRoll(String(data.formula)).instances.filter(i=>i.persistent),baseConditionSource=game.pf2e.ConditionManager.getCondition("persistent-damage").toObject(),conditions=instances.map(i=>mergeObject(baseConditionSource,{system:{persistent:{formula:i.head.expression,damageType:i.type,dc:15}}}));return actor.createEmbeddedDocuments("Item",conditions),!1}return!0})}},nouislider_min="",dayInSeconds=Duration.fromObject({hours:24}).as("seconds");function darknessLevelAtTime(time){const secondsElapsed=time.diff(time.startOf("day")).as("seconds"),radians=2*Math.PI*(secondsElapsed/dayInSeconds),lightnessLevel=-1*Math.cos(radians),rad18degrees=Math.toRadians(18);return 1-(lightnessLevel>0?1:lightnessLevel<-rad18degrees?0:Math.sin((lightnessLevel+rad18degrees)/rad18degrees*Math.PI/2))}__name(darknessLevelAtTime,"darknessLevelAtTime"),__name2(darknessLevelAtTime,"darknessLevelAtTime");function intervalToTransition(interval,compactInterval){const currentDarkness=canvas.darknessLevel,targetDarkness=darknessLevelAtTime(interval.end),darknessDiff=Math.abs((currentDarkness??targetDarkness)-targetDarkness),proportionOfDay=compactInterval.length("seconds")/dayInSeconds,darkTimeMean=(darknessDiff*.5+proportionOfDay)/2;return{target:targetDarkness,duration:darkTimeMean*6e3,interval}}__name(intervalToTransition,"intervalToTransition"),__name2(intervalToTransition,"intervalToTransition");async function runAnimation(transition){if(!canvas.lighting||canvas.darknessLevel===transition.target)return;const duration=Math.min(Math.trunc(100*transition.duration)/100,6e3);await canvas.effects.animateDarkness(transition.target,{duration}),game.user.isGM&&await canvas.scene.update({darkness:transition.target})}__name(runAnimation,"runAnimation"),__name2(runAnimation,"runAnimation");async function animateDarkness(timeDiff){if(!this.syncDarkness)return;const newTime=this.worldTime,oldTime=newTime.minus({seconds:timeDiff}),fullInterval=Interval.fromDateTimes(oldTime,newTime);if(!fullInterval.isValid){await runAnimation({target:darknessLevelAtTime(newTime),duration:100,interval:fullInterval});return}const compactInterval=(()=>{if(fullInterval.length("hours")>24){const adjustedOldTime=newTime.minus({hours:24});return Interval.fromDateTimes(adjustedOldTime,newTime)}return fullInterval})(),transitionTimes=[4.75,18].map(hour=>compactInterval.start.set({hour,minute:0,second:0})).concat([4.75,18].map(hour=>compactInterval.end.set({hour,minute:0,second:0}))).filter(dateTime=>compactInterval.contains(dateTime)).concat([compactInterval.start,compactInterval.end]).sort((dtA,dtB)=>dtAdtB?1:0),transitions=transitionTimes.reduce((pairs,dateTime)=>{const index=transitionTimes.indexOf(dateTime);if(index===0)return[];const before=transitionTimes[index-1];return[...pairs,[before,dateTime]]},[]).map(pair=>Interval.fromDateTimes(pair[0],pair[1])).filter(interval=>interval.length()>0).map(interval=>intervalToTransition(interval,compactInterval));for(const transition of transitions)await runAnimation(transition)}__name(animateDarkness,"animateDarkness"),__name2(animateDarkness,"animateDarkness");var TimeChangeMode=(TimeChangeMode2=>(TimeChangeMode2[TimeChangeMode2.ADVANCE=0]="ADVANCE",TimeChangeMode2[TimeChangeMode2.RETRACT=1]="RETRACT",TimeChangeMode2))(TimeChangeMode||{});const _TimeOfDay=__name(class{constructor(hour,minute,second){this.hour=hour,this.minute=minute,this.second=second}diffSeconds(worldTime,mode){const targetTime=worldTime.set(this),targetDayDifference=_TimeOfDay.diffDays(worldTime,targetTime,mode);return worldTime.plus({day:targetDayDifference}).set(this).diff(worldTime,"seconds").seconds}static diffDays(currentTime,targetTime,mode){return currentTime>=targetTime&&mode===0?1:currentTime<=targetTime&&mode===1?-1:0}},"_TimeOfDay");let TimeOfDay=_TimeOfDay;__name2(TimeOfDay,"TimeOfDay"),__publicField(TimeOfDay,"DAWN",new _TimeOfDay(4,58,54)),__publicField(TimeOfDay,"NOON",new _TimeOfDay(12,0,0)),__publicField(TimeOfDay,"DUSK",new _TimeOfDay(18,34,6)),__publicField(TimeOfDay,"MIDNIGHT",new _TimeOfDay(0,0,0));class WorldClock extends Application{constructor(){var _a;super(),__publicField(this,"ctrlKeyDown",!1),__publicField(this,"animateDarkness",animateDarkness);const settingValue=game.settings.get("pf2e","worldClock.worldCreatedOn"),defaultValue=(_a=game.settings.settings.get("pf2e.worldClock.worldCreatedOn"))==null?void 0:_a.default;typeof settingValue=="string"&&settingValue===defaultValue?game.settings.set("pf2e","worldClock.worldCreatedOn",settingValue):DateTime.fromISO(settingValue).isValid||game.settings.set("pf2e","worldClock.worldCreatedOn",defaultValue)}get dateTheme(){return game.settings.get("pf2e","worldClock.dateTheme")}get timeConvention(){const setting=game.settings.get("pf2e","worldClock.timeConvention");if(setting!==24&&setting!==12)throw Error("PF2e System | Unrecognized time convention");return setting}get syncDarkness(){var _a;const sceneSetting=((_a=canvas.scene)==null?void 0:_a.flags.pf2e.syncDarkness)??"default";return{enabled:!0,disabled:!1,default:game.settings.get("pf2e","worldClock.syncDarkness")}[sceneSetting]}get worldCreatedOn(){const value=game.settings.get("pf2e","worldClock.worldCreatedOn");return DateTime.fromISO(value).toUTC()}get worldTime(){return this.worldCreatedOn.plus({seconds:game.time.worldTime})}static get defaultOptions(){return mergeObject(super.defaultOptions,{id:"world-clock",width:400,template:"systems/pf2e/templates/system/world-clock.hbs",title:"PF2E.WorldClock.Title"})}get era(){switch(this.dateTheme){case"AR":return game.i18n.localize(CONFIG.PF2E.worldClock.AR.Era);case"AD":return this.worldTime.toFormat("G");default:return""}}get year(){const yearOffset=(()=>{switch(this.dateTheme){case"AR":return CONFIG.PF2E.worldClock.AR.yearOffset;case"AD":return CONFIG.PF2E.worldClock.AD.yearOffset;default:return 0}})();return this.worldTime.year+yearOffset}get month(){switch(this.dateTheme){case"AR":{const months=CONFIG.PF2E.worldClock.AR.Months,month=this.worldTime.setLocale("en-US").monthLong;return game.i18n.localize(months[month])}default:return this.worldTime.monthLong}}get weekday(){switch(this.dateTheme){case"AR":{const weekdays=CONFIG.PF2E.worldClock.AR.Weekdays,weekday=this.worldTime.setLocale("en-US").weekdayLong;return game.i18n.localize(weekdays[weekday])}default:return this.worldTime.weekdayLong}}getData(options){const date=this.dateTheme==="CE"?this.worldTime.toLocaleString(DateTime.DATE_HUGE):game.i18n.format(CONFIG.PF2E.worldClock.Date,{era:this.era,year:this.year,month:this.month,day:ordinal(this.worldTime.day),weekday:this.weekday}),time=this.timeConvention===24?this.worldTime.toFormat("HH:mm:ss"):this.worldTime.toLocaleString(DateTime.TIME_WITH_SECONDS),sign=this.ctrlKeyDown?"-":"+";return{date,time,options,user:game.user,sign}}_getHeaderButtons(){return(game.user.isGM?[{label:"PF2E.SETTINGS.Settings",class:"configure-settings",icon:"fas fa-cog",onclick:()=>{const menu=game.settings.menus.get("pf2e.worldClock");if(!menu)throw ErrorPF2e("PF2e System | World Clock Settings application not found");new menu.type().render(!0)}}]:[]).concat(...super._getHeaderButtons())}static calculateIncrement(wordTime,interval,intervalMode){const mode=intervalMode==="+"?TimeChangeMode.ADVANCE:TimeChangeMode.RETRACT;switch(interval){case"dawn":return TimeOfDay.DAWN.diffSeconds(wordTime,mode);case"noon":return TimeOfDay.NOON.diffSeconds(wordTime,mode);case"dusk":return TimeOfDay.DUSK.diffSeconds(wordTime,mode);case"midnight":return TimeOfDay.MIDNIGHT.diffSeconds(wordTime,mode);default:{const sign=mode===TimeChangeMode.ADVANCE?1:-1;return Number(interval)*sign}}}activateListeners($html){super.activateListeners($html),$html.find("button[data-advance-time]").on("click",event=>{const $button=$(event.currentTarget),advanceTime=$button.data("advanceTime")??"0",advanceMode=$button.data("advanceMode")??"+",increment=WorldClock.calculateIncrement(this.worldTime,advanceTime,advanceMode);increment!==0&&game.time.advance(increment)}),$html.find("button[name=advance], button[name=retract]").on("click",event=>{const value=$html.find('input[type=number][name="diff-value"]').val(),unit=$html.find('select[name="diff-unit"]').val(),increment=($(event.currentTarget).attr("name")==="advance"?1:-1)*Number(value)*Number(unit);game.time.advance(increment)});for(const eventName of["keydown.pf2e.world-clock","keyup.pf2e.world-clock"])$(document).off(eventName),$(document).on(eventName,event=>{var _a;const{originalEvent}=event;if(!(originalEvent instanceof KeyboardEvent))return;const ctrlKeys=KeyboardManager.CONTROL_KEY_STRING==="\u2318"?["Control","Meta"]:["Control"];if(originalEvent.repeat||!ctrlKeys.includes(originalEvent.key)||!(event.ctrlKey||this.ctrlKeyDown))return;const retractTime=this.ctrlKeyDown=event.type==="keydown",{Advance,Retract,TimeOfDay:TimeOfDay2}=CONFIG.PF2E.worldClock.Button,advanceButtons=Array.from(((_a=$html.get(0))==null?void 0:_a.querySelectorAll("button[data-advance-time]"))??[]);for(const button of advanceButtons){const{advanceMode,advanceTime}=button.dataset,nextMode=advanceMode==="+"?"-":"+";button.dataset.advanceMode=nextMode;const sign=button.querySelector(".sign");if(sign&&(sign.innerHTML=nextMode),tupleHasValue(["dawn","noon","dusk","midnight"],advanceTime)){const timeOfDayKeys=nextMode==="+"?TimeOfDay2.Advance:TimeOfDay2.Retract;button.title=timeOfDayKeys[advanceTime.titleCase()]}}$html.find("button[name=advance], button[name=retract]").attr("name",retractTime?"retract":"advance").text(game.i18n.localize(retractTime?Retract:Advance))})}async close(options){$(document).off("keydown.pf2e.world-clock").off("keyup.pf2e.world-clock"),await super.close(options)}static createSyncedMessage(){const managedBy=document.createElement("span");managedBy.classList.add("managed"),managedBy.innerHTML=" ".concat(game.i18n.localize("PF2E.SETTINGS.WorldClock.SyncDarknessScene.ManagedBy"));const anchor=document.createElement("a"),wtLink=managedBy.querySelector("wt");return anchor.innerText=wtLink?.innerHTML??"",anchor.setAttribute("href",""),anchor.addEventListener("click",event=>{event.preventDefault(),event.stopPropagation();const menu=game.settings.menus.get("pf2e.worldClock");if(!menu)throw ErrorPF2e("World Clock Settings application not found");new menu.type().render(!0)}),wtLink?.replaceWith(anchor),managedBy}}__name(WorldClock,"WorldClock"),__name2(WorldClock,"WorldClock");const _SceneDarknessAdjuster=__name(class extends Application{constructor(){super(...arguments),__privateAdd(this,_slider,void 0),__privateAdd(this,_noRefreshHook,!1)}static get defaultOptions(){return{...super.defaultOptions,id:"darkness-adjuster",title:"CONTROLS.AdjustSceneDarkness",template:"systems/pf2e/templates/system/scene-darkness-adjuster.hbs",width:400,height:45,minimizable:!1}}async getData(options={}){var _a;return{...await super.getData(options),darknessSyncedToTime:!!((_a=game.scenes.viewed)!=null&&_a.darknessSyncedToTime)}}async render(force=!1,options={}){var _a;if(!game.scenes.viewed)return this;const controls=ui.controls.element[0],bounds=(_a=controls?.querySelector("li[data-tool=darkness-adjuster]"))==null?void 0:_a.getBoundingClientRect();return bounds?(options.left=bounds.right+6,options.top=bounds.top-3,this.rendered?super.render(force,options):(await super.render(force,options),await $("#darkness-adjuster").hide(0).fadeIn().promise(),this)):this}async close(options){return this.rendered?(await $("#darkness-adjuster").fadeOut().promise(),super.close(options)):super.close(options)}activateListeners($html){var _a;if(!game.scenes.viewed)return;const slider=$html[0].querySelector(".slider");if(__privateSet(this,_slider,noUiSlider.create(slider,{range:{min:0,max:1},start:[.25,game.scenes.viewed.darkness,.75],connect:[!0,!1,!1,!0],behaviour:"snap-unconstrained-snap",pips:{mode:nouisliderExports.PipsMode.Range,density:5},step:.05})),(_a=game.scenes.viewed)!=null&&_a.darknessSyncedToTime){const synchronized=document.createElement("div");synchronized.className="message";const message=WorldClock.createSyncedMessage();synchronized.append(message),slider.append(synchronized)}slider.querySelectorAll(".noUi-origin").forEach((thumb,index)=>{var _a2;index!==1&&$(thumb).attr({disabled:"disabled"}),(_a2=game.scenes.viewed)!=null&&_a2.darknessSyncedToTime&&thumb.setAttribute("disabled","true")}),__privateGet(this,_slider).on("slide",(values,thumbNumber)=>{thumbNumber===1&&canvas.scene&&(__privateSet(this,_noRefreshHook,!0),canvas.colorManager.initialize({darknessLevel:Number(values[1])}),canvas.app.ticker.add(()=>{__privateSet(this,_noRefreshHook,!1)}))}),__privateGet(this,_slider).on("change",async(values,thumbNumber)=>{if(canvas.scene&&thumbNumber===1){const newValue=Number(values[1]);await canvas.scene.update({darkness:newValue},{animateDarkness:Math.round(5e3*Math.abs(canvas.scene.darkness-newValue))})}}),slider.querySelectorAll(".noUi-handle").forEach((handle,index)=>{const decoration={0:["threshold_bright-light",fontAwesomeIcon("sun")],1:["darkness-level",null],2:["threshold_darkness",fontAwesomeIcon("moon",{fixedWidth:!0})]},$handle=$(handle),[cssClass,icon]=decoration[index];icon&&$handle.append(icon),$handle.addClass(cssClass)}),slider.querySelectorAll(".noUi-connect").forEach((connect,index)=>{const classes={0:"range_bright-light",1:"range_darkness"};connect.classList.add(classes[index])})}onLightingRefresh(darkness){var _a;if(!this.rendered||__privateGet(this,_noRefreshHook))return;const sliderValues=(_a=__privateGet(this,_slider))==null?void 0:_a.get();if(__privateGet(this,_slider)&&Array.isArray(sliderValues)){const currentValue=sliderValues[1],stepValue=Math.round(darkness*20)/20;stepValue!==currentValue&&(sliderValues[1]=stepValue,__privateGet(this,_slider).set(sliderValues))}}},"_SceneDarknessAdjuster");let SceneDarknessAdjuster=_SceneDarknessAdjuster;__name2(SceneDarknessAdjuster,"SceneDarknessAdjuster"),_slider=new WeakMap,_noRefreshHook=new WeakMap,__publicField(SceneDarknessAdjuster,"instance",new _SceneDarknessAdjuster);const GetSceneControlButtons={listen:()=>{Hooks.on("getSceneControlButtons",controls=>{var _a;const tokenTools=(_a=controls.find(c=>c.name==="token"))==null?void 0:_a.tools;tokenTools?.push({name:"worldclock",title:"CONTROLS.WorldClock",icon:"fas fa-clock",button:!0,visible:game.settings.get("pf2e","worldClock.showClockButton")&&(game.user.isGM||game.settings.get("pf2e","worldClock.playersCanView")),onClick:()=>{game.pf2e.worldClock.rendered?game.pf2e.worldClock.close({force:!0}):game.pf2e.worldClock.render(!0)}});const lightingControls=controls.find(c=>c.name==="lighting"),lightingTools=lightingControls?.tools,dayTool=lightingTools?.find(tool=>tool.name==="day");if(!(lightingControls&&lightingTools&&dayTool))return;lightingControls.visible&&SceneDarknessAdjuster.instance.rendered&&SceneDarknessAdjuster.instance.close({force:!0});const adjusterTool={name:"darkness-adjuster",title:"CONTROLS.AdjustSceneDarkness",icon:"fa-solid fa-adjust",visible:game.user.isGM&&game.settings.get("pf2e","automation.rulesBasedVision"),toggle:!0,active:!1,onClick:()=>{const adjuster=SceneDarknessAdjuster.instance;adjuster.rendered?adjuster.close({force:!0}):adjuster.render(!0)}},gmVisionTool=(()=>{var _a2,_b;const binding=(_b=(_a2=game.keybindings.actions.get("pf2e.gm-vision"))==null?void 0:_a2.editable)==null?void 0:_b[0];if(!(binding&&game.user.isGM))return null;const gmVisionLabel=game.i18n.localize("PF2E.Keybinding.GMVision.Label"),bindingLabel=KeybindingsConfig._humanizeBinding(binding),gmVisionIcon=__name2((active=game.settings.get("pf2e","gmVision"))=>active?"fa-solid fa-lightbulb-cfl-on":"fa-solid fa-lightbulb-cfl","gmVisionIcon");return{name:"gm-vision",title:`${gmVisionLabel} [${bindingLabel}]`,icon:gmVisionIcon(),visible:game.user.isGM,toggle:!0,active:game.settings.get("pf2e","gmVision"),onClick:()=>{var _a3;const newStatus=!game.settings.get("pf2e","gmVision");game.settings.set("pf2e","gmVision",newStatus);const toggle=(_a3=ui.controls.control)==null?void 0:_a3.tools.find(t=>t.name==="gm-vision");toggle&&(toggle.active=newStatus,toggle.icon=gmVisionIcon(newStatus),ui.controls.render())}}})(),tools=[adjusterTool,gmVisionTool??[]].flat();lightingTools.splice(lightingTools?.indexOf(dayTool),0,...tools)})}};class MystifiedTraits{static compile(){this.mystifiedTraits=new Set(["artifact","extradimensional","invested","shadow",...Object.keys(CONFIG.PF2E.consumableTraits).filter(t=>!["consumable","nonlethal"].includes(t))].sort())}static has(trait){return this.mystifiedTraits.has(trait)}}__name(MystifiedTraits,"MystifiedTraits"),__name2(MystifiedTraits,"MystifiedTraits"),__publicField(MystifiedTraits,"mystifiedTraits",new Set);const ITEM_CARRY_TYPES=new Set(["held","worn","stowed","dropped"]),RANGE_TRAITS=["range-5","range-10","range-15","range-20","range-25","range-30","range-40","range-50","range-60","range-70","range-80","range-90","range-100","range-110","range-120","range-140","range-150","range-160","range-170","range-180","range-190","range-200","range-210","range-220","range-230","range-240","range-250","range-260","range-270","range-280","range-290","range-300","range-310","range-320","range-500","range-increment-5","range-increment-10","range-increment-15","range-increment-20","range-increment-25","range-increment-30","range-increment-40","range-increment-50","range-increment-60","range-increment-70","range-increment-75","range-increment-80","range-increment-90","range-increment-100","range-increment-110","range-increment-120","range-increment-130","range-increment-140","range-increment-150","range-increment-160","range-increment-170","range-increment-180","range-increment-190","range-increment-200","range-increment-210","range-increment-220","range-increment-230","range-increment-240","range-increment-250","range-increment-260","range-increment-270","range-increment-280","range-increment-290","range-increment-300","range-increment-310","range-increment-320"],immunityTypes={acid:"PF2E.Damage.RollFlavor.acid",adamantine:"PF2E.Damage.IWR.Type.adamantine",air:"PF2E.Damage.RollFlavor.air","area-damage":"PF2E.Damage.IWR.Type.area-damage",auditory:"PF2E.Damage.IWR.Type.auditory",bleed:"PF2E.Damage.RollFlavor.bleed",blinded:"PF2E.Damage.IWR.Type.blinded",bludgeoning:"PF2E.Damage.RollFlavor.bludgeoning",chaotic:"PF2E.Damage.RollFlavor.chaotic",clumsy:"PF2E.Damage.IWR.Type.clumsy",cold:"PF2E.Damage.RollFlavor.cold","cold-iron":"PF2E.Damage.IWR.Type.cold-iron",confused:"PF2E.Damage.IWR.Type.confused",conjuration:"PF2E.Damage.IWR.Type.conjuration",controlled:"PF2E.Damage.IWR.Type.controlled","critical-hits":"PF2E.Damage.IWR.Type.critical-hits",curse:"PF2E.Damage.IWR.Type.curse",darkwood:"PF2E.Damage.IWR.Type.darkwood",dazzled:"PF2E.Damage.IWR.Type.dazzled",deafened:"PF2E.Damage.IWR.Type.deafened","death-effects":"PF2E.Damage.IWR.Type.death-effects",disease:"PF2E.Damage.IWR.Type.disease",doomed:"PF2E.Damage.IWR.Type.doomed",drained:"PF2E.Damage.IWR.Type.drained",earth:"PF2E.Damage.RollFlavor.earth",electricity:"PF2E.Damage.RollFlavor.electricity",emotion:"PF2E.Damage.IWR.Type.emotion",enchantment:"PF2E.Damage.IWR.Type.enchantment",energy:"PF2E.Damage.IWR.Type.energy",enfeebled:"PF2E.Damage.IWR.Type.enfeebled",evil:"PF2E.Damage.RollFlavor.evil",evocation:"PF2E.Damage.IWR.Type.evocation",fascinated:"PF2E.Damage.IWR.Type.fascinated",fatigued:"PF2E.Damage.IWR.Type.fatigued","fear-effects":"PF2E.Damage.IWR.Type.fear-effects",fire:"PF2E.Damage.RollFlavor.fire","flat-footed":"PF2E.Damage.IWR.Type.flat-footed",fleeing:"PF2E.Damage.IWR.Type.fleeing",force:"PF2E.Damage.RollFlavor.force",frightened:"PF2E.Damage.IWR.Type.frightened",good:"PF2E.Damage.RollFlavor.good",grabbed:"PF2E.Damage.IWR.Type.grabbed",healing:"PF2E.Damage.IWR.Type.healing",illusion:"PF2E.Damage.IWR.Type.illusion",immobilized:"PF2E.Damage.IWR.Type.immobilized",inhaled:"PF2E.Damage.IWR.Type.inhaled",lawful:"PF2E.Damage.RollFlavor.lawful",light:"PF2E.Damage.IWR.Type.light",magic:"PF2E.Damage.IWR.Type.magic",mental:"PF2E.Damage.RollFlavor.mental","misfortune-effects":"PF2E.Damage.IWR.Type.misfortune-effects",mithral:"PF2E.Damage.IWR.Type.mithral",necromancy:"PF2E.Damage.IWR.Type.necromancy",negative:"PF2E.Damage.RollFlavor.negative","non-magical":"PF2E.Damage.IWR.Type.non-magical","nonlethal-attacks":"PF2E.Damage.IWR.Type.nonlethal-attacks","object-immunities":"PF2E.Damage.IWR.Type.object-immunities",olfactory:"PF2E.Damage.IWR.Type.olfactory",orichalcum:"PF2E.Damage.IWR.Type.orichalcum",paralyzed:"PF2E.Damage.IWR.Type.paralyzed",petrified:"PF2E.Damage.IWR.Type.petrified",physical:"PF2E.Damage.IWR.Type.physical",piercing:"PF2E.Damage.RollFlavor.piercing",poison:"PF2E.Damage.RollFlavor.poison",polymorph:"PF2E.Damage.IWR.Type.polymorph",positive:"PF2E.Damage.RollFlavor.positive",possession:"PF2E.Damage.IWR.Type.possession",precision:"PF2E.Damage.RollFlavor.precision",prone:"PF2E.Damage.IWR.Type.prone",restrained:"PF2E.Damage.IWR.Type.restrained","salt-water":"PF2E.Damage.IWR.Type.salt-water",scrying:"PF2E.Damage.IWR.Type.scrying",sickened:"PF2E.Damage.IWR.Type.sickened",silver:"PF2E.Damage.IWR.Type.silver",slashing:"PF2E.Damage.RollFlavor.slashing",sleep:"PF2E.Damage.IWR.Type.sleep",slowed:"PF2E.Damage.IWR.Type.slowed",sonic:"PF2E.Damage.RollFlavor.sonic","spell-deflection":"PF2E.Damage.IWR.Type.spell-deflection",stunned:"PF2E.Damage.IWR.Type.stunned",stupefied:"PF2E.Damage.IWR.Type.stupefied","swarm-attacks":"PF2E.Damage.IWR.Type.swarm-attacks","swarm-mind":"PF2E.Damage.IWR.Type.swarm-mind",transmutation:"PF2E.Damage.IWR.Type.transmutation",trip:"PF2E.Damage.IWR.Type.trip","unarmed-attacks":"PF2E.Damage.IWR.Type.unarmed-attacks",unconscious:"PF2E.Damage.IWR.Type.unconscious",visual:"PF2E.Damage.IWR.Type.visual",water:"PF2E.Damage.IWR.Type.water"},weaknessTypes={acid:"PF2E.Damage.RollFlavor.acid",adamantine:"PF2E.Damage.IWR.Type.adamantine",air:"PF2E.Damage.RollFlavor.air","area-damage":"PF2E.Damage.IWR.Type.area-damage","arrow-vulnerability":"PF2E.Damage.IWR.Type.arrow-vulnerability","axe-vulnerability":"PF2E.Damage.IWR.Type.axe-vulnerability",bleed:"PF2E.Damage.RollFlavor.bleed",bludgeoning:"PF2E.Damage.RollFlavor.bludgeoning",chaotic:"PF2E.Damage.RollFlavor.chaotic",cold:"PF2E.Damage.RollFlavor.cold","cold-iron":"PF2E.Damage.IWR.Type.cold-iron","critical-hits":"PF2E.Damage.IWR.Type.critical-hits",darkwood:"PF2E.Damage.IWR.Type.darkwood",earth:"PF2E.Damage.RollFlavor.earth",electricity:"PF2E.Damage.RollFlavor.electricity",emotion:"PF2E.Damage.IWR.Type.emotion",energy:"PF2E.Damage.IWR.Type.energy",evil:"PF2E.Damage.RollFlavor.evil",fire:"PF2E.Damage.RollFlavor.fire",force:"PF2E.Damage.RollFlavor.force","ghost-touch":"PF2E.Damage.IWR.Type.ghost-touch",glass:"PF2E.Damage.IWR.Type.glass",good:"PF2E.Damage.RollFlavor.good",lawful:"PF2E.Damage.RollFlavor.lawful",light:"PF2E.Damage.IWR.Type.light",magical:"PF2E.Damage.IWR.Type.magical",mental:"PF2E.Damage.RollFlavor.mental",metal:"PF2E.Damage.RollFlavor.metal",mithral:"PF2E.Damage.IWR.Type.mithral",negative:"PF2E.Damage.RollFlavor.negative","non-magical":"PF2E.Damage.IWR.Type.non-magical","nonlethal-attacks":"PF2E.Damage.IWR.Type.nonlethal-attacks",orichalcum:"PF2E.Damage.IWR.Type.orichalcum",physical:"PF2E.Damage.IWR.Type.physical",piercing:"PF2E.Damage.RollFlavor.piercing",poison:"PF2E.Damage.RollFlavor.poison",positive:"PF2E.Damage.RollFlavor.positive",precision:"PF2E.Damage.RollFlavor.precision",radiation:"PF2E.Damage.IWR.Type.radiation",salt:"PF2E.Damage.IWR.Type.salt","salt-water":"PF2E.Damage.IWR.Type.salt-water",silver:"PF2E.Damage.IWR.Type.silver",slashing:"PF2E.Damage.RollFlavor.slashing",sonic:"PF2E.Damage.RollFlavor.sonic","splash-damage":"PF2E.Damage.IWR.Type.splash-damage","unarmed-attacks":"PF2E.Damage.IWR.Type.unarmed-attacks","vampire-weaknesses":"PF2E.Damage.IWR.Type.vampire-weaknesses",vorpal:"PF2E.Damage.IWR.Type.vorpal","vorpal-fear":"PF2E.Damage.IWR.Type.vorpal-fear","vulnerable-to-sunlight":"PF2E.Damage.IWR.Type.vulnerable-to-sunlight",warpglass:"PF2E.Damage.IWR.Type.warpglass",water:"PF2E.Damage.IWR.Type.water",weapons:"PF2E.Damage.IWR.Type.weapons","weapons-shedding-bright-light":"PF2E.Damage.IWR.Type.weapons-shedding-bright-light"},resistanceTypes={acid:"PF2E.Damage.RollFlavor.acid",adamantine:"PF2E.Damage.IWR.Type.adamantine",air:"PF2E.Damage.RollFlavor.air","all-damage":"PF2E.Damage.IWR.Type.all-damage","area-damage":"PF2E.Damage.IWR.Type.area-damage",bleed:"PF2E.Damage.RollFlavor.bleed",bludgeoning:"PF2E.Damage.RollFlavor.bludgeoning",chaotic:"PF2E.Damage.RollFlavor.chaotic",cold:"PF2E.Damage.RollFlavor.cold","cold-iron":"PF2E.Damage.IWR.Type.cold-iron","critical-hits":"PF2E.Damage.IWR.Type.critical-hits","damage-from-spells":"PF2E.Damage.IWR.Type.damage-from-spells",darkwood:"PF2E.Damage.IWR.Type.darkwood",earth:"PF2E.Damage.RollFlavor.earth",electricity:"PF2E.Damage.RollFlavor.electricity",energy:"PF2E.Damage.IWR.Type.energy",evil:"PF2E.Damage.RollFlavor.evil",fire:"PF2E.Damage.RollFlavor.fire",force:"PF2E.Damage.RollFlavor.force","ghost-touch":"PF2E.Damage.IWR.Type.ghost-touch",good:"PF2E.Damage.RollFlavor.good",lawful:"PF2E.Damage.RollFlavor.lawful",light:"PF2E.Damage.IWR.Type.light",magical:"PF2E.Damage.IWR.Type.magical",mental:"PF2E.Damage.RollFlavor.mental",metal:"PF2E.Damage.RollFlavor.metal",mithral:"PF2E.Damage.IWR.Type.mithral",negative:"PF2E.Damage.RollFlavor.negative","non-magical":"PF2E.Damage.IWR.Type.non-magical",nonlethal:"PF2E.Damage.IWR.Type.nonlethal","nonlethal-attacks":"PF2E.Damage.IWR.Type.nonlethal-attacks",orichalcum:"PF2E.Damage.IWR.Type.orichalcum",physical:"PF2E.Damage.IWR.Type.physical",piercing:"PF2E.Damage.RollFlavor.piercing",plant:"PF2E.Damage.IWR.Type.plant",poison:"PF2E.Damage.RollFlavor.poison",positive:"PF2E.Damage.RollFlavor.positive",precision:"PF2E.Damage.RollFlavor.precision","protean-anatomy":"PF2E.Damage.IWR.Type.protean-anatomy",radiation:"PF2E.Damage.IWR.Type.radiation",salt:"PF2E.Damage.IWR.Type.salt","salt-water":"PF2E.Damage.IWR.Type.salt-water",silver:"PF2E.Damage.IWR.Type.silver",slashing:"PF2E.Damage.RollFlavor.slashing",sonic:"PF2E.Damage.RollFlavor.sonic","unarmed-attacks":"PF2E.Damage.IWR.Type.unarmed-attacks",vorpal:"PF2E.Damage.IWR.Type.vorpal","vorpal-adamantine":"PF2E.Damage.IWR.Type.vorpal-adamantine",warpglass:"PF2E.Damage.IWR.Type.warpglass",water:"PF2E.Damage.IWR.Type.water",weapons:"PF2E.Damage.IWR.Type.weapons","weapons-shedding-bright-light":"PF2E.Damage.IWR.Type.weapons-shedding-bright-light"},ABILITY_ABBREVIATIONS=new Set(["str","dex","con","int","wis","cha"]),CREATURE_ACTOR_TYPES=["character","npc","familiar"],SAVE_TYPES=["fortitude","reflex","will"],IMMUNITY_TYPES=new Set(Object.keys(immunityTypes)),WEAKNESS_TYPES=new Set(Object.keys(weaknessTypes)),RESISTANCE_TYPES=new Set(Object.keys(resistanceTypes)),UNAFFECTED_TYPES=new Set(["good","evil","lawful","chaotic","negative","positive","bleed"]),SKILL_ABBREVIATIONS=new Set(["acr","arc","ath","cra","dec","dip","itm","med","nat","occ","prf","rel","soc","ste","sur","thi"]),SKILL_DICTIONARY={acr:"acrobatics",arc:"arcana",ath:"athletics",cra:"crafting",dec:"deception",dip:"diplomacy",itm:"intimidation",med:"medicine",nat:"nature",occ:"occultism",prf:"performance",rel:"religion",soc:"society",ste:"stealth",sur:"survival",thi:"thievery"},SKILL_LONG_FORMS=new Set(Object.values(SKILL_DICTIONARY)),SKILL_DICTIONARY_REVERSE=Object.fromEntries(Object.entries(SKILL_DICTIONARY).map(([abbrev,value])=>[value,abbrev])),DC_SLUGS=new Set(["ac","armor","perception",...SAVE_TYPES,...SKILL_LONG_FORMS]),SKILL_EXPANDED={acrobatics:{ability:"dex",shortform:"acr"},arcana:{ability:"int",shortform:"arc"},athletics:{ability:"str",shortform:"ath"},crafting:{ability:"int",shortform:"cra"},deception:{ability:"cha",shortform:"dec"},diplomacy:{ability:"cha",shortform:"dip"},intimidation:{ability:"cha",shortform:"itm"},medicine:{ability:"wis",shortform:"med"},nature:{ability:"wis",shortform:"nat"},occultism:{ability:"int",shortform:"occ"},performance:{ability:"cha",shortform:"prf"},religion:{ability:"wis",shortform:"rel"},society:{ability:"int",shortform:"soc"},stealth:{ability:"dex",shortform:"ste"},survival:{ability:"wis",shortform:"sur"},thievery:{ability:"dex",shortform:"thi"}},MOVEMENT_TYPES=["land","burrow","climb","fly","swim"],ANIMAL_COMPANION_SOURCE_ID="Compendium.pf2e-animal-companions.AC-Ancestries-and-Class.h6Ybhv5URar01WPk",CONSTRUCT_COMPANION_SOURCE_ID="Compendium.pf2e-animal-companions.AC-Features.OJePkZgnguu5Z8cA";var LightLevels=(LightLevels2=>(LightLevels2[LightLevels2.DARKNESS=.25]="DARKNESS",LightLevels2[LightLevels2.BRIGHT_LIGHT=.75]="BRIGHT_LIGHT",LightLevels2))(LightLevels||{});let auraCheckLock=Promise.resolve();const checkAuras=foundry.utils.debounce(async function(){var _a;if(!(canvas.ready&&this.isInFocus&&this.grid.type===CONST.GRID_TYPES.SQUARE))return;await auraCheckLock;const lock={release:()=>{}};auraCheckLock=new Promise(resolve=>{lock.release=resolve});const tokens=this.tokens.reduce((list,token)=>(token.isLinked&&list.some(t=>t.actor===token.actor)||list.push(token),list),[]);for(const token of tokens)await((_a=token.object)==null?void 0:_a._animation);const auras=tokens.flatMap(t=>Array.from(t.auras.values()));for(const aura of auras){const auradTokens=tokens.filter(t=>aura.containsToken(t));await aura.notifyActors(auradTokens);const nonAuradTokens=tokens.filter(t=>!auradTokens.includes(t)),nonAuradActors=new Set(nonAuradTokens.flatMap(t=>t.actor??[]));for(const actor of nonAuradActors)actor.checkAreaEffects()}const sceneActors=new Set(tokens.flatMap(t=>{var _a2;return(_a2=t.actor)!=null&&_a2.canUserModify(game.user,"update")?t.actor:[]}));for(const actor of sceneActors)actor.checkAreaEffects();lock.release()},100);class ScenePF2e extends Scene{get rulesBasedVision(){const settingEnabled=game.settings.get("pf2e","automation.rulesBasedVision");return this.tokenVision&&settingEnabled}get darknessSyncedToTime(){return this.flags.pf2e.syncDarkness==="enabled"||this.flags.pf2e.syncDarkness==="default"&&game.settings.get("pf2e","worldClock.syncDarkness")}get lightLevel(){return 1-this.darkness}get isBright(){return this.lightLevel>=LightLevels.BRIGHT_LIGHT}get isDimlyLit(){return!this.isBright&&!this.isDark}get isDark(){return this.lightLevel<=LightLevels.DARKNESS}get hasHexGrid(){return![CONST.GRID_TYPES.GRIDLESS,CONST.GRID_TYPES.SQUARE].includes(this.grid.type)}get isInFocus(){const soleUserIsGM=__name2(()=>game.user.isGM&&game.users.filter(u=>u.active).length===1,"soleUserIsGM");return this.active||game.scenes.viewed===this&&soleUserIsGM()}prepareData(){super.prepareData(),Promise.resolve().then(()=>{this.checkAuras()})}prepareBaseData(){var _a,_b;super.prepareBaseData(),this.rulesBasedVision&&(this.globalLight=!0,this.hasGlobalThreshold=!0,this.globalLightThreshold=1-(LightLevels.DARKNESS+.001)),(_a=this.flags).pf2e??(_a.pf2e={syncDarkness:"default"}),(_b=this.flags.pf2e).syncDarkness??(_b.syncDarkness="default")}_onUpdate(changed,options,userId){if(super._onUpdate(changed,options,userId),changed.active&&canvas.scene===this)for(const token of canvas.tokens.placeables)token.auras.draw()}}__name(ScenePF2e,"ScenePF2e"),__name2(ScenePF2e,"ScenePF2e"),Object.defineProperty(ScenePF2e.prototype,"checkAuras",{configurable:!1,enumerable:!1,writable:!1,value:checkAuras});class AmbientLightDocumentPF2e extends AmbientLightDocument{get isDarkness(){var _a;return((_a=this.object)==null?void 0:_a.source.isDarkness)??!1}}__name(AmbientLightDocumentPF2e,"AmbientLightDocumentPF2e"),__name2(AmbientLightDocumentPF2e,"AmbientLightDocumentPF2e");class TileDocumentPF2e extends TileDocument{}__name(TileDocumentPF2e,"TileDocumentPF2e"),__name2(TileDocumentPF2e,"TileDocumentPF2e");class PersistentDamageDialog extends Application{constructor(actor,options={}){super(options),__privateAdd(this,_prepareDamageTypes),__privateAdd(this,_getInputElements),this.actor=actor,actor.apps[this.appId]=this}static get defaultOptions(){return{...super.defaultOptions,classes:["persistent-damage-dialog"],template:"systems/pf2e/templates/items/persistent-damage-dialog.hbs",width:380,height:"auto"}}get id(){return`persistent-damage-${this.actor.id}`}get title(){return game.i18n.format("PF2E.Item.Condition.PersistentDamage.Dialog.Title",{actor:this.actor.name})}async getData(){return{existing:this.actor.itemTypes.condition.filter(c=>c.slug==="persistent-damage").map(c=>({id:c.id,bullet:damageDiceIcon(c.system.persistent.damage).outerHTML,active:c.active,...pick(c.system.persistent,["formula","damageType","dc"])})),damageTypes:__privateMethod(this,_prepareDamageTypes,prepareDamageTypes_fn).call(this)}}activateListeners($html){var _a,_b,_c;const html=$html[0];for(const section of htmlQueryAll(html,".persistent-entry[data-id")){const id=section.dataset.id,existing=this.actor.items.get(id,{strict:!0}),elements=__privateMethod(this,_getInputElements,getInputElements_fn).call(this,section);for(const element of Object.values(elements))element?.addEventListener("change",()=>{var _a2,_b2,_c2,_d;const formula=((_a2=elements.formula)==null?void 0:_a2.value.trim())??"",damageType=(_b2=elements.damageType)==null?void 0:_b2.value,dc=Number((_c2=elements.dc)==null?void 0:_c2.value)||15;formula===""||!DamageRoll.validate(`(${formula})[${damageType}]`)?(_d=elements.formula)==null||_d.classList.add("invalid"):existing.update({system:{persistent:{formula,damageType,dc}}})});(_a=htmlQuery(section,"[data-action=delete"))==null||_a.addEventListener("click",()=>{existing.delete()})}(_b=html.querySelector("[data-action=add]"))==null||_b.addEventListener("click",event=>{var _a2,_b2,_c2,_d;const section=htmlClosest(event.target,".persistent-entry");if(!section)return;const elements=__privateMethod(this,_getInputElements,getInputElements_fn).call(this,section),formula=((_a2=elements.formula)==null?void 0:_a2.value.trim())||"1d6",damageType=(_b2=elements.damageType)==null?void 0:_b2.value,dc=Number((_c2=elements.dc)==null?void 0:_c2.value)||15;if(!DamageRoll.validate(`(${formula})[${damageType}]`))(_d=elements.formula)==null||_d.classList.add("invalid");else{const baseConditionSource=game.pf2e.ConditionManager.getCondition("persistent-damage").toObject(),persistentSource=mergeObject(baseConditionSource,{system:{persistent:{formula,damageType,dc}}});this.actor.createEmbeddedDocuments("Item",[persistentSource])}}),(_c=html.querySelector("[data-action=roll-persistent]"))==null||_c.addEventListener("click",()=>{const existing=this.actor.itemTypes.condition.filter(c=>c.slug==="persistent-damage");for(const condition of existing)condition.onEndTurn()})}_injectHTML($html){var _a;super._injectHTML($html),(_a=htmlQuery($html[0],".new .formula"))==null||_a.focus()}}__name(PersistentDamageDialog,"PersistentDamageDialog"),__name2(PersistentDamageDialog,"PersistentDamageDialog"),_prepareDamageTypes=new WeakSet,prepareDamageTypes_fn=__name2(function(){return Object.keys(CONFIG.PF2E.damageTypes).map(type2=>{const labels=CONFIG.PF2E.damageTypes,faGlyph=DAMAGE_TYPE_ICONS[type2]??"question";return{type:type2,iconClass:`fa-${faGlyph}`,label:game.i18n.localize(labels[type2]??type2)}}).sort(sortBy(type2=>type2.label))},"#prepareDamageTypes"),_getInputElements=new WeakSet,getInputElements_fn=__name2(function(section){return{formula:htmlQuery(section,".formula"),damageType:htmlQuery(section,".damageType"),dc:htmlQuery(section,".dc")}},"#getInputElements");const CONDITION_SLUGS=new Set(["blinded","broken","clumsy","concealed","confused","controlled","dazzled","deafened","doomed","drained","dying","encumbered","enfeebled","fascinated","fatigued","flat-footed","fleeing","friendly","frightened","grabbed","helpful","hidden","hostile","immobilized","indifferent","invisible","observed","paralyzed","persistent-damage","petrified","prone","quickened","restrained","sickened","slowed","stunned","stupefied","unconscious","undetected","unfriendly","unnoticed","wounded"]);function isCycle(item,container){return item===container?!0:container.container?isCycle(item,container.container):!1}__name(isCycle,"isCycle"),__name2(isCycle,"isCycle");function hasExtraDimensionalParent(item,encountered=new Set){if(encountered.has(item.id))return!1;encountered.add(item.id);const parent=item.container;return parent?parent.traits.has("extradimensional")?!0:(encountered.add(parent.id),hasExtraDimensionalParent(parent)):!1}__name(hasExtraDimensionalParent,"hasExtraDimensionalParent"),__name2(hasExtraDimensionalParent,"hasExtraDimensionalParent");const PHYSICAL_ITEM_TYPES=new Set(["armor","backpack","book","consumable","equipment","treasure","weapon"]),PRECIOUS_MATERIAL_GRADES=new Set(["low","standard","high"]),DENOMINATIONS=["pp","gp","sp","cp"];function isItemSystemData(data){return isObject(data)&&isObject(data.description)&&typeof data.description.value=="string"&&Array.isArray(data.rules)&&(data.slug===null||typeof data.slug=="string")}__name(isItemSystemData,"isItemSystemData"),__name2(isItemSystemData,"isItemSystemData");function isPhysicalData(source){return setHasElement(PHYSICAL_ITEM_TYPES,source.type)}__name(isPhysicalData,"isPhysicalData"),__name2(isPhysicalData,"isPhysicalData");function hasInvestedProperty(source){return isPhysicalData(source)&&"invested"in source.system.equipped}__name(hasInvestedProperty,"hasInvestedProperty"),__name2(hasInvestedProperty,"hasInvestedProperty");class SpellCollection extends Collection{constructor(entry){if(!entry.actor)throw ErrorPF2e("a spell collection must have an associated actor");super(),__privateAdd(this,_assertEntryIsDocument),__privateAdd(this,_getRitualData),__publicField(this,"entry"),__publicField(this,"actor"),this.entry=entry,this.actor=entry.actor}get id(){return this.entry.id}get highestLevel(){var _a;const highestSpell=Math.max(...this.map(s=>s.level)),actorSpellLevel=Math.ceil((((_a=this.actor)==null?void 0:_a.level)??0)/2);return Math.min(10,Math.max(highestSpell,actorSpellLevel))}async addSpell(spell,options={}){var _a;const{actor}=this;if(!actor.isOfType("creature"))throw ErrorPF2e("Spellcasting entries can only exist on creatures");const canHeighten=!(spell.isCantrip||spell.isFocusSpell||spell.isRitual)&&(this.entry.isSpontaneous||this.entry.isInnate),heightenLevel=canHeighten?options.slotLevel??spell.level:spell.baseLevel;if(spell.system.location.value===this.id&&spell.level===heightenLevel)return null;if(spell.isFocusSpell&&!this.entry.isFocusPool){const focusTypeLabel=game.i18n.format("PF2E.SpellFocusLabel");return ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.WrongSpellType",{spellType:focusTypeLabel})),null}if(spell.baseLevel>heightenLevel&&this.id===((_a=spell.system.location)==null?void 0:_a.value)){const targetLevelLabel=game.i18n.format("PF2E.SpellLevel",{level:ordinal(heightenLevel)}),baseLabel=game.i18n.format("PF2E.SpellLevel",{level:ordinal(spell.baseLevel)});ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.InvalidLevel",{name:spell.name,targetLevel:targetLevelLabel,baseLevel:baseLabel}))}const heightenedUpdate=canHeighten&&heightenLevel>=spell.baseLevel?{"system.location.heightenedLevel":heightenLevel}:{};if(spell.actor===actor)return spell.update({"system.location.value":this.id,...heightenedUpdate});{const source=spell.clone({"system.location.value":this.id,...heightenedUpdate}).toObject(),created=(await actor.createEmbeddedDocuments("Item",[source])).shift();return created instanceof SpellPF2e?created:null}}async prepareSpell(spell,slotLevel,spellSlot){if(__privateMethod(this,_assertEntryIsDocument,assertEntryIsDocument_fn).call(this,this.entry),spell.baseLevel>slotLevel&&!(slotLevel===0&&spell.isCantrip)){const targetLevelLabel=game.i18n.format("PF2E.SpellLevel",{level:ordinal(slotLevel)}),baseLabel=game.i18n.format("PF2E.SpellLevel",{level:ordinal(spell.baseLevel)});return ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.InvalidLevel",{name:spell.name,targetLevel:targetLevelLabel,baseLevel:baseLabel})),this.entry}CONFIG.debug.hooks&&console.debug(`PF2e System | Updating location for spell ${spell.name} to match spellcasting entry ${this.id}`);const key=`system.slots.slot${slotLevel}.prepared.${spellSlot}`,updates={[key]:{id:spell.id}},slot=this.entry.system.slots[`slot${slotLevel}`].prepared[spellSlot];return slot&&(slot.prepared!==void 0&&(updates[`${key}.-=prepared`]=null),slot.name!==void 0&&(updates[`${key}.-=name`]=null)),this.entry.update(updates)}unprepareSpell(slotLevel,spellSlot){__privateMethod(this,_assertEntryIsDocument,assertEntryIsDocument_fn).call(this,this.entry),CONFIG.debug.hooks===!0&&console.debug(`PF2e System | Updating spellcasting entry ${this.id} to remove spellslot ${spellSlot} for spell level ${slotLevel}`);const key=`system.slots.slot${slotLevel}.prepared.${spellSlot}`;return this.entry.update({[key]:{name:game.i18n.localize("PF2E.SpellSlotEmpty"),id:null,prepared:!1,expended:!1}})}setSlotExpendedState(slotLevel,spellSlot,isExpended){__privateMethod(this,_assertEntryIsDocument,assertEntryIsDocument_fn).call(this,this.entry);const key=`system.slots.slot${slotLevel}.prepared.${spellSlot}.expended`;return this.entry.update({[key]:isExpended})}async getSpellData(){var _a,_b;const{actor}=this;if(!actor.isOfType("character","npc"))throw ErrorPF2e("Spellcasting entries can only exist on characters and npcs");if(this.entry instanceof RitualSpellcasting)return __privateMethod(this,_getRitualData,getRitualData_fn).call(this);__privateMethod(this,_assertEntryIsDocument,assertEntryIsDocument_fn).call(this,this.entry);const results=[],spells=this.contents.sort((s1,s2)=>(s1.sort||0)-(s2.sort||0)),signatureSpells=spells.filter(s=>s.system.location.signature),isFlexible=this.entry.isFlexible;if(this.entry.isPrepared&&this.entry instanceof SpellcastingEntryPF2e)for(let level=0;level<=this.highestLevel;level++){const data=this.entry.system.slots[`slot${level}`],active=[];if((this.entry.system.showSlotlessLevels.value||data.max>0)&&(level===0||!isFlexible)){const maxPrepared=Math.max(data.max,0);active.push(...Array(maxPrepared).fill(null));for(const[key,value]of Object.entries(data.prepared)){const spell=value.id?this.get(value.id):null;spell&&(active[Number(key)]={castLevel:spell.computeCastLevel(level),spell,expended:!!value.expended})}}results.push({label:level===0?"PF2E.TraitCantrip":CONFIG.PF2E.spellLevels[level],level,uses:{value:level>0&&isFlexible?data.value||0:void 0,max:data.max},isCantrip:level===0,active})}else if(this.entry.isFocusPool){const cantrips=spells.filter(spell=>spell.isCantrip),leveled=spells.filter(spell=>!spell.isCantrip);if(cantrips.length){const active=await Promise.all(cantrips.map(async spell=>({spell})));results.push({label:"PF2E.Actor.Creature.Spellcasting.Cantrips",level:0,isCantrip:!0,active})}if(leveled.length){const active=await Promise.all(leveled.map(async spell=>({spell})));results.push({label:actor.type==="character"?"PF2E.Focus.Spells":"PF2E.Focus.Pool",level:Math.max(1,Math.ceil(actor.level/2)),isCantrip:!1,uses:actor.system.resources.focus??{value:0,max:0},active})}}else{const alwaysShowHeader=!this.entry.isRitual,spellsByLevel=groupBy(spells,spell=>spell.isCantrip?0:spell.level);for(let level=0;level<=this.highestLevel;level++){const data=this.entry.system.slots[`slot${level}`],spells2=spellsByLevel.get(level)??[];if(alwaysShowHeader||spells2.length){const uses=this.entry.isSpontaneous&&level!==0?{value:data.value,max:data.max}:void 0,active=await Promise.all(spells2.map(async spell=>{var _a2;return{spell,expended:this.entry.isInnate&&!((_a2=spell.system.location.uses)!=null&&_a2.value),uses:this.entry.isInnate&&!spell.unlimited?spell.system.location.uses:void 0}})),hideForSpontaneous=this.entry.isSpontaneous&&uses?.max===0&&active.length===0,hideForInnate=this.entry.isInnate&&active.length===0;if(!this.entry.system.showSlotlessLevels.value&&(hideForSpontaneous||hideForInnate))continue;results.push({label:level===0?"PF2E.TraitCantrip":CONFIG.PF2E.spellLevels[level],level,isCantrip:level===0,uses,active})}}}if(this.entry.isSpontaneous||isFlexible){for(const spell of signatureSpells)for(const result of results){if(spell.baseLevel>result.level||!this.entry.system.showSlotlessLevels.value&&((_a=result.uses)==null?void 0:_a.max)===0)continue;const existing=result.active.find(a=>a?.spell.id===spell.id);if(existing)existing.signature=!0;else{const castLevel=result.level;result.active.push({spell,castLevel,signature:!0,virtual:!0})}}for(const result of results)if(result.level>0&&((_b=result.uses)==null?void 0:_b.value)===0&&result.uses.max>0)for(const slot of result.active)slot&&(slot.expended=!0)}const flexibleAvailable=(()=>{if(!isFlexible)return null;const totalSlots=results.filter(result=>!result.isCantrip).map(level=>{var _a2;return((_a2=level.uses)==null?void 0:_a2.max)||0}).reduce((first,second)=>first+second,0);return{value:signatureSpells.length,max:totalSlots}})();return{levels:results,flexibleAvailable,spellPrepList:this.getSpellPrepList(spells)}}getSpellPrepList(spells){var _a;if(!this.entry.isPrepared)return{};const spellPrepList={},spellsByLevel=groupBy(spells,spell=>spell.isCantrip?0:spell.baseLevel);for(let level=0;level<=this.highestLevel;level++)spellPrepList[level]=((_a=spellsByLevel.get(level))==null?void 0:_a.map(spell=>({spell,signature:this.entry.isFlexible&&spell.system.location.signature})))??[];return Object.values(spellPrepList).some(s=>!!s.length)?spellPrepList:null}}__name(SpellCollection,"SpellCollection"),__name2(SpellCollection,"SpellCollection"),_assertEntryIsDocument=new WeakSet,assertEntryIsDocument_fn=__name2(function(entry){if(!(entry instanceof ItemPF2e))throw ErrorPF2e("`this#entry` is not a `SpellcastingEntryPF2e`")},"#assertEntryIsDocument"),_getRitualData=new WeakSet,getRitualData_fn=__name2(async function(){const groupedByLevel=groupBy(Array.from(this.values()),s=>s.level);return{levels:await Promise.all(Array.from(groupedByLevel.entries()).sort(([a],[b])=>a-b).map(async([level,spells])=>({label:CONFIG.PF2E.spellLevels[level],level,isCantrip:!1,active:await Promise.all(spells.map(async spell=>({spell})))}))),spellPrepList:null}},"#getRitualData");class RitualSpellcasting{constructor(actor,rituals){__publicField(this,"actor"),__publicField(this,"spells"),this.actor=actor,this.spells=new SpellCollection(this);for(const ritual of rituals)this.spells.set(ritual.id,ritual)}get id(){return"rituals"}get name(){return game.i18n.localize("PF2E.Actor.Creature.Spellcasting.Rituals")}get sort(){return Math.max(0,...this.actor.itemTypes.spellcastingEntry.map(e=>e.sort))+10}get category(){return"ritual"}get tradition(){return null}get isFlexible(){return!1}get isFocusPool(){return!1}get isInnate(){return!1}get isPrepared(){return!1}get isRitual(){return!0}get isSpontaneous(){return!1}canCast(spell){return spell.isRitual}async cast(spell,options={}){if(!spell.isRitual)throw ErrorPF2e("Attempted to cast non-ritual from `RitualSpellcasting`");await spell.toMessage(void 0,{rollMode:options.rollMode})}async getSheetData(){return{id:this.id,name:this.name,statistic:null,tradition:null,category:this.category,isRitual:!0,hasCollection:!0,sort:this.sort,...await this.spells.getSpellData()}}}__name(RitualSpellcasting,"RitualSpellcasting"),__name2(RitualSpellcasting,"RitualSpellcasting");class MigrationRunnerBase{constructor(migrations=[]){__publicField(this,"migrations"),this.migrations=migrations.sort((a,b)=>a.version-b.version)}needsMigration(currentVersion){return currentVersion0&&this.updateSchemaRecord(current.system.schema,migrations.slice(-1)[0]),current}async getUpdatedTable(tableSource,migrations){var _a;const current=deepClone(tableSource);for(const migration of migrations)try{await((_a=migration.updateTable)==null?void 0:_a.call(migration,current))}catch(err){console.error(err)}return current}async getUpdatedMacro(macroSource,migrations){var _a;const current=deepClone(macroSource);for(const migration of migrations)try{await((_a=migration.updateMacro)==null?void 0:_a.call(migration,current))}catch(err){console.error(err)}return current}async getUpdatedJournalEntry(source,migrations){var _a;const clone=deepClone(source);for(const migration of migrations)try{await((_a=migration.updateJournalEntry)==null?void 0:_a.call(migration,clone))}catch(err){console.error(err)}return clone}async getUpdatedToken(token,migrations){var _a;const current=token.toObject();for(const migration of migrations)await((_a=migration.updateToken)==null?void 0:_a.call(migration,current,token.actor,token.scene));return current}async getUpdatedUser(userData,migrations){var _a;const current=deepClone(userData);for(const migration of migrations)try{await((_a=migration.updateUser)==null?void 0:_a.call(migration,current))}catch(err){console.error(err)}return current}updateSchemaRecord(schema,latestMigration){if(!("game"in globalThis&&latestMigration))return;const fromVersion=typeof schema.version=="number"?schema.version:null;schema.version=latestMigration.version,schema.lastMigration={datetime:DateTime.now().toISO(),version:{schema:fromVersion,foundry:"game"in globalThis?game.version:void 0,system:"game"in globalThis?game.system.version:void 0}}}}__name(MigrationRunnerBase,"MigrationRunnerBase"),__name2(MigrationRunnerBase,"MigrationRunnerBase"),__publicField(MigrationRunnerBase,"LATEST_SCHEMA_VERSION",.84),__publicField(MigrationRunnerBase,"MINIMUM_SAFE_VERSION",.618),__publicField(MigrationRunnerBase,"RECOMMENDED_SAFE_VERSION",.634);const _MigrationRunner=__name(class extends MigrationRunnerBase{constructor(){super(...arguments),__privateAdd(this,_migrateDocuments),__privateAdd(this,_migrateItem),__privateAdd(this,_migrateActor),__privateAdd(this,_migrateWorldJournalEntry),__privateAdd(this,_migrateWorldMacro),__privateAdd(this,_migrateWorldTable),__privateAdd(this,_migrateSceneToken),__privateAdd(this,_migrateUser)}needsMigration(){return super.needsMigration(game.settings.get("pf2e","worldSchemaVersion"))}static async ensureSchemaVersion(document2,migrations){if(migrations.length===0)return;const currentVersion=this.LATEST_SCHEMA_VERSION;if((Number(document2.schemaVersion)||0){try{return"items"in source?await runner.getUpdatedActor(source,runner.migrations):await runner.getUpdatedItem(source,runner.migrations)}catch{return null}})();updated&&document2.updateSource(updated)}if(document2.updateSource({"system.schema.version":currentVersion}),"items"in document2&&"token"in document2)for(const item of document2.items)item.schemaVersion||item.updateSource({"system.schema.version":currentVersion})}async runCompendiumMigration(compendium){ui.notifications.info(game.i18n.format("PF2E.Migrations.Starting",{version:game.system.version}),{permanent:!0});const documents=await compendium.getDocuments(),lowestSchemaVersion=Math.min(MigrationRunnerBase.LATEST_SCHEMA_VERSION,...documents.map(d=>d.system.schema.version).filter(d=>!!d)),migrations=this.migrations.filter(migration=>migration.version>lowestSchemaVersion);await __privateMethod(this,_migrateDocuments,migrateDocuments_fn).call(this,compendium,migrations),ui.notifications.info(game.i18n.format("PF2E.Migrations.Finished",{version:game.system.version}),{permanent:!0})}async runMigrations(migrations){var _a;if(migrations.length===0)return;await __privateMethod(this,_migrateDocuments,migrateDocuments_fn).call(this,game.actors,migrations),await __privateMethod(this,_migrateDocuments,migrateDocuments_fn).call(this,game.items,migrations);for(const entry of game.journal)await __privateMethod(this,_migrateWorldJournalEntry,migrateWorldJournalEntry_fn).call(this,entry,migrations);const promises=[];for(const macro of game.macros)promises.push(__privateMethod(this,_migrateWorldMacro,migrateWorldMacro_fn).call(this,macro,migrations));for(const table of game.tables)promises.push(__privateMethod(this,_migrateWorldTable,migrateWorldTable_fn).call(this,table,migrations));for(const user of game.users)promises.push(__privateMethod(this,_migrateUser,migrateUser_fn).call(this,user,migrations));for(const migration of migrations)migration.migrate&&promises.push(migration.migrate());await Promise.allSettled(promises);for(const scene of game.scenes)for(const token of scene.tokens){const{actor}=token;if(!actor||!!!await __privateMethod(this,_migrateSceneToken,migrateSceneToken_fn).call(this,token,migrations))continue;const hasMigratableData=!!((_a=token._source.actorData.flags)!=null&&_a.pf2e)||Object.keys(token._source.actorData).some(k=>["items","system"].includes(k));if(actor.isToken&&hasMigratableData){const updated=await __privateMethod(this,_migrateActor,migrateActor_fn).call(this,migrations,actor);if(updated)try{await actor.update(updated)}catch(error){console.warn(error)}}}}async runMigration(force=!1){const schemaVersion={latest:_MigrationRunner.LATEST_SCHEMA_VERSION,current:game.settings.get("pf2e","worldSchemaVersion")},systemVersion=game.system.version;ui.notifications.info(game.i18n.format("PF2E.Migrations.Starting",{version:systemVersion}),{permanent:!0});const migrationsToRun=force?this.migrations:this.migrations.filter(x=>schemaVersion.current0&&await this.runMigrations(migrationPhase);await game.settings.set("pf2e","worldSchemaVersion",schemaVersion.latest)}},"_MigrationRunner");let MigrationRunner=_MigrationRunner;__name2(MigrationRunner,"MigrationRunner"),_migrateDocuments=new WeakSet,migrateDocuments_fn=__name2(async function(collection,migrations){const DocumentClass=collection.documentClass,pack="metadata"in collection?collection.metadata.id:null,updateGroup=[];for(const document2 of collection.contents.sort(a=>a.type==="familiar"?1:-1)){if(updateGroup.length===50)try{await DocumentClass.updateDocuments(updateGroup,{noHook:!0,pack})}catch(error){console.warn(error)}finally{updateGroup.length=0}const updated="items"in document2?await __privateMethod(this,_migrateActor,migrateActor_fn).call(this,migrations,document2,{pack}):await __privateMethod(this,_migrateItem,migrateItem_fn).call(this,migrations,document2,{pack});updated&&updateGroup.push(updated)}if(updateGroup.length>0)try{await DocumentClass.updateDocuments(updateGroup,{noHook:!0,pack})}catch(error){console.warn(error)}},"#migrateDocuments"),_migrateItem=new WeakSet,migrateItem_fn=__name2(async function(migrations,item,options={}){var _a;const{pack}=options,baseItem=item.toObject(),updatedItem=await(()=>{try{return this.getUpdatedItem(baseItem,migrations)}catch(error){return error instanceof Error&&console.error(`Error thrown while migrating ${item.uuid}: ${error.message}`),null}})();if(!updatedItem)return null;const baseAEs=[...baseItem.effects],updatedAEs=[...updatedItem.effects],aeDiff=this.diffCollection(baseAEs,updatedAEs);if(aeDiff.deleted.length>0)try{const finalDeleted=aeDiff.deleted.filter(deletedId=>item.effects.some(effect=>effect.id===deletedId));await item.deleteEmbeddedDocuments("ActiveEffect",finalDeleted,{noHook:!0,pack})}catch(error){console.warn(error)}return updatedItem.effects=(_a=item.actor)!=null&&_a.isToken?updatedAEs:aeDiff.updated,updatedItem},"#migrateItem"),_migrateActor=new WeakSet,migrateActor_fn=__name2(async function(migrations,actor,options={}){const{pack}=options,baseActor=actor.toObject(),updatedActor=await(()=>{try{return this.getUpdatedActor(baseActor,migrations)}catch(error){return error instanceof Error&&console.error(`Error thrown while migrating ${actor.uuid}: ${error.message}`),null}})();if(!updatedActor)return null;const baseItems=[...baseActor.items],baseAEs=[...baseActor.effects],updatedItems=[...updatedActor.items],updatedAEs=[...updatedActor.effects],itemDiff=this.diffCollection(baseItems,updatedItems);if(itemDiff.deleted.length>0)try{const finalDeleted=itemDiff.deleted.filter(deletedId=>actor.items.some(item=>item.id===deletedId));await actor.deleteEmbeddedDocuments("Item",finalDeleted,{noHook:!0,pack})}catch(error){console.warn(error)}const aeDiff=this.diffCollection(baseAEs,updatedAEs);if(aeDiff.deleted.length>0)try{const finalDeleted=aeDiff.deleted.filter(deletedId=>actor.effects.some(effect=>effect.id===deletedId));await actor.deleteEmbeddedDocuments("ActiveEffect",finalDeleted,{noHook:!0,pack})}catch(error){console.warn(error)}if(itemDiff.inserted.length>0)try{await actor.createEmbeddedDocuments("Item",itemDiff.inserted,{noHook:!0,pack})}catch(error){console.warn(error)}for(const updated of updatedItems){const original=baseActor.items.find(i=>i._id===updated._id);if(!original)continue;if(this.diffCollection(original.effects,updated.effects).deleted.length>0)try{await Item.updateDocuments([updated],{parent:actor,diff:!1,recursive:!1,pack})}catch(error){console.warn(error)}}return updatedActor.items=actor.isToken?updatedItems:itemDiff.updated,updatedActor},"#migrateActor"),_migrateWorldJournalEntry=new WeakSet,migrateWorldJournalEntry_fn=__name2(async function(journalEntry,migrations){if(migrations.some(migration=>!!migration.updateJournalEntry))try{const updated=await this.getUpdatedJournalEntry(journalEntry.toObject(),migrations),changes=diffObject(journalEntry.toObject(),updated);Object.keys(changes).length>0&&await journalEntry.update(changes,{noHook:!0})}catch(error){console.warn(error)}},"#migrateWorldJournalEntry"),_migrateWorldMacro=new WeakSet,migrateWorldMacro_fn=__name2(async function(macro,migrations){if(migrations.some(migration=>!!migration.updateMacro))try{const updatedMacro=await this.getUpdatedMacro(macro.toObject(),migrations),changes=diffObject(macro.toObject(),updatedMacro);Object.keys(changes).length>0&&await macro.update(changes,{noHook:!0})}catch(error){console.warn(error)}},"#migrateWorldMacro"),_migrateWorldTable=new WeakSet,migrateWorldTable_fn=__name2(async function(table,migrations){if(migrations.some(migration=>!!migration.updateTable))try{const updatedMacro=await this.getUpdatedTable(table.toObject(),migrations),changes=diffObject(table.toObject(),updatedMacro);Object.keys(changes).length>0&&table.update(changes,{noHook:!0})}catch(error){console.warn(error)}},"#migrateWorldTable"),_migrateSceneToken=new WeakSet,migrateSceneToken_fn=__name2(async function(token,migrations){if(!migrations.some(migration=>!!migration.updateToken))return token.toObject();try{const updatedToken=await this.getUpdatedToken(token,migrations),changes=diffObject(token.toObject(),updatedToken);if(Object.keys(changes).length>0)try{await token.update(changes,{noHook:!0})}catch(error){console.warn(error)}return updatedToken}catch(error){return console.error(error),null}},"#migrateSceneToken"),_migrateUser=new WeakSet,migrateUser_fn=__name2(async function(user,migrations){if(migrations.some(migration=>!!migration.updateUser))try{const baseUser=user.toObject(),updatedUser=await this.getUpdatedUser(baseUser,migrations),changes=diffObject(user.toObject(),updatedUser);Object.keys(changes).length>0&&await user.update(changes,{noHook:!0})}catch(error){console.error(error)}},"#migrateUser");class MigrationBase{constructor(){__publicField(this,"version",this.constructor.version),__publicField(this,"requiresFlush",!1)}}__name(MigrationBase,"MigrationBase"),__name2(MigrationBase,"MigrationBase"),__publicField(MigrationBase,"version");class Migration600Reach extends MigrationBase{async updateItem(item){item.type==="ancestry"&&(item.system.reach=5)}}__name(Migration600Reach,"Migration600Reach"),__name2(Migration600Reach,"Migration600Reach"),__publicField(Migration600Reach,"version",.6);const _Migration601SplitEffectCompendia=__name(class extends MigrationBase{async updateItem(item){var _a;typeof item.system.description.value=="string"&&(item.system.description.value=item.system.description.value.replace(/(@Compendium\[pf2e\.)(spell-effects)(\.)([a-zA-Z0-9]{16})(\]{.*?})/g,(_full,first,_replace,dot,itemId,rest)=>{const packName=objectHasKey(_Migration601SplitEffectCompendia.effectLocations,itemId)?_Migration601SplitEffectCompendia.effectLocations[itemId]:"??";return first+packName+dot+itemId+rest})),typeof((_a=item.flags.core)==null?void 0:_a.sourceId)=="string"&&(item.flags.core.sourceId=item.flags.core.sourceId.replace(/(Compendium\.pf2e\.)(spell-effects)(\.)([a-zA-Z0-9]{16})/g,(_full,first,_replace,dot,itemId)=>{const packName=objectHasKey(_Migration601SplitEffectCompendia.effectLocations,itemId)?_Migration601SplitEffectCompendia.effectLocations[itemId]:"??";return first+packName+dot+itemId}))}async migrate(){for(const macro of game.macros)macro._source.command=macro._source.command.replace(/(Compendium\.pf2e\.)(spell-effects)(\.)([a-zA-Z0-9]{16})/g,(_full,first,_replace,dot,itemId)=>{const packName=objectHasKey(_Migration601SplitEffectCompendia.effectLocations,itemId)?_Migration601SplitEffectCompendia.effectLocations[itemId]:"??";return first+packName+dot+itemId})}},"_Migration601SplitEffectCompendia");let Migration601SplitEffectCompendia=_Migration601SplitEffectCompendia;__name2(Migration601SplitEffectCompendia,"Migration601SplitEffectCompendia"),__publicField(Migration601SplitEffectCompendia,"version",.601),__publicField(Migration601SplitEffectCompendia,"effectLocations",{QuZ5frBMJF3gi7RY:"consumable-effects","7z1iY4AaNEAIKuAU":"consumable-effects","1mKjaWC65KWPuFR4":"consumable-effects",mi4Md1fB2XThCand:"consumable-effects",R106i7WCXvHLGMTu:"consumable-effects",kkDbalYEavzRpYlp:"consumable-effects",qVKrrKpTghgMIuGH:"consumable-effects",HeRHBo2NaKy5IxhU:"consumable-effects",tTBJ33UGtzXjWOJp:"consumable-effects",xVAdPzFaSvJXPMKv:"consumable-effects",fYjvLx9DHIdCHdDx:"consumable-effects",kwD0wuW5Ndkc9YXB:"consumable-effects",fIpzDpuwLdIS4tW5:"consumable-effects","1ouUo8lLK6H79Rqh":"consumable-effects",xFQRiVU6h8EA6Lw9:"consumable-effects",MI5OCkF9IXmD2lPF:"consumable-effects",S4MZzALqFoXJsr6o:"consumable-effects",wFF0SZs1Hcf87Kk1:"consumable-effects","2C1HuKDQDGFZuv7l":"consumable-effects",q1EhQ716bPSgJVnC:"consumable-effects",eh7EqmDBDW30ShCu:"consumable-effects",wTZnKkT0K4Tdy8mD:"consumable-effects",Cxa7MdgMCUoMqbKm:"consumable-effects",PeuUz7JaabCgl6Yh:"consumable-effects",lNWACCNe9RYgaFxb:"consumable-effects",j9zVZwRBVAcnpEkE:"consumable-effects",qit1mLbJUyRTYcPU:"consumable-effects",jaBMZKdoywOTrQvP:"consumable-effects",RT1BxXrbbGgk40Ti:"consumable-effects",ztxW3lBPRcesF7wK:"consumable-effects","7vCenP9j6FuHRv5C":"consumable-effects","7UL8belWmo7U5YGM":"consumable-effects",bcxVvIbuZWOvsKcA:"consumable-effects","4tepFOJLhZSelPoa":"consumable-effects",qwoLV4awdezlEJ60:"consumable-effects",GBBjw61g4ekJymT0:"consumable-effects",vFOr2JAJxiVvvn2E:"consumable-effects",BV8RPntjc9FUzD3g:"consumable-effects",kgotU0sFmtAHYySB:"consumable-effects",VCypzSu659eC6jNi:"consumable-effects",wyLEew86nhNUXASu:"consumable-effects",Wa4317cqU4lJ8vAQ:"consumable-effects",Z9oPh462q82IYIZ6:"consumable-effects",EpB7yJPEuG6ez4z3:"consumable-effects",PpLxndUSgzgs6dd0:"consumable-effects",lPRuIRbu0rHBkoKY:"consumable-effects",Yxssrnh9UZJAM0V7:"consumable-effects","9MeHc072G4L8AJkp":"consumable-effects",xLilBqqf34ZJYO9i:"consumable-effects","1l139A2Qik4lBHKO":"consumable-effects","2PNo8u4wxSbz5WEs":"consumable-effects",fUrZ4xcMJz0CfTyG:"consumable-effects","6A8jsLR7upLGuRiv":"consumable-effects",Zdh2uO1vVYJmaqld:"consumable-effects",Mf9EBLhYmZerf0nS:"consumable-effects",ModBoFdCi7YQU4gP:"consumable-effects",W3xQBLj5hLOtb6Tj:"consumable-effects","2Bds6d4UGQZqYSZM":"consumable-effects","6PNLBIdlqqWNCFMy":"consumable-effects","988f6NpOo4YzFzIr":"consumable-effects",VPtsrpbP0AE642al:"consumable-effects",MCny5ohCGf09a7Wl:"consumable-effects",RRusoN3HEGnDO1Dg:"consumable-effects",thOpQunbQr77XWdF:"consumable-effects","9keegq0GdS1eSrNr":"consumable-effects",jw6Tr9FbErjLAFLQ:"consumable-effects","5xgapIXn5DwbXHKh":"consumable-effects",t7VUJHSUT6bkVUjg:"consumable-effects",yrbz0rZzp8aZEqbv:"consumable-effects","16tOZk4qy329s2aK":"consumable-effects",zd85Ny1RS46OL0TD:"consumable-effects",oAewXfq9c0ecaSfw:"consumable-effects",dpIrjd1UPY7EnWUD:"consumable-effects","9FfFhu2kl2wMTsiI":"consumable-effects",v5Ht1V4MZvRKRBjL:"consumable-effects",TkRuKKYyPHTGPfgf:"consumable-effects",XrlChFETfe8avLsX:"consumable-effects",qzRcSQ0HTTp58hV2:"consumable-effects",TsWUTODTVi487SEz:"consumable-effects","5Gof60StUppR2Xn9":"consumable-effects",mG6S6zm6hxaF7Tla:"consumable-effects",zlSNbMDIlTOpcO8R:"consumable-effects",b9DTIJyBT8kvIBpj:"consumable-effects",PEPOd38VfVzQMKG5:"consumable-effects","1xHHvQlW4pRR89qj":"consumable-effects",AMhUb42NAJ1aisZp:"consumable-effects",kwOtHtmlH69ctK0O:"consumable-effects",VrYfR2WuyA15zFhq:"consumable-effects",OAN5Fj21PJPhIqRU:"consumable-effects",e6dXfbKzv5sNr1zh:"consumable-effects",Hnt3Trd7TiFICB06:"consumable-effects",p2aGtovaY1feytws:"equipment-effects",yvabfuAO74pvH8hh:"equipment-effects",etJW0w4CiSFgMrWP:"equipment-effects",vOU4Yv2MyAfYBbmF:"equipment-effects",FbFl95WRpzrrijh3:"equipment-effects",iK6JeCsZwm5Vakks:"equipment-effects",P7Y7pO2ulZ5wBgxU:"equipment-effects",cg5qyeMJUh6b4fta:"equipment-effects",fbSFwwp60AuDDKpK:"equipment-effects","88kqcDmsoAEddzUt":"equipment-effects",lLP56tbG689TNKW5:"equipment-effects",PeiuJ951kkBPTCSM:"equipment-effects",G0lG7IIZnCZtYi6v:"equipment-effects",gDefAEEMXVVZgqXH:"equipment-effects",uXEp1rPU5fY4OiBf:"equipment-effects",Uadsb25G18pKdZ2e:"equipment-effects",viCX9fZzTWGuoO85:"equipment-effects",eeGWTG9ZAha4IIOY:"equipment-effects",ioGzmVSmMGXWWBYb:"equipment-effects",pAMyEbJzWBoYoGhs:"equipment-effects","7dLsA9PAb5ij7Bc6":"equipment-effects",NE7Fm5YnUhD4ySX3:"equipment-effects","8ersuvNJXX00XaIQ":"equipment-effects",EpNflrkmWzQ0lEb4:"equipment-effects",iEkH8BKLMUa2wxLX:"equipment-effects",bP40jr6wE6MCsRvY:"equipment-effects",eSIYyxi6uTKiP6W5:"equipment-effects",E4B02mJmNexQLa8F:"equipment-effects","3O5lvuX4VHqtpCkU":"equipment-effects",ah41XCrV4LFsVyzl:"equipment-effects",W3BCLbX6j1IqL0uB:"equipment-effects",zqKzWGLODgIvtiKf:"equipment-effects",lBMhT2W2raYMa8JS:"equipment-effects","5uK3fmGlfJrbWQz4":"equipment-effects",i0tm2ZHekp7rGGR3:"equipment-effects",Zb8RYgmzCI6fQE0o:"equipment-effects",QapoFh0tbUgMwSIB:"equipment-effects",UlalLihKzDxcOdXL:"equipment-effects",lO95TwgihBdTilAB:"equipment-effects","9PASRixhNM0ogqmG":"equipment-effects","7MgpgF8tOXOiDEwv":"equipment-effects","1S51uIRb9bnZtpFU":"equipment-effects","1nCwQErK6hpkNvfw":"feat-effects","5IGz4iheaiUWm5KR":"feat-effects",uFYvW3kFP9iyNfVX:"feat-effects",CgxYa0lrLUjS2ZhI:"feat-effects",nwkYZs6YwXYAJ4ps:"feat-effects",qUowHpn79Dpt1hVn:"feat-effects",RozqjLocahvQWERr:"feat-effects",tPKXLtDJ3bzJcXlv:"feat-effects",gYpy9XBPScIlY93p:"feat-effects",Im5JBInybWFbHEYS:"feat-effects",BCyGDKcplkJiSAKJ:"feat-effects",PMHwCrnh9W4sMu5b:"feat-effects",pf9yvKNg6jZLrE30:"feat-effects",eeAlh6edygcZIz9c:"feat-effects",b2kWJuCPj1rDMdwz:"feat-effects",UQ7vZgmfK0VSFS8A:"feature-effects",s1tulrmW6teTFjVd:"feature-effects",aKRo5TIhUtu0kyEr:"feature-effects",yfbP64r4a9e5oyli:"feature-effects",n1vhmOd7aNiuR3nk:"feature-effects",FNTTeJHiK6iOjrSq:"feature-effects","3gGBZHcUFsHLJeQH":"feature-effects",rJpkKaPRGaH0pLse:"feature-effects","9AUcoY48H5LrVZiF":"feature-effects",KVbS7AbhQdeuA0J6:"feature-effects","6fb15XuSV4TNuVAT":"feature-effects",vguxP8ukwVTWWWaA:"feature-effects",SVGW8CLKwixFlnTv:"feature-effects",ruRAfGJnik7lRavk:"feature-effects",uBJsxCzNhje8m8jj:"feature-effects","7BFd8A9HFrmg6vwL":"feature-effects",z3uyCMBddrPK5umr:"feature-effects",Nv70aqcQgCBpDYp8:"feature-effects",OqH6IaeOwRWkGPrk:"feature-effects",Lb4q2bBAgxamtix5:"feature-effects",Gqy7K6FnbLtwGpud:"spell-effects","41WThj17MZBXTO2X":"spell-effects",sPCWrhUHqlbGhYSD:"spell-effects","3qHKBDF7lrHw8jFK":"spell-effects",l9HRQggofFGIxEse:"spell-effects",beReeFroAx24hj83:"spell-effects",qkwb5DD3zmKwvbk0:"spell-effects",GnWkI3T3LYRlm3X8:"spell-effects",dWbg2gACxMkSnZag:"spell-effects",Jemq5UknGdMO7b73:"spell-effects",LXf1Cqi1zyo4DaLv:"spell-effects"});class Migration602UpdateDiehardFeat extends MigrationBase{constructor(){super(),__publicField(this,"requiresFlush",!0),__privateAdd(this,_diehardPromise,void 0),__privateSet(this,_diehardPromise,fromUuid("Compendium.pf2e.feats-srd.I0BhPWqYf1bbzEYg"))}async updateActor(actorData){const diehard=actorData.items.find(itemData=>itemData.system.slug==="diehard"&&itemData.type==="feat");if(actorData.type==="character"&&diehard!==void 0){actorData.system.attributes.dying.max=4;const diehardIndex=actorData.items.indexOf(diehard),newDiehard=await __privateGet(this,_diehardPromise);if(!(newDiehard instanceof FeatPF2e))throw Error("PF2E System | Expected item not found in Compendium");actorData.items.splice(diehardIndex,1,newDiehard.toObject())}}}__name(Migration602UpdateDiehardFeat,"Migration602UpdateDiehardFeat"),__name2(Migration602UpdateDiehardFeat,"Migration602UpdateDiehardFeat"),_diehardPromise=new WeakMap,__publicField(Migration602UpdateDiehardFeat,"version",.602);class Migration603ResetQuickRollDefault extends MigrationBase{async updateUser(userData){const flags=userData.flags;isObject(flags.PF2e)&&isObject(flags.PF2e.settings)&&typeof flags.PF2e.settings.quickD20roll=="boolean"&&(flags.PF2e.settings.quickD20roll=!1)}}__name(Migration603ResetQuickRollDefault,"Migration603ResetQuickRollDefault"),__name2(Migration603ResetQuickRollDefault,"Migration603ResetQuickRollDefault"),__publicField(Migration603ResetQuickRollDefault,"version",.603);class Migration604FixClassItem extends MigrationBase{async updateItem(item){item.type==="class"&&(Array.isArray(item.system.ancestryFeatLevels)&&(item.system.ancestryFeatLevels={value:item.system.ancestryFeatLevels}),Array.isArray(item.system.classFeatLevels)&&(item.system.classFeatLevels={value:item.system.classFeatLevels}),Array.isArray(item.system.skillFeatLevels)&&(item.system.skillFeatLevels={value:item.system.skillFeatLevels}),Array.isArray(item.system.generalFeatLevels)&&(item.system.generalFeatLevels={value:item.system.generalFeatLevels}),Array.isArray(item.system.skillIncreaseLevels)&&(item.system.skillIncreaseLevels={value:item.system.skillIncreaseLevels}),Array.isArray(item.system.abilityBoostLevels)&&(item.system.abilityBoostLevels={value:item.system.abilityBoostLevels}))}}__name(Migration604FixClassItem,"Migration604FixClassItem"),__name2(Migration604FixClassItem,"Migration604FixClassItem"),__publicField(Migration604FixClassItem,"version",.604);class Migration605CatchUpToTemplateJSON extends MigrationBase{addEffects(entityData){Array.isArray(entityData.effects)||(entityData.effects=[])}async updateActor(actorData){if(this.addEffects(actorData),actorData.type==="character"||actorData.type==="npc"){if(typeof actorData.system.attributes.hp.max=="string"){const newMax=parseInt(actorData.system.attributes.hp.max,10);Number.isInteger(newMax)&&(actorData.system.attributes.hp.max=newMax)}if(typeof actorData.system.attributes.hp.value=="string"){const newValue=parseInt(actorData.system.attributes.hp.value,10);Number.isInteger(newValue)&&(actorData.system.attributes.hp.value=newValue)}if(typeof actorData.system.details.level.value=="string"){const newLevel=parseInt(actorData.system.details.level.value,10);Number.isInteger(newLevel)&&(actorData.system.details.level.value=newLevel)}"tempmax"in actorData.system.attributes.hp&&delete actorData.system.attributes.hp.tempmax,"special"in actorData.system.attributes.speed&&delete actorData.system.attributes.speed.special}}async updateItem(itemData,actorData){this.addEffects(itemData),!itemData.system.slug&&actorData&&(itemData.system.slug=null),Array.isArray(itemData.system.rules)||(itemData.system.rules=[]);const traits=itemData.system.traits;if(traits&&!traits.custom&&(traits.custom=""),traits&&!traits.rarity&&(traits.rarity={value:"common"}),isPhysicalData(itemData)&&!itemData.system.identification){const withoutIdentifyData=itemData.system;withoutIdentifyData.identification.status="identified"}itemData.type==="spell"&&!itemData.system.hasCounteractCheck&&(itemData.system.hasCounteractCheck={value:!1}),itemData.type==="lore"&&"featType"in itemData.system&&delete itemData.system.featType,itemData.type==="action"&&"skill_requirements"in itemData.system&&delete itemData.system.skill_requirements,itemData.type==="action"&&"skill_requirement"in itemData.system&&itemData.system.skill_requirement}}__name(Migration605CatchUpToTemplateJSON,"Migration605CatchUpToTemplateJSON"),__name2(Migration605CatchUpToTemplateJSON,"Migration605CatchUpToTemplateJSON"),__publicField(Migration605CatchUpToTemplateJSON,"version",.605);class Migration606SignatureSpells extends MigrationBase{async updateItem(item){if(item.type==="spellcastingEntry"){const data=item.system;data.signatureSpells||(data.signatureSpells={value:[]})}}}__name(Migration606SignatureSpells,"Migration606SignatureSpells"),__name2(Migration606SignatureSpells,"Migration606SignatureSpells"),__publicField(Migration606SignatureSpells,"version",.606);class Migration607MeleeItemDamageRolls extends MigrationBase{async updateItem(itemData){if(itemData.type==="melee"&&Array.isArray(itemData.system.damageRolls)){const damageRolls={};itemData.system.damageRolls.forEach(roll=>{const key=randomID(20);damageRolls[key]=roll}),itemData.system.damageRolls=damageRolls}}}__name(Migration607MeleeItemDamageRolls,"Migration607MeleeItemDamageRolls"),__name2(Migration607MeleeItemDamageRolls,"Migration607MeleeItemDamageRolls"),__publicField(Migration607MeleeItemDamageRolls,"version",.607);class Migration608DeletePersistedKits extends MigrationBase{async updateItem(itemData,actorData){if(actorData&&itemData.type==="kit"){const index=actorData.items.indexOf(itemData);actorData.items.splice(index,1)}}}__name(Migration608DeletePersistedKits,"Migration608DeletePersistedKits"),__name2(Migration608DeletePersistedKits,"Migration608DeletePersistedKits"),__publicField(Migration608DeletePersistedKits,"version",.608);class Migration609LootActorTraits extends MigrationBase{async updateActor(source){if(source.type==="loot"&&source.system.traits&&"traits"in source.system.traits){const systemData=source.system;systemData.traits||(systemData.traits={rarity:{value:"common"},size:{value:"med"},traits:{value:[]},di:{value:[]},dr:[],dv:[],ci:[]})}}}__name(Migration609LootActorTraits,"Migration609LootActorTraits"),__name2(Migration609LootActorTraits,"Migration609LootActorTraits"),__publicField(Migration609LootActorTraits,"version",.609);class Migration610SetHeritageFeatType extends MigrationBase{async updateItem(source){var _a;const itemTraits=(_a=source.system.traits)==null?void 0:_a.value;if(source.type==="feat"&&itemTraits?.includes("heritage")){const{system:system2}=source,featType="featType"in system2&&isObject(system2.featType)&&"value"in system2.featType&&typeof system2.featType.value=="string"?system2.featType:{value:""};featType.value="heritage";const index=itemTraits.indexOf("heritage");itemTraits.splice(index,1)}}}__name(Migration610SetHeritageFeatType,"Migration610SetHeritageFeatType"),__name2(Migration610SetHeritageFeatType,"Migration610SetHeritageFeatType"),__publicField(Migration610SetHeritageFeatType,"version",.61);class Migration611UpdateToughnessMountainsStoutness extends MigrationBase{constructor(){super(),__publicField(this,"requiresFlush",!0),__privateAdd(this,_featSlugs,["mountains-stoutness","mountain-s-stoutness","toughness"]),__privateAdd(this,_featsPromise,void 0),__privateSet(this,_featsPromise,game.packs.get("pf2e.feats-srd").getDocuments())}async updateActor(actorData){if(actorData.type!=="character")return;const oldFeatsData=actorData.items.filter(itemData=>__privateGet(this,_featSlugs).includes(itemData.system.slug??"")&&itemData.type==="feat");for(const oldFeatData of oldFeatsData){oldFeatData.system.slug==="mountain-s-stoutness"&&(oldFeatData.system.slug="mountains-stoutness");const newFeat=oldFeatData.system.slug==="toughness"?(await __privateGet(this,_featsPromise)).find(feat=>feat.slug==="toughness"):(await __privateGet(this,_featsPromise)).find(feat=>feat.slug==="mountains-stoutness");if(!(newFeat instanceof FeatPF2e))throw ErrorPF2e("Expected item not found in Compendium");newFeat._source.system.location=oldFeatData.system.location;const oldFeatIndex=actorData.items.indexOf(oldFeatData);actorData.items.splice(oldFeatIndex,1,newFeat.toObject())}}}__name(Migration611UpdateToughnessMountainsStoutness,"Migration611UpdateToughnessMountainsStoutness"),__name2(Migration611UpdateToughnessMountainsStoutness,"Migration611UpdateToughnessMountainsStoutness"),_featSlugs=new WeakMap,_featsPromise=new WeakMap,__publicField(Migration611UpdateToughnessMountainsStoutness,"version",.611);class Migration612NormalizeRarities extends MigrationBase{async updateActor(actorData){const traitsRaw=actorData.system.traits;if(actorData.type==="familiar"||!traitsRaw)return;const traitsAndOtherMiscellany=traitsRaw;"rarity"in traitsAndOtherMiscellany||(traitsAndOtherMiscellany.rarity={value:"common"});const rarities=["common","uncommon","rare","unique"];for(const rarity of rarities){const{traits}=traitsAndOtherMiscellany;if(traits?.value.includes(rarity)){const index=traits.value.indexOf(rarity);traits.value.splice(index,1),traitsAndOtherMiscellany.rarity={value:rarity}}}}}__name(Migration612NormalizeRarities,"Migration612NormalizeRarities"),__name2(Migration612NormalizeRarities,"Migration612NormalizeRarities"),__publicField(Migration612NormalizeRarities,"version",.612);class Migration613RemoveAmmoCharges extends MigrationBase{async updateItem(itemData){itemData.type==="consumable"&&itemData.system.consumableType.value==="ammo"&&(itemData.system.charges.value=0,itemData.system.charges.max=0)}}__name(Migration613RemoveAmmoCharges,"Migration613RemoveAmmoCharges"),__name2(Migration613RemoveAmmoCharges,"Migration613RemoveAmmoCharges"),__publicField(Migration613RemoveAmmoCharges,"version",.613);class Migration614NumifyMeleeBonuses extends MigrationBase{async updateItem(itemData){itemData.type==="melee"&&(itemData.system.bonus={value:Number(itemData.system.bonus.value)})}}__name(Migration614NumifyMeleeBonuses,"Migration614NumifyMeleeBonuses"),__name2(Migration614NumifyMeleeBonuses,"Migration614NumifyMeleeBonuses"),__publicField(Migration614NumifyMeleeBonuses,"version",.614);class Migration615RemoveInstinctTrait extends MigrationBase{async updateItem(itemData){var _a;const traits=itemData.system.traits;traits&&(typeof traits.value=="string"?traits.value=[]:traits.value=(_a=traits.value)==null?void 0:_a.filter(trait=>trait!=="instinct"))}}__name(Migration615RemoveInstinctTrait,"Migration615RemoveInstinctTrait"),__name2(Migration615RemoveInstinctTrait,"Migration615RemoveInstinctTrait"),__publicField(Migration615RemoveInstinctTrait,"version",.615);class Migration616MigrateFeatPrerequisites extends MigrationBase{async updateItem(source){if(source.type==="feat"){const update=[],prerequisites=source.system.prerequisites;if(prerequisites.value){if(typeof prerequisites.value=="string")update.push({value:prerequisites.value});else if(Array.isArray(prerequisites.value))for(const p of prerequisites.value)p&&update.push({value:isObject(p)&&typeof p.value=="string"?p.value:String(p)})}else if(Array.isArray(prerequisites))for(const p of prerequisites)p&&update.push({value:p?.value?p.value:p});source.system.prerequisites={value:update}}}}__name(Migration616MigrateFeatPrerequisites,"Migration616MigrateFeatPrerequisites"),__name2(Migration616MigrateFeatPrerequisites,"Migration616MigrateFeatPrerequisites"),__publicField(Migration616MigrateFeatPrerequisites,"version",.616);class Migration617FixUserFlags extends MigrationBase{async updateUser(source){var _a,_b;const flags=source.flags,settings=(_a=flags.PF2e)==null?void 0:_a.settings;if(isObject(settings)&&typeof settings.color=="string"){const uiTheme=settings.color??"blue",showRollDialogs=!settings.quickD20roll;flags.pf2e??(flags.pf2e={}),flags.pf2e.settings={uiTheme,showEffectPanel:((_b=flags.pf2e)==null?void 0:_b.showEffectPanel)??!0,showRollDialogs},delete flags.PF2e,flags["-=PF2e"]=null}}}__name(Migration617FixUserFlags,"Migration617FixUserFlags"),__name2(Migration617FixUserFlags,"Migration617FixUserFlags"),__publicField(Migration617FixUserFlags,"version",.617);class Migration618MigrateItemImagePaths extends MigrationBase{constructor(){super(...arguments),__privateAdd(this,_IMAGE_PATHS,{"systems/pf2e/icons/equipment/weapons/blowgun.png":"systems/pf2e/icons/equipment/weapons/blowgun.jpg","systems/pf2e/icons/equipment/weapons/trident.png":"systems/pf2e/icons/equipment/weapons/trident.jpg","systems/pf2e/icons/equipment/weapons/longsword.png":"systems/pf2e/icons/equipment/weapons/longsword.jpg","systems/pf2e/icons/equipment/weapons/composite-longbow.png":"systems/pf2e/icons/equipment/weapons/composite-longbow.jpg","systems/pf2e/icons/equipment/weapons/composite-shortbow.png":"systems/pf2e/icons/equipment/weapons/composite-shortbow.jpg","systems/pf2e/icons/equipment/weapons/dagger.png":"systems/pf2e/icons/equipment/weapons/dagger.jpg","systems/pf2e/icons/equipment/weapons/katar.png":"systems/pf2e/icons/equipment/weapons/katar.jpg","systems/pf2e/icons/equipment/weapons/kukri.png":"systems/pf2e/icons/equipment/weapons/kukri.jpg","systems/pf2e/icons/equipment/weapons/shortbow.png":"systems/pf2e/icons/equipment/weapons/shortbow.jpg","systems/pf2e/icons/equipment/weapons/scimitar.png":"systems/pf2e/icons/equipment/weapons/scimitar.jpg","systems/pf2e/icons/equipment/weapons/hatchet.png":"systems/pf2e/icons/equipment/weapons/hatchet.jpg","systems/pf2e/icons/equipment/weapons/halfling-sling-staff.png":"systems/pf2e/icons/equipment/weapons/halfling-sling-staff.jpg","systems/pf2e/icons/equipment/weapons/halberd.png":"systems/pf2e/icons/equipment/weapons/halberd.jpg","systems/pf2e/icons/equipment/weapons/shield-spikes.png":"systems/pf2e/icons/equipment/weapons/shield-spikes.jpg","systems/pf2e/icons/equipment/weapons/light-mace.jpg":"systems/pf2e/icons/equipment/weapons/light-mace.jpg","systems/pf2e/icons/equipment/weapons/morningstar.png":"systems/pf2e/icons/equipment/weapons/morningstar.jpg","systems/pf2e/icons/equipment/weapons/sling.png":"systems/pf2e/icons/equipment/weapons/sling.jpg","systems/pf2e/icons/equipment/weapons/main-gauche.png":"systems/pf2e/icons/equipment/weapons/main-gauche.jpg","systems/pf2e/icons/equipment/weapons/bastard-sword.png":"systems/pf2e/icons/equipment/weapons/bastard-sword.jpg","systems/pf2e/icons/equipment/weapons/spear.png":"systems/pf2e/icons/equipment/weapons/spear.jpg","systems/pf2e/icons/equipment/weapons/staff.png":"systems/pf2e/icons/equipment/weapons/staff.jpg","systems/pf2e/icons/equipment/weapons/katana.png":"systems/pf2e/icons/equipment/weapons/katana.jpg","systems/pf2e/icons/equipment/weapons/elven-curve-blade.png":"systems/pf2e/icons/equipment/weapons/elven-curve-blade.jpg","systems/pf2e/icons/equipment/weapons/bo-staff.png":"systems/pf2e/icons/equipment/weapons/bo-staff.jpg","systems/pf2e/icons/equipment/weapons/clan-dagger.png":"systems/pf2e/icons/equipment/weapons/clan-dagger.jpg","systems/pf2e/icons/equipment/weapons/dogslicer.png":"systems/pf2e/icons/equipment/weapons/dogslicer.jpg","systems/pf2e/icons/equipment/weapons/falchion.png":"systems/pf2e/icons/equipment/weapons/falchion.jpg","systems/pf2e/icons/equipment/weapons/fist.png":"systems/pf2e/icons/equipment/weapons/fist.jpg","systems/pf2e/icons/equipment/weapons/gauntlet.png":"systems/pf2e/icons/equipment/weapons/gauntlet.jpg","systems/pf2e/icons/equipment/weapons/gnome-hooked-hammer.png":"systems/pf2e/icons/equipment/weapons/gnome-hooked-hammer.jpg","systems/pf2e/icons/equipment/weapons/greatpick.png":"systems/pf2e/icons/equipment/weapons/greatpick.jpg","systems/pf2e/icons/equipment/weapons/guisarme.png":"systems/pf2e/icons/equipment/weapons/guisarme.jpg","systems/pf2e/icons/equipment/weapons/horsechopper.png":"systems/pf2e/icons/equipment/weapons/horsechopper.jpg","systems/pf2e/icons/equipment/weapons/lance.png":"systems/pf2e/icons/equipment/weapons/lance.jpg","systems/pf2e/icons/equipment/weapons/maul.png":"systems/pf2e/icons/equipment/weapons/maul.jpg","systems/pf2e/icons/equipment/weapons/pick.png":"systems/pf2e/icons/equipment/weapons/pick.jpg","systems/pf2e/icons/equipment/weapons/ranseur.png":"systems/pf2e/icons/equipment/weapons/ranseur.jpg","systems/pf2e/icons/equipment/weapons/sai.png":"systems/pf2e/icons/equipment/weapons/sai.jpg","systems/pf2e/icons/equipment/weapons/sawtooth-saber.png":"systems/pf2e/icons/equipment/weapons/sawtooth-saber.jpg","systems/pf2e/icons/equipment/weapons/shield-bash.png":"systems/pf2e/icons/equipment/weapons/shield-bash.jpg","systems/pf2e/icons/equipment/weapons/shield-boss.png":"systems/pf2e/icons/equipment/weapons/shield-boss.jpg","systems/pf2e/icons/equipment/weapons/shuriken.png":"systems/pf2e/icons/equipment/weapons/shuriken.jpg","systems/pf2e/icons/equipment/weapons/spiked-gauntlet.png":"systems/pf2e/icons/equipment/weapons/spiked-gauntlet.jpg","systems/pf2e/icons/equipment/weapons/broom.png":"systems/pf2e/icons/equipment/held-items/broom-of-flying.jpg","systems/pf2e/icons/equipment/weapons/cutlass.png":"systems/pf2e/icons/equipment/weapons/scimitar.jpg","systems/pf2e/icons/equipment/weapons/scalpel.png":"systems/pf2e/icons/equipment/weapons/war-razor.jpg","systems/pf2e/icons/equipment/weapons/cane.png":"systems/pf2e/icons/equipment/weapons/cane.jpg"})}async updateItem(itemData){itemData.img=__privateGet(this,_IMAGE_PATHS)[itemData.img]??itemData.img}}__name(Migration618MigrateItemImagePaths,"Migration618MigrateItemImagePaths"),__name2(Migration618MigrateItemImagePaths,"Migration618MigrateItemImagePaths"),_IMAGE_PATHS=new WeakMap,__publicField(Migration618MigrateItemImagePaths,"version",.618);const LEGIT_TRADITIONS=["arcane","divine","occult","primal","focus","ritual","halcyon",""];function makeLowercase(value){return value.toLowerCase()}__name(makeLowercase,"makeLowercase"),__name2(makeLowercase,"makeLowercase");class Migration619TraditionLowercaseAndRemoveWandScroll extends MigrationBase{async updateItem(item,actorData){if(!actorData||item.type!=="spellcastingEntry")return;const tradition=item.system.tradition;if(tradition.value=makeLowercase(tradition.value),tupleHasValue(LEGIT_TRADITIONS,item.system.tradition.value))return;const highestTradition=actorData.items.filter(itemData=>itemData.type==="spellcastingEntry").reduce((prev,current)=>{if(tupleHasValue(LEGIT_TRADITIONS,current.system.tradition.value)){const value=current.system.spelldc.value??0;if(value>prev.value)return{name:current.system.tradition.value,value}}return prev},{name:"arcane",value:0});tradition.value=highestTradition.name}}__name(Migration619TraditionLowercaseAndRemoveWandScroll,"Migration619TraditionLowercaseAndRemoveWandScroll"),__name2(Migration619TraditionLowercaseAndRemoveWandScroll,"Migration619TraditionLowercaseAndRemoveWandScroll"),__publicField(Migration619TraditionLowercaseAndRemoveWandScroll,"version",.619);class Migration620RenameToWebp extends MigrationBase{constructor(){super(...arguments),__publicField(this,"regexp",/(\/?systems\/pf2e\/[^"]+)\.(?:jpg|png)\b/)}renameToWebP(imgPath){return typeof imgPath=="string"&&this.regexp.test(imgPath)?imgPath.replace(this.regexp,"$1.webp"):imgPath?.replace("icons/svg/mystery-man.svg","systems/pf2e/icons/default-icons/mystery-man.svg")}isABCK(itemData){return["ancestry","background","class","kit"].includes(itemData.type)}async updateActor(actorData){var _a;actorData.img=this.renameToWebP(actorData.img),typeof((_a=actorData.prototypeToken)==null?void 0:_a.texture.src)=="string"&&(actorData.prototypeToken.texture.src=this.renameToWebP(actorData.prototypeToken.texture.src));for(const effect of actorData.effects??[])effect.icon=this.renameToWebP(effect.icon);if(actorData.type==="character"){const details=actorData.system.details;details.deity&&(details.deity.image=this.renameToWebP(details.deity.image))}}async updateItem(itemData){itemData.img=this.renameToWebP(itemData.img);for(const effect of itemData.effects??[])effect.icon=this.renameToWebP(effect.icon);if(this.isABCK(itemData)){const embedData=itemData.system.items,embeds=Object.values(embedData).filter(maybeEmbed=>!!maybeEmbed);for(const embed of embeds)if(embed.img=this.renameToWebP(embed.img),"items"in embed&&embed.items){const deepEmbeds=Object.values(embed.items).filter(maybeDeepEmbed=>!!maybeDeepEmbed);for(const deepEmbed of deepEmbeds)deepEmbed.img=this.renameToWebP(deepEmbed.img)}}}async updateMacro(macroData){macroData.img=this.renameToWebP(macroData.img)}async updateTable(tableData){tableData.img=this.renameToWebP(tableData.img);for(const result of tableData.results)result.img=this.renameToWebP(result.img)}async updateToken(tokenData){tokenData.texture.src=this.renameToWebP(tokenData.texture.src),tokenData.effects=tokenData.effects.filter(texture=>!this.regexp.test(texture))}async updateUser(userData){userData.img=this.renameToWebP(userData.img)}}__name(Migration620RenameToWebp,"Migration620RenameToWebp"),__name2(Migration620RenameToWebp,"Migration620RenameToWebp"),__publicField(Migration620RenameToWebp,"version",.62);const MAGIC_SCHOOLS=new Set(["abjuration","conjuration","divination","enchantment","evocation","illusion","necromancy","transmutation"]),MAGIC_TRADITIONS=new Set(["arcane","divine","occult","primal"]);class Migration621RemoveConfigSpellSchools extends MigrationBase{constructor(){super(...arguments),__publicField(this,"KEY_MAP",{abj:"abjuration",con:"conjuration",div:"divination",enc:"enchantment",evo:"evocation",ill:"illusion",nec:"necromancy",trs:"transmutation"})}reassignSchool(abbreviation){return objectHasKey(this.KEY_MAP,abbreviation)?this.KEY_MAP[abbreviation]:setHasElement(MAGIC_SCHOOLS,abbreviation)?abbreviation:this.KEY_MAP.evo}async updateItem(itemData){if(itemData.type==="spell"){const school=itemData.system.school??{value:"evocation"};school.value=this.reassignSchool(school.value)}}}__name(Migration621RemoveConfigSpellSchools,"Migration621RemoveConfigSpellSchools"),__name2(Migration621RemoveConfigSpellSchools,"Migration621RemoveConfigSpellSchools"),__publicField(Migration621RemoveConfigSpellSchools,"version",.621);class Migration623NumifyPotencyRunes extends MigrationBase{async updateItem(itemData){if(!(itemData.type==="weapon"||itemData.type==="armor"))return;const potencyRune=itemData.system.potencyRune;potencyRune?potencyRune.value=Number(itemData.system.potencyRune.value)||null:itemData.system.potencyRune={value:null}}}__name(Migration623NumifyPotencyRunes,"Migration623NumifyPotencyRunes"),__name2(Migration623NumifyPotencyRunes,"Migration623NumifyPotencyRunes"),__publicField(Migration623NumifyPotencyRunes,"version",.623);class Migration624RemoveTokenEffectIconFlags extends MigrationBase{async updateActor(actorData){var _a,_b;const flags=actorData.flags;(_b=(_a=flags.pf2e)==null?void 0:_a.token)!=null&&_b.effects&&(delete flags.pf2e.token.effects,"game"in globalThis&&(flags.pf2e.token["-=effects"]=null))}async updateToken(tokenData){var _a,_b;const flags=tokenData.actorData.flags??{};(_b=(_a=flags.pf2e)==null?void 0:_a.token)!=null&&_b.effects&&(delete flags.pf2e.token.effects,"game"in globalThis&&(flags.pf2e.token["-=effects"]=null))}}__name(Migration624RemoveTokenEffectIconFlags,"Migration624RemoveTokenEffectIconFlags"),__name2(Migration624RemoveTokenEffectIconFlags,"Migration624RemoveTokenEffectIconFlags"),__publicField(Migration624RemoveTokenEffectIconFlags,"version",.624);class Migration625EnsurePresenceOfSaves extends MigrationBase{async updateActor(actorData){if(actorData.type!=="npc")return;const saves=actorData.system.saves;for(const key of["fortitude","reflex","will"])saves[key]??(saves[key]={value:0,saveDetail:""}),typeof saves[key].value!="number"&&(saves[key].value=Number(saves[key].value)||0),typeof saves[key].saveDetail!="string"&&(saves[key].saveDetail="")}}__name(Migration625EnsurePresenceOfSaves,"Migration625EnsurePresenceOfSaves"),__name2(Migration625EnsurePresenceOfSaves,"Migration625EnsurePresenceOfSaves"),__publicField(Migration625EnsurePresenceOfSaves,"version",.625);class Migration626UpdateSpellCategory extends MigrationBase{async updateItem(source){var _a,_b;if(source.type!=="spell")return;const systemData=source.system,traditions=systemData.traditions,isFocus=traditions.value.includes("focus"),isRitual=traditions.value.includes("ritual");if(typeof traditions.value=="string"&&(traditions.value=[]),systemData.spellCategorie||systemData.spellCategory){const currentCategory=((_a=systemData.spellCategorie)==null?void 0:_a.value)??((_b=systemData.spellCategory)==null?void 0:_b.value)??"";source.system.category={value:isFocus?"focus":isRitual?"ritual":currentCategory===""?"spell":currentCategory},delete systemData.spellCategorie,delete systemData.spellCategory,"game"in globalThis&&(systemData["-=spellCategorie"]=null,systemData["-=spellCategory"]=null)}["focus","ritual"].includes(source.system.spellType.value)&&(source.system.spellType.value="utility"),traditions.value=traditions.value.filter(tradition=>!["focus","ritual"].includes(tradition))}}__name(Migration626UpdateSpellCategory,"Migration626UpdateSpellCategory"),__name2(Migration626UpdateSpellCategory,"Migration626UpdateSpellCategory"),__publicField(Migration626UpdateSpellCategory,"version",.626);class Migration627LowerCaseSpellSaves extends MigrationBase{async updateItem(itemData){var _a;if(itemData.type!=="spell")return;const saveType=((_a=itemData.system.save.value)==null?void 0:_a.toLowerCase())??"";tupleHasValue(["fortitude","reflex","will"],saveType)?itemData.system.save.value=saveType:itemData.system.save.value=""}}__name(Migration627LowerCaseSpellSaves,"Migration627LowerCaseSpellSaves"),__name2(Migration627LowerCaseSpellSaves,"Migration627LowerCaseSpellSaves"),__publicField(Migration627LowerCaseSpellSaves,"version",.627);class Migration629SetBaseItems extends MigrationBase{constructor(){super(...arguments),__privateAdd(this,_BASE_ARMORS,["explorers-clothing","padded-armor","leather-armor","studded-leather-armor","chain-shirt","hide-armor","scale-mail","chain-mail","breastplate","splint-mail","half-plate","full-plate","hellknight-plate"]),__privateAdd(this,_MAGIC_ARMOR_TO_BASE,{"breastplate-of-command-greater":"breastplate","breastplate-of-command":"breastplate","celestial-armor":"chain-mail","demon-armor":"full-plate",dragonplate:"full-plate","electric-eelskin":"leather-armor","forgotten-shell":"full-plate","ghoul-hide":"hide-armor","glorious-plate":"full-plate","impenetrable-scale":"scale-mail","jerkin-of-liberation":"studded-leather-armor","mail-of-luck":"splint-mail","moonlit-chain":"chain-shirt","noxious-jerkin":"padded-armor","numerian-steel-breastplate":"breastplate","plate-armor-of-the-deep":"full-plate","rhino-hide":"hide-armor","spangled-riders-suit":"studded-leather-armor","victory-plate":"full-plate"}),__privateAdd(this,_BASE_WEAPONS,["adze","aklys","alchemical-bomb","alchemical-crossbow","aldori-dueling-sword","arrows","bastard-sword","battle-axe","battle-lute","bladed-diabolo","bladed-hoop","bladed-scarf","blowgun-darts","blowgun","bo-staff","boarding-axe","boarding-pike","bola","bolts","buugeng","clan-dagger","claw","claw-blade","club","combat-grapnel","composite-longbow","composite-shortbow","crossbow","dagger","daikyu","dart","dogslicer","dwarven-war-axe","elven-curve-blade","exquisite-sword-cane-sheath","exquisite-sword-cane","falchion","fangwire","fauchard","fighting-fan","filchers-fork","fire-poi","fist","flail","gaff","gauntlet","gill-hook","glaive","gnome-flickmace","gnome-hooked-hammer","greataxe","greatclub","greatpick","greatsword","guisarme","halberd","halfling-sling-staff","hand-adze","hand-crossbow","hatchet","heavy-crossbow","horsechopper","javelin","jaws","juggling-club","kama","katana","katar","khakkhara","khopesh","kukri","lance","light-hammer","light-mace","light-pick","longbow","longspear","longsword","mace","machete","main-gauche","mambele","maul","meteor-hammer","monkeys-fist","morningstar","naginata","nightstick","nine-ring-sword","nunchaku","ogre-hook","orc-knuckle-dagger","orc-necksplitter","pick","poi","polytool","ranseur","rapier","rhoka-sword","rungu","sai","sap","sawtooth-saber","scimitar","scorpion-whip","scourge","scythe","shears","shield-bash","shield-boss","shield-spikes","shortbow","shortsword","shuriken","sickle","sling-bullets","sling","spear","spiked-chain","spiked-gauntlet","staff","starknife","stiletto-pen","sword-cane","tamchal-chakram","taw-launcher","tekko-kagi","temple-sword","tengu-gale-blade","throwing-knife","thunder-sling","tricky-pick","trident","urumi","wakizashi","war-flail","war-razor","warhammer","whip-claw","whip","wish-blade","wish-knife","wooden-taws"])}async updateItem(itemData){if(!isPhysicalData(itemData))return;const systemData=itemData.system;!systemData.slug||itemData.type!=="armor"&&itemData.type!=="weapon"||(itemData.type==="armor"?((systemData.slug==="hide"||sluggify(itemData.name)==="hide")&&(systemData.slug="hide-armor"),__privateGet(this,_BASE_ARMORS).includes(systemData.slug??"")?systemData.baseItem=systemData.slug:systemData.slug in __privateGet(this,_MAGIC_ARMOR_TO_BASE)&&(systemData.baseItem=__privateGet(this,_MAGIC_ARMOR_TO_BASE)[systemData.slug])):itemData.type==="weapon"&&(__privateGet(this,_BASE_WEAPONS).includes(systemData.slug)&&(systemData.baseItem=systemData.slug),systemData.slug==="cinderclaw-gauntlet"&&(systemData.baseItem="spiked-gauntlet")))}}__name(Migration629SetBaseItems,"Migration629SetBaseItems"),__name2(Migration629SetBaseItems,"Migration629SetBaseItems"),_BASE_ARMORS=new WeakMap,_MAGIC_ARMOR_TO_BASE=new WeakMap,_BASE_WEAPONS=new WeakMap,__publicField(Migration629SetBaseItems,"version",.629);class Migration630FixTalismanSpelling extends MigrationBase{async updateItem(itemData){if(itemData.type==="consumable"){const consumableType=itemData.system.consumableType;consumableType.value==="talasman"&&(consumableType.value="talisman")}}}__name(Migration630FixTalismanSpelling,"Migration630FixTalismanSpelling"),__name2(Migration630FixTalismanSpelling,"Migration630FixTalismanSpelling"),__publicField(Migration630FixTalismanSpelling,"version",.63);class Migration631FixSenseRuleElementSelector extends MigrationBase{constructor(){super(...arguments),__publicField(this,"SENSE_SELECTOR_CONVERSION",{lowlightvision:"lowLightVision",Tremorsense:"tremorsense"})}async updateItem(source){const rules=source.system.rules;for(const rule of rules)rule.key==="PF2E.RuleElement.Sense"&&typeof rule.selector=="string"&&(rule.selector=this.SENSE_SELECTOR_CONVERSION[rule.selector]??rule.selector)}}__name(Migration631FixSenseRuleElementSelector,"Migration631FixSenseRuleElementSelector"),__name2(Migration631FixSenseRuleElementSelector,"Migration631FixSenseRuleElementSelector"),__publicField(Migration631FixSenseRuleElementSelector,"version",.631);class Migration632DeleteOrphanedSpells extends MigrationBase{constructor(){super(...arguments),__publicField(this,"requiresFlush",!0)}async updateActor(actorData){const spells=actorData.items.filter(itemData=>itemData.type==="spell"),entries=actorData.items.filter(itemData=>itemData.type==="spellcastingEntry"),orphans=spells.filter(spellData=>!entries.some(entryData=>entryData._id===spellData.system.location.value));actorData.items=actorData.items.filter(itemData=>!orphans.some(orphan=>orphan._id===itemData._id))}}__name(Migration632DeleteOrphanedSpells,"Migration632DeleteOrphanedSpells"),__name2(Migration632DeleteOrphanedSpells,"Migration632DeleteOrphanedSpells"),__publicField(Migration632DeleteOrphanedSpells,"version",.632);class Migration633DeleteUnidentifiedTraits extends MigrationBase{async updateItem(itemData){var _a,_b;if(itemData.type==="melee"){const systemData=itemData.system;systemData.identification&&("game"in globalThis?itemData["system.-=identification"]=null:delete systemData.identification)}if(!isPhysicalData(itemData))return;const unidentifiedDataData=(_b=(_a=itemData.system.identification)==null?void 0:_a.unidentified)==null?void 0:_b.data;unidentifiedDataData?.traits&&("game"in globalThis?itemData["system.identification.unidentified.data.-=traits"]=null:delete unidentifiedDataData.traits)}}__name(Migration633DeleteUnidentifiedTraits,"Migration633DeleteUnidentifiedTraits"),__name2(Migration633DeleteUnidentifiedTraits,"Migration633DeleteUnidentifiedTraits"),__publicField(Migration633DeleteUnidentifiedTraits,"version",.633);class Migration634PurgeMartialItems extends MigrationBase{async updateActor(actorData){const martialIds=actorData.items.filter(itemData=>itemData.type==="martial").map(itemData=>itemData._id),martialItemWeapons=actorData.items.filter(itemData=>{var _a;if(itemData.type!=="weapon")return!1;const systemData=itemData.system;return martialIds.includes(((_a=systemData.weaponType)==null?void 0:_a.value)??"")});for(const weaponData of martialItemWeapons)weaponData.data.category="simple";actorData.items=actorData.items.filter(itemData=>itemData.type!=="martial")}}__name(Migration634PurgeMartialItems,"Migration634PurgeMartialItems"),__name2(Migration634PurgeMartialItems,"Migration634PurgeMartialItems"),__publicField(Migration634PurgeMartialItems,"version",.634);class Migration635NumifyACAndQuantity extends MigrationBase{async updateActor(actorData){(actorData.type==="hazard"||actorData.type==="npc"||actorData.type==="vehicle")&&(actorData.system.attributes.ac.value=Number(actorData.system.attributes.ac.value))}async updateItem(itemData){if(isPhysicalData(itemData)){const quantity=itemData.system.quantity||{value:0};quantity instanceof Object&&(quantity.value=Number(quantity.value))}}}__name(Migration635NumifyACAndQuantity,"Migration635NumifyACAndQuantity"),__name2(Migration635NumifyACAndQuantity,"Migration635NumifyACAndQuantity"),__publicField(Migration635NumifyACAndQuantity,"version",.635);class Migration636NumifyArmorData extends MigrationBase{async updateItem(itemData){if(itemData.type!=="armor")return;const systemData=itemData.system;systemData.armor.value=Number(systemData.armor.value)||0,systemData.check.value=Number(systemData.check.value)||0,systemData.dex.value=Number(systemData.dex.value)||0,systemData.strength.value=Number(systemData.strength.value)||0,typeof systemData.speed.value=="string"&&(systemData.speed.value=parseInt(systemData.speed.value,10)||0)}}__name(Migration636NumifyArmorData,"Migration636NumifyArmorData"),__name2(Migration636NumifyArmorData,"Migration636NumifyArmorData"),__publicField(Migration636NumifyArmorData,"version",.636);const meleeKeys=new Set(["description","source","traits","rules","slug","weaponType","attack","damageRolls","bonus","attackEffects"]);class Migration637CleanMeleeItems extends MigrationBase{async updateItem(itemData){if(itemData.type!=="melee")return;const systemData=itemData.system;for(const key of Object.keys(systemData))meleeKeys.has(key)||delete systemData[key]}}__name(Migration637CleanMeleeItems,"Migration637CleanMeleeItems"),__name2(Migration637CleanMeleeItems,"Migration637CleanMeleeItems");const validComponents=["material","somatic","verbal"];class Migration638SpellComponents extends MigrationBase{async updateItem(itemData){var _a;if(itemData.type!=="spell")return;const components=itemData.system.components,oldComponents=new Set((_a=components.value)==null?void 0:_a.split(",").map(v=>v.trim().toLowerCase()));for(const component of validComponents)components[component]=components[component]||oldComponents.has(component);delete components.value,"game"in globalThis&&(components["-=value"]=null)}}__name(Migration638SpellComponents,"Migration638SpellComponents"),__name2(Migration638SpellComponents,"Migration638SpellComponents"),__publicField(Migration638SpellComponents,"version",.638);class CoinsPF2e{constructor(data){__publicField(this,"cp"),__publicField(this,"sp"),__publicField(this,"gp"),__publicField(this,"pp"),data??(data={}),this.cp=data.cp??0,this.sp=data.sp??0,this.gp=data.gp??0,this.pp=data.pp??0}get copperValue(){const{cp,sp,gp,pp}=this;return cp+sp*10+gp*100+pp*1e3}get goldValue(){return this.copperValue/100}add(coins){const other=new CoinsPF2e(coins);return new CoinsPF2e({pp:this.pp+other.pp,gp:this.gp+other.gp,sp:this.sp+other.sp,cp:this.cp+other.cp})}scale(factor){const result=new CoinsPF2e(this);if(result.pp*=factor,result.gp*=factor,result.sp*=factor,result.cp*=factor,factor%1!==0){result.gp+=result.pp%1*10,result.sp+=result.gp%1*10,result.cp+=result.sp%1*10;for(const denomination of DENOMINATIONS)result[denomination]=Math.floor(Number(result[denomination].toFixed(1)))}return result}adjustForSize(size){const basePrice=new CoinsPF2e(this);switch(size){case"lg":return basePrice.scale(2);case"huge":return basePrice.scale(4);case"grg":return basePrice.scale(8);default:return basePrice}}toObject(){return DENOMINATIONS.reduce((result,denomination)=>this[denomination]!==0?{...result,[denomination]:this[denomination]}:result,{})}static fromString(coinString,quantity=1){return[...String(coinString).trim().replace(/,/g,"").matchAll(/(\d+)\s*([pgsc]p)/g)].map(match=>{const[value,denomination]=match.slice(1,3),computedValue=(Number(value)||0)*quantity;return{[denomination]:computedValue}}).reduce((first,second)=>first.add(second),new CoinsPF2e)}static fromPrice(price,factor){const per=Math.max(1,price.per??1);return new CoinsPF2e(price.value).scale(factor/per)}toString(){if(DENOMINATIONS.every(denomination=>!this[denomination]))return"0 gp";const DENOMINATIONS_REVERSED=[...DENOMINATIONS].reverse(),parts=[];for(const denomation of DENOMINATIONS_REVERSED)this[denomation]&&parts.push(`${this[denomation]} ${denomation}`);return parts.join(", ")}}__name(CoinsPF2e,"CoinsPF2e"),__name2(CoinsPF2e,"CoinsPF2e");const coinCompendiumIds={pp:"JuNPeK5Qm1w6wpb4",gp:"B6B7tBWJSqOBz5zz",sp:"5Ew82vBF9YfaiY9f",cp:"lzJ8AVhRcbFul5fh"};class Migration639NormalizeLevelAndPrice extends MigrationBase{constructor(){super(...arguments),__publicField(this,"coinSlugs",new Set(["platinum-pieces","gold-pieces","silver-pieces","copper-pieces"]))}async updateItem(source){if(source.system.level&&(source.system.level.value=Number(source.system.level.value)||0),!isPhysicalData(source)||this.coinSlugs.has(source.system.slug??""))return;const system2=source.system,price=system2.price;if(!(typeof price.value!="string"&&isObject(price.value)))if(price.value?price.value=price.value.trim():price.value="0 gp",/^[0-9]+$/.test(price.value))price.value=`${price.value} gp`;else{const quantity=system2.quantity,priceValue=price.value;CoinsPF2e.fromString(priceValue,quantity).copperValue&&(price.value="0 gp")}}}__name(Migration639NormalizeLevelAndPrice,"Migration639NormalizeLevelAndPrice"),__name2(Migration639NormalizeLevelAndPrice,"Migration639NormalizeLevelAndPrice"),__publicField(Migration639NormalizeLevelAndPrice,"version",.639);class Migration640CantripsAreNotZeroLevel extends MigrationBase{async updateItem(itemData){if(itemData.type!=="spell")return;const level=itemData.system.level;level.value===0&&(level.value=1,itemData.system.traits.value.includes("cantrip")||itemData.system.traits.value.push("cantrip"))}}__name(Migration640CantripsAreNotZeroLevel,"Migration640CantripsAreNotZeroLevel"),__name2(Migration640CantripsAreNotZeroLevel,"Migration640CantripsAreNotZeroLevel"),__publicField(Migration640CantripsAreNotZeroLevel,"version",.64);class Migration641SovereignSteelValue extends MigrationBase{async updateItem(source){var _a;if(source.type!=="weapon")return;const material=source.system.preciousMaterial;((_a=material.value)==null?void 0:_a.toLowerCase())==="sovereign steel"&&(material.value="sovereignSteel")}}__name(Migration641SovereignSteelValue,"Migration641SovereignSteelValue"),__name2(Migration641SovereignSteelValue,"Migration641SovereignSteelValue"),__publicField(Migration641SovereignSteelValue,"version",.641);class Migration642TrackSchemaVersion extends MigrationBase{async updateActor(actorSource){var _a;(_a=actorSource.system).schema??(_a.schema={version:null,lastMigration:null})}async updateItem(itemSource){var _a;(_a=itemSource.system).schema??(_a.schema={version:null,lastMigration:null})}}__name(Migration642TrackSchemaVersion,"Migration642TrackSchemaVersion"),__name2(Migration642TrackSchemaVersion,"Migration642TrackSchemaVersion"),__publicField(Migration642TrackSchemaVersion,"version",.642);class Migration643HazardLevel extends MigrationBase{async updateActor(actorSource){if(actorSource.type!=="hazard")return;const hazardDetails=actorSource.system.details;if(typeof hazardDetails.level=="number"){const level=hazardDetails.level;hazardDetails.level={value:level}}}}__name(Migration643HazardLevel,"Migration643HazardLevel"),__name2(Migration643HazardLevel,"Migration643HazardLevel"),__publicField(Migration643HazardLevel,"version",.643);const defaultTraditionByClass$1={wizard:"arcane",cleric:"divine",druid:"primal",bard:"occult",ranger:"primal",champion:"divine",monk:"divine"};class Migration644SpellcastingCategory extends MigrationBase{async updateItem(item,actor){if(!actor||item.type!=="spellcastingEntry")return;const spellcasting=item.system;if(spellcasting.tradition.value==="ritual")spellcasting.prepared.value="ritual",spellcasting.tradition.value="";else if(spellcasting.tradition.value==="focus"){spellcasting.prepared.value="focus";const possibleMatch=actor.items.find(testItem=>{if(testItem.type!=="spellcastingEntry")return!1;const testSpellcasting=testItem.system;return tupleHasValue(["prepared","spontaneous"],testSpellcasting.prepared.value)&&testSpellcasting.tradition.value!=="focus"&&(actor.type==="character"?testSpellcasting.proficiency.value===spellcasting.proficiency.value:testSpellcasting.spelldc.value===spellcasting.spelldc.value)&&(testSpellcasting.ability.value||"int")===(spellcasting.ability.value||"int")});if(possibleMatch)spellcasting.tradition.value=possibleMatch.system.tradition.value;else{const classItem=actor.items.find(testItem=>testItem.type==="class"),className=classItem?.system.slug||sluggify(classItem?.name??"");spellcasting.tradition.value=defaultTraditionByClass$1[className]??"arcane"}}}}__name(Migration644SpellcastingCategory,"Migration644SpellcastingCategory"),__name2(Migration644SpellcastingCategory,"Migration644SpellcastingCategory"),__publicField(Migration644SpellcastingCategory,"version",.644);class Migration645TokenImageSize extends MigrationBase{constructor(){super(...arguments),__privateAdd(this,_isTokenImageFlag),__privateAdd(this,_isTokenSizeFlag),__privateAdd(this,_imageOverrides,new Map),__privateAdd(this,_sizeOverrides,new Map)}async updateActor(actorSource){var _a,_b,_c,_d,_e;const flags=actorSource.flags,originalImg=(_b=(_a=flags.pf2e)==null?void 0:_a.token)==null?void 0:_b.img;__privateMethod(this,_isTokenImageFlag,isTokenImageFlag_fn).call(this,originalImg)&&__privateGet(this,_imageOverrides).set(actorSource._id,originalImg);const originalSize=(_d=(_c=flags.pf2e)==null?void 0:_c.token)==null?void 0:_d.size;__privateMethod(this,_isTokenSizeFlag,isTokenSizeFlag_fn).call(this,originalSize)&&__privateGet(this,_sizeOverrides).set(actorSource._id,originalSize),typeof((_e=flags.pf2e)==null?void 0:_e.token)=="object"&&("game"in globalThis&&(flags.pf2e["-=token"]=null),delete flags.pf2e.token)}async updateToken(tokenSource,actor){tokenSource.texture.src=__privateGet(this,_imageOverrides).get(actor?.id??"")??tokenSource.texture.src;const sizeOverride=__privateGet(this,_sizeOverrides).get(actor?.id??"");tokenSource.height=sizeOverride?.height??tokenSource.height,tokenSource.width=sizeOverride?.width??tokenSource.width}}__name(Migration645TokenImageSize,"Migration645TokenImageSize"),__name2(Migration645TokenImageSize,"Migration645TokenImageSize"),_imageOverrides=new WeakMap,_sizeOverrides=new WeakMap,_isTokenImageFlag=new WeakSet,isTokenImageFlag_fn=__name2(function(flag){return typeof flag=="string"},"#isTokenImageFlag"),_isTokenSizeFlag=new WeakSet,isTokenSizeFlag_fn=__name2(function(flag){return flag instanceof Object&&"height"in flag&&typeof flag.height=="number"&&"width"in flag&&typeof flag.width=="number"},"#isTokenSizeFlag"),__publicField(Migration645TokenImageSize,"version",.645);class Migration646UpdateInlineLinks extends MigrationBase{updateCheckAttributes(markup=""){return markup.replace(/\bdata-pf2-([a-z]+)-check="\w*"/g,'data-pf2-check="$1"').replace(/\bdata-pf2-(?:saving-throw|skill-check)\b/g,"data-pf2-check")}async updateActor(actorData){if(actorData.type==="hazard"){const hazardDetails=actorData.system.details;hazardDetails.disable=this.updateCheckAttributes(hazardDetails.disable??"")}}async updateItem(itemData){const description=itemData.system.description;description.value=this.updateCheckAttributes(description.value??"")}}__name(Migration646UpdateInlineLinks,"Migration646UpdateInlineLinks"),__name2(Migration646UpdateInlineLinks,"Migration646UpdateInlineLinks"),__publicField(Migration646UpdateInlineLinks,"version",.646);class Migration647FixPCSenses extends MigrationBase{async updateActor(actorData){if(actorData.type!=="character")return;const notTraits=actorData.system.traits;Array.isArray(notTraits.senses)?notTraits.senses=notTraits.senses.filter(sense=>!!sense):notTraits.senses=[]}}__name(Migration647FixPCSenses,"Migration647FixPCSenses"),__name2(Migration647FixPCSenses,"Migration647FixPCSenses"),__publicField(Migration647FixPCSenses,"version",.647);class Migration648RemoveInvestedProperty extends MigrationBase{async updateItem(itemSource){if(!(itemSource.type==="treasure"||itemSource.type==="consumable"))return;const systemData=itemSource.system;delete systemData.invested,"game"in globalThis&&(systemData["-=invested"]=null)}}__name(Migration648RemoveInvestedProperty,"Migration648RemoveInvestedProperty"),__name2(Migration648RemoveInvestedProperty,"Migration648RemoveInvestedProperty"),__publicField(Migration648RemoveInvestedProperty,"version",.648);function isCreatureSource(source){return["character","npc"].includes(source.type)}__name(isCreatureSource,"isCreatureSource"),__name2(isCreatureSource,"isCreatureSource");class Migration649FocusToActor extends MigrationBase{async updateActor(actorData){if(!isCreatureSource(actorData))return;const systemData=actorData.system;systemData.resources||(systemData.resources={});const spellLists=actorData.items.filter(i=>i.type==="spellcastingEntry").sort((a,b)=>(a.sort||0)-(b.sort||0)).map(i=>i.system).filter(i=>i.prepared.value==="focus"&&i.focus).sort((a,b)=>{var _a,_b;return(((_a=b.focus)==null?void 0:_a.pool)||0)-(((_b=a.focus)==null?void 0:_b.pool)||0)});if(spellLists.length===0)return;const focusOld=spellLists[0].focus,resources=actorData.system.resources;resources.focus={value:focusOld?.points??0,max:focusOld?.pool??1}}async updateItem(itemData){if(itemData.type!=="spellcastingEntry")return;const data=itemData.system;delete data.focus,"game"in globalThis&&(data["-=focus"]=null)}}__name(Migration649FocusToActor,"Migration649FocusToActor"),__name2(Migration649FocusToActor,"Migration649FocusToActor"),__publicField(Migration649FocusToActor,"version",.649);class Migration650StringifyWeaponProperties extends MigrationBase{async updateItem(itemData){var _a;if(itemData.type!=="weapon")return;const systemData=itemData.system;systemData.weaponType&&((_a=systemData.weaponType).value||(_a.value="simple"));const range=systemData.range??(systemData.range={value:"melee"});range instanceof Object&&typeof range.value=="string"&&(range.value=range.value.trim()||"melee",range.value==="reach"&&(range.value="melee"))}}__name(Migration650StringifyWeaponProperties,"Migration650StringifyWeaponProperties"),__name2(Migration650StringifyWeaponProperties,"Migration650StringifyWeaponProperties"),__publicField(Migration650StringifyWeaponProperties,"version",.65);class Migration651EphemeralFocusPool extends MigrationBase{constructor(){super(...arguments),__privateAdd(this,_needsRuleElement),__privateAdd(this,_isClassFeature),__privateAdd(this,_increasesByOne,new Set(["abundant-step","achaekeks-grip","advanced-bloodline","advanced-deitys-domain","advanced-domain","advanced-revelation","advanced-school-spell","advanced-seeker-of-truths","animal-feature","arcane-school-spell","apex-companion","basic-lesson","beastmasters-trance","blessed-sacrifice","cackle","champions-sacrifice","clinging-shadows-initiate","counter-perform","debilitating-dichotomy","domain-acumen","domain-fluency","empty-body","enlarge-companion","ephemeral-tracking","familiar-form","fatal-aria","gaze-of-veracity","greater-bloodline","greater-lesson","greater-revelation","heal-animal","healing-touch","hunters-luck","hunters-vision","impaling-briars","inspire-heroics","invoke-disaster","invoke-the-crimson-oath","ki-blast","ki-form","ki-rush","ki-strike","leaf-order","light-of-revelation","lingering-composition","litany-against-sloth","litany-against-wrath","litany-of-depravity","litany-of-righteousness","litany-of-self-interest","loremasters-etude","magic-hide","major-lesson","mantis-form","medusas-wrath","order-spell","perfect-ki-adept","perfect-strike","quivering-palm","rangers-bramble","shadow-magic","shadows-web","shall-not-falter-shall-not-rout","snare-hopping","song-of-the-fallen","soothing-ballad","soothing-mist","speaking-sky","spellmasters-ward","steal-the-sky","storm-order","sun-blade","suns-fury","terrain-transposition","transcribe-moment","universal-versatility","vision-of-weakness","wholeness-of-body","wild-winds-initiate","wind-caller","wind-jump","wronged-monks-wrath"]))}async updateActor(source){var _a,_b;if(source.type!=="character")return;const systemData=source.system;systemData.resources??(systemData.resources={});const resources=systemData.resources;typeof((_a=resources.focus)==null?void 0:_a.max)=="number"&&"game"in globalThis?resources.focus["-=max"]=null:(_b=resources.focus)==null||delete _b.max}async updateItem(source){if(source.type!=="feat")return;const systemData=source.system,rule=(()=>{const slug=systemData.slug??sluggify(source.name);return slug==="revelation-spells"?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"upgrade",value:2,priority:10}:slug==="major-curse"?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"upgrade",value:3}:["composition-spells","devotion-spells","druidic-order","hexes"].includes(slug)||/^(?:arcane-school|bloodline)-/.test(slug)&&__privateMethod(this,_isClassFeature,isClassFeature_fn).call(this,source)?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"upgrade",value:1,priority:10}:__privateGet(this,_increasesByOne).has(slug)||slug.startsWith("first-revelation-")?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"add",value:1}:null})();rule&&__privateMethod(this,_needsRuleElement,needsRuleElement_fn).call(this,source.system.rules)&&systemData.rules.push(rule)}}__name(Migration651EphemeralFocusPool,"Migration651EphemeralFocusPool"),__name2(Migration651EphemeralFocusPool,"Migration651EphemeralFocusPool"),_needsRuleElement=new WeakSet,needsRuleElement_fn=__name2(function(rules){return!rules.some(rule=>rule.key==="ActiveEffectLike"&&rule.path==="system.resources.focus.max")},"#needsRuleElement"),_increasesByOne=new WeakMap,_isClassFeature=new WeakSet,isClassFeature_fn=__name2(function(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"},"#isClassFeature"),__publicField(Migration651EphemeralFocusPool,"version",.651);const defaultTraditionByClass={wizard:"arcane",druid:"primal",ranger:"primal"};class Migration652KillHalcyonTradition extends MigrationBase{async updateItem(itemData,actor){if(itemData.type!=="spellcastingEntry")return;const tradition=itemData.system.tradition;if(tradition.value==="halcyon"){const classItem=actor?.items.find(testItem=>testItem.type==="class"),className=classItem?.system.slug||sluggify(classItem?.name??"");tradition.value=defaultTraditionByClass[className]??"arcane"}}}__name(Migration652KillHalcyonTradition,"Migration652KillHalcyonTradition"),__name2(Migration652KillHalcyonTradition,"Migration652KillHalcyonTradition"),__publicField(Migration652KillHalcyonTradition,"version",.652);class Migration653AEstoREs extends MigrationBase{constructor(){super(...arguments),__publicField(this,"pathsToRemove",new Set([...["unarmored","light","medium","heavy"].map(category=>`system.martial.${category}.rank`),...["unarmed","simple","martial","advanced"].map(category=>`system.martial.${category}.rank`),...["fortitude","reflex","will"].map(save=>`system.saves.${save}.rank`),"system.details.keyability.value","system.attributes.perception.rank","system.attributes.classDC.rank"]))}isRemovableAE(effect){return effect.changes.every(this.isRemoveableChange)}isRemoveableChange(change){return change.mode!==0&&Number.isInteger(Number(change.value))||change.mode===5&&!change.value.startsWith("{")}fixClassKeyAbilities(classSource){const keyAbility=classSource.system.keyAbility;keyAbility.value=keyAbility.value.map(value=>typeof value=="string"?value:value.value)}async updateActor(actorSource){if(actorSource.type!=="character")return;const systemData=actorSource.system;systemData.martial={},actorSource.effects=actorSource.effects.filter(effect=>{var _a;const origin=effect.origin??"",itemId=(_a=/\bItem\.([A-Za-z0-9]{16})$/.exec(origin))==null?void 0:_a[1],itemSource=actorSource.items.find(maybeSource=>maybeSource._id===itemId);return itemSource&&!(["class","effect","feat"].includes(itemSource.type)&&this.isRemovableAE(effect))})}async updateItem(itemSource){if(!(itemSource.type==="class"||itemSource.type==="effect"||itemSource.type==="feat"))return;itemSource.type==="class"&&this.fixClassKeyAbilities(itemSource);const modes2={1:"multiply",2:"add",3:"downgrade",4:"upgrade",5:"override"};for(const effect of[...itemSource.effects]){itemSource.type==="class"&&(effect.changes=effect.changes.filter(change=>!this.pathsToRemove.has(change.key)));const toAELikes=effect.changes.filter(this.isRemoveableChange),rules=itemSource.system.rules;for(const change of toAELikes){if(change.mode===0)continue;const newRule={key:"ActiveEffectLike",path:change.key,mode:modes2[change.mode],value:Number.isNaN(Number(change.value))?change.value:Number(change.value),priority:change.priority};rules.push(newRule)}effect.changes=effect.changes.filter(change=>!this.isRemoveableChange(change))}itemSource.effects=itemSource.effects.filter(effect=>!this.isRemovableAE(effect))}}__name(Migration653AEstoREs,"Migration653AEstoREs"),__name2(Migration653AEstoREs,"Migration653AEstoREs"),__publicField(Migration653AEstoREs,"version",.653);class Migration654ActionTypeAndCount extends MigrationBase{async updateItem(item){if(item.type!=="feat"&&item.type!=="action")return;const systemData=item.system;systemData.actions.value=Math.min(3,Math.max(Number(systemData.actions.value),0))||null}}__name(Migration654ActionTypeAndCount,"Migration654ActionTypeAndCount"),__name2(Migration654ActionTypeAndCount,"Migration654ActionTypeAndCount"),__publicField(Migration654ActionTypeAndCount,"version",.654);class Migration655CreatureTokenSizes extends MigrationBase{constructor(){super(...arguments),__privateAdd(this,_isTokenSizeRE),__privateAdd(this,_isActorSizeAELike),__privateAdd(this,_isBracketedValue),__publicField(this,"dimensionToSize",{.5:"tiny",2:"lg",3:"huge",4:"grg"})}async updateItem(itemSource){var _a;(_a=itemSource.system).rules??(_a.rules=[]);const rules=itemSource.system.rules,actorSizeAELike=rules.find(__privateMethod(this,_isActorSizeAELike,isActorSizeAELike_fn)),tokenSizeRE=rules.find(__privateMethod(this,_isTokenSizeRE,isTokenSizeRE_fn));if(actorSizeAELike)actorSizeAELike.key="CreatureSize",delete actorSizeAELike.path,delete actorSizeAELike.mode;else if(tokenSizeRE&&["number","string","object"].includes(typeof tokenSizeRE.value))if(tokenSizeRE.key="CreatureSize",__privateMethod(this,_isBracketedValue,isBracketedValue_fn).call(this,tokenSizeRE.value))for(const bracket of tokenSizeRE.value.brackets)typeof bracket.value=="number"&&(bracket.value=this.dimensionToSize[bracket.value]??"med");else typeof tokenSizeRE.value=="number"&&(tokenSizeRE.value=this.dimensionToSize[tokenSizeRE.value]??"med");tokenSizeRE&&tokenSizeRE.key!=="CreatureSize"&&itemSource.system.rules.splice(itemSource.system.rules.indexOf(tokenSizeRE),1)}}__name(Migration655CreatureTokenSizes,"Migration655CreatureTokenSizes"),__name2(Migration655CreatureTokenSizes,"Migration655CreatureTokenSizes"),_isTokenSizeRE=new WeakSet,isTokenSizeRE_fn=__name2(function(rule){return typeof rule.key=="string"&&rule.key.endsWith("TokenSize")},"#isTokenSizeRE"),_isActorSizeAELike=new WeakSet,isActorSizeAELike_fn=__name2(function(rule){return typeof rule.key=="string"&&rule.key.endsWith("ActiveEffectLike")&&rule.path==="system.traits.size.value"},"#isActorSizeAELike"),_isBracketedValue=new WeakSet,isBracketedValue_fn=__name2(function(value){return isObject(value)&&Array.isArray(value.brackets)},"#isBracketedValue"),__publicField(Migration655CreatureTokenSizes,"version",.655);class Migration656OtherFocusPoolSources extends MigrationBase{constructor(){super(...arguments),__publicField(this,"increasesByOne",new Set(["additional-shadow-magic","basic-bloodline-spell","blessed-one-dedication","breath-of-the-dragon","crystal-ward-spells","domain-initiate","expanded-domain-initiate","gravity-weapon","heal-companion","leaf-order","shadow-illusion","storm-order","wings-of-the-dragon"]))}needsRuleElement(rules){return!rules.some(rule=>rule.key==="ActiveEffectLike"&&rule.path==="system.resources.focus.max")}async updateItem(itemSource){if(itemSource.type!=="feat")return;const systemData=itemSource.system,rule=(()=>{const slug=systemData.slug??sluggify(itemSource.name);return slug==="druidic-order"?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"upgrade",value:1,priority:10}:this.increasesByOne.has(slug)?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"add",value:1}:null})();rule&&this.needsRuleElement(itemSource.system.rules)&&systemData.rules.push(rule)}}__name(Migration656OtherFocusPoolSources,"Migration656OtherFocusPoolSources"),__name2(Migration656OtherFocusPoolSources,"Migration656OtherFocusPoolSources"),__publicField(Migration656OtherFocusPoolSources,"version",.656);class Migration657RemoveSetProperty extends MigrationBase{async updateActor(actorSource){const systemFlags=actorSource.flags.pf2e??{};delete systemFlags["set-property"],"game"in globalThis&&"set-property"in systemFlags&&(systemFlags["-=set-property"]=null)}async updateItem(itemSource){var _a;(_a=itemSource.system).rules??(_a.rules=[]);const rules=itemSource.system.rules,setPropertyRules=itemSource.system.rules.filter(rule=>typeof rule.key=="string"&&["SetProperty","PF2E.RuleElement.SetProperty"].includes(rule.key)&&typeof rule.property=="string"&&typeof rule.on=="object"&&rule.on!==null&&"added"in rule.on),aeLikes=setPropertyRules.map(setProperty2=>({key:"ActiveEffectLike",mode:"override",path:setProperty2.property.replace(/^flags\.2e/,"flags.pf2e"),value:setProperty2.on.added,priority:10}));for(const setPropertyRule of setPropertyRules){const index=rules.indexOf(setPropertyRule);rules.splice(index,1,aeLikes.shift())}itemSource.system.rules=itemSource.system.rules.filter(rule=>rule&&typeof rule.key=="string"&&!rule.key.trim().endsWith("SetProperty"))}}__name(Migration657RemoveSetProperty,"Migration657RemoveSetProperty"),__name2(Migration657RemoveSetProperty,"Migration657RemoveSetProperty"),__publicField(Migration657RemoveSetProperty,"version",.657);class Migration658MonkUnarmoredProficiency extends MigrationBase{async updateItem(itemSource){const slug=itemSource.system.slug??sluggify(itemSource.name);itemSource.type==="class"&&slug==="monk"&&itemSource.system.defenses.unarmored!==2&&(itemSource.system.defenses.unarmored=2)}}__name(Migration658MonkUnarmoredProficiency,"Migration658MonkUnarmoredProficiency"),__name2(Migration658MonkUnarmoredProficiency,"Migration658MonkUnarmoredProficiency"),__publicField(Migration658MonkUnarmoredProficiency,"version",.658);const formulaHasValue=__name2(value=>!!value&&value!=="0","formulaHasValue"),modes=["level1","level2","level3","level4"];class Migration659MultipleDamageRows extends MigrationBase{async updateItem(itemData){var _a;if(itemData.type!=="spell")return;const data=itemData.system;if(data.scaling instanceof Object&&(typeof data.scaling.mode=="string"&&tupleHasValue(modes,data.scaling.mode)&&(data.scaling.interval=modes.indexOf(data.scaling.mode)+1),typeof data.scaling.formula=="string"&&formulaHasValue(data.scaling.formula)&&!data.scaling.damage&&(data.scaling.damage={0:data.scaling.formula}),!data.scaling.interval||!data.scaling.damage?"game"in globalThis?data["-=scaling"]=null:delete data.scaling:"game"in globalThis?(data.scaling["-=mode"]=null,data.scaling["-=formula"]=null):(delete data.scaling.mode,delete data.scaling.formula)),typeof data.damage.value=="string"){if(formulaHasValue(data.damage.value)||data.damage.applyMod){const value=data.damage.value;data.damage.value={0:{value,applyMod:data.damage.applyMod||void 0,type:{value:((_a=data.damageType)==null?void 0:_a.value)||"untyped",categories:[]}}}}else data.damage.value={};"game"in globalThis?data.damage["-=applyMod"]=null:delete data.damage.applyMod}"damageType"in data&&("game"in globalThis?data["-=damageType"]=null:data.damageType=void 0)}}__name(Migration659MultipleDamageRows,"Migration659MultipleDamageRows"),__name2(Migration659MultipleDamageRows,"Migration659MultipleDamageRows"),__publicField(Migration659MultipleDamageRows,"version",.659);class Migration660DerivedSpellTraits extends MigrationBase{constructor(){super(...arguments),__publicField(this,"derivedTraits",[...MAGIC_SCHOOLS,...MAGIC_TRADITIONS])}async updateItem(itemSource){if(itemSource.type==="spell"){const traits=itemSource.system.traits;traits.value=traits.value.filter(trait=>!this.derivedTraits.includes(trait))}}}__name(Migration660DerivedSpellTraits,"Migration660DerivedSpellTraits"),__name2(Migration660DerivedSpellTraits,"Migration660DerivedSpellTraits"),__publicField(Migration660DerivedSpellTraits,"version",.66);class Migration661NumifyVehicleDimensions extends MigrationBase{async updateActor(actorSource){if(actorSource.type==="vehicle"){const{space}=actorSource.system.details;space.long=Number(space.long)||2,space.wide=Number(space.wide)||2,space.high=Number(space.high)||1}}}__name(Migration661NumifyVehicleDimensions,"Migration661NumifyVehicleDimensions"),__name2(Migration661NumifyVehicleDimensions,"Migration661NumifyVehicleDimensions"),__publicField(Migration661NumifyVehicleDimensions,"version",.661);class Migration662LinkToActorSizeDefaults extends MigrationBase{async updateActor(actorSource){var _a,_b,_c;const linkToActorSize=!["hazard","loot"].includes(actorSource.type);(_a=actorSource.prototypeToken).flags??(_a.flags={pf2e:{linkToActorSize}}),(_b=actorSource.prototypeToken.flags).pf2e??(_b.pf2e={linkToActorSize}),(_c=actorSource.prototypeToken.flags.pf2e).linkToActorSize??(_c.linkToActorSize=linkToActorSize)}async updateToken(tokenSource,actor){var _a,_b;const linkToActorSize=!["hazard","loot"].includes(actor.type);(_a=tokenSource.flags).pf2e??(_a.pf2e={linkToActorSize}),(_b=tokenSource.flags.pf2e).linkToActorSize??(_b.linkToActorSize=linkToActorSize)}}__name(Migration662LinkToActorSizeDefaults,"Migration662LinkToActorSizeDefaults"),__name2(Migration662LinkToActorSizeDefaults,"Migration662LinkToActorSizeDefaults"),__publicField(Migration662LinkToActorSizeDefaults,"version",.662);function createBasicDamage(value,applyMod,damageType){return{0:{applyMod,type:{categories:[],value:damageType},value}}}__name(createBasicDamage,"createBasicDamage"),__name2(createBasicDamage,"createBasicDamage");function createBasicScaling(interval,scaling){return{interval,damage:{0:scaling}}}__name(createBasicScaling,"createBasicScaling"),__name2(createBasicScaling,"createBasicScaling");class Migration663FixSpellDamage extends MigrationBase{async updateItem(itemData){var _a;if(itemData.type!=="spell"||Object.keys(((_a=itemData.system.damage)==null?void 0:_a.value)??{}).length>0)return;const itemName=itemData.system.slug??sluggify(itemData.name),systemData=itemData.system;switch(itemName){case"animated-assault":systemData.damage.value=createBasicDamage("2d10",!1,"bludgeoning"),systemData.scaling=createBasicScaling(2,"2d10");break;case"daze":systemData.damage.value=createBasicDamage("0",!0,"mental"),systemData.scaling=createBasicScaling(2,"1d6");break;case"personal-blizzard":systemData.damage.value={0:{applyMod:!1,type:{value:"cold",categories:[]},value:"1d6"},1:{applyMod:!1,type:{value:"cold",subtype:"persistent",categories:[]},value:"1d6"}},systemData.scaling={interval:1,damage:{0:"1",1:"1"}};break;case"power-word-kill":systemData.damage.value=createBasicDamage("50",!1,"untyped");break}}}__name(Migration663FixSpellDamage,"Migration663FixSpellDamage"),__name2(Migration663FixSpellDamage,"Migration663FixSpellDamage"),__publicField(Migration663FixSpellDamage,"version",.663);class Migration664DeleteCUBConditions extends MigrationBase{async updateActor(actorSource){const cubConditions=actorSource.items.filter(item=>{var _a;return item.type==="condition"&&!((_a=item.system.references)!=null&&_a.overriddenBy)});for(const condition of cubConditions)actorSource.items.findSplice(item=>item===condition)}}__name(Migration664DeleteCUBConditions,"Migration664DeleteCUBConditions"),__name2(Migration664DeleteCUBConditions,"Migration664DeleteCUBConditions"),__publicField(Migration664DeleteCUBConditions,"version",.664);class Migration665HandwrapsCorrections extends MigrationBase{async updateItem(itemSource){const slug=itemSource.system.slug??sluggify(itemSource.name);if(itemSource.type==="weapon"&&slug==="handwraps-of-mighty-blows"){const usage=itemSource.system.usage;usage.value="worn-gloves"}const dirPath="systems/pf2e/icons/equipment/worn-items/other-worn-items";itemSource.img===`${dirPath}/handwraps-of-nighty-blows.webp`&&(itemSource.img=`${dirPath}/handwraps-of-mighty-blows.webp`)}}__name(Migration665HandwrapsCorrections,"Migration665HandwrapsCorrections"),__name2(Migration665HandwrapsCorrections,"Migration665HandwrapsCorrections"),__publicField(Migration665HandwrapsCorrections,"version",.665);class Migration666UsageAndStowingContainers extends MigrationBase{constructor(){super(...arguments),__publicField(this,"backpacks",new Set(["backpack","knapsack-of-halflingkind","knapsack-of-halflingkind-greater","sturdy-satchel","vaultbreaker-harness","voyagers-pack"])),__publicField(this,"wornGarment",new Set(["sleeves-of-storage","sleeves-of-storage-greater"])),__publicField(this,"wornGloves",new Set(["gloves-of-storing"])),__publicField(this,"heldInTwoHands",new Set(["bag-of-devouring-type-i","bag-of-devouring-type-ii","bag-of-devouring-type-iii","bag-of-holding-type-i","bag-of-holding-type-ii","bag-of-holding-type-iii","bag-of-holding-type-iv","bag-of-weasels","chest","sealing-chest-greater","sealing-chest-lesser","sealing-chest-moderate"])),__publicField(this,"stowingContainers",new Set([...this.backpacks,...this.heldInTwoHands,...this.wornGarment,...this.wornGloves,"extradimensional-stash"]))}async updateItem(itemSource){var _a;if(!itemSource.system.traits)return;const traits=itemSource.system.traits;if(typeof((_a=traits.usage)==null?void 0:_a.value)=="string"){const traitUsage=traits.usage.value,isPhysical=isPhysicalData(itemSource),keepUsage=isPhysical&&(traitUsage!=="held-in-one-hand"||itemSource.system.usage.value==="");isPhysical&&keepUsage&&(itemSource.system.usage.value=traits.usage.value),"game"in globalThis?traits["-=usage"]=null:delete traits.usage}if(itemSource.type!=="backpack")return;const slug=itemSource.system.slug??sluggify(itemSource.name);this.backpacks.has(slug)?itemSource.system.usage.value="wornbackpack":this.heldInTwoHands.has(slug)?itemSource.system.usage.value="held-in-two-hands":this.wornGarment.has(slug)?itemSource.system.usage.value="worngarment":this.wornGloves.has(slug)?itemSource.system.usage.value="worngloves":itemSource.system.usage.value="worn",itemSource.system.stowing=this.stowingContainers.has(slug)}}__name(Migration666UsageAndStowingContainers,"Migration666UsageAndStowingContainers"),__name2(Migration666UsageAndStowingContainers,"Migration666UsageAndStowingContainers"),__publicField(Migration666UsageAndStowingContainers,"version",.666);class Migration667HPSubProperties extends MigrationBase{addRecoveryMultiplier(itemSource,slug){if(!["dream-may","fast-recovery"].includes(slug))return;const rules=itemSource.system.rules;if(!rules.some(rule=>"path"in rule&&rule.path==="system.attributes.hp.recoveryMultiplier")){const element={key:"ActiveEffectLike",mode:"add",path:"system.attributes.hp.recoveryMultiplier",value:1};rules.push(element)}}addNegativeHealing(itemSource,slug){if(!["dhampir","negative-healing"].includes(slug))return;const rules=itemSource.system.rules;if(!rules.some(rule=>"path"in rule&&rule.path==="system.attributes.hp.negativeHealing")){const element={key:"ActiveEffectLike",mode:"override",path:"system.attributes.hp.negativeHealing",value:!0};rules.push(element)}}async updateItem(itemSource){if(itemSource.type!=="feat"&&itemSource.type!=="action")return;const slug=itemSource.system.slug??sluggify(itemSource.name);this.addRecoveryMultiplier(itemSource,slug),this.addNegativeHealing(itemSource,slug)}}__name(Migration667HPSubProperties,"Migration667HPSubProperties"),__name2(Migration667HPSubProperties,"Migration667HPSubProperties"),__publicField(Migration667HPSubProperties,"version",.667);class Migration668ArmorSpeedPenalty extends MigrationBase{async updateItem(itemSource){var _a;const slug=itemSource.system.slug??sluggify(itemSource.name);if(itemSource.type==="armor"){const rules=(_a=itemSource.system).rules??(_a.rules=[]),rule=rules.find(r=>typeof r.key=="string"&&r.key.endsWith("FlatModifier")&&r.selector==="speed"&&typeof r.value=="object"&&JSON.stringify(r.predicate??null)===JSON.stringify({not:["unburdened-iron"]}));rule&&rules.splice(rules.indexOf(rule),1)}else if(itemSource.type==="feat"){if(slug==="unburdened-iron"){const rule={key:"RollOption",domain:"speed",option:"armor:ignore-speed-penalty"};itemSource.system.rules=[rule]}else if(slug==="armored-stealth"){const rule={key:"RollOption",domain:"stealth",option:"armor:ignore-noisy-penalty"};itemSource.system.rules=[rule]}}}}__name(Migration668ArmorSpeedPenalty,"Migration668ArmorSpeedPenalty"),__name2(Migration668ArmorSpeedPenalty,"Migration668ArmorSpeedPenalty"),__publicField(Migration668ArmorSpeedPenalty,"version",.668);class Migration669NPCAttackEffects extends MigrationBase{async updateItem(item,actor){var _a;!actor||item.type!=="melee"||((_a=item.system).attackEffects??(_a.attackEffects={value:[]}),Array.isArray(item.system.attackEffects.value)&&item.system.attackEffects.value.forEach((entry,index,arr)=>{arr[index]=sluggify(entry)}))}}__name(Migration669NPCAttackEffects,"Migration669NPCAttackEffects"),__name2(Migration669NPCAttackEffects,"Migration669NPCAttackEffects"),__publicField(Migration669NPCAttackEffects,"version",.669);class Migration670NoCustomTrait extends MigrationBase{async updateItem(itemSource){const traits=itemSource.system.traits;traits&&(Array.isArray(traits.value)?traits.value=traits.value.filter(trait=>trait&&trait!=="custom"):traits.value=[])}}__name(Migration670NoCustomTrait,"Migration670NoCustomTrait"),__name2(Migration670NoCustomTrait,"Migration670NoCustomTrait"),__publicField(Migration670NoCustomTrait,"version",.67);class Migration670AncestryVision extends MigrationBase{constructor(){super(...arguments),__privateAdd(this,_setAncestryVision),__publicField(this,"DARKVISION_ID","HHVQDp61ehcpdiU8"),__publicField(this,"LOWLIGHTVISION_ID","DRtaqOHXTRtGRIUT")}async updateActor(source){if(source.type!=="character")return;const ancestry=source.items.find(item=>item.type==="ancestry");if(ancestry){__privateMethod(this,_setAncestryVision,setAncestryVision_fn).call(this,ancestry);for(const vision of["darkvision","low-light-vision"]){const index=source.items.findIndex(item=>item.type==="feat"&&(item.system.slug??sluggify(item.name))===vision);index!==-1&&source.items.splice(index,1)}}}async updateItem(source,actor){source.type==="ancestry"&&!actor&&__privateMethod(this,_setAncestryVision,setAncestryVision_fn).call(this,source)}}__name(Migration670AncestryVision,"Migration670AncestryVision"),__name2(Migration670AncestryVision,"Migration670AncestryVision"),_setAncestryVision=new WeakSet,setAncestryVision_fn=__name2(function(ancestry){var _a;const features=ancestry.system.items;for(const[key,value]of Object.entries(features))value?.id===this.LOWLIGHTVISION_ID?("game"in globalThis?features[`-=${key}`]=null:delete features[key],ancestry.system.vision=ancestry.system.vision==="darkvision"?"darkvision":"lowLightVision"):value?.id===this.DARKVISION_ID&&("game"in globalThis?features[`-=${key}`]=null:delete features[key],ancestry.system.vision="darkvision");(_a=ancestry.system).vision??(_a.vision="normal")},"#setAncestryVision"),__publicField(Migration670AncestryVision,"version",.67);class Migration671NoPCItemsOnNonPCs extends MigrationBase{async updateActor(actorSource){if(actorSource.type==="character")return;const pcOnlyTypes=["ancestry","background","class","feat"],forbiddenItems=actorSource.items.filter(item=>pcOnlyTypes.includes(item.type));for(const forbiddenItem of forbiddenItems){const index=actorSource.items.findIndex(item=>item===forbiddenItem);index!==-1&&actorSource.items.splice(index,1)}}}__name(Migration671NoPCItemsOnNonPCs,"Migration671NoPCItemsOnNonPCs"),__name2(Migration671NoPCItemsOnNonPCs,"Migration671NoPCItemsOnNonPCs"),__publicField(Migration671NoPCItemsOnNonPCs,"version",.671);class Migration672RemoveNPCBaseProperties extends MigrationBase{removeBase(property,replace="value"){property[replace]=Number(property[replace])||0,typeof property.base=="number"&&(property[replace]=property.base,"game"in globalThis?property["-=base?"]=null:delete property.base)}async updateActor(actorSource){if(actorSource.type!=="npc")return;const{ac,hp,perception}=actorSource.system.attributes;this.removeBase(ac),this.removeBase(hp,"max"),this.removeBase(perception);const{saves}=actorSource.system;for(const saveType of SAVE_TYPES)this.removeBase(saves[saveType])}async updateItem(itemSource,actorSource){actorSource?.type==="npc"&&itemSource.type==="lore"&&this.removeBase(itemSource.system.mod)}}__name(Migration672RemoveNPCBaseProperties,"Migration672RemoveNPCBaseProperties"),__name2(Migration672RemoveNPCBaseProperties,"Migration672RemoveNPCBaseProperties"),__publicField(Migration672RemoveNPCBaseProperties,"version",.672);class Migration673RemoveBulwarkREs extends MigrationBase{hasRuleElement(rules){return rules.some(r=>{var _a;return typeof r.key=="string"&&r.key.endsWith("FlatModifier")&&isObject(r.predicate)&&!!((_a=r.predicate.all)!=null&&_a.includes("self:armor:trait:bulwark"))})}async updateItem(item){const{rules}=item.system;if(item.type==="armor"){const index=rules.findIndex(rule=>typeof rule.key=="string"&&rule.key.endsWith("FlatModifier")&&rule.selector==="reflex"&&rule.type==="ability"&&/bulwark/i.test(String(rule.label??"")));index!==-1&&rules.splice(index)}const slug=item.system.slug??sluggify(item.name);if(item.type==="feat"&&slug==="mighty-bulwark"&&!this.hasRuleElement(rules)){const newRules=[{key:"FlatModifier",predicate:{all:["self:armor:trait:bulwark"]},selector:"reflex",type:"untyped",value:4},{key:"RollOption",domain:"reflex",option:"self:armor:bulwark-all"}];rules.push(...newRules)}}}__name(Migration673RemoveBulwarkREs,"Migration673RemoveBulwarkREs"),__name2(Migration673RemoveBulwarkREs,"Migration673RemoveBulwarkREs"),__publicField(Migration673RemoveBulwarkREs,"version",.673);const HOMEBREW_TRAIT_KEYS=["creatureTraits","featTraits","languages","magicSchools","spellTraits","weaponCategories","weaponGroups","baseWeapons","weaponTraits","equipmentTraits"],SECONDARY_TRAIT_RECORDS={creatureTraits:["ancestryItemTraits"],equipmentTraits:["armorTraits","consumableTraits"],featTraits:["actionTraits"],weaponTraits:["npcAttackTraits"]};class PredicatePF2e extends Array{constructor(...statements){var __super=__name((...args)=>{super(...args),__publicField(this,"isValid")},"__super");Array.isArray(statements[0])?__super(...statements[0]):__super(...statements),this.isValid=PredicatePF2e.isValid(this)}static isValid(statements){return this.isArray(statements)}static isArray(statements){return super.isArray(statements)&&statements.every(s=>StatementValidator.isStatement(s))}static test(predicate=[],options){return predicate instanceof PredicatePF2e?predicate.test(options):new PredicatePF2e(...predicate).test(options)}test(options){if(this.length===0)return!0;if(!this.isValid)return console.warn("PF2e System | The provided predicate set is malformed."),!1;const domain=options instanceof Set?options:new Set(options);return this.every(s=>this.isTrue(s,domain))}toObject(){return deepClone([...this])}clone(){return new PredicatePF2e(this.toObject())}isTrue(statement,domain){return typeof statement=="string"&&domain.has(statement)||StatementValidator.isBinaryOp(statement)&&this.testBinaryOp(statement,domain)||StatementValidator.isCompound(statement)&&this.testCompound(statement,domain)}testBinaryOp(statement,domain){if("eq"in statement)return domain.has(`${statement.eq[0]}:${statement.eq[1]}`);{const operator=Object.keys(statement)[0],[left,right]=Object.values(statement)[0],domainArray=Array.from(domain),getValues=__name2(operand=>{const maybeNumber=Number(operand);if(!Number.isNaN(maybeNumber))return[maybeNumber];const pattern=new RegExp(String.raw`^${operand}:([^:]+)$`);return domainArray.map(s=>{var _a;return Number(((_a=pattern.exec(s))==null?void 0:_a[1])||NaN)}).filter(v=>!Number.isNaN(v))},"getValues"),leftValues=getValues(left),rightValues=getValues(right);switch(operator){case"gt":return leftValues.some(l=>rightValues.every(r=>l>r));case"gte":return leftValues.some(l=>rightValues.every(r=>l>=r));case"lt":return leftValues.some(l=>rightValues.every(r=>lrightValues.every(r=>l<=r));default:return console.warn("PF2e System | Malformed binary operation encountered"),!1}}}testCompound(statement,domain){return"and"in statement&&statement.and.every(subProp=>this.isTrue(subProp,domain))||"nand"in statement&&!statement.nand.every(subProp=>this.isTrue(subProp,domain))||"or"in statement&&statement.or.some(subProp=>this.isTrue(subProp,domain))||"nor"in statement&&!statement.nor.some(subProp=>this.isTrue(subProp,domain))||"not"in statement&&!this.isTrue(statement.not,domain)||"if"in statement&&!(this.isTrue(statement.if,domain)&&!this.isTrue(statement.then,domain))}}__name(PredicatePF2e,"PredicatePF2e"),__name2(PredicatePF2e,"PredicatePF2e");class StatementValidator{static isStatement(statement){return statement instanceof Object?this.isCompound(statement)||this.isBinaryOp(statement):typeof statement=="string"?this.isAtomic(statement):!1}static isAtomic(statement){return typeof statement=="string"&&statement.length>0||this.isBinaryOp(statement)}static isBinaryOp(statement){if(!isObject(statement))return!1;const entries=Object.entries(statement);if(entries.length>1)return!1;const[operator,operands]=entries[0];return this.binaryOperators.has(operator)&&Array.isArray(operands)&&operands.length===2&&typeof operands[0]=="string"&&["string","number"].includes(typeof operands[1])}static isCompound(statement){return isObject(statement)&&(this.isAnd(statement)||this.isOr(statement)||this.isNand(statement)||this.isNor(statement)||this.isNot(statement)||this.isIf(statement))}static isAnd(statement){return Object.keys(statement).length===1&&Array.isArray(statement.and)&&statement.and.every(subProp=>this.isStatement(subProp))}static isNand(statement){return Object.keys(statement).length===1&&Array.isArray(statement.nand)&&statement.nand.every(subProp=>this.isStatement(subProp))}static isOr(statement){return Object.keys(statement).length===1&&Array.isArray(statement.or)&&statement.or.every(subProp=>this.isStatement(subProp))}static isNor(statement){return Object.keys(statement).length===1&&Array.isArray(statement.nor)&&statement.nor.every(subProp=>this.isStatement(subProp))}static isNot(statement){return Object.keys(statement).length===1&&!!statement.not&&this.isStatement(statement.not)}static isIf(statement){return Object.keys(statement).length===2&&this.isStatement(statement.if)&&this.isStatement(statement.then)}}__name(StatementValidator,"StatementValidator"),__name2(StatementValidator,"StatementValidator"),__publicField(StatementValidator,"binaryOperators",new Set(["eq","gt","gte","lt","lte"]));const{fields:fields$b}=foundry.data;class LaxSchemaField extends fields$b.SchemaField{_cleanType(data,options={}){options.source=options.source||data;for(const[name2,field]of this.entries())!(name2 in data)&&options.partial||(data[name2]=field.clean(data[name2],options),data[name2]===void 0&&delete data[name2]);return data}}__name(LaxSchemaField,"LaxSchemaField"),__name2(LaxSchemaField,"LaxSchemaField");class SlugField extends fields$b.StringField{constructor(options={}){options.blank=!1,options.camel??(options.camel=null),super(options)}static get _defaults(){return{...super._defaults,nullable:!0,initial:null,camel:null}}_cleanType(value,options){const slug=super._cleanType(value,options),camel=this.options.camel??null;return typeof slug=="string"?sluggify(slug,{camel}):slug}}__name(SlugField,"SlugField"),__name2(SlugField,"SlugField");class PredicateStatementField extends fields$b.DataField{constructor(options={}){super({...options,required:!0,nullable:!1,initial:void 0,validationError:"must be recognized predicated statement type"})}_validateType(value){return StatementValidator.isStatement(value)}_cast(value){return value}_cleanType(value){return typeof value=="string"?value.trim():value}}__name(PredicateStatementField,"PredicateStatementField"),__name2(PredicateStatementField,"PredicateStatementField");class PredicateField extends fields$b.ArrayField{constructor(options){super(new PredicateStatementField,options)}_cast(value){return value}_cleanType(value){return value}initialize(value,model,options){const statements=super.initialize(value,model,options);return statements&&new PredicatePF2e(...statements)}}__name(PredicateField,"PredicateField"),__name2(PredicateField,"PredicateField");const{DataModel:DataModel$1}=foundry.abstract,{fields:fields$a}=foundry.data;class RuleElementPF2e extends DataModel$1{constructor(source,item,options={}){if(source.label??(source.label=item.name),super(source,{strict:!1}),__publicField(this,"data"),__publicField(this,"sourceIndex"),__publicField(this,"suppressWarnings"),this.item=item,this.suppressWarnings=options.suppressWarnings??!this.actor.id,this.sourceIndex=options.sourceIndex??null,!tupleHasValue(this.constructor.validActorTypes,item.actor.type)){const ruleName=game.i18n.localize(`PF2E.RuleElement.${this.key}`),actorType=game.i18n.localize(`ACTOR.Type${item.actor.type.titleCase()}`);console.warn(`PF2e System | A ${ruleName} rules element may not be applied to a ${actorType}`),source.ignored=!0}this.label=typeof source.label=="string"?game.i18n.localize(this.resolveInjectedProperties(source.label)):item.name,this.data={...source,key:this.key,predicate:Array.isArray(source.predicate)?source.predicate:void 0,label:this.label,removeUponCreate:!!(source.removeUponCreate??!1)},this.invalid?this.ignored=!0:item instanceof PhysicalItemPF2e?(this.requiresEquipped=!!(source.requiresEquipped??!0),this.requiresInvestment=item.isInvested===null?null:!!(source.requiresInvestment??this.requiresEquipped),this.ignored===!1&&(this.ignored=!!this.requiresEquipped&&!item.isEquipped||item.system.equipped.carryType==="dropped"||!!this.requiresInvestment&&!item.isInvested)):(this.requiresEquipped=null,this.requiresInvestment=null)}static defineSchema(){return{key:new fields$a.StringField({required:!0,nullable:!1,blank:!1,initial:void 0}),slug:new SlugField({required:!0,nullable:!0}),label:new fields$a.StringField({required:!0,nullable:!1,blank:!1,initial:void 0}),priority:new fields$a.NumberField({required:!1,nullable:!1,integer:!0,initial:100}),ignored:new fields$a.BooleanField({required:!1,nullable:!1,initial:!1}),predicate:new PredicateField,requiresEquipped:new fields$a.BooleanField({required:!1,nullable:!0,initial:void 0}),requiresInvestment:new fields$a.BooleanField({required:!1,nullable:!0,initial:void 0})}}static get schema(){if(this._schema&&Object.hasOwn(this,"_schema"))return this._schema;const schema=new LaxSchemaField(Object.freeze(this.defineSchema()));return schema.name=this.name,Object.defineProperty(this,"_schema",{value:schema,writable:!1}),schema}get actor(){return this.item.actor}get token(){var _a;const actor=this.actor;if(actor.token)return actor.token;const tokens=actor.getActiveTokens(),controlled=tokens.find(token=>token.controlled);return controlled?.document??((_a=tokens.shift())==null?void 0:_a.document)??null}getReducedLabel(label=this.label){return label.includes(":")?label.replace(/^[^:]+:\s*|\s*\([^)]+\)$/g,""):label}validate(options={}){return options.fallback=!1,super.validate(options)}test(rollOptions){if(this.ignored)return!1;if(this.predicate.length===0)return!0;const optionSet=new Set([...rollOptions??this.actor.getRollOptions(),...this.item.getRollOptions("parent")]);return this.resolveInjectedProperties(this.predicate).test(optionSet)}failValidation(...message){const fullMessage=message.join(" "),{name:name2,uuid}=this.item;if(!this.suppressWarnings){const ruleName=game.i18n.localize(`PF2E.RuleElement.${this.key}`);this.actor.synthetics.preparationWarnings.add(`PF2e System | ${ruleName} rules element on item ${name2} (${uuid}) failed to validate: ${fullMessage}`)}this.ignored=!0}resolveInjectedProperties(source){if(source===null||typeof source=="number"||typeof source=="string"&&!source.includes("{"))return source;if(Array.isArray(source))for(let i=0;i{const data=key==="rule"?this.data:key==="actor"||key==="item"?this[key]:this.item,value=getProperty(data,prop);return value===void 0&&this.failValidation(`Failed to resolve injected property "${source}"`),String(value)});return source}resolveValue(valueData=this.data.value,defaultValue=0,{evaluate=!0,resolvables={}}={}){var _a;let value=valueData??defaultValue??null;if(["number","boolean"].includes(typeof value)||value===null)return value;if(typeof value=="string"&&(value=this.resolveInjectedProperties(value)),this.actor.isOfType("character")&&(resolvables.armor=this.actor.wornArmor),this.isBracketedValue(valueData)){const bracketNumber=(()=>{if(!valueData?.field)return this.actor.level;const field=String(valueData.field),separator=field.indexOf("|"),source=field.substring(0,separator),{actor,item}=this;switch(source){case"actor":return Number(getProperty(actor,field.substring(separator+1)))||0;case"item":return Number(getProperty(item,field.substring(separator+1)))||0;case"rule":return Number(getProperty(this,field.substring(separator+1)))||0;default:return Number(getProperty(actor,field.substring(0)))||0}})(),brackets=valueData?.brackets??[],bracketFallthrough=(()=>{switch(typeof defaultValue){case"number":case"boolean":case"object":return defaultValue;case"string":return Number.isNaN(Number(defaultValue))?defaultValue:Number(defaultValue);default:return null}})();value=((_a=brackets.find(bracket=>{const start=bracket.start??0,end=bracket.end??1/0;return start<=bracketNumber&&end>=bracketNumber}))==null?void 0:_a.value)??bracketFallthrough}const saferEval=__name2(formula=>{try{const unresolveds=formula.match(/@[a-z]+/gi)??[];return unresolveds.length>0?(unresolveds.every(u=>u==="@target")||this.failValidation(`Failed to resolve all components of formula, "${formula}"`),0):Roll.safeEval(formula)}catch{return this.failValidation(`Error thrown while attempting to evaluate formula, "${formula}"`),0}},"saferEval");return value instanceof Object&&defaultValue instanceof Object?mergeObject(defaultValue,value,{inplace:!1}):typeof value=="string"&&value.includes("@")&&evaluate?saferEval(Roll.replaceFormulaData(value,{actor:this.actor,item:this.item,...resolvables})):value}isBracketedValue(value){return isObject(value)&&Array.isArray(value.brackets)&&(typeof value.field=="string"||!("fields"in value))}}__name(RuleElementPF2e,"RuleElementPF2e"),__name2(RuleElementPF2e,"RuleElementPF2e"),__publicField(RuleElementPF2e,"validActorTypes",["character","npc","familiar","hazard","loot","vehicle"]),(RuleElementPF2e2=>{})(RuleElementPF2e||(RuleElementPF2e={}));class ActorTraitsRuleElement extends RuleElementPF2e{constructor(data,item,options){if(data.add??(data.add=[]),data.remove??(data.remove=[]),super({...data,priority:99},item,options),__publicField(this,"add",[]),__publicField(this,"remove",[]),!(Array.isArray(data.add)&&Array.isArray(data.remove))){this.failValidation("`add` and `remove` properties must be arrays or omitted");return}if(data.add.length===0&&data.remove.length===0){this.failValidation("At least one non-empty `add` or `remove` array is required");return}for(const array of[data.add,data.remove])if(!array.every(t=>typeof t=="string")){this.failValidation("Actor traits must consist only of strings");return}this.add=data.add,this.remove=data.remove}beforePrepareData(){if(this.test()&&this.actor.system.traits){const traits=this.actor.system.traits,newTraits=this.resolveInjectedProperties(this.add).filter(t=>!traits.value.includes(t));for(const trait of newTraits)traits.value.push(trait),this.actor.rollOptions.all[`self:trait:${trait}`]=!0;const toRemoves=this.resolveInjectedProperties(this.remove);for(const trait of toRemoves)traits.value=traits.value.filter(t=>t!==trait),delete this.actor.rollOptions.all[`self:trait:${trait}`]}}}__name(ActorTraitsRuleElement,"ActorTraitsRuleElement"),__name2(ActorTraitsRuleElement,"ActorTraitsRuleElement");const _DegreeOfSuccess=__name(class{constructor(roll,dc,dosAdjustments=null){__privateAdd(this,_getDegreeAdjustment),__privateAdd(this,_adjustDegreeOfSuccess),__privateAdd(this,_adjustDegreeByDieValue),__privateAdd(this,_calculateDegreeOfSuccess),__publicField(this,"value"),__publicField(this,"unadjusted"),__publicField(this,"adjustment"),__publicField(this,"dieResult"),__publicField(this,"rollTotal"),__publicField(this,"dc");var _a;roll instanceof Roll?(this.dieResult=((_a=roll.isDeterministic?roll.terms.find(t=>t instanceof NumericTerm):roll.dice.find(d=>d instanceof Die&&d.faces===20))==null?void 0:_a.total)??1,this.rollTotal=roll.total):(this.dieResult=roll.dieValue,this.rollTotal=roll.dieValue+roll.modifier),this.dc=typeof dc=="number"?{value:dc}:dc,this.unadjusted=__privateMethod(this,_calculateDegreeOfSuccess,calculateDegreeOfSuccess_fn).call(this),this.adjustment=__privateMethod(this,_getDegreeAdjustment,getDegreeAdjustment_fn).call(this,this.unadjusted,dosAdjustments),this.value=this.adjustment?__privateMethod(this,_adjustDegreeOfSuccess,adjustDegreeOfSuccess_fn).call(this,this.adjustment.amount,this.unadjusted):this.unadjusted}},"_DegreeOfSuccess");let DegreeOfSuccess=_DegreeOfSuccess;__name2(DegreeOfSuccess,"DegreeOfSuccess"),_getDegreeAdjustment=new WeakSet,getDegreeAdjustment_fn=__name2(function(degree,adjustments){if(!adjustments)return null;for(const outcome of["all",...DEGREE_OF_SUCCESS_STRINGS]){const{label,amount}=adjustments[outcome]??{};if(amount&&label&&!(degree===_DegreeOfSuccess.CRITICAL_SUCCESS&&amount===DEGREE_ADJUSTMENT_AMOUNTS.INCREASE)&&!(degree===_DegreeOfSuccess.CRITICAL_FAILURE&&amount===DEGREE_ADJUSTMENT_AMOUNTS.LOWER)&&(outcome==="all"||DEGREE_OF_SUCCESS_STRINGS.indexOf(outcome)===degree))return{label,amount}}return null},"#getDegreeAdjustment"),_adjustDegreeOfSuccess=new WeakSet,adjustDegreeOfSuccess_fn=__name2(function(amount,degreeOfSuccess){switch(amount){case"criticalFailure":return 0;case"failure":return 1;case"success":return 2;case"criticalSuccess":return 3;default:return Math.clamped(degreeOfSuccess+amount,0,3)}},"#adjustDegreeOfSuccess"),_adjustDegreeByDieValue=new WeakSet,adjustDegreeByDieValue_fn=__name2(function(degree){return this.dieResult===20?__privateMethod(this,_adjustDegreeOfSuccess,adjustDegreeOfSuccess_fn).call(this,DEGREE_ADJUSTMENT_AMOUNTS.INCREASE,degree):this.dieResult===1?__privateMethod(this,_adjustDegreeOfSuccess,adjustDegreeOfSuccess_fn).call(this,DEGREE_ADJUSTMENT_AMOUNTS.LOWER,degree):degree},"#adjustDegreeByDieValue"),_calculateDegreeOfSuccess=new WeakSet,calculateDegreeOfSuccess_fn=__name2(function(){const dc=this.dc.value;return this.rollTotal-dc>=10?__privateMethod(this,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn).call(this,_DegreeOfSuccess.CRITICAL_SUCCESS):dc-this.rollTotal>=10?__privateMethod(this,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn).call(this,_DegreeOfSuccess.CRITICAL_FAILURE):this.rollTotal>=dc?__privateMethod(this,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn).call(this,_DegreeOfSuccess.SUCCESS):__privateMethod(this,_adjustDegreeByDieValue,adjustDegreeByDieValue_fn).call(this,_DegreeOfSuccess.FAILURE)},"#calculateDegreeOfSuccess"),__publicField(DegreeOfSuccess,"CRITICAL_FAILURE",0),__publicField(DegreeOfSuccess,"FAILURE",1),__publicField(DegreeOfSuccess,"SUCCESS",2),__publicField(DegreeOfSuccess,"CRITICAL_SUCCESS",3);const DEGREE_ADJUSTMENT_AMOUNTS={LOWER_BY_TWO:-2,LOWER:-1,INCREASE:1,INCREASE_BY_TWO:2,TO_CRITICAL_FAILURE:"criticalFailure",TO_FAILURE:"failure",TO_SUCCESS:"success",TO_CRITICAL_SUCCESS:"criticalSuccess"},DEGREE_OF_SUCCESS={CRITICAL_SUCCESS:3,SUCCESS:2,FAILURE:1,CRITICAL_FAILURE:0},DEGREE_OF_SUCCESS_STRINGS=["criticalFailure","failure","success","criticalSuccess"];class AdjustDegreeOfSuccessRuleElement extends RuleElementPF2e{constructor(data,item,options){super(data,item,options),__privateAdd(this,_isAdjustmentData),__publicField(this,"selector"),typeof data.selector=="string"?this.selector=data.selector:(this.failValidation("Missing string selector property"),this.selector="")}beforePrepareData(){var _a;if(this.ignored)return;const selector=this.resolveInjectedProperties(this.selector),adjustments=this.data.adjustment;if(!(selector&&isObject(adjustments)))return this.failValidation("Degree of success adjustment requires a selector field, a type field and an adjustment object.");if(!__privateMethod(this,_isAdjustmentData,isAdjustmentData_fn).call(this,adjustments))return this.failValidation("Degree of success adjustment does not have the correct format");const stringToNumber={"two-degrees-better":DEGREE_ADJUSTMENT_AMOUNTS.INCREASE_BY_TWO,"one-degree-better":DEGREE_ADJUSTMENT_AMOUNTS.INCREASE,"one-degree-worse":DEGREE_ADJUSTMENT_AMOUNTS.LOWER,"two-degrees-worse":DEGREE_ADJUSTMENT_AMOUNTS.LOWER_BY_TWO,"to-critical-failure":DEGREE_ADJUSTMENT_AMOUNTS.TO_CRITICAL_FAILURE,"to-failure":DEGREE_ADJUSTMENT_AMOUNTS.TO_FAILURE,"to-success":DEGREE_ADJUSTMENT_AMOUNTS.TO_SUCCESS,"to-critical-success":DEGREE_ADJUSTMENT_AMOUNTS.TO_CRITICAL_SUCCESS},record=["all",...DEGREE_OF_SUCCESS_STRINGS].reduce((accumulated,outcome)=>{const adjustment=adjustments[outcome];return adjustment&&(accumulated[outcome]={label:this.label,amount:stringToNumber[adjustment]}),accumulated},{});((_a=this.actor.synthetics.degreeOfSuccessAdjustments)[selector]??(_a[selector]=[])).push({adjustments:record,predicate:this.predicate})}}__name(AdjustDegreeOfSuccessRuleElement,"AdjustDegreeOfSuccessRuleElement"),__name2(AdjustDegreeOfSuccessRuleElement,"AdjustDegreeOfSuccessRuleElement"),_isAdjustmentData=new WeakSet,isAdjustmentData_fn=__name2(function(adjustment){const outcomes=["all",...DEGREE_OF_SUCCESS_STRINGS];return Object.entries(adjustment).every(([key,value])=>outcomes.includes(key)&°reeAdjustmentAmountString.includes(value))},"#isAdjustmentData");const degreeAdjustmentAmountString=["one-degree-better","one-degree-worse","two-degrees-better","two-degrees-worse","to-critical-failure","to-failure","to-success","to-critical-success"];class ResolvableValueField extends foundry.data.fields.DataField{_validateType(value){return value!==null&&["string","number","object","boolean"].includes(typeof value)}_cast(value){return value}_cleanType(value){return typeof value=="string"?value.trim():(isObject(value)&&Array.isArray(value.brackets)&&(value.field??(value.field="actor|level")),value)}}__name(ResolvableValueField,"ResolvableValueField"),__name2(ResolvableValueField,"ResolvableValueField");const{fields:fields$9}=foundry.data,_AELikeRuleElement=__name(class extends RuleElementPF2e{constructor(data,item,options){const hasExplicitPriority=typeof data.priority=="number";super(data,item,options),hasExplicitPriority||(this.priority=_AELikeRuleElement.CHANGE_MODES[this.mode])}static defineSchema(){return{...super.defineSchema(),mode:new fields$9.StringField({required:!0,choices:Object.keys(this.CHANGE_MODES),initial:void 0}),path:new fields$9.StringField({required:!0,nullable:!1,blank:!1,initial:void 0}),phase:new fields$9.StringField({required:!1,nullable:!1,choices:deepClone(this.PHASES),initial:"applyAEs"}),value:new ResolvableValueField({required:!0,nullable:!0,initial:void 0})}}validateData(){const actor=this.item.actor;if(!(typeof this.path=="string"&&this.path.length>0&&[this.path,this.path.replace(/\.\w+$/,""),this.path.replace(/\.?\w+\.\w+$/,"")].some(path=>typeof getProperty(actor,path)!==void 0)))return this.warn("path")}onApplyActiveEffects(){!this.ignored&&this.phase==="applyAEs"&&this.applyAELike()}beforePrepareData(){!this.ignored&&this.phase==="beforeDerived"&&this.applyAELike()}afterPrepareData(){!this.ignored&&this.phase==="afterDerived"&&this.applyAELike()}beforeRoll(_domains,rollOptions){!this.ignored&&this.phase==="beforeRoll"&&this.applyAELike(rollOptions)}applyAELike(rollOptions=new Set(this.actor.getRollOptions())){if(this.validateData(),!this.test(rollOptions))return;const path=this.resolveInjectedProperties(this.path).replace(_AELikeRuleElement.SKILL_LONG_FORM_PATH,(match,group)=>objectHasKey(SKILL_EXPANDED,group)?`system.skills.${SKILL_EXPANDED[group].shortform}`:match);if(/\bundefined\b/.test(path))return;const{actor}=this,current=getProperty(actor,path),change=this.resolveValue(this.value),newValue=this.getNewValue(current,change);if(!this.ignored)if(this.mode==="add"&&Array.isArray(current))current.includes(newValue)||current.push(newValue);else if(["subtract","remove"].includes(this.mode)&&Array.isArray(current))current.splice(current.indexOf(newValue),1);else try{setProperty(actor,path,newValue),this.logChange(change)}catch(error){console.warn(error)}}getNewValue(current,change){const addOrSubtract=__name2(value=>{const isNumericAdd=typeof value=="number"&&(typeof current=="number"||current===void 0||current===null),isArrayAdd=Array.isArray(current)&¤t.every(e=>typeof e==typeof value);return isNumericAdd?(current??0)+value:isArrayAdd?value:(this.warn("path"),null)},"addOrSubtract");switch(this.mode){case"multiply":return typeof change=="number"&&(typeof current=="number"||current===void 0)?Math.trunc((current??0)*change):(this.warn("path"),null);case"add":return addOrSubtract(change);case"subtract":case"remove":{const addedChange=(typeof current=="number"||current===void 0)&&typeof change=="number"?-1*change:change;return addOrSubtract(addedChange)}case"downgrade":return typeof change=="number"&&(typeof current=="number"||current===void 0)?Math.min(current??0,change):(this.warn("path"),null);case"upgrade":return typeof change=="number"&&(typeof current=="number"||current===void 0)?Math.max(current??0,change):this.warn("path");case"override":{if(isObject(change))for(const[key,value]of Object.entries(change))typeof value=="string"&&(change[key]=this.resolveInjectedProperties(value));return change}default:return null}}logChange(value){var _a,_b;const{item,mode}=this;if(!(!(typeof value=="number"||typeof value=="string")&&typeof value=="string"&&mode!=="override"))return;const level=item instanceof FeatPF2e?Number((_a=/-(\d+)$/.exec(item.system.location??""))==null?void 0:_a[1])||item.level:"level"in item&&typeof item.level=="number"?item.level:null,{autoChanges}=this.actor.system;(autoChanges[_b=this.path]??(autoChanges[_b]=[])).push({mode,level,value,source:this.item.name})}warn(property){this.failValidation(`"${property}" property is invalid`)}},"_AELikeRuleElement");let AELikeRuleElement=_AELikeRuleElement;__name2(AELikeRuleElement,"AELikeRuleElement"),__publicField(AELikeRuleElement,"CHANGE_MODES",{multiply:10,add:20,subtract:20,remove:20,downgrade:30,upgrade:40,override:50}),__publicField(AELikeRuleElement,"PHASES",["applyAEs","beforeDerived","afterDerived","beforeRoll"]),__publicField(AELikeRuleElement,"SKILL_LONG_FORM_PATH",(()=>{const skillLongForms=Array.from(SKILL_LONG_FORMS).join("|");return new RegExp(String.raw`^system\.skills\.(${skillLongForms})\b`)})());class AdjustModifierRuleElement extends AELikeRuleElement{constructor(data,item,options){data.path="ignore",data.suppress&&(data.mode="override",data.priority??(data.priority=99)),super({...data,phase:"beforeDerived"},item,options),__publicField(this,"applications",0),typeof data.selector=="string"&&this.selectors.length===0&&(this.selectors=[data.selector]),this.suppress??(this.suppress=!1),this.maxApplications??(this.maxApplications=1/0)}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!0,initial:null}),path:new fields2.StringField({blank:!0}),selector:new fields2.StringField({required:!1,blank:!1,initial:void 0}),selectors:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1})),relabel:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:void 0}),damageType:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),suppress:new fields2.BooleanField({required:!1,nullable:!0,initial:void 0}),maxApplications:new fields2.NumberField({required:!1,nullable:!0,initial:void 0})}}_validateModel(data){if(super._validateModel(data),data.suppress===!0&&typeof data.maxApplications=="number")throw Error("use of `maxApplications` in combination with `suppress` is not currently supported")}applyAELike(){var _a;if(this.validateData(),this.ignored)return;const adjustment={slug:this.slug,predicate:new PredicatePF2e(this.resolveInjectedProperties(deepClone([...this.predicate]))),suppress:this.suppress,getNewValue:current=>{const change=this.resolveValue();return typeof change!="number"?(this.failValidation("value does not resolve to a number"),current):this.ignored?current:(this.applications+=1,this.applications===this.maxApplications&&(this.ignored=!0),this.getNewValue(current,change))},getDamageType:current=>{if(!this.damageType)return current;const damageType=this.resolveInjectedProperties(this.damageType);return objectHasKey(CONFIG.PF2E.damageTypes,damageType)?damageType:(this.failValidation(`${damageType} is an unrecognized damage type.`),current)}};this.relabel&&(adjustment.relabel=this.getReducedLabel(this.resolveInjectedProperties(this.relabel)));for(const selector of this.selectors.map(s=>this.resolveInjectedProperties(s)))((_a=this.actor.synthetics.modifierAdjustments)[selector]??(_a[selector]=[])).push(adjustment)}}__name(AdjustModifierRuleElement,"AdjustModifierRuleElement"),__name2(AdjustModifierRuleElement,"AdjustModifierRuleElement");class WeaponTraitToggles{constructor(weapon){__privateAdd(this,_resolveOptions),__privateAdd(this,_weapon,void 0),__privateSet(this,_weapon,weapon)}get modular(){var _a,_b;const options=__privateMethod(this,_resolveOptions,resolveOptions_fn).call(this,"modular"),sourceSelection=(_b=(_a=__privateGet(this,_weapon)._source.system.traits.toggles)==null?void 0:_a.modular)==null?void 0:_b.selection,selection=tupleHasValue(options,sourceSelection)?sourceSelection:options.includes(__privateGet(this,_weapon).system.damage.damageType)?__privateGet(this,_weapon).system.damage.damageType:null;return{options,selection}}get versatile(){var _a,_b;const options=__privateMethod(this,_resolveOptions,resolveOptions_fn).call(this,"versatile"),sourceSelection=((_b=(_a=__privateGet(this,_weapon)._source.system.traits.toggles)==null?void 0:_a.versatile)==null?void 0:_b.selection)??null,selection=tupleHasValue(options,sourceSelection)?sourceSelection:null;return{options,selection}}}__name(WeaponTraitToggles,"WeaponTraitToggles"),__name2(WeaponTraitToggles,"WeaponTraitToggles"),_weapon=new WeakMap,_resolveOptions=new WeakSet,resolveOptions_fn=__name2(function(toggle){const types=__privateGet(this,_weapon).system.traits.value.filter(t=>t.startsWith(toggle)).flatMap(trait=>{var _a;if(trait==="modular")return["bludgeoning","piercing","slashing"];const damageType=(_a=/^versatile-(\w+)$/.exec(trait))==null?void 0:_a.at(1);switch(damageType){case"b":return"bludgeoning";case"p":return"piercing";case"s":return"slashing";default:return objectHasKey(CONFIG.PF2E.damageTypes,damageType)?damageType:[]}}),allOptions=Array.from(new Set(types));return toggle==="modular"?allOptions:allOptions.filter(t=>__privateGet(this,_weapon).system.damage.damageType!==t)},"#resolveOptions");async function toggleWeaponTrait({weapon,trait,selection}){var _a;if(weapon.system.traits.toggles[trait].selection===selection)return!1;const item=(_a=weapon.actor)==null?void 0:_a.items.get(weapon.id);if(item?.isOfType("weapon")&&item===weapon)await item.update({[`system.traits.toggles.${trait}.selection`]:selection});else if(item?.isOfType("weapon")&&weapon.altUsageType==="melee")item.update({[`system.meleeUsage.traitToggles.${trait}`]:selection});else{const rule=item?.rules.find(r=>r.key==="Strike"&&!r.ignored&&r.slug===weapon.slug);await rule?.toggleTrait({trait,selection})}return!0}__name(toggleWeaponTrait,"toggleWeaponTrait"),__name2(toggleWeaponTrait,"toggleWeaponTrait");function prunePropertyRunes(runes){const runeSet=new Set(runes);return Array.from(runeSet).filter(r=>!setHasElement(runeSet,`greater${r.titleCase()}`))}__name(prunePropertyRunes,"prunePropertyRunes"),__name2(prunePropertyRunes,"prunePropertyRunes");const{fields:fields$8}=foundry.data,_AdjustStrikeRuleElement=__name(class extends AELikeRuleElement{constructor(data,item,options){super({...data,path:"ignore",phase:"beforeDerived",priority:110},item,options)}static defineSchema(){return{...super.defineSchema(),path:new fields$8.StringField({blank:!0}),property:new fields$8.StringField({required:!0,choices:Array.from(this.VALID_PROPERTIES),initial:void 0}),definition:new PredicateField,value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0})}}applyAELike(){if(!this.test())return;const change=this.resolveValue(this.value),adjustment=(()=>{if(!this.property)throw ErrorPF2e("Unexpected error applying adjustment");const definition=this.resolveInjectedProperties(this.definition);switch(this.property){case"materials":return{adjustDamageRoll:(weapon,{materials})=>{if(!["add","subtract","remove"].includes(this.mode))return this.failValidation('A strike adjustment of material effects must be used with the "add", "subtract", or "remove" mode.');if(!definition.test(weapon.getRollOptions("item")))return;if(!objectHasKey(CONFIG.PF2E.materialDamageEffects,change))return this.failValidation(`"${change} is not a supported weapon material effect.`);const method=this.mode==="add"?"add":"delete";materials?.[method](change)}};case"range-increment":return{adjustWeapon:weapon=>{if(weapon.isOfType("melee"))return;if(typeof change!="number")return this.failValidation("Change value is not a number.");if(!definition.test(weapon.getRollOptions("item")))return;const rangeIncrement=weapon.rangeIncrement;if(typeof rangeIncrement!="number")return this.failValidation("A weapon that meets the definition lacks a range increment.");const newRangeIncrement=this.getNewValue(rangeIncrement,change);weapon.system.range=newRangeIncrement}};case"traits":return{adjustTraits:(weapon,traits)=>{if(!["add","subtract","remove"].includes(this.mode))return this.failValidation('A strike adjustment of traits must be used with the "add", "subtract", or "remove" mode.');if(!objectHasKey(CONFIG.PF2E.actionTraits,change))return this.failValidation(`"${change} is not a recognized action trait.`);definition.test(weapon.getRollOptions("item"))&&(this.mode==="add"&&!traits.includes(change)?traits.push(change):["subtract","remove"].includes(this.mode)&&traits.includes(change)&&traits.splice(traits.indexOf(change),1))}};case"weapon-traits":return{adjustWeapon:weapon=>{if(!["add","subtract","remove"].includes(this.mode))return this.failValidation('A strike adjustment of weapon traits must be used with the "add", "subtract", or "remove" mode.');if(!objectHasKey(CONFIG.PF2E.weaponTraits,change))return this.failValidation(`"${change} is not a recognized weapon trait.`);if(!definition.test(weapon.getRollOptions("item"))||weapon.slug==="basic-unarmed"&&/^(?:modular|versatile)/.test(change))return;const traits=weapon.system.traits.value,annotatedTraitMatch=change.match(/^([-a-z]*)-(\d*d?\d+)$/);if(this.mode==="add"&&annotatedTraitMatch){const changeBaseTrait=annotatedTraitMatch[1],changeValue=annotatedTraitMatch[2],traitRegex=new RegExp(`${changeBaseTrait}-(\\d*d?\\d*)`),existingTraitMatch=traits.map(trait=>trait.match(traitRegex)).find(match=>!!match);if(existingTraitMatch){const existingTrait=existingTraitMatch[1],existingValue=_AdjustStrikeRuleElement.getTraitScore(existingTrait);_AdjustStrikeRuleElement.getTraitScore(changeValue)>existingValue&&traits.findSplice(trait=>trait===existingTraitMatch[0],change);return}}this.mode==="add"&&!traits.includes(change)?traits.push(change):this.mode!=="add"&&traits.includes(change)&&traits.splice(traits.indexOf(change),1)}};case"property-runes":return{adjustWeapon:weapon=>{if(weapon.isOfType("melee"))return;if(!["add","subtract","remove"].includes(this.mode))return this.failValidation('A strike adjustment of weapon property runes must be used with the "add", "subtract", or "remove" mode.');const runeSlug=sluggify(String(change),{camel:"dromedary"});if(!objectHasKey(CONFIG.PF2E.weaponPropertyRunes,runeSlug))return this.failValidation(`"${change} is not a recognized weapon property rune.`);if(!definition.test(weapon.getRollOptions("item")))return;const propertyRunes=weapon.system.runes.property;this.mode==="add"?propertyRunes.push(runeSlug):propertyRunes.includes(runeSlug)&&propertyRunes.splice(propertyRunes.indexOf(runeSlug),1),weapon.system.runes.property=prunePropertyRunes(propertyRunes)}}}})();this.actor.synthetics.strikeAdjustments.push(adjustment)}static getTraitScore(traitValue){const traitValueMatch=traitValue.match(/(\d*)d(\d+)/);return traitValueMatch?Number(traitValueMatch[1]||1)*((Number(traitValueMatch[2])+1)/2):Number(traitValue)}},"_AdjustStrikeRuleElement");let AdjustStrikeRuleElement=_AdjustStrikeRuleElement;__name2(AdjustStrikeRuleElement,"AdjustStrikeRuleElement"),__publicField(AdjustStrikeRuleElement,"validActorTypes",["character","familiar","npc"]),__publicField(AdjustStrikeRuleElement,"VALID_PROPERTIES",new Set(["materials","property-runes","range-increment","traits","weapon-traits"]));class UUIDUtils{static fromUuidSync(uuid,relative){if(game.release.generation===10){const{doc,embedded}=__privateMethod(this,_parseUuid2,parseUuid_fn).call(this,uuid,relative);if(doc)return embedded.length?_resolveEmbedded(doc,embedded)??null:doc}return fromUuidSync(uuid,relative)}static async fromUUIDs(uuids){uuids=uniq(uuids);const documentsAndIndexData=uuids.flatMap(u=>fromUuidSync(u)??[]),worldDocs=documentsAndIndexData.filter(d=>d instanceof foundry.abstract.Document),indexEntries=documentsAndIndexData.filter(d=>!tupleHasValue(worldDocs,d)),packs=uniq(indexEntries.flatMap(e=>game.packs.get(e.pack??"")??[])),packDocs=(await Promise.all(packs.map(async pack=>{const ids=indexEntries.filter(e=>e.pack===pack.metadata.id).map(e=>e._id),cacheHits=ids.flatMap(id=>pack.get(id)??[]),cacheMisses=ids.filter(id=>!cacheHits.some(i=>i._id===id)),fromServer=cacheMisses.length>0?await pack.getDocuments({_id:{$in:cacheMisses}}):[];return[cacheHits,fromServer].flat()}))).flat();return sortBy$1([...worldDocs,...packDocs],d=>uuids.indexOf(d.uuid))}static isItemUUID(uuid){if(typeof uuid!="string")return!1;if(/^(?:Actor\.[a-zA-Z0-9]{16}\.)?Item\.[a-zA-Z0-9]{16}$/.test(uuid))return!0;const[type2,scope,packId,id]=uuid.split(".");if(type2!=="Compendium")return!1;if(!(scope&&packId&&id))throw ErrorPF2e(`Unable to parse UUID: ${uuid}`);const pack=game.packs.get(`${scope}.${packId}`);return pack?.documentName==="Item"}static isTokenUUID(uuid){return typeof uuid=="string"&&/^Scene\.[A-Za-z0-9]{16}\.Token\.[A-Za-z0-9]{16}$/.test(uuid)}}__name(UUIDUtils,"UUIDUtils"),__name2(UUIDUtils,"UUIDUtils"),_parseUuid2=new WeakSet,parseUuid_fn=__name2(function(uuid,relative){const resolved=_parseUuid(uuid,relative);return resolved.collection&&(resolved.doc=resolved.collection.get(resolved.documentId)??null),resolved},"#parseUuid"),__privateAdd(UUIDUtils,_parseUuid2);class AuraRuleElement extends RuleElementPF2e{constructor(source,item,options){super(source,item,options),__privateAdd(this,_processEffects),this.slug??(this.slug=this.item.slug??sluggify(this.item.name));for(const effect of this.effects)effect.includesSelf??(effect.includesSelf=effect.affects!=="enemies"),effect.removeOnExit??(effect.removeOnExit=Array.isArray(effect.events)?effect.events.includes("enter"):!1)}static defineSchema(){const{fields:fields2}=foundry.data,auraTraitField=new fields2.StringField({required:!0,nullable:!1,initial:void 0,choices:{...CONFIG.PF2E.spellTraits,...CONFIG.PF2E.actionTraits}}),effectSchemaField=new fields2.SchemaField({uuid:new fields2.StringField({required:!0,blank:!1,nullable:!1,initial:void 0}),affects:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:"all",choices:["allies","enemies","all"]}),events:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,nullable:!1,initial:void 0,choices:["enter","turn-start","turn-end"]}),{required:!0,nullable:!1,initial:["enter"]}),save:new fields2.SchemaField({type:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0,choices:SAVE_TYPES}),dc:new ResolvableValueField({required:!0,nullable:!1,initial:void 0})},{required:!0,nullable:!0,initial:null}),predicate:new PredicateField({required:!1,nullable:!1}),removeOnExit:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0}),includesSelf:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0})});return{...super.defineSchema(),radius:new ResolvableValueField({required:!0,nullable:!1,initial:void 0}),traits:new fields2.ArrayField(auraTraitField,{required:!0,nullable:!1,initial:[]}),effects:new fields2.ArrayField(effectSchemaField,{required:!1,nullable:!1,initial:[]}),colors:new fields2.SchemaField({border:new fields2.ColorField({required:!1,nullable:!0,initial:null}),fill:new fields2.ColorField({required:!1,nullable:!0,initial:null})},{required:!1,nullable:!0,initial:null})}}afterPrepareData(){var _a;if(!this.test())return;const radius=Math.clamped(Number(this.resolveValue(this.radius)),5,240);if(Number.isInteger(radius)&&radius>0&&radius%5===0){const data={slug:this.slug,level:((_a=this.item.system.level)==null?void 0:_a.value)??null,radius,effects:__privateMethod(this,_processEffects,processEffects_fn).call(this),traits:this.traits,colors:this.colors};for(const effect of data.effects){const indexEntry=UUIDUtils.fromUuidSync(effect.uuid);if(!(indexEntry&&"type"in indexEntry&&typeof indexEntry.type=="string")){this.failValidation(`Unable to resolve effect uuid: ${effect.uuid}`);return}["effect","affliction"].includes(indexEntry.type)||this.failValidation('effects transmitted by auras must be of type "effect" or "affliction"')}this.actor.auras.set(this.slug,data)}}}__name(AuraRuleElement,"AuraRuleElement"),__name2(AuraRuleElement,"AuraRuleElement"),_processEffects=new WeakSet,processEffects_fn=__name2(function(){return this.effects.map(e=>{var _a;return{...e,uuid:this.resolveInjectedProperties(e.uuid),level:((_a=this.item.system.level)==null?void 0:_a.value)??null,save:null}})},"#processEffects");class BaseSpeedRuleElement extends RuleElementPF2e{constructor(data,item,options){super(data,item,options),__privateAdd(this,_createMovementType),__publicField(this,"selector"),__publicField(this,"value",0),this.selector=String(data.selector).trim().replace(/-speed$/,""),typeof data.value=="string"||typeof data.value=="number"||this.isBracketedValue(data.value)?this.value=data.value:this.failValidation("A value must be a number, string, or bracketed value")}beforePrepareData(){var _a;if(this.ignored)return;const speedType=this.resolveInjectedProperties(this.selector);if(!tupleHasValue(MOVEMENT_TYPES,speedType))return this.failValidation("Unrecognized or missing selector");const speed=__privateMethod(this,_createMovementType,createMovementType_fn).call(this,speedType);((_a=this.actor.synthetics.movementTypes)[speedType]??(_a[speedType]=[])).push(speed)}}__name(BaseSpeedRuleElement,"BaseSpeedRuleElement"),__name2(BaseSpeedRuleElement,"BaseSpeedRuleElement"),_createMovementType=new WeakSet,createMovementType_fn=__name2(function(type2){return()=>{if(!this.test())return null;const value=Math.trunc(Number(this.resolveValue(this.value)));if(!Number.isInteger(value))return this.failValidation("Failed to resolve value"),null;const derivedFromLand=type2!=="land"&&typeof this.value=="string"&&/attributes\.speed\.(?:value|total)/.test(this.value);return value>0?{type:type2,value,source:this.item.name,derivedFromLand}:null}},"#createMovementType"),__publicField(BaseSpeedRuleElement,"validActorTypes",["character","familiar","npc"]);class CreatureSensePF2e{constructor(data){__publicField(this,"type"),__publicField(this,"acuity"),__publicField(this,"value"),__publicField(this,"source"),this.type=data.type,this.acuity=data.acuity??"precise",this.value=data.value??"",this.source=data.source||void 0}get range(){return Number(this.value)||1/0}get label(){const buildLabel=__name2((type2,acuity,range2)=>{const senses2=CONFIG.PF2E.senses,sense=game.i18n.localize(senses2[type2]??"")||type2,acuityLabel=acuity?game.i18n.localize(CONFIG.PF2E.senseAcuity[acuity]):null;return acuity&&range2?game.i18n.format("PF2E.Actor.Creature.Sense.WithAcuityAndRange",{sense,acuity:acuityLabel,range:range2}):acuity?game.i18n.format("PF2E.Actor.Creature.Sense.WithAcuity",{sense,acuity:acuityLabel}):sense},"buildLabel"),range=this.range<1/0?this.range:void 0;switch(this.type){case"darkvision":case"greaterDarkvision":case"lowLightVision":case"seeInvisibility":return buildLabel(this.type);case"scent":return this.acuity==="vague"?null:buildLabel(this.type,this.acuity,range);default:return buildLabel(this.type,this.acuity,range)}}isMoreAcuteThan(sense){return this.acuity==="precise"&&["imprecise","vague"].includes(sense.acuity??"precise")||this.acuity==="imprecise"&&sense.acuity==="vague"}hasLongerRangeThan(sense){return this.range>Number(sense.value)}}__name(CreatureSensePF2e,"CreatureSensePF2e"),__name2(CreatureSensePF2e,"CreatureSensePF2e");const SENSE_ACUITIES=["precise","imprecise","vague"],SENSE_TYPES=new Set(["darkvision","echolocation","greaterDarkvision","lifesense","lowLightVision","motionsense","scent","seeInvisibility","spiritsense","thoughtsense","tremorsense","wavesense"]);class IWRData{constructor(data){__publicField(this,"type"),__publicField(this,"exceptions"),__publicField(this,"source"),this.type=data.type,this.exceptions=deepClone(data.exceptions??[]),this.source=data.source??null}get applicationLabel(){const type2=this.typeLabel,exceptions=this.createFormatData({list:this.exceptions,prefix:"exception"}),key=`Exceptions${this.exceptions.length}DoubleVs0`;return game.i18n.format(`PF2E.Damage.IWR.CompositeLabel.${key}`,{type:type2,...exceptions,value:""}).replace(/\s+/g," ").trim()}get typeLabel(){return game.i18n.localize(this.typeLabels[this.type])}describe(iwrType){if(setHasElement(CONDITION_SLUGS,iwrType))return["item:type:condition",`item:slug:${iwrType}`];switch(iwrType){case"air":case"earth":case"water":return[`item:trait:${iwrType}`];case"all-damage":return["damage"];case"area-damage":return["area-damage"];case"arrow-vulnerability":return["item:group:bow",{not:"item:tag:crossbow"}];case"auditory":return["item:trait:auditory"];case"axe-vulnerability":return["item:group:axe"];case"critical-hits":return["damage:component:critical"];case"damage-from-spells":return["damage","item:type:spell"];case"emotion":return["item:type:effect","item:trait:emotion"];case"energy":case"physical":return[`damage:category:${iwrType}`];case"fear-effects":return["item:type:effect","item:trait:fear"];case"ghost-touch":return["item:rune:property:ghost-touch"];case"magical":return["item:magical"];case"mental":return[{or:["damage:type:mental",{and:["item:type:effect","item:trait:mental"]}]}];case"non-magical":return[{not:"item:magical"}];case"object-immunities":return[{or:["damage:type:bleed","damage:type:mental","damage:type:poison",{and:["item:type:condition",{or:["item:slug:doomed","item:slug:drained","item:slug:fatigued","item:slug:paralyzed","item:slug:sickened","item:slug:unconscious"]}]}]}];case"precision":case"splash-damage":return[`damage:component:${iwrType==="splash-damage"?"splash":"precision"}`];case"visual":return["item:trait:visual"];case"unarmed-attacks":return["item:category:unarmed"];default:{if(iwrType in CONFIG.PF2E.damageTypes)return[`damage:type:${iwrType}`];if(objectHasKey(CONFIG.PF2E.materialDamageEffects,iwrType))switch(iwrType){case"cold-iron":return[{or:["damage:material:cold-iron","damage:material:sovereign-steel"]}];case"darkwood":return[{or:["damage:material:darkwood",{and:["self:mode:undead","damage:material:peachwood"]}]}];case"silver":return[{or:["damage:material:silver","damage:material:mithral"]}];default:return[`damage:material:${iwrType}`]}return setHasElement(MAGIC_SCHOOLS,iwrType)?["item:trait:spell",`item:trait:${iwrType}`]:[`unhandled:${iwrType}`]}}}get predicate(){const typeStatements=this.describe(this.type),exceptions=this.exceptions.flatMap(exception=>{const described=this.describe(exception).filter(s=>s!=="damage");return described.length===1?described:{and:described}}),statements=[typeStatements,exceptions.length===0?[]:exceptions.length===1?{not:exceptions[0]}:{nor:exceptions}].flat();return new PredicatePF2e(statements)}toObject(){return{type:this.type,exceptions:deepClone(this.exceptions),source:this.source,label:this.label}}createFormatData({list,prefix}){return list.slice(0,4).map((e,i)=>({[`${prefix}${i+1}`]:game.i18n.localize(this.typeLabels[e])})).reduce((accum,obj)=>({...accum,...obj}),{})}test(statements){return this.predicate.test(statements)}}__name(IWRData,"IWRData"),__name2(IWRData,"IWRData");class ImmunityData extends IWRData{constructor(){super(...arguments),__publicField(this,"typeLabels",CONFIG.PF2E.immunityTypes)}get label(){return this.applicationLabel}}__name(ImmunityData,"ImmunityData"),__name2(ImmunityData,"ImmunityData");class WeaknessData extends IWRData{constructor(data){super(data),__publicField(this,"typeLabels",CONFIG.PF2E.weaknessTypes),__publicField(this,"value"),this.value=data.value}get label(){const type2=this.typeLabel,exceptions=this.createFormatData({list:this.exceptions,prefix:"exception"}),key=`Exceptions${this.exceptions.length}DoubleVs0`;return game.i18n.format(`PF2E.Damage.IWR.CompositeLabel.${key}`,{type:type2,value:this.value,...exceptions})}toObject(){return{...super.toObject(),value:this.value}}}__name(WeaknessData,"WeaknessData"),__name2(WeaknessData,"WeaknessData");class ResistanceData extends IWRData{constructor(data){super(data),__publicField(this,"typeLabels",CONFIG.PF2E.resistanceTypes),__publicField(this,"value"),__publicField(this,"doubleVs"),this.value=data.value,this.doubleVs=deepClone(data.doubleVs??[])}get label(){const type2=this.typeLabel,exceptions=this.createFormatData({list:this.exceptions,prefix:"exception"}),doubleVs=this.createFormatData({list:this.doubleVs,prefix:"doubleVs"}),key=`Exceptions${this.exceptions.length}DoubleVs${this.doubleVs.length}`;return game.i18n.format(`PF2E.Damage.IWR.CompositeLabel.${key}`,{type:type2,value:this.value,...exceptions,...doubleVs})}get applicationLabel(){const type2=this.typeLabel,exceptions=this.createFormatData({list:this.exceptions,prefix:"exception"}),doubleVs=this.createFormatData({list:this.doubleVs,prefix:"doubleVs"}),key=`Exceptions${this.exceptions.length}DoubleVs${this.doubleVs.length}`;return game.i18n.format(`PF2E.Damage.IWR.CompositeLabel.${key}`,{type:type2,value:"",...exceptions,...doubleVs}).replace(/\s+/g," ").trim()}toObject(){return{...super.toObject(),value:this.value,doubleVs:deepClone(this.doubleVs)}}getDoubledValue(damageDescription){return this.doubleVs.length===0?this.value:new PredicatePF2e(this.doubleVs.flatMap(d=>this.describe(d))).test(damageDescription)?this.value*2:this.value}}__name(ResistanceData,"ResistanceData"),__name2(ResistanceData,"ResistanceData");const PROFICIENCY_RANK_OPTION=["proficiency:untrained","proficiency:trained","proficiency:expert","proficiency:master","proficiency:legendary"];function ensureProficiencyOption(options,rank){rank>=0&&options.add(`skill:rank:${rank}`).add(PROFICIENCY_RANK_OPTION[rank])}__name(ensureProficiencyOption,"ensureProficiencyOption"),__name2(ensureProficiencyOption,"ensureProficiencyOption");const MODIFIER_TYPES=new Set(["ability","circumstance","item","potency","proficiency","status","untyped"]),_ModifierPF2e=__name(class{constructor(...args){__publicField(this,"slug"),__publicField(this,"label"),__publicField(this,"modifier"),__privateAdd(this,_originalValue,void 0),__publicField(this,"type"),__publicField(this,"ability"),__publicField(this,"adjustments"),__publicField(this,"force"),__publicField(this,"enabled"),__publicField(this,"ignored"),__publicField(this,"item"),__publicField(this,"source"),__publicField(this,"custom"),__publicField(this,"damageType"),__publicField(this,"damageCategory"),__publicField(this,"predicate"),__publicField(this,"critical"),__publicField(this,"traits"),__publicField(this,"notes"),__publicField(this,"hideIfDisabled"),__publicField(this,"kind");const params=__name2(args2=>typeof args2[0]=="string","isLegacyParams")(args)?{label:args[0],modifier:args[1],type:args[2]??"untyped",enabled:args[3],ignored:args[4],source:args[5],notes:args[6]}:args[0];if(this.label=game.i18n.localize(params.label??params.name),this.slug=sluggify(params.slug??this.label),__privateSet(this,_originalValue,this.modifier=params.modifier),this.type=setHasElement(MODIFIER_TYPES,params.type)?params.type:"untyped",this.ability=params.ability??null,this.force=params.force??!1,this.adjustments=deepClone(params.adjustments??[]),this.enabled=params.enabled??!0,this.ignored=params.ignored??!1,this.custom=params.custom??!1,this.source=params.source??null,this.predicate=new PredicatePF2e(params.predicate??[]),this.notes=params.notes??"",this.traits=deepClone(params.traits??[]),this.hideIfDisabled=params.hideIfDisabled??!1,this.modifier=params.modifier,this.item=params.item??null,Object.defineProperty(this,"item",{enumerable:!1}),this.damageType=objectHasKey(CONFIG.PF2E.damageTypes,params.damageType)?params.damageType:null,this.damageCategory=this.damageType==="bleed"?"persistent":params.damageCategory??null,this.critical=this.damageCategory==="splash"?!!params.critical:params.critical??null,this.kind=(()=>this.modifier>=0&&!["ability","untyped"].includes(this.type)?"bonus":this.modifier<0&&this.type!=="ability"?"penalty":"modifier")(),this.force&&this.type==="untyped")throw ErrorPF2e("A forced modifier must have a type")}get category(){return this.damageCategory}get value(){return this.kind==="penalty"&&this.modifier===0?-this.modifier:this.modifier}get signedValue(){return this.modifier===0&&this.kind==="penalty"?signedInteger(-this.modifier,{emptyStringZero:!1}):signedInteger(this.modifier,{emptyStringZero:!1})}clone(options={}){const clone=this.modifier===__privateGet(this,_originalValue)?new _ModifierPF2e(this):new _ModifierPF2e({...this,modifier:__privateGet(this,_originalValue)});return options.test&&clone.test(options.test),clone}getRollOptions(){const options=["slug","type","value"].map(p=>`${this.kind}:${p}:${this[p]}`);if(this.type==="ability"&&this.ability&&options.push(`modifier:ability:${this.ability}`),this.item){const itemSlug=this.item.slug??sluggify(this.item.name);options.push(`${this.kind}:item:type:${this.item.type}`),options.push(`${this.kind}:item:slug:${itemSlug}`);const grantingItem=this.item.grantedBy;if(grantingItem){const granterSlug=grantingItem.slug??sluggify(grantingItem.name);options.push(`${this.kind}:item:granter:type:${grantingItem.type}`),options.push(`${this.kind}:item:granter:slug:${granterSlug}`)}}return new Set(options)}test(options){this.ignored=!this.predicate.test(options)}toObject(){return duplicate({...this,item:void 0})}toString(){return this.label}},"_ModifierPF2e");let ModifierPF2e=_ModifierPF2e;__name2(ModifierPF2e,"ModifierPF2e"),_originalValue=new WeakMap;function createAbilityModifier({actor,ability,domains,max}){const withAbilityBased=domains.includes(`${ability}-based`)?domains:[...domains,`${ability}-based`],modifierValue=Math.floor((actor.abilities[ability].value-10)/2),cappedValue=Math.min(modifierValue,max??modifierValue);return new ModifierPF2e({slug:ability,label:CONFIG.PF2E.abilities[ability],modifier:cappedValue,type:"ability",ability,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,withAbilityBased,ability)})}__name(createAbilityModifier,"createAbilityModifier"),__name2(createAbilityModifier,"createAbilityModifier");function createProficiencyModifier({actor,rank,domains,addLevel}){rank=Math.clamped(rank,0,4),addLevel??(addLevel=rank>0);const pwolVariant=game.settings.get("pf2e","proficiencyVariant")==="ProficiencyWithoutLevel",baseBonuses=pwolVariant?[game.settings.get("pf2e","proficiencyUntrainedModifier"),game.settings.get("pf2e","proficiencyTrainedModifier"),game.settings.get("pf2e","proficiencyExpertModifier"),game.settings.get("pf2e","proficiencyMasterModifier"),game.settings.get("pf2e","proficiencyLegendaryModifier")]:[0,2,4,6,8],addedLevel=addLevel&&!pwolVariant?actor.level:0,bonus=baseBonuses[rank]+addedLevel;return new ModifierPF2e({slug:"proficiency",label:`PF2E.ProficiencyLevel${rank}`,modifier:bonus,type:"proficiency",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"proficiency")})}__name(createProficiencyModifier,"createProficiencyModifier"),__name2(createProficiencyModifier,"createProficiencyModifier");const HIGHER_BONUS=__name2((a,b)=>a.modifier>=b.modifier,"HIGHER_BONUS"),LOWER_PENALTY=__name2((a,b)=>a.modifier<=b.modifier,"LOWER_PENALTY");function applyStacking(best,modifier,isBetter){const existing=best[modifier.type];return existing===void 0?(modifier.enabled=!0,best[modifier.type]=modifier,modifier.modifier):isBetter(modifier,existing)?(existing.enabled=!1,modifier.enabled=!0,best[modifier.type]=modifier,modifier.modifier-existing.modifier):(modifier.enabled=!1,0)}__name(applyStacking,"applyStacking"),__name2(applyStacking,"applyStacking");function applyStackingRules(modifiers){let total=0;const highestBonus={},lowestPenalty={},abilityModifiers=modifiers.filter(m=>m.type==="ability"&&!m.ignored),bestAbility=abilityModifiers.reduce((best,modifier)=>best===null||modifier.force?modifier:best.force?best:modifier.modifier>best.modifier?modifier:best,null);for(const modifier of abilityModifiers)modifier.ignored=modifier!==bestAbility;for(const modifier of modifiers){if(modifier.ignored){modifier.enabled=!1;continue}if(modifier.type==="untyped"){modifier.enabled=!0,total+=modifier.modifier;continue}modifier.modifier<0?total+=applyStacking(lowestPenalty,modifier,LOWER_PENALTY):total+=applyStacking(highestBonus,modifier,HIGHER_BONUS)}return total}__name(applyStackingRules,"applyStackingRules"),__name2(applyStackingRules,"applyStackingRules");class StatisticModifier{constructor(slug,modifiers=[],rollOptions=new Set){__publicField(this,"slug"),__publicField(this,"_modifiers"),__publicField(this,"breakdown",""),__publicField(this,"notes"),rollOptions=rollOptions instanceof Set?rollOptions:new Set(rollOptions),this.slug=slug;const seen=[];for(const modifier of modifiers)seen.some(m=>m.slug===modifier.slug)||seen.push(modifier);this._modifiers=seen,this.calculateTotal(rollOptions)}get name(){return foundry.utils.logCompatibilityWarning("StatisticModifier#name has been split into #slug and #label",{mode:CONST.COMPATIBILITY_MODES.WARNING,since:"4.1.0",until:"4.5.0"}),this.label??this.slug}set name(_value){}get modifiers(){return[...this._modifiers]}push(modifier){return this._modifiers.find(o=>o.slug===modifier.slug)===void 0&&(this._modifiers.push(modifier),this.calculateTotal()),this._modifiers.length}unshift(modifier){return this._modifiers.find(o=>o.slug===modifier.slug)===void 0&&(this._modifiers.unshift(modifier),this.calculateTotal()),this._modifiers.length}delete(modifierSlug){const toDelete2=typeof modifierSlug=="object"?modifierSlug:this._modifiers.find(modifier=>modifier.slug===modifierSlug),wasDeleted=toDelete2&&this._modifiers.includes(toDelete2)?!!this._modifiers.findSplice(modifier=>modifier===toDelete2):!1;return wasDeleted&&this.calculateTotal(),wasDeleted}calculateTotal(rollOptions=new Set){if(rollOptions.size>0){for(const modifier of this._modifiers)modifier.test(rollOptions);adjustModifiers(this._modifiers,rollOptions)}applyStackingRules(this._modifiers),this.totalModifier=this._modifiers.filter(m=>m.enabled).reduce((total,m)=>total+m.modifier,0)}}__name(StatisticModifier,"StatisticModifier"),__name2(StatisticModifier,"StatisticModifier");function adjustModifiers(modifiers,rollOptions){for(const modifier of[...modifiers].sort((a,b)=>Math.abs(b.value)-Math.abs(a.value))){const adjustments=modifier.adjustments.filter(a=>a.predicate.test([...rollOptions,...modifier.getRollOptions()]));if(adjustments.some(a=>a.suppress)){modifier.ignored=!0;continue}const resolvedAdjustment=adjustments.reduce((resolved,adjustment)=>{var _a;const newValue=((_a=adjustment.getNewValue)==null?void 0:_a.call(adjustment,resolved.value))??resolved.value;return newValue!==resolved.value&&(resolved.value=newValue,resolved.relabel=adjustment.relabel??null),resolved},{value:modifier.modifier,relabel:null});modifier.modifier=resolvedAdjustment.value,resolvedAdjustment.relabel&&(modifier.label=game.i18n.localize(resolvedAdjustment.relabel)),modifier.damageType=adjustments.reduce((damageType,adjustment)=>{var _a;return((_a=adjustment.getDamageType)==null?void 0:_a.call(adjustment,damageType))??damageType},modifier.damageType)}}__name(adjustModifiers,"adjustModifiers"),__name2(adjustModifiers,"adjustModifiers");class CheckModifier extends StatisticModifier{constructor(slug,statistic,modifiers=[],rollOptions=new Set){const baseModifiers=statistic.modifiers.map(m=>"clone"in m?m.clone():new ModifierPF2e(m));super(slug,baseModifiers.concat(modifiers),rollOptions)}}__name(CheckModifier,"CheckModifier"),__name2(CheckModifier,"CheckModifier");class DiceModifierPF2e{constructor(params){if(__publicField(this,"slug"),__publicField(this,"label"),__publicField(this,"diceNumber"),__publicField(this,"dieSize"),__publicField(this,"critical"),__publicField(this,"category"),__publicField(this,"damageType"),__publicField(this,"override"),__publicField(this,"ignored"),__publicField(this,"enabled"),__publicField(this,"custom"),__publicField(this,"predicate"),this.label=game.i18n.localize(params.label??""),this.slug=sluggify(params.slug??this.label),!this.slug)throw ErrorPF2e("A DiceModifier must have a slug");this.diceNumber=params.diceNumber??0,this.dieSize=params.dieSize??null,this.critical=params.critical??null,this.damageType=params.damageType??null,this.category=params.category??null,this.override=params.override??null,this.custom=params.custom??!1,this.category=tupleHasValue(["persistent","precision","splash"],params.category)?params.category:this.damageType==="bleed"?"persistent":null,this.predicate=new PredicatePF2e(params.predicate??[]),this.enabled=params.enabled??this.predicate.test([]),this.ignored=params.ignored??!this.enabled}}__name(DiceModifierPF2e,"DiceModifierPF2e"),__name2(DiceModifierPF2e,"DiceModifierPF2e");class DamageDicePF2e extends DiceModifierPF2e{constructor(params){const predicate=params.predicate instanceof PredicatePF2e?params.predicate:new PredicatePF2e(params.predicate??[]);if(super({...params,predicate}),__publicField(this,"selector"),params.selector)this.selector=params.selector;else throw ErrorPF2e("Selector is mandatory")}clone(){return new DamageDicePF2e(this)}toObject(){return{...this,predicate:deepClone([...this.predicate])}}}__name(DamageDicePF2e,"DamageDicePF2e"),__name2(DamageDicePF2e,"DamageDicePF2e");class StrikeAttackTraits{static getLabel(traitOrTag){const traits=CONFIG.PF2E.weaponTraits,tags=CONFIG.PF2E.otherWeaponTags;return traits[traitOrTag]??tags[traitOrTag]??traitOrTag}static getUnannotatedTrait(trait){return trait.replace(/-d?\d{1,3}$/,"")}static createAttackModifiers({weapon}){const{actor}=weapon;if(!actor)throw ErrorPF2e("The weapon must be embedded");return weapon.system.traits.value.flatMap(trait=>{const unannotatedTrait=this.getUnannotatedTrait(trait);switch(unannotatedTrait){case"volley":{if(!weapon.rangeIncrement)return[];const penaltyRange=Number(/-(\d+)$/.exec(trait)[1]);return new ModifierPF2e({slug:unannotatedTrait,label:this.getLabel(trait),modifier:-2,type:"untyped",ignored:!0,predicate:new PredicatePF2e({lte:["target:distance",penaltyRange]},{not:"self:ignore-volley-penalty"})})}case"sweep":return new ModifierPF2e({slug:unannotatedTrait,label:this.getLabel(trait),modifier:1,type:"circumstance",predicate:new PredicatePF2e("self:sweep-bonus")});case"backswing":return new ModifierPF2e({slug:unannotatedTrait,label:this.getLabel(trait),modifier:1,type:"circumstance",predicate:new PredicatePF2e("self:backswing-bonus")});default:return[]}})}}__name(StrikeAttackTraits,"StrikeAttackTraits"),__name2(StrikeAttackTraits,"StrikeAttackTraits");function setImmunitiesFromTraits(actor){if(actor.isOfType("character"))return;const{traits}=actor,{immunities}=actor.attributes;if(traits.has("construct")&&!traits.has("eidolon")){const constructImmunities=["bleed","death-effects","disease","doomed","drained","fatigued","healing","necromancy","nonlethal-attacks","paralyzed","poison","sickened","unconscious"];for(const immunityType of constructImmunities)immunities.some(i=>i.type===immunityType)||immunities.push(new ImmunityData({type:immunityType,source:game.i18n.localize("PF2E.TraitConstruct")}))}traits.has("mindless")&&!immunities.some(i=>i.type==="mental")&&immunities.push(new ImmunityData({type:"mental",source:game.i18n.localize("PF2E.TraitMindless")}))}__name(setImmunitiesFromTraits,"setImmunitiesFromTraits"),__name2(setImmunitiesFromTraits,"setImmunitiesFromTraits");function createSheetOptions(options,selections=[],{selected=!1}={}){const sheetOptions=Object.entries(options).reduce((compiledOptions,[stringKey,label])=>{const selectionList=Array.isArray(selections)?selections:selections.value,key=typeof selectionList[0]=="number"?Number(stringKey):stringKey,isSelected=selectionList.includes(key);return(isSelected||!selected)&&(compiledOptions[key]={label:game.i18n.localize(label),value:stringKey,selected:isSelected}),compiledOptions},{});return sortLabeledRecord(sheetOptions)}__name(createSheetOptions,"createSheetOptions"),__name2(createSheetOptions,"createSheetOptions");function createSheetTags(options,selections){return createSheetOptions(options,selections,{selected:!0})}__name(createSheetTags,"createSheetTags"),__name2(createSheetTags,"createSheetTags");function createTagifyTraits(traits,{sourceTraits,record}){const sourceSet=new Set(sourceTraits),traitSlugs=[...traits],readonlyTraits=traitSlugs.filter(t=>!sourceSet.has(t));return traitSlugs.map(slug=>{const label=game.i18n.localize(record?.[slug]??slug);return{id:slug,value:label,readonly:readonlyTraits.includes(slug)}}).sort((t1,t2)=>t1.value.localeCompare(t2.value))}__name(createTagifyTraits,"createTagifyTraits"),__name2(createTagifyTraits,"createTagifyTraits");function processTagifyInSubmitData(form,data){const tagifyInputElements=form.querySelectorAll("tags.tagify ~ input");for(const inputEl of tagifyInputElements.values()){const path=inputEl.name,inputValue=data[path],selections=inputValue&&typeof inputValue=="string"?JSON.parse(inputValue):inputValue;Array.isArray(selections)&&(data[path]=selections.filter(s=>!s.readonly).map(s=>s.id??s.value))}}__name(processTagifyInSubmitData,"processTagifyInSubmitData"),__name2(processTagifyInSubmitData,"processTagifyInSubmitData");async function maintainTagifyFocusInRender(sheet,renderLogic){var _a,_b;const element=sheet.element[0],active=document.activeElement,activeWasHere=element?.contains(active);if(await renderLogic(),activeWasHere&&active?.classList.contains("tagify__input")){const name2=(_a=htmlClosest(active,"tags"))==null?void 0:_a.dataset.name;name2&&sheet.element[0]&&((_b=htmlQuery(element,`tags[data-name="${name2}"] span[contenteditable]`))==null||_b.focus())}}__name(maintainTagifyFocusInRender,"maintainTagifyFocusInRender"),__name2(maintainTagifyFocusInRender,"maintainTagifyFocusInRender");const _id="i3OJZU2nk64Df3xm",img="systems/pf2e/icons/conditions/clumsy.webp",name$1="Clumsy",system={description:{value:"

Your movements become clumsy and inexact. Clumsy always includes a value. You take a status penalty equal to the condition value to Dexterity-based checks and DCs, including AC, Reflex saves, ranged attack rolls, and skill checks using Acrobatics, Stealth, and Thievery.

"},duration:{value:0},group:"abilities",overrides:[],references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"dex-based",slug:"clumsy",type:"status",value:"-@item.badge.value"}],source:{value:"Pathfinder Core Rulebook"},value:{isValued:!0,value:1}},type="condition",clumsySource={_id,img,name:name$1,system,type};class PCStrikeAttackTraits extends StrikeAttackTraits{static adjustWeapon(weapon){var _a;const traits=weapon.system.traits.value;for(const trait of[...traits])switch(trait.replace(/-d?\d{1,3}$/,"")){case"fatal-aim":{if(weapon.rangeIncrement&&weapon.handsHeld===2){const fatal=trait.replace("-aim","");objectHasKey(CONFIG.PF2E.weaponTraits,fatal)&&!traits.includes(fatal)&&traits.push(fatal)}break}case"jousting":{if(weapon.handsHeld===1){const die=(_a=/(d\d{1,2})$/.exec(trait))==null?void 0:_a[1];setHasElement(DAMAGE_DIE_FACES,die)&&(weapon.system.damage.die=die)}break}}}static createAttackModifiers({weapon,domains}){const{actor}=weapon;if(!actor)throw ErrorPF2e("The weapon must be embedded");const traitsAndTags=[weapon.system.traits.value,weapon.system.traits.otherTags].flat(),synthetics=actor.synthetics.modifierAdjustments,pcSpecificModifiers=traitsAndTags.flatMap(trait=>{const unannotatedTrait=this.getUnannotatedTrait(trait);switch(unannotatedTrait){case"kickback":return new ModifierPF2e({slug:unannotatedTrait,label:CONFIG.PF2E.weaponTraits.kickback,modifier:-2,type:"circumstance",predicate:new PredicatePF2e({lt:["ability:str:score",14]}),adjustments:extractModifierAdjustments(synthetics,domains,unannotatedTrait)});case"improvised":return new ModifierPF2e({slug:unannotatedTrait,label:this.getLabel(trait),modifier:-2,type:"item",predicate:new PredicatePF2e({not:"self:ignore-improvised-penalty"}),adjustments:extractModifierAdjustments(synthetics,domains,unannotatedTrait)});default:return[]}});return[...super.createAttackModifiers({weapon}),...pcSpecificModifiers]}}__name(PCStrikeAttackTraits,"PCStrikeAttackTraits"),__name2(PCStrikeAttackTraits,"PCStrikeAttackTraits");class WeaponAuxiliaryAction{constructor({weapon,action:action2,purpose,hands}){__publicField(this,"weapon"),__publicField(this,"action"),__publicField(this,"actions"),__publicField(this,"carryType"),__publicField(this,"hands"),__publicField(this,"purpose"),__publicField(this,"fullPurpose"),this.weapon=weapon,this.action=action2,this.purpose=purpose,this.hands=hands??null;const[actions,carryType,fullPurpose]=(()=>{var _a;switch(purpose){case"Draw":return[1,"held",`${purpose}${hands}H`];case"PickUp":return[1,"held",`${purpose}${hands}H`];case"Retrieve":return[(_a=weapon.container)!=null&&_a.isHeld?2:3,"held",`${purpose}${hands}H`];case"Grip":return[action2==="Interact"?1:0,"held",purpose];case"Sheathe":return[1,"worn",purpose];case"Modular":return[1,null,purpose];case"Drop":return[0,"dropped",purpose]}})();this.actions=actions,this.carryType=carryType,this.fullPurpose=fullPurpose}get actor(){return this.weapon.parent}get label(){return game.i18n.localize(`PF2E.Actions.${this.action}.${this.fullPurpose}.Title`)}get glyph(){return getActionGlyph(this.actions)}get options(){return this.purpose==="Modular"?createSheetOptions(pick(CONFIG.PF2E.damageTypes,this.weapon.system.traits.toggles.modular.options),[this.weapon.system.traits.toggles.modular.selection??[]].flat()):null}async execute({selection=null}={}){const{actor,weapon}=this;if(typeof this.carryType=="string")actor.adjustCarryType(this.weapon,this.carryType,this.hands??0);else if(selection&&tupleHasValue(weapon.system.traits.toggles.modular.options,selection)&&!await toggleWeaponTrait({weapon,trait:"modular",selection}))return;if(!game.combat)return;const templates={flavor:"./systems/pf2e/templates/chat/action/flavor.hbs",content:"./systems/pf2e/templates/chat/action/content.hbs"},flavorAction={title:`PF2E.Actions.${this.action}.Title`,subtitle:`PF2E.Actions.${this.action}.${this.fullPurpose}.Title`,typeNumber:this.glyph},flavor=await renderTemplate(templates.flavor,{action:flavorAction,traits:[{name:CONFIG.PF2E.featTraits.manipulate,description:CONFIG.PF2E.traitsDescriptions.manipulate}]}),content=await renderTemplate(templates.content,{imgPath:weapon.img,message:game.i18n.format(`PF2E.Actions.${this.action}.${this.fullPurpose}.Description`,{actor:actor.name,weapon:weapon.name,damageType:game.i18n.localize(`PF2E.Damage.RollFlavor.${selection}`)})}),token=actor.getActiveTokens(!1,!0).shift();await ChatMessagePF2e.create({content,speaker:ChatMessagePF2e.getSpeaker({actor,token}),flavor,type:CONST.CHAT_MESSAGE_TYPES.EMOTE})}}__name(WeaponAuxiliaryAction,"WeaponAuxiliaryAction"),__name2(WeaponAuxiliaryAction,"WeaponAuxiliaryAction");function imposeOversizedWeaponCondition(actor){var _a;const wieldedOversizedWeapon=actor.itemTypes.weapon.find(w=>w.isEquipped&&w.isOversized&&w.category!=="unarmed"),conditionSource=wieldedOversizedWeapon&&actor.conditions.bySlug("clumsy").length===0?mergeObject(clumsySource,{_id:"xxxxOVERSIZExxxx",name:game.i18n.localize(CONFIG.PF2E.statusEffects.conditions.clumsy),system:{slug:"clumsy",references:{parent:{id:wieldedOversizedWeapon.id}}}},{inplace:!1}):null;if(!conditionSource)return;const clumsyOne=new ConditionPF2e(conditionSource,{parent:actor});clumsyOne.prepareSiblingData(),clumsyOne.prepareActorData();for(const rule of clumsyOne.prepareRuleElements())(_a=rule.beforePrepareData)==null||_a.call(rule)}__name(imposeOversizedWeaponCondition,"imposeOversizedWeaponCondition"),__name2(imposeOversizedWeaponCondition,"imposeOversizedWeaponCondition");function createForceOpenPenalty(actor,domains){const slug="no-crowbar",{modifierAdjustments}=actor.synthetics;return new ModifierPF2e({slug,label:"PF2E.Actions.ForceOpen.NoCrowbarPenalty",type:"item",modifier:-2,predicate:["action:force-open","action:force-open:prying"],hideIfDisabled:!0,adjustments:extractModifierAdjustments(modifierAdjustments,domains,slug)})}__name(createForceOpenPenalty,"createForceOpenPenalty"),__name2(createForceOpenPenalty,"createForceOpenPenalty");function createShoddyPenalty(actor,item,domains){if(!actor.isOfType("character")||!item?.isShoddy)return null;const slug="shoddy";return new ModifierPF2e({label:"PF2E.Item.Physical.OtherTag.Shoddy",type:"item",slug,modifier:-2,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,slug)})}__name(createShoddyPenalty,"createShoddyPenalty"),__name2(createShoddyPenalty,"createShoddyPenalty");function createHinderingPenalty(actor){var _a;const slug="hindering";return(_a=actor.wornArmor)!=null&&_a.traits.has(slug)?new ModifierPF2e({label:"PF2E.TraitHindering",type:"untyped",slug,modifier:-5,adjustments:[]}):null}__name(createHinderingPenalty,"createHinderingPenalty"),__name2(createHinderingPenalty,"createHinderingPenalty");function createPonderousPenalty(actor){const armor=actor.wornArmor,slug="ponderous";if(!armor?.traits.has(slug))return null;const penaltyValue=actor.abilities.str.value>=(armor.strength??0)?-1:armor.checkPenalty||-1;return new ModifierPF2e({label:"PF2E.TraitPonderous",type:"untyped",slug,modifier:penaltyValue,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,["all","initiative"],slug)})}__name(createPonderousPenalty,"createPonderousPenalty"),__name2(createPonderousPenalty,"createPonderousPenalty");const adjustmentScale=["incredibly-easy","very-easy","easy","normal","hard","very-hard","incredibly-hard"],dcAdjustments=new Map([["incredibly-easy",-10],["very-easy",-5],["easy",-2],["normal",0],["hard",2],["very-hard",5],["incredibly-hard",10]]),dcByLevel=new Map([[-1,13],[0,14],[1,15],[2,16],[3,18],[4,19],[5,20],[6,22],[7,23],[8,24],[9,26],[10,27],[11,28],[12,30],[13,31],[14,32],[15,34],[16,35],[17,36],[18,38],[19,39],[20,40],[21,42],[22,44],[23,46],[24,48],[25,50]]);function rarityToDCAdjustment(rarity="common"){switch(rarity){case"uncommon":return"hard";case"rare":return"very-hard";case"unique":return"incredibly-hard";default:return"normal"}}__name(rarityToDCAdjustment,"rarityToDCAdjustment"),__name2(rarityToDCAdjustment,"rarityToDCAdjustment");function adjustDC(dc,adjustment="normal"){return dc+(dcAdjustments.get(adjustment)??0)}__name(adjustDC,"adjustDC"),__name2(adjustDC,"adjustDC");function adjustDCByRarity(dc,rarity="common"){return adjustDC(dc,rarityToDCAdjustment(rarity))}__name(adjustDCByRarity,"adjustDCByRarity"),__name2(adjustDCByRarity,"adjustDCByRarity");function calculateDC(level,{proficiencyWithoutLevel,rarity="common"}={}){const pwlSetting=game.settings.get("pf2e","proficiencyVariant");proficiencyWithoutLevel??(proficiencyWithoutLevel=pwlSetting==="ProficiencyWithoutLevel");const dc=dcByLevel.get(level)??14;return adjustDCByRarity(proficiencyWithoutLevel?dc-Math.max(level,0):dc,rarity)}__name(calculateDC,"calculateDC"),__name2(calculateDC,"calculateDC");function combineDCAdjustments(first,second){const startingIndex=adjustmentScale.indexOf(first),lowerByIndex=adjustmentScale.indexOf(second),resultIndex=Math.min(Math.max(startingIndex+lowerByIndex-3,0),6);return adjustmentScale[resultIndex]}__name(combineDCAdjustments,"combineDCAdjustments"),__name2(combineDCAdjustments,"combineDCAdjustments");function createDifficultyScale(dc,startAt){const beginAtIndex=adjustmentScale.indexOf(startAt);return adjustmentScale.filter((_value,index)=>index>=beginAtIndex).map(value=>adjustDC(dc,value))}__name(createDifficultyScale,"createDifficultyScale"),__name2(createDifficultyScale,"createDifficultyScale");const cantripDeckId="tLa4bewBhyqzi6Ow",scrollCompendiumIds={1:"RjuupS9xyXDLgyIr",2:"Y7UD64foDbDMV9sx",3:"ZmefGBXGJF3CFDbn",4:"QSQZJ5BC3DeHv153",5:"tjLvRWklAylFhBHQ",6:"4sGIy77COooxhQuC",7:"fomEZZ4MxVVK3uVu",8:"iPki3yuoucnj7bIt",9:"cFHomF3tty8Wi1e5",10:"o1XIHJ4MJyroAHfF"},SPELL_CONSUMABLE_NAME_TEMPLATES={cantripDeck5:"PF2E.Item.Physical.FromSpell.CantripDeck5",scroll:"PF2E.Item.Physical.FromSpell.Scroll",wand:"PF2E.Item.Physical.FromSpell.Wand"},wandCompendiumIds={1:"UJWiN0K3jqVjxvKk",2:"vJZ49cgi8szuQXAD",3:"wrDmWkGxmwzYtfiA",4:"Sn7v9SsbEDMUIwrO",5:"5BF7zMnrPYzyigCs",6:"kiXh4SUWKr166ZeM",7:"nmXPj9zuMRQBNT60",8:"Qs8RgNH6thRPv2jt",9:"Fgv722039TVM5JTc"};function getIdForSpellConsumable(type2,heightenedLevel){switch(type2){case"cantripDeck5":return cantripDeckId;case"scroll":return scrollCompendiumIds[heightenedLevel]??null;default:return wandCompendiumIds[heightenedLevel]??null}}__name(getIdForSpellConsumable,"getIdForSpellConsumable"),__name2(getIdForSpellConsumable,"getIdForSpellConsumable");function getNameForSpellConsumable(type2,spellName,heightenedLevel){const templateId=SPELL_CONSUMABLE_NAME_TEMPLATES[type2]||`${type2} of {name} (Level {level})`;return game.i18n.format(templateId,{name:spellName,level:heightenedLevel})}__name(getNameForSpellConsumable,"getNameForSpellConsumable"),__name2(getNameForSpellConsumable,"getNameForSpellConsumable");function isSpellConsumable(itemId){return itemId===cantripDeckId||Object.values(scrollCompendiumIds).includes(itemId)||Object.values(wandCompendiumIds).includes(itemId)}__name(isSpellConsumable,"isSpellConsumable"),__name2(isSpellConsumable,"isSpellConsumable");async function createConsumableFromSpell(type2,spell,heightenedLevel=spell.baseLevel){const pack=game.packs.find(p=>p.collection==="pf2e.equipment-srd"),itemId=getIdForSpellConsumable(type2,heightenedLevel),consumable=await pack?.getDocument(itemId??"");if(!(consumable instanceof ConsumablePF2e))throw ErrorPF2e("Failed to retrieve consumable item");const consumableSource=consumable.toObject();consumableSource.system.traits.value.push(...spell.traditions),consumableSource.name=getNameForSpellConsumable(type2,spell.name,heightenedLevel);const description=consumableSource.system.description.value;return consumableSource.system.description.value=(()=>{const paragraphElement=document.createElement("p"),linkElement=document.createElement("em");linkElement.append(spell.sourceId?"@"+spell.sourceId.replace(".","[")+"]":spell.description),paragraphElement.append(linkElement);const containerElement=document.createElement("div"),hrElement=document.createElement("hr");return containerElement.append(paragraphElement,hrElement),hrElement.insertAdjacentHTML("afterend",description),containerElement.innerHTML})(),type2!=="cantripDeck5"&&(consumableSource.system.spell=spell.clone({"system.location.heightenedLevel":heightenedLevel}).toObject()),consumableSource}__name(createConsumableFromSpell,"createConsumableFromSpell"),__name2(createConsumableFromSpell,"createConsumableFromSpell");function calculateTrickMagicItemCheckDC(item,options={proficiencyWithoutLevel:!1}){const level=Number(item.level),saveDC=calculateDC(level,options),skills=item.system.traits.value.filter(t=>setHasElement(MAGIC_TRADITIONS,t)).map(tradition=>[traditionSkills[tradition],saveDC]);return Object.fromEntries(skills)}__name(calculateTrickMagicItemCheckDC,"calculateTrickMagicItemCheckDC"),__name2(calculateTrickMagicItemCheckDC,"calculateTrickMagicItemCheckDC");const WEAPON_CATEGORIES=new Set(["unarmed","simple","martial","advanced"]),MELEE_OR_RANGED_GROUPS=new Set(["dart","knife"]),MELEE_WEAPON_GROUPS=new Set([...MELEE_OR_RANGED_GROUPS,"axe","brawling","club","flail","hammer","pick","polearm","shield","spear","sword"]),MANDATORY_RANGED_GROUPS=new Set(["bomb","bow","firearm","sling"]);[...MELEE_WEAPON_GROUPS,...MANDATORY_RANGED_GROUPS];const THROWN_RANGES=new Set([10,15,20,30,40,60,80,100]),WEAPON_RANGES=new Set([...THROWN_RANGES,50,70,90,120,140,150,180,200,240,300]),CROSSBOW_WEAPONS=new Set(["alchemical-crossbow","crossbow","hand-crossbow","heavy-crossbow","repeating-crossbow","repeating-hand-crossbow","repeating-heavy-crossbow","taw-launcher"]),SIZES=["tiny","sm","med","lg","huge","grg"],SIZE_SLUGS=["tiny","small","medium","large","huge","gargantuan"],RARITIES=["common","uncommon","rare","unique"];function goesToEleven(value){return value>=0&&value<=11}__name(goesToEleven,"goesToEleven"),__name2(goesToEleven,"goesToEleven");const PROFICIENCY_RANKS=["untrained","trained","expert","master","legendary"];function buildRewards(...rewards){const[trained,expert,master,legendary]=rewards;return{1:new CoinsPF2e(trained),2:new CoinsPF2e(expert??trained),3:new CoinsPF2e(master??expert??trained),4:new CoinsPF2e(legendary??master??expert??trained)}}__name(buildRewards,"buildRewards"),__name2(buildRewards,"buildRewards");const earnIncomeTable={0:{failure:{cp:1},rewards:buildRewards({cp:5})},1:{failure:{cp:2},rewards:buildRewards({sp:2})},2:{failure:{cp:4},rewards:buildRewards({sp:3})},3:{failure:{cp:8},rewards:buildRewards({sp:5})},4:{failure:{sp:1},rewards:buildRewards({sp:7},{sp:8})},5:{failure:{sp:2},rewards:buildRewards({sp:9},{gp:1})},6:{failure:{sp:3},rewards:buildRewards({gp:1,sp:5},{gp:2})},7:{failure:{sp:4},rewards:buildRewards({gp:2},{gp:2,sp:5})},8:{failure:{sp:5},rewards:buildRewards({gp:2,sp:5},{gp:3})},9:{failure:{sp:6},rewards:buildRewards({gp:3},{gp:4})},10:{failure:{sp:7},rewards:buildRewards({gp:4},{gp:5},{gp:6})},11:{failure:{sp:8},rewards:buildRewards({gp:5},{gp:6},{gp:8})},12:{failure:{sp:9},rewards:buildRewards({gp:6},{gp:8},{gp:10})},13:{failure:{gp:1},rewards:buildRewards({gp:7},{gp:10},{gp:15})},14:{failure:{gp:1,sp:5},rewards:buildRewards({gp:8},{gp:15},{gp:20})},15:{failure:{gp:2},rewards:buildRewards({gp:10},{gp:20},{gp:28})},16:{failure:{gp:2,sp:5},rewards:buildRewards({gp:13},{gp:25},{gp:36},{gp:40})},17:{failure:{gp:3},rewards:buildRewards({gp:15},{gp:30},{gp:45},{gp:55})},18:{failure:{gp:4},rewards:buildRewards({gp:20},{gp:45},{gp:70},{gp:90})},19:{failure:{gp:6},rewards:buildRewards({gp:30},{gp:60},{gp:100},{gp:130})},20:{failure:{gp:8},rewards:buildRewards({gp:40},{gp:75},{gp:150},{gp:200})},21:{failure:{cp:0},rewards:buildRewards({gp:50},{gp:90},{gp:175},{gp:300})}};function getIncomeForLevel(level){const income=earnIncomeTable[Math.clamped(level,0,21)];return{failure:new CoinsPF2e(income.failure),rewards:income.rewards}}__name(getIncomeForLevel,"getIncomeForLevel"),__name2(getIncomeForLevel,"getIncomeForLevel");function applyIncomeOptions({result,options,level,proficiency}){options.useLoreAsExperiencedProfessional&&(result.degreeOfSuccess===DegreeOfSuccess.CRITICAL_FAILURE?(result.degreeOfSuccess=DegreeOfSuccess.FAILURE,result.rewards=new CoinsPF2e(getIncomeForLevel(level).failure)):result.degreeOfSuccess===DegreeOfSuccess.FAILURE&&proficiency!==1&&(result.rewards=new CoinsPF2e(result.rewards).scale(2)))}__name(applyIncomeOptions,"applyIncomeOptions"),__name2(applyIncomeOptions,"applyIncomeOptions");function earnIncome({level,days,rollBrief,proficiency,options,dc}){const degree=new DegreeOfSuccess(rollBrief,dc),result={rewards:new CoinsPF2e,degreeOfSuccess:degree.value};return degree.value===DegreeOfSuccess.CRITICAL_SUCCESS?result.rewards=getIncomeForLevel(level+1).rewards[proficiency]:degree.value===DegreeOfSuccess.SUCCESS?result.rewards=getIncomeForLevel(level).rewards[proficiency]:degree.value===DegreeOfSuccess.FAILURE&&(result.rewards=getIncomeForLevel(level).failure),applyIncomeOptions({result,options,level,proficiency}),{rewards:{perDay:result.rewards,combined:new CoinsPF2e(result.rewards).scale(days)},degreeOfSuccess:result.degreeOfSuccess,daysSpentWorking:days,level,dc,roll:degree.rollTotal}}__name(earnIncome,"earnIncome"),__name2(earnIncome,"earnIncome");function calculateDaysToNoCost(costs){return Math.ceil((costs.itemPrice.copperValue-costs.materials.copperValue)/costs.reductionPerDay.copperValue)}__name(calculateDaysToNoCost,"calculateDaysToNoCost"),__name2(calculateDaysToNoCost,"calculateDaysToNoCost");async function prepStrings(costs,item){const rollData=item.getRollData();return{reductionPerDay:costs.reductionPerDay.toString(),materialCost:game.i18n.format("PF2E.Actions.Craft.Details.PayMaterials",{cost:costs.materials.toString()}),itemCost:game.i18n.format("PF2E.Actions.Craft.Details.PayFull",{cost:costs.itemPrice.toString()}),lostMaterials:game.i18n.format("PF2E.Actions.Craft.Details.LostMaterials",{cost:costs.lostMaterials.toString()}),itemLink:await TextEditor.enrichHTML(item.link,{rollData,async:!0})}}__name(prepStrings,"prepStrings"),__name2(prepStrings,"prepStrings");function calculateCosts(item,quantity,actor,degreeOfSuccess){const itemPrice=CoinsPF2e.fromPrice(item.price,quantity),materialCosts=itemPrice.scale(.5),lostMaterials=new CoinsPF2e,reductionPerDay=new CoinsPF2e,proficiency=actor.skills.crafting.rank;return proficiency?(degreeOfSuccess===DegreeOfSuccess.CRITICAL_SUCCESS?Object.assign(reductionPerDay,getIncomeForLevel(actor.level+1).rewards[proficiency]):degreeOfSuccess===DegreeOfSuccess.SUCCESS?Object.assign(reductionPerDay,getIncomeForLevel(actor.level).rewards[proficiency]):degreeOfSuccess===DegreeOfSuccess.CRITICAL_FAILURE&&Object.assign(lostMaterials,materialCosts.scale(.1)),{itemPrice,materials:materialCosts,lostMaterials,reductionPerDay}):null}__name(calculateCosts,"calculateCosts"),__name2(calculateCosts,"calculateCosts");async function craftItem(item,itemQuantity,actor,infused){const itemSource=item.toObject();itemSource.system.quantity=itemQuantity,itemSource.system.size=actor.size==="tiny"?"tiny":"med";const itemTraits=item.traits;if(infused&&itemTraits.has("alchemical")&&itemTraits.has("consumable")&&(itemSource.system.traits.value.push("infused"),itemSource.system.temporary=!0),!await actor.addToInventory(itemSource)){ui.notifications.warn(game.i18n.localize("PF2E.Actions.Craft.Warning.CantAddItem"));return}await ChatMessagePF2e.create({user:game.user.id,content:game.i18n.format("PF2E.Actions.Craft.Information.ReceiveItem",{actorName:actor.name,quantity:itemQuantity,itemName:item.name}),speaker:{alias:actor.name}})}__name(craftItem,"craftItem"),__name2(craftItem,"craftItem");async function craftSpellConsumable(item,itemQuantity,actor){const consumableType=item.category;if(!(consumableType==="scroll"||consumableType==="wand"))return;const spellLevel=consumableType==="wand"?Math.ceil(item.level/2)-1:Math.ceil(item.level/2),validSpells=actor.itemTypes.spell.filter(s=>s.baseLevel<=spellLevel&&!s.isCantrip&&!s.isFocusSpell&&!s.isRitual).reduce((result,spell)=>(result[spell.baseLevel]=[...result[spell.baseLevel]||[],spell],result),{}),content=await renderTemplate("systems/pf2e/templates/actors/crafting-select-spell-dialog.hbs",{spells:validSpells});new Dialog({title:game.i18n.localize("PF2E.Actions.Craft.SelectSpellDialog.Title"),content,buttons:{cancel:{icon:'',label:game.i18n.localize("Cancel")},craft:{icon:'',label:game.i18n.localize("PF2E.Actions.Craft.SelectSpellDialog.CraftButtonLabel"),callback:async $dialog=>{const spellId=String($dialog.find("select[name=spell]").val()),spell=actor.items.get(spellId);if(!spell?.isOfType("spell"))return;const item2=await createConsumableFromSpell(consumableType,spell,spellLevel);return craftItem(new ConsumablePF2e(item2),itemQuantity,actor)}}},default:"craft"}).render(!0)}__name(craftSpellConsumable,"craftSpellConsumable"),__name2(craftSpellConsumable,"craftSpellConsumable");async function renderCraftingInline(item,roll,quantity,actor,free){if(!actor.isOfType("character"))return null;const degreeOfSuccess=roll.options.degreeOfSuccess??0,costs=calculateCosts(item,quantity,actor,degreeOfSuccess);if(!costs)return null;const daysForZeroCost=degreeOfSuccess>1?calculateDaysToNoCost(costs):0;return await renderTemplate("systems/pf2e/templates/chat/crafting-result.hbs",{daysForZeroCost,strings:await prepStrings(costs,item),item,quantity,success:degreeOfSuccess>1,criticalFailure:degreeOfSuccess===0,free})}__name(renderCraftingInline,"renderCraftingInline"),__name2(renderCraftingInline,"renderCraftingInline");class AutomaticBonusProgression{static isEnabled(actor){var _a;if(actor&&!((_a=actor.flags)!=null&&_a.pf2e))return!1;const settingEnabled=game.settings.get("pf2e","automaticBonusVariant")!=="noABP",abpDisabledForActor=!!actor?.flags.pf2e.disableABP;return settingEnabled&&!abpDisabledForActor}static getStrikingDice(level){return level<4?0:level<12?1:level<19?2:3}static concatModifiers(actor){var _a,_b,_c,_d,_e;if(!this.isEnabled(actor))return;const{level,synthetics}=actor,values=this.abpValues(level),ac=values.ac,perception=values.perception,save=values.save,setting=game.settings.get("pf2e","automaticBonusVariant");if(save>0&&((_a=synthetics.statisticsModifiers)["saving-throw"]??(_a["saving-throw"]=[])).push(()=>new ModifierPF2e({slug:"save-potency",label:"PF2E.AutomaticBonusProgression.savePotency",modifier:save,type:"potency"})),ac>0&&((_b=synthetics.statisticsModifiers).ac??(_b.ac=[])).push(()=>new ModifierPF2e({slug:"defense-potency",label:"PF2E.AutomaticBonusProgression.defensePotency",modifier:ac,type:"potency"})),perception>0&&((_c=synthetics.statisticsModifiers).perception??(_c.perception=[])).push(()=>new ModifierPF2e({slug:"perception-potency",label:"PF2E.AutomaticBonusProgression.perceptionPotency",modifier:perception,type:"potency"})),setting==="ABPRulesAsWritten"){const attack=this.abpValues(level).attack;attack>0&&((_d=synthetics.statisticsModifiers)["strike-attack-roll"]??(_d["strike-attack-roll"]=[])).push(()=>new ModifierPF2e({slug:"attack-potency",label:"PF2E.AutomaticBonusProgression.attackPotency",modifier:attack,type:"potency"}))}if(setting==="ABPFundamentalPotency"){const attack=this.abpValues(level).attack;if(attack>0){const potency={label:game.i18n.localize("PF2E.AutomaticBonusProgression.attackPotency"),type:"potency",bonus:attack,predicate:new PredicatePF2e};((_e=synthetics.weaponPotency)["strike-attack-roll"]??(_e["strike-attack-roll"]=[])).push(potency)}}}static cleanupRunes(item){if(!this.isEnabled(item.actor))return;item.system.potencyRune.value=null;const otherFundamental=item.isOfType("weapon")?item.system.strikingRune:item.system.resiliencyRune;if(otherFundamental.value=null,game.settings.get("pf2e","automaticBonusVariant")==="ABPRulesAsWritten"){const propertyRunes=[1,2,3,4].map(n=>item.system[`propertyRune${n}`]);for(const rune of propertyRunes)rune.value=null}}static suppressRuleElement(rule,value){return this.isEnabled(rule.actor)&&rule.type==="item"&&value>=0&&rule.fromEquipment}static getAttackPotency(level){return level<2?0:level<10?1:level<16?2:3}static abpValues(level){const attack=this.getAttackPotency(level);let ac,perception,save;return level>=5&&level<11?ac=1:level>=11&&level<18?ac=2:level>=18?ac=3:ac=0,level>=7&&level<13?perception=1:level>=13&&level<19?perception=2:level>=19?perception=3:perception=0,level>=8&&level<14?save=1:level>=14&&level<20?save=2:level>=20?save=3:save=0,{attack,ac,perception,save}}}__name(AutomaticBonusProgression,"AutomaticBonusProgression"),__name2(AutomaticBonusProgression,"AutomaticBonusProgression");function isRelevantEvent(event){return!!event&&"ctrlKey"in event&&"metaKey"in event&&"shiftKey"in event}__name(isRelevantEvent,"isRelevantEvent"),__name2(isRelevantEvent,"isRelevantEvent");function eventToRollParams(event){const skipDefault=!game.user.settings.showRollDialogs;if(!isRelevantEvent(event))return{skipDialog:skipDefault};const params={skipDialog:event.shiftKey?!skipDefault:skipDefault};return(event.ctrlKey||event.metaKey)&&(params.rollMode=game.user.isGM?"gmroll":"blindroll"),params}__name(eventToRollParams,"eventToRollParams"),__name2(eventToRollParams,"eventToRollParams");class CheckRoll extends Roll{constructor(formula,data={},options={}){super(formula,data,options),__publicField(this,"roller"),__publicField(this,"isReroll"),__publicField(this,"isRerollable"),this.isReroll=options.isReroll??!1,this.isRerollable=!this.isReroll&&!this.dice.some(d=>d.modifiers.includes("kh")||d.modifiers.includes("kl")),this.roller=game.users.get(this.options.rollerId??"")??null}get degreeOfSuccess(){return this.options.degreeOfSuccess??null}}__name(CheckRoll,"CheckRoll"),__name2(CheckRoll,"CheckRoll");const _StrikeAttackRoll=__name(class extends CheckRoll{async render(options={}){this._evaluated||await this.evaluate({async:!0});const{isPrivate,flavor,template}=options,chatData={formula:isPrivate?"???":this._formula,flavor:isPrivate?null:flavor,user:game.user.id,tooltip:isPrivate?"":await this.getTooltip(),total:isPrivate?"?":Math.round(this.total*100)/100,strike:this.options.strike,degree:this.options.degreeOfSuccess,canRollDamage:this.roller===game.user||game.user.isGM};return renderTemplate(template??_StrikeAttackRoll.CHAT_TEMPLATE,chatData)}},"_StrikeAttackRoll");let StrikeAttackRoll=_StrikeAttackRoll;__name2(StrikeAttackRoll,"StrikeAttackRoll"),__publicField(StrikeAttackRoll,"CHAT_TEMPLATE","systems/pf2e/templates/chat/check/strike/attack-roll.hbs");function isCheckContextFlag(flag){return!!flag&&!tupleHasValue(["damage-roll","spell-cast"],flag.type)}__name(isCheckContextFlag,"isCheckContextFlag"),__name2(isCheckContextFlag,"isCheckContextFlag");async function applyDamageFromMessage({message,multiplier=1,addend=0,promptModifier=!1,rollIndex=0}){var _a;if(promptModifier)return shiftAdjustDamage(message,multiplier,rollIndex);const html=htmlQuery(ui.chat.element[0],`li.chat-message[data-message-id="${message.id}"]`),tokens=html?.dataset.actorIsTarget&&message.token?[message.token]:canvas.tokens.controlled.filter(t=>!!t.actor).map(t=>t.document);if(tokens.length===0)return ui.notifications.error("PF2E.UI.errorTargetToken",{localize:!0});const shieldBlockRequest=CONFIG.PF2E.chatDamageButtonShieldToggle,roll=message.rolls.at(rollIndex);if(!(roll instanceof DamageRoll))throw ErrorPF2e("Unexpected error retrieving damage roll");const damage=multiplier<0?multiplier*roll.total+addend:roll.alter(multiplier,addend),messageRollOptions=[...((_a=message.flags.pf2e.context)==null?void 0:_a.options)??[]],originRollOptions=messageRollOptions.filter(o=>o.startsWith("self:")).map(o=>o.replace(/^self/,"origin"));for(const token of tokens){if(!token.actor)continue;messageRollOptions.some(o=>o.startsWith("target"))||messageRollOptions.push(...token.actor.getSelfRollOptions("target"));const ephemeralEffects=multiplier>0?await extractEphemeralEffects({affects:"target",origin:message.actor,target:token.actor,item:message.item,domains:["damage-received"],options:messageRollOptions}):[],contextClone=token.actor.getContextualClone(originRollOptions,ephemeralEffects),applicationRollOptions=new Set([...messageRollOptions.filter(o=>!/^(?:self|target):/.test(o)),...originRollOptions,...contextClone.getSelfRollOptions()]);await contextClone.applyDamage({damage,token,item:message.item,skipIWR:multiplier<=0,rollOptions:applicationRollOptions,shieldBlockRequest})}toggleOffShieldBlock(message.id)}__name(applyDamageFromMessage,"applyDamageFromMessage"),__name2(applyDamageFromMessage,"applyDamageFromMessage");function shiftAdjustDamage(message,multiplier,rollIndex){new Dialog({title:game.i18n.localize("PF2E.UI.shiftModifyDamageTitle"),content:`